diff --git "a/CodeTrans Datasets/LLMTrans/LLMTrans.json" "b/CodeTrans Datasets/LLMTrans/LLMTrans.json" new file mode 100644--- /dev/null +++ "b/CodeTrans Datasets/LLMTrans/LLMTrans.json" @@ -0,0 +1,350 @@ +{"id": 0, "output": "\t1\nA\t1\nBARK\t1\nBOOK\t0\nTREAT\t1\nCOMMON\t0\nSQUAD\t1\nConfuse\t1\n", "Python": "blocks = [(\"B\", \"O\"),\n (\"X\", \"K\"),\n (\"D\", \"Q\"),\n (\"C\", \"P\"),\n (\"N\", \"A\"),\n (\"G\", \"T\"),\n (\"R\", \"E\"),\n (\"T\", \"G\"),\n (\"Q\", \"D\"),\n (\"F\", \"S\"),\n (\"J\", \"W\"),\n (\"H\", \"U\"),\n (\"V\", \"I\"),\n (\"A\", \"N\"),\n (\"O\", \"B\"),\n (\"E\", \"R\"),\n (\"F\", \"S\"),\n (\"L\", \"Y\"),\n (\"P\", \"C\"),\n (\"Z\", \"M\")]\n\n\ndef can_make_word(word, block_collection=blocks):\n \"\"\"\n Return True if `word` can be made from the blocks in `block_collection`.\n\n >>> can_make_word(\"\")\n False\n >>> can_make_word(\"a\")\n True\n >>> can_make_word(\"bark\")\n True\n >>> can_make_word(\"book\")\n False\n >>> can_make_word(\"treat\")\n True\n >>> can_make_word(\"common\")\n False\n >>> can_make_word(\"squad\")\n True\n >>> can_make_word(\"coNFused\")\n True\n \"\"\"\n if not word:\n return False\n\n blocks_remaining = block_collection[:]\n for char in word.upper():\n for block in blocks_remaining:\n if char in block:\n blocks_remaining.remove(block)\n break\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n \"COMMON\", \"squad\", \"Confused\"]))", "C": "#include \n#include \n\nint can_make_words(char **b, char *word)\n{\n\tint i, ret = 0, c = toupper(*word);\n\n#define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }\n\n\tif (!c) return 1;\n\tif (!b[0]) return 0;\n\n\tfor (i = 0; b[i] && !ret; i++) {\n\t\tif (b[i][0] != c && b[i][1] != c) continue;\n\t\tSWAP(b[i], b[0]);\n\t\tret = can_make_words(b + 1, word + 1);\n\t\tSWAP(b[i], b[0]);\n\t}\n\n\treturn ret;\n}\n\nint main(void)\n{\n\tchar* blocks[] = {\n\t\t\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \n\t\t\"GT\", \"RE\", \"TG\", \"QD\", \"FS\", \n\t\t\"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \n\t\t\"ER\", \"FS\", \"LY\", \"PC\", \"ZM\",\n\t\t0 };\n\n\tchar *words[] = {\n\t\t\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"Confuse\", 0\n\t};\n\n\tchar **w;\n\tfor (w = words; *w; w++)\n\t\tprintf(\"%s\\t%d\\n\", *w, can_make_words(blocks, *w));\n\n\treturn 0;\n}"} +{"id": 1, "output": "627615: pers 2, root 9\n39390: pers 2, root 6\n588225: pers 2, root 3\n393900588225: pers 2, root 9\n", "Python": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\" \n % (n, persistance, root))", "C": "#include \n\nint droot(long long int x, int base, int *pers)\n{\n\tint d = 0;\n\tif (pers)\n\t\tfor (*pers = 0; x >= base; x = d, (*pers)++)\n\t\t\tfor (d = 0; x; d += x % base, x /= base);\n\telse if (x && !(d = x % (base - 1)))\n\t\t\td = base - 1;\n\n\treturn d;\n}\n\nint main(void)\n{\n\tint i, d, pers;\n\tlong long x[] = {627615, 39390, 588225, 393900588225LL};\n\n\tfor (i = 0; i < 4; i++) {\n\t\td = droot(x[i], 10, &pers);\n\t\tprintf(\"%lld: pers %d, root %d\\n\", x[i], pers, d);\n\t}\n\n\treturn 0;\n}"} +{"id": 2, "output": "23", "Python": "def 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)", "C": "#include \n\n// returns x where (a * x) % b == 1\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}"} +{"id": 3, "output": "3", "Python": "def dotp(a,b):\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n\nif __name__ == '__main__':\n a, b = [1, 3, -5], [4, -2, -1]\n assert dotp(a,b) == 3", "C": "#include \n#include \n\nint dot_product(int *, int *, size_t);\n\nint\nmain(void)\n{\n int a[3] = {1, 3, -5};\n int b[3] = {4, -2, -1};\n\n printf(\"%d\\n\", dot_product(a, b, sizeof(a) / sizeof(a[0])));\n\n return EXIT_SUCCESS;\n}\n\nint\ndot_product(int *a, int *b, size_t n)\n{\n int sum = 0;\n size_t i;\n\n for (i = 0; i < n; i++) {\n sum += a[i] * b[i];\n }\n\n return sum;\n}"} +{"id": 4, "output": "The smallest number whose square ends in 269696 is 25264", "Python": "n=0 # n is a variable and its value is 0\n\n# we will increase its value by one until\n# its square ends in 269,696\n\nwhile n**2 % 1000000 != 269696:\n\n # n**2 -> n squared\n # % -> 'modulo' or remainder after division\n # != -> not equal to\n \n n += 1 # += -> increase by a certain number\n\nprint(n) # prints n", "C": "#include \n#include \n#include \n \nint main() {\n\tint current = 0, \t//the current number \n\t square;\t\t//the square of the current number\n\n\t//the strategy of take the rest of division by 1e06 is\n\t//to take the a number how 6 last digits are 269696\n\twhile (((square=current*current) % 1000000 != 269696) && (square+INT_MAX)\n\t printf(\"Condition not satisfied before INT_MAX reached.\");\n\telse\t\t \n\t printf (\"The smallest number whose square ends in 269696 is %d\\n\", current);\n\t \n //the end\n\treturn 0 ;\n}"} +{"id": 5, "output": "'': True\n'[]': True\n']][[': False\n'[][][]': True\n'[]][[]][': False\n'[]][[[[]]]': False\n']]]][[[]][[[': False\n']]]]]][][[[[[[': False\n'[][]][[][[[]]][]': False", "Python": "from itertools import accumulate\nfrom random import shuffle\ndef gen(n):\n txt = list('[]' * n)\n shuffle(txt)\n return ''.join(txt)\ndef balanced(txt):\n brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt)\n return all(x>=0 for x in accumulate(brackets))\nfor txt in (gen(N) for N in range(10)):\n print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))", "C": "#include\n#include\n#include\n\nint isBal(const char*s,int l){\n signed c=0;\n while(l--)\n\tif(s[l]==']') ++c;\n\telse if(s[l]=='[') if(--c<0) break;\n return !c;\n}\n\nvoid shuffle(char*s,int h){\n int x,t,i=h;\n while(i--){\n\tt=s[x=rand()%h];\n\ts[x]=s[i];\n\ts[i]=t;\n }\n}\n\nvoid genSeq(char*s,int n){\n if(n){\n\tmemset(s,'[',n);\n\tmemset(s+n,']',n);\n\tshuffle(s,n*2);\n }\n s[n*2]=0;\n}\n\nvoid doSeq(int n){\n char s[64];\n const char *o=\"False\";\n genSeq(s,n);\n if(isBal(s,n*2)) o=\"True\";\n printf(\"'%s': %s\\n\",s,o);\n}\n\nint main(){\n int n=0;\n while(n<9) doSeq(n++);\n return 0;\n}"} +{"id": 6, "output": "The factorions for base 9 are:\n1 2 41282 \n\nThe factorions for base 10 are:\n1 2 145 40585 \n\nThe factorions for base 11 are:\n1 2 26 48 40472 \n\nThe factorions for base 12 are:\n1 2 ", "Python": "fact = [1] # cache factorials from 0 to 11\nfor n in range(1, 12):\n fact.append(fact[n-1] * n)\n\nfor b in range(9, 12+1):\n print(f\"The factorions for base {b} are:\")\n for i in range(1, 1500000):\n fact_sum = 0\n j = i\n while j > 0:\n d = j % b\n fact_sum += fact[d]\n j = j//b\n if fact_sum == i:\n print(i, end=\" \")\n print(\"\\n\")", "C": "#include \n\nint main() { \n int n, b, d;\n unsigned long long i, j, sum, fact[12];\n // cache factorials from 0 to 11\n fact[0] = 1;\n for (n = 1; n < 12; ++n) {\n fact[n] = fact[n-1] * n;\n }\n\n for (b = 9; b <= 12; ++b) {\n printf(\"The factorions for base %d are:\\n\", b);\n for (i = 1; i < 1500000; ++i) {\n sum = 0;\n j = i;\n while (j > 0) {\n d = j % b;\n sum += fact[d];\n j /= b;\n }\n if (sum == i) printf(\"%llu \", i);\n }\n printf(\"\\n\\n\");\n }\n return 0;\n}"} +{"id": 7, "output": " i d\n 2 3.21851142\n 3 4.38567760\n 4 4.60094928\n 5 4.65513050\n 6 4.66611195\n 7 4.66854858\n 8 4.66906066\n 9 4.66917155\n10 4.66919515\n11 4.66920026\n12 4.66920098\n13 4.66920537", "Python": "max_it = 13\nmax_it_j = 10\na1 = 1.0\na2 = 0.0\nd1 = 3.2\na = 0.0\n\nprint \" i d\"\nfor i in range(2, max_it + 1):\n a = a1 + (a1 - a2) / d1\n for j in range(1, max_it_j + 1):\n x = 0.0\n y = 0.0\n for k in range(1, (1 << i) + 1):\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n a = a - x / y\n d = (a1 - a2) / (a - a1)\n print(\"{0:2d} {1:.8f}\".format(i, d))\n d1 = d\n a2 = a1\n a1 = a", "C": "#include \n\nvoid feigenbaum() {\n int i, j, k, max_it = 13, max_it_j = 10;\n double a, x, y, d, a1 = 1.0, a2 = 0.0, d1 = 3.2;\n printf(\" i d\\n\");\n for (i = 2; i <= max_it; ++i) {\n a = a1 + (a1 - a2) / d1;\n for (j = 1; j <= max_it_j; ++j) {\n x = 0.0;\n y = 0.0;\n for (k = 1; k <= 1 << i; ++k) {\n y = 1.0 - 2.0 * y * x;\n x = a - x * x;\n }\n a -= x / y;\n }\n d = (a1 - a2) / (a - a1);\n printf(\"%2d %.8f\\n\", i, d);\n d1 = d;\n a2 = a1;\n a1 = a;\n }\n}\n\nint main() {\n feigenbaum();\n return 0;\n}"} +{"id": 8, "output": "Checksum correct", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "C": "#include \n#include \n#include \n\nbool damm(unsigned char *input, size_t length) {\n static const unsigned char table[10][10] = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n \n unsigned char interim = 0;\n for (size_t i = 0; i < length; i++) {\n interim = table[interim][input[i]];\n }\n return interim == 0;\n}\n\nint main() {\n unsigned char input[4] = {5, 7, 2, 4};\n puts(damm(input, 4) ? \"Checksum correct\" : \"Checksum incorrect\");\n return 0;\n}"} +{"id": 9, "output": " 91 259 451 481 703 1729 2821 2981 3367 4141 4187 5461 6533 6541 6601 7471 7777 8149 8401 8911", "Python": "from itertools import count, islice\nfrom math import isqrt\n\ndef is_deceptive(n):\n if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:\n for d in range(7, isqrt(n) + 1, 6):\n if not (n % d and n % (d + 4)): return True\n return False\n\nprint(*islice(filter(is_deceptive, count()), 20))", "C": "#include \n\nunsigned modpow(unsigned b, unsigned e, unsigned m)\n{\n unsigned p;\n for (p = 1; e; e >>= 1) {\n if (e & 1)\n p = p * b % m;\n b = b * b % m;\n }\n return p;\n}\n\nint is_deceptive(unsigned n)\n{\n unsigned x;\n if (n & 1 && n % 3 && n % 5) {\n for (x = 7; x * x <= n; x += 6) {\n if (!(n % x && n % (x + 4)))\n return modpow(10, n - 1, n) == 1;\n }\n }\n return 0;\n}\n\nint main(void)\n{\n unsigned c, i = 20;\n for (c = 0; c != 20; ++i) {\n if (is_deceptive(i)) {\n printf(\" %u\", i);\n ++c;\n }\n }\n return 0;\n}"} +{"id": 10, "output": "1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845", "Python": "def catalan_number(n):\n nm = dm = 1\n for k in range(2, n+1):\n nm, dm = ( nm*(n+k), dm*k )\n return nm/dm\n \nprint [catalan_number(n) for n in range(1, 16)]", "C": "#include \n#include \n\n//the number of Catalan's Numbers to be printed\nconst int N = 15;\n\nint main()\n{\n //loop variables (in registers)\n register int k, n;\n\n //necessarily ull for reach big values\n unsigned long long int num, den;\n\n //the nmmber\n int catalan;\n\n //the first is not calculated for the formula\n printf(\"1 \");\n\n //iterating from 2 to 15\n for (n=2; n<=N; ++n) {\n //initializaing for products\n num = den = 1;\n //applying the formula\n for (k=2; k<=n; ++k) {\n num *= (n+k);\n den *= k;\n catalan = num /den;\n }\n \n //output\n printf(\"%d \", catalan);\n }\n\n //the end\n printf(\"\\n\");\n return 0;\n}"} +{"id": 11, "output": "15\n-13\n120", "Python": "from functools import reduce\nfrom operator import add, mul\n\nnums = range(1,11)\n\nsummation = reduce(add, nums)\n\nproduct = reduce(mul, nums)\n\nconcatenation = reduce(lambda a, b: str(a) + str(b), nums)\n\nprint(summation, product, concatenation)", "C": "#include \n\ntypedef int (*intFn)(int, int);\n\nint reduce(intFn fn, int size, int *elms)\n{\n int i, val = *elms;\n for (i = 1; i < size; ++i)\n val = fn(val, elms[i]);\n return val;\n}\n\nint add(int a, int b) { return a + b; }\nint sub(int a, int b) { return a - b; }\nint mul(int a, int b) { return a * b; }\n\nint main(void)\n{\n int nums[] = {1, 2, 3, 4, 5};\n printf(\"%d\\n\", reduce(add, 5, nums));\n printf(\"%d\\n\", reduce(sub, 5, nums));\n printf(\"%d\\n\", reduce(mul, 5, nums));\n return 0;\n}"} +{"id": 12, "output": "func[0]: 0\nfunc[1]: 1\nfunc[2]: 4\nfunc[3]: 9\nfunc[4]: 16\nfunc[5]: 25\nfunc[6]: 36\nfunc[7]: 49\nfunc[8]: 64", "Python": "funcs = [(lambda i: lambda: i)(i * i) for i in range(10)]\nprint funcs[3]() # prints 9", "C": "#include \n#include \n#include \n#include \n\ntypedef int (*f_int)();\n \n#define TAG 0xdeadbeef\nint _tmpl() { \n\tvolatile int x = TAG;\n\treturn x * x;\n}\n\n#define PROT (PROT_EXEC | PROT_WRITE)\n#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) \nf_int dupf(int v)\n{\n\tsize_t len = (void*)dupf - (void*)_tmpl;\n\tf_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);\n\tchar *p;\n\tif(ret == MAP_FAILED) {\n\t\tperror(\"mmap\");\n\t\texit(-1);\n\t}\n\tmemcpy(ret, _tmpl, len);\n\tfor (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)\n\t\tif (*(int *)p == TAG) *(int *)p = v;\n\treturn ret;\n}\n \nint main()\n{\n\tf_int funcs[10];\n\tint i;\n\tfor (i = 0; i < 10; i++) funcs[i] = dupf(i);\n \n\tfor (i = 0; i < 9; i++)\n\t\tprintf(\"func[%d]: %d\\n\", i, funcs[i]());\n \n\treturn 0;\n}"} +{"id": 13, "output": "-0.01\n1.60279\n-1.6132\n1.24549\n-0.49099\n0.0657607", "Python": "import copy\nfrom fractions import Fraction\n\ndef gauss(a, b):\n a = copy.deepcopy(a)\n b = copy.deepcopy(b)\n n = len(a)\n p = len(b[0])\n det = 1\n for i in range(n - 1):\n k = i\n for j in range(i + 1, n):\n if abs(a[j][i]) > abs(a[k][i]):\n k = j\n if k != i:\n a[i], a[k] = a[k], a[i]\n b[i], b[k] = b[k], b[i]\n det = -det\n \n for j in range(i + 1, n):\n t = a[j][i]/a[i][i]\n for k in range(i + 1, n):\n a[j][k] -= t*a[i][k]\n for k in range(p):\n b[j][k] -= t*b[i][k]\n \n for i in range(n - 1, -1, -1):\n for j in range(i + 1, n):\n t = a[i][j]\n for k in range(p):\n b[i][k] -= t*b[j][k]\n t = 1/a[i][i]\n det *= a[i][i]\n for j in range(p):\n b[i][j] *= t\n return det, b\n\ndef zeromat(p, q):\n return [[0]*q for i in range(p)]\n\ndef matmul(a, b):\n n, p = len(a), len(a[0])\n p1, q = len(b), len(b[0])\n if p != p1:\n raise ValueError(\"Incompatible dimensions\")\n c = zeromat(n, q)\n for i in range(n):\n for j in range(q):\n c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))\n return c\n\n\ndef mapmat(f, a):\n return [list(map(f, v)) for v in a]\n\ndef ratmat(a):\n return mapmat(Fraction, a)\n\n# As an example, compute the determinant and inverse of 3x3 magic square\n\na = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]\nb = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\ndet, c = gauss(a, b)", "C": "#include \n#include \n#include \n\n#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))\n\nvoid swap_row(double *a, double *b, int r1, int r2, int n)\n{\n\tdouble tmp, *p1, *p2;\n\tint i;\n\n\tif (r1 == r2) return;\n\tfor (i = 0; i < n; i++) {\n\t\tp1 = mat_elem(a, r1, i, n);\n\t\tp2 = mat_elem(a, r2, i, n);\n\t\ttmp = *p1, *p1 = *p2, *p2 = tmp;\n\t}\n\ttmp = b[r1], b[r1] = b[r2], b[r2] = tmp;\n}\n\nvoid gauss_eliminate(double *a, double *b, double *x, int n)\n{\n#define A(y, x) (*mat_elem(a, y, x, n))\n\tint i, j, col, row, max_row,dia;\n\tdouble max, tmp;\n\n\tfor (dia = 0; dia < n; dia++) {\n\t\tmax_row = dia, max = A(dia, dia);\n\n\t\tfor (row = dia + 1; row < n; row++)\n\t\t\tif ((tmp = fabs(A(row, dia))) > max)\n\t\t\t\tmax_row = row, max = tmp;\n\n\t\tswap_row(a, b, dia, max_row, n);\n\n\t\tfor (row = dia + 1; row < n; row++) {\n\t\t\ttmp = A(row, dia) / A(dia, dia);\n\t\t\tfor (col = dia+1; col < n; col++)\n\t\t\t\tA(row, col) -= tmp * A(dia, col);\n\t\t\tA(row, dia) = 0;\n\t\t\tb[row] -= tmp * b[dia];\n\t\t}\n\t}\n\tfor (row = n - 1; row >= 0; row--) {\n\t\ttmp = b[row];\n\t\tfor (j = n - 1; j > row; j--)\n\t\t\ttmp -= x[j] * A(row, j);\n\t\tx[row] = tmp / A(row, row);\n\t}\n#undef A\n}\n\nint main(void)\n{\n\tdouble a[] = {\n\t\t1.00, 0.00, 0.00, 0.00, 0.00, 0.00,\n\t\t1.00, 0.63, 0.39, 0.25, 0.16, 0.10,\n\t\t1.00, 1.26, 1.58, 1.98, 2.49, 3.13,\n\t\t1.00, 1.88, 3.55, 6.70, 12.62, 23.80,\n\t\t1.00, 2.51, 6.32, 15.88, 39.90, 100.28,\n\t\t1.00, 3.14, 9.87, 31.01, 97.41, 306.02\n\t};\n\tdouble b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 };\n\tdouble x[6];\n\tint i;\n\n\tgauss_eliminate(a, b, x, 6);\n\n\tfor (i = 0; i < 6; i++)\n\t\tprintf(\"%g\\n\", x[i]);\n\n\treturn 0;\n}"} +{"id": 14, "output": "[6.0, 25.5, 40.0, 42.5, 49.0]\n\n[7.0, 15.0, 37.5, 40.0, 41.0]\n\n[-1.950595940, -0.676741205, 0.233247060, 0.746070945, 1.731315070]", "Python": "from __future__ import division\nimport math\nimport sys\n\ndef fivenum(array):\n n = len(array)\n if n == 0:\n print(\"you entered an empty array.\")\n sys.exit()\n x = sorted(array)\n \n n4 = math.floor((n+3.0)/2.0)/2.0\n d = [1, n4, (n+1)/2, n+1-n4, n]\n sum_array = []\n \n for e in range(5):\n floor = int(math.floor(d[e] - 1))\n ceil = int(math.ceil(d[e] - 1))\n sum_array.append(0.5 * (x[floor] + x[ceil]))\n \n return sum_array\n\nx = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,\n-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,\n1.04312009, -0.10305385, 0.75775634, 0.32566578]\n\ny = fivenum(x)\nprint(y)", "C": "#include \n#include \n\ndouble median(double *x, int start, int end_inclusive) {\n int size = end_inclusive - start + 1;\n if (size <= 0) {\n printf(\"Array slice cannot be empty\\n\");\n exit(1);\n }\n int m = start + size / 2;\n if (size % 2) return x[m];\n return (x[m - 1] + x[m]) / 2.0;\n}\n\nint compare (const void *a, const void *b) {\n double aa = *(double*)a; \n double bb = *(double*)b;\n if (aa > bb) return 1;\n if (aa < bb) return -1;\n return 0;\n}\n\nint fivenum(double *x, double *result, int x_len) {\n int i, m, lower_end;\n for (i = 0; i < x_len; i++) {\n if (x[i] != x[i]) {\n printf(\"Unable to deal with arrays containing NaN\\n\\n\");\n return 1;\n }\n } \n qsort(x, x_len, sizeof(double), compare);\n result[0] = x[0];\n result[2] = median(x, 0, x_len - 1);\n result[4] = x[x_len - 1];\n m = x_len / 2;\n lower_end = (x_len % 2) ? m : m - 1;\n result[1] = median(x, 0, lower_end);\n result[3] = median(x, m, x_len - 1);\n return 0;\n}\n\nint show(double *result, int places) {\n int i;\n char f[7];\n sprintf(f, \"%%.%dlf\", places);\n printf(\"[\");\n for (i = 0; i < 5; i++) { \n printf(f, result[i]);\n if (i < 4) printf(\", \");\n }\n printf(\"]\\n\\n\");\n}\n\nint main() {\n double result[5];\n\n double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0};\n if (!fivenum(x1, result, 11)) show(result, 1);\n\n double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0};\n if (!fivenum(x2, result, 6)) show(result, 1);\n\n double x3[20] = {\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n };\n if (!fivenum(x3, result, 20)) show(result, 9);\n\n return 0;\n}"} +{"id": 15, "output": " 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15", "Python": "def floyd(rowcount=5):\n\trows = [[1]]\n\twhile len(rows) < rowcount:\n\t\tn = rows[-1][-1] + 1\n\t\trows.append(list(range(n, n + len(rows[-1]) + 1)))\n\treturn rows\n\nfloyd()\n[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]\ndef pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):\n\tcolspace = [len(str(n)) for n in rows[-1]]\n\tfor row in rows:\n\t\tprint( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))", "C": "#include \n\nvoid t(int n)\n{\n\tint i, j, c, len;\n\n\ti = n * (n - 1) / 2;\n\tfor (len = c = 1; c < i; c *= 10, len++);\n\tc -= i; // c is the col where width changes\n\n#define SPEED_MATTERS 0\n#if SPEED_MATTERS\t// in case we really, really wanted to print huge triangles often\n\tchar tmp[32], s[4096], *p;\n\n\tsprintf(tmp, \"%*d\", len, 0);\n\n\tinline void inc_numstr(void) {\n\t\tint k = len;\n\n\tredo:\tif (!k--) return;\n\n\t\tif (tmp[k] == '9') {\n\t\t\ttmp[k] = '0';\n\t\t\tgoto redo;\n\t\t}\n\n\t\tif (++tmp[k] == '!')\n\t\t\ttmp[k] = '1';\n\t}\n\n\tfor (p = s, i = 1; i <= n; i++) {\n\t\tfor (j = 1; j <= i; j++) {\n\t\t\tinc_numstr();\n\t\t\t__builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c));\n\t\t\tp += len - (j < c);\n\n\t\t\t*(p++) = (i - j)? ' ' : '\\n';\n\n\t\t\tif (p - s + len >= 4096) {\n\t\t\t\tfwrite(s, 1, p - s, stdout);\n\t\t\t\tp = s;\n\t\t\t}\n\t\t}\n\t}\n\n\tfwrite(s, 1, p - s, stdout);\n#else // NO_IT_DOESN'T\n\tint num;\n\tfor (num = i = 1; i <= n; i++)\n\t\tfor (j = 1; j <= i; j++)\n\t\t\tprintf(\"%*d%c\",\tlen - (j < c), num++, i - j ? ' ':'\\n');\n#endif\n}\n\nint main(void)\n{\n\tt(5);\n\n\t// maybe not \n\t// t(10000);\n\treturn 0;\n}"} +{"id": 16, "output": "Max sum = 15\n3 5 6 -2 -1 4", "Python": "def maxsubseq(seq):\n return max((seq[begin:end] for begin in xrange(len(seq)+1)\n for end in xrange(begin, len(seq)+1)),\n key=sum)", "C": "#include \"stdio.h\"\n\ntypedef struct Range {\n int start, end, sum;\n} Range;\n\nRange maxSubseq(const int sequence[], const int len) {\n int maxSum = 0, thisSum = 0, i = 0;\n int start = 0, end = -1, j;\n\n for (j = 0; j < len; j++) {\n thisSum += sequence[j];\n if (thisSum < 0) {\n i = j + 1;\n thisSum = 0;\n } else if (thisSum > maxSum) {\n maxSum = thisSum;\n start = i;\n end = j;\n }\n }\n\n Range r;\n if (start <= end && start >= 0 && end >= 0) {\n r.start = start;\n r.end = end + 1;\n r.sum = maxSum;\n } else {\n r.start = 0;\n r.end = 0;\n r.sum = 0;\n }\n return r;\n}\n\nint main(int argc, char **argv) {\n int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1};\n int alength = sizeof(a)/sizeof(a[0]);\n\n Range r = maxSubseq(a, alength);\n printf(\"Max sum = %d\\n\", r.sum);\n int i;\n for (i = r.start; i < r.end; i++)\n printf(\"%d \", a[i]);\n printf(\"\\n\");\n\n return 0;\n}"} +{"id": 17, "output": "[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len=112\nMax 351 at j= 77031", "Python": "def hailstone(n):\n seq = [n]\n while n > 1:\n n = 3 * n + 1 if n & 1 else n // 2\n seq.append(n)\n return seq\n\n\nif __name__ == '__main__':\n h = hailstone(27)\n assert (len(h) == 112\n and h[:4] == [27, 82, 41, 124]\n and h[-4:] == [8, 4, 2, 1])\n max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))\n print(f\"Maximum length {max_length} was found for hailstone({n}) \"\n f\"for numbers <100,000\")", "C": "#include \n#include \n\nint hailstone(int n, int *arry)\n{\n int hs = 1;\n\n while (n!=1) {\n hs++;\n if (arry) *arry++ = n;\n n = (n&1) ? (3*n+1) : (n/2);\n }\n if (arry) *arry++ = n;\n return hs;\n}\n\nint main()\n{\n int j, hmax = 0;\n int jatmax, n;\n int *arry;\n\n for (j=1; j<100000; j++) {\n n = hailstone(j, NULL);\n if (hmax < n) {\n hmax = n;\n jatmax = j;\n }\n }\n n = hailstone(27, NULL);\n arry = malloc(n*sizeof(int));\n n = hailstone(27, arry);\n\n printf(\"[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\\n\",\n arry[0],arry[1],arry[2],arry[3],\n arry[n-4], arry[n-3], arry[n-2], arry[n-1], n);\n printf(\"Max %d at j= %d\\n\", hmax, jatmax);\n free(arry);\n\n return 0;\n}"} +{"id": 18, "output": "1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 \n1002", "Python": "import itertools\ndef harshad():\n\tfor n in itertools.count(1):\n\t\tif n % sum(int(ch) for ch in str(n)) == 0:\n\t\t\tyield n\t\t\nlist(itertools.islice(harshad(), 0, 20))\nfor n in harshad():\n\tif n > 1000:\n\t\tprint(n)\n\t\tbreak\n", "C": "#include \n\nstatic int digsum(int n)\n{\n int sum = 0;\n do { sum += n % 10; } while (n /= 10);\n return sum;\n}\n\nint main(void)\n{\n int n, done, found;\n\n for (n = 1, done = found = 0; !done; ++n) {\n if (n % digsum(n) == 0) {\n if (found++ < 20) printf(\"%d \", n);\n if (n > 1000) done = printf(\"\\n%d\\n\", n);\n }\n }\n\n return 0;\n}"} +{"id": 19, "output": "R(1 .. 10): 1 3 7 12 18 26 35 45 56 69\nfirst 1000 ok", "Python": "def ffr(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffr.r[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n ffr_n_1 = ffr(n-1)\n lastr = r[-1]\n # extend s up to, and one past, last r \n s += list(range(s[-1] + 1, lastr))\n if s[-1] < lastr: s += [lastr + 1]\n # access s[n-1] temporarily extending s if necessary\n len_s = len(s)\n ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n ans = ffr_n_1 + ffs_n_1\n r.append(ans)\n return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffs.s[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n for i in range(len(r), n+2):\n ffr(i)\n if len(s) > n:\n return s[n]\n raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n first10 = [ffr(i) for i in range(1,11)]\n assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n print(\"ffr(n) for n = [1..10] is\", first10)\n #\n bin = [None] + [0]*1000\n for i in range(40, 0, -1):\n bin[ffr(i)] += 1\n for i in range(960, 0, -1):\n bin[ffs(i)] += 1\n if all(b == 1 for b in bin[1:1000]):\n print(\"All Integers 1..1000 found OK\")\n else:\n print(\"All Integers 1..1000 NOT found only once: ERROR\")", "C": "#include \n#include \n\n// simple extensible array stuff\ntypedef unsigned long long xint;\n\ntypedef struct {\n\tsize_t len, alloc;\n\txint *buf;\n} xarray;\n\nxarray rs, ss;\n\nvoid setsize(xarray *a, size_t size)\n{\n\tsize_t n = a->alloc;\n\tif (!n) n = 1;\n\n\twhile (n < size) n <<= 1;\n\tif (a->alloc < n) {\n\t\ta->buf = realloc(a->buf, sizeof(xint) * n);\n\t\tif (!a->buf) abort();\n\t\ta->alloc = n;\n\t}\n}\n\nvoid push(xarray *a, xint v)\n{\n\twhile (a->alloc <= a->len)\n\t\tsetsize(a, a->alloc * 2);\n\n\ta->buf[a->len++] = v;\n}\n\n\n// sequence stuff\nvoid RS_append(void);\n\nxint R(int n)\n{\n\twhile (n > rs.len) RS_append();\n\treturn rs.buf[n - 1];\n}\n\nxint S(int n)\n{\n\twhile (n > ss.len) RS_append();\n\treturn ss.buf[n - 1];\n}\n\nvoid RS_append()\n{\n\tint n = rs.len;\n\txint r = R(n) + S(n);\n\txint s = S(ss.len);\n\n\tpush(&rs, r);\n\twhile (++s < r) push(&ss, s);\n\tpush(&ss, r + 1); // pesky 3\n}\n\nint main(void)\n{\n\tpush(&rs, 1);\n\tpush(&ss, 2);\n\n\tint i;\n\tprintf(\"R(1 .. 10):\");\n\tfor (i = 1; i <= 10; i++)\n\t\tprintf(\" %llu\", R(i));\n\n\tchar seen[1001] = { 0 };\n\tfor (i = 1; i <= 40; i++) seen[ R(i) ] = 1;\n\tfor (i = 1; i <= 960; i++) seen[ S(i) ] = 1;\n\tfor (i = 1; i <= 1000 && seen[i]; i++);\n\n\tif (i <= 1000) {\n\t\tfprintf(stderr, \"%d not seen\\n\", i);\n\t\tabort();\n\t}\n\n\tputs(\"\\nfirst 1000 ok\");\n\treturn 0;\n}"} +{"id": 20, "output": "1 1 2 3 3 4 5 5 6 6\n502\nflips: 49798", "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))", "C": "#include \n#include \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}"} +{"id": 21, "output": "128.0", "Python": "def horner(coeffs, x):\n\tacc = 0\n\tfor c in reversed(coeffs):\n\t\tacc = acc * x + c\n\treturn acc\n\nhorner( (-19, 7, -4, 6), 3)", "C": "#include \n\ndouble horner(double *coeffs, int s, double x)\n{\n int i;\n double res = 0.0;\n \n for(i=s-1; i >= 0; i--)\n {\n res = res * x + coeffs[i];\n }\n return res;\n}\n\n\nint main()\n{\n double coeffs[] = { -19.0, 7.0, -4.0, 6.0 };\n \n printf(\"%5.1f\\n\", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0));\n return 0;\n}"} +{"id": 22, "output": "n\\k| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n-------------------------------------------------------------------\n1 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n3 | 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1\n5 | 0 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0\n7 | 0 1 1 -1 1 -1 -1 0 1 1 -1 1 -1 -1 0 1 1 -1 1 -1 -1\n9 | 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1\n11 | 0 1 -1 1 1 1 -1 -1 -1 1 -1 0 1 -1 1 1 1 -1 -1 -1 1\n13 | 0 1 -1 1 1 -1 -1 -1 -1 1 1 -1 1 0 1 -1 1 1 -1 -1 -1\n15 | 0 1 1 0 1 0 0 -1 1 0 0 -1 0 -1 -1 0 1 1 0 1 0\n17 | 0 1 1 -1 1 -1 -1 -1 1 1 -1 -1 -1 1 -1 1 1 0 1 1 -1\n19 | 0 1 -1 -1 1 1 1 1 -1 1 -1 1 -1 -1 -1 -1 1 1 -1 0 1\n21 | 0 1 -1 0 1 1 0 0 -1 0 -1 -1 0 -1 0 0 1 1 0 -1 1", "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", "C": "#include \n#include \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}"} +{"id": 23, "output": "3\n0\n", "Python": "def countJewels(s, j):\n return sum(x in j for x in s)\n\nprint countJewels(\"aAAbbbb\", \"aA\")\nprint countJewels(\"ZZ\", \"z\")", "C": "#include \n#include \n\nint count_jewels(const char *s, const char *j) {\n int count = 0;\n for ( ; *s; ++s) if (strchr(j, *s)) ++count;\n return count;\n}\n\nint main() {\n printf(\"%d\\n\", count_jewels(\"aAAbbbb\", \"aA\"));\n printf(\"%d\\n\", count_jewels(\"ZZ\", \"z\"));\n return 0;\n}"} +{"id": 24, "output": " 30107 29759 30107 30096 30056 30030 30167 29867 29863 29948", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n sample, i = [], 0\n def s_of_n(item):\n nonlocal i\n\n i += 1\n if i <= n:\n # Keep first n items\n sample.append(item)\n elif randrange(i) < n:\n # Keep item\n sample[randrange(n)] = item\n return sample\n return s_of_n\n\nif __name__ == '__main__':\n bin = [0]* 10\n items = range(10)\n print(\"Single run samples for n = 3:\")\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n print(\" Item: %i -> sample: %s\" % (item, sample))\n #\n for trial in range(100000):\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n for s in sample:\n bin[s] += 1\n print(\"\\nTest item frequencies for 100000 runs:\\n \",\n '\\n '.join(\"%i:%i\" % x for x in enumerate(bin)))", "C": "#include \n#include \n#include \n#include \n\nstruct s_env {\n unsigned int n, i;\n size_t size;\n void *sample;\n};\n\nvoid s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)\n{\n s_env->i = 0;\n s_env->n = n;\n s_env->size = size;\n s_env->sample = malloc(n * size);\n}\n\nvoid sample_set_i(struct s_env *s_env, unsigned int i, void *item)\n{\n memcpy(s_env->sample + i * s_env->size, item, s_env->size);\n}\n\nvoid *s_of_n(struct s_env *s_env, void *item)\n{\n s_env->i++;\n if (s_env->i <= s_env->n)\n sample_set_i(s_env, s_env->i - 1, item);\n else if ((rand() % s_env->i) < s_env->n)\n sample_set_i(s_env, rand() % s_env->n, item);\n return s_env->sample;\n}\n\nint *test(unsigned int n, int *items_set, unsigned int num_items)\n{\n int i;\n struct s_env s_env;\n s_of_n_init(&s_env, sizeof(items_set[0]), n);\n for (i = 0; i < num_items; i++) {\n s_of_n(&s_env, (void *) &items_set[i]);\n }\n return (int *)s_env.sample;\n}\n\nint main()\n{\n unsigned int i, j;\n unsigned int n = 3;\n unsigned int num_items = 10;\n unsigned int *frequencies;\n int *items_set;\n srand(time(NULL));\n items_set = malloc(num_items * sizeof(int));\n frequencies = malloc(num_items * sizeof(int));\n for (i = 0; i < num_items; i++) {\n items_set[i] = i;\n frequencies[i] = 0;\n }\n for (i = 0; i < 100000; i++) {\n int *res = test(n, items_set, num_items);\n for (j = 0; j < n; j++) {\n frequencies[res[j]]++;\n }\n\tfree(res);\n }\n for (i = 0; i < num_items; i++) {\n printf(\" %d\", frequencies[i]);\n }\n puts(\"\");\n return 0;\n}"} +{"id": 25, "output": "998764543431\n6054854654", "Python": "try:\n cmp # Python 2 OK or NameError in Python 3\n def maxnum(x):\n return ''.join(sorted((str(n) for n in x),\n cmp=lambda x,y:cmp(y+x, x+y)))\nexcept NameError:\n # Python 3\n from functools import cmp_to_key\n def cmp(x, y):\n return -1 if x\n#include \n#include \n\nint catcmp(const void *a, const void *b)\n{\n\tchar ab[32], ba[32];\n\tsprintf(ab, \"%d%d\", *(int*)a, *(int*)b);\n\tsprintf(ba, \"%d%d\", *(int*)b, *(int*)a);\n\treturn strcmp(ba, ab);\n}\n\nvoid maxcat(int *a, int len)\n{\n\tint i;\n\tqsort(a, len, sizeof(int), catcmp);\n\tfor (i = 0; i < len; i++)\n\t\tprintf(\"%d\", a[i]);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint x[] = {1, 34, 3, 98, 9, 76, 45, 4};\n\tint y[] = {54, 546, 548, 60};\n\n\tmaxcat(x, sizeof(x)/sizeof(x[0]));\n\tmaxcat(y, sizeof(y)/sizeof(y[0]));\n\n\treturn 0;\n}"} +{"id": 26, "output": "Number found : 9867312", "Python": "from itertools import (chain, permutations)\nfrom functools import (reduce)\nfrom math import (gcd)\n\n\n# main :: IO ()\ndef main():\n '''Tests'''\n\n # (Division by zero is not an option, so 0 and 5 are omitted)\n digits = [1, 2, 3, 4, 6, 7, 8, 9]\n\n # Least common multiple of the digits above\n lcmDigits = reduce(lcm, digits)\n\n # Any 7 items drawn from the digits above,\n # including any two of [1, 4, 7]\n sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])\n\n print(\n max(\n (\n intFromDigits(x) for x\n in concatMap(permutations)(sevenDigits)\n ),\n key=lambda n: n if 0 == n % lcmDigits else 0\n )\n )\n\n\n# intFromDigits :: [Int] -> Int\ndef intFromDigits(xs):\n '''An integer derived from an\n ordered list of digits.\n '''\n return reduce(lambda a, x: a * 10 + x, xs, 0)\n\n\n# ----------------------- GENERIC ------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been\n mapped. The list monad can be derived by using a\n function f which wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# delete :: Eq a => [a] -> a -> [a]\ndef delete(xs):\n '''xs with the first instance of\n x removed.\n '''\n def go(x):\n ys = xs.copy()\n ys.remove(x)\n return ys\n return go\n\n\n# lcm :: Int -> Int -> Int\ndef lcm(x, y):\n '''The smallest positive integer divisible\n without remainder by both x and y.\n '''\n return 0 if (0 == x or 0 == y) else abs(\n y * (x // gcd(x, y))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C": "#include\n\nint main()\n{\n\tint num = 9876432,diff[] = {4,2,2,2},i,j,k=0;\n\tchar str[10];\n\t\n\t\tstart:snprintf(str,10,\"%d\",num);\n\n\t\tfor(i=0;str[i+1]!=00;i++){\n\t\t\tif(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){\n\t\t\t\tnum -= diff[k];\n\t\t\t\tk = (k+1)%4;\n\t\t\t\tgoto start;\n\t\t\t}\n\t\t\tfor(j=i+1;str[j]!=00;j++)\n\t\t\t\tif(str[i]==str[j]){\n\t\t\t\t\tnum -= diff[k];\n\t\t\t\t\tk = (k+1)%4;\n\t\t\t\t\tgoto start;\n\t\t\t}\n\t\t}\t\n\t\n\tprintf(\"Number found : %d\",num);\n\treturn 0;\n}"} +{"id": 27, "output": " 1 1 1 2 1 3 1 4 3 5\n 1 6 1 7 5 8 1 9 1 10\n 7 11 1 12 5 13 9 14 1 15\n 1 16 11 17 7 18 1 19 13 20\n 1 21 1 22 15 23 1 24 7 25\n 17 26 1 27 11 28 19 29 1 30\n 1 31 21 32 13 33 1 34 23 35\n 1 36 1 37 25 38 11 39 1 40\n 27 41 1 42 17 43 29 44 1 45\n 13 46 31 47 19 48 1 49 33 50", "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 '')", "C": "#include \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}"} +{"id": 28, "output": "gamma = 90 degrees, a*a + b*b == c*c, number of triangles = 3\ngamma = 60 degrees, a*a + b*b - a*b == c*c, number of triangles = 15\ngamma = 120 degrees, a*a + b*b + a*b == c*c, number of triangles = 2", "Python": "N = 13\n\ndef method1(N=N):\n squares = [x**2 for x in range(0, N+1)]\n sqrset = set(squares)\n tri90, tri60, tri120 = (set() for _ in range(3))\n for a in range(1, N+1):\n a2 = squares[a]\n for b in range(1, a + 1):\n b2 = squares[b]\n c2 = a2 + b2\n if c2 in sqrset:\n tri90.add(tuple(sorted((a, b, int(c2**0.5)))))\n ab = a * b\n c2 -= ab\n if c2 in sqrset:\n tri60.add(tuple(sorted((a, b, int(c2**0.5)))))\n c2 += 2 * ab\n if c2 in sqrset:\n tri120.add(tuple(sorted((a, b, int(c2**0.5)))))\n return sorted(tri90), sorted(tri60), sorted(tri120)\n#%%\nif __name__ == '__main__':\n print(f'Integer triangular triples for sides 1..{N}:')\n for angle, triples in zip([90, 60, 120], method1(N)):\n print(f' {angle:3}\u63b3 has {len(triples)} solutions:\\n {triples}')\n _, t60, _ = method1(10_000)\n notsame = sum(1 for a, b, c in t60 if a != b or b != c)\n print('Extra credit:', notsame)", "C": "#include \n#include \n\n#define MAX_SIDE_LENGTH 13\n//#define DISPLAY_TRIANGLES 1\n\nint main(void)\n{\n static char description[3][80] = {\n \"gamma = 90 degrees, a*a + b*b == c*c\",\n \"gamma = 60 degrees, a*a + b*b - a*b == c*c\",\n \"gamma = 120 degrees, a*a + b*b + a*b == c*c\"\n };\n static int coeff[3] = { 0, 1, -1 };\n\n for (int k = 0; k < 3; k++)\n {\n int counter = 0;\n for (int a = 1; a <= MAX_SIDE_LENGTH; a++)\n for (int b = 1; b <= a; b++)\n for (int c = 1; c <= MAX_SIDE_LENGTH; c++)\n if (a * a + b * b - coeff[k] * a * b == c * c)\n {\n counter++;\n#ifdef DISPLAY_TRIANGLES\n printf(\" %d %d %d\\n\", a, b, c);\n#endif\n }\n printf(\"%s, number of triangles = %d\\n\", description[k], counter);\n }\n\n return 0;\n}"} +{"id": 29, "output": "lcm(35, 21) = 105", "Python": "import fractions\ndef lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0", "C": "#include \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}"} +{"id": 30, "output": "distance between `rosettacode' and `raisethysword': 8", "Python": "def levenshteinDistance(str1, str2):\n m = len(str1)\n n = len(str2)\n d = [[i] for i in range(1, m + 1)] # d matrix rows\n d.insert(0, list(range(0, n + 1))) # d matrix columns\n for j in range(1, n + 1):\n for i in range(1, m + 1):\n if str1[i - 1] == str2[j - 1]: # Python (string) is 0-based\n substitutionCost = 0\n else:\n substitutionCost = 1\n d[i].insert(j, min(d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + substitutionCost))\n return d[-1][-1]\n\nprint(levenshteinDistance(\"kitten\",\"sitting\"))\nprint(levenshteinDistance(\"rosettacode\",\"raisethysword\"))", "C": "#include \n#include \n\n/* s, t: two strings; ls, lt: their respective length */\nint levenshtein(const char *s, int ls, const char *t, int lt)\n{\n int a, b, c;\n\n /* if either string is empty, difference is inserting all chars \n * from the other\n */\n if (!ls) return lt;\n if (!lt) return ls;\n\n /* if last letters are the same, the difference is whatever is\n * required to edit the rest of the strings\n */\n if (s[ls - 1] == t[lt - 1])\n return levenshtein(s, ls - 1, t, lt - 1);\n\n /* else try:\n * changing last letter of s to that of t; or\n * remove last letter of s; or\n * remove last letter of t,\n * any of which is 1 edit plus editing the rest of the strings\n */\n a = levenshtein(s, ls - 1, t, lt - 1);\n b = levenshtein(s, ls, t, lt - 1);\n c = levenshtein(s, ls - 1, t, lt );\n\n if (a > b) a = b;\n if (a > c) a = c;\n\n return a + 1;\n}\n\nint main()\n{\n const char *s1 = \"rosettacode\";\n const char *s2 = \"raisethysword\";\n printf(\"distance between `%s' and `%s': %d\\n\", s1, s2,\n levenshtein(s1, strlen(s1), s2, strlen(s2)));\n\n return 0;\n}"} +{"id": 31, "output": "1801 1807 1812 1818 1824 1829 1835 1840 1846 1852 1857 1863 1868 1874 1880 1885 1891 1896 1903 1908 1914 1920 1925 1931 1936 1942 1948 1953 1959 1964 1970 1976 1981 1987 1992 1998 2004 2009 2015 2020 2026 2032 2037 2043 2048 2054 2060 2065 2071 2076 2082 2088 2093 2099 ", "Python": "from datetime import date\n\n\n# longYear :: Year Int -> Bool\ndef longYear(y):\n '''True if the ISO year y has 53 weeks.'''\n return 52 < date(y, 12, 28).isocalendar()[1]\n\n\ndef main():\n '''Longer (53 week) years in the range 2000-2100'''\n for year in [\n x for x in range(2000, 1 + 2100)\n if longYear(x)\n ]:\n print(year)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C": "#include \n#include \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\tprint_long_years(1800, 2100);\n\tprintf(\"\\n\");\n\treturn 0;\n}"} +{"id": 32, "output": " 3 4 5\n 0 4 6 9 13 15", "Python": "def longest_increasing_subsequence(X):\n \"\"\"Returns the Longest Increasing Subsequence in the Given List/Array\"\"\"\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)))", "C": "#include \n#include \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// find longest chain that can follow n[i]\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// find longest chain\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}"} +{"id": 33, "output": "123: 123\n12345: 234\n1234567: 345\n987654321: 654\n10001: 000\n-10001: 000\n-123: 123\n-100: 100\n100: 100\n-12345: 234\n1: error\n2: error\n-1: error\n-10: error\n2002: error\n-2002: error\n0: error\n1234567890: error", "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\npassing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\nfailing = [1, 2, -1, -10, 2002, -2002, 0]\nfor 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))", "C": "#include \n#include \n#include \n\n// we return a static buffer; caller wants it, caller copies it\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}"} +{"id": 34, "output": "The first 30 terms of the Mian-Chowla sequence are:\n1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312 \n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n22526 23291 23564 23881 24596 24768 25631 26037 26255 27219 ", "Python": "from itertools import count, islice, chain\n\ndef mian_chowla():\n mc = [1]\n yield mc[-1]\n psums = set([2])\n newsums = set([])\n for trial in count(2):\n for n in chain(mc, [trial]):\n sum = n + trial\n if sum in psums:\n newsums.clear()\n break\n newsums.add(sum)\n else:\n psums |= newsums\n newsums.clear()\n mc.append(trial)\n yield trial\n\ndef pretty(p, t, s, f):\n print(p, t, \" \".join(str(n) for n in (islice(mian_chowla(), s, f))))\n\nif __name__ == '__main__':\n ts = \"of the Mian-Chowla sequence are:\\n\"\n pretty(\"The first 30 terms\", ts, 0, 30)\n pretty(\"\\nTerms 91 to 100\", ts, 90, 100)", "C": "#include \n#include \n#include \n \n#define n 100\n#define nn ((n * (n + 1)) >> 1)\n\nbool Contains(int lst[], int item, int size) {\n\tfor (int i = size - 1; i >= 0; i--)\n \t\tif (item == lst[i]) return true;\n\treturn false;\n}\n \nint * MianChowla()\n{\n\tstatic int mc[n]; mc[0] = 1;\n\tint sums[nn];\tsums[0] = 2;\n\tint sum, le, ss = 1;\n\tfor (int i = 1; i < n; i++) {\n\t\tle = ss;\n\t\tfor (int j = mc[i - 1] + 1; ; j++) {\n\t\t\tmc[i] = j;\n\t\t\tfor (int k = 0; k <= i; k++) {\n\t\t\t\tsum = mc[k] + j;\n\t\t\t\tif (Contains(sums, sum, ss)) {\n\t\t\t\t\tss = le; goto nxtJ;\n\t\t\t\t}\n\t\t\t\tsums[ss++] = sum;\n\t\t\t}\n\t\t\tbreak;\n\t\tnxtJ:;\n\t\t}\n\t}\n\treturn mc;\n}\n \nint main() {\n\tint * mc; mc = MianChowla();\n\tprintf(\"The first 30 terms of the Mian-Chowla sequence are:\\n\");\n\tfor (int i = 0; i < 30; i++) printf(\"%d \", mc[i]);\n\tprintf(\"\\n\\nTerms 91 to 100 of the Mian-Chowla sequence are:\\n\");\n\tfor (int i = 90; i < 100; i++) printf(\"%d \", mc[i]); \n}"} +{"id": 35, "output": "Maximum non-McNuggets number is 43\n", "Python": "from itertools import product\nnuggets = set(range(101))\nfor 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\nmax(nuggets)", "C": "#include \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}"} +{"id": 36, "output": " 1 1 1 1 1 1 1 1 1 19", "Python": "from itertools import count, islice\n\n\n# a131382 :: [Int]\ndef a131382():\n '''An infinite series of the terms of A131382'''\n return (\n elemIndex(x)(\n productDigitSums(x)\n ) for x in count(1)\n )\n\n\n# productDigitSums :: Int -> [Int]\ndef productDigitSums(n):\n '''The sum of the decimal digits of n'''\n return (digitSum(n * x) for x in count(0))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 40 terms of A131382'''\n\n print(\n table(10)([\n str(x) for x in islice(\n a131382(),\n 40\n )\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divisible, the final list will be shorter than 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# digitSum :: Int -> Int\ndef digitSum(n):\n '''The sum of the digital digits of n.\n '''\n return sum(int(x) for x in list(str(n)))\n\n\n# elemIndex :: a -> [a] -> (None | Int)\ndef elemIndex(x):\n '''Just the first index of x in xs,\n or None if no elements match.\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# table :: Int -> [String] -> String\ndef table(n):\n '''A list of strings formatted as\n right-justified rows of n columns.\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# MAIN ---\nif __name__ == '__main__':\n main()", "C": "#include \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 <= 10; n++) {\n printf(\"%9u\", a131382(n));\n if (n % 10 == 0) printf(\"\\n\");\n }\n return 0;\n}"} +{"id": 37, "output": "First 15 terms of the Padovan n-step number sequences:\n2: 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 \n3: 1 1 1 2 3 4 6 9 13 19 28 41 60 88 129 \n4: 1 1 1 2 3 5 7 11 17 26 40 61 94 144 221 \n5: 1 1 1 2 3 5 8 12 19 30 47 74 116 182 286 \n6: 1 1 1 2 3 5 8 13 20 32 51 81 129 205 326 \n7: 1 1 1 2 3 5 8 13 21 33 53 85 136 218 349 \n8: 1 1 1 2 3 5 8 13 21 34 54 87 140 225 362 ", "Python": "def pad_like(max_n=8, t=15):\n \"\"\"\n First t terms of the first 2..max_n-step Padovan sequences.\n \"\"\"\n start = [[], [1, 1, 1]] # for n=0 and n=1 (hidden).\n for n in range(2, max_n+1):\n this = start[n-1][:n+1] # Initialise from last\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('''\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Padovan n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Values\n|-\n '''.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)", "C": "#include \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}"} +{"id": 38, "output": "p( 1) = 0 p( 2) = 1 p( 3) = 3 p( 4) = 4 p( 5) = 5 \np( 6) = 7 p( 7) = 8 p( 8) = 9 p( 9) = 10 p(10) = 11 \np(11) = 13 p(12) = 14 p(13) = 15 p(14) = 16 p(15) = 17 \np(16) = 18 p(17) = 19 p(18) = 20 p(19) = 21 p(20) = 23 ", "Python": "import 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 \"\"\"Flip the stack of pancakes at the given position.\"\"\"\n return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n \"\"\"Return the nth pancake number.\"\"\"\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.\")", "C": "#include \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}"} +{"id": 39, "output": "yes: The quick brown fox jumps over lazy dogs.\nno : The five boxing wizards dump quickly.", "Python": "import string, sys\nif sys.version_info[0] < 3:\n input = raw_input\n\ndef ispangram(sentence, alphabet=string.ascii_lowercase):\n alphaset = set(alphabet)\n return alphaset <= set(sentence.lower())\n\nprint ( ispangram(input('Sentence: ')) )", "C": "#include \n\nint pangram(const char *s)\n{\n\tint c, mask = (1 << 26) - 1;\n\twhile ((c = (*s++)) != '\\0') /* 0x20 converts lowercase to upper */\n\t\tif ((c &= ~0x20) <= 'Z' && c >= 'A')\n\t\t\tmask &= ~(1 << (c - 'A'));\n\n\treturn !mask;\n}\n\nint main()\n{\n\tint i;\n\tconst char *s[] = {\t\"The quick brown fox jumps over lazy dogs.\",\n\t\t\t\t\"The five boxing wizards dump quickly.\", };\n\n\tfor (i = 0; i < 2; i++)\n\t\tprintf(\"%s: %s\\n\", pangram(s[i]) ? \"yes\" : \"no \", s[i]);\n\n\treturn 0;\n}"} +{"id": 1, "output": "Results: (4,000000 + 0,000000 i) (1,000000 + -2,414214 i) (0,000000 + 0,000000 i) (1,000000 + -0,414214 i) (0,000000 + 0,000000 i) (1,000000 + 0,414214 i) (0,000000 + 0,000000 i) (1,000000 + 2,414214 i)\n", "Python": "from cmath import exp, pi\n\ndef fft(x):\n N = len(x)\n if N <= 1: return x\n even = fft(x[0::2])\n odd = fft(x[1::2])\n T= [exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]\n return [even[k] + T[k] for k in range(N//2)] + \\\n [even[k] - T[k] for k in range(N//2)]\n\nprint( ' '.join(\"%5.3f\" % abs(f) \n for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) )\n", "Java": "import static java.lang.Math.*;\n\npublic class FastFourierTransform {\n\n public static int bitReverse(int n, int bits) {\n int reversedN = n;\n int count = bits - 1;\n\n n >>= 1;\n while (n > 0) {\n reversedN = (reversedN << 1) | (n & 1);\n count--;\n n >>= 1;\n }\n\n return ((reversedN << count) & ((1 << bits) - 1));\n }\n\n static void fft(Complex[] buffer) {\n\n int bits = (int) (log(buffer.length) / log(2));\n for (int j = 1; j < buffer.length / 2; j++) {\n\n int swapPos = bitReverse(j, bits);\n Complex temp = buffer[j];\n buffer[j] = buffer[swapPos];\n buffer[swapPos] = temp;\n }\n\n for (int N = 2; N <= buffer.length; N <<= 1) {\n for (int i = 0; i < buffer.length; i += N) {\n for (int k = 0; k < N / 2; k++) {\n\n int evenIndex = i + k;\n int oddIndex = i + k + (N / 2);\n Complex even = buffer[evenIndex];\n Complex odd = buffer[oddIndex];\n\n double term = (-2 * PI * k) / (double) N;\n Complex exp = (new Complex(cos(term), sin(term)).mult(odd));\n\n buffer[evenIndex] = even.add(exp);\n buffer[oddIndex] = even.sub(exp);\n }\n }\n }\n }\n\n public static void main(String[] args) {\n double[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};\n\n Complex[] cinput = new Complex[input.length];\n for (int i = 0; i < input.length; i++)\n cinput[i] = new Complex(input[i], 0.0);\n\n fft(cinput);\n\n System.out.println(\"Results:\");\n for (Complex c : cinput) {\n System.out.println(c);\n }\n }\n}\n\nclass Complex {\n public final double re;\n public final double im;\n\n public Complex() {\n this(0, 0);\n }\n\n public Complex(double r, double i) {\n re = r;\n im = i;\n }\n\n public Complex add(Complex b) {\n return new Complex(this.re + b.re, this.im + b.im);\n }\n\n public Complex sub(Complex b) {\n return new Complex(this.re - b.re, this.im - b.im);\n }\n\n public Complex mult(Complex b) {\n return new Complex(this.re * b.re - this.im * b.im,\n this.re * b.im + this.im * b.re);\n }\n\n @Override\n public String toString() {\n return String.format(\"(%f,%f)\", re, im);\n }\n}\n"} +{"id": 2, "output": "Count of divisors for the first 100 positive integers: 1 2 2 3 2 4 2 4 3 4 2 6 2 4 4 5 2 6 2 6 4 4 2 8 3 4 4 6 2 8 2 6 4 4 4 9 2 4 4 8 2 8 2 6 6 4 2 10 3 6 4 6 2 8 4 8 4 4 2 12 2 4 6 7 4 8 2 6 4 8 2 12 2 4 6 6 4 8 2 10 5 4 2 12 4 4 4 8 2 12 4 6 4 4 4 12 2 6 6 9 \n", "Python": "def factorize(n):\n assert(isinstance(n, int))\n if n < 0: \n n = -n \n if n < 2: \n return \n k = 0 \n while 0 == n%2: \n k += 1 \n n //= 2 \n if 0 < k: \n yield (2,k) \n p = 3 \n while p*p <= n: \n k = 0 \n while 0 == n%p: \n k += 1 \n n //= p \n if 0 < k: \n yield (p,k)\n p += 2 \n if 1 < n: \n yield (n,1) \n\ndef tau(n): \n assert(n != 0) \n ans = 1 \n for (p,k) in factorize(n): \n ans *= 1 + k\n return ans\n\nif __name__ == \"__main__\":\n print(*map(tau, range(1, 101)))\n", "Java": "public class TauFunction {\n private static long divisorCount(long n) {\n long total = 1;\n // Deal with powers of 2 first\n for (; (n & 1) == 0; n >>= 1) {\n ++total;\n }\n // Odd prime factors up to the square root\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 // If n > 1 then it's prime\n if (n > 1) {\n total *= 2;\n }\n return total;\n }\n\n public static void main(String[] args) {\n final int limit = 100;\n System.out.printf(\"Count of divisors for the first %d positive integers:\\n\", limit);\n for (long n = 1; n <= limit; ++n) {\n System.out.printf(\"%3d\", divisorCount(n));\n if (n % 20 == 0) {\n System.out.println();\n }\n }\n }\n}\n"} +{"id": 3, "output": "[6.0, 25.5, 40.0, 42.5, 49.0] [7.0, 15.0, 37.5, 40.0, 41.0] [-1.95059594, -0.676741205, 0.23324706, 0.746070945, 1.73131507]\n", "Python": "from __future__ import division\nimport math\nimport sys\n\ndef fivenum(array):\n n = len(array)\n if n == 0:\n print(\"you entered an empty array.\")\n sys.exit()\n x = sorted(array)\n \n n4 = math.floor((n+3.0)/2.0)/2.0\n d = [1, n4, (n+1)/2, n+1-n4, n]\n sum_array = []\n \n for e in range(5):\n floor = int(math.floor(d[e] - 1))\n ceil = int(math.ceil(d[e] - 1))\n sum_array.append(0.5 * (x[floor] + x[ceil]))\n \n return sum_array\n\nx = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,\n-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,\n1.04312009, -0.10305385, 0.75775634, 0.32566578]\n\ny = fivenum(x)\nprint(y)\n", "Java": "import java.util.Arrays;\n\npublic class Fivenum {\n\n static double median(double[] x, int start, int endInclusive) {\n int size = endInclusive - start + 1;\n if (size <= 0) throw new IllegalArgumentException(\"Array slice cannot be empty\");\n int m = start + size / 2;\n return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;\n }\n\n static double[] fivenum(double[] x) {\n for (Double d : x) {\n if (d.isNaN())\n throw new IllegalArgumentException(\"Unable to deal with arrays containing NaN\");\n }\n double[] result = new double[5];\n Arrays.sort(x);\n result[0] = x[0];\n result[2] = median(x, 0, x.length - 1);\n result[4] = x[x.length - 1];\n int m = x.length / 2;\n int lowerEnd = (x.length % 2 == 1) ? m : m - 1;\n result[1] = median(x, 0, lowerEnd);\n result[3] = median(x, m, x.length - 1);\n return result;\n }\n\n public static void main(String[] args) {\n double xl[][] = {\n {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},\n {36.0, 40.0, 7.0, 39.0, 41.0, 15.0},\n {\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n }\n };\n for (double[] x : xl) System.out.printf(\"%s\\n\\n\", Arrays.toString(fivenum(x)));\n }\n}\n"} +{"id": 4, "output": "2\n", "Python": "arr = ['apple', 'orange'] # a list for an array\n\ndef setup():\n println(len(arr))\n", "Java": "String[] array = [\"apple\", \"orange\"];\nInt length = array.size;\n"} +{"id": 5, "output": "0.8472130847939792\n", "Python": "from math import sqrt\n\ndef agm(a0, g0, tolerance=1e-10):\n \"\"\"\n Calculating the arithmetic-geometric mean of two numbers a0, g0.\n\n tolerance the tolerance for the converged \n value of the arithmetic-geometric mean\n (default value = 1e-10)\n \"\"\"\n an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)\n while abs(an - gn) > tolerance:\n an, gn = (an + gn) / 2.0, sqrt(an * gn)\n return an\n\nprint agm(1, 1 / sqrt(2))\n", "Java": "/*\n * Arithmetic-Geometric Mean of 1 & 1/sqrt(2)\n * Brendan Shaklovitz\n * 5/29/12\n */\npublic class ArithmeticGeometricMean {\n\n public static double agm(double a, double g) {\n double a1 = a;\n double g1 = g;\n while (Math.abs(a1 - g1) >= 1.0e-14) {\n double arith = (a1 + g1) / 2.0;\n double geom = Math.sqrt(a1 * g1);\n a1 = arith;\n g1 = geom;\n }\n return a1;\n }\n\n public static void main(String[] args) {\n System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0)));\n }\n}\n"} +{"id": 6, "output": "1, Solve RC tasks 2, Tax return 3, Clear drains 4, Feed cat 5, Make tea\n", "Python": ">>> import queue\n>>> pq = queue.PriorityQueue()\n>>> for item in ((3, \"Clear drains\"), (4, \"Feed cat\"), (5, \"Make tea\"), (1, \"Solve RC tasks\"), (2, \"Tax return\")):\n pq.put(item)\n\n \n>>> while not pq.empty():\n print(pq.get_nowait())\n\n \n(1, 'Solve RC tasks')\n(2, 'Tax return')\n(3, 'Clear drains')\n(4, 'Feed cat')\n(5, 'Make tea')\n>>>\n", "Java": "import java.util.PriorityQueue;\n\nclass Main implements Comparable
{\n final int priority;\n final String name;\n\n public Task(int p, String n) {\n priority = p;\n name = n;\n }\n\n public String toString() {\n return priority + \", \" + name;\n }\n\n public int compareTo(Task other) {\n return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;\n }\n\n public static void main(String[] args) {\n PriorityQueue pq = new PriorityQueue();\n pq.add(new Task(3, \"Clear drains\"));\n pq.add(new Task(4, \"Feed cat\"));\n pq.add(new Task(5, \"Make tea\"));\n pq.add(new Task(1, \"Solve RC tasks\"));\n pq.add(new Task(2, \"Tax return\"));\n\n while (!pq.isEmpty())\n System.out.println(pq.remove());\n }\n}\n"} +{"id": 7, "output": "0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427 2646798\n", "Python": "#!/usr/bin/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": 8, "output": "1 2 3 4 5 6 11 13 24 66 68 75 167 171 172 287\n", "Python": "import pyprimes\n\ndef primorial_prime(_pmax=500):\n isprime = pyprimes.isprime\n n, primo = 0, 1\n for prime in pyprimes.nprimes(_pmax):\n n, primo = n+1, primo * prime\n if isprime(primo-1) or isprime(primo+1):\n yield n\n \nif __name__ == '__main__':\n # Turn off warning on use of probabilistic formula for prime test\n pyprimes.warn_probably = False \n for i, n in zip(range(20), primorial_prime()):\n print('Primorial prime %2i at primorial index: %3i' % (i+1, n))\n", "Java": "import java.math.BigInteger;\n\npublic class PrimorialPrimes {\n\n final static int sieveLimit = 1550_000;\n static boolean[] notPrime = sieve(sieveLimit);\n\n public static void main(String[] args) {\n\n int count = 0;\n for (int i = 1; i < 1000_000 && count < 20; i++) {\n BigInteger b = primorial(i);\n if (b.add(BigInteger.ONE).isProbablePrime(1)\n || b.subtract(BigInteger.ONE).isProbablePrime(1)) {\n System.out.printf(\"%d \", i);\n count++;\n }\n }\n }\n\n static BigInteger primorial(int n) {\n if (n == 0)\n return BigInteger.ONE;\n\n BigInteger result = BigInteger.ONE;\n for (int i = 0; i < sieveLimit && n > 0; i++) {\n if (notPrime[i])\n continue;\n result = result.multiply(BigInteger.valueOf(i));\n n--;\n }\n return result;\n }\n\n public static boolean[] sieve(int limit) {\n boolean[] composite = new boolean[limit];\n composite[0] = composite[1] = true;\n\n int max = (int) Math.sqrt(limit);\n for (int n = 2; n <= max; n++) {\n if (!composite[n]) {\n for (int k = n * n; k < limit; k += n) {\n composite[k] = true;\n }\n }\n }\n return composite;\n }\n}\n"} +{"id": 9, "output": "3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198938095257201065485862824\n", "Python": "from decimal import *\n\nD = Decimal\ngetcontext().prec = 100\na = n = D(1)\ng, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)\nfor i in range(18):\n x = [(a + g) * half, (a * g).sqrt()]\n var = x[0] - a\n z -= var * var * n\n n += n\n a, g = x \nprint(a * a / z)\n", "Java": "import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Objects;\n\npublic class Calculate_Pi {\n private static final MathContext con1024 = new MathContext(1024);\n private static final BigDecimal bigTwo = new BigDecimal(2);\n private static final BigDecimal bigFour = new BigDecimal(4);\n\n private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {\n BigDecimal x0 = BigDecimal.ZERO;\n BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));\n while (!Objects.equals(x0, x1)) {\n x0 = x1;\n x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);\n }\n return x1;\n }\n\n public static void main(String[] args) {\n BigDecimal a = BigDecimal.ONE;\n BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);\n BigDecimal t;\n BigDecimal sum = BigDecimal.ZERO;\n BigDecimal pow = bigTwo;\n while (!Objects.equals(a, g)) {\n t = a.add(g).divide(bigTwo, con1024);\n g = bigSqrt(a.multiply(g), con1024);\n a = t;\n pow = pow.multiply(bigTwo);\n sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));\n }\n BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);\n System.out.println(pi);\n }\n}\n"} +{"id": 10, "output": "Average time is : 23:47:43\n", "Python": "from cmath import rect, phase\nfrom math import radians, degrees\n\n\ndef mean_angle(deg):\n return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n\ndef mean_time(times):\n t = (time.split(':') for time in times)\n seconds = ((float(s) + int(m) * 60 + int(h) * 3600) \n for h, m, s in t)\n day = 24 * 60 * 60\n to_angles = [s * 360. / day for s in seconds]\n mean_as_angle = mean_angle(to_angles)\n mean_seconds = mean_as_angle * day / 360.\n if mean_seconds < 0:\n mean_seconds += day\n h, m = divmod(mean_seconds, 3600)\n m, s = divmod(m, 60)\n return '%02i:%02i:%02i' % (h, m, s)\n\n\nif __name__ == '__main__':\n print( mean_time([\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"]) )\n", "Java": "public class MeanTimeOfDay {\n \n static double meanAngle(double[] angles) {\n int len = angles.length;\n double sinSum = 0.0;\n for (int i = 0; i < len; i++) {\n sinSum += Math.sin(angles[i] * Math.PI / 180.0);\n }\n \n double cosSum = 0.0;\n for (int i = 0; i < len; i++) {\n cosSum += Math.cos(angles[i] * Math.PI / 180.0);\n }\n\n return Math.atan2(sinSum / len, cosSum / len) * 180.0 / Math.PI;\n }\n\n /* time string assumed to be in format \"hh:mm:ss\" */\n static int timeToSecs(String t) {\n int hours = Integer.parseInt(t.substring(0, 2));\n int mins = Integer.parseInt(t.substring(3, 5));\n int secs = Integer.parseInt(t.substring(6, 8));\n return 3600 * hours + 60 * mins + secs;\n }\n\n /* 1 second of time = 360/(24 * 3600) = 1/240th degree */\n static double timeToDegrees(String t) {\n return timeToSecs(t) / 240.0;\n }\n\n static String degreesToTime(double d) {\n if (d < 0.0) d += 360.0;\n int secs = (int)(d * 240.0);\n int hours = secs / 3600;\n int mins = secs % 3600;\n secs = mins % 60;\n mins /= 60;\n return String.format(\"%2d:%2d:%2d\", hours, mins, secs);\n }\n\n public static void main(String[] args) {\n String[] tm = {\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"};\n double[] angles = new double[4];\n for (int i = 0; i < 4; i++) angles[i] = timeToDegrees(tm[i]); \n double mean = meanAngle(angles);\n System.out.println(\"Average time is : \" + degreesToTime(mean));\n }\n}\n"} +{"id": 11, "output": "5 6 7 10 11 12 13 17 18 19 21 25 28 31 33 35 36 37 41 47 49 55 59 61 65 67 69 73 79 82 84 87 91 93 97 103 107 109 115 117 121 127 129 131 133 137 143 145 151 155 157 162 167 171 173 179 181 185 191 193 199\n", "Python": "'''Binary and Ternary digit sums both prime'''\n\n\n# digitSumsPrime :: Int -> [Int] -> Bool\ndef digitSumsPrime(n):\n '''True if the digits of n in each\n given base have prime sums.\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# digitSum :: Int -> Int -> Int\ndef digitSum(base):\n '''The sum of the digits of n in a given 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# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Matching integers in the range [1..199]'''\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# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than 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# isPrime :: Int -> Bool\ndef isPrime(n):\n '''True if n is prime.'''\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# table :: Int -> [String] -> String\ndef table(n):\n '''A list of strings formatted as\n rows of n (right justified) columns.\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# MAIN ---\nif __name__ == '__main__':\n main()\n", "C": "#include \n#include \n\n/* good enough for small numbers */\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/* digit sum in given base */\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": 12, "output": "1 2 3 4 5 6 7 8 9 10 11 12 1 1 10 2 16 3 22 4 28 5 34 6 1 1 5 1 8 10 11 2 14 16 17 3 1 1 16 1 4 5 34 1 7 8 52 10 1 1 8 1 2 16 17 1 22 4 26 5 1 1 4 1 1 8 52 1 11 2 13 16 1 1 2 1 1 4 26 1 34 1 40 8 1 1 1 1 1 2 13 1 17 1 20 4 1 1 1 1 1 1 40 1 52 1 10 2 1 1 1 1 1 1 20 1 26 1 5 1 1 1 1 1 1 1 10 1 13 1 16 1 1 1 1 1 1 1 5 1 40 1 8 1 1 1 1 1 1 1 16 1 20 1 4 1 1 1 1 1 1 1 8 1 10 1 2 1 1 1 1 1 1 1 4 1 5 1 1 1 1 1 1 1 1 1 2 1 16 1 1 1 1 1 1 1 1 1 1 1 8 1 1 1 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 COUNTS: 0 1 7 2 5 8 16 3 19 6 14 9\n", "Python": "environments = [{'cnt':0, 'seq':i+1} for i in range(12)]\n\ncode = '''\nprint('% 4d' % seq, end='')\nif seq != 1:\n cnt += 1\n seq = 3 * seq + 1 if seq & 1 else seq // 2\n'''\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 \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": 13, "output": "Sh ws soul strppr. Sh took my hrt!\n", "Python": ">>> def stripchars(s, chars):\n... return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws soul strppr. Sh took my hrt!'\n", "C": "#include \n#include \n#include \n\n /* removes all chars from string */\nchar *strip_chars(const char *string, const char *chars)\n{\n char * newstr = malloc(strlen(string) + 1);\n int counter = 0;\n\n for ( ; *string; string++) {\n if (!strchr(chars, *string)) {\n newstr[ counter ] = *string;\n ++ counter;\n }\n }\n\n newstr[counter] = 0;\n return newstr;\n}\n\nint main(void)\n{\n char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n printf(\"%s\\n\", new);\n\n free(new);\n return 0;\n}\n"} +{"id": 14, "output": "627615: pers 2, root 9 39390: pers 2, root 6 588225: pers 2, root 3 393900588225: pers 2, root 9\n", "Python": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\" \n % (n, persistance, root))\n", "C": "#include \n\nint droot(long long int x, int base, int *pers)\n{\n\tint d = 0;\n\tif (pers)\n\t\tfor (*pers = 0; x >= base; x = d, (*pers)++)\n\t\t\tfor (d = 0; x; d += x % base, x /= base);\n\telse if (x && !(d = x % (base - 1)))\n\t\t\td = base - 1;\n\n\treturn d;\n}\n\nint main(void)\n{\n\tint i, d, pers;\n\tlong long x[] = {627615, 39390, 588225, 393900588225LL};\n\n\tfor (i = 0; i < 4; i++) {\n\t\td = droot(x[i], 10, &pers);\n\t\tprintf(\"%lld: pers %d, root %d\\n\", x[i], pers, d);\n\t}\n\n\treturn 0;\n}\n"} +{"id": 15, "output": "1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1\n", "Python": "def pascal(n):\n \"\"\"Prints out n rows of Pascal's triangle.\n It returns False for failure and True for success.\"\"\"\n row = [1]\n k = [0]\n for x in range(max(n,0)):\n print row\n row=[l+r for l,r in zip(row+k,k+row)]\n return n>=1\n", "C": "#include \n\nvoid pascaltriangle(unsigned int n)\n{\n unsigned int c, i, j, k;\n\n for(i=0; i < n; i++) {\n c = 1;\n for(j=1; j <= 2*(n-1-i); j++) printf(\" \");\n for(k=0; k <= i; k++) {\n printf(\"%3d \", c);\n c = c * (i-k)/(k+1);\n }\n printf(\"\\n\");\n }\n}\n\nint main()\n{\n pascaltriangle(8);\n return 0;\n}\n"} +{"id": 16, "output": "Extra primes under 10,000: 1: 2 2: 3 3: 5 4: 7 5: 23 6: 223 7: 227 8: 337 9: 353 10: 373 11: 557 12: 577 13: 733 14: 757 15: 773 16: 2,333 17: 2,357 18: 2,377 19: 2,557 20: 2,753 21: 2,777 22: 3,253 23: 3,257 24: 3,323 25: 3,527 26: 3,727 27: 5,233 28: 5,237 29: 5,273 30: 5,323 31: 5,527 32: 7,237 33: 7,253 34: 7,523 35: 7,723 36: 7,727 Last 10 extra primes under 1,000,000,000: 9,049: 777,753,773 9,050: 777,755,753 9,051: 777,773,333 9,052: 777,773,753 9,053: 777,775,373 9,054: 777,775,553 9,055: 777,775,577 9,056: 777,777,227 9,057: 777,777,577 9,058: 777,777,773 \n", "Python": "from itertools import *\nfrom functools import reduce\n\nclass Sieve(object):\n \"\"\"Sieve of Eratosthenes\"\"\"\n def __init__(self):\n self._primes = []\n self._comps = {}\n self._max = 2;\n \n def isprime(self, n):\n \"\"\"check if number is prime\"\"\"\n if n >= self._max: self._genprimes(n)\n return n >= 2 and n in self._primes\n \n def _genprimes(self, max):\n while self._max <= max:\n if self._max not in self._comps:\n self._primes.append(self._max)\n self._comps[self._max*self._max] = [self._max]\n else:\n for p in self._comps[self._max]:\n ps = self._comps.setdefault(self._max+p, [])\n ps.append(p)\n del self._comps[self._max]\n self._max += 1\n \ndef extra_primes():\n \"\"\"Successively generate all extra primes.\"\"\"\n d = [2,3,5,7]\n s = Sieve()\n for cand in chain.from_iterable(product(d, repeat=r) for r in count(1)):\n num = reduce(lambda x, y: x*10+y, cand)\n if s.isprime(num) and s.isprime(sum(cand)): yield num\n \nfor n in takewhile(lambda n: n < 10000, extra_primes()):\n print(n)\n", "C": "#include \n#include \n#include \n\nunsigned int next_prime_digit_number(unsigned int n) {\n if (n == 0)\n return 2;\n switch (n % 10) {\n case 2:\n return n + 1;\n case 3:\n case 5:\n return n + 2;\n default:\n return 2 + next_prime_digit_number(n/10) * 10;\n }\n}\n\nbool is_prime(unsigned int n) {\n if (n < 2)\n return false;\n if ((n & 1) == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n if (n % 5 == 0)\n return n == 5;\n static const unsigned int wheel[] = { 4,2,4,2,4,6,2,6 };\n unsigned int p = 7;\n for (;;) {\n for (int w = 0; w < sizeof(wheel)/sizeof(wheel[0]); ++w) {\n if (p * p > n)\n return true;\n if (n % p == 0)\n return false;\n p += wheel[w];\n }\n }\n}\n\nunsigned int digit_sum(unsigned int n) {\n unsigned int sum = 0;\n for (; n > 0; n /= 10)\n sum += n % 10;\n return sum;\n}\n\nint main() {\n setlocale(LC_ALL, \"\");\n const unsigned int limit1 = 10000;\n const unsigned int limit2 = 1000000000;\n const int last = 10;\n unsigned int p = 0, n = 0;\n unsigned int extra_primes[last];\n printf(\"Extra primes under %'u:\\n\", limit1);\n while ((p = next_prime_digit_number(p)) < limit2) {\n if (is_prime(digit_sum(p)) && is_prime(p)) {\n ++n;\n if (p < limit1)\n printf(\"%2u: %'u\\n\", n, p);\n extra_primes[n % last] = p;\n }\n }\n printf(\"\\nLast %d extra primes under %'u:\\n\", last, limit2);\n for (int i = last - 1; i >= 0; --i)\n printf(\"%'u: %'u\\n\", n-i, extra_primes[(n-i) % last]);\n return 0;\n}\n"} +{"id": 17, "output": "take all salami take all ham take all brawn take all greaves take 3.5kg of 3.7 kg of welt\n", "Python": "# NAME, WEIGHT, VALUE (for this weight)\nitems = [(\"beef\", 3.8, 36.0),\n (\"pork\", 5.4, 43.0),\n (\"ham\", 3.6, 90.0),\n (\"greaves\", 2.4, 45.0),\n (\"flitch\", 4.0, 30.0),\n (\"brawn\", 2.5, 56.0),\n (\"welt\", 3.7, 67.0),\n (\"salami\", 3.0, 95.0),\n (\"sausage\", 5.9, 98.0)]\n\nMAXWT = 15.0\n\nsorted_items = sorted(((value/amount, amount, name)\n for name, amount, value in items),\n reverse = True)\nwt = val = 0\nbagged = []\nfor unit_value, amount, name in sorted_items:\n portion = min(MAXWT - wt, amount)\n wt += portion\n addval = portion * unit_value\n val += addval\n bagged += [(name, portion, addval)]\n if wt >= MAXWT:\n break\n\nprint(\" ITEM PORTION VALUE\")\nprint(\"\\n\".join(\"%10s %6.2f %6.2f\" % item for item in bagged))\nprint(\"\\nTOTAL WEIGHT: %5.2f\\nTOTAL VALUE: %5.2f\" % (wt, val))\n", "C": "#include \n#include \n\nstruct item { double w, v; const char *name; } items[] = {\n\t{ 3.8, 36, \"beef\" },\n\t{ 5.4, 43, \"pork\" },\n\t{ 3.6, 90, \"ham\" },\n\t{ 2.4, 45, \"greaves\" },\n\t{ 4.0, 30, \"flitch\" },\n\t{ 2.5, 56, \"brawn\" },\n\t{ 3.7, 67, \"welt\" },\n\t{ 3.0, 95, \"salami\" },\n\t{ 5.9, 98, \"sausage\" },\n};\n\nint item_cmp(const void *aa, const void *bb)\n{\n\tconst struct item *a = aa, *b = bb;\n\tdouble ua = a->v / a->w, ub = b->v / b->w;\n\treturn ua < ub ? -1 : ua > ub;\n}\n\nint main()\n{\n\tstruct item *it;\n\tdouble space = 15;\n\n\tqsort(items, 9, sizeof(struct item), item_cmp);\n\tfor (it = items + 9; it---items && space > 0; space -= it->w)\n\t\tif (space >= it->w)\n\t\t\tprintf(\"take all %s\\n\", it->name);\n\t\telse\n\t\t\tprintf(\"take %gkg of %g kg of %s\\n\",\n\t\t\t\tspace, it->w, it->name);\n\n\treturn 0;\n}\n"} +{"id": 18, "output": "<= : 87.197168% 80551 > : 12.802832% 11827\n", "Python": "from itertools import combinations as comb\n\ndef statistic(ab, a):\n sumab, suma = sum(ab), sum(a)\n return ( suma / len(a) -\n (sumab -suma) / (len(ab) - len(a)) )\n\ndef permutationTest(a, b):\n ab = a + b\n Tobs = statistic(ab, a)\n under = 0\n for count, perm in enumerate(comb(ab, len(a)), 1):\n if statistic(ab, perm) <= Tobs:\n under += 1\n return under * 100. / count\n\ntreatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]\ncontrolGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]\nunder = permutationTest(treatmentGroup, controlGroup)\nprint(\"under=%.2f%%, over=%.2f%%\" % (under, 100. - under))\n", "C": "#include \n\nint data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,\n 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };\n\nint pick(int at, int remain, int accu, int treat)\n{\n if (!remain) return (accu > treat) ? 1 : 0;\n\n return pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );\n}\n\nint main()\n{\n int treat = 0, i;\n int le, gt;\n double total = 1;\n for (i = 0; i < 9; i++) treat += data[i];\n for (i = 19; i > 10; i--) total *= i;\n for (i = 9; i > 0; i--) total /= i;\n\n gt = pick(19, 9, 0, treat);\n le = total - gt;\n\n printf(\"<= : %f%% %d\\n > : %f%% %d\\n\",\n 100 * le / total, le, 100 * gt / total, gt);\n return 0;\n}\n"} +{"id": 19, "output": "abracadabra, brabacadaar, (0) seesaw, wssaee, (0) elk, kel, (0) grrrrrr, rrrrrrg, (5) up, pu, (0) a, a, (1) aabbbbaa, bbaaaabb, (0) , , (0) xxxxx, xxxxx, (5)\n", "Python": "import random\n\ndef count(w1,wnew):\n return sum(c1==c2 for c1,c2 in zip(w1, wnew))\n\ndef best_shuffle(w):\n wnew = list(w)\n n = len(w)\n rangelists = (list(range(n)), list(range(n)))\n for r in rangelists:\n random.shuffle(r)\n rangei, rangej = rangelists\n for i in rangei:\n for j in rangej:\n if i != j and wnew[j] != wnew[i] and w[i] != wnew[j] and w[j] != wnew[i]:\n wnew[j], wnew[i] = wnew[i], wnew[j]\n break\n wnew = ''.join(wnew)\n return wnew, count(w, wnew)\n\n\nif __name__ == '__main__':\n test_words = ('tree abracadabra seesaw elk grrrrrr up a ' \n + 'antidisestablishmentarianism hounddogs').split()\n test_words += ['aardvarks are ant eaters', 'immediately', 'abba']\n for w in test_words:\n wnew, c = best_shuffle(w)\n print(\"%29s, %-29s ,(%i)\" % (w, wnew, c))\n", "C": "#include \n#include \n#include \n#include \n#include \n\n#define DEBUG\n\nvoid best_shuffle(const char* txt, char* result) {\n const size_t len = strlen(txt);\n if (len == 0)\n return;\n\n#ifdef DEBUG\n // txt and result must have the same length\n assert(len == strlen(result));\n#endif\n\n // how many of each character?\n size_t counts[UCHAR_MAX];\n memset(counts, '\\0', UCHAR_MAX * sizeof(int));\n size_t fmax = 0;\n for (size_t i = 0; i < len; i++) {\n counts[(unsigned char)txt[i]]++;\n const size_t fnew = counts[(unsigned char)txt[i]];\n if (fmax < fnew)\n fmax = fnew;\n }\n assert(fmax > 0 && fmax <= len);\n\n // all character positions, grouped by character\n size_t *ndx1 = malloc(len * sizeof(size_t));\n if (ndx1 == NULL)\n exit(EXIT_FAILURE);\n for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++)\n if (counts[ch])\n for (size_t j = 0; j < len; j++)\n if (ch == (unsigned char)txt[j]) {\n ndx1[i] = j;\n i++;\n }\n\n // regroup them for cycles\n size_t *ndx2 = malloc(len * sizeof(size_t));\n if (ndx2 == NULL)\n exit(EXIT_FAILURE);\n for (size_t i = 0, n = 0, m = 0; i < len; i++) {\n ndx2[i] = ndx1[n];\n n += fmax;\n if (n >= len) {\n m++;\n n = m;\n }\n }\n\n // how long can our cyclic groups be?\n const size_t grp = 1 + (len - 1) / fmax;\n assert(grp > 0 && grp <= len);\n\n // how many of them are full length?\n const size_t lng = 1 + (len - 1) % fmax;\n assert(lng > 0 && lng <= len);\n\n // rotate each group\n for (size_t i = 0, j = 0; i < fmax; i++) {\n const size_t first = ndx2[j];\n const size_t glen = grp - (i < lng ? 0 : 1);\n for (size_t k = 1; k < glen; k++)\n ndx1[j + k - 1] = ndx2[j + k];\n ndx1[j + glen - 1] = first;\n j += glen;\n }\n\n // result is original permuted according to our cyclic groups\n result[len] = '\\0';\n for (size_t i = 0; i < len; i++)\n result[ndx2[i]] = txt[ndx1[i]];\n\n free(ndx1);\n free(ndx2);\n}\n\nvoid display(const char* txt1, const char* txt2) {\n const size_t len = strlen(txt1);\n assert(len == strlen(txt2));\n int score = 0;\n for (size_t i = 0; i < len; i++)\n if (txt1[i] == txt2[i])\n score++;\n (void)printf(\"%s, %s, (%u)\\n\", txt1, txt2, score);\n}\n\nint main() {\n const char* data[] = {\"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\",\n \"up\", \"a\", \"aabbbbaa\", \"\", \"xxxxx\"};\n const size_t data_len = sizeof(data) / sizeof(data[0]);\n for (size_t i = 0; i < data_len; i++) {\n const size_t shuf_len = strlen(data[i]) + 1;\n char shuf[shuf_len];\n\n#ifdef DEBUG\n memset(shuf, 0xFF, sizeof shuf);\n shuf[shuf_len - 1] = '\\0';\n#endif\n\n best_shuffle(data[i], shuf);\n display(data[i], shuf);\n }\n\n return EXIT_SUCCESS;\n}\n"} +{"id": 20, "output": "4 65 2 -31 0 99 2 83 782 1 -31 0 1 2 2 4 65 83 99 782\n", "Python": "def shell(seq):\n inc = len(seq) // 2\n while inc:\n for i, el in enumerate(seq[inc:], inc):\n while i >= inc and seq[i - inc] > el:\n seq[i] = seq[i - inc]\n i -= inc\n seq[i] = el\n inc = 1 if inc == 2 else inc * 5 // 11\n", "C": "#include \n\nvoid shell_sort (int *a, int n) {\n int h, i, j, t;\n for (h = n; h /= 2;) {\n for (i = h; i < n; i++) {\n t = a[i];\n for (j = i; j >= h && t < a[j - h]; j -= h) {\n a[j] = a[j - h];\n }\n a[j] = t;\n }\n }\n}\n\nint main (int ac, char **av) {\n int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n int n = sizeof a / sizeof a[0];\n int i;\n for (i = 0; i < n; i++)\n printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n shell_sort(a, n);\n for (i = 0; i < n; i++)\n printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n return 0;\n}\n"} +{"id": 21, "output": "BSD next 10 Random 987750813 612308498 1723994595 1520891872 266205849 255099230 1702488383 1068741132 554346325 1363367274 MS next 10 Random 30410 17352 21710 14780 17138 32592 16950 4484 23450 21848\n", "Python": "def bsd_rand(seed):\n def rand():\n rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff\n return rand.seed\n rand.seed = seed\n return rand\n\ndef msvcrt_rand(seed):\n def rand():\n rand.seed = (214013*rand.seed + 2531011) & 0x7fffffff\n return rand.seed >> 16\n rand.seed = seed\n return rand\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nnamespace LinearCongruentialGenerator\n{\n static class LinearCongruentialGenerator\n {\n static int _seed = (int)DateTime.Now.Ticks; // from bad random gens might as well have bad seed!\n static int _bsdCurrent = _seed;\n static int _msvcrtCurrent = _seed;\n\n static int Next(int seed, int a, int b) => (a * seed + b) & int.MaxValue;\n\n static int BsdRand() => _bsdCurrent = Next(_bsdCurrent, 1103515245, 12345); \n\n static int MscvrtRand() => _msvcrtCurrent = Next (_msvcrtCurrent << 16,214013,2531011) >> 16;\n\n static void PrintRandom(int count, bool isBsd)\n {\n var name = isBsd ? \"BSD\" : \"MS\";\n WriteLine($\"{name} next {count} Random\");\n var gen = isBsd ? (Func)(BsdRand) : MscvrtRand;\n foreach (var r in Enumerable.Repeat(gen, count))\n WriteLine(r.Invoke());\n }\n\n static void Main(string[] args)\n {\n PrintRandom(10, true);\n PrintRandom(10, false);\n Read();\n }\n }\n}\n"} +{"id": 22, "output": "parent = root, x = 320, y = 240, text = First parent = root, x = 0, y = 0, text = Origin parent = root, x = 500, y = 0, text = Default parent = root, x = 0, y = 400, text = Footer \n", "Python": "def subtract(x, y):\n return x - y\n\nsubtract(5, 3) # used as positional parameters; evaluates to 2\nsubtract(y = 3, x = 5) # used as named parameters; evaluates to 2\n", "C#": "using System;\n\nnamespace NamedParams\n{\n class Program\n {\n static void AddWidget(string parent, float x = 0, float y = 0, string text = \"Default\")\n {\n Console.WriteLine(\"parent = {0}, x = {1}, y = {2}, text = {3}\", parent, x, y, text);\n }\n\n static void Main(string[] args)\n {\n AddWidget(\"root\", 320, 240, \"First\");\n AddWidget(\"root\", text: \"Origin\");\n AddWidget(\"root\", 500);\n AddWidget(\"root\", text: \"Footer\", y: 400);\n }\n }\n}\n"} +{"id": 23, "output": "working... Sort the letters of string in alphabitical order: Input: forever ring programming language Output: aaaeeefgggggiilmmnnnooprrrrruv done...\n", "Python": "'''Sorted string'''\n\nfrom functools import reduce\n\n\n# qSort :: [a] -> [a]\ndef qSort(xs):\n '''Sorted elements of the list xs, where the values\n of xs are assumed to be of some orderable type.\n '''\n if xs:\n h = xs[0]\n below, above = partition(\n lambda v: v <= h\n )(xs[1:])\n\n return qSort(below) + [h] + qSort(above)\n else:\n return []\n\n\n# ------------------------- TEST -------------------------\ndef main():\n '''A character-sorted version of a test string\n '''\n print(quoted('\"')(\n ''.join(qSort(list(\n \"Is this misspelling of alphabetical as alphabitical a joke ?\"\n )))\n ))\n\n\n# ----------------------- GENERIC ------------------------\n\n# partition :: (a -> Bool) -> [a] -> ([a], [a])\ndef partition(p):\n '''The pair of lists of those elements in xs\n which respectively do, and don't\n satisfy the predicate p.\n '''\n def go(a, x):\n ts, fs = a\n return (ts + [x], fs) if p(x) else (ts, fs + [x])\n return lambda xs: reduce(go, xs, ([], []))\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "C#": "using System; using static System.Console;\nclass Program {\n static void Main(string[] args) {\n var nl = \"\\n\";\n var omit_spaces = true;\n var str = \"forever ring programming language\";\n Write( \"working...\" + nl );\n Write( \"Sort the letters of string in alphabitical order:\" + nl );\n Write( \"Input: \" + str + nl );\n Write( \"Output: \" );\n for (var ch = omit_spaces ? 33 : 0; ch < 256; ch++)\n foreach (var itm in str)\n if (ch == itm) Console.Write(itm);\n Write( nl + \"done...\" );\n }\n}\n"} +{"id": 24, "output": "0.9054054 → 67 / 74 0.518518 → 14 / 27 0.75 → 3 / 4 0.4285714 → 3 / 7 0.833333 → 5 / 6 0.90909 → 10 / 11 3.14159265358979 → 104348 / 33215 2.71828182845905 → 49171 / 18089\n", "Python": ">>> from fractions import Fraction\n>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))\n\n0.9054054 67/74\n0.518518 14/27\n0.75 3/4\n>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))\n\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n>>>\n", "C#": "using System;\nusing System.Text;\n\nnamespace RosettaDecimalToFraction\n{\n public class Fraction\n {\n public Int64 Numerator;\n public Int64 Denominator;\n public Fraction(double f, Int64 MaximumDenominator = 4096)\n {\n /* Translated from the C version. */\n /* a: continued fraction coefficients. */\n Int64 a;\n var h = new Int64[3] { 0, 1, 0 };\n var k = new Int64[3] { 1, 0, 0 };\n Int64 x, d, n = 1;\n int i, neg = 0;\n\n if (MaximumDenominator <= 1)\n {\n Denominator = 1;\n Numerator = (Int64)f;\n return;\n }\n\n if (f < 0) { neg = 1; f = -f; }\n\n while (f != Math.Floor(f)) { n <<= 1; f *= 2; }\n d = (Int64)f;\n\n /* continued fraction and check denominator each step */\n for (i = 0; i < 64; i++)\n {\n a = (n != 0) ? d / n : 0;\n if ((i != 0) && (a == 0)) break;\n\n x = d; d = n; n = x % n;\n\n x = a;\n if (k[1] * a + k[0] >= MaximumDenominator)\n {\n x = (MaximumDenominator - k[0]) / k[1];\n if (x * 2 >= a || k[1] >= MaximumDenominator)\n i = 65;\n else\n break;\n }\n\n h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2];\n k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2];\n }\n Denominator = k[1];\n Numerator = neg != 0 ? -h[1] : h[1];\n }\n public override string ToString()\n {\n return string.Format(\"{0} / {1}\", Numerator, Denominator);\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n Console.OutputEncoding = UTF8Encoding.UTF8;\n foreach (double d in new double[] { 0.9054054, 0.518518, 0.75, 0.4285714, 0.833333,\n 0.90909, 3.14159265358979, 2.7182818284590451 })\n {\n var f = new Fraction(d, d >= 2 ? 65536 : 4096);\n Console.WriteLine(\"{0,20} → {1}\", d, f);\n\n }\n }\n }\n}\n"} +{"id": 25, "output": "Maximum from 2^1 to 2^2 is 0.666666666666667 at 3 Maximum from 2^2 to 2^3 is 0.666666666666667 at 6 Maximum from 2^3 to 2^4 is 0.636363636363636 at 11 Maximum from 2^4 to 2^5 is 0.608695652173913 at 23 Maximum from 2^5 to 2^6 is 0.590909090909091 at 44 Maximum from 2^6 to 2^7 is 0.576086956521739 at 92 Maximum from 2^7 to 2^8 is 0.567415730337079 at 178 Maximum from 2^8 to 2^9 is 0.559459459459459 at 370 Maximum from 2^9 to 2^10 is 0.554937413073713 at 719 Maximum from 2^10 to 2^11 is 0.550100874243443 at 1487 Maximum from 2^11 to 2^12 is 0.547462892647566 at 2897 Maximum from 2^12 to 2^13 is 0.544144747863964 at 5969 Maximum from 2^13 to 2^14 is 0.542442708780362 at 11651 Maximum from 2^14 to 2^15 is 0.540071097511587 at 22223 Maximum from 2^15 to 2^16 is 0.538784020584256 at 45083 Maximum from 2^16 to 2^17 is 0.537043656999866 at 89516 Maximum from 2^17 to 2^18 is 0.536020067811561 at 181385 Maximum from 2^18 to 2^19 is 0.534645431078112 at 353683 Maximum from 2^19 to 2^20 is 0.533779229963368 at 722589 The winning number is 1489. \n", "Python": "from __future__ import division\n\ndef maxandmallows(nmaxpower2):\n nmax = 2**nmaxpower2\n mx = (0.5, 2)\n mxpow2 = []\n mallows = None\n\n # Hofstadter-Conway sequence starts at hc[1],\n # hc[0] is not part of the series.\n hc = [None, 1, 1]\n\n for n in range(2, nmax + 1):\n ratio = hc[n] / n\n if ratio > mx[0]:\n mx = (ratio, n)\n if ratio >= 0.55:\n mallows = n\n if ratio == 0.5:\n print(\"In the region %7i < n <= %7i: max a(n)/n = %6.4f at n = %i\" %\n\t\t (n//2, n, mx[0], mx[1]))\n mxpow2.append(mx[0])\n mx = (ratio, n)\n hc.append(hc[hc[n]] + hc[-hc[n]])\n\n return hc, mallows if mxpow2 and mxpow2[-1] < 0.55 and n > 4 else None\n\nif __name__ == '__main__':\n hc, mallows = maxandmallows(20)\n if mallows:\n print(\"\\nYou too might have won $1000 with the mallows number of %i\" % mallows)\n", "C#": "using System;\nusing System.Linq;\n\nnamespace HofstadterConway\n{\n class Program\n {\n static int[] GenHofstadterConway(int max)\n {\n int[] result = new int[max];\n result[0]=result[1]=1;\n for (int ix = 2; ix < max; ix++)\n result[ix] = result[result[ix - 1] - 1] + result[ix - result[ix - 1]];\n return result;\n }\n\n static void Main(string[] args)\n {\n double[] adiv = new double[1 << 20];\n {\n int[] a = GenHofstadterConway(1 << 20);\n for (int i = 0; i < 1 << 20; i++)\n adiv[i] = a[i] / (double)(i + 1);\n }\n for (int p = 2; p <= 20; p++)\n {\n var max = Enumerable.Range(\n (1 << (p - 1)) - 1,\n (1 << p) - (1 << (p - 1))\n )\n .Select(ix => new { I = ix + 1, A = adiv[ix] })\n .OrderByDescending(x => x.A)\n .First();\n Console.WriteLine(\"Maximum from 2^{0} to 2^{1} is {2} at {3}\",\n p - 1, p, max.A, max.I);\n }\n Console.WriteLine(\"The winning number is {0}.\",\n Enumerable.Range(0, 1 << 20)\n .Last(i => (adiv[i] > 0.55)) + 1\n );\n }\n }\n}\n"} +{"id": 26, "output": "3 6\n", "Python": "def eqindex2Pass(data):\n \"Two pass\"\n suml, sumr, ddelayed = 0, sum(data), 0\n for i, d in enumerate(data):\n suml += ddelayed\n sumr -= d\n ddelayed = d\n if suml == sumr:\n yield i\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n static IEnumerable EquilibriumIndices(IEnumerable sequence)\n {\n var left = 0;\n var right = sequence.Sum();\n var index = 0;\n foreach (var element in sequence)\n {\n right -= element;\n if (left == right)\n {\n yield return index;\n }\n left += element;\n index++;\n }\n }\n\n static void Main()\n {\n foreach (var index in EquilibriumIndices(new[] { -7, 1, 5, 2, -4, 3, 0 }))\n {\n Console.WriteLine(index);\n }\n }\n}\n"} +{"id": 27, "output": "3, 4, 5 5, 12, 13 6, 8, 10 8, 15, 17 9, 12, 15 12, 16, 20\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", "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": 28, "output": "chowla(1) = 0 chowla(2) = 0 chowla(3) = 0 chowla(4) = 2 chowla(5) = 0 chowla(6) = 5 chowla(7) = 0 chowla(8) = 6 chowla(9) = 3 chowla(10) = 7 chowla(11) = 0 chowla(12) = 15 chowla(13) = 0 chowla(14) = 9 chowla(15) = 8 chowla(16) = 14 chowla(17) = 0 chowla(18) = 20 chowla(19) = 0 chowla(20) = 21 chowla(21) = 10 chowla(22) = 13 chowla(23) = 0 chowla(24) = 35 chowla(25) = 5 chowla(26) = 15 chowla(27) = 12 chowla(28) = 27 chowla(29) = 0 chowla(30) = 41 chowla(31) = 0 chowla(32) = 30 chowla(33) = 14 chowla(34) = 19 chowla(35) = 12 chowla(36) = 54 chowla(37) = 0 Count of primes up to 100 = 25 Count of primes up to 1,000 = 168 Count of primes up to 10,000 = 1,229 Count of primes up to 100,000 = 9,592 Count of primes up to 1,000,000 = 78,498 Count of primes up to 10,000,000 = 664,579 6 is a number that is perfect 28 is a number that is perfect 496 is a number that is perfect 8,128 is a number that is perfect 33,550,336 is a number that is perfect There are 5 perfect numbers <= 35,000,000\n", "Python": "# https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors\nfrom sympy import divisors\n\ndef chowla(n):\n return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n\n\ndef is_prime(n):\n return chowla(n) == 0\n\ndef primes_to(n):\n return sum(chowla(i) == 0 for i in range(2, n))\n\ndef perfect_between(n, m):\n c = 0\n print(f\"\\nPerfect numbers between [{n:_}, {m:_})\")\n for i in range(n, m):\n if i > 1 and chowla(i) == i - 1:\n print(f\" {i:_}\")\n c += 1\n print(f\"Found {c} Perfect numbers between [{n:_}, {m:_})\")\n \n\nif __name__ == '__main__':\n for i in range(1, 38):\n print(f\"chowla({i:2}) == {chowla(i)}\")\n for i in range(2, 6):\n print(f\"primes_to({10**i:_}) == {primes_to(10**i):_}\")\n perfect_between(1, 1_000_000)\n print()\n for i in range(6, 8):\n print(f\"primes_to({10**i:_}) == {primes_to(10**i):_}\")\n perfect_between(1_000_000, 35_000_000)\n", "C#": "using System;\n\nnamespace chowla_cs\n{\n class Program\n {\n static int chowla(int n)\n {\n int sum = 0;\n for (int i = 2, j; i * i <= n; i++)\n if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);\n return sum;\n }\n\n static bool[] sieve(int limit)\n {\n // True denotes composite, false denotes prime.\n // Only interested in odd numbers >= 3\n bool[] c = new bool[limit];\n for (int i = 3; i * 3 < limit; i += 2)\n if (!c[i] && (chowla(i) == 0))\n for (int j = 3 * i; j < limit; j += 2 * i)\n c[j] = true;\n return c;\n }\n\n static void Main(string[] args)\n {\n for (int i = 1; i <= 37; i++)\n Console.WriteLine(\"chowla({0}) = {1}\", i, chowla(i));\n int count = 1, limit = (int)(1e7), power = 100;\n bool[] c = sieve(limit);\n for (int i = 3; i < limit; i += 2)\n {\n if (!c[i]) count++;\n if (i == power - 1)\n {\n Console.WriteLine(\"Count of primes up to {0,10:n0} = {1:n0}\", power, count);\n power *= 10;\n }\n }\n\n count = 0; limit = 35000000;\n int k = 2, kk = 3, p;\n for (int i = 2; ; i++)\n {\n if ((p = k * kk) > limit) break;\n if (chowla(p) == p - 1)\n {\n Console.WriteLine(\"{0,10:n0} is a number that is perfect\", p);\n count++;\n }\n k = kk + 1; kk += k;\n }\n Console.WriteLine(\"There are {0} perfect numbers <= 35,000,000\", count);\n if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();\n }\n }\n}\n"} +{"id": 29, "output": "25 Dec 2011 25 Dec 2016 25 Dec 2022 25 Dec 2033 25 Dec 2039 25 Dec 2044 25 Dec 2050 25 Dec 2061 25 Dec 2067 25 Dec 2072 25 Dec 2078 25 Dec 2089 25 Dec 2095 25 Dec 2101 25 Dec 2107 25 Dec 2112 25 Dec 2118\n", "Python": "from calendar import weekday, SUNDAY\n\n[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]\n", "C#": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 2008; i <= 2121; i++)\n {\n DateTime date = new DateTime(i, 12, 25);\n if (date.DayOfWeek == DayOfWeek.Sunday)\n {\n Console.WriteLine(date.ToString(\"dd MMM yyyy\"));\n }\n }\n }\n}\n"} +{"id": 30, "output": "k = 1: 2 3 5 7 11 13 17 19 23 29 k = 2: 4 6 9 10 14 15 21 22 25 26 k = 3: 8 12 18 20 27 28 30 42 44 45 k = 4: 16 24 36 40 54 56 60 81 84 88 k = 5: 32 48 72 80 108 112 120 162 168 176 \n", "Python": "from prime_decomposition import decompose\nfrom itertools import islice, count\ntry: \n from functools import reduce\nexcept: \n pass\n\n\ndef almostprime(n, k=2):\n d = decompose(n)\n try:\n terms = [next(d) for i in range(k)]\n return reduce(int.__mul__, terms, 1) == n\n except:\n return False\n\nif __name__ == '__main__':\n for k in range(1,6):\n print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace AlmostPrime\n{\n class Program\n {\n static void Main(string[] args)\n {\n foreach (int k in Enumerable.Range(1, 5))\n {\n KPrime kprime = new KPrime() { K = k };\n Console.WriteLine(\"k = {0}: {1}\",\n k, string.Join(\" \", kprime.GetFirstN(10)));\n }\n }\n }\n\n class KPrime\n {\n public int K { get; set; }\n\n public bool IsKPrime(int number)\n {\n int primes = 0;\n for (int p = 2; p * p <= number && primes < K; ++p)\n {\n while (number % p == 0 && primes < K)\n {\n number /= p;\n ++primes;\n }\n }\n if (number > 1)\n {\n ++primes;\n }\n return primes == K;\n }\n\n public List GetFirstN(int n)\n {\n List result = new List();\n for (int number = 2; result.Count < n; ++number)\n {\n if (IsKPrime(number))\n {\n result.Add(number);\n }\n }\n return result;\n }\n }\n}\n"} +{"id": 31, "output": "3rd root of 8 = 2 3rd root of 9 = 2 2nd root of 2000000000000000000 = 1414213562\n", "Python": "def root(a, b):\n if b < 2:\n return b\n a1 = a - 1\n c = 1\n d = (a1 * c + b // (c ** a1)) // a\n e = (a1 * d + b // (d ** a1)) // a\n while c not in (d, e):\n c, d, e = d, e, (a1 * e + b // (e ** a1)) // a\n return min(d, e)\n\n\nprint(\"First 2,001 digits of the square root of two:\\n{}\".format(\n root(2, 2 * 100 ** 2000)\n))\n", "C++": "#include \n#include \n\nunsigned long long root(unsigned long long base, unsigned int n) {\n\tif (base < 2) return base;\n\tif (n == 0) return 1;\n\n\tunsigned int n1 = n - 1;\n\tunsigned long long n2 = n;\n\tunsigned long long n3 = n1;\n\tunsigned long long c = 1;\n\tauto d = (n3 + base) / n2;\n\tauto e = (n3 * d + base / pow(d, n1)) / n2;\n\n\twhile (c != d && c != e) {\n\t\tc = d;\n\t\td = e;\n\t\te = (n3*e + base / pow(e, n1)) / n2;\n\t}\n\n\tif (d < e) return d;\n\treturn e;\n}\n\nint main() {\n\tusing namespace std;\n\n\tcout << \"3rd root of 8 = \" << root(8, 3) << endl;\n\tcout << \"3rd root of 9 = \" << root(9, 3) << endl;\n\n\tunsigned long long b = 2e18;\n\tcout << \"2nd root of \" << b << \" = \" << root(b, 2) << endl;\n\n\treturn 0;\n}\n"} +{"id": 32, "output": "Input : C++ Programming Language Output : C++ Prgrmmng Lngg\n", "Python": "'''Remove a defined subset of glyphs from a string'''\n\n\n# exceptGlyphs :: String -> String -> String\ndef exceptGlyphs(exclusions):\n '''A string from which all instances of a\n given set of glyphs have been removed.\n '''\n def go(s):\n return ''.join(\n c for c in s if c not in exclusions\n )\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n txt = '''\n Rosetta Code is a programming chrestomathy site. \n The idea is to present solutions to the same \n task in as many different languages as possible, \n to demonstrate how languages are similar and \n different, and to aid a person with a grounding \n in one approach to a problem in learning another.'''\n\n print(\n exceptGlyphs('eau')(txt)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "C++": "#include \n#include \n\nclass print_no_vowels {\nprivate:\n const std::string &str;\npublic:\n print_no_vowels(const std::string &s) : str(s) {}\n friend std::ostream &operator<<(std::ostream &, print_no_vowels);\n};\n\nstd::ostream &operator<<(std::ostream &os, print_no_vowels pnv) {\n auto it = pnv.str.cbegin();\n auto end = pnv.str.cend();\n std::for_each(\n it, end,\n [&os](char c) {\n switch (c) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n case 'a':\n case 'e':\n case 'i':\n case 'o':\n case 'u':\n break;\n default:\n os << c;\n break;\n }\n }\n );\n return os;\n}\n\nvoid test(const std::string &s) {\n std::cout << \"Input  : \" << s << '\\n';\n std::cout << \"Output : \" << print_no_vowels(s) << '\\n';\n}\n\nint main() {\n test(\"C++ Programming Language\");\n return 0;\n}\n"} +{"id": 33, "output": "a[0] = 11 a[1] = 12 a[2] = 13 a[3] = 21 a[4] = 22 a[5] = 23 a[6] = 24 \n", "Python": "arr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "C++": "#include \n#include \n\nint main()\n{\n std::vector a(3), b(4);\n a[0] = 11; a[1] = 12; a[2] = 13;\n b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n a.insert(a.end(), b.begin(), b.end());\n\n for (int i = 0; i < a.size(); ++i)\n std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n"} +{"id": 34, "output": "5.18738 5.18738\n", "Python": "class Ref(object):\n def __init__(self, value=None):\n self.value = value\n\ndef harmonic_sum(i, lo, hi, term):\n # term is passed by-name, and so is i\n temp = 0\n i.value = lo\n while i.value <= hi: # Python \"for\" loop creates a distinct which\n temp += term() # would not be shared with the passed \"i\"\n i.value += 1 # Here the actual passed \"i\" is incremented.\n return temp\n\ni = Ref()\n\n# note the correspondence between the mathematical notation and the\n# call to sum it's almost as good as sum(1/i for i in range(1,101))\nprint harmonic_sum(i, 1, 100, lambda: 1.0/i.value)\n", "C++": "#include \n\n#define SUM(i,lo,hi,term)\\\n[&](const int _lo,const int _hi){\\\n decltype(+(term)) sum{};\\\n for (i = _lo; i <= _hi; ++i) sum += (term);\\\n return sum;\\\n}((lo),(hi))\n\nint i;\ndouble sum(int &i, int lo, int hi, double (*term)()) {\n double temp = 0;\n for (i = lo; i <= hi; i++)\n temp += term();\n return temp;\n}\ndouble term_func() { return 1.0 / i; }\n\nint main () {\n std::cout << sum(i, 1, 100, term_func) << std::endl;\n std::cout << SUM(i,1,100,1.0/i) << \"\\n\";\n return 0;\n}\n"} +{"id": 35, "output": "1: 0/1 1/1 2: 0/1 1/2 1/1 3: 0/1 1/3 1/2 2/3 1/1 4: 0/1 1/4 1/3 1/2 2/3 3/4 1/1 5: 0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1 6: 0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 5/6 1/1 7: 0/1 1/7 1/6 1/5 1/4 2/7 1/3 2/5 3/7 1/2 4/7 3/5 2/3 5/7 3/4 4/5 5/6 6/7 1/1 8: 0/1 1/8 1/7 1/6 1/5 1/4 2/7 1/3 3/8 2/5 3/7 1/2 4/7 3/5 5/8 2/3 5/7 3/4 4/5 5/6 6/7 7/8 1/1 9: 0/1 1/9 1/8 1/7 1/6 1/5 2/9 1/4 2/7 1/3 3/8 2/5 3/7 4/9 1/2 5/9 4/7 3/5 5/8 2/3 5/7 3/4 7/9 4/5 5/6 6/7 7/8 8/9 1/1 10: 0/1 1/10 1/9 1/8 1/7 1/6 1/5 2/9 1/4 2/7 3/10 1/3 3/8 2/5 3/7 4/9 1/2 5/9 4/7 3/5 5/8 2/3 7/10 5/7 3/4 7/9 4/5 5/6 6/7 7/8 8/9 9/10 1/1 11: 0/1 1/11 1/10 1/9 1/8 1/7 1/6 2/11 1/5 2/9 1/4 3/11 2/7 3/10 1/3 4/11 3/8 2/5 3/7 4/9 5/11 1/2 6/11 5/9 4/7 3/5 5/8 7/11 2/3 7/10 5/7 8/11 3/4 7/9 4/5 9/11 5/6 6/7 7/8 8/9 9/10 10/11 1/1 100: 3045 200: 12233 300: 27399 400: 48679 500: 76117 600: 109501 700: 149019 800: 194751 900: 246327 1000: 304193\n", "Python": "from fractions import Fraction\n\n\nclass Fr(Fraction):\n def __repr__(self):\n return '(%s/%s)' % (self.numerator, self.denominator)\n\n\ndef farey(n, length=False):\n if not length:\n return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n else:\n #return 1 + len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n return (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))\n \nif __name__ == '__main__':\n print('Farey sequence for order 1 through 11 (inclusive):')\n for n in range(1, 12): \n print(farey(n))\n print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')\n print([farey(i, length=True) for i in range(100, 1001, 100)])\n", "C++": "#include \n\nstruct fraction {\n fraction(int n, int d) : numerator(n), denominator(d) {}\n int numerator;\n int denominator;\n};\n\nstd::ostream& operator<<(std::ostream& out, const fraction& f) {\n out << f.numerator << '/' << f.denominator;\n return out;\n}\n\nclass farey_sequence {\npublic:\n explicit farey_sequence(int n) : n_(n), a_(0), b_(1), c_(1), d_(n) {}\n fraction next() {\n // See https://en.wikipedia.org/wiki/Farey_sequence#Next_term\n fraction result(a_, b_);\n int k = (n_ + b_)/d_;\n int next_c = k * c_ - a_;\n int next_d = k * d_ - b_;\n a_ = c_;\n b_ = d_;\n c_ = next_c;\n d_ = next_d;\n return result;\n }\n bool has_next() const { return a_ <= n_; }\nprivate:\n int n_, a_, b_, c_, d_;\n};\n\nint main() {\n for (int n = 1; n <= 11; ++n) {\n farey_sequence seq(n);\n std::cout << n << \": \" << seq.next();\n while (seq.has_next())\n std::cout << ' ' << seq.next();\n std::cout << '\\n';\n }\n for (int n = 100; n <= 1000; n += 100) {\n int count = 0;\n for (farey_sequence seq(n); seq.has_next(); seq.next())\n ++count;\n std::cout << n << \": \" << count << '\\n';\n }\n return 0;\n}\n"} +{"id": 36, "output": "sum = 348173 prod = -793618560\n", "Python": "from itertools import chain\n\nprod, sum_, x, y, z, one,three,seven = 1, 0, 5, -5, -2, 1, 3, 7\n\ndef _range(x, y, z=1):\n return range(x, y + (1 if z > 0 else -1), z)\n\nprint(f'list(_range(x, y, z)) = {list(_range(x, y, z))}')\nprint(f'list(_range(-seven, seven, x)) = {list(_range(-seven, seven, x))}')\n\nfor j in chain(_range(-three, 3**3, three), _range(-seven, seven, x), \n _range(555, 550 - y), _range(22, -28, -three),\n _range(1927, 1939), _range(x, y, z),\n _range(11**x, 11**x + 1)):\n sum_ += abs(j)\n if abs(prod) < 2**27 and (j != 0):\n prod *= j\nprint(f' sum= {sum_}\\nprod= {prod}')\n", "C++": "#include \n#include \n#include \n\nusing std::abs;\nusing std::cout;\nusing std::pow;\nusing std::vector;\n\n\nint main()\n{\n int prod = 1,\n sum = 0,\n x = 5,\n y = -5,\n z = -2,\n one = 1,\n three = 3,\n seven = 7;\n\n auto summingValues = vector{};\n\n for(int n = -three; n <= pow(3, 3); n += three)\n summingValues.push_back(n);\n for(int n = -seven; n <= seven; n += x)\n summingValues.push_back(n);\n for(int n = 555; n <= 550 - y; ++n)\n summingValues.push_back(n);\n for(int n = 22; n >= -28; n -= three)\n summingValues.push_back(n);\n for(int n = 1927; n <= 1939; ++n)\n summingValues.push_back(n);\n for(int n = x; n >= y; n += z)\n summingValues.push_back(n);\n for(int n = pow(11, x); n <= pow(11, x) + one; ++n)\n summingValues.push_back(n);\n\n for(auto j : summingValues)\n {\n sum += abs(j);\n if(abs(prod) < pow(2, 27) && j != 0)\n prod *= j;\n }\n\n cout << \"sum = \" << sum << \"\\n\";\n cout << \"prod = \" << prod << \"\\n\";\n}\n"} +{"id": 37, "output": "3 0\n", "Python": "def countJewels(s, j):\n return sum(x in j for x in s)\n\nprint countJewels(\"aAAbbbb\", \"aA\")\nprint countJewels(\"ZZ\", \"z\")\n", "C++": "#include \n#include \n\nint countJewels(const std::string& s, const std::string& j) {\n int count = 0;\n for (char c : s) {\n if (j.find(c) != std::string::npos) {\n count++;\n }\n }\n return count;\n}\n\nint main() {\n using namespace std;\n\n cout << countJewels(\"aAAbbbb\", \"aA\") << endl;\n cout << countJewels(\"ZZ\", \"z\") << endl;\n\n return 0;\n}\n"} +{"id": 38, "output": "-199 -52 2 3 33 56 99 100 177 200\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", "C++": "#include \n#include \n#include \n\ntemplate 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(std::cout, \" \"));\n std::cout << \"\\n\";\n}\n"} +{"id": 39, "output": "0 ^ 0 = 1 0+0i ^ 0+0i = (nan,nan)\n", "Python": "from decimal import Decimal\nfrom fractions import Fraction\nfrom itertools import product\n\nzeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]\nfor i, j in product(zeroes, repeat=2):\n try:\n ans = i**j\n except:\n ans = ''\n print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')\n", "C++": "#include \n#include \n#include \n\nint main()\n{\n std::cout << \"0 ^ 0 = \" << std::pow(0,0) << std::endl;\n std::cout << \"0+0i ^ 0+0i = \" <<\n std::pow(std::complex(0),std::complex(0)) << std::endl;\n return 0;\n}\n"} +{"id": 40, "output": "242\n", "Python": "def changes(amount, coins):\n ways = [0] * (amount + 1)\n ways[0] = 1\n for coin in coins:\n for j in xrange(coin, amount + 1):\n ways[j] += ways[j - coin]\n return ways[amount]\n\nprint changes(100, [1, 5, 10, 25])\nprint changes(100000, [1, 5, 10, 25, 50, 100])\n", "C++": "#include \n#include \n#include \n\nstruct DataFrame {\n int sum;\n std::vector coins;\n std::vector avail_coins;\n};\n\nint main() {\n std::stack s;\n s.push({ 100, {}, { 25, 10, 5, 1 } });\n int ways = 0;\n while (!s.empty()) {\n DataFrame top = s.top();\n s.pop();\n if (top.sum < 0) continue;\n if (top.sum == 0) {\n ++ways;\n continue;\n }\n if (top.avail_coins.empty()) continue;\n DataFrame d = top;\n d.sum -= top.avail_coins[0];\n d.coins.push_back(top.avail_coins[0]);\n s.push(d);\n d = top;\n d.avail_coins.erase(std::begin(d.avail_coins));\n s.push(d);\n }\n std::cout << ways << std::endl;\n return 0;\n}\n"} +{"id": 41, "output": "AErBcadCbFD\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", "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": 42, "output": "pisanoPrime( 2: 2) = 6 pisanoPrime( 3: 2) = 24 pisanoPrime( 5: 2) = 100 pisanoPrime( 7: 2) = 112 pisanoPrime(11: 2) = 110 pisanoPrime(13: 2) = 364 pisanoPrime( 2: 1) = 3 pisanoPrime( 3: 1) = 8 pisanoPrime( 5: 1) = 20 pisanoPrime( 7: 1) = 16 pisanoPrime( 11: 1) = 10 pisanoPrime( 13: 1) = 28 pisanoPrime( 17: 1) = 36 pisanoPrime( 19: 1) = 18 pisanoPrime( 23: 1) = 48 pisanoPrime( 29: 1) = 14 pisanoPrime( 31: 1) = 30 pisanoPrime( 37: 1) = 76 pisanoPrime( 41: 1) = 40 pisanoPrime( 43: 1) = 88 pisanoPrime( 47: 1) = 32 pisanoPrime( 53: 1) = 108 pisanoPrime( 59: 1) = 58 pisanoPrime( 61: 1) = 60 pisanoPrime( 67: 1) = 136 pisanoPrime( 71: 1) = 70 pisanoPrime( 73: 1) = 148 pisanoPrime( 79: 1) = 78 pisanoPrime( 83: 1) = 168 pisanoPrime( 89: 1) = 44 pisanoPrime( 97: 1) = 196 pisanoPrime(101: 1) = 50 pisanoPrime(103: 1) = 208 pisanoPrime(107: 1) = 72 pisanoPrime(109: 1) = 108 pisanoPrime(113: 1) = 76 pisanoPrime(127: 1) = 256 pisanoPrime(131: 1) = 130 pisanoPrime(137: 1) = 276 pisanoPrime(139: 1) = 46 pisanoPrime(149: 1) = 148 pisanoPrime(151: 1) = 50 pisanoPrime(157: 1) = 316 pisanoPrime(163: 1) = 328 pisanoPrime(167: 1) = 336 pisanoPrime(173: 1) = 348 pisanoPrime(179: 1) = 178 pisano(n) for integers 'n' from 1 to 180 are: 1 3 8 6 20 24 16 12 24 60 10 24 28 48 40 24 36 24 18 60 16 30 48 24 100 84 72 48 14 120 30 48 40 36 80 24 76 18 56 60 40 48 88 30 120 48 32 24 112 300 72 84 108 72 20 48 72 42 58 120 60 30 48 96 140 120 136 36 48 240 70 24 148 228 200 18 80 168 78 120 216 120 168 48 180 264 56 60 44 120 112 48 120 96 180 48 196 336 120 300 50 72 208 84 80 108 72 72 108 60 152 48 76 72 240 42 168 174 144 120 110 60 40 30 500 48 256 192 88 420 130 120 144 408 360 36 276 48 46 240 32 210 140 24 140 444 112 228 148 600 50 36 72 240 60 168 316 78 216 240 48 216 328 120 40 168 336 48 364 180 72 264 348 168 400 120 232 132 178 120 \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", "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// Gets the prime decomposition of 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// OK for 'small' numbers.\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// Calculates the Pisano period of 'm' from first principles.\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// Calculates the Pisano period of p^k where 'p' is prime and 'k' is a positive integer.\nfunc pisanoPrime(p uint, k uint) uint {\n if !isPrime(p) || k == 0 {\n return 0 // can't do this one\n }\n return ipow(p, k-1) * pisanoPeriod(p)\n}\n\n// Calculates the Pisano period of 'm' using pisanoPrime.\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": 43, "output": "float64: 1 big integer: 1 complex: (1+0i)\n", "Python": "from decimal import Decimal\nfrom fractions import Fraction\nfrom itertools import product\n\nzeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]\nfor i, j in product(zeroes, repeat=2):\n try:\n ans = i**j\n except:\n ans = ''\n print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')\n", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"math/cmplx\"\n)\n\nfunc main() {\n fmt.Println(\"float64: \", math.Pow(0, 0))\n var b big.Int\n fmt.Println(\"big integer:\", b.Exp(&b, &b, nil))\n fmt.Println(\"complex: \", cmplx.Pow(0, 0))\n}\n"} +{"id": 44, "output": "ends with 'string' I am the modified string\n", "Python": "import re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n", "Go": "package main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n str := \"I am the original string\"\n\n // Test\n matched, _ := regexp.MatchString(\".*string$\", str)\n if matched { fmt.Println(\"ends with 'string'\") }\n\n // Substitute\n pattern := regexp.MustCompile(\"original\")\n result := pattern.ReplaceAllString(str, \"modified\")\n fmt.Println(result)\n}\n"} +{"id": 45, "output": "lcp([\"interspecies\" \"interstellar\" \"interstate\"]) = \"inters\" lcp([\"throne\" \"throne\"]) = \"throne\" lcp([\"throne\" \"dungeon\"]) = \"\" lcp([\"throne\" \"\" \"throne\"]) = \"\" lcp([\"cheese\"]) = \"cheese\" lcp([\"\"]) = \"\" lcp([]) = \"\" lcp([\"prefix\" \"suffix\"]) = \"\" lcp([\"foo\" \"foobar\"]) = \"foo\"\n", "Python": "import os.path\n\ndef lcp(*s):\n return os.path.commonprefix(s)\n\nassert lcp(\"interspecies\",\"interstellar\",\"interstate\") == \"inters\"\nassert lcp(\"throne\",\"throne\") == \"throne\"\nassert lcp(\"throne\",\"dungeon\") == \"\"\nassert lcp(\"cheese\") == \"cheese\"\nassert lcp(\"\") == \"\"\nassert lcp(\"prefix\",\"suffix\") == \"\"\nassert lcp(\"foo\",\"foobar\") == \"foo\"\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc lcp(l []string) string {\n\tswitch len(l) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn l[0]\n\t}\n\t// LCP of min and max (lexigraphically)\n\tmin, max := l[0], l[0]\n\tfor _, s := range l[1:] {\n\t\tswitch {\n\t\tcase s < min:\n\t\t\tmin = s\n\t\tcase s > max:\n\t\t\tmax = s\n\t\t}\n\t}\n\tfor i := 0; i < len(min) && i < len(max); i++ {\n\t\tif min[i] != max[i] {\n\t\t\treturn min[:i]\n\t\t}\n\t}\n\t// In the case where lengths are not equal but all bytes\n\t// are equal, min is the answer (\"foo\" < \"foobar\").\n\treturn min\n}\n\n// Normally something like this would be a TestLCP function in *_test.go\n// and use the testing package to report failures.\nfunc main() {\n\tfor _, l := range [][]string{\n\t\t{\"interspecies\", \"interstellar\", \"interstate\"},\n\t\t{\"throne\", \"throne\"},\n\t\t{\"throne\", \"dungeon\"},\n\t\t{\"throne\", \"\", \"throne\"},\n\t\t{\"cheese\"},\n\t\t{\"\"},\n\t\tnil,\n\t\t{\"prefix\", \"suffix\"},\n\t\t{\"foo\", \"foobar\"},\n\t} {\n\t\tfmt.Printf(\"lcp(%q) = %q\\n\", l, lcp(l))\n\t}\n}\n"} +{"id": 46, "output": "Source file entropy: 4.478969245062461 Binary file entropy: 6.4993394594241245\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", "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": 47, "output": "[map compass water sandwich glucose banana suntan cream waterproof trousers waterproof overclothes note-case sunglasses socks] weight: 396 value: 1030\n", "Python": "from itertools import combinations\n\ndef anycomb(items):\n ' return combinations of any length from the items '\n return ( comb\n for r in range(1, len(items)+1)\n for comb in combinations(items, r)\n )\n\ndef totalvalue(comb):\n ' Totalise a particular combination of items'\n totwt = totval = 0\n for item, wt, val in comb:\n totwt += wt\n totval += val\n return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n (\"socks\", 4, 50), (\"book\", 30, 10),\n )\nbagged = max( anycomb(items), key=totalvalue) # max val or min wt if values equal\nprint(\"Bagged the following items\\n \" +\n '\\n '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n", "Go": "package main\n\nimport \"fmt\"\n\ntype item struct {\n string\n w, v int\n}\n\nvar wants = []item{\n {\"map\", 9, 150},\n {\"compass\", 13, 35},\n {\"water\", 153, 200},\n {\"sandwich\", 50, 160},\n {\"glucose\", 15, 60},\n {\"tin\", 68, 45},\n {\"banana\", 27, 60},\n {\"apple\", 39, 40},\n {\"cheese\", 23, 30},\n {\"beer\", 52, 10},\n {\"suntan cream\", 11, 70},\n {\"camera\", 32, 30},\n {\"T-shirt\", 24, 15},\n {\"trousers\", 48, 10},\n {\"umbrella\", 73, 40},\n {\"waterproof trousers\", 42, 70},\n {\"waterproof overclothes\", 43, 75},\n {\"note-case\", 22, 80},\n {\"sunglasses\", 7, 20},\n {\"towel\", 18, 12},\n {\"socks\", 4, 50},\n {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n items, w, v := m(len(wants)-1, maxWt)\n fmt.Println(items)\n fmt.Println(\"weight:\", w)\n fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n if i < 0 || w == 0 {\n return nil, 0, 0\n } else if wants[i].w > w {\n return m(i-1, w)\n }\n i0, w0, v0 := m(i-1, w)\n i1, w1, v1 := m(i-1, w-wants[i].w)\n v1 += wants[i].v\n if v1 > v0 {\n return append(i1, wants[i].string), w1 + wants[i].w, v1\n }\n return i0, w0, v0\n}\n"} +{"id": 48, "output": "{53.53042923188481 99.96848991484791} {53.48871857608132 99.97685948527237} distance: 0.0425420793644058\n", "Python": "\"\"\"\n Compute nearest pair of points using two algorithms\n \n First algorithm is 'brute force' comparison of every possible pair.\n Second, 'divide and conquer', is based on:\n www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt \n\"\"\"\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n# Note the use of complex numbers to represent 2D points making distance == abs(P1-P2)\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 # Points within dm of xDivider sorted by Y coord\n closeY = [p for p in yP if abs(p.real - xDivider) < dm]\n numCloseY = len(closeY)\n if numCloseY > 1:\n # There is a proof that you only need compare a max of 7 next points\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 ''' Time the different functions\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": 49, "output": "Total before tax: 22000000000000005.72 Tax: 1683000000000000.44 Total: 23683000000000006.16\n", "Python": "from decimal import Decimal as D\nfrom collections import namedtuple\n\nItem = namedtuple('Item', 'price, quant')\n\nitems = dict( hamburger=Item(D('5.50'), D('4000000000000000')),\n milkshake=Item(D('2.86'), D('2')) )\ntax_rate = D('0.0765')\n\nfmt = \"%-10s %8s %18s %22s\"\nprint(fmt % tuple('Item Price Quantity Extension'.upper().split()))\n\ntotal_before_tax = 0\nfor item, (price, quant) in sorted(items.items()):\n ext = price * quant\n print(fmt % (item, price, quant, ext))\n total_before_tax += ext\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'subtotal', total_before_tax))\n\ntax = (tax_rate * total_before_tax).quantize(D('0.00'))\nprint(fmt % ('', '', 'Tax', tax))\n\ntotal = total_before_tax + tax\nprint(fmt % ('', '', '', '--------------------'))\nprint(fmt % ('', '', 'Total', total))\n", "Go": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\n// DC for dollars and cents. Value is an integer number of cents.\ntype DC int64\n\nfunc (dc DC) String() string {\n d := dc / 100\n if dc < 0 {\n dc = -dc\n }\n return fmt.Sprintf(\"%d.%02d\", d, dc%100)\n}\n\n// Extend returns extended price of a unit price.\nfunc (dc DC) Extend(n int) DC {\n return dc * DC(n)\n}\n\nvar one = big.NewInt(1)\nvar hundred = big.NewRat(100, 1)\n\n// ParseDC parses dollars and cents as a string into a DC.\nfunc ParseDC(s string) (DC, bool) {\n r, ok := new(big.Rat).SetString(s)\n if !ok {\n return 0, false\n }\n r.Mul(r, hundred)\n if r.Denom().Cmp(one) != 0 {\n return 0, false\n }\n return DC(r.Num().Int64()), true\n}\n\n// TR for tax rate. Value is an an exact rational.\ntype TR struct {\n *big.Rat\n}\nfunc NewTR() TR {\n return TR{new(big.Rat)}\n}\n\n// SetString overrides Rat.SetString to return the TR type.\nfunc (tr TR) SetString(s string) (TR, bool) {\n if _, ok := tr.Rat.SetString(s); !ok {\n return TR{}, false\n }\n return tr, true\n}\n\nvar half = big.NewRat(1, 2)\n\n// Tax computes a tax amount, rounding to the nearest cent.\nfunc (tr TR) Tax(dc DC) DC {\n r := big.NewRat(int64(dc), 1)\n r.Add(r.Mul(r, tr.Rat), half)\n return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())\n}\n\nfunc main() {\n hamburgerPrice, ok := ParseDC(\"5.50\")\n if !ok {\n log.Fatal(\"Invalid hamburger price\")\n }\n milkshakePrice, ok := ParseDC(\"2.86\")\n if !ok {\n log.Fatal(\"Invalid milkshake price\")\n }\n taxRate, ok := NewTR().SetString(\"0.0765\")\n if !ok {\n log.Fatal(\"Invalid tax rate\")\n }\n\n totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +\n milkshakePrice.Extend(2)\n tax := taxRate.Tax(totalBeforeTax)\n total := totalBeforeTax + tax\n\n fmt.Printf(\"Total before tax: %22s\\n\", totalBeforeTax)\n fmt.Printf(\" Tax: %22s\\n\", tax)\n fmt.Printf(\" Total: %22s\\n\", total)\n}\n"} +{"id": 50, "output": "The numbers with indices 1 and 3 sum to 21\n", "Python": "def two_sum(arr, num):\n i = 0\n j = len(arr) - 1\n while i < j:\n if arr[i] + arr[j] == num:\n return (i, j)\n if arr[i] + arr[j] < num:\n i += 1\n else:\n j -= 1\n return None\n\n\nnumbers = [0, 2, 11, 19, 90]\nprint(two_sum(numbers, 21))\nprint(two_sum(numbers, 25))\n", "Go": "package main\n\nimport \"fmt\"\n\nfunc twoSum(a []int, targetSum int) (int, int, bool) {\n len := len(a)\n if len < 2 {\n return 0, 0, false\n }\n for i := 0; i < len - 1; i++ {\n if a[i] <= targetSum {\n for j := i + 1; j < len; j++ {\n sum := a[i] + a[j]\n if sum == targetSum {\n return i, j, true\n }\n if sum > targetSum {\n break\n }\n }\n } else {\n break\n }\n }\n return 0, 0, false\n}\n\nfunc main() {\n a := []int {0, 2, 11, 19, 90}\n targetSum := 21\n p1, p2, ok := twoSum(a, targetSum)\n if (!ok) {\n fmt.Println(\"No two numbers were found whose sum is\", targetSum)\n } else {\n fmt.Println(\"The numbers with indices\", p1, \"and\", p2, \"sum to\", targetSum)\n }\n}\n"} +{"id": 51, "output": "55 3628800\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", "PHP": "\n"} +{"id": 52, "output": "4 3 5 6 4 3 4 3 5 6 4 3 4 3 5 4 3 5 Rosetta Code Is Awesome! Rosetta Code Is Awesome!\n", "Python": "def print_all(*things):\n for x in things:\n print x\n", "PHP": "\n"} +{"id": 53, "output": "#0 StackTraceDemo::inner() called at [/box/script.php:7] #1 StackTraceDemo::middle() called at [/box/script.php:10] #2 StackTraceDemo::outer() called at [/box/script.php:14]\n", "Python": "import traceback\n\ndef f(): return g()\ndef g(): traceback.print_stack()\n\nf()\n", "PHP": "\n"} +{"id": 54, "output": "Mean angle for 1st sample: -1.6148099320579E-15 degrees. Mean angle for 2nd sample: -90 degrees. Mean angle for 3rd sample: 20 degrees.\n", "Python": ">>> from cmath import rect, phase\n>>> from math import radians, degrees\n>>> def mean_angle(deg):\n... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n... \n>>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:\n... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')\n... \nThe mean angle of [350, 10] is: -0.0 degrees\nThe mean angle of [90, 180, 270, 360] is: -90.0 degrees\nThe mean angle of [10, 20, 30] is: 20.0 degrees\n>>>\n", "PHP": " array(350, 10),\n\t'2nd' => array(90, 180, 270, 360),\n\t'3rd' => array(10, 20, 30)\n);\n\nforeach($samples as $key => $sample){\n\techo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL;\n} \n\nfunction meanAngle ($angles){\n\t$y_part = $x_part = 0;\n\t$size = count($angles);\n\tfor ($i = 0; $i < $size; $i++){\n\t\t$x_part += cos(deg2rad($angles[$i]));\n\t\t$y_part += sin(deg2rad($angles[$i]));\n\t}\n\t$x_part /= $size;\n\t$y_part /= $size;\n\treturn rad2deg(atan2($y_part, $x_part));\n}\n?>\n"} +{"id": 55, "output": "Police: 2, Sanitation: 3, Fire: 7 Police: 2, Sanitation: 4, Fire: 6 Police: 2, Sanitation: 6, Fire: 4 Police: 2, Sanitation: 7, Fire: 3 Police: 4, Sanitation: 1, Fire: 7 Police: 4, Sanitation: 2, Fire: 6 Police: 4, Sanitation: 3, Fire: 5 Police: 4, Sanitation: 5, Fire: 3 Police: 4, Sanitation: 6, Fire: 2 Police: 4, Sanitation: 7, Fire: 1 Police: 6, Sanitation: 1, Fire: 5 Police: 6, Sanitation: 2, Fire: 4 Police: 6, Sanitation: 4, Fire: 2 Police: 6, Sanitation: 5, Fire: 1 14 valid combinations found. \n", "Python": "from itertools import permutations\n \ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n \nif __name__ == '__main__':\n solve()\n", "PHP": ">> 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": ">> from math import sqrt\n>>> def sd(x):\n sd.sum += x\n sd.sum2 += x*x\n sd.n += 1.0\n sum, sum2, n = sd.sum, sd.sum2, sd.n\n return sqrt(sum2/n - sum*sum/n/n)\n\n>>> sd.sum = sd.sum2 = sd.n = 0\n>>> for value in (2,4,4,4,5,5,7,9):\n print (value, sd(value))\n\n \n(2, 0.0)\n(4, 1.0)\n(4, 0.94280904158206258)\n(4, 0.8660254037844386)\n(5, 0.97979589711327075)\n(5, 1.0)\n(7, 1.3997084244475311)\n(9, 2.0)\n>>>\n", "PHP": "reset();\n }\n # callable on an instance\n function reset() {\n $this->cnt=0; $this->sumup=0; $this->square=0;\n }\n function add($f) {\n $this->cnt++;\n $this->sumup += $f;\n $this->square += pow($f, 2);\n return $this->calc();\n }\n function calc() {\n if ($this->cnt==0 || $this->sumup==0) {\n return 0;\n } else {\n return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));\n }\n }\n }\n\n# start test, adding test data one by one\n$c = new sdcalc();\nforeach ([2,4,4,4,5,5,7,9] as $v) {\n printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);\n}\n"} +{"id": 58, "output": "var is undefined at first check var is undefined at third check Done\n", "Python": "try: name\nexcept NameError: print \"name is undefined at first check\"\n\n# Create a name, giving it a string value\nname = \"Chocolate\"\n\n# Check to see whether the name is defined now.\ntry: name\nexcept NameError: print \"name is undefined at second check\"\n\ndel name\n\n# Check to see whether it is defined after the explicit removal.\ntry: name\nexcept NameError: print \"name is undefined at third check\"\n\n# Recreate the name, giving it a value of 42\nname = 42\n\n# Check to see whether the name is defined now.\ntry: name\nexcept NameError: print \"name is undefined at fourth check\"\n\nprint \"Done\"\n", "PHP": "\n"} +{"id": 59, "output": "0 15 3 -9 12
(empty)
4
\n", "Python": "def maxsubseq(seq):\n return max((seq[begin:end] for begin in xrange(len(seq)+1)\n for end in xrange(begin, len(seq)+1)),\n key=sum)\n", "PHP": " $max_sum) {\n $max_sum = $sum;\n $max_start = $sum_start;\n $max_len = $i + 1 - $max_start;\n }\n if ($sum < 0) { # start new sequence\n $sum = 0;\n $sum_start = $i + 1;\n }\n }\n return array_slice($sequence, $max_start, $max_len);\n}\n \nfunction print_array($arr) {\n if (count($arr) > 0) {\n echo join(\" \", $arr);\n } else {\n echo \"(empty)\";\n }\n echo '
';\n} \n// tests\nprint_array(max_sum_seq(array(-1, 0, 15, 3, -9, 12, -4)));\nprint_array(max_sum_seq(array(-1)));\nprint_array(max_sum_seq(array(4, -10, 3)));\n?>\n"} +{"id": 60, "output": "+----------+----------+----------+----------+----------+----------+ | 32: Spc | 48: 0 | 64: @ | 80: P | 96: ` | 112: p | | 33: ! | 49: 1 | 65: A | 81: Q | 97: a | 113: q | | 34: \" | 50: 2 | 66: B | 82: R | 98: b | 114: r | | 35: # | 51: 3 | 67: C | 83: S | 99: c | 115: s | | 36: $ | 52: 4 | 68: D | 84: T | 100: d | 116: t | | 37: % | 53: 5 | 69: E | 85: U | 101: e | 117: u | | 38: & | 54: 6 | 70: F | 86: V | 102: f | 118: v | | 39: ' | 55: 7 | 71: G | 87: W | 103: g | 119: w | | 40: ( | 56: 8 | 72: H | 88: X | 104: h | 120: x | | 41: ) | 57: 9 | 73: I | 89: Y | 105: i | 121: y | | 42: * | 58: : | 74: J | 90: Z | 106: j | 122: z | | 43: + | 59: ; | 75: K | 91: [ | 107: k | 123: { | | 44: , | 60: < | 76: L | 92: \\ | 108: l | 124: | | | 45: - | 61: = | 77: M | 93: ] | 109: m | 125: } | | 46: . | 62: > | 78: N | 94: ^ | 110: n | 126: ~ | | 47: / | 63: ? | 79: O | 95: _ | 111: o | 127: Del | +----------+----------+----------+----------+----------+----------+ \n", "Python": "for i in range(16):\n for j in range(32+i, 127+1, 16):\n if j == 32:\n k = 'Spc'\n elif j == 127:\n k = 'Del'\n else:\n k = chr(j)\n print(\"%3d : %-3s\" % (j,k), end=\"\")\n print()\n", "PHP": "= 0 && d < 26)\n if (!isUsed[d])\n {\n isUsed[d] = true;\n total++;\n }\n }\n return (total == 26);\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n string str1 = \"The quick brown fox jumps over the lazy dog.\";\n string str2 = \"The qu1ck brown fox jumps over the lazy d0g.\";\n Console.WriteLine(\"{0} is {1}a pangram\", str1,\n PangrammChecker.IsPangram(str1)?\"\":\"not \");\n Console.WriteLine(\"{0} is {1}a pangram\", str2,\n PangrammChecker.IsPangram(str2)?\"\":\"not \");\n \n }\n }\n}"} +{"id": 1, "output": "Passes Completed!!! Here are the results: \n\nDoor #1: Open\nDoor #2: Closed\nDoor #3: Closed\nDoor #4: Open\nDoor #5: Closed\nDoor #6: Closed\nDoor #7: Closed\nDoor #8: Closed\nDoor #9: Open\nDoor #10: Closed", "Python": "for i in xrange(1, 10):\n root = i ** 0.5\n print \"Door %d:\" % i, 'open' if root == int(root) else 'close'", "C#": "namespace ConsoleApplication1\n{\n using System;\n class Program\n {\n static void Main(string[] args)\n {\n bool[] doors = new bool[100];\n\n //Close all doors to start.\n for (int d = 0; d < 100; d++) doors[d] = false;\n\n //For each pass...\n for (int p = 0; p < 100; p++)//number of passes\n {\n //For each door to toggle...\n for (int d = 0; d < 100; d++)//door number\n {\n if ((d + 1) % (p + 1) == 0)\n {\n doors[d] = !doors[d];\n }\n }\n }\n\n //Output the results.\n Console.WriteLine(\"Passes Completed!!! Here are the results: \\r\\n\");\n for (int d = 0; d < 10; d++)\n {\n if (doors[d])\n {\n Console.WriteLine(String.Format(\"Door #{0}: Open\", d + 1));\n }\n else\n {\n Console.WriteLine(String.Format(\"Door #{0}: Closed\", d + 1));\n }\n }\n Console.ReadKey(true);\n }\n }\n}"} +{"id": 2, "output": "10001 104743", "Python": "def 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 prime(n: int) -> int:\n if n == 1:\n return 2\n p = 3\n pn = 1\n while pn < n:\n if isPrime(p):\n pn += 1\n p += 2\n return p-2\n\nif __name__ == '__main__':\n print(prime(10001))", "C#": "using System; using System.Text; // PRIME_numb.cs russian DANILIN\nnamespace p10001 // 1 second 10001 104743 \n{ class Program // rextester.com/ZBEPGE34760\n { static void Main(string[] args)\n { int max=10001; int n=1; int p=1; int f; int j; long s;\n while (n <= max) \n { f=0; j=2; s=Convert.ToInt32(Math.Pow(p,0.5));\n while (f < 1) \n { if (j >= s) \n { f=2; } \n if (p % j == 0) { f=1; }\n j++;\n }\n if (f != 1) { n++; } // Console.WriteLine(\"{0} {1}\", n, p);\n p++;\n }\nConsole.Write(\"{0} {1}\", n-1, p-1);\nConsole.ReadKey(); \n}}}"} +{"id": 3, "output": "5 bottles of beer on the wall, 5 bottles of beer.\nTake one down and pass it around, 4 bottles of beer on the wall.\n\n4 bottles of beer on the wall, 4 bottles of beer.\nTake one down and pass it around, 3 bottles of beer on the wall.\n\n3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n\n2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottles of beer on the wall.\n\n1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.", "Python": "VERSE = '''\\\n{n} bottle{s} of beer on the wall\n{n} bottle{s} of beer\nTake one down, pass it around\n{n_minus_1} bottle{s2} of beer on the wall\n\n'''\n\n\nfor n in range(5, 0, -1):\n if n == 1:\n n_minus_1 = 'No more'\n s = ''\n s2 = 's'\n elif n == 2:\n n_minus_1 = n - 1;\n s = 's'\n s2 = ''\n else:\n n_minus_1 = n - 1;\n s = 's'\n s2 = 's'\n \n \n print(VERSE.format(n=n, s=s, s2=s2, n_minus_1=n_minus_1))", "C#": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 5; i > -1; i--)\n {\n if (i == 0)\n {\n Console.WriteLine(\"No more bottles of beer on the wall, no more bottles of beer.\");\n Console.WriteLine(\"Go to the store and buy some more, 99 bottles of beer on the wall.\");\n break;\n }\n if (i == 1)\n {\n Console.WriteLine(\"1 bottle of beer on the wall, 1 bottle of beer.\");\n Console.WriteLine(\"Take one down and pass it around, no more bottles of beer on the wall.\");\n Console.WriteLine();\n }\n else\n {\n Console.WriteLine(\"{0} bottles of beer on the wall, {0} bottles of beer.\", i);\n Console.WriteLine(\"Take one down and pass it around, {0} bottles of beer on the wall.\", i - 1);\n Console.WriteLine();\n }\n }\n }\n}"} +{"id": 4, "output": "0 maps to -1\n1 maps to -0.9\n2 maps to -0.8\n3 maps to -0.7\n4 maps to -0.6\n5 maps to -0.5\n6 maps to -0.4\n7 maps to -0.3\n8 maps to -0.2\n9 maps to -0.1\n10 maps to 0", "Python": "def maprange( a, b, s):\n\t(a1, a2), (b1, b2) = a, b\n\treturn b1 + ((s - a1) * (b2 - b1) / (a2 - a1))\n\nfor s in range(11):\n\tprint(\"%2g maps to %g\" % (s, maprange( (0, 10), (-1, 0), s)))", "C#": "using System;\nusing System.Linq;\n\npublic class MapRange\n{\n public static void Main() {\n foreach (int i in Enumerable.Range(0, 11))\n Console.WriteLine($\"{i} maps to {Map(0, 10, -1, 0, i)}\");\n }\n \n static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1);\n}"} +{"id": 5, "output": "2\n", "Python": "print(len(['apple', 'orange']))", "C#": "using System;\n\nclass Program\n{\n public static void Main()\n {\n var fruit = new[] { \"apple\", \"orange\" };\n Console.WriteLine(fruit.Length);\n }\n}"} +{"id": 6, "output": "The attractive numbers up to and including 50 are:\n 4 6 8 9 10 12 14 15 18 20 21 22 25 26 27 28 30 32 33 34\n 35 38 39 42 44 45 46 48 49 50\n", "Python": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,51):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,", "C#": "using System;\n\nnamespace AttractiveNumbers {\n class Program {\n const int MAX = 50;\n\n static bool 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 static int PrimeFactorCount(int n) {\n if (n == 1) return 0;\n if (IsPrime(n)) return 1;\n int count = 0;\n int f = 2;\n while (true) {\n if (n % f == 0) {\n count++;\n n /= f;\n if (n == 1) return count;\n if (IsPrime(n)) f = n;\n } else if (f >= 3) {\n f += 2;\n } else {\n f = 3;\n }\n }\n }\n\n static void Main(string[] args) {\n Console.WriteLine(\"The attractive numbers up to and including {0} are:\", MAX);\n int i = 1;\n int count = 0;\n while (i <= MAX) {\n int n = PrimeFactorCount(i);\n if (IsPrime(n)) {\n Console.Write(\"{0,4}\", i);\n if (++count % 20 == 0) Console.WriteLine();\n }\n ++i;\n }\n Console.WriteLine();\n }\n }\n}"} +{"id": 7, "output": "\"\" is balanced.\n\"[]\" is balanced.\n\"[]][\" is not balanced.\n\"[[[]]]\" is balanced.\n\"[]]][[[]\" is not balanced.", "Python": "def gen(N):\n txt = ['[', ']'] * N\n random.shuffle( txt )\n return ''.join(txt)\n\ndef balanced(txt):\n braced = 0\n for ch in txt:\n if ch == '[': braced += 1\n if ch == ']':\n braced -= 1\n if braced < 0: return False\n return braced == 0\n\nfor txt in (gen(N) for N in range(10)):\n print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n static bool IsBalanced(string text, char open = '[', char close = ']')\n {\n var level = 0;\n foreach (var character in text)\n {\n if (character == close)\n {\n if (level == 0)\n {\n return false;\n }\n level--;\n }\n if (character == open)\n {\n level++;\n }\n }\n return level == 0;\n }\n\n static string RandomBrackets(int count, char open = '[', char close = ']')\n {\n var random = new Random();\n return string.Join(string.Empty,\n (new string(open, count) + new string(close, count)).OrderBy(c => random.Next()));\n }\n\n static void Main()\n {\n for (var count = 0; count < 5; count++)\n {\n var text = RandomBrackets(count);\n Console.WriteLine(\"\\\"{0}\\\" is {1}balanced.\", text, IsBalanced(text) ? string.Empty : \"not \");\n }\n }\n}"} +{"id": 8, "output": "e = 2.718281828459050", "Python": "import math\n#Implementation of Brother's formula\ne0 = 0\ne = 2\nn = 0\nfact = 1\nwhile(e-e0 > 1e-15):\n\te0 = e\n\tn += 1\n\tfact *= 2*n*(2*n+1)\n\te += (2.*n+2)/fact\n\nprint \"Computed e = \"+str(e)\nprint \"Real e = \"+str(math.e)\nprint \"Error = \"+str(math.e-e)\nprint \"Number of iterations = \"+str(n)", "C#": "using System;\n\nnamespace CalculateE {\n class Program {\n public const double EPSILON = 1.0e-15;\n\n static void Main(string[] args) {\n ulong fact = 1;\n double e = 2.0;\n double e0;\n uint n = 2;\n do {\n e0 = e;\n fact *= n++;\n e += 1.0 / fact;\n } while (Math.Abs(e - e0) >= EPSILON);\n Console.WriteLine(\"e = {0:F15}\", e);\n }\n }\n}"} +{"id": 9, "output": "1: 1\n2: 2\n3: 3\n4: 2 * 2\n5: 5\n6: 2 * 3\n7: 7\n8: 2 * 2 * 2\n9: 3 * 3\n10: 2 * 5", "Python": "from functools import lru_cache\n\nprimes = [2, 3, 5, 7, 11, 13, 17] # Will be extended\n\n@lru_cache(maxsize=2000)\ndef pfactor(n):\n if n == 1:\n return [1]\n n2 = n // 2 + 1\n for p in primes:\n if p <= n2:\n d, m = divmod(n, p)\n if m == 0:\n if d > 1:\n return [p] + pfactor(d)\n else:\n return [p]\n else:\n if n > primes[-1]:\n primes.append(n)\n return [n]\n \nif __name__ == '__main__':\n mx = 10\n for n in range(1, mx + 1):\n factors = pfactor(n)\n if n <= 10 or n >= mx - 20:\n print( '%4i %5s %s' % (n,\n '' if factors != [n] or n == 1 else 'prime',\n 'x'.join(str(i) for i in factors)) )\n if n == 11:\n print('...')\n \n print('\\nNumber of primes gathered up to', n, 'is', len(primes))\n print(pfactor.cache_info())", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tfor( int i=1; i<=10; i++ )\n\t\t\t{\t\t\t\t\n\t\t\t\tList f = Factorize(i);\n\t\t\t\tConsole.Write( i + \": \" + f[0] );\n\t\t\t\tfor( int j=1; j Factorize( int n )\n\t\t{\n\t\t\tList l = new List();\n\t\t \n\t\t\tif ( n == 1 )\n\t\t\t{\n\t\t\t\tl.Add(1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint k = 2;\n\t\t\t\twhile( n > 1 ) \n\t\t\t\t{\n\t\t\t\t\twhile( n % k == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tl.Add( k );\n\t\t\t\t\t\tn /= k;\n\t\t\t\t\t}\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\treturn l;\n\t\t}\t\n\t}\n}"} +{"id": 10, "output": " 5724 is valid\n 5727 is invalid\n112946 is valid\n112949 is invalid", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "C#": "using System;\n\nnamespace DammAlgorithm {\n class Program {\n static int[,] table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n static bool Damm(string s) {\n int interim = 0;\n foreach (char c in s) {\n interim = table[interim, c - '0'];\n }\n return interim == 0;\n }\n\n static void Main(string[] args) {\n int[] numbers = { 5724, 5727, 112946, 112949 };\n foreach (int number in numbers) {\n bool isValid = Damm(number.ToString());\n if (isValid) {\n Console.WriteLine(\"{0,6} is valid\", number);\n }\n else {\n Console.WriteLine(\"{0,6} is invalid\", number);\n }\n }\n }\n }\n}"} +{"id": 11, "output": "25 Dec 2095\n25 Dec 2101\n25 Dec 2107\n25 Dec 2112\n25 Dec 2118", "Python": "from calendar import weekday, SUNDAY\n\n[year for year in range(2090, 2122) if weekday(year, 12, 25) == SUNDAY]", "C#": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n for (int i = 2090; i <= 2121; i++)\n {\n DateTime date = new DateTime(i, 12, 25);\n if (date.DayOfWeek == DayOfWeek.Sunday)\n {\n Console.WriteLine(date.ToString(\"dd MMM yyyy\"));\n }\n }\n }\n}"} +{"id": 12, "output": "Default implementation.\nDefault implementation.\nDelegate implementation.", "Python": "class Delegator:\n def __init__(self):\n self.delegate = None\n def operation(self):\n if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):\n return self.delegate.thing()\n return 'default implementation'\n\nclass Delegate:\n def thing(self):\n return 'delegate implementation'\n\nif __name__ == '__main__':\n\n # No delegate\n a = Delegator()\n assert a.operation() == 'default implementation'\n\n # With a delegate that does not implement \"thing\"\n a.delegate = 'A delegate may be any object'\n assert a.operation() == 'default implementation'\n\n # With delegate that implements \"thing\"\n a.delegate = Delegate()\n assert a.operation() == 'delegate implementation'", "C#": "using System;\n\ninterface IOperable\n{\n string Operate();\n}\n\nclass Inoperable\n{\n}\n\nclass Operable : IOperable\n{\n public string Operate()\n {\n return \"Delegate implementation.\";\n }\n}\n\nclass Delegator : IOperable\n{\n object Delegate;\n\n public string Operate()\n {\n var operable = Delegate as IOperable;\n return operable != null ? operable.Operate() : \"Default implementation.\";\n }\n\n static void Main()\n {\n var delegator = new Delegator();\n foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })\n {\n delegator.Delegate = @delegate;\n Console.WriteLine(delegator.Operate());\n }\n }\n}"} +{"id": 13, "output": "Police:2, Sanitation:3, Fire:7\nPolice:2, Sanitation:7, Fire:3\nPolice:2, Sanitation:4, Fire:6\nPolice:2, Sanitation:6, Fire:4\nPolice:4, Sanitation:1, Fire:7\nPolice:4, Sanitation:7, Fire:1\nPolice:4, Sanitation:2, Fire:6\nPolice:4, Sanitation:6, Fire:2\nPolice:4, Sanitation:3, Fire:5\nPolice:4, Sanitation:5, Fire:3\nPolice:6, Sanitation:1, Fire:5\nPolice:6, Sanitation:5, Fire:1\nPolice:6, Sanitation:2, Fire:4\nPolice:6, Sanitation:4, Fire:2", "Python": "from itertools import permutations\n \ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n \nif __name__ == '__main__':\n solve()", "C#": "using System;\npublic class Program\n{\n public static void Main() {\n for (int p = 2; p <= 7; p+=2) {\n for (int s = 1; s <= 7; s++) {\n int f = 12 - p - s;\n if (s >= f) break;\n if (f > 7) continue;\n if (s == p || f == p) continue; //not even necessary\n Console.WriteLine($\"Police:{p}, Sanitation:{s}, Fire:{f}\");\n Console.WriteLine($\"Police:{p}, Sanitation:{f}, Fire:{s}\");\n }\n }\n }\n}"} +{"id": 14, "output": "Examining [] which has a length of 0:\n All characters in the string are the same.\nExamining [ ] which has a length of 3:\n All characters in the string are the same.\nExamining [2] which has a length of 1:\n All characters in the string are the same.\nExamining [333] which has a length of 3:\n All characters in the string are the same.\nExamining [.55] which has a length of 3:\n Not all characters in the string are the same.\n '5' (0x35) is different at position 1\nExamining [tttTTT] which has a length of 6:\n Not all characters in the string are the same.\n 'T' (0x54) is different at position 3\nExamining [4444 444k] which has a length of 9:\n Not all characters in the string are the same.\n ' ' (0x20) is different at position 4", "Python": "from itertools import groupby\n\n\n# firstDifferingCharLR :: String -> Either String Dict\ndef firstDifferingCharLR(s):\n '''Either a message reporting that no character changes were\n seen, or a dictionary with details of the first character\n (if any) that differs from that at the head of the string.\n '''\n def details(xs):\n c = xs[1][0]\n return {\n 'char': repr(c),\n 'hex': hex(ord(c)),\n 'index': s.index(c),\n 'total': len(s)\n }\n xs = list(groupby(s))\n return Right(details(xs)) if 1 < len(xs) else (\n Left('Total length ' + str(len(s)) + ' - No character changes.')\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test of 7 strings'''\n\n print(fTable('First, if any, points of difference:\\n')(repr)(\n either(identity)(\n lambda dct: dct['char'] + ' (' + dct['hex'] +\n ') at character ' + str(1 + dct['index']) +\n ' of ' + str(dct['total']) + '.'\n )\n )(firstDifferingCharLR)([\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444'\n ]))\n\n\n# GENERIC -------------------------------------------------\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\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# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C#": "using System;\n\nnamespace AllSame {\n class Program {\n static void Analyze(string s) {\n Console.WriteLine(\"Examining [{0}] which has a length of {1}:\", s, s.Length);\n if (s.Length > 1) {\n var b = s[0];\n for (int i = 1; i < s.Length; i++) {\n var c = s[i];\n if (c != b) {\n Console.WriteLine(\" Not all characters in the string are the same.\");\n Console.WriteLine(\" '{0}' (0x{1:X02}) is different at position {2}\", c, (int)c, i);\n return;\n }\n }\n\n }\n Console.WriteLine(\" All characters in the string are the same.\");\n }\n\n static void Main() {\n var strs = new string[] { \"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\" };\n foreach (var str in strs) {\n Analyze(str);\n }\n }\n }\n}"} +{"id": 15, "output": "627615 has additive persistence 2 and digital root 9\n39390 has additive persistence 2 and digital root 6\n588225 has additive persistence 2 and digital root 3\n393900588225 has additive persistence 2 and digital root 9", "Python": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\" \n % (n, persistance, root))", "C#": "using System;\nusing System.Linq;\n\nclass Program\n{\n static Tuple DigitalRoot(long num)\n {\n int additivepersistence = 0;\n while (num > 9)\n {\n num = num.ToString().ToCharArray().Sum(x => x - '0');\n additivepersistence++;\n }\n return new Tuple(additivepersistence, (int)num);\n }\n static void Main(string[] args)\n {\n foreach (long num in new long[] { 627615, 39390, 588225, 393900588225 })\n {\n var t = DigitalRoot(num);\n Console.WriteLine(\"{0} has additive persistence {1} and digital root {2}\", num, t.Item1, t.Item2);\n }\n }\n}"} +{"id": 16, "output": "Maximum total: 1320", "Python": "def solve(tri):\n while len(tri) > 1:\n t0 = tri.pop()\n t1 = tri.pop()\n tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)])\n return tri[0][0]\n\n\ndata = \"\"\" 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\nprint solve([map(int, row.split()) for row in data.splitlines()])", "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= 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}"} +{"id": 17, "output": "EvenEven", "Python": "def is_odd(i): return bool(i & 1)\ndef is_even(i): return not is_odd(i)\n[(j, is_odd(j)) for j in range(10)]\n[(j, is_even(j)) for j in range(10)]\n", "C#": "namespace RosettaCode\n{\n using System;\n\n public static class EvenOrOdd\n {\n public static bool IsEvenBitwise(this int number)\n {\n return (number & 1) == 0;\n }\n\n public static bool IsOddBitwise(this int number)\n {\n return (number & 1) != 0;\n }\n\n public static bool IsEvenRemainder(this int number)\n {\n int remainder;\n Math.DivRem(number, 2, out remainder);\n return remainder == 0;\n }\n\n public static bool IsOddRemainder(this int number)\n {\n int remainder;\n Math.DivRem(number, 2, out remainder);\n return remainder != 0;\n }\n\n public static bool IsEvenModulo(this int number)\n {\n return (number % 2) == 0;\n }\n\n public static bool IsOddModulo(this int number)\n {\n return (number % 2) != 0;\n }\n }\n public class Program\n {\n public static void Main()\n {\n int num = 26; //Set this to any integer.\n if (num.IsEvenBitwise()) //Replace this with any even function.\n {\n Console.Write(\"Even\");\n }\n else\n {\n Console.Write(\"Odd\");\n }\n //Prints \"Even\".\n if (num.IsOddBitwise()) //Replace this with any odd function.\n {\n Console.Write(\"Odd\");\n }\n else\n {\n Console.Write(\"Even\");\n }\n //Prints \"Even\".\n }\n }\n}"} +{"id": 18, "output": "2^929-1 = 0 (mod 13007)", "Python": "def is_prime(number):\n return True # code omitted - see Primality by Trial Division\n\ndef m_factor(p):\n max_k = 16384 / p # arbitrary limit; since Python automatically uses long's, it doesn't overflow\n for k in xrange(max_k):\n q = 2*p*k + 1\n if not is_prime(q):\n continue\n elif q % 8 != 1 and q % 8 != 7:\n continue\n elif pow(2, p, q) == 1:\n return q\n return None\n\nif __name__ == '__main__':\n exponent = int(raw_input(\"Enter exponent of Mersenne number: \"))\n if not is_prime(exponent):\n print \"Exponent is not prime: %d\" % exponent\n else:\n factor = m_factor(exponent)\n if not factor:\n print \"No factor found for M%d\" % exponent\n else:\n print \"M%d has a factor: %d\" % (exponent, factor)", "C#": "using System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint q = 929;\n\t\t\tif ( !isPrime(q) ) return;\n\t\t\tint r = q;\n\t\t\twhile( r > 0 ) \n\t\t\t\tr <<= 1;\n\t\t\tint d = 2 * q + 1;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tint i = 1;\n\t\t\t\tfor( int p=r; p!=0; p<<=1 )\n\t\t\t\t{\n\t\t\t\t\ti = (i*i) % d;\n\t\t\t\t\tif (p < 0) i *= 2;\n\t\t\t\t\tif (i > d) i -= d;\n\t\t\t\t}\n\t\t\t\tif (i != 1) d += 2 * q; else break;\t\t\t\t\n\t\t\t}\n\t\t\twhile(true);\n\t\t\t\n\t\t\tConsole.WriteLine(\"2^\"+q+\"-1 = 0 (mod \"+d+\")\"); \n\t\t}\n\t\t\n\t\tstatic bool isPrime(int n)\n\t\t{\n\t\t\tif ( n % 2 == 0 ) return n == 2;\n\t\t\tif ( n % 3 == 0 ) return n == 3;\n\t\t\tint d = 5;\n\t\t\twhile( d*d <= n )\n\t\t\t{\n\t\t\t\tif ( n % d == 0 ) return false;\n\t\t\t\td += 2;\n\t\t\t\tif ( n % d == 0 ) return false;\n\t\t\t\td += 4;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n}"} +{"id": 19, "output": "F1: 0/1, 1/1\nF2: 0/1, 1/2, 1/1\nF3: 0/1, 1/3, 1/2, 2/3, 1/1\nF4: 0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1\nF5: 0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1\nF100 has 3045 terms.\nF200 has 12233 terms.\nF300 has 27399 terms.\nF400 has 48679 terms.\nF500 has 76117 terms.", "Python": "from fractions import Fraction\n\n\nclass Fr(Fraction):\n def __repr__(self):\n return '(%s/%s)' % (self.numerator, self.denominator)\n\n\ndef farey(n, length=False):\n if not length:\n return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n else:\n #return 1 + len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})\n return (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))\n \nif __name__ == '__main__':\n print('Farey sequence for order 1 through 11 (inclusive):')\n for n in range(1, 12): \n print(farey(n))\n print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:')\n print([farey(i, length=True) for i in range(100, 1001, 100)])", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class FareySequence\n{\n public static void Main() {\n for (int i = 1; i <= 5; i++) {\n Console.WriteLine($\"F{i}: \" + string.Join(\", \", Generate(i).Select(f => $\"{f.num}/{f.den}\")));\n }\n for (int i = 100; i <= 500; i+=100) {\n Console.WriteLine($\"F{i} has {Generate(i).Count()} terms.\");\n }\n }\n\n public static IEnumerable<(int num, int den)> Generate(int i) {\n var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n));\n var seq = new SortedSet<(int n, int d)>(comparer);\n for (int d = 1; d <= i; d++) {\n for (int n = 0; n <= d; n++) {\n seq.Add((n, d));\n }\n }\n return seq;\n }\n}"} +{"id": 20, "output": " i d\n 2 3.21851142\n 3 4.38567760\n 4 4.60094928\n 5 4.65513050\n 6 4.66611195\n 7 4.66854858\n 8 4.66906066\n 9 4.66917155\n10 4.66919515\n11 4.66920026\n12 4.66920098\n13 4.66920537", "Python": "max_it = 13\nmax_it_j = 10\na1 = 1.0\na2 = 0.0\nd1 = 3.2\na = 0.0\n\nprint \" i d\"\nfor i in range(2, max_it + 1):\n a = a1 + (a1 - a2) / d1\n for j in range(1, max_it_j + 1):\n x = 0.0\n y = 0.0\n for k in range(1, (1 << i) + 1):\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n a = a - x / y\n d = (a1 - a2) / (a - a1)\n print(\"{0:2d} {1:.8f}\".format(i, d))\n d1 = d\n a2 = a1\n a1 = a", "C#": "using System;\n\nnamespace FeigenbaumConstant {\n class Program {\n static void Main(string[] args) {\n var maxIt = 13;\n var maxItJ = 10;\n var a1 = 1.0;\n var a2 = 0.0;\n var d1 = 3.2;\n Console.WriteLine(\" i d\");\n for (int i = 2; i <= maxIt; i++) {\n var a = a1 + (a1 - a2) / d1;\n for (int j = 1; j <= maxItJ; j++) {\n var x = 0.0;\n var y = 0.0;\n for (int k = 1; k <= 1<= 2). We can use a set to detect the element appearing\n # an odd number of times. Detect odd occurrences by toggling admission/expulsion\n # to and from the set for each value encountered. At the end of each pass one element\n # will remain in the set.\n missing_permutation = ''\n for pos in range(len(arr[0])):\n s = set()\n for permutation in arr:\n c = permutation[pos]\n if c in s:\n s.remove(c)\n else:\n s.add(c)\n missing_permutation += list(s)[0]\n return missing_permutation\n \ngiven = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()\n \nprint missing_permutation(given)", "C#": "using System;\nusing System.Linq;\n\npublic class Test\n{\n public static void Main()\n {\n var input = new [] {\"ABCD\",\"CABD\",\"ACDB\",\"DACB\",\"BCDA\",\n \"ACBD\",\"ADCB\",\"CDAB\",\"DABC\",\"BCAD\",\"CADB\",\n \"CDBA\",\"CBAD\",\"ABDC\",\"ADBC\",\"BDCA\",\"DCBA\",\n \"BACD\",\"BADC\",\"BDAC\",\"CBDA\",\"DBCA\",\"DCAB\"};\n \n int[] values = {0,0,0,0};\n foreach (string s in input)\n for (int i = 0; i < 4; i++)\n values[i] ^= s[i];\n Console.WriteLine(string.Join(\"\", values.Select(i => (char)i)));\n }\n}"} +{"id": 22, "output": "0.5\n0.5\n0.5", "Python": "x,xi, y,yi = 2.0,0.5, 4.0,0.25\nz = x + y\nzi = 1.0 / (x + y)\nmultiplier = lambda n1, n2: (lambda m: n1 * n2 * m)\nnumlist = [x, y, z]\nnumlisti = [xi, yi, zi]\n[multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]\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 multiplier = m => n1 * n2 * m;\n return multiplier;\n });\n\n foreach (var multiplier in multiplied)\n Console.WriteLine(multiplier(0.5));\n }\n}"} +{"id": 23, "output": "2090 - December\n2092 - August\n2093 - May\n2094 - January\n2094 - October\n2095 - July\n2097 - March\n2098 - August\n2099 - May\n2100 - January\n2100 - October\nTotal 5-weekend months between 2090 and 2100: 11\nTotal number of years with no 5-weekend months 2", "Python": "from datetime import (date,\n timedelta)\n\nDAY = timedelta(days=1)\nSTART, STOP = date(2090, 1, 1), date(2101, 1, 1)\nWEEKEND = {6, 5, 4} # Sunday is day 6\nFMT = '%Y %m(%B)'\n\n\ndef five_weekends_per_month(start: date = START,\n stop: date = STOP) -> list[date]:\n \"\"\"Compute months with five weekends between dates\"\"\"\n current_date = start\n last_month = weekend_days = 0\n five_weekends = []\n while current_date < stop:\n if current_date.month != last_month:\n if weekend_days >= 15:\n five_weekends.append(current_date - DAY)\n weekend_days = 0\n last_month = current_date.month\n if current_date.weekday() in WEEKEND:\n weekend_days += 1\n current_date += DAY\n return five_weekends\n\n\ndates = five_weekends_per_month()\nindent = ' '\nprint(f\"There are {len(dates)} months of which the first and last five are:\")\nprint(indent + ('\\n' + indent).join(d.strftime(FMT) for d in dates[:5]))\nprint(indent + '...')\nprint(indent + ('\\n' + indent).join(d.strftime(FMT) for d in dates[-5:]))\n\nyears_without_five_weekends_months = (STOP.year - START.year\n - len({d.year for d in dates}))\nprint(f\"\\nThere are {years_without_five_weekends_months} years in the \"\n f\"range that do not have months with five weekends\")", "C#": "using System;\n\nnamespace _5_Weekends\n{\n class Program\n {\n const int FIRST_YEAR = 2090;\n const int LAST_YEAR = 2100;\n static int[] _31_MONTHS = { 1, 3, 5, 7, 8, 10, 12 }; \n\n static void Main(string[] args)\n {\n int totalNum = 0;\n int totalNo5Weekends = 0;\n\n for (int year = FIRST_YEAR; year <= LAST_YEAR; year++)\n {\n bool has5Weekends = false;\n\n foreach (int month in _31_MONTHS)\n {\n DateTime firstDay = new DateTime(year, month, 1);\n if (firstDay.DayOfWeek == DayOfWeek.Friday)\n {\n totalNum++;\n has5Weekends = true;\n Console.WriteLine(firstDay.ToString(\"yyyy - MMMM\"));\n }\n }\n\n if (!has5Weekends) totalNo5Weekends++;\n }\n Console.WriteLine(\"Total 5-weekend months between {0} and {1}: {2}\", FIRST_YEAR, LAST_YEAR, totalNum);\n Console.WriteLine(\"Total number of years with no 5-weekend months {0}\", totalNo5Weekends);\n }\n }\n}"} +{"id": 24, "output": "[6.00000000, 25.50000000, 40.00000000, 42.50000000, 49.00000000]\n[7.00000000, 15.00000000, 37.50000000, 40.00000000, 41.00000000]\n[-1.95059594, -0.67674121, 0.23324706, 0.74607095, 1.73131507]", "Python": "from __future__ import division\nimport math\nimport sys\n\ndef fivenum(array):\n n = len(array)\n if n == 0:\n print(\"you entered an empty array.\")\n sys.exit()\n x = sorted(array)\n \n n4 = math.floor((n+3.0)/2.0)/2.0\n d = [1, n4, (n+1)/2, n+1-n4, n]\n sum_array = []\n \n for e in range(5):\n floor = int(math.floor(d[e] - 1))\n ceil = int(math.ceil(d[e] - 1))\n sum_array.append(0.5 * (x[floor] + x[ceil]))\n \n return sum_array\n\nx = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,\n-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,\n1.04312009, -0.10305385, 0.75775634, 0.32566578]\n\ny = fivenum(x)\nprint(y)", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Fivenum {\n public static class Helper {\n public static string AsString(this ICollection c, string format = \"{0}\") {\n StringBuilder sb = new StringBuilder(\"[\");\n int count = 0;\n foreach (var t in c) {\n if (count++ > 0) {\n sb.Append(\", \");\n }\n sb.AppendFormat(format, t);\n }\n return sb.Append(\"]\").ToString();\n }\n }\n\n class Program {\n static double Median(double[] x, int start, int endInclusive) {\n int size = endInclusive - start + 1;\n if (size <= 0) throw new ArgumentException(\"Array slice cannot be empty\");\n int m = start + size / 2;\n return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;\n }\n\n static double[] Fivenum(double[] x) {\n foreach (var d in x) {\n if (Double.IsNaN(d)) {\n throw new ArgumentException(\"Unable to deal with arrays containing NaN\");\n }\n }\n double[] result = new double[5];\n Array.Sort(x);\n result[0] = x.First();\n result[2] = Median(x, 0, x.Length - 1);\n result[4] = x.Last();\n int m = x.Length / 2;\n int lowerEnd = (x.Length % 2 == 1) ? m : m - 1;\n result[1] = Median(x, 0, lowerEnd);\n result[3] = Median(x, m, x.Length - 1);\n return result;\n }\n\n static void Main(string[] args) {\n double[][] x1 = new double[][]{\n new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},\n new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0},\n new double[]{\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n },\n };\n foreach(var x in x1) {\n var result = Fivenum(x);\n Console.WriteLine(result.AsString(\"{0:F8}\"));\n }\n }\n }\n}"} +{"id": 25, "output": "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz", "Python": "for i in range(1, 101):\n if i % 15 == 0:\n print(\"FizzBuzz\")\n elif i % 3 == 0:\n print(\"Fizz\")\n elif i % 5 == 0:\n print(\"Buzz\")\n else:\n print(i)", "C#": "using System;\nusing System.Linq;\n\nnamespace FizzBuzz\n{\n class Program\n {\n static void Main(string[] args)\n {\n Enumerable.Range(1, 10)\n .Select(a => String.Format(\"{0}{1}\", a % 3 == 0 ? \"Fizz\" : string.Empty, a % 5 == 0 ? \"Buzz\" : string.Empty))\n .Select((b, i) => String.IsNullOrEmpty(b) ? (i + 1).ToString() : b)\n .ToList()\n .ForEach(Console.WriteLine);\n }\n }\n}"} +{"id": 26, "output": " 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30 31 32 33 34 35 36\n37 38 39 40 41 42 43 44 45\n46 47 48 49 50 51 52 53 54 55\n56 57 58 59 60 61 62 63 64 65 66\n67 68 69 70 71 72 73 74 75 76 77 78\n79 80 81 82 83 84 85 86 87 88 89 90 91\n92 93 94 95 96 97 98 99 100 101 102 103 104 105", "Python": "def floyd(rowcount=5):\n\trows = [[1]]\n\twhile len(rows) < rowcount:\n\t\tn = rows[-1][-1] + 1\n\t\trows.append(list(range(n, n + len(rows[-1]) + 1)))\n\treturn rows\n\nfloyd()\n\ndef pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):\n\tcolspace = [len(str(n)) for n in rows[-1]]\n\tfor row in rows:\n\t\tprint( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))", "C#": "using System;\nusing System.Text;\n\npublic class FloydsTriangle\n{\n internal static void Main(string[] args)\n {\n int count;\n if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0)\n {\n Console.WriteLine(MakeTriangle(count));\n }\n else\n {\n Console.WriteLine(MakeTriangle(5));\n Console.WriteLine();\n Console.WriteLine(MakeTriangle(14));\n }\n }\n\n public static string MakeTriangle(int rows)\n {\n int maxValue = (rows * (rows + 1)) / 2;\n int digit = 0;\n StringBuilder output = new StringBuilder();\n\n for (int row = 1; row <= rows; row++)\n {\n for (int column = 0; column < row; column++)\n {\n int colMaxDigit = (maxValue - rows) + column + 1;\n if (column > 0)\n {\n output.Append(' ');\n }\n\n digit++;\n output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length));\n }\n\n output.AppendLine();\n }\n\n return output.ToString();\n }\n}"} +{"id": 27, "output": "Main Thread\nSpawned Thread", "Python": "import os\n\npid = os.fork()\nif pid > 0:\n # parent code\nelse:\n # child code", "C#": "using System;\nusing System.Threading;\n\nnamespace Fork {\n class Program {\n static void Fork() {\n Console.WriteLine(\"Spawned Thread\");\n }\n\n static void Main(string[] args) {\n Thread t = new Thread(new ThreadStart(Fork));\n t.Start();\n\n Console.WriteLine(\"Main Thread\");\n t.Join();\n\n Console.ReadLine();\n }\n }\n}"} +{"id": 28, "output": "The first 15 gapful numbers > 1,000,000 are: \n1000000 1000005 1000008 1000010 1000016 1000020 1000021 1000030 1000032 1000034 1000035 1000040 1000050 1000060 1000065 ", "Python": "from itertools import islice, count\nfor start, n in [(1_000_000, 15)]:\n print(f\"\\nFirst {n} gapful numbers from {start:_}\")\n print(list(islice(( x for x in count(start) \n if (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) )\n , n)))", "C#": "using System;\n\nnamespace GapfulNumbers\n{\n class Program\n {\n static void Main(string[] args)\n {\n \n Console.WriteLine(\"The first 15 gapful numbers > 1,000,000 are: \");\n FindGap(1000000, 15);\n\n Console.Read();\n }\n\n public static int firstNum(int n)\n {\n /*Divide by ten until the leading digit remains.*/\n while (n >= 10)\n {\n n /= 10;\n }\n return (n);\n }\n\n public static int lastNum(int n)\n {\n /*Modulo gives you the last digit. */\n return (n % 10);\n }\n\n static void FindGap(int n, int gaps)\n {\n int count = 0;\n while (count < gaps)\n {\n\n /* We have to convert our first and last digits to strings to concatenate.*/\n string concat = firstNum(n).ToString() + lastNum(n).ToString();\n /* And then convert our concatenated string back to an integer. */\n int i = Convert.ToInt32(concat);\n\n /* Modulo with our new integer and output the result. */\n if (n % i == 0)\n {\n Console.Write(n + \" \");\n count++;\n n++;\n }\n else\n {\n n++;\n continue;\n }\n }\n }\n }\n}"} +{"id": 29, "output": "First integer:\nFirst string:\nSecond integer:\nSecond string:\nThird integer:\nThird string:\nLimit (inclusive):", "Python": "def genfizzbuzz(factorwords, numbers):\n # sort entries by factor\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)))", "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}"} +{"id": 30, "output": "abcdefghijklmnopqrstuvwxyz", "Python": "# From the standard library:\nfrom string import ascii_lowercase\n\n# Generation:\nlower = [chr(i) for i in range(ord('a'), ord('z') + 1)]", "C#": "using System;\nusing System.Linq;\n\ninternal class Program\n{\n private static void Main()\n {\n Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c)));\n }\n}"} +{"id": 31, "output": "3\n5\n6\n-2\n-1\n4", "Python": "def maxsubseq(seq):\n return max((seq[begin:end] for begin in xrange(len(seq)+1)\n for end in xrange(begin, len(seq)+1)),\n key=sum)", "C#": "using System;\n\nnamespace Tests_With_Framework_4\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[] integers = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; int length = integers.Length;\n int maxsum, beginmax, endmax, sum; maxsum = beginmax = sum = 0; endmax = -1;\n\n for (int i = 0; i < length; i++)\n {\n sum = 0;\n for (int k = i; k < length; k++)\n {\n sum += integers[k];\n if (sum > maxsum)\n {\n maxsum = sum;\n beginmax = i;\n endmax = k;\n }\n }\n }\n\n for (int i = beginmax; i <= endmax; i++)\n Console.WriteLine(integers[i]);\n\n Console.ReadKey();\n }\n }\n}"} +{"id": 32, "output": "1900 is not a leap year.\n1994 is not a leap year.\n1996 is a leap year.\n2023 is not a leap year.", "Python": "def is_leap_year(year):\n return not year % (4 if year % 100 else 400)", "C#": "using System;\n\nclass Program\n{\n static void Main()\n {\n foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n {\n Console.WriteLine(\"{0} is {1}a leap year.\",\n year,\n DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n }\n }\n}"} +{"id": 33, "output": "112 Elements\nStarting with : 27,82,41,124 and ending with : 8,4,2,1\nNumber < 100000 with longest Hailstone seq.: 77031 with length of 351", "Python": "def hailstone(n):\n seq = [n]\n while n > 1:\n n = 3 * n + 1 if n & 1 else n // 2\n seq.append(n)\n return seq\n\n\nif __name__ == '__main__':\n h = hailstone(27)\n assert (len(h) == 112\n and h[:4] == [27, 82, 41, 124]\n and h[-4:] == [8, 4, 2, 1])\n max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))\n print(f\"Maximum length {max_length} was found for hailstone({n}) \"\n f\"for numbers <100,000\")", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Hailstone\n{\n class Program\n {\n public static List hs(int n,List seq)\n {\n List sequence = seq;\n sequence.Add(n);\n if (n == 1)\n {\n return sequence;\n }else{\n int newn = (n % 2 == 0) ? n / 2 : (3 * n) + 1;\n return hs(newn, sequence);\n } \n }\n\n static void Main(string[] args)\n {\n int n = 27;\n List sequence = hs(n,new List());\n Console.WriteLine(sequence.Count + \" Elements\");\n List start = sequence.GetRange(0, 4);\n List end = sequence.GetRange(sequence.Count - 4, 4);\n Console.WriteLine(\"Starting with : \" + string.Join(\",\", start) + \" and ending with : \" + string.Join(\",\", end)); \n int number = 0, longest = 0; \n for (int i = 1; i < 100000; i++)\n {\n int count = (hs(i, new List())).Count;\n if (count > longest)\n {\n longest = count;\n number = i;\n }\n }\n Console.WriteLine(\"Number < 100000 with longest Hailstone seq.: \" + number + \" with length of \" + longest);\n }\n }\n}"} +{"id": 34, "output": "1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 1002 ", "Python": "import itertools\ndef harshad():\n\tfor n in itertools.count(1):\n\t\tif n % sum(int(ch) for ch in str(n)) == 0:\n\t\t\tyield n\n\n\t\t\nlist(itertools.islice(harshad(), 0, 20))\nfor n in harshad():\n\tif n > 1000:\n\t\tprint(n)\n\t\tbreak\n", "C#": "using System;\nusing System.Collections.Generic;\n\nnamespace Harshad\n{\n class Program\n {\n public static bool IsHarshad(int n)\n {\n char[] inputChars = n.ToString().ToCharArray();\n IList digits = new List();\n\n foreach (char digit in inputChars)\n {\n digits.Add((byte)Char.GetNumericValue(digit));\n }\n\n if (n < 1)\n {\n return false;\n }\n\n int sum = 0;\n\n foreach (byte digit in digits)\n {\n sum += digit;\n }\n\n return n % sum == 0;\n }\n\n static void Main(string[] args)\n {\n int i = 1;\n int count = 0;\n\n while (true)\n {\n if (IsHarshad(i))\n {\n count++;\n\n if (count <= 20)\n {\n Console.Write(string.Format(\"{0} \", i));\n }\n else if (i > 1000)\n {\n Console.Write(string.Format(\"{0} \", i));\n break;\n }\n }\n\n i++;\n }\n\n Console.ReadKey();\n }\n }\n}"} +{"id": 35, "output": "First 8 happy numbers : 1,7,10,13,19,23,28,31\n", "Python": "def happy(n):\npast = set()\t\t\t\nwhile n != 1:\n n = sum(int(i)**2 for i in str(n))\n if n in past:\n return False\n past.add(n)\n return True\n\n[x for x in xrange(500) if happy(x)][:8]\n", "C#": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace HappyNums\n{\n class Program\n {\n public static bool ishappy(int n)\n {\n List cache = new List();\n int sum = 0;\n while (n != 1)\n {\n if (cache.Contains(n))\n {\n return false;\n }\n cache.Add(n);\n while (n != 0)\n {\n int digit = n % 10;\n sum += digit * digit;\n n /= 10;\n }\n n = sum;\n sum = 0;\n }\n return true; \n }\n\n static void Main(string[] args)\n {\n int num = 1;\n List happynums = new List();\n\n while (happynums.Count < 8)\n {\n if (ishappy(num))\n {\n happynums.Add(num);\n }\n num++;\n }\n Console.WriteLine(\"First 8 happy numbers : \" + string.Join(\",\", happynums));\n }\n }\n}"} +{"id": 36, "output": "Hello world!", "Python": "print(\"Hello world!\")", "C#": "namespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n System.Console.WriteLine(\"Hello world!\");\n }\n }\n}"} +{"id": 37, "output": "3\n0\n", "Python": "def countJewels(stones, jewels):\n jewelset = set(jewels)\n return sum(1 for stone in stones if stone in jewelset)\n\nprint(countJewels(\"aAAbbbb\", \"aA\"))\nprint(countJewels(\"ZZ\", \"z\"))", "C#": "using System;\nusing System.Linq;\n\npublic class Program\n{\n public static void Main() {\n Console.WriteLine(Count(\"aAAbbbb\", \"Aa\"));\n Console.WriteLine(Count(\"ZZ\", \"z\"));\n }\n\n private static int Count(string stones, string jewels) {\n var bag = jewels.ToHashSet();\n return stones.Count(bag.Contains);\n }\n}"} +{"id": 38, "output": "Long years in the 21st century:\n2004 2009 2015 2020 2026 2032 2037 2043 2048 2054 2060 2065 2071 2076 2082 2088 2093 2099\n", "Python": "from datetime import date\n\n\n# longYear :: Year Int -> Bool\ndef longYear(y):\n '''True if the ISO year y has 53 weeks.'''\n return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Longer (53 week) years in the range 2000-2100'''\n for year in [\n x for x in range(2000, 1 + 2100)\n if longYear(x)\n ]:\n print(year)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "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 To(this int start, int end) {\n for (int i = start; i < end; i++) yield return i;\n }\n \n}"} +{"id": 39, "output": "1 1 3 5 9 15 25 41 67 109 177 287 465 753 1219 1973 3193 5167 8361 13529 21891 35421 57313 92735 150049\n0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368", "Python": "def Leonardo(L_Zero, L_One, Add, Amount):\n terms = [L_Zero,L_One]\n while len(terms) < Amount:\n new = terms[-1] + terms[-2]\n new += Add\n terms.append(new)\n return terms\n\nout = \"\"\nprint \"First 25 Leonardo numbers:\"\nfor term in Leonardo(1,1,1,25):\n out += str(term) + \" \"\nprint out\n\nout = \"\"\nprint \"Leonardo numbers with fibonacci parameters:\"\nfor term in Leonardo(0,1,0,25):\n out += str(term) + \" \"\nprint out", "C#": "using System;\nusing System.Linq;\n\npublic class Program\n{\n public static void Main() {\n Console.WriteLine(string.Join(\" \", Leonardo().Take(25)));\n Console.WriteLine(string.Join(\" \", Leonardo(L0: 0, L1: 1, add: 0).Take(25)));\n }\n\n public static IEnumerable Leonardo(int L0 = 1, int L1 = 1, int add = 1) {\n while (true) {\n yield return L0;\n (L0, L1) = (L1, L0 + L1 + add);\n }\n }\n}"} +{"id": 0, "output": "map_value(0) = -1\nmap_value(1) = -0.9\nmap_value(2) = -0.8\nmap_value(3) = -0.7\nmap_value(4) = -0.6\nmap_value(5) = -0.5\nmap_value(6) = -0.4\nmap_value(7) = -0.3\nmap_value(8) = -0.2\nmap_value(9) = -0.1\nmap_value(10) = 0", "Python": "from fractions import Fraction\nfor s in range(11):\n\tprint(\"%2g maps to %s\" % (s, maprange( (0, 10), (-1, 0), Fraction(s))))\n", "C++": "#include \n#include \n\ntemplate\ntVal map_value(std::pair a, std::pair b, tVal inVal)\n{\n tVal inValNorm = inVal - a.first;\n tVal aUpperNorm = a.second - a.first;\n tVal normPosition = inValNorm / aUpperNorm;\n\n tVal bUpperNorm = b.second - b.first;\n tVal bValNorm = normPosition * bUpperNorm;\n tVal outVal = b.first + bValNorm;\n\n return outVal;\n}\n\nint main()\n{\n std::pair a(0,10), b(-1,0);\n\n for(float value = 0.0; 10.0 >= value; ++value)\n std::cout << \"map_value(\" << value << \") = \" << map_value(a, b, value) << std::endl;\n\n return 0;\n}"} +{"id": 1, "output": "337 355 373 535 553 733 2227 2272 2335 2353 2533 2722 3235 3253 3325 3352 3523 3532 5233 5323 5332 7222 22225 22252 22333 22522 23233 23323 23332 25222 32233 32323 32332 33223 33232 33322 52222 222223 222232 222322 223222 232222 322222 ", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n q = deque([(r, 0)])\n while q:\n r, n = q.popleft()\n for d in 2, 3, 5, 7:\n if d >= r:\n if d == r: yield n + d\n break\n q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))", "C++": "#include \n#include \n#include \n\nusing namespace std;\n\nint main() { \n vector> 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; }"} +{"id": 2, "output": " 0 1 2 3 4 5 6 7 8 9\n 53 371 913", "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()", "C++": "#include \n#include \n#include \n\nconst int LIMIT = 1000;\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; id2)\n d1 = d2\n num //= 10\n return height == 0\n \ndef sequence(start, fn):\n \"\"\"Generate a sequence defined by a function\"\"\"\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# Generate the first 200 numbers\nprint(\"The first 200 numbers are:\")\nprint(*itertools.islice(a296712, 200))\n\n# Generate the 10,000,000th number\nprint(\"The 10,000,000th number is:\")\nprint(*itertools.islice(a296712, 10000000-200-1, 10000000-200))\n# It is necessary to subtract 200 from the index, because 200 numbers\n# have already been consumed.", "C++": "#include \n#include \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 = 10000;\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}"} +{"id": 4, "output": "1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 \nevil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58 \nodious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 ", "Python": "def popcount(n): return bin(n).count(\"1\")\n\n[popcount(3**i) for i in range(30)]\n\nevil, odious, i = [], [], 0\nwhile len(evil) < 30 or len(odious) < 30:\n p = popcount(i)\n if p % 2: odious.append(i)\n else: evil.append(i)\n i += 1\n\nevil[:30]\n\nodious[:30]\n\n", "C++": "#include \n#include \n#include \n\nsize_t popcount(unsigned long long n) {\n return std::bitset(n).count();\n}\n\nint main() {\n {\n unsigned long long n = 1;\n for (int i = 0; i < 30; i++) {\n std::cout << popcount(n) << \" \";\n n *= 3;\n }\n std::cout << std::endl;\n }\n\n int od[30];\n int ne = 0, no = 0;\n std::cout << \"evil : \";\n for (int n = 0; ne+no < 60; n++) {\n if ((popcount(n) & 1) == 0) {\n if (ne < 30) {\n\tstd::cout << n << \" \";\n\tne++;\n }\n } else {\n if (no < 30) {\n\tod[no++] = n;\n }\n }\n }\n std::cout << std::endl;\n std::cout << \"odious: \";\n for (int i = 0; i < 30; i++) {\n std::cout << od[i] << \" \";\n }\n std::cout << std::endl;\n\n return 0;\n}"} +{"id": 5, "output": "{ }\n{ 2 }\n{ 2, 3 }\n{ 2, 3, 5 }\n{ 2, 3, 5, 7 }\n{ 2, 3, 7 }\n{ 2, 5 }\n{ 2, 5, 7 }\n{ 2, 7 }\n{ 3 }\n{ 3, 5 }\n{ 3, 5, 7 }\n{ 3, 7 }\n{ 5 }\n{ 5, 7 }\n{ 7 }", "Python": "def list_powerset(lst):\n # the power set of the empty set has one element, the empty set\n result = [[]]\n for x in lst:\n # for every additional element in our set\n # the power set consists of the subsets that don't\n # contain this element (just take the previous power set)\n # plus the subsets that do contain the element (use list\n # comprehension to add [x] onto everything in the\n # previous power set)\n result.extend([subset + [x] for subset in result])\n return result\n\n# the above function in one statement\ndef list_powerset2(lst):\n return reduce(lambda result, x: result + [subset + [x] for subset in result],\n lst, [[]])\n\ndef powerset(s):\n return frozenset(map(frozenset, list_powerset(list(s))))", "C++": "#include \n#include \n#include \n#include \n#include \ntypedef std::set set_type;\ntypedef std::set powerset_type;\n\npowerset_type powerset(set_type const& set)\n{\n typedef set_type::const_iterator set_iter;\n typedef std::vector vec;\n typedef vec::iterator vec_iter;\n\n struct local\n {\n static int dereference(set_iter v) { return *v; }\n };\n\n powerset_type result;\n\n vec elements;\n do\n {\n set_type tmp;\n std::transform(elements.begin(), elements.end(),\n std::inserter(tmp, tmp.end()),\n local::dereference);\n result.insert(tmp);\n if (!elements.empty() && ++elements.back() == set.end())\n {\n elements.pop_back();\n }\n else\n {\n set_iter iter;\n if (elements.empty())\n {\n iter = set.begin();\n }\n else\n {\n iter = elements.back();\n ++iter;\n }\n for (; iter != set.end(); ++iter)\n {\n elements.push_back(iter);\n }\n }\n } while (!elements.empty());\n\n return result;\n}\n\nint main()\n{\n int values[4] = { 2, 3, 5, 7 };\n set_type test_set(values, values+4);\n\n powerset_type test_powerset = powerset(test_set);\n\n for (powerset_type::iterator iter = test_powerset.begin();\n iter != test_powerset.end();\n ++iter)\n {\n std::cout << \"{ \";\n char const* prefix = \"\";\n for (set_type::iterator iter2 = iter->begin();\n iter2 != iter->end();\n ++iter2)\n {\n std::cout << prefix << *iter2;\n prefix = \", \";\n }\n std::cout << \" }\\n\";\n }\n}"} +{"id": 6, "output": "1123 1231 1237 8123 11239 12301 12323 12329 12343 12347 \n12373 12377 12379 12391 17123 20123 22123 28123 29123 31123 \n31231 31237 34123 37123 40123 41231 41233 44123 47123 49123 \n50123 51239 56123 59123 61231 64123 65123 70123 71233 71237 \n76123 81233 81239 89123 91237 98123 \nThere are 451 such numbers below 1000000!", "Python": "#!/usr/bin/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\u00fameros primos que contienen 123:\")\n limite = 100000\n prime(limite, True)\n print(\"\\n\\nEncontrados \", columna, \" n\u00fameros primos por debajo de\", limite)\n limite = 1000000\n prime(limite, False)\n print(\"\\n\\nEncontrados \", columna, \" n\u00fameros primos por debajo de\", limite)", "C++": "#include \n#include \n#include \n#include \n\nbool isPrime( int number ) {\n if ( number < 2 ) {\n return false ;\n }\n int stop = std::sqrt( static_cast( number ) ) ;\n for ( int i = 2 ; i <= stop ; ++i )\n if ( number % i == 0 )\n return false ;\n return true ;\n}\n\nbool condition( int n ) {\n std::string numberstring { std::to_string( n ) } ;\n return isPrime( n ) && numberstring.find( \"123\" ) != std::string::npos ;\n}\n\nint main( ) {\n std::vector wantedPrimes ; \n for ( int i = 1 ; i < 100000 ; i++ ) {\n if ( condition( i ) ) \n wantedPrimes.push_back( i ) ;\n }\n int count = 0 ;\n for ( int i : wantedPrimes ) {\n std::cout << i << ' ' ;\n count++ ;\n if ( count % 10 == 0 ) {\n std::cout << std::endl ;\n }\n }\n count = wantedPrimes.size( ) ;\n for ( int i = wantedPrimes.back( ) + 1 ; i < 1000000 ; i++ ) {\n if ( condition ( i ) ) \n count++ ;\n }\n std::cout << std::endl ;\n std::cout << \"There are \" << count << \" such numbers below 1000000!\\n\" ;\n return 0 ;\n}"} +{"id": 7, "output": " 30 3025 55\n 31 3136 56\n 32 324 18\n 33 3364 58\n 34 3481 59\n 35 35344 188\n 36 36 6\n 37 3721 61\n 38 3844 62\n 39 3969 63\n 40 400 20\n 41 41209 203\n 42 4225 65\n 43 4356 66\n 44 441 21\n 45 45369 213\n 46 4624 68\n 47 4761 69\n 48 484 22\n 49 49 7", "Python": "from itertools import count\n\n\n# firstSquareWithPrefix :: Int -> Int\ndef firstSquareWithPrefix(n):\n '''The first perfect square prefixed (in decimal)\n by the decimal digits of N.\n '''\n pfx = str(n)\n lng = len(pfx)\n return int(\n next(\n s for s in (\n str(x * x) for x in count(0)\n )\n if pfx == s[0:lng]\n )\n )\n\n\n# ------------------------- TEST -------------------------\ndef main():\n '''First matches for the range [1..49]'''\n\n print('\\n'.join([\n str(firstSquareWithPrefix(x)) for x in range(1, 50)\n ]))\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C++": "#include \n\nvoid f(int n) {\n if (n < 1) {\n return;\n }\n\n int i = 1;\n while (true) {\n int sq = i * i;\n while (sq > n) {\n sq /= 10;\n }\n if (sq == n) {\n printf(\"%3d %9d %4d\\n\", n, i * i, i);\n return;\n }\n i++;\n }\n}\n\nint main() {\n std::cout << \"Prefix n^2 n\\n\";\n for (int i = 0; i < 50; i++) {\n f(i);\n }\n\n return 0;\n}"} +{"id": 8, "output": "Before sorting:\n{grass, green}\n{snow, white}\n{sky, blue}\n{cherry, red}\nAfter sorting:\n{cherry, red}\n{grass, green}\n{sky, blue}\n{snow, white}", "Python": "people = [('joe', 120), ('foo', 31), ('bar', 51)]\nsorted(people)", "C++": "#include \n#include \n#include \n\nstruct entry {\n std::string name;\n std::string value;\n};\n\nint main() {\n entry array[] = { { \"grass\", \"green\" }, { \"snow\", \"white\" },\n { \"sky\", \"blue\" }, { \"cherry\", \"red\" } };\n\n std::cout << \"Before sorting:\\n\";\n for (const auto &e : array) {\n std::cout << \"{\" << e.name << \", \" << e.value << \"}\\n\";\n }\n\n std::sort(std::begin(array), std::end(array), \n [](const entry & a, const entry & b) {\n return a.name < b.name;\n });\n\n std::cout << \"After sorting:\\n\";\n for (const auto &e : array) {\n std::cout << \"{\" << e.name << \", \" << e.value << \"}\\n\";\n }\n}"} +{"id": 9, "output": "7 0 5 4 3 2 1 6 ", "Python": "def sort_disjoint_sublist(data, indices):\n\tindices = sorted(indices)\n\tvalues = sorted(data[i] for i in indices)\n\tfor index, value in zip(indices, values):\n\t\tdata[index] = value\n\n\t\t\nd = [7, 6, 5, 4, 3, 2, 1, 0]\ni = set([6, 1, 7])\nsort_disjoint_sublist(d, i)\ndef sort_disjoint_sublist(data, indices):\n\tfor index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value\n", "C++": "#include \n#include \n#include \n#include \n\ntemplate \nvoid sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin,\n\t\t IndicesIterator indicesEnd) {\n std::vector temp;\n\n for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i)\n temp.push_back(valsBegin[*i]); // extract\n\n std::sort(indicesBegin, indicesEnd); // sort\n std::sort(temp.begin(), temp.end()); // sort a C++ container\n\n std::vector::const_iterator j = temp.begin();\n for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j)\n valsBegin[*i] = *j; // replace\n}\n\t\t \n\nint main()\n{\n int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 };\n int indices[] = { 6, 1, 7 };\n\n sortDisjoint(values, indices, indices+3);\n\n std::copy(values, values + 8, std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n\n return 0;\n}"} +{"id": 10, "output": "0: [0,1]\n5: [1,2,3,4,5]\n13: [1,10,11,12,13,2,3,4,5,6,7,8,9]\n21: [1,10,11,12,13,14,15,16,17,18,19,2,20,21,3,4,5,6,7,8,9]\n-22: [-1,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-2,-20,-21,-22,-3,-4,-5,-6,-7,-8,-9,0,1]", "Python": "n=13\nprint(sorted(range(1,n+1), key=str))", "C++": "#include \n#include \n#include \n#include \n#include \n\nvoid lexicographical_sort(std::vector& numbers) {\n std::vector strings(numbers.size());\n std::transform(numbers.begin(), numbers.end(), strings.begin(),\n [](int i) { return std::to_string(i); });\n std::sort(strings.begin(), strings.end());\n std::transform(strings.begin(), strings.end(), numbers.begin(),\n [](const std::string& s) { return std::stoi(s); });\n}\n\nstd::vector lexicographically_sorted_vector(int n) {\n std::vector numbers(n >= 1 ? n : 2 - n);\n std::iota(numbers.begin(), numbers.end(), std::min(1, n));\n lexicographical_sort(numbers);\n return numbers;\n}\n\ntemplate \nvoid print_vector(std::ostream& out, const std::vector& v) {\n out << '[';\n if (!v.empty()) {\n auto i = v.begin();\n out << *i++;\n for (; i != v.end(); ++i)\n out << ',' << *i;\n }\n out << \"]\\n\";\n}\n\nint main(int argc, char** argv) {\n for (int i : { 0, 5, 13, 21, -22 }) {\n std::cout << i << \": \";\n print_vector(std::cout, lexicographically_sorted_vector(i));\n }\n return 0;\n}"} +{"id": 11, "output": "Now is the time for all good men to come to the aid of our country.\n .Naaccddeeeeeffghhiiillmmmnnoooooooooorrrsttttttuuwy\n", "Python": "from functools import reduce\n\n\n# qSort :: [a] -> [a]\ndef qSort(xs):\n '''Sorted elements of the list xs, where the values\n of xs are assumed to be of some orderable type.\n '''\n if xs:\n h = xs[0]\n below, above = partition(\n lambda v: v <= h\n )(xs[1:])\n\n return qSort(below) + [h] + qSort(above)\n else:\n return []\n\n\n# ------------------------- TEST -------------------------\ndef main():\n '''A character-sorted version of a test string\n '''\n print(quoted('\"')(\n ''.join(qSort(list(\n \"Is this misspelling of alphabetical as alphabitical a joke ?\"\n )))\n ))\n\n\n# ----------------------- GENERIC ------------------------\n\n# partition :: (a -> Bool) -> [a] -> ([a], [a])\ndef partition(p):\n '''The pair of lists of those elements in xs\n which respectively do, and don't\n satisfy the predicate p.\n '''\n def go(a, x):\n ts, fs = a\n return (ts + [x], fs) if p(x) else (ts, fs + [x])\n return lambda xs: reduce(go, xs, ([], []))\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C++": "#include \n#include \n\nint main() {\n std::string s = \"Now is the time for all good men \"\n \"to come to the aid of our country.\";\n \n std::cout << s << std::endl;\n std::sort(s.begin(), s.end());\n std::cout << s << std::endl; \n return 0;\n}"} +{"id": 12, "output": "-12\n0\n77444\n\n(from the \"Wizard of OZ\")\nbears, oh my!\nlions, tigers, and\n\n-9.7\n11.17\n11.3\n", "Python": "while True:\n x, y, z = eval(input('Three Python values: '))\n print(f'As read: x = {x!r}; y = {y!r}; z = {z!r}')\n x, y, z = sorted((x, y, z))\n print(f' Sorted: x = {x!r}; y = {y!r}; z = {z!r}')", "C++": "#include \n#include \n#include \n#include \n \ntemplate < class T >\nvoid sort3( T& x, T& y, T& z) {\n std::vector v{x, y, z};\n std::sort(v.begin(), v.end());\n x = v[0]; y = v[1]; z = v[2];\n}\nint main() {\n int xi = 77444, yi = -12, zi = 0;\n sort3( xi, yi, zi );\n std::cout << xi << \"\\n\" << yi << \"\\n\" << zi << \"\\n\\n\";\n \n std::string xs, ys, zs;\n xs = \"lions, tigers, and\";\n ys = \"bears, oh my!\";\n zs = \"(from the \\\"Wizard of OZ\\\")\";\n sort3( xs, ys, zs );\n std::cout << xs << \"\\n\" << ys << \"\\n\" << zs << \"\\n\\n\";\n \n float xf = 11.3f, yf = -9.7f, zf = 11.17f;\n sort3( xf, yf, zf );\n std::cout << xf << \"\\n\" << yf << \"\\n\" << zf << \"\\n\\n\";\n}"} +{"id": 13, "output": "#1 Beads falling down: \n\nBeads on their sides: 13 10 10 8 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n#2 Beads right side up: \nSorted list/array: 734 432 324 324 42 32 24 4 3 3 1 1 1 ", "Python": "from itertools import zip_longest\n\n# This is wrong, it works only on specific examples\ndef beadsort(l):\n return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n# Demonstration code:\nprint(beadsort([5,3,1,7,4,1,1]))", "C++": "#include \n#include \n\nusing std::cout;\nusing std::vector;\n\nvoid distribute(int dist, vector &List) {\n\t//*beads* go down into different buckets using gravity (addition).\n if (dist > List.size() )\n List.resize(dist); //resize if too big for current vector\n\n for (int i=0; i < dist; i++)\n List[i]++;\n}\n\nvector beadSort(int *myints, int n) {\n vector 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 //second part\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 sorted = beadSort(myints, sizeof(myints)/sizeof(int));\n\tcout << \"Sorted list/array: \";\n\tfor(unsigned int i=0; i\n#include \n#include \n#include \n\ntemplate \nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,\n Predicate p) {\n std::random_device rd;\n std::mt19937 generator(rd());\n while (!std::is_sorted(begin, end, p)) {\n std::shuffle(begin, end, generator);\n }\n}\n\ntemplate \nvoid bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n bogo_sort(\n begin, end,\n std::less<\n typename std::iterator_traits::value_type>());\n}\n\nint main() {\n int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n bogo_sort(std::begin(a), std::end(a));\n copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n}"} +{"id": 15, "output": "HaHaHaHaHa", "Python": "def repeat(s, times):\n return s * times\n\nprint(repeat(\"ha\", 5))", "C++": "#include \n#include \n\nstd::string repeat( const std::string &word, int times ) {\n std::string result ;\n result.reserve(times*word.length()); // avoid repeated reallocation\n for ( int a = 0 ; a < times ; a++ ) \n result += word ;\n return result ;\n}\n\nint main( ) {\n std::cout << repeat( \"Ha\" , 5 ) << std::endl ;\n return 0 ;\n}"} +{"id": 16, "output": "The smallest number is -10, the biggest 987!", "Python": "def addsub(x, y):\n return x + y, x - y\nsum, difference = addsub(33, 12)\nprint \"33 + 12 = %s\" % sum\nprint \"33 - 12 = %s\" % difference", "C++": "#include \n#include \n#include \n#include \n#include \n\nstd::tuple 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{{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}"} +{"id": 17, "output": "------------ Fire and Ice ----------\n\nSome say the world will end in fire,\nSome say in ice.\nFrom what I've tasted of desire\nI hold with those who favor fire.\n\n... last paragraph elided ...\n\n----------------------- Robert Frost\n---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------", "Python": "text = '''\\\n---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------'''\n\nfor line in text.split('\\n'): print(' '.join(line.split()[::-1]))", "C++": "#include \n#include \n#include \n#include \n#include \n\n//code for a C++11 compliant compiler\ntemplate \nvoid block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {\n std::reverse(first, last);\n auto block_last = first;\n do {\n using std::placeholders::_1;\n auto block_first = std::find_if_not(block_last, last, \n std::bind(std::equal_to(),_1, separator));\n block_last = std::find(block_first, last, separator);\n std::reverse(block_first, block_last);\n } while(block_last != last);\n}\n\n//code for a C++03 compliant compiler\ntemplate \nvoid block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {\n std::reverse(first, last);\n BidirectionalIterator block_last = first;\n do {\n BidirectionalIterator block_first = std::find_if(block_last, last, \n std::bind2nd(std::not_equal_to(), separator));\n block_last = std::find(block_first, last, separator);\n std::reverse(block_first, block_last);\n } while(block_last != last);\n}\n\nint main() {\n std::string str1[] = \n {\n \"---------- Ice and Fire ------------\",\n \"\",\n \"fire, in end will world the say Some\",\n \"ice. in say Some\",\n \"desire of tasted I've what From\",\n \"fire. favor who those with hold I\",\n \"\",\n \"... elided paragraph last ...\",\n \"\",\n \"Frost Robert -----------------------\"\n };\n\n std::for_each(begin(str1), end(str1), [](std::string& s){\n block_reverse_cpp11(begin(s), end(s), ' ');\n std::cout << s << std::endl;\n });\n \n std::for_each(begin(str1), end(str1), [](std::string& s){\n block_reverse_cpp03(begin(s), end(s), ' ');\n std::cout << s << std::endl;\n });\n\n return 0;\n}"} +{"id": 18, "output": "y( 0.0)\t= 1.000000 \t error: 0.000000e+00\ny( 1.0)\t= 1.562500 \t error: 1.457219e-07\ny( 2.0)\t= 3.999999 \t error: 9.194792e-07\ny( 3.0)\t= 10.562497 \t error: 2.909562e-06\ny( 4.0)\t= 24.999994 \t error: 6.234909e-06\ny( 5.0)\t= 52.562489 \t error: 1.081970e-05\ny( 6.0)\t= 99.999983 \t error: 1.659460e-05\ny( 7.0)\t= 175.562476 \t error: 2.351773e-05\ny( 8.0)\t= 288.999968 \t error: 3.156520e-05\ny( 9.0)\t= 451.562459 \t error: 4.072316e-05\ny(10.0)\t= 675.999949 \t error: 5.098329e-05", "Python": "from math import sqrt\n \ndef rk4(f, x0, y0, x1, n):\n vx = [0] * (n + 1)\n vy = [0] * (n + 1)\n h = (x1 - x0) / float(n)\n vx[0] = x = x0\n vy[0] = y = y0\n for i in range(1, n + 1):\n k1 = h * f(x, y)\n k2 = h * f(x + 0.5 * h, y + 0.5 * k1)\n k3 = h * f(x + 0.5 * h, y + 0.5 * k2)\n k4 = h * f(x + h, y + k3)\n vx[i] = x = x0 + i * h\n vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6\n return vx, vy\n \ndef f(x, y):\n return x * sqrt(y)\n \nvx, vy = rk4(f, 0, 1, 10, 100)\nfor x, y in list(zip(vx, vy))[::10]:\n print(\"%4.1f %10.5f %+12.4e\" % (x, y, y - (4 + x * x)**2 / 16))", "C++": "# include \n# include \n \nauto rk4(double f(double, double))\n{\n return [f](double t, double y, double dt) -> double {\n double dy1 { dt * f( t , y ) },\n dy2 { dt * f( t+dt/2, y+dy1/2 ) },\n dy3 { dt * f( t+dt/2, y+dy2/2 ) },\n dy4 { dt * f( t+dt , y+dy3 ) };\n return ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6;\n };\n}\n\nint main(void)\n{\n constexpr\n double TIME_MAXIMUM { 10.0 },\n T_START { 0.0 },\n Y_START { 1.0 },\n DT { 0.1 },\n WHOLE_TOLERANCE { 1e-12 };\n\n auto dy = rk4( [](double t, double y) -> double { return t*sqrt(y); } ) ;\n \n for (\n auto y { Y_START }, t { T_START };\n t <= TIME_MAXIMUM;\n y += dy(t,y,DT), t += DT\n )\n if (ceilf(t)-t < WHOLE_TOLERANCE)\n printf(\"y(%4.1f)\\t=%12.6f \\t error: %12.6e\\n\", t, y, std::fabs(y - pow(t*t+4,2)/16));\n \n return 0;\n}"} +{"id": 19, "output": "-199 -52 2 3 33 56 99 100 177 200 ", "Python": "def bubble_sort(seq):\n \"\"\"Inefficiently sort the mutable sequence (list) in place.\n seq MUST BE A MUTABLE SEQUENCE.\n\n As with list.sort() and random.shuffle this does NOT return \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 \"\"\"Sample usage and simple test suite\"\"\"\n\n from random import shuffle\n\n testset = [_ for _ in range(100)]\n testcase = testset.copy() # make a copy\n shuffle(testcase)\n assert testcase != testset # we've shuffled it\n bubble_sort(testcase)\n assert testcase == testset # we've unshuffled it back into a copy", "C++": "#include \n#include \n#include \n\ntemplate \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(std::cout, \" \"));\n std::cout << \"\\n\";\n}"} +{"id": 20, "output": "6 7 8 9 2 5 3 4 1 \n1 3 4 2 5 6 7 8 9 \n1 2 3 4 5 6 7 8 9 ", "Python": "def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':\n '''\n >>> L = [3, 2, 8, 28, 2,]\n >>> circle_sort(L)\n 3\n >>> print(L)\n [2, 2, 3, 8, 28]\n >>> L = [3, 2, 8, 28,]\n >>> circle_sort(L)\n 1\n >>> print(L)\n [2, 3, 8, 28]\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# more tests!\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)", "C++": "#include \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}"} +{"id": 21, "output": "before: 5 1 -6 12 3 13 2 4 0 15\nafter: -6 0 1 2 3 4 5 12 13 15", "Python": "def cocktailshiftingbounds(A):\n beginIdx = 0\n endIdx = len(A) - 1\n \n while beginIdx <= endIdx:\n newBeginIdx = endIdx\n newEndIdx = beginIdx\n for ii in range(beginIdx,endIdx):\n if A[ii] > A[ii + 1]:\n A[ii+1], A[ii] = A[ii], A[ii+1]\n newEndIdx = ii\n \n endIdx = newEndIdx\n \n for ii in range(endIdx,beginIdx-1,-1):\n if A[ii] > A[ii + 1]:\n A[ii+1], A[ii] = A[ii], A[ii+1]\n newBeginIdx = ii\n \n beginIdx = newBeginIdx + 1\n \ntest1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]\ncocktailshiftingbounds(test1)\nprint(test1)\n \ntest2=list('big fjords vex quick waltz nymph')\ncocktailshiftingbounds(test2)\nprint(''.join(test2))", "C++": "#include \n#include \n#include \n#include \n#include \n\n// This only works for random access iterators\ntemplate \nvoid cocktail_shaker_sort(iterator begin, iterator end) {\n if (begin == end)\n return;\n for (--end; begin < end; ) {\n iterator new_begin = end;\n iterator new_end = begin;\n for (iterator i = begin; i < end; ++i) {\n iterator j = i + 1;\n if (*j < *i) {\n std::iter_swap(i, j);\n new_end = i;\n }\n }\n end = new_end;\n for (iterator i = end; i > begin; --i) {\n iterator j = i - 1;\n if (*i < *j) {\n std::iter_swap(i, j);\n new_begin = i;\n }\n }\n begin = new_begin;\n }\n}\n\ntemplate \nvoid print(iterator begin, iterator end) {\n if (begin == end)\n return;\n std::cout << *begin++;\n while (begin != end)\n std::cout << ' ' << *begin++;\n std::cout << '\\n';\n}\n\nint main() {\n std::vector v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};\n std::cout << \"before: \";\n print(v.begin(), v.end());\n cocktail_shaker_sort(v.begin(), v.end());\n assert(std::is_sorted(v.begin(), v.end()));\n std::cout << \"after: \";\n print(v.begin(), v.end());\n return 0;\n}"} +{"id": 22, "output": "-199 -52 2 3 33 56 99 100 177 200 ", "Python": "def gnomesort(a):\n\ti,j,size = 1,2,len(a)\n\twhile i < size:\n\t\tif a[i-1] <= a[i]:\n\t\t\ti,j = j, j+1\n\t\telse:\n\t\t\ta[i-1],a[i] = a[i],a[i-1]\n\t\t\ti -= 1\n\t\t\tif i == 0:\n\t\t\t\ti,j = j, j+1\n\treturn a\ngnomesort([3,4,2,5,1,6])\n", "C++": "#include \n#include \n#include \n\ntemplate\nvoid gnome_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n auto i = begin + 1;\n auto j = begin + 2;\n \n while (i < end) {\n if (!(*i < *(i - 1))) {\n i = j;\n ++j;\n } else {\n std::iter_swap(i - 1, i);\n --i;\n if (i == begin) {\n i = j;\n ++j;\n }\n }\n }\n}\n\nint main() {\n int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n gnome_sort(std::begin(a), std::end(a));\n copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n}"} +{"id": 23, "output": "-199 -52 2 3 33 56 99 100 177 200 ", "Python": "def heapsort(lst):\n ''' Heapsort. Note: this function sorts in-place (it mutates the list). '''\n\n # in pseudo-code, heapify only called once, so inline it here\n for start in range((len(lst)-2)/2, -1, -1):\n siftdown(lst, start, len(lst)-1)\n\n for end in range(len(lst)-1, 0, -1):\n lst[end], lst[0] = lst[0], lst[end]\n siftdown(lst, 0, end - 1)\n return lst\n\ndef siftdown(lst, start, end):\n root = start\n while True:\n child = root * 2 + 1\n if child > end: break\n if child + 1 <= end and lst[child] < lst[child + 1]:\n child += 1\n if lst[root] < lst[child]:\n lst[root], lst[child] = lst[child], lst[root]\n root = child\n else:\n break", "C++": "#include \n#include \n#include \n\ntemplate\nvoid heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n std::make_heap(begin, end);\n std::sort_heap(begin, end);\n}\n\nint main() {\n int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};\n heap_sort(std::begin(a), std::end(a));\n copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n}"} +{"id": 24, "output": "-199 -52 2 3 33 56 99 100 177 200 ", "Python": "def insertion_sort(L):\n for i in xrange(1, len(L)):\n j = i-1 \n key = L[i]\n while j >= 0 and L[j] > key:\n L[j+1] = L[j]\n j -= 1\n L[j+1] = key", "C++": "#include \n#include \n#include \n\n// std::rotate is used to shift the sub-region\n// if the predicate p is true\ntemplate \nvoid insertion_sort(RandomAccessIterator begin, RandomAccessIterator end,\n Predicate p) {\n for (auto i = begin; i != end; ++i) {\n std::rotate(std::upper_bound(begin, i, *i, p), i, i + 1);\n }\n}\n\n// calls with default Predicate std::less (sort ascending)\ntemplate \nvoid insertion_sort(RandomAccessIterator begin, RandomAccessIterator end) {\n insertion_sort(begin, end, std::less::value_type>());\n}\n\n\nint main() {\n\n int a[] = { 100, 2, 56, 200, -52, 3, 99, 33, 177, -199 };\n\n insertion_sort(std::begin(a), std::end(a));\n\n // 'iterates' numbers to std::cout \n // converts ints to strings for output to screen\n copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, \" \"));\n \nstd::cout << \"\\n\";\n}"} +{"id": 25, "output": "4 10 11 15 14 16 17 1 6 9 3 7 19 2 0 12 5 18 13 8 \n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ", "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 # This indexed max needs moving\n if maxindex != 0:\n # Flip the max item to the left\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 # Flip it into its final position\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()\nif __name__ == '__main__':\n import random\n\n tutor = True\n data = list('123456789')\n while data == sorted(data):\n random.shuffle(data)\n print('Original List: %r' % ' '.join(data))\n pancakesort(data)\n print('Pancake Sorted List: %r' % ' '.join(data))", "C++": "#include \n#include \n#include \n#include \n\n// pancake sort template (calls predicate to determine order)\ntemplate \nvoid pancake_sort(BidIt first, BidIt last, Pred order)\n{\n if (std::distance(first, last) < 2) return; // no sort needed\n\n for (; first != last; --last)\n {\n BidIt mid = std::max_element(first, last, order);\n if (mid == last - 1)\n {\n continue; // no flips needed\n }\n if (first != mid)\n {\n std::reverse(first, mid + 1); // flip element to front\n }\n std::reverse(first, last); // flip front to final position\n }\n}\n\n// pancake sort template (ascending order)\ntemplate \nvoid pancake_sort(BidIt first, BidIt last)\n{\n pancake_sort(first, last, std::less::value_type>());\n}\n\nint main()\n{\n std::vector data;\n for (int i = 0; i < 20; ++i)\n {\n data.push_back(i); // generate test data\n }\n std::random_shuffle(data.begin(), data.end()); // scramble data\n\n std::copy(data.begin(), data.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n\n pancake_sort(data.begin(), data.end()); // ascending pancake sort\n\n std::copy(data.begin(), data.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << \"\\n\";\n}"} +{"id": 26, "output": "-31, 0, 1, 2, 4, 65, 83, 99, 782, ", "Python": "from functools import total_ordering\nfrom bisect import bisect_left\nfrom heapq import merge\n\n@total_ordering\nclass Pile(list):\n def __lt__(self, other): return self[-1] < other[-1]\n def __eq__(self, other): return self[-1] == other[-1]\n\ndef patience_sort(n):\n piles = []\n # sort into piles\n for x in n:\n new_pile = Pile([x])\n i = bisect_left(piles, new_pile)\n if i != len(piles):\n piles[i].append(x)\n else:\n piles.append(new_pile)\n\n # use a heap-based merge to merge piles efficiently\n n[:] = merge(*[reversed(pile) for pile in piles])\n\nif __name__ == \"__main__\":\n a = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n patience_sort(a)\n print a", "C++": "#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nstruct pile_less {\n bool operator()(const std::stack &pile1, const std::stack &pile2) const {\n return pile1.top() < pile2.top();\n }\n};\n\ntemplate \nstruct pile_greater {\n bool operator()(const std::stack &pile1, const std::stack &pile2) const {\n return pile1.top() > pile2.top();\n }\n};\n\n\ntemplate \nvoid patience_sort(Iterator first, Iterator last) {\n typedef typename std::iterator_traits::value_type E;\n typedef std::stack Pile;\n\n std::vector piles;\n // sort into piles\n for (Iterator it = first; it != last; it++) {\n E& x = *it;\n Pile newPile;\n newPile.push(x);\n typename std::vector::iterator i =\n std::lower_bound(piles.begin(), piles.end(), newPile, pile_less());\n if (i != piles.end())\n i->push(x);\n else\n piles.push_back(newPile);\n }\n\n // priority queue allows us to merge piles efficiently\n // we use greater-than comparator for min-heap\n std::make_heap(piles.begin(), piles.end(), pile_greater());\n for (Iterator it = first; it != last; it++) {\n std::pop_heap(piles.begin(), piles.end(), pile_greater());\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());\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(std::cout, \", \"));\n std::cout << std::endl;\n return 0;\n}"} +{"id": 27, "output": "-802 -90 2 24 45 66 75 170 ", "Python": "def flatten(some_list):\n \"\"\"\n Flatten a list of lists.\n Usage: flatten([[list a], [list b], ...])\n Output: [elements of list a, elements of list b]\n \"\"\"\n new_list = []\n for sub_list in some_list:\n new_list += sub_list\n return new_list\n\ndef radix(some_list, idex=None, size=None):\n \"\"\"\n Recursive radix sort\n Usage: radix([unsorted list])\n Output: [sorted list]\n \"\"\"\n # Initialize variables not set in the initial call\n if size == None:\n largest_num = max(some_list)\n largest_num_str = str(largest_num)\n largest_num_len = len(largest_num_str)\n size = largest_num_len\n\n if idex == None:\n idex = size\n\n # Translate the index we're looking at into an array index.\n # e.g., looking at the 10's place for 100:\n # size: 3\n # idex: 2\n # i: (3-2) == 1\n # str(123)[i] -> 2\n i = size - idex \n\n # The recursive base case.\n # Hint: out of range indexing errors\n if i >= size:\n return some_list\n\n # Initialize the bins we will place numbers into\n bins = [[] for _ in range(10)]\n\n # Iterate over the list of numbers we are given\n for e in some_list:\n # The destination bin; e.g.,:\n # size: 5\n # e: 29\n # num_s: '00029'\n # i: 3\n # dest_c: '2'\n # dest_i: 2\n num_s = str(e).zfill(size)\n dest_c = num_s[i]\n dest_i = int(dest_c) \n bins[dest_i] += [e]\n\n result = []\n for b in bins:\n #If the bin is empty it skips the recursive call\n if b == []:\n continue\n # Make the recursive call\n # Sort each of the sub-lists in our bins\n result.append(radix(b, idex-1, size))\n\n # Flatten our list\n # This is also called in our recursive call,\n # so we don't need flatten to be recursive.\n flattened_result = flatten(result)\n\n return flattened_result", "C++": "#include \n#include \n#include \n\n// Radix sort comparator for 32-bit two's complement integers\nclass radix_test\n{\n const int bit; // bit position [0..31] to examine\npublic:\n radix_test(int offset) : bit(offset) {} // constructor\n\n bool operator()(int value) const // function call operator\n {\n if (bit == 31) // sign bit\n return value < 0; // negative int to left partition\n else\n return !(value & (1 << bit)); // 0 bit to left partition\n }\n};\n\n// Least significant digit radix sort\nvoid lsd_radix_sort(int *first, int *last)\n{\n for (int lsb = 0; lsb < 32; ++lsb) // least-significant-bit\n {\n std::stable_partition(first, last, radix_test(lsb));\n }\n}\n\n// Most significant digit radix sort (recursive)\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--; // decrement most-significant-bit\n msd_radix_sort(first, mid, msb); // sort left partition\n msd_radix_sort(mid, last, msb); // sort right partition\n }\n}\n\n// test radix_sort\nint main()\n{\n int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };\n\n lsd_radix_sort(data, data + 8);\n // msd_radix_sort(data, data + 8);\n\n std::copy(data, data + 8, std::ostream_iterator(std::cout, \" \"));\n\n return 0;\n}"} +{"id": 28, "output": " sv :1\n sv2:1\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)) )", "C++": "#include \n\nstruct SpecialVariables\n{\n int i = 0;\n\n SpecialVariables& operator++()\n {\n // 'this' is a special variable that is a pointer to the current\n // class instance. It can optionally be used to refer to elements\n // of the class.\n this->i++; // has the same meaning as 'i++'\n\n // returning *this lets the object return a reference to itself\n return *this;\n }\n\n};\n\nint main()\n{\n SpecialVariables sv;\n auto sv2 = ++sv; // makes a copy of sv after it was incremented\n std::cout << \" sv :\" << sv.i << \"\\n sv2:\" << sv2.i << \"\\n\";\n}"} +{"id": 29, "output": "[ 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 Found 25 primes.", "Python": "def prime(a):\n return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))\n\ndef primes_below(n):\n return [i for i in range(n) if prime(i)]\nprimes_below(100)", "C++": "#include \n#include \n#include \n\nbool isPrime( unsigned u ) {\n if( u < 4 ) return u > 1;\n if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false;\n\n unsigned q = static_cast( sqrt( static_cast( u ) ) ),\n c = 5;\n while( c <= q ) {\n if( !( u % c ) || !( u % ( c + 2 ) ) ) return false;\n c += 6;\n }\n return true;\n}\nint main( int argc, char* argv[] )\n{\n unsigned mx = 100,\n wid = static_cast( log10( static_cast( mx ) ) ) + 1;\n\n std::cout << \"[\" << std::setw( wid ) << 2 << \" \";\n unsigned u = 3, p = 1; // <- start computing from 3\n while( u < mx ) {\n if( isPrime( u ) ) { std::cout << std::setw( wid ) << u << \" \"; p++; }\n u += 2;\n }\n std::cout << \"]\\n\\n Found \" << p << \" primes.\\n\\n\";\n return 0;\n}"} +{"id": 30, "output": "The first 15 terms of the sequence are:\n1 2 4 6 16 18 64 66 100 112 1024 1035 4096 4288 4624 \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)", "C++": "#include \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}"} +{"id": 31, "output": "The first 15 terms of the sequence are:\n1 2 4 6 16 12 64 24 36 48 1024 60 4096 192 144 ", "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)", "C++": "#include \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}"} +{"id": 32, "output": "(0, 1] \u222a [0, 2) contains 0 is true\n[0, 2) \u2229 (1, 2] contains 0 is false\n[0, 3) - (0, 1) contains 0 is true\n[0, 3) - [0, 1] contains 0 is false\n\n(0, 1] \u222a [0, 2) contains 1 is true\n[0, 2) \u2229 (1, 2] contains 1 is false\n[0, 3) - (0, 1) contains 1 is true\n[0, 3) - [0, 1] contains 1 is false\n\n(0, 1] \u222a [0, 2) contains 2 is false\n[0, 2) \u2229 (1, 2] contains 2 is false\n[0, 3) - (0, 1) contains 2 is true\n[0, 3) - [0, 1] contains 2 is true\n\n[0, 0] is empty is false\n\nApproximate length of A - B is 2.07587", "Python": "class Setr():\n def __init__(self, lo, hi, includelo=True, includehi=False):\n self.eqn = \"(%i<%sX<%s%i)\" % (lo,\n '=' if includelo else '',\n '=' if includehi else '',\n hi)\n\n def __contains__(self, X):\n return eval(self.eqn, locals())\n\n # union\n def __or__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sor%s)\" % (self.eqn, b.eqn)\n return ans\n\n # intersection\n def __and__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sand%s)\" % (self.eqn, b.eqn)\n return ans\n\n # difference\n def __sub__(self, b):\n ans = Setr(0,0)\n ans.eqn = \"(%sand not%s)\" % (self.eqn, b.eqn)\n return ans\n\n def __repr__(self):\n return \"Setr%s\" % self.eqn\n\n\nsets = [\n Setr(0,1, 0,1) | Setr(0,2, 1,0),\n Setr(0,2, 1,0) & Setr(1,2, 0,1),\n Setr(0,3, 1,0) - Setr(0,1, 0,0),\n Setr(0,3, 1,0) - Setr(0,1, 1,1),\n]\nsettexts = '(0, 1] \u222a [0, 2);[0, 2) \u2229 (1, 2];[0, 3) \u2212 (0, 1);[0, 3) \u2212 [0, 1]'.split(';')\n\nfor s,t in zip(sets, settexts):\n print(\"Set %s %s. %s\" % (t,\n ', '.join(\"%scludes %i\"\n % ('in' if v in s else 'ex', v)\n for v in range(3)),\n s.eqn))", "C++": "#include \n#include \n#include \n\n#define _USE_MATH_DEFINES\n#include \n\nenum RangeType {\n CLOSED,\n BOTH_OPEN,\n LEFT_OPEN,\n RIGHT_OPEN\n};\n\nclass RealSet {\nprivate:\n double low, high;\n double interval = 0.00001;\n std::function predicate;\n\npublic:\n RealSet(double low, double high, const std::function& predicate) {\n this->low = low;\n this->high = high;\n this->predicate = predicate;\n }\n\n RealSet(double start, double end, RangeType rangeType) {\n low = start;\n high = end;\n\n switch (rangeType) {\n case CLOSED:\n predicate = [start, end](double d) { return start <= d && d <= end; };\n break;\n case BOTH_OPEN:\n predicate = [start, end](double d) { return start < d && d < end; };\n break;\n case LEFT_OPEN:\n predicate = [start, end](double d) { return start < d && d <= end; };\n break;\n case RIGHT_OPEN:\n predicate = [start, end](double d) { return start <= d && d < end; };\n break;\n default:\n assert(!\"Unexpected range type encountered.\");\n }\n }\n\n bool contains(double d) const {\n return predicate(d);\n }\n\n RealSet unionSet(const RealSet& rhs) const {\n double low2 = fmin(low, rhs.low);\n double high2 = fmax(high, rhs.high);\n return RealSet(\n low2, high2,\n [this, &rhs](double d) { return predicate(d) || rhs.predicate(d); }\n );\n }\n\n RealSet intersect(const RealSet& rhs) const {\n double low2 = fmin(low, rhs.low);\n double high2 = fmax(high, rhs.high);\n return RealSet(\n low2, high2,\n [this, &rhs](double d) { return predicate(d) && rhs.predicate(d); }\n );\n }\n\n RealSet subtract(const RealSet& rhs) const {\n return RealSet(\n low, high,\n [this, &rhs](double d) { return predicate(d) && !rhs.predicate(d); }\n );\n }\n\n double length() const {\n if (isinf(low) || isinf(high)) return -1.0; // error value\n if (high <= low) return 0.0;\n\n double p = low;\n int count = 0;\n do {\n if (predicate(p)) count++;\n p += interval;\n } while (p < high);\n return count * interval;\n }\n\n bool empty() const {\n if (high == low) {\n return !predicate(low);\n }\n return length() == 0.0;\n }\n};\n\nint main() {\n using namespace std;\n\n RealSet a(0.0, 1.0, LEFT_OPEN);\n RealSet b(0.0, 2.0, RIGHT_OPEN);\n RealSet c(1.0, 2.0, LEFT_OPEN);\n RealSet d(0.0, 3.0, RIGHT_OPEN);\n RealSet e(0.0, 1.0, BOTH_OPEN);\n RealSet f(0.0, 1.0, CLOSED);\n RealSet g(0.0, 0.0, CLOSED);\n\n for (int i = 0; i <= 2; ++i) {\n cout << \"(0, 1] \u222a [0, 2) contains \" << i << \" is \" << boolalpha << a.unionSet(b).contains(i) << \"\\n\";\n cout << \"[0, 2) \u2229 (1, 2] contains \" << i << \" is \" << boolalpha << b.intersect(c).contains(i) << \"\\n\";\n cout << \"[0, 3) - (0, 1) contains \" << i << \" is \" << boolalpha << d.subtract(e).contains(i) << \"\\n\";\n cout << \"[0, 3) - [0, 1] contains \" << i << \" is \" << boolalpha << d.subtract(f).contains(i) << \"\\n\";\n cout << endl;\n }\n\n cout << \"[0, 0] is empty is \" << boolalpha << g.empty() << \"\\n\";\n cout << endl;\n\n RealSet aa(\n 0.0, 10.0,\n [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x * x)) > 0.5; }\n );\n RealSet bb(\n 0.0, 10.0,\n [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x)) > 0.5; }\n );\n auto cc = aa.subtract(bb);\n cout << \"Approximate length of A - B is \" << cc.length() << endl;\n\n return 0;\n}"} +{"id": 33, "output": "Hello , world!", "Python": "str = \"12345678\";\nstr += \"9!\";\nprint(str)", "C++": "#include \n#include \n\nint main( ) {\n std::string greeting( \"Hello\" ) ;\n greeting.append( \" , world!\" ) ;\n std::cout << greeting << std::endl ;\n return 0 ;\n}"} +{"id": 34, "output": "111 112 114 116 120 121 123 125 129 141\n143 147 149 161 165 167 202 203 205 207\n211 212 214 216 230 232 234 238 250 252\n256 258 292 294 298 302 303 305 307 320\n321 323 325 329 341 343 347 349 383 385\n389 411 412 414 416 430 432 434 438 470\n474 476 492 494 498 ", "Python": "def isStrangePlus(n):\n '''True all consecutive decimal digit\n pairs in n have prime sums.\n '''\n def test(a, b):\n return a + b in [2, 3, 5, 7, 11, 13, 17]\n\n xs = digits(n)\n return all(map(test, xs, xs[1:]))\n\n\n# ------------------- TEST AND DISPLAY -------------------\n# main :: IO ()\ndef main():\n '''List and count of Strange Plus Numbers'''\n\n xs = [\n n for n in range(100, 1 + 500)\n if isStrangePlus(n)\n ]\n print('\\n\"Strange Plus\" numbers in range [100..500]\\n')\n print('(Total: ' + str(len(xs)) + ')\\n')\n print(\n '\\n'.join(\n ' '.join(\n str(x) for x in row\n ) for row in chunksOf(10)(xs)\n )\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than 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# digits :: Int -> [Int]\ndef digits(n):\n '''Component digits of a decimal number.'''\n return [int(c) for c in str(n)]\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C++": "#include \n#include \n\nconst std::vector p{\n false, false, true, true, false,\n true, false, true, false, false,\n false, true, false, true, false,\n false, false, true, false\n};\n\nbool isStrange(long n) {\n if (n < 10) {\n return false;\n }\n for (; n >= 10; n /= 10) {\n if (!p[n % 10 + (n / 10) % 10]) {\n return false;\n }\n }\n return true;\n}\n\nvoid test(int nMin, int nMax) {\n int k = 0;\n\n for (long n = nMin; n <= nMax;n++) {\n if (isStrange(n)) {\n std::cout << n;\n if (++k % 10 != 0) {\n std::cout << ' ';\n } else {\n std::cout << '\\n';\n }\n }\n }\n}\n\nint main() {\n test(101, 499);\n return 0;\n}"} +{"id": 35, "output": "1.2.Foo and 1.3.Bar are not exactly lexically equal.\n1.2.Foo and 1.3.Bar are lexicallyinequal.\n1.2.Foo is lexically ordered before 1.3.Bar.\n1.2.Foo is not lexically ordered after 1.3.Bar.\n1.2.foo and 1.3.bar are not exactly lexically equal.\n1.2.foo and 1.3.bar are lexicallyinequal.\n1.2.foo is lexically ordered before 1.3.bar.\n1.2.foo is not lexically ordered after 1.3.bar.\n1.2 and 1.3 are not exactly numerically equal.\n1.2 and 1.3 are numericallyinequal.\n1.2 is numerically ordered before 1.3.\n1.2 is not numerically ordered after 1.3.", "Python": "def compare(a, b):\n print(\"\\n%r is of type %r and %r is of type %r\"\n % (a, type(a), b, type(b)))\n if a < b: print('%r is strictly less than %r' % (a, b))\n if a <= b: print('%r is less than or equal to %r' % (a, b))\n if a > b: print('%r is strictly greater than %r' % (a, b))\n if a >= b: print('%r is greater than or equal to %r' % (a, b))\n if a == b: print('%r is equal to %r' % (a, b))\n if a != b: print('%r is not equal to %r' % (a, b))\n if a is b: print('%r has object identity with %r' % (a, b))\n if a is not b: print('%r has negated object identity with %r' % (a, b))\n\ncompare('YUP', 'YUP')\ncompare('BALL', 'BELL')\ncompare('24', '123')\ncompare(24, 123)\ncompare(5.0, 5)", "C++": "#include \n#include \n#include \n#include \n\ntemplate \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 // Case-sensitive comparisons.\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(a, b, \"lexically\");\n\n // Case-insensitive comparisons by folding both strings to a common case.\n std::transform(a.begin(), a.end(), a.begin(), ::tolower);\n std::transform(b.begin(), b.end(), b.begin(), ::tolower);\n demo_compare(a, b, \"lexically\");\n\n // Numeric comparisons; here 'double' could be any type for which the\n // relevant >> operator is defined, eg int, long, etc.\n double numA, numB;\n std::istringstream(a) >> numA;\n std::istringstream(b) >> numB;\n demo_compare(numA, numB, \"numerically\");\n return (a == b);\n}"} +{"id": 36, "output": "Sh ws soul strppr. Sh took my hrt!", "Python": "import re\ndef stripchars(s, chars):\n\treturn re.sub('[%s]+' % re.escape(chars), '', s)\n\nstripchars(\"She was a soul stripper. She took my heart!\", \"aei\")", "C++": "#include \n#include \n#include \n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n str.erase(\n std::remove_if(str.begin(), str.end(), [&](char c){\n return chars.find(c) != std::string::npos;\n }),\n str.end()\n );\n return str;\n}\n\nint main()\n{\n std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n return 0;\n}"} +{"id": 37, "output": "alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate escritoire exorcism fiat filmy flatworm mincemeat plugging speakeasy\nalliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate escritoire exorcism infra isis mincemeat moresby mycenae smokescreen speakeasy\nalliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate escritoire fiat infra isis markham mincemeat plugging speakeasy\nalliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate exorcism fiat infra isis mincemeat moresby plugging vein\nalliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate exorcism fiat infra isis smokescreen", "Python": "words = { # some values are different from example\n\t\"alliance\": -624,\t\"archbishop\": -925,\t\"balm\":\t397,\n\t\"bonnet\": 452,\t\t\"brute\": 870,\t\t\"centipede\": -658,\n\t\"cobol\": 362,\t\t\"covariate\": 590,\t\"departure\": 952,\n\t\"deploy\": 44,\t\t\"diophantine\": 645,\t\"efferent\": 54,\n\t\"elysee\": -326,\t\t\"eradicate\": 376,\t\"escritoire\": 856,\n\t\"exorcism\": -983,\t\"fiat\": 170,\t\t\"filmy\": -874,\n\t\"flatworm\": 503,\t\"gestapo\": 915,\t\t\"infra\": -847,\n\t\"isis\": -982,\t\t\"lindholm\": 999,\t\"markham\": 475,\n\t\"mincemeat\": -880,\t\"moresby\": 756,\t\t\"mycenae\": 183,\n\t\"plugging\": -266,\t\"smokescreen\": 423,\t\"speakeasy\": -745,\n\t\"vein\": 813\n}\n\nneg = 0\npos = 0\nfor (w,v) in words.iteritems():\n\tif v > 0: pos += v\n\telse: neg += v\n\nsums = [0] * (pos - neg + 1)\n\nfor (w,v) in words.iteritems():\n\ts = sums[:]\n\tif not s[v - neg]: s[v - neg] = (w,)\n\n\tfor (i, w2) in enumerate(sums):\n\t\tif w2 and not s[i + v]:\n\t\t\ts[i + v] = w2 + (w,)\n\n\tsums = s\n\tif s[-neg]:\n\t\tfor x in s[-neg]:\n\t\t\tprint(x, words[x])\n\t\tbreak", "C++": "#include \n#include \n\nstd::ostream& operator<<(std::ostream& out, const std::string& str) {\n return out << str.c_str();\n}\n\nstd::vector> items{\n {\"alliance\", -624},\n {\"archbishop\", -915},\n {\"balm\", 397},\n {\"bonnet\", 452},\n {\"brute\", 870},\n {\"centipede\", -658},\n {\"cobol\", 362},\n {\"covariate\", 590},\n {\"departure\", 952},\n {\"deploy\", 44},\n {\"diophantine\", 645},\n {\"efferent\", 54},\n {\"elysee\", -326},\n {\"eradicate\", 376},\n {\"escritoire\", 856},\n {\"exorcism\", -983},\n {\"fiat\", 170},\n {\"filmy\", -874},\n {\"flatworm\", 503},\n {\"gestapo\", 915},\n {\"infra\", -847},\n {\"isis\", -982},\n {\"lindholm\", 999},\n {\"markham\", 475},\n {\"mincemeat\", -880},\n {\"moresby\", 756},\n {\"mycenae\", 183},\n {\"plugging\", -266},\n {\"smokescreen\", 423},\n {\"speakeasy\", -745},\n {\"vein\", 813},\n};\n\nstd::vector indices;\nint count = 0;\nconst int LIMIT = 5;\n\nvoid subsum(int i, int weight) {\n if (i != 0 && weight == 0) {\n for (int j = 0; j < i; ++j) {\n auto item = items[indices[j]];\n std::cout << (j ? \" \" : \"\") << item.first;\n }\n std::cout << '\\n';\n if (count < LIMIT) count++;\n else return;\n }\n int k = (i != 0) ? indices[i - 1] + 1 : 0;\n for (int j = k; j < items.size(); ++j) {\n indices[i] = j;\n subsum(i + 1, weight + items[j].second);\n if (count == LIMIT) return;\n }\n}\n\nint main() {\n indices.resize(items.size());\n subsum(0, 0);\n return 0;\n}"} +{"id": 38, "output": " * \n * * \n * * \n * * * * \n * * \n * * * * \n * * * * \n * * * * * * * * \n * * \n * * * * \n * * * * \n * * * * * * * * \n * * * * \n * * * * * * * * \n * * * * * * * * \n* * * * * * * * * * * * * * * *", "Python": "def sierpinski(n):\n d = [\"*\"]\n for i in xrange(n):\n sp = \" \" * (2 ** i)\n d = [sp+x+sp for x in d] + [x+\" \"+x for x in d]\n return d\n\nprint \"\\n\".join(sierpinski(4))", "C++": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ntemplate\nvoid sierpinski(int n, OutIt result)\n{\n if( n == 0 )\n {\n *result++ = \"*\";\n }\n else\n {\n list prev;\n sierpinski(n-1, back_inserter(prev));\n\n string sp(1 << (n-1), ' ');\n result = transform(prev.begin(), prev.end(),\n result,\n [sp](const string& x) { return sp + x + sp; });\n transform(prev.begin(), prev.end(),\n result,\n [sp](const string& x) { return x + \" \" + x; });\n }\n}\n\nint main()\n{\n sierpinski(4, ostream_iterator(cout, \"\\n\"));\n return 0;\n}"} +{"id": 39, "output": "Before: 1 2 3 4 5 6 7 8 9 \n After: 4 5 6 7 8 9 1 2 3 ", "Python": "from itertools import cycle, islice\n\n\n# rotated :: Int -> [a] -> [a]\ndef rotated(n):\n '''A list rotated n elements to the left.'''\n def go(xs):\n lng = len(xs)\n stream = cycle(xs)\n\n # (n modulo lng) elements dropped from the start,\n list(islice(stream, n % lng))\n\n # and lng elements drawn from the remaining cycle.\n return list(islice(stream, lng))\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Positive and negative (left and right)\n rotations tested for list and range inputs.\n '''\n xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n print(\"List rotated 3 positions to the left:\")\n print(\n rotated(3)(xs)\n )\n print(\"List rotated 3 positions to the right:\")\n print(\n rotated(-3)(xs)\n )\n print(\"\\nLists obtained by rotations of an input range:\")\n rng = range(1, 1 + 9)\n print(\n rotated(3)(rng)\n )\n print(\n rotated(-3)(rng)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "C++": "#include \n#include \n#include \n#include \n\ntemplate \nvoid print(const std::vector& v) {\n std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << '\\n';\n}\n\nint main() {\n std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9};\n std::cout << \"Before: \";\n print(vec);\n std::rotate(vec.begin(), vec.begin() + 3, vec.end());\n std::cout << \" After: \";\n print(vec);\n}"} +{"id": 0, "output": "original: [1, 2, 3, 4, 5, 6, 7, 8, 9]\nrotated: [4, 5, 6, 7, 8, 9, 1, 2, 3]", "Python": "from itertools import cycle, islice\n\n\n# rotated :: Int -> [a] -> [a]\ndef rotated(n):\n '''A list rotated n elements to the left.'''\n def go(xs):\n lng = len(xs)\n stream = cycle(xs)\n\n # (n modulo lng) elements dropped from the start,\n list(islice(stream, n % lng))\n\n # and lng elements drawn from the remaining cycle.\n return list(islice(stream, lng))\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Positive and negative (left and right)\n rotations tested for list and range inputs.\n '''\n xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n print(\"List rotated 3 positions to the left:\")\n print(\n rotated(3)(xs)\n )\n print(\"List rotated 3 positions to the right:\")\n print(\n rotated(-3)(xs)\n )\n print(\"\\nLists obtained by rotations of an input range:\")\n rng = range(1, 1 + 9)\n print(\n rotated(3)(rng)\n )\n print(\n rotated(-3)(rng)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "Java": "import java.util.List;\nimport java.util.Arrays;\nimport java.util.Collections;\n\npublic class RotateLeft {\n public static void main(String[] args) {\n List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);\n System.out.println(\"original: \" + list);\n Collections.rotate(list, -3);\n System.out.println(\"rotated: \" + list);\n }\n}"} +{"id": 1, "output": "sum = 15\nsum = 15\nproduct = 120", "Python": "from operator import mul, add\nsum = reduce(add, numbers) # note: this version doesn't work with empty lists\nsum = reduce(add, numbers, 0)\nproduct = reduce(mul, numbers) # note: this version doesn't work with empty lists\nproduct = reduce(mul, numbers, 1)", "Java": "import java.util.Arrays;\n\npublic class SumProd\n{\n public static void main(final String[] args)\n {\n int[] arg = {1,2,3,4,5};\n System.out.printf(\"sum = %d\\n\", Arrays.stream(arg).sum());\n System.out.printf(\"sum = %d\\n\", Arrays.stream(arg).reduce(0, (a, b) -> a + b));\n System.out.printf(\"product = %d\\n\", Arrays.stream(arg).reduce(1, (a, b) -> a * b));\n }\n}"} +{"id": 2, "output": "1\n15\n15\n29\n29\n90", "Python": "def sumDigits(num, base=10):\n if base < 2:\n print(\"Error: base must be at least 2\")\n return\n num, sum = abs(num), 0\n while num >= base:\n num, rem = divmod(num, base)\n sum += rem\n return sum + num\n\nprint(sumDigits(1))\nprint(sumDigits(12345))\nprint(sumDigits(-123045))\nprint(sumDigits(0xfe, 16))\nprint(sumDigits(0xf0e, 16))", "Java": "import java.math.BigInteger;\npublic class SumDigits {\n public static int sumDigits(long num) {\n\treturn sumDigits(num, 10);\n }\n public static int sumDigits(long num, int base) {\n\tString s = Long.toString(num, base);\n\tint result = 0;\n\tfor (int i = 0; i < s.length(); i++)\n\t result += Character.digit(s.charAt(i), base);\n\treturn result;\n }\n public static int sumDigits(BigInteger num) {\n\treturn sumDigits(num, 10);\n }\n public static int sumDigits(BigInteger num, int base) {\n\tString s = num.toString(base);\n\tint result = 0;\n\tfor (int i = 0; i < s.length(); i++)\n\t result += Character.digit(s.charAt(i), base);\n\treturn result;\n }\n\n public static void main(String[] args) {\n\tSystem.out.println(sumDigits(1));\n\tSystem.out.println(sumDigits(12345));\n\tSystem.out.println(sumDigits(123045));\n\tSystem.out.println(sumDigits(0xfe, 16));\n\tSystem.out.println(sumDigits(0xf0e, 16));\n\tSystem.out.println(sumDigits(new BigInteger(\"12345678901234567890\")));\n }\n}"} +{"id": 3, "output": "233168", "Python": "def sum35a(n):\n 'Direct count'\n # note: ranges go to n-1\n return sum(x for x in range(n) if x%3==0 or x%5==0)\n\ndef sum35b(n): \n \"Count all the 3's; all the 5's; minus double-counted 3*5's\"\n # note: ranges go to n-1\n return sum(range(3, n, 3)) + sum(range(5, n, 5)) - sum(range(15, n, 15))\n \ndef sum35c(n):\n 'Sum the arithmetic progressions: sum3 + sum5 - sum15'\n consts = (3, 5, 15)\n # Note: stop at n-1\n divs = [(n-1) // c for c in consts]\n sums = [d*c*(1+d)/2 for d,c in zip(divs, consts)]\n return sums[0] + sums[1] - sums[2]\n\n#test\nfor n in range(1001):\n sa, sb, sc = sum35a(n), sum35b(n), sum35c(n)\n assert sa == sb == sc # python tests aren't like those of c.\n\nprint('For n = %7i -> %i\\n' % (n, sc))\n\n# Pretty patterns\nfor p in range(7):\n print('For n = %7i -> %i' % (10**p, sum35c(10**p)))\n\n# Scalability \np = 20\nprint('\\nFor n = %20i -> %i' % (10**p, sum35c(10**p)))", "Java": "class SumMultiples {\n\tpublic static long getSum(long n) {\n\t\tlong sum = 0;\n\t\tfor (int i = 3; i < n; i++) {\n\t\t\tif (i % 3 == 0 || i % 5 == 0) sum += i;\n\t\t}\n\t\treturn sum;\n\t}\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(getSum(1000));\n\t}\n}"} +{"id": 4, "output": "Sum of divisors for the first 100 positive integers:\n 1 3 4 7 6 12 8 15 13 18\n 12 28 14 24 24 31 18 39 20 42\n 32 36 24 60 31 42 40 56 30 72\n 32 63 48 54 48 91 38 60 56 90\n 42 96 44 84 78 72 48 124 57 93\n 72 98 54 120 72 120 80 90 60 168\n 62 96 104 127 84 144 68 126 96 144\n 72 195 74 114 124 140 96 168 80 186\n 121 126 84 224 108 132 120 180 90 234\n 112 168 128 144 120 252 98 171 156 217", "Python": "def sum_of_divisors(n):\n assert(isinstance(n, int) and 0 < n)\n ans, i, j = 0, 1, 1\n while i*i <= n:\n if 0 == n%i:\n ans += i\n j = n//i\n if j != i:\n ans += j\n i += 1\n return ans\n \nif __name__ == \"__main__\":\n print([sum_of_divisors(n) for n in range(1,101)])", "Java": "public class DivisorSum {\n private static long divisorSum(long n) {\n var total = 1L;\n var power = 2L;\n // Deal with powers of 2 first\n for (; (n & 1) == 0; power <<= 1, n >>= 1) {\n total += power;\n }\n // Odd prime factors up to the square root\n for (long p = 3; p * p <= n; p += 2) {\n long sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p) {\n sum += power;\n }\n total *= sum;\n }\n // If n > 1 then it's prime\n if (n > 1) {\n total *= n + 1;\n }\n return total;\n }\n\n public static void main(String[] args) {\n final long limit = 100;\n System.out.printf(\"Sum of divisors for the first %d positive integers:%n\", limit);\n for (long n = 1; n <= limit; ++n) {\n System.out.printf(\"%4d\", divisorSum(n));\n if (n % 10 == 0) {\n System.out.println();\n }\n }\n }\n}"} +{"id": 5, "output": "The sum of the squares is: 55.0", "Python": "sum(x * x for x in [1, 2, 3, 4, 5])\n# or\nsum(x ** 2 for x in [1, 2, 3, 4, 5])\n# or\nsum(pow(x, 2) for x in [1, 2, 3, 4, 5])", "Java": "public class SumSquares\n{\n public static void main(final String[] args)\n {\n double sum = 0;\n int[] nums = {1,2,3,4,5};\n for (int i : nums)\n sum += i * i;\n System.out.println(\"The sum of the squares is: \" + sum);\n }\n}"} +{"id": 6, "output": "49.0\n<5.0, 5.0, -7.0>\n6.0\n<-267.0, 204.0, -3.0>\n", "Python": "def crossp(a, b):\n '''Cross product of two 3D vectors'''\n assert len(a) == len(b) == 3, 'For 3D vectors only'\n a1, a2, a3 = a\n b1, b2, b3 = b\n return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)\n \ndef dotp(a,b):\n '''Dot product of two eqi-dimensioned vectors'''\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n \ndef scalartriplep(a, b, c):\n '''Scalar triple product of three vectors: \"a . (b x c)\"'''\n return dotp(a, crossp(b, c))\n \ndef vectortriplep(a, b, c):\n '''Vector triple product of three vectors: \"a x (b x c)\"'''\n return crossp(a, crossp(b, c))\n \nif __name__ == '__main__':\n a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)\n print(\"a = %r; b = %r; c = %r\" % (a, b, c))\n print(\"a . b = %r\" % dotp(a,b))\n print(\"a x b = %r\" % (crossp(a,b),))\n print(\"a . (b x c) = %r\" % scalartriplep(a, b, c))\n print(\"a x (b x c) = %r\" % (vectortriplep(a, b, c),))", "Java": "public class VectorProds{\n public static class Vector3D{\n private T a, b, c;\n\n public Vector3D(T a, T b, T c){\n this.a = a;\n this.b = b;\n this.c = c;\n }\n\n public double dot(Vector3D vec){\n return (a.doubleValue() * vec.a.doubleValue() +\n b.doubleValue() * vec.b.doubleValue() +\n c.doubleValue() * vec.c.doubleValue());\n }\n\n public Vector3D cross(Vector3D vec){\n Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue();\n Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue();\n Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue();\n return new Vector3D(newA, newB, newC);\n }\n\n public double scalTrip(Vector3D vecB, Vector3D vecC){\n return this.dot(vecB.cross(vecC));\n }\n\n public Vector3D vecTrip(Vector3D vecB, Vector3D vecC){\n return this.cross(vecB.cross(vecC));\n }\n\n @Override\n public String toString(){\n return \"<\" + a.toString() + \", \" + b.toString() + \", \" + c.toString() + \">\";\n }\n }\n\n public static void main(String[] args){\n Vector3D a = new Vector3D(3, 4, 5);\n Vector3D b = new Vector3D(4, 3, 5);\n Vector3D c = new Vector3D(-5, -12, -13);\n\n System.out.println(a.dot(b));\n System.out.println(a.cross(b));\n System.out.println(a.scalTrip(b, c));\n System.out.println(a.vecTrip(b, c));\n }\n}"} +{"id": 7, "output": "Left Truncatable : 998443\nRight Truncatable : 739399", "Python": "maxprime = 1000000\n\ndef primes(n):\n multiples = set()\n prime = []\n for i in range(2, n+1):\n if i not in multiples:\n prime.append(i)\n multiples.update(set(range(i*i, n+1, i)))\n return prime\n\ndef truncatableprime(n):\n 'Return a longest left and right truncatable primes below n'\n primelist = [str(x) for x in primes(n)[::-1]]\n primeset = set(primelist)\n for n in primelist:\n # n = 'abc'; [n[i:] for i in range(len(n))] -> ['abc', 'bc', 'c']\n alltruncs = set(n[i:] for i in range(len(n)))\n if alltruncs.issubset(primeset):\n truncateleft = int(n)\n break\n for n in primelist:\n # n = 'abc'; [n[:i+1] for i in range(len(n))] -> ['a', 'ab', 'abc']\n alltruncs = set([n[:i+1] for i in range(len(n))])\n if alltruncs.issubset(primeset):\n truncateright = int(n)\n break\n return truncateleft, truncateright\n\nprint(truncatableprime(maxprime))", "Java": "import java.util.BitSet;\n\npublic class Main {\n\n\tpublic static void main(String[] args){\n\n\t\tfinal int MAX = 1000000;\n\n\t\t//Sieve of Eratosthenes (using BitSet only for odd numbers)\n\t\tBitSet primeList = new BitSet(MAX>>1); \n\t\tprimeList.set(0,primeList.size(),true); \n\n\t\tint sqroot = (int) Math.sqrt(MAX); \n\t\tprimeList.clear(0); \n\t\tfor(int num = 3; num <= sqroot; num+=2) \n\t\t{ \n\t\t\tif( primeList.get(num >> 1) ) \n\t\t\t{ \n\t\t\t\tint inc = num << 1;\n\t\t\t\tfor(int factor = num * num; factor < MAX; factor += inc) \n\t\t\t\t{ \n\t\t\t\t\t//if( ((factor) & 1) == 1) \n\t\t\t\t\t//{ \n\t\t\t\t\tprimeList.clear(factor >> 1); \n\t\t\t\t\t//} \n\t\t\t\t} \n\t\t\t} \n\t\t}\n\t\t//Sieve ends...\n\n\t\t//Find Largest Truncatable Prime. (so we start from 1000000 - 1\n\t\tint rightTrunc = -1, leftTrunc = -1;\n\t\tfor(int prime = (MAX - 1) | 1; prime >= 3; prime -= 2)\n\t\t{\n\t\t\tif(primeList.get(prime>>1))\n\t\t\t{\n\t\t\t\t//Already found Right Truncatable Prime?\n\t\t\t\tif(rightTrunc == -1)\n\t\t\t\t{\n\t\t\t\t\tint right = prime;\n\t\t\t\t\twhile(right > 0 && right % 2 != 0 && primeList.get(right >> 1)) right /= 10;\n\t\t\t\t\tif(right == 0) rightTrunc = prime;\n\t\t\t\t}\n\n\t\t\t\t//Already found Left Truncatable Prime?\n\t\t\t\tif(leftTrunc == -1 )\n\t\t\t\t{\n\t\t\t\t\t//Left Truncation\n\t\t\t\t\tString left = Integer.toString(prime);\n\t\t\t\t\tif(!left.contains(\"0\"))\n\t\t\t\t\t{\n\t\t\t\t\t\twhile( left.length() > 0 ){\n\t\t\t\t\t\t\tint iLeft = Integer.parseInt(left);\n\t\t\t\t\t\t\tif(!primeList.get( iLeft >> 1)) break;\n\t\t\t\t\t\t\tleft = left.substring(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(left.length() == 0) leftTrunc = prime;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(leftTrunc != -1 && rightTrunc != -1) //Found both? then Stop loop\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(\"Left Truncatable : \" + leftTrunc);\n\t\tSystem.out.println(\"Right Truncatable : \" + rightTrunc);\n\t}\n}"} +{"id": 8, "output": "1 3 4 6 7 11 \n\n1 Solutions found.", "Python": "from itertools import product\n#from pprint import pprint as pp\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)", "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}"} +{"id": 9, "output": "[-6, -5, -2, 1, 3, 3, 4, 5, 7, 10]", "Python": "data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]\ndef 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\nstoogesort(data)", "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}"} +{"id": 10, "output": "The first 100 tau numbers are:\n 1 2 8 9 12 18 24 36 40 56\n 60 72 80 84 88 96 104 108 128 132\n 136 152 156 180 184 204 225 228 232 240\n 248 252 276 288 296 328 344 348 360 372\n 376 384 396 424 441 444 448 450 468 472\n 480 488 492 504 516 536 560 564 568 584\n 600 612 625 632 636 640 664 672 684 708\n 712 720 732 776 792 804 808 824 828 852\n 856 864 872 876 880 882 896 904 936 948\n 972 996 1016 1040 1044 1048 1056 1068 1089 1096", "Python": "def tau(n):\n assert(isinstance(n, int) and 0 < n)\n ans, i, j = 0, 1, 1\n while i*i <= n:\n if 0 == n%i:\n ans += 1\n j = n//i\n if j != i:\n ans += 1\n i += 1\n return ans\n\ndef is_tau_number(n):\n assert(isinstance(n, int))\n if n <= 0:\n return False\n return 0 == n%tau(n)\n\nif __name__ == \"__main__\":\n n = 1\n ans = []\n while len(ans) < 100:\n if is_tau_number(n):\n ans.append(n)\n n += 1\n print(ans)", "Java": "public class Tau {\n private static long divisorCount(long n) {\n long total = 1;\n // Deal with powers of 2 first\n for (; (n & 1) == 0; n >>= 1) {\n ++total;\n }\n // Odd prime factors up to the square root\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 // If n > 1 then it's prime\n if (n > 1) {\n total *= 2;\n }\n return total;\n }\n\n public static void main(String[] args) {\n final long limit = 100;\n System.out.printf(\"The first %d tau numbers are:%n\", limit);\n long count = 0;\n for (long n = 1; count < limit; ++n) {\n if (n % divisorCount(n) == 0) {\n System.out.printf(\"%6d\", n);\n ++count;\n if (count % 10 == 0) {\n System.out.println();\n }\n }\n }\n }\n}"} +{"id": 11, "output": "[1, 3]", "Python": "from itertools import (product)\n\n\n# sumTwo :: [Int] -> Int -> [(Int, Int)]\ndef sumTwo(xs):\n '''All the pairs of integers in xs which\n sum to n.\n '''\n def go(n):\n ixs = list(enumerate(xs))\n return [\n (fst(x), fst(y)) for (x, y) in (\n product(ixs, ixs[1:])\n ) if fst(x) < fst(y) and n == snd(x) + snd(y)\n ]\n return lambda n: go(n)\n\n\n# TEST ----------------------------------------------------\n\n# main :: IO ()\ndef main():\n '''Tests'''\n\n xs = [0, 2, 11, 19, 90, 10]\n\n print(\n fTable(\n 'The indices of any two integers drawn from ' + repr(xs) +\n '\\nthat sum to a given value:\\n'\n )(str)(\n lambda x: str(x) + ' = ' + ', '.join(\n ['(' + str(xs[a]) + ' + ' + str(xs[b]) + ')' for a, b in x]\n ) if x else '(none)'\n )(\n sumTwo(xs)\n )(enumFromTo(10)(25))\n )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\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# MAIN ---\nif __name__ == '__main__':\n main()", "Java": "import java.util.Arrays;\n\npublic class TwoSum {\n\n public static void main(String[] args) {\n long sum = 21;\n int[] arr = {0, 2, 11, 19, 90};\n\n System.out.println(Arrays.toString(twoSum(arr, sum)));\n }\n\n public static int[] twoSum(int[] a, long target) {\n int i = 0, j = a.length - 1;\n while (i < j) {\n long sum = a[i] + a[j];\n if (sum == target)\n return new int[]{i, j};\n if (sum < target) i++;\n else j--;\n }\n return null;\n }\n}"} +{"id": 12, "output": "[7, 6, 5, 4, 3, 2, 1, 0]\n[7, 0, 5, 4, 3, 2, 1, 6]", "Python": "def disjointSort(ixs):\n '''A copy of the list xs, in which the disjoint sublist\n of items at zero-based indexes ixs is sorted in a\n default numeric or lexical order.'''\n def go(xs):\n ks = sorted(ixs)\n dct = dict(zip(ks, sorted(xs[k] for k in ks)))\n return [\n dct[i] if i in dct else x \n for i, x in enumerate(xs)\n ]\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Disjoint sublist at three indices.'''\n print(\n tabulated(\n 'Disjoint sublist at indices [6, 1, 7] sorted:\\n'\n )\n (str)(str)(\n disjointSort([6, 1, 7])\n )([\n [7, 6, 5, 4, 3, 2, 1, 0],\n ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']\n ])\n )\n\n\n# ------------------------ DISPLAY -------------------------\n\n# tabulated :: String -> (a -> String) ->\n# (b -> String) ->\n# (a -> b) -> [a] -> String\ndef tabulated(s):\n '''Heading -> x display function -> fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join(\n xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n )\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\nif __name__ == '__main__':\n main()", "Java": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Disjoint {\n public static > void sortDisjoint(\n List array, int[] idxs) {\n Arrays.sort(idxs);\n List disjoint = new ArrayList();\n for (int idx : idxs) {\n disjoint.add(array.get(idx));\n }\n Collections.sort(disjoint);\n int i = 0;\n for (int idx : idxs) {\n array.set(idx, disjoint.get(i++));\n }\n }\n\n public static void main(String[] args) {\n List list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0);\n int[] indices = {6, 1, 7};\n System.out.println(list);\n sortDisjoint(list, indices);\n System.out.println(list);\n }\n}"} +{"id": 13, "output": "p( 1) = 0 p( 2) = 1 p( 3) = 3 p( 4) = 4 p( 5) = 5 \np( 6) = 7 p( 7) = 8 p( 8) = 9 p( 9) = 10 p(10) = 11 \np(11) = 13 p(12) = 14 p(13) = 15 p(14) = 16 p(15) = 17 \np(16) = 18 p(17) = 19 p(18) = 20 p(19) = 21 p(20) = 23 ", "Python": "import 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 \"\"\"Flip the stack of pancakes at the given position.\"\"\"\n return tuple([*reversed(pancakes[:position]), *pancakes[position:]])\n\n\ndef pancake(n: int) -> Tuple[Pancakes, int]:\n \"\"\"Return the nth pancake number.\"\"\"\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.\")", "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}"} +{"id": 14, "output": " n Motzkin[n]\n-----------------------------\n 0 1\n 1 1\n 2 2 prime\n 3 4\n 4 9\n 5 21\n 6 51\n 7 127 prime\n 8 323\n 9 835", "Python": "from sympy import isprime\n\n\ndef motzkin(num_wanted):\n \"\"\" Return list of the first N Motzkin numbers \"\"\"\n mot = [1] * (num_wanted + 1)\n for i in range(2, num_wanted + 1):\n mot[i] = (mot[i-1]*(2*i+1) + mot[i-2]*(3*i-3)) // (i + 2)\n return mot\n\n\ndef print_motzkin_table(N=41):\n \"\"\" Print table of first N Motzkin numbers, and note if prime \"\"\"\n print(\n \" n M[n] Prime?\\n-----------------------------------\")\n for i, e in enumerate(motzkin(N)):\n print(f'{i : 3}{e : 24,}', isprime(e))\n\n\nprint_motzkin_table()", "Java": "import java.math.BigInteger;\nimport java.text.NumberFormat;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n\npublic final class MotzkinNumbers {\n\n\tpublic static void main(String[] aArgs) {\n\t\tfinal int count = 42;\n\t\tList motzkins = motzkinNumbers(count);\n\t\t\n\t\tNumberFormat ukNumberFormat = NumberFormat.getInstance(Locale.UK);\n\t\t\n\t System.out.println(\" n Motzkin[n]\");\n\t System.out.println(\"-----------------------------\");\n\t \n\t for ( int n = 0; n < count; n++ ) {\n\t \tBigInteger motzkin = motzkins.get(n);\n\t \tboolean prime = motzkin.isProbablePrime(PROBABILITY);\n\t \tSystem.out.print(String.format(\"%2d %23s\", n, ukNumberFormat.format(motzkin)));\t \t\n\t \tSystem.out.println( prime ? \" prime\" : \"\" );\t \n\t }\n\t}\n\t\n\tprivate static List motzkinNumbers(int aSize) {\n\t\tList result = new ArrayList(aSize);\n\t\tresult.add(BigInteger.ONE);\n\t\tresult.add(BigInteger.ONE);\n\t\tfor ( int i = 2; i < aSize; i++ ) {\n\t\t\tBigInteger nextMotzkin = result.get(i - 1).multiply(BigInteger.valueOf(2 * i + 1))\n\t\t\t\t.add(result.get(i - 2).multiply(BigInteger.valueOf(3 * i - 3)))\n\t\t\t\t.divide(BigInteger.valueOf(i + 2));\n\t\t\t\n\t\t\tresult.add(nextMotzkin);\n\t\t}\n\n\t\treturn result;\t\t\n\t}\n\t\n\tprivate static final int PROBABILITY = 20;\n\n}"} +{"id": 15, "output": "\n\n32 13 34 29 24 15 26 1 \n35 64 31 14 37 28 23 16 \n12 33 36 61 30 25 2 27 \n63 60 55 38 49 40 17 22 \n54 11 62 41 56 21 48 3 \n59 8 53 50 39 42 45 18 \n10 51 6 57 20 47 4 43 \n 7 58 9 52 5 44 19 46 ", "Python": "import copy\n\nboardsize=6\n_kmoves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)) \n\n\ndef chess2index(chess, boardsize=boardsize):\n 'Convert Algebraic chess notation to internal index format'\n chess = chess.strip().lower()\n x = ord(chess[0]) - ord('a')\n y = boardsize - int(chess[1:])\n return (x, y)\n \ndef boardstring(board, boardsize=boardsize):\n r = range(boardsize)\n lines = ''\n for y in r:\n lines += '\\n' + ','.join('%2i' % board[(x,y)] if board[(x,y)] else ' '\n for x in r)\n return lines\n \ndef knightmoves(board, P, boardsize=boardsize):\n Px, Py = P\n kmoves = set((Px+x, Py+y) for x,y in _kmoves)\n kmoves = set( (x,y)\n for x,y in kmoves\n if 0 <= x < boardsize\n and 0 <= y < boardsize\n and not board[(x,y)] )\n return kmoves\n\ndef accessibility(board, P, boardsize=boardsize):\n access = []\n brd = copy.deepcopy(board)\n for pos in knightmoves(board, P, boardsize=boardsize):\n brd[pos] = -1\n access.append( (len(knightmoves(brd, pos, boardsize=boardsize)), pos) )\n brd[pos] = 0\n return access\n \ndef knights_tour(start, boardsize=boardsize, _debug=False):\n board = {(x,y):0 for x in range(boardsize) for y in range(boardsize)}\n move = 1\n P = chess2index(start, boardsize)\n board[P] = move\n move += 1\n if _debug:\n print(boardstring(board, boardsize=boardsize))\n while move <= len(board):\n P = min(accessibility(board, P, boardsize))[1]\n board[P] = move\n move += 1\n if _debug:\n print(boardstring(board, boardsize=boardsize))\n input('\\n%2i next: ' % move)\n return board\n\nif __name__ == '__main__':\n while 1:\n boardsize = int(input('\\nboardsize: '))\n if boardsize < 5:\n continue\n start = input('Start position: ')\n board = knights_tour(start, boardsize)\n print(boardstring(board, boardsize=boardsize))", "Java": "import java.util.*;\n\npublic class KnightsTour {\n private final static int base = 12;\n private final static int[][] moves = {{1,-2},{2,-1},{2,1},{1,2},{-1,2},\n {-2,1},{-2,-1},{-1,-2}};\n private static int[][] grid;\n private static int total;\n\n public static void main(String[] args) {\n grid = new int[base][base];\n total = (base - 4) * (base - 4);\n\n for (int r = 0; r < base; r++)\n for (int c = 0; c < base; c++)\n if (r < 2 || r > base - 3 || c < 2 || c > base - 3)\n grid[r][c] = -1;\n\n int row = 2 + (int) (Math.random() * (base - 4));\n int col = 2 + (int) (Math.random() * (base - 4));\n\n grid[row][col] = 1;\n\n if (solve(row, col, 2))\n printResult();\n else System.out.println(\"no result\");\n\n }\n\n private static boolean solve(int r, int c, int count) {\n if (count > total)\n return true;\n\n List nbrs = neighbors(r, c);\n\n if (nbrs.isEmpty() && count != total)\n return false;\n\n Collections.sort(nbrs, new Comparator() {\n public int compare(int[] a, int[] b) {\n return a[2] - b[2];\n }\n });\n\n for (int[] nb : nbrs) {\n r = nb[0];\n c = nb[1];\n grid[r][c] = count;\n if (!orphanDetected(count, r, c) && solve(r, c, count + 1))\n return true;\n grid[r][c] = 0;\n }\n\n return false;\n }\n\n private static List neighbors(int r, int c) {\n List 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);\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 boolean orphanDetected(int cnt, int r, int c) {\n if (cnt < total - 1) {\n List nbrs = neighbors(r, c);\n for (int[] nb : nbrs)\n if (countNeighbors(nb[0], nb[1]) == 0)\n return true;\n }\n return false;\n }\n\n private static void printResult() {\n for (int[] row : grid) {\n for (int i : row) {\n if (i == -1) continue;\n System.out.printf(\"%2d \", i);\n }\n System.out.println();\n }\n }\n}"} +{"id": 16, "output": "[30006, 29705, 30049, 29947, 30327, 30225, 29873, 29817, 29994, 30057]", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n sample, i = [], 0\n def s_of_n(item):\n nonlocal i\n\n i += 1\n if i <= n:\n # Keep first n items\n sample.append(item)\n elif randrange(i) < n:\n # Keep item\n sample[randrange(n)] = item\n return sample\n return s_of_n\n\nif __name__ == '__main__':\n bin = [0]* 10\n items = range(10)\n print(\"Single run samples for n = 3:\")\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n print(\" Item: %i -> sample: %s\" % (item, sample))\n #\n for trial in range(100000):\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n for s in sample:\n bin[s] += 1\n print(\"\\nTest item frequencies for 100000 runs:\\n \",\n '\\n '.join(\"%i:%i\" % x for x in enumerate(bin)))", "Java": "import java.util.*;\n \nclass SOfN {\n private static final Random rand = new Random();\n \n private List sample;\n private int i = 0;\n private int n;\n\n public SOfN(int _n) {\n n = _n;\n sample = new ArrayList(n);\n }\n\n public List process(T item) {\n if (++i <= n) {\n sample.add(item);\n } else if (rand.nextInt(i) < n) {\n sample.set(rand.nextInt(n), item);\n }\n return sample;\n }\n}\n \npublic class AlgorithmS {\n public static void main(String[] args) {\n int[] bin = new int[10];\n for (int trial = 0; trial < 100000; trial++) {\n SOfN s_of_n = new SOfN(3);\n for (int i = 0; i < 9; i++) s_of_n.process(i);\n for (int s : s_of_n.process(9)) bin[s]++;\n }\n System.out.println(Arrays.toString(bin));\n }\n}"} +{"id": 17, "output": "998764543431\n6054854654", "Python": "try:\n cmp # Python 2 OK or NameError in Python 3\n def maxnum(x):\n return ''.join(sorted((str(n) for n in x),\n cmp=lambda x,y:cmp(y+x, x+y)))\nexcept NameError:\n # Python 3\n from functools import cmp_to_key\n def cmp(x, y):\n return -1 if x sorter = new Comparator(){\n @Override\n public int compare(Integer o1, Integer o2){\n String o1s = o1.toString();\n String o2s = o2.toString();\n \n if(o1s.length() == o2s.length()){\n return o2s.compareTo(o1s);\n }\n\n int mlen = Math.max(o1s.length(), o2s.length());\n while(o1s.length() < mlen * 2) o1s += o1s;\n while(o2s.length() < mlen * 2) o2s += o2s;\n \n return o2s.compareTo(o1s);\n }\n };\n \n public static String join(List things){\n String output = \"\";\n for(Object obj:things){\n output += obj;\n }\n return output;\n }\n \n public static void main(String[] args){\n List ints1 = new ArrayList(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4));\n \n Collections.sort(ints1, sorter);\n System.out.println(join(ints1));\n \n List ints2 = new ArrayList(Arrays.asList(54, 546, 548, 60));\n \n Collections.sort(ints2, sorter);\n System.out.println(join(ints2));\n }\n}"} +{"id": 18, "output": "Max side length 13, formula: a*a + b*b = c*c\n (4, 3, 5)\n (8, 6, 10)\n (12, 5, 13)\n3 triangles\nMax side length 13, formula: a*a + b*b - a*b = c*c\n (1, 1, 1)\n (2, 2, 2)\n (3, 3, 3)\n (4, 4, 4)\n (5, 5, 5)\n (6, 6, 6)\n (7, 7, 7)\n (8, 3, 7)\n (8, 5, 7)\n (8, 8, 8)\n (9, 9, 9)\n (10, 10, 10)\n (11, 11, 11)\n (12, 12, 12)\n (13, 13, 13)\n15 triangles\nMax side length 13, formula: a*a + b*b + a*b = c*c\n (5, 3, 7)\n (8, 7, 13)\n2 triangles\n\nExtra Credit.\nMax side length 100, sides different length, formula: a*a + b*b - a*b = c*c\n70 triangles", "Python": "N = 13\n\ndef method1(N=N):\n squares = [x**2 for x in range(0, N+1)]\n sqrset = set(squares)\n tri90, tri60, tri120 = (set() for _ in range(3))\n for a in range(1, N+1):\n a2 = squares[a]\n for b in range(1, a + 1):\n b2 = squares[b]\n c2 = a2 + b2\n if c2 in sqrset:\n tri90.add(tuple(sorted((a, b, int(c2**0.5)))))\n ab = a * b\n c2 -= ab\n if c2 in sqrset:\n tri60.add(tuple(sorted((a, b, int(c2**0.5)))))\n c2 += 2 * ab\n if c2 in sqrset:\n tri120.add(tuple(sorted((a, b, int(c2**0.5)))))\n return sorted(tri90), sorted(tri60), sorted(tri120)\n#%%\nif __name__ == '__main__':\n print(f'Integer triangular triples for sides 1..{N}:')\n for angle, triples in zip([90, 60, 120], method1(N)):\n print(f' {angle:3}\u00b0 has {len(triples)} solutions:\\n {triples}')\n _, t60, _ = method1(10_000)\n notsame = sum(1 for a, b, c in t60 if a != b or b != c)\n print('Extra credit:', notsame)", "Java": "public class LawOfCosines {\n\n public static void main(String[] args) {\n generateTriples(13);\n generateTriples60(100);\n }\n \n private static void generateTriples(int max) {\n for ( int coeff : new int[] {0, -1, 1} ) {\n int count = 0;\n System.out.printf(\"Max side length %d, formula: a*a + b*b %s= c*c%n\", max, coeff == 0 ? \"\" : (coeff<0 ? \"-\" : \"+\") + \" a*b \");\n for ( int a = 1 ; a <= max ; a++ ) {\n for ( int b = 1 ; b <= a ; b++ ) {\n int val = a*a + b*b + coeff*a*b;\n int c = (int) (Math.sqrt(val) + .5d);\n if ( c > max ) {\n break;\n }\n if ( c*c == val ) {\n System.out.printf(\" (%d, %d, %d)%n\", a, b ,c);\n count++;\n }\n }\n }\n System.out.printf(\"%d triangles%n\", count);\n } \n }\n\n private static void generateTriples60(int max) {\n int count = 0;\n System.out.printf(\"%nExtra Credit.%nMax side length %d, sides different length, formula: a*a + b*b - a*b = c*c%n\", max);\n for ( int a = 1 ; a <= max ; a++ ) {\n for ( int b = 1 ; b < a ; b++ ) {\n int val = a*a + b*b - a*b;\n int c = (int) (Math.sqrt(val) + .5d);\n if ( c*c == val ) {\n count++;\n }\n }\n }\n System.out.printf(\"%d triangles%n\", count);\n }\n\n}"} +{"id": 19, "output": "\nThe year 1800 is leaper: false / false.\nThe year 1900 is leaper: false / false.\nThe year 1994 is leaper: false / false.\nThe year 1998 is leaper: false / false.\nThe year 1999 is leaper: false / false.\nThe year 2000 is leaper: true / true.\nThe year 2001 is leaper: false / false.\nThe year 2004 is leaper: true / true.\nThe year 2100 is leaper: false / false.", "Python": "import datetime\n\ndef is_leap_year(year):\n try:\n datetime.date(year, 2, 29)\n except ValueError:\n return False\n return True", "Java": "import java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n public static void main(String[] argv){\n int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n GregorianCalendar cal = new GregorianCalendar();\n for(int year : yrs){\n System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} / {2}.\",\n year, cal.isLeapYear(year), isLeapYear(year)));\n }\n\n }\n public static boolean isLeapYear(int year){\n return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n }\n}"} +{"id": 20, "output": "10^0\t0\n10^1\t4\n10^2\t25\n10^3\t168\n10^4\t1229\n10^5\t9592\n10^6\t78498\n10^7\t664579\n10^8\t5761455\n10^9\t50847534", "Python": "from primesieve import primes\nfrom math import isqrt\nfrom functools import cache\n\np = primes(isqrt(1_000_000_000))\n\n@cache\ndef phi(x, a):\n res = 0\n while True:\n if not a or not x:\n return x + res\n \n a -= 1\n res -= phi(x//p[a], a) # partial tail recursion\n\ndef legpi(n):\n if n < 2: return 0\n\n a = legpi(isqrt(n))\n return phi(n, a) + a - 1\n\nfor e in range(10):\n print(f'10^{e}', legpi(10**e))", "Java": "import java.util.*;\n\npublic class LegendrePrimeCounter {\n public static void main(String[] args) {\n LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);\n for (int i = 0, n = 1; i < 10; ++i, n *= 10)\n System.out.printf(\"10^%d\\t%d\\n\", i, counter.primeCount((n)));\n }\n\n private List primes;\n\n public LegendrePrimeCounter(int limit) {\n primes = generatePrimes((int)Math.sqrt((double)limit));\n }\n\n public int primeCount(int n) {\n if (n < 2)\n return 0;\n int a = primeCount((int)Math.sqrt((double)n));\n return phi(n, a) + a - 1;\n }\n\n private int phi(int x, int a) {\n if (a == 0)\n return x;\n if (a == 1)\n return x - (x >> 1);\n int pa = primes.get(a - 1);\n if (x <= pa)\n return 1;\n return phi(x, a - 1) - phi(x / pa, a - 1);\n }\n\n private static List 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 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}"} +{"id": 21, "output": "The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:\n[1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, 13529, 21891, 35421, 57313, 92735, 150049]\n\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]", "Python": "def Leonardo(L_Zero, L_One, Add, Amount):\n terms = [L_Zero,L_One]\n while len(terms) < Amount:\n new = terms[-1] + terms[-2]\n new += Add\n terms.append(new)\n return terms\n\nout = \"\"\nprint \"First 25 Leonardo numbers:\"\nfor term in Leonardo(1,1,1,25):\n out += str(term) + \" \"\nprint out\n\nout = \"\"\nprint \"Leonardo numbers with fibonacci parameters:\"\nfor term in Leonardo(0,1,0,25):\n out += str(term) + \" \"\nprint out", "Java": "import java.util.Arrays;\nimport java.util.List;\n\n@SuppressWarnings(\"SameParameterValue\")\npublic class LeonardoNumbers {\n private static List leonardo(int n) {\n return leonardo(n, 1, 1, 1);\n }\n\n private static List leonardo(int n, int l0, int l1, int add) {\n Integer[] leo = new Integer[n];\n leo[0] = l0;\n leo[1] = l1;\n for (int i = 2; i < n; i++) {\n leo[i] = leo[i - 1] + leo[i - 2] + add;\n }\n return Arrays.asList(leo);\n }\n\n public static void main(String[] args) {\n System.out.println(\"The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:\");\n System.out.println(leonardo(25));\n System.out.println(\"\\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:\");\n System.out.println(leonardo(25, 0, 1, 0));\n }\n}"} +{"id": 22, "output": "distance(kitten, sitting) = 3\ndistance(saturday, sunday) = 3\ndistance(rosettacode, raisethysword) = 8", "Python": "def levenshteinDistance(str1, str2):\n m = len(str1)\n n = len(str2)\n d = [[i] for i in range(1, m + 1)] # d matrix rows\n d.insert(0, list(range(0, n + 1))) # d matrix columns\n for j in range(1, n + 1):\n for i in range(1, m + 1):\n if str1[i - 1] == str2[j - 1]: # Python (string) is 0-based\n substitutionCost = 0\n else:\n substitutionCost = 1\n d[i].insert(j, min(d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + substitutionCost))\n return d[-1][-1]\n\nprint(levenshteinDistance(\"kitten\",\"sitting\"))\nprint(levenshteinDistance(\"rosettacode\",\"raisethysword\"))", "Java": "public class Levenshtein {\n\n public static int distance(String a, String b) {\n a = a.toLowerCase();\n b = b.toLowerCase();\n // i == 0\n int [] costs = new int [b.length() + 1];\n for (int j = 0; j < costs.length; j++)\n costs[j] = j;\n for (int i = 1; i <= a.length(); i++) {\n // j == 0; nw = lev(i - 1, j)\n costs[0] = i;\n int nw = i - 1;\n for (int j = 1; j <= b.length(); j++) {\n int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);\n nw = costs[j];\n costs[j] = cj;\n }\n }\n return costs[b.length()];\n }\n\n public static void main(String [] args) {\n String [] data = { \"kitten\", \"sitting\", \"saturday\", \"sunday\", \"rosettacode\", \"raisethysword\" };\n for (int i = 0; i < data.length; i += 2)\n System.out.println(\"distance(\" + data[i] + \", \" + data[i+1] + \") = \" + distance(data[i], data[i+1]));\n }\n}"} +{"id": 23, "output": "Number of 5-trees: 9\n((((()))))\n(((()())))\n((()(())))\n((()()()))\n(()((())))\n(()(()()))\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# Maybe this lessens eye strain. Maybe not.\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]))", "Java": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class ListRootedTrees {\n private static final List TREE_LIST = new ArrayList<>();\n\n private static final List 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}"} +{"id": 24, "output": "The long primes up to 500 are:\n[7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179, 181, 193, 223, 229, 233, 257, 263, 269, 313, 337, 367, 379, 383, 389, 419, 433, 461, 487, 491, 499]\n\nThe number of long primes up to:\n 500 is 35\n 1000 is 60\n 2000 is 116\n 4000 is 218\n 8000 is 390\n 16000 is 716\n 32000 is 1300\n 64000 is 2430", "Python": "def sieve(limit):\n primes = []\n c = [False] * (limit + 1) # composite = true\n # no need to process even numbers\n p = 3\n while True:\n p2 = p * p\n if p2 > limit: break\n for i in range(p2, limit, 2 * p): c[i] = True\n while True:\n p += 2\n if not c[p]: break\n\n for i in range(3, limit, 2):\n if not c[i]: primes.append(i)\n return primes\n\n# finds the period of the reciprocal of n\ndef findPeriod(n):\n r = 1\n for i in range(1, n): r = (10 * r) % n\n rr = r\n period = 0\n while True:\n r = (10 * r) % n\n period += 1\n if r == rr: break\n return period\n\nprimes = sieve(64000)\nlongPrimes = []\nfor prime in primes:\n if findPeriod(prime) == prime - 1:\n longPrimes.append(prime)\nnumbers = [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]\ncount = 0\nindex = 0\ntotals = [0] * len(numbers)\nfor longPrime in longPrimes:\n if longPrime > numbers[index]:\n totals[index] = count\n index += 1\n count += 1\ntotals[-1] = count\nprint('The long primes up to 500 are:')\nprint(str(longPrimes[:totals[0]]).replace(',', ''))\nprint('\\nThe number of long primes up to:')\nfor (i, total) in enumerate(totals):\n print(' %5d is %d' % (numbers[i], total))", "Java": "import java.util.LinkedList;\nimport java.util.List;\n\npublic class LongPrimes\n{\n private static void sieve(int limit, List primes)\n {\n boolean[] c = new boolean[limit];\n for (int i = 0; i < limit; i++)\n c[i] = false;\n // No need to process even numbers\n int p = 3, n = 0;\n int p2 = p * p;\n while (p2 <= limit)\n {\n for (int i = p2; i <= limit; i += 2 * p)\n c[i] = true;\n do\n p += 2;\n while (c[p]);\n p2 = p * p;\n }\n for (int i = 3; i <= limit; i += 2)\n if (!c[i])\n primes.add(i);\n }\n\n // Finds the period of the reciprocal of n\n private static int findPeriod(int n)\n {\n int r = 1, period = 0;\n for (int i = 1; i < n; i++)\n r = (10 * r) % n;\n int rr = r;\n do\n {\n r = (10 * r) % n;\n ++period;\n }\n while (r != rr);\n return period;\n }\n \n public static void main(String[] args)\n {\n int[] numbers = new int[]{500, 1000, 2000, 4000, 8000, 16000, 32000, 64000};\n int[] totals = new int[numbers.length]; \n List primes = new LinkedList();\n List longPrimes = new LinkedList();\n sieve(64000, primes);\n for (int prime : primes)\n if (findPeriod(prime) == prime - 1)\n longPrimes.add(prime);\n int count = 0, index = 0;\n for (int longPrime : longPrimes)\n {\n if (longPrime > numbers[index])\n totals[index++] = count;\n ++count;\n }\n totals[numbers.length - 1] = count;\n System.out.println(\"The long primes up to \" + numbers[0] + \" are:\");\n System.out.println(longPrimes.subList(0, totals[0]));\n System.out.println();\n System.out.println(\"The number of long primes up to:\");\n for (int i = 0; i <= 7; i++)\n System.out.printf(\" %5d is %d\\n\", numbers[i], totals[i]);\n }\n}"} +{"id": 25, "output": "Long years this century:\n2004 2009 2015 2020 2026 2032 2037 2043 2048 2054 2060 2065 2071 2076 2082 2088 2093 2099 ", "Python": "from datetime import date\n\n\n# longYear :: Year Int -> Bool\ndef longYear(y):\n '''True if the ISO year y has 53 weeks.'''\n return 52 < date(y, 12, 28).isocalendar()[1]\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Longer (53 week) years in the range 2000-2100'''\n for year in [\n x for x in range(2000, 1 + 2100)\n if longYear(x)\n ]:\n print(year)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "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}"} +{"id": 26, "output": "test\ntest\nsting\nsting", "Python": "s1 = \"thisisatest\"\ns2 = \"testing123testing\"\nlen1, len2 = len(s1), len(s2)\nir, jr = 0, -1\nfor i1 in range(len1):\n i2 = s2.find(s1[i1])\n while i2 >= 0:\n j1, j2 = i1, i2\n while j1 < len1 and j2 < len2 and s2[j2] == s1[j1]:\n if j1-i1 >= jr-ir:\n ir, jr = i1, j1\n j1 += 1; j2 += 1\n i2 = s2.find(s1[i1], i2+1)\nprint (s1[ir:jr+1])", "Java": "public class LongestCommonSubstring {\n\n public static void main(String[] args) {\n System.out.println(lcs(\"testing123testing\", \"thisisatest\"));\n System.out.println(lcs(\"test\", \"thisisatest\"));\n System.out.println(lcs(\"testing\", \"sting\"));\n System.out.println(lcs(\"testing\", \"thisisasting\"));\n }\n\n static String lcs(String a, String b) {\n if (a.length() > b.length())\n return lcs(b, a);\n\n String res = \"\";\n for (int ai = 0; ai < a.length(); ai++) {\n for (int len = a.length() - ai; len > 0; len--) {\n\n for (int bi = 0; bi <= b.length() - len; bi++) {\n\n if (a.regionMatches(ai, b, bi, len) && len > res.length()) {\n res = a.substring(ai, ai + len);\n }\n }\n }\n }\n return res;\n }\n}"} +{"id": 27, "output": "[baabababc, baabc, bbbabc] -> `abc`\n[baabababc, baabc, bbbazc] -> `c`\n[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] -> `day`\n[longest, common, suffix] -> ``\n[suffix] -> `suffix`\n[] -> ``\n", "Python": "from itertools import takewhile\nfrom functools import reduce\n\n\n# longestCommonSuffix :: [String] -> String\ndef longestCommonSuffix(xs):\n '''Longest suffix shared by all\n strings in 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# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Test'''\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# MAIN ---\nif __name__ == '__main__':\n main()", "Java": "import java.util.List;\n\npublic class App {\n private static String lcs(List 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 test : tests) {\n System.out.printf(\"%s -> `%s`\\n\", test, lcs(test));\n }\n }\n}"} +{"id": 28, "output": "17 24 1 8 15 \n23 5 7 14 16 \n 4 6 13 20 22 \n10 12 19 21 3 \n11 18 25 2 9 \n\nMagic constant: 65 ", "Python": "def magic(n):\n for row in range(1, n + 1):\n print(' '.join('%*i' % (len(str(n**2)), cell) for cell in\n (n * ((row + col - 1 + n // 2) % n) +\n ((row + 2 * col - 2) % n) + 1\n for col in range(1, n + 1))))\n print('\\nAll sum to magic number %i' % ((n * n + 1) * n // 2))\n\n \nfor n in (5, 3, 7):\n\tprint('\\nOrder %i\\n=======' % n)\n\tmagic(n)\n", "Java": "public class MagicSquare {\n\n public static void main(String[] args) {\n int n = 5;\n for (int[] row : magicSquareOdd(n)) {\n for (int x : row)\n System.out.format(\"%2s \", x);\n System.out.println();\n }\n System.out.printf(\"\\nMagic constant: %d \", (n * n + 1) * n / 2);\n }\n\n public static int[][] magicSquareOdd(final int base) {\n if (base % 2 == 0 || base < 3)\n throw new IllegalArgumentException(\"base must be odd and > 2\");\n\n int[][] grid = new int[base][base];\n int r = 0, number = 0;\n int size = base * base;\n\n int c = base / 2;\n while (number++ < size) {\n grid[r][c] = number;\n if (r == 0) {\n if (c == base - 1) {\n r++;\n } else {\n r = base - 1;\n c++;\n }\n } else {\n if (c == base - 1) {\n r--;\n c = 0;\n } else {\n if (grid[r - 1][c + 1] == 0) {\n r--;\n c++;\n } else {\n r++;\n }\n }\n }\n }\n return grid;\n }\n}"} +{"id": 29, "output": "0.0 in [0, 10] maps to -1.0 in [-1, 0].\n1.0 in [0, 10] maps to -0.9 in [-1, 0].\n2.0 in [0, 10] maps to -0.8 in [-1, 0].\n3.0 in [0, 10] maps to -0.7 in [-1, 0].\n4.0 in [0, 10] maps to -0.6 in [-1, 0].\n5.0 in [0, 10] maps to -0.5 in [-1, 0].\n6.0 in [0, 10] maps to -0.4 in [-1, 0].\n7.0 in [0, 10] maps to -0.30000000000000004 in [-1, 0].\n8.0 in [0, 10] maps to -0.19999999999999996 in [-1, 0].\n9.0 in [0, 10] maps to -0.09999999999999998 in [-1, 0].\n10.0 in [0, 10] maps to 0.0 in [-1, 0].", "Python": "def maprange( a, b, s):\n\t(a1, a2), (b1, b2) = a, b\n\treturn b1 + ((s - a1) * (b2 - b1) / (a2 - a1))\n\nfor s in range(11):\n\tprint(\"%2g maps to %g\" % (s, maprange( (0, 10), (-1, 0), s)))", "Java": "public class Range {\n\tpublic static void main(String[] args){\n\t\tfor(float s = 0;s <= 10; s++){\n\t\t\tSystem.out.println(s + \" in [0, 10] maps to \"+ \n\t\t\t\t\tmapRange(0, 10, -1, 0, s)+\" in [-1, 0].\");\n\t\t}\n\t}\n\t\n\tpublic static double mapRange(double a1, double a2, double b1, double b2, double s){\n\t\treturn b1 + ((s - a1)*(b2 - b1))/(a2 - a1);\n\t}\n}"} +{"id": 30, "output": "n\\k 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 \n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \n 3 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 \n 5 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0 1 -1 -1 1 0 \n 7 1 1 -1 1 -1 -1 0 1 1 -1 1 -1 -1 0 1 1 -1 1 -1 -1 0 1 1 -1 1 -1 -1 0 1 1 \n 9 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 \n11 1 -1 1 1 1 -1 -1 -1 1 -1 0 1 -1 1 1 1 -1 -1 -1 1 -1 0 1 -1 1 1 1 -1 -1 -1 \n13 1 -1 1 1 -1 -1 -1 -1 1 1 -1 1 0 1 -1 1 1 -1 -1 -1 -1 1 1 -1 1 0 1 -1 1 1 \n15 1 1 0 1 0 0 -1 1 0 0 -1 0 -1 -1 0 1 1 0 1 0 0 -1 1 0 0 -1 0 -1 -1 0 \n17 1 1 -1 1 -1 -1 -1 1 1 -1 -1 -1 1 -1 1 1 0 1 1 -1 1 -1 -1 -1 1 1 -1 -1 -1 1 \n19 1 -1 -1 1 1 1 1 -1 1 -1 1 -1 -1 -1 -1 1 1 -1 0 1 -1 -1 1 1 1 1 -1 1 -1 1 \n21 1 -1 0 1 1 0 0 -1 0 -1 -1 0 -1 0 0 1 1 0 -1 1 0 1 -1 0 1 1 0 0 -1 0 \n23 1 1 1 1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 -1 1 -1 -1 -1 -1 0 1 1 1 1 -1 1 -1 \n25 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 \n27 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 1 -1 0 \n29 1 -1 -1 1 1 1 1 -1 1 -1 -1 -1 1 -1 -1 1 -1 -1 -1 1 -1 1 1 1 1 -1 -1 1 0 1 \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", "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 // Compute (k n), where k is numerator\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}"} +{"id": 31, "output": "Prisoners executed in order:\n2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 \nSurvivor: 30\nPrisoners executed in order:\n2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 \nSurvivors: [15, 30, 34]\n", "Python": "from itertools import compress, cycle\ndef josephus(prisoner, kill, surviver):\n p = range(prisoner)\n k = [0] * kill\n k[kill-1] = 1\n s = [1] * kill\n s[kill -1] = 0\n queue = p\n \n queue = compress(queue, cycle(s))\n try:\n while True:\n p.append(queue.next()) \n except StopIteration:\n pass \n\n kil=[]\n killed = compress(p, cycle(k))\n try:\n while True:\n kil.append(killed.next())\n except StopIteration:\n pass \n \n print 'The surviver is: ', kil[-surviver:]\n print 'The kill sequence is ', kil[:prisoner-surviver]\n\njosephus(41,3,2)", "Java": "import java.util.ArrayList;\n\npublic class Josephus {\n public static int execute(int n, int k){\n int killIdx = 0;\n ArrayList prisoners = new ArrayList(n);\n for(int i = 0;i < n;i++){\n prisoners.add(i);\n }\n System.out.println(\"Prisoners executed in order:\");\n while(prisoners.size() > 1){\n killIdx = (killIdx + k - 1) % prisoners.size();\n System.out.print(prisoners.get(killIdx) + \" \");\n prisoners.remove(killIdx);\n }\n System.out.println();\n return prisoners.get(0);\n }\n \n public static ArrayList executeAllButM(int n, int k, int m){\n int killIdx = 0;\n ArrayList prisoners = new ArrayList(n);\n for(int i = 0;i < n;i++){\n prisoners.add(i);\n }\n System.out.println(\"Prisoners executed in order:\");\n while(prisoners.size() > m){\n killIdx = (killIdx + k - 1) % prisoners.size();\n System.out.print(prisoners.get(killIdx) + \" \");\n prisoners.remove(killIdx);\n }\n System.out.println();\n return prisoners;\n }\n \n public static void main(String[] args){\n System.out.println(\"Survivor: \" + execute(41, 3));\n System.out.println(\"Survivors: \" + executeAllButM(41, 3, 3));\n }\n}"} +{"id": 32, "output": "5.187377517639621", "Python": "class Ref(object):\n def __init__(self, value=None):\n self.value = value\n\ndef harmonic_sum(i, lo, hi, term):\n # term is passed by-name, and so is i\n temp = 0\n i.value = lo\n while i.value <= hi: # Python \"for\" loop creates a distinct which\n temp += term() # would not be shared with the passed \"i\"\n i.value += 1 # Here the actual passed \"i\" is incremented.\n return temp\n\ni = Ref()\n\n# note the correspondence between the mathematical notation and the\n# call to sum it's almost as good as sum(1/i for i in range(1,101))\nprint harmonic_sum(i, 1, 100, lambda: 1.0/i.value)", "Java": "import java.util.function.*;\nimport java.util.stream.*;\n\npublic class Jensen {\n static double sum(int lo, int hi, IntToDoubleFunction f) {\n return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum();\n }\n \n public static void main(String args[]) {\n System.out.println(sum(1, 100, (i -> 1.0/i)));\n }\n}"} +{"id": 33, "output": "0.9444444444444445\n0.7666666666666666\n0.8962962962962964", "Python": "from __future__ import division\n\n\ndef jaro(s, t):\n '''Jaro distance between two strings.'''\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 '''Tests'''\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()", "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}"} +{"id": 34, "output": "R(): 1 3 7 12 18 26 35 45 56 69\nDone", "Python": "def ffr(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffr.r[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n ffr_n_1 = ffr(n-1)\n lastr = r[-1]\n # extend s up to, and one past, last r \n s += list(range(s[-1] + 1, lastr))\n if s[-1] < lastr: s += [lastr + 1]\n # access s[n-1] temporarily extending s if necessary\n len_s = len(s)\n ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]\n ans = ffr_n_1 + ffs_n_1\n r.append(ans)\n return ans\nffr.r = [None, 1]\n\ndef ffs(n):\n if n < 1 or type(n) != int: raise ValueError(\"n must be an int >= 1\")\n try:\n return ffs.s[n]\n except IndexError:\n r, s = ffr.r, ffs.s\n for i in range(len(r), n+2):\n ffr(i)\n if len(s) > n:\n return s[n]\n raise Exception(\"Whoops!\")\nffs.s = [None, 2]\n\nif __name__ == '__main__':\n first10 = [ffr(i) for i in range(1,11)]\n assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], \"ffr() value error(s)\"\n print(\"ffr(n) for n = [1..10] is\", first10)\n #\n bin = [None] + [0]*1000\n for i in range(40, 0, -1):\n bin[ffr(i)] += 1\n for i in range(960, 0, -1):\n bin[ffs(i)] += 1\n if all(b == 1 for b in bin[1:1000]):\n print(\"All Integers 1..1000 found OK\")\n else:\n print(\"All Integers 1..1000 NOT found only once: ERROR\")", "Java": "import java.util.*;\n\nclass Hofstadter\n{\n private static List getSequence(int rlistSize, int slistSize)\n {\n List rlist = new ArrayList();\n List slist = new ArrayList();\n Collections.addAll(rlist, 1, 3, 7);\n Collections.addAll(slist, 2, 4, 5, 6);\n List list = (rlistSize > 0) ? rlist : slist;\n int targetSize = (rlistSize > 0) ? rlistSize : slistSize;\n while (list.size() > targetSize)\n list.remove(list.size() - 1);\n while (list.size() < targetSize)\n {\n int lastIndex = rlist.size() - 1;\n int lastr = rlist.get(lastIndex).intValue();\n int r = lastr + slist.get(lastIndex).intValue();\n rlist.add(Integer.valueOf(r));\n for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)\n slist.add(Integer.valueOf(s));\n }\n return list;\n }\n \n public static int ffr(int n)\n { return getSequence(n, 0).get(n - 1).intValue(); }\n \n public static int ffs(int n)\n { return getSequence(0, n).get(n - 1).intValue(); }\n \n public static void main(String[] args)\n {\n System.out.print(\"R():\");\n for (int n = 1; n <= 10; n++)\n System.out.print(\" \" + ffr(n));\n System.out.println();\n \n Set first40R = new HashSet();\n for (int n = 1; n <= 40; n++)\n first40R.add(Integer.valueOf(ffr(n)));\n \n Set first960S = new HashSet();\n for (int n = 1; n <= 960; n++)\n first960S.add(Integer.valueOf(ffs(n)));\n \n for (int i = 1; i <= 1000; i++)\n {\n Integer n = Integer.valueOf(i);\n if (first40R.contains(n) == first960S.contains(n))\n System.out.println(\"Integer \" + i + \" either in both or neither set\");\n }\n System.out.println(\"Done\");\n }\n}"} +{"id": 35, "output": "Hello world!", "Python": "print(\"Hello world!\")", "Java": "public class HelloWorld\n{\n public static void main(String[] args)\n {\n System.out.println(\"Hello world!\");\n }\n}"} +{"id": 36, "output": "Hamming(1 .. 20) = 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36\nHamming(1691) = 2125764000\nHamming(1000) = 51200000", "Python": "from itertools import islice\n\ndef hamming2():\n \n h = 1\n _h=[h] # memoized\n multipliers = (2, 3, 5)\n multindeces = [0 for i in multipliers] # index into _h for multipliers\n multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)]\n yield h\n while True:\n h = min(multvalues)\n _h.append(h)\n for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)):\n if v == h:\n i += 1\n multindeces[n] = i\n multvalues[n] = x * _h[i]\n # cap the memoization\n mini = min(multindeces)\n if mini >= 1000:\n del _h[:mini]\n multindeces = [i - mini for i in multindeces]\n #\n yield h", "Java": "import java.math.BigInteger;\nimport java.util.PriorityQueue;\n\nfinal class Hamming {\n private static BigInteger THREE = BigInteger.valueOf(3);\n private static BigInteger FIVE = BigInteger.valueOf(5);\n\n private static void updateFrontier(BigInteger x,\n PriorityQueue pq) {\n pq.offer(x.shiftLeft(1));\n pq.offer(x.multiply(THREE));\n pq.offer(x.multiply(FIVE));\n }\n\n public static BigInteger hamming(int n) {\n if (n <= 0)\n throw new IllegalArgumentException(\"Invalid parameter\");\n PriorityQueue frontier = new PriorityQueue();\n updateFrontier(BigInteger.ONE, frontier);\n BigInteger lowest = BigInteger.ONE;\n for (int i = 1; i < n; i++) {\n lowest = frontier.poll();\n while (frontier.peek().equals(lowest))\n frontier.poll();\n updateFrontier(lowest, frontier);\n }\n return lowest;\n }\n\n public static void main(String[] args) {\n System.out.print(\"Hamming(1 .. 20) =\");\n for (int i = 1; i < 21; i++)\n System.out.print(\" \" + hamming(i));\n System.out.println(\"\\nHamming(1691) = \" + hamming(1691));\n System.out.println(\"Hamming(1000) = \" + hamming(1000));\n }\n}"} +{"id": 37, "output": "1\n7\n10\n13\n19\n23\n28\n31", "Python": "from itertools import islice\n\n\n# main :: IO ()\ndef main():\n '''Test'''\n print(\n take(8)(\n happyNumbers()\n )\n )\n\n\n# happyNumbers :: Gen [Int]\ndef happyNumbers():\n '''Generator :: non-finite stream of happy numbers.'''\n x = 1\n while True:\n x = until(isHappy)(succ)(x)\n yield x\n x = succ(x)\n\n\n# isHappy :: Int -> Bool\ndef isHappy(n):\n '''Happy number sequence starting at n reaches 1 ?'''\n seen = set()\n\n # p :: Int -> Bool\n def p(x):\n if 1 == x or x in seen:\n return True\n else:\n seen.add(x)\n return False\n\n # f :: Int -> Int\n def f(x):\n return sum(int(d)**2 for d in str(x))\n\n return 1 == until(p)(f)(n)\n\n\n# GENERIC -------------------------------------------------\n\n# succ :: Int -> Int\ndef succ(x):\n '''The successor of an integer.'''\n return 1 + x\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.'''\n def go(f, x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return lambda f: lambda x: go(f, x)\n\n\nif __name__ == '__main__':\n main()", "Java": "import java.util.HashSet;\npublic class Happy{\n public static boolean happy(long number){\n long m = 0;\n int digit = 0;\n HashSet cycle = new HashSet();\n while(number != 1 && cycle.add(number)){\n m = 0;\n while(number > 0){\n digit = (int)(number % 10);\n m += digit*digit;\n number /= 10;\n }\n number = m;\n }\n return number == 1;\n }\n\n public static void main(String[] args){\n for(long num = 1,count = 0;count<8;num++){\n if(happy(num)){\n System.out.println(num);\n count++;\n }\n }\n }\n}"} +{"id": 38, "output": "2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118", "Python": "from calendar import weekday, SUNDAY\n\n[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]", "Java": "import static java.util.Calendar.*;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\npublic class Yuletide{\n\tpublic static void main(String[] args) {\n\t\tCalendar calendar;\n int count = 1;\n for (int year = 2008; year <= 2121; year++) {\n calendar = new GregorianCalendar(year, DECEMBER, 25);\n if (calendar.get(DAY_OF_WEEK) == SUNDAY) {\n if (count != 1)\n System.out.print(\", \");\n System.out.printf(\"%d\", calendar.get(YEAR));\n count++;\n }\n }\n\t}\n}"} +{"id": 39, "output": " 5724 is valid\n 5727 is invalid\n112946 is valid\n112949 is invalid", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "Java": "public class DammAlgorithm {\n private static final int[][] table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n };\n\n private static boolean damm(String s) {\n int interim = 0;\n for (char c : s.toCharArray()) interim = table[interim][c - '0'];\n return interim == 0;\n }\n\n public static void main(String[] args) {\n int[] numbers = {5724, 5727, 112946, 112949};\n for (Integer number : numbers) {\n boolean isValid = damm(number.toString());\n if (isValid) {\n System.out.printf(\"%6d is valid\\n\", number);\n } else {\n System.out.printf(\"%6d is invalid\\n\", number);\n }\n }\n }\n}"} +{"id": 0, "output": " 5724 true\n 5727 false\n112946 true\n112949 false", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "Go": "package main\n\nimport \"fmt\"\n\nvar table = [10][10]byte{\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n}\n\nfunc damm(input string) bool {\n var interim byte\n for _, c := range []byte(input) {\n interim = table[interim][c-'0']\n }\n return interim == 0\n}\n\nfunc main() {\n for _, s := range []string{\"5724\", \"5727\", \"112946\", \"112949\"} {\n fmt.Printf(\"%6s %t\\n\", s, damm(s))\n }\n}\n"} +{"id": 1, "output": "25 December 2011 is Sunday\n25 December 2016 is Sunday\n25 December 2022 is Sunday\n25 December 2033 is Sunday\n25 December 2039 is Sunday\n25 December 2044 is Sunday\n25 December 2050 is Sunday\n25 December 2061 is Sunday\n25 December 2067 is Sunday\n25 December 2072 is Sunday\n25 December 2078 is Sunday\n25 December 2089 is Sunday\n25 December 2095 is Sunday\n25 December 2101 is Sunday\n25 December 2107 is Sunday\n25 December 2112 is Sunday\n25 December 2118 is Sunday", "Python": "from calendar import weekday, SUNDAY\n\n[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]", "Go": "package main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc main() {\n for year := 2008; year <= 2121; year++ {\n if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==\n time.Sunday {\n fmt.Printf(\"25 December %d is Sunday\\n\", year)\n }\n }\n}"} +{"id": 2, "output": "1 0 0 1 0 0 0 0 1 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 1 0 0 0 0 0\n0 0 0 0 0 1 0 0 0 0\n0 0 0 0 0 0 0 0 1 0\n0 0 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 1", "Python": "doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\" % (i+1), 'open' if doors[i] else 'close')", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n doors := [100]bool{}\n\n // the 100 passes called for in the task description\n for pass := 1; pass <= 100; pass++ {\n for door := pass-1; door < 100; door += pass {\n doors[door] = !doors[door]\n }\n }\n\n // one more pass to answer the question\n for i, v := range doors {\n if v {\n fmt.Print(\"1\")\n } else {\n fmt.Print(\"0\")\n }\n\n if i%10 == 9 {\n fmt.Print(\"\\n\")\n } else {\n fmt.Print(\" \")\n }\n\n }\n}"} +{"id": 3, "output": "104743", "Python": "def 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 prime(n: int) -> int:\n if n == 1:\n return 2\n p = 3\n pn = 1\n while pn < n:\n if isPrime(p):\n pn += 1\n p += 2\n return p-2\n\nif __name__ == '__main__':\n print(prime(10001))", "Go": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n if n == 1 {\n return false\n }\n i := 2\n for i*i <= n {\n if n%i == 0 {\n return false\n }\n i++\n }\n return true\n}\n\nfunc main() {\n var final, pNum int\n\n for i := 1; pNum < 10001; i++ {\n if isPrime(i) {\n pNum++\n }\n final = i\n }\n fmt.Println(final)\n}"} +{"id": 4, "output": "5 bottles of beer on the wall\n5 bottles of beer\nTake one down, pass it around\n4 bottles of beer on the wall\n4 bottles of beer on the wall\n4 bottles of beer\nTake one down, pass it around\n3 bottles of beer on the wall\n3 bottles of beer on the wall\n3 bottles of beer\nTake one down, pass it around\n2 bottles of beer on the wall\n2 bottles of beer on the wall\n2 bottles of beer\nTake one down, pass it around\n1 bottle of beer on the wall\n1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around\nNo more bottles of beer on the wall", "Python": "from functools import partial\nfrom typing import Callable\n\n\ndef regular_plural(noun: str) -> str:\n \"\"\"English rule to get the plural form of a word\"\"\"\n if noun[-1] == \"s\":\n return noun + \"es\"\n \n return noun + \"s\"\n\n\ndef beer_song(\n *,\n location: str = 'on the wall',\n distribution: str = 'Take one down, pass it around',\n solution: str = 'Better go to the store to buy some more!',\n container: str = 'bottle',\n plurifier: Callable[[str], str] = regular_plural,\n liquid: str = \"beer\",\n initial_count: int = 99,\n) -> str:\n \"\"\"\n Return the lyrics of the beer song\n :param location: initial location of the drink\n :param distribution: specifies the process of its distribution\n :param solution: what happens when we run out of drinks\n :param container: bottle/barrel/flask or other containers\n :param plurifier: function converting a word to its plural form\n :param liquid: the name of the drink in the given container\n :param initial_count: how many containers available initially\n \"\"\"\n \n verse = partial(\n get_verse,\n initial_count = initial_count, \n location = location,\n distribution = distribution,\n solution = solution,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n verses = map(verse, range(initial_count, -1, -1))\n return '\\n\\n'.join(verses)\n\n\ndef get_verse(\n count: int,\n *,\n initial_count: str,\n location: str,\n distribution: str,\n solution: str,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"Returns the verse for the given amount of drinks\"\"\"\n \n asset = partial(\n get_asset,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n current_asset = asset(count)\n next_number = count - 1 if count else initial_count\n next_asset = asset(next_number)\n action = distribution if count else solution\n \n inventory = partial(\n get_inventory,\n location = location,\n )\n \n return '\\n'.join((\n inventory(current_asset),\n current_asset,\n action,\n inventory(next_asset),\n ))\n\n\ndef get_inventory(\n asset: str,\n *,\n location: str,\n) -> str:\n \"\"\"\n Used to return the first or the fourth line of the verse\n\n >>> get_inventory(\"10 bottles of beer\", location=\"on the wall\")\n \"10 bottles of beer on the wall\"\n \"\"\"\n return ' '.join((asset, location))\n\n\ndef get_asset(\n count: int,\n *,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"\n Quantified asset\n \n >>> get_asset(0, container=\"jar\", plurifier=regular_plural, liquid='milk')\n \"No more jars of milk\"\n \"\"\"\n \n containers = plurifier(container) if count != 1 else container\n spelled_out_quantity = str(count) if count else \"No more\" \n return ' '.join((spelled_out_quantity, containers, \"of\", liquid))\n\n\nif __name__ == '__main__':\n print(beer_song())", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tbottles := func(i int) string {\n\t\tswitch i {\n\t\tcase 0:\n\t\t\treturn \"No more bottles\"\n\t\tcase 1:\n\t\t\treturn \"1 bottle\"\n\t\tdefault:\n\t\t\treturn fmt.Sprintf(\"%d bottles\", i)\n\t\t}\n\t}\n\n\tfor i := 10; i > 0; i-- {\n\t\tfmt.Printf(\"%s of beer on the wall\\n\", bottles(i))\n\t\tfmt.Printf(\"%s of beer\\n\", bottles(i))\n\t\tfmt.Printf(\"Take one down, pass it around\\n\")\n\t\tfmt.Printf(\"%s of beer on the wall\\n\", bottles(i-1))\n\t}\n}"} +{"id": 5, "output": "user words: riG rePEAT copies put mo rest types fup. 6 poweRin \nfull words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT", "Python": "command_table_text = \\\n\"\"\"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\nCOUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\nNFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\nJoin SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\nMErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\nREAD RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\nRIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\"\"\"\n\nuser_words = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n \"\"\" find the minimal abbreviation length for each word by counting capital letters.\n a word that does not have capital letters gets it's full length as the minimum.\n \"\"\"\n command_table = dict()\n for word in command_table_text.split():\n abbr_len = sum(1 for c in word if c.isupper())\n if abbr_len == 0:\n abbr_len = len(word)\n command_table[word] = abbr_len\n return command_table\n\ndef find_abbreviations(command_table):\n \"\"\" for each command insert all possible abbreviations\"\"\"\n abbreviations = dict()\n for command, min_abbr_len in command_table.items():\n for l in range(min_abbr_len, len(command)+1):\n abbr = command[:l].lower()\n abbreviations[abbr] = command.upper()\n return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n user_words = [word.lower() for word in user_string.split()]\n commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)", "Go": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \" +\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \" +\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \" +\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \" +\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n results := make([]string, 0)\n if len(words) == 0 {\n return results\n }\n for _, word := range words {\n matchFound := false\n wlen := len(word)\n for i, command := range commands {\n if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n continue\n }\n c := strings.ToUpper(command)\n w := strings.ToUpper(word)\n if strings.HasPrefix(c, w) {\n results = append(results, c)\n matchFound = true\n break\n }\n }\n if !matchFound {\n results = append(results, \"*error*\")\n }\n }\n return results\n}\n\nfunc main() {\n table = strings.TrimSpace(table)\n commands := strings.Fields(table)\n clen := len(commands)\n minLens := make([]int, clen)\n for i := 0; i < clen; i++ {\n count := 0\n for _, c := range commands[i] {\n if c >= 'A' && c <= 'Z' {\n count++\n }\n }\n minLens[i] = count\n }\n sentence := \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n words := strings.Fields(sentence)\n results := validate(commands, words, minLens)\n fmt.Print(\"user words: \")\n for j := 0; j < len(words); j++ {\n fmt.Printf(\"%-*s \", len(results[j]), words[j])\n }\n fmt.Print(\"\\nfull words: \")\n fmt.Println(strings.Join(results, \" \"))\n}"} +{"id": 6, "output": "A true\nBARK true\nBOOK false\nTREAT true\nCOMMON false\nSQUAD true\nCONFUSE true", "Python": "blocks = [(\"B\", \"O\"),\n (\"X\", \"K\"),\n (\"D\", \"Q\"),\n (\"C\", \"P\"),\n (\"N\", \"A\"),\n (\"G\", \"T\"),\n (\"R\", \"E\"),\n (\"T\", \"G\"),\n (\"Q\", \"D\"),\n (\"F\", \"S\"),\n (\"J\", \"W\"),\n (\"H\", \"U\"),\n (\"V\", \"I\"),\n (\"A\", \"N\"),\n (\"O\", \"B\"),\n (\"E\", \"R\"),\n (\"F\", \"S\"),\n (\"L\", \"Y\"),\n (\"P\", \"C\"),\n (\"Z\", \"M\")]\n\n\ndef can_make_word(word, block_collection=blocks):\n \"\"\"\n Return True if `word` can be made from the blocks in `block_collection`.\n\n >>> can_make_word(\"\")\n False\n >>> can_make_word(\"a\")\n True\n >>> can_make_word(\"bark\")\n True\n >>> can_make_word(\"book\")\n False\n >>> can_make_word(\"treat\")\n True\n >>> can_make_word(\"common\")\n False\n >>> can_make_word(\"squad\")\n True\n >>> can_make_word(\"coNFused\")\n True\n \"\"\"\n if not word:\n return False\n\n blocks_remaining = block_collection[:]\n for char in word.upper():\n for block in blocks_remaining:\n if char in block:\n blocks_remaining.remove(block)\n break\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n \"COMMON\", \"squad\", \"Confused\"]))", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc newSpeller(blocks string) func(string) bool {\n\tbl := strings.Fields(blocks)\n\treturn func(word string) bool {\n\t\treturn r(word, bl)\n\t}\n}\n\nfunc r(word string, bl []string) bool {\n\tif word == \"\" {\n\t\treturn true\n\t}\n\tc := word[0] | 32\n\tfor i, b := range bl {\n\t\tif c == b[0]|32 || c == b[1]|32 {\n\t\t\tbl[i], bl[0] = bl[0], b\n\t\t\tif r(word[1:], bl[1:]) == true {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tbl[i], bl[0] = bl[0], bl[i]\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main() {\n\tsp := newSpeller(\n\t\t\"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\")\n\tfor _, word := range []string{\n\t\t\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\"} {\n\t\tfmt.Println(word, sp(word))\n\t}\n}"} +{"id": 7, "output": "N Integer Portion Pow Nth Term (33 dp)\n-----------------------------------------------------------------------------------------\n0 96 -3 0.096000000000000000000000000000000\n1 5122560 -9 0.005122560000000000000000000000000\n2 190722470400 -15 0.000190722470400000000000000000000\n3 7574824857600000 -21 0.000007574824857600000000000000000\n4 312546150372456000000 -27 0.000000312546150372456000000000000\n5 13207874703225491420651520 -33 0.000000013207874703225491420651520\n6 567273919793089083292259942400 -39 0.000000000567273919793089083292260\n7 24650600248172987140112763715584000 -45 0.000000000024650600248172987140113\n8 1080657854354639453670407474439566400000 -51 0.000000000001080657854354639453670\n9 47701779391594966287470570490839978880000000 -57 0.000000000000047701779391594966287\n\nPi to 70 decimal places is:\n3.1415926535897932384626433832795028841971693993751058209749445923078164\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\u03c0 to 70 digits is ', end='')\n mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n print('mpmath \u03c0 is ', end='')\n mp.nprint(mp.pi, 71)", "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}"} +{"id": 8, "output": "0.8472130847939792", "Python": "from math import sqrt\n\ndef agm(a0, g0, tolerance=1e-10):\n \"\"\"\n Calculating the arithmetic-geometric mean of two numbers a0, g0.\n\n tolerance the tolerance for the converged \n value of the arithmetic-geometric mean\n (default value = 1e-10)\n \"\"\"\n an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)\n while abs(an - gn) > tolerance:\n an, gn = (an + gn) / 2.0, sqrt(an * gn)\n return an\n\nprint agm(1, 1 / sqrt(2))", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst \u03b5 = 1e-14\n\nfunc agm(a, g float64) float64 {\n for math.Abs(a-g) > math.Abs(a)*\u03b5 {\n a, g = (a+g)*.5, math.Sqrt(a*g)\n }\n return a\n}\n\nfunc main() {\n fmt.Println(agm(1, 1/math.Sqrt2))\n}"} +{"id": 9, "output": "3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475647992", "Python": "from decimal import *\n\nD = Decimal\ngetcontext().prec = 100\na = n = D(1)\ng, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)\nfor i in range(18):\n x = [(a + g) * half, (a * g).sqrt()]\n var = x[0] - a\n z -= var * var * n\n n += n\n a, g = x \nprint(a * a / z)", "Go": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n one := big.NewFloat(1)\n two := big.NewFloat(2)\n four := big.NewFloat(4)\n prec := uint(768) // say\n\n a := big.NewFloat(1).SetPrec(prec)\n g := new(big.Float).SetPrec(prec)\n\n // temporary variables\n t := new(big.Float).SetPrec(prec)\n u := new(big.Float).SetPrec(prec)\n\n g.Quo(a, t.Sqrt(two))\n sum := new(big.Float)\n pow := big.NewFloat(2)\n\n for a.Cmp(g) != 0 {\n t.Add(a, g)\n t.Quo(t, two)\n g.Sqrt(u.Mul(a, g))\n a.Set(t)\n pow.Mul(pow, two)\n t.Sub(t.Mul(a, a), u.Mul(g, g))\n sum.Add(sum, t.Mul(t, pow))\n }\n\n t.Mul(a, a)\n t.Mul(t, four)\n pi := t.Quo(t, u.Sub(one, sum))\n fmt.Println(pi)\n}"} +{"id": 10, "output": "Length of [apple orange pear] is 3.", "Python": "print(len(['apple', 'orange']))", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tarr := [...]string{\"apple\", \"orange\", \"pear\"}\n\n\tfmt.Printf(\"Length of %v is %v.\\n\", arr, len(arr))\n}"} +{"id": 11, "output": "The attractive numbers up to and including 120 are:\n 4 6 8 9 10 12 14 15 18 20 21 22 25 26 27 28 30 32 33 34\n 35 38 39 42 44 45 46 48 49 50 51 52 55 57 58 62 63 65 66 68\n 69 70 72 74 75 76 77 78 80 82 85 86 87 91 92 93 94 95 98 99\n 102 105 106 108 110 111 112 114 115 116 117 118 119 120", "Python": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,121):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,", "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 countPrimeFactors(n int) int {\n switch {\n case n == 1:\n return 0\n case isPrime(n):\n return 1\n default:\n count, f := 0, 2\n for {\n if n%f == 0 {\n count++\n n /= f\n if n == 1 {\n return count\n }\n if isPrime(n) {\n f = n\n }\n } else if f >= 3 {\n f += 2\n } else {\n f = 3\n }\n }\n return count\n }\n}\n\nfunc main() {\n const max = 120\n fmt.Println(\"The attractive numbers up to and including\", max, \"are:\")\n count := 0\n for i := 1; i <= max; i++ {\n n := countPrimeFactors(i)\n if isPrime(n) {\n fmt.Printf(\"%4d\", i)\n count++\n if count % 20 == 0 {\n fmt.Println()\n }\n } \n }\n fmt.Println()\n}"} +{"id": 12, "output": "N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.5007 1.5000 ( 0.05%)\n 3 1.8959 1.8889 ( 0.37%)\n 4 2.2138 2.2188 ( 0.22%)\n 5 2.5013 2.5104 ( 0.36%)\n 6 2.7940 2.7747 ( 0.70%)\n 7 3.0197 3.0181 ( 0.05%)\n 8 3.2715 3.2450 ( 0.82%)\n 9 3.4147 3.4583 ( 1.26%)\n 10 3.6758 3.6602 ( 0.43%)\n 11 3.8672 3.8524 ( 0.38%)\n 12 4.0309 4.0361 ( 0.13%)\n 13 4.2153 4.2123 ( 0.07%)\n 14 4.3380 4.3820 ( 1.00%)\n 15 4.5030 4.5458 ( 0.94%)\n 16 4.7563 4.7043 ( 1.11%)\n 17 4.8616 4.8579 ( 0.08%)\n 18 4.9933 5.0071 ( 0.27%)\n 19 5.1534 5.1522 ( 0.02%)\n 20 5.3031 5.2936 ( 0.18%)", "Python": "from __future__ import division # Only necessary for Python 2.X\nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n count = 0\n for i in range(times):\n x, bits = 1, 0\n while not (bits & x):\n count += 1\n bits |= x\n x = 1 << randrange(n)\n return count / times\n\nif __name__ == '__main__':\n print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n for n in range(1, MAX_N+1):\n avg = test(n, TIMES)\n theory = analytical(n)\n diff = (avg / theory - 1) * 100\n print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n fmt.Println(\" N average analytical (error)\")\n fmt.Println(\"=== ========= ============ =========\")\n for n := 1; n <= nmax; n++ {\n a := avg(n)\n b := ana(n)\n fmt.Printf(\"%3d %9.4f %12.4f (%6.2f%%)\\n\",\n n, a, b, math.Abs(a-b)/b*100)\n }\n}\n\nfunc avg(n int) float64 {\n const tests = 1e4\n sum := 0\n for t := 0; t < tests; t++ {\n var v [nmax]bool\n for x := 0; !v[x]; x = rand.Intn(n) {\n v[x] = true\n sum++\n }\n }\n return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n nn := float64(n)\n term := 1.\n sum := 1.\n for i := nn - 1; i >= 1; i-- {\n term *= i / nn\n sum += term\n }\n return sum\n}"} +{"id": 13, "output": "The mean angle of [350 10] is: -0.000000 degrees\nThe mean angle of [90 180 270 360] is: -90.000000 degrees\nThe mean angle of [10 20 30] is: 20.000000 degrees", "Python": "from cmath import rect, phase\nfrom math import radians, degrees\ndef mean_angle(deg):\n return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n\nfor angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:\n print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/cmplx\"\n)\n\nfunc deg2rad(d float64) float64 { return d * math.Pi / 180 }\nfunc rad2deg(r float64) float64 { return r * 180 / math.Pi }\n\nfunc mean_angle(deg []float64) float64 {\n\tsum := 0i\n\tfor _, x := range deg {\n\t\tsum += cmplx.Rect(1, deg2rad(x))\n\t}\n\treturn rad2deg(cmplx.Phase(sum))\n}\n\nfunc main() {\n\tfor _, angles := range [][]float64{\n\t\t{350, 10},\n\t\t{90, 180, 270, 360},\n\t\t{10, 20, 30},\n\t} {\n\t\tfmt.Printf(\"The mean angle of %v is: %f degrees\\n\", angles, mean_angle(angles))\n\t}\n}"} +{"id": 14, "output": "23:47:43", "Python": "from cmath import rect, phase\nfrom math import radians, degrees\n\n\ndef mean_angle(deg):\n return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n\ndef mean_time(times):\n t = (time.split(':') for time in times)\n seconds = ((float(s) + int(m) * 60 + int(h) * 3600) \n for h, m, s in t)\n day = 24 * 60 * 60\n to_angles = [s * 360. / day for s in seconds]\n mean_as_angle = mean_angle(to_angles)\n mean_seconds = mean_as_angle * day / 360.\n if mean_seconds < 0:\n mean_seconds += day\n h, m = divmod(mean_seconds, 3600)\n m, s = divmod(m, 60)\n return '%02i:%02i:%02i' % (h, m, s)\n\n\nif __name__ == '__main__':\n print( mean_time([\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"]) )", "Go": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"log\"\n \"math\"\n \"time\"\n)\n\nvar inputs = []string{\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"}\n\nfunc main() {\n tList := make([]time.Time, len(inputs))\n const clockFmt = \"15:04:05\"\n var err error\n for i, s := range inputs {\n tList[i], err = time.Parse(clockFmt, s)\n if err != nil {\n log.Fatal(err)\n }\n }\n mean, err := meanTime(tList)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(mean.Format(clockFmt))\n}\n\nfunc meanTime(times []time.Time) (mean time.Time, err error) {\n if len(times) == 0 {\n err = errors.New(\"meanTime: no times specified\")\n return\n }\n var ssum, csum float64\n for _, t := range times {\n h, m, s := t.Clock()\n n := t.Nanosecond()\n fSec := (float64((h*60+m)*60+s) + float64(n)*1e-9)\n sin, cos := math.Sincos(fSec * math.Pi / (12 * 60 * 60))\n ssum += sin\n csum += cos\n }\n if ssum == 0 && csum == 0 {\n err = errors.New(\"meanTime: mean undefined\")\n return\n }\n _, dayFrac := math.Modf(1 + math.Atan2(ssum, csum)/(2*math.Pi))\n return mean.Add(time.Duration(dayFrac * 24 * float64(time.Hour))), nil\n}"} +{"id": 15, "output": "2\n3", "Python": "def median(aray):\n srtd = sorted(aray)\n alen = len(srtd)\n return 0.5*( srtd[(alen-1)//2] + srtd[alen//2])\n\na = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)\nprint a, median(a)\na = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)\nprint a, median(a)", "Go": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc main() {\n fmt.Println(median([]float64{3, 1, 4, 1})) // prints 2\n fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3\n}\n\nfunc median(a []float64) float64 {\n sort.Float64s(a)\n half := len(a) / 2\n m := a[half]\n if len(a)%2 == 0 {\n m = (m + a[half-1]) / 2\n }\n return m\n}"} +{"id": 16, "output": "Vector: []\nMean undefined\n\nVector: [+Inf +Inf]\nMean of 2 numbers is +Inf\n\nVector: [+Inf -Inf]\nMean of 2 numbers is NaN\n\nVector: [3 1 4 1 5 9]\nMean of 6 numbers is 3.8333333333333335\n\nVector: [1e+20 3 1 4 1 5 9 -1e+20]\nMean of 8 numbers is 2.875\n\nVector: [10 9 8 7 6 5 4 3 2 1 0 0 0 0 0.11]\nMean of 15 numbers is 3.674\n\nVector: [10 20 30 40 50 -100 4.7 -1100]\nMean of 8 numbers is -130.6625", "Python": "def average(x):\n return sum(x)/float(len(x)) if x else 0\nprint (average([0,0,3,1,4,1,5,9,0,0]))\nprint (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc mean(v []float64) (m float64, ok bool) {\n if len(v) == 0 {\n return\n }\n // an algorithm that attempts to retain accuracy\n // with widely different values.\n var parts []float64\n for _, x := range v {\n var i int\n for _, p := range parts {\n sum := p + x\n var err float64\n switch ax, ap := math.Abs(x), math.Abs(p); {\n case ax < ap:\n err = x - (sum - p)\n case ap < ax:\n err = p - (sum - x)\n }\n if err != 0 {\n parts[i] = err\n i++\n }\n x = sum\n }\n parts = append(parts[:i], x)\n }\n var sum float64\n for _, x := range parts {\n sum += x\n }\n return sum / float64(len(v)), true\n}\n\nfunc main() {\n for _, v := range [][]float64{\n []float64{}, // mean returns ok = false\n []float64{math.Inf(1), math.Inf(1)}, // answer is +Inf\n\n // answer is NaN, and mean returns ok = true, indicating NaN\n // is the correct result\n []float64{math.Inf(1), math.Inf(-1)},\n\n []float64{3, 1, 4, 1, 5, 9},\n\n // large magnitude numbers cancel. answer is mean of small numbers.\n []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},\n\n []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},\n []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},\n } {\n fmt.Println(\"Vector:\", v)\n if m, ok := mean(v); ok {\n fmt.Printf(\"Mean of %d numbers is %g\\n\\n\", len(v), m)\n } else {\n fmt.Println(\"Mean undefined\\n\")\n }\n }\n}"} +{"id": 17, "output": "[2]\n[2 8]", "Python": "from collections import defaultdict\ndef modes(values):\n\tcount = defaultdict(int)\n\tfor v in values:\n\t\tcount[v] +=1\n\tbest = max(count.values())\n\treturn [k for k,v in count.items() if v == best]\n\nmodes([1,3,6,6,6,6,7,7,12,12,17])\nmodes((1,1,2,4,4))", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(mode([]int{2, 7, 1, 8, 2}))\n fmt.Println(mode([]int{2, 7, 1, 8, 2, 8}))\n}\n\nfunc mode(a []int) []int {\n m := make(map[int]int)\n for _, v := range a {\n m[v]++\n }\n var mode []int\n var n int\n for k, v := range m {\n switch {\n case v < n:\n case v > n:\n n = v\n mode = append(mode[:0], k)\n default:\n mode = append(mode, k)\n }\n }\n return mode\n}"} +{"id": 18, "output": "A: 5.5 G: 4.528728688116765 H: 3.414171521474055\nA >= G >= H: true", "Python": "from operator import mul\nfrom functools import reduce\n\n\ndef amean(num):\n return sum(num) / len(num)\n\n\ndef gmean(num):\n return reduce(mul, num, 1)**(1 / len(num))\n\n\ndef hmean(num):\n return len(num) / sum(1 / n for n in num)\n\n\nnumbers = range(1, 11) # 1..10\na, g, h = amean(numbers), gmean(numbers), hmean(numbers)\nprint(a, g, h)\nassert a >= g >= h", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n sum, sumr, prod := 0., 0., 1.\n for n := 1.; n <= 10; n++ {\n sum += n\n sumr += 1 / n\n prod *= n\n }\n a, g, h := sum/10, math.Pow(prod, .1), 10/sumr\n fmt.Println(\"A:\", a, \"G:\", g, \"H:\", h)\n fmt.Println(\"A >= G >= H:\", a >= g && g >= h)\n}"} +{"id": 19, "output": "6.2048368229954285", "Python": "from math import sqrt\ndef qmean(num):\n\treturn sqrt(sum(n*n for n in num)/len(num))\n\nprint(qmean(range(1,11)))", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n const n = 10\n sum := 0.\n for x := 1.; x <= n; x++ {\n sum += x * x\n }\n fmt.Println(math.Sqrt(sum / n))\n}"} +{"id": 20, "output": "x sma3 sma5\n1.000 1.000 1.000\n2.000 1.500 1.500\n3.000 2.000 2.000\n4.000 3.000 2.500\n5.000 4.000 3.000\n5.000 4.667 3.800\n4.000 4.667 4.200\n3.000 4.000 4.200\n2.000 3.000 3.800\n1.000 2.000 3.000", "Python": "from collections import deque\n\ndef simplemovingaverage(period):\n assert period == int(period) and period > 0, \"Period must be an integer >0\"\n \n summ = n = 0.0\n values = deque([0.0] * period) # old value queue\n\n def sma(x):\n nonlocal summ, n\n \n values.append(x)\n summ += x - values.popleft()\n n = min(n+1, period)\n return summ / n\n\n return sma", "Go": "package main\n\nimport \"fmt\"\n\nfunc sma(period int) func(float64) float64 {\n var i int\n var sum float64\n var storage = make([]float64, 0, period)\n\n return func(input float64) (avrg float64) {\n if len(storage) < period {\n sum += input\n storage = append(storage, input)\n }\n\n\tsum += input - storage[i]\n storage[i], i = input, (i+1)%period\n\tavrg = sum / float64(len(storage))\n\n\treturn\n }\n}\n\nfunc main() {\n sma3 := sma(3)\n sma5 := sma(5)\n fmt.Println(\"x sma3 sma5\")\n for _, x := range []float64{1, 2, 3, 4, 5, 5, 4, 3, 2, 1} {\n fmt.Printf(\"%5.3f %5.3f %5.3f\\n\", x, sma3(x), sma5(x))\n }\n}"} +{"id": 21, "output": "The smallest number whose square ends with 269696 is 25264", "Python": "print(next(x for x in range(30000) if pow(x, 2, 1000000) == 269696))", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tconst (\n\t\ttarget = 269696\n\t\tmodulus = 1000000\n\t)\n\tfor n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...\n\t\tsquare := n * n\n\t\tending := square % modulus\n\t\tif ending == target {\n\t\t\tfmt.Println(\"The smallest number whose square ends with\",\n\t\t\t\ttarget, \"is\", n,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t}\n}"} +{"id": 22, "output": ": ok\n[]: ok\n[]][: not ok\n][][[]: not ok\n[[]][[]]: ok\n][[]]][[[]: not ok\n[]][][][[]][: not ok\n[][]][]]][[[[]: not ok\n[][[[]]][[][[]]]: ok\n[[[][][[]][][[]]]]: ok\n(): not ok", "Python": "import numpy as np\nfrom random import shuffle\ndef gen(n):\n txt = list('[]' * n)\n shuffle(txt)\n return ''.join(txt)\n\nm = np.array([{'[': 1, ']': -1}.get(chr(c), 0) for c in range(128)])\ndef balanced(txt):\n a = np.array(txt, 'c').view(np.uint8)\n return np.all(m[a].cumsum() >= 0)\n\nfor txt in (gen(N) for N in range(10)):\n print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))", "Go": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nfunc init() {\n rand.Seed(time.Now().UnixNano())\n}\n\nfunc generate(n uint) string {\n a := bytes.Repeat([]byte(\"[]\"), int(n))\n for i := len(a) - 1; i >= 1; i-- {\n j := rand.Intn(i + 1)\n a[i], a[j] = a[j], a[i]\n }\n return string(a)\n}\n\nfunc testBalanced(s string) {\n fmt.Print(s + \": \")\n open := 0\n for _,c := range s {\n switch c {\n case '[':\n open++\n case ']':\n if open == 0 {\n fmt.Println(\"not ok\")\n return\n }\n open--\n default:\n fmt.Println(\"not ok\")\n return\n }\n }\n if open == 0 {\n fmt.Println(\"ok\")\n } else {\n fmt.Println(\"not ok\")\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n for i := uint(0); i < 10; i++ {\n testBalanced(generate(i))\n }\n testBalanced(\"()\")\n}"} +{"id": 23, "output": " 10 11 12 13 14 15 26 27 28 29 30 31 42 43 44 \n 45 46 47 58 59 60 61 62 63 74 75 76 77 78 79 \n 90 91 92 93 94 95 106 107 108 109 110 111 122 123 124 \n125 126 127 138 139 140 141 142 143 154 155 156 157 158 159 \n160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 \n175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 \n190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 \n205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 \n220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 \n235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 \n250 251 252 253 254 255 266 267 268 269 270 271 282 283 284 \n285 286 287 298 299 300 301 302 303 314 315 316 317 318 319 \n330 331 332 333 334 335 346 347 348 349 350 351 362 363 364 \n365 366 367 378 379 380 381 382 383 394 395 396 397 398 399 \n410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 \n425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 \n440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 \n455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 \n470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 \n485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 \n500 \n\n301 such numbers found.", "Python": "def p(n):\n '''True if n requires any digits above 9\n when expressed as a hexadecimal.\n '''\n return 9 < n and (9 < n % 16 or p(n // 16))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Matches for the predicate p in the range [0..500]'''\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# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divisible, the final list will be shorter than 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# table :: Int -> [String] -> String\ndef table(n):\n '''A list of strings formatted as\n right-justified rows of n columns.\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# MAIN ---\nif __name__ == '__main__':\n main()", "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}"} +{"id": 24, "output": "Original : Rosetta Code Base64 decode data task\n\nEncoded : Um9zZXR0YSBDb2RlIEJhc2U2NCBkZWNvZGUgZGF0YSB0YXNr\n\nDecoded : Rosetta Code Base64 decode data task", "Python": "import base64\ndata = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='\nprint(base64.b64decode(data).decode('utf-8'))", "Go": "package main\n\nimport (\n \"encoding/base64\"\n \"fmt\"\n)\n\nfunc main() {\n msg := \"Rosetta Code Base64 decode data task\"\n fmt.Println(\"Original :\", msg)\n encoded := base64.StdEncoding.EncodeToString([]byte(msg))\n fmt.Println(\"\\nEncoded :\", encoded)\n decoded, err := base64.StdEncoding.DecodeString(encoded)\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"\\nDecoded :\", string(decoded))\n}"} +{"id": 25, "output": "First fifteen and fiftieth Bell numbers:\n 1: 1\n 2: 1\n 3: 2\n 4: 5\n 5: 15\n 6: 52\n 7: 203\n 8: 877\n 9: 4140\n10: 21147\n11: 115975\n12: 678570\n13: 4213597\n14: 27644437\n15: 190899322\n50: 10726137154573358400342215518590002633917247281\n\nThe first ten rows of Bell's triangle:\n[1]\n[1 2]\n[2 3 5]\n[5 7 10 15]\n[15 20 27 37 52]\n[52 67 87 114 151 203]\n[203 255 322 409 523 674 877]\n[877 1080 1335 1657 2066 2589 3263 4140]\n[4140 5017 6097 7432 9089 11155 13744 17007 21147]\n[21147 25287 30304 36401 43833 52922 64077 77821 94828 115975]", "Python": "def bellTriangle(n):\n tri = [None] * n\n for i in xrange(n):\n tri[i] = [0] * i\n tri[1][0] = 1\n for i in xrange(2, n):\n tri[i][0] = tri[i - 1][i - 2]\n for j in xrange(1, i):\n tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]\n return tri\n\ndef main():\n bt = bellTriangle(51)\n print \"First fifteen and fiftieth Bell numbers:\"\n for i in xrange(1, 16):\n print \"%2d: %d\" % (i, bt[i][0])\n print \"50:\", bt[50][0]\n print\n print \"The first ten rows of Bell's triangle:\"\n for i in xrange(1, 11):\n print bt[i]\n\nmain()", "Go": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc bellTriangle(n int) [][]*big.Int {\n tri := make([][]*big.Int, n)\n for i := 0; i < n; i++ {\n tri[i] = make([]*big.Int, i)\n for j := 0; j < i; j++ {\n tri[i][j] = new(big.Int)\n }\n }\n tri[1][0].SetUint64(1)\n for i := 2; i < n; i++ {\n tri[i][0].Set(tri[i-1][i-2])\n for j := 1; j < i; j++ {\n tri[i][j].Add(tri[i][j-1], tri[i-1][j-1])\n }\n }\n return tri\n}\n\nfunc main() {\n bt := bellTriangle(51)\n fmt.Println(\"First fifteen and fiftieth Bell numbers:\")\n for i := 1; i <= 15; i++ {\n fmt.Printf(\"%2d: %d\\n\", i, bt[i][0])\n }\n fmt.Println(\"50:\", bt[50][0])\n fmt.Println(\"\\nThe first ten rows of Bell's triangle:\")\n for i := 1; i <= 10; i++ {\n fmt.Println(bt[i])\n } \n}"} +{"id": 26, "output": "First 1000 Fibonacci numbers\nDigit Observed Predicted\n 1 0.301 0.301\n 2 0.177 0.176\n 3 0.125 0.125\n 4 0.096 0.097\n 5 0.080 0.079\n 6 0.067 0.067\n 7 0.056 0.058\n 8 0.053 0.051\n 9 0.045 0.046", "Python": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n a,b = 1,1\n while True:\n yield a\n a,b = b,a+b\n\n# powers of 3 as a test sequence\ndef power_of_threes():\n return (3**k for k in count(0))\n\ndef heads(s):\n for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n c = Counter(s)\n size = sum(c.values())\n res = [c[d]/size for d in range(1,10)]\n\n print(\"\\n%s Benfords deviation\" % title)\n for r, e in zip(res, expected):\n print(\"%5.1f%% %5.1f%% %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n show_dist(\"fibbed\", islice(heads(fib()), 1000))\n show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n # just to show that not all kind-of-random sets behave like that\n show_dist(\"random\", islice(heads(rand1000()), 10000))", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc Fib1000() []float64 {\n a, b, r := 0., 1., [1000]float64{}\n for i := range r {\n r[i], a, b = b, b, b+a\n }\n return r[:]\n}\n\nfunc main() {\n show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n var f [9]int\n for _, v := range c {\n f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n }\n fmt.Println(title)\n fmt.Println(\"Digit Observed Predicted\")\n for i, n := range f {\n fmt.Printf(\" %d %9.3f %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n math.Log10(1+1/float64(i+1)))\n }\n}"} +{"id": 27, "output": "B( 0) = 1/1\nB( 1) = 1/2\nB( 2) = 1/6\nB( 4) = -1/30\nB( 6) = 1/42\nB( 8) = -1/30\nB(10) = 5/66", "Python": "from fractions import Fraction as Fr\n\ndef bernoulli(n):\n A = [0] * (n+1)\n for m in range(n+1):\n A[m] = Fr(1, m+1)\n for j in range(m, 0, -1):\n A[j-1] = j*(A[j-1] - A[j])\n return A[0] # (which is Bn)\n\nbn = [(i, bernoulli(i)) for i in range(11)]\nbn = [(i, b) for i,b in bn if b]\nwidth = max(len(str(b.numerator)) for i,b in bn)\nfor i,b in bn:\n print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc b(n int) *big.Rat {\n\tvar f big.Rat\n\ta := make([]big.Rat, n+1)\n\tfor m := range a {\n\t\ta[m].SetFrac64(1, int64(m+1))\n\t\tfor j := m; j >= 1; j-- {\n\t\t\td := &a[j-1]\n\t\t\td.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j]))\n\t\t}\n\t}\n\treturn f.Set(&a[0])\n}\n\nfunc main() {\n\tfor n := 0; n <= 10; n++ {\n\t\tif b := b(n); b.Num().BitLen() > 0 {\n\t\t\tfmt.Printf(\"B(%2d) =%45s/%s\\n\", n, b.Num(), b.Denom())\n\t\t}\n\t}\n}"} +{"id": 28, "output": "0\n1\n10\n11\n100\n101\n110\n111\n1000\n1001\n1010\n1011\n1100\n1101\n1110\n1111", "Python": "for i in range(16): print('{0:b}'.format(i))", "Go": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfor i := 0; i < 16; i++ {\n\t\tfmt.Printf(\"%b\\n\", i)\n\t}\n}"} +{"id": 29, "output": "SEQUENCE:\n 0: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\n 50: CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\n 100: AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\n 150: GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\n 200: CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\n 250: TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\n 300: TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\n 350: CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\n 400: TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\n 450: GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\nBASE COUNT:\n A: 129\n C: 97\n G: 119\n T: 155\n ------\n \u03a3: 500\n ======", "Python": "from collections import Counter\n\ndef basecount(dna):\n return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n for i, part in enumerate(seq_split(dna, n)):\n print(f\"{i*n:>5}: {part}\")\n print(\"\\n BASECOUNT:\")\n tot = 0\n for base, count in basecount(dna):\n print(f\" {base:>3}: {count}\")\n tot += count\n base, count = 'TOT', tot\n print(f\" {base:>3}= {count}\")\n \nif __name__ == '__main__':\n print(\"SEQUENCE:\")\n sequence = '''\\\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'''\n seq_pp(sequence)", "Go": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc main() {\n dna := \"\" +\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n fmt.Println(\"SEQUENCE:\")\n le := len(dna)\n for i := 0; i < le; i += 50 {\n k := i + 50\n if k > le {\n k = le\n }\n fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n }\n baseMap := make(map[byte]int) // allows for 'any' base\n for i := 0; i < le; i++ {\n baseMap[dna[i]]++\n }\n var bases []byte\n for k := range baseMap {\n bases = append(bases, k)\n }\n sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order\n return bases[i] < bases[j]\n })\n\n fmt.Println(\"\\nBASE COUNT:\")\n for _, base := range bases {\n fmt.Printf(\" %c: %3d\\n\", base, baseMap[base])\n }\n fmt.Println(\" ------\")\n fmt.Println(\" \u03a3:\", le)\n fmt.Println(\" ======\")\n}"} +{"id": 30, "output": "e = 2.718281828459046", "Python": "import math\n#Implementation of Brother's formula\ne0 = 0\ne = 2\nn = 0\nfact = 1\nwhile(e-e0 > 1e-15):\n\te0 = e\n\tn += 1\n\tfact *= 2*n*(2*n+1)\n\te += (2.*n+2)/fact\n\nprint \"Computed e = \"+str(e)\nprint \"Real e = \"+str(math.e)\nprint \"Error = \"+str(math.e-e)\nprint \"Number of iterations = \"+str(n)", "Go": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst epsilon = 1.0e-15\n\nfunc main() {\n fact := uint64(1)\n e := 2.0\n n := uint64(2)\n for {\n e0 := e\n fact *= n\n n++\n e += 1.0 / float64(fact)\n if math.Abs(e - e0) < epsilon {\n break\n }\n }\n fmt.Printf(\"e = %.15f\\n\", e)\n}"} +{"id": 31, "output": "The first 20 terms of the Calkin-Wilf sequnence are:\n 1: 1\n 2: 1/2\n 3: 2\n 4: 1/3\n 5: 3/2\n 6: 2/3\n 7: 3\n 8: 1/4\n 9: 4/3\n10: 3/5\n11: 5/2\n12: 2/5\n13: 5/3\n14: 3/4\n15: 4\n16: 1/5\n17: 5/4\n18: 4/7\n19: 7/3\n20: 3/8\n\n83116/51639 is the 123,456,789th term of the 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.\")", "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 { // ensure always odd\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}"} +{"id": 32, "output": "87.70.141.1/22 -> 87.70.140.0/22\n36.18.154.103/12 -> 36.16.0.0/12\n62.62.197.11/29 -> 62.62.197.8/29\n67.137.119.181/4 -> 64.0.0.0/4\n161.214.74.21/24 -> 161.214.74.0/24\n184.232.176.184/18 -> 184.232.128.0/18", "Python": "DIGITS = (24, 16, 8, 0)\n\n\ndef dotted_to_int(dotted: str) -> int:\n digits = [int(digit) for digit in dotted.split(\".\")]\n return sum(a << b for a, b in zip(digits, DIGITS))\n\n\ndef int_to_dotted(ip: int) -> str:\n digits = [(ip & (255 << d)) >> d for d in DIGITS]\n return \".\".join(str(d) for d in digits)\n\n\ndef network_mask(number_of_bits: int) -> int:\n return ((1 << number_of_bits) - 1) << (32 - number_of_bits)\n\n\ndef canonicalize(ip: str) -> str:\n dotted, network_bits = ip.split(\"/\")\n i = dotted_to_int(dotted)\n mask = network_mask(int(network_bits))\n return int_to_dotted(i & mask) + \"/\" + network_bits\n\n\nTEST_CASES = [\n (\"36.18.154.103/12\", \"36.16.0.0/12\"),\n (\"62.62.197.11/29\", \"62.62.197.8/29\"),\n (\"67.137.119.181/4\", \"64.0.0.0/4\"),\n (\"161.214.74.21/24\", \"161.214.74.0/24\"),\n (\"184.232.176.184/18\", \"184.232.128.0/18\"),\n]\n\nif __name__ == \"__main__\":\n for ip, expect in TEST_CASES:\n rv = canonicalize(ip)\n print(f\"{ip:<18} -> {rv}\")\n assert rv == expect", "Go": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n \"strings\"\n)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n// canonicalize a CIDR block: make sure none of the host bits are set\nfunc canonicalize(cidr string) string {\n // dotted-decimal / bits in network part\n split := strings.Split(cidr, \"/\")\n dotted := split[0]\n size, err := strconv.Atoi(split[1])\n check(err)\n\n // get IP as binary string\n var bin []string\n for _, n := range strings.Split(dotted, \".\") {\n i, err := strconv.Atoi(n)\n check(err)\n bin = append(bin, fmt.Sprintf(\"%08b\", i))\n }\n binary := strings.Join(bin, \"\")\n\n // replace the host part with all zeros\n binary = binary[0:size] + strings.Repeat(\"0\", 32-size)\n\n // convert back to dotted-decimal\n var canon []string\n for i := 0; i < len(binary); i += 8 {\n num, err := strconv.ParseInt(binary[i:i+8], 2, 64)\n check(err)\n canon = append(canon, fmt.Sprintf(\"%d\", num))\n }\n\n // and return\n return strings.Join(canon, \".\") + \"/\" + split[1]\n}\n\nfunc main() {\n tests := []string{\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\",\n }\n\n for _, test := range tests {\n fmt.Printf(\"%-18s -> %s\\n\", test, canonicalize(test))\n }\n}"} +{"id": 33, "output": "*********************************************************************************\n*************************** ***************************\n********* ********* ********* *********\n*** *** *** *** *** *** *** ***\n* * * * * * * * * * * * * * * *", "Python": "WIDTH = 81\nHEIGHT = 5\n\nlines=[]\ndef cantor(start, len, index):\n seg = len / 3\n if seg == 0:\n return None\n for it in xrange(HEIGHT-index):\n i = index + it\n for jt in xrange(seg):\n j = start + seg + jt\n pos = i * WIDTH + j\n lines[pos] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n return None\n\nlines = ['*'] * (WIDTH*HEIGHT)\ncantor(0, WIDTH, 1)\n\nfor i in xrange(HEIGHT):\n beg = WIDTH * i\n print ''.join(lines[beg : beg+WIDTH])", "Go": "package main\n\nimport \"fmt\"\n\nconst (\n width = 81\n height = 5\n)\n\nvar lines [height][width]byte\n\nfunc init() {\n for i := 0; i < height; i++ {\n for j := 0; j < width; j++ {\n lines[i][j] = '*'\n }\n }\n}\n\nfunc cantor(start, len, index int) {\n seg := len / 3\n if seg == 0 {\n return\n }\n for i := index; i < height; i++ {\n for j := start + seg; j < start + 2 * seg; j++ {\n lines[i][j] = ' '\n }\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n}\n\nfunc main() {\n cantor(0, width, 1)\n for _, line := range lines {\n fmt.Println(string(line[:]))\n }\n}"} +{"id": 34, "output": "[[1 3] [1 4] [2 3] [2 4]]\n[[3 1] [3 2] [4 1] [4 2]]\n[]\n[]\n", "Python": "import itertools\n\ndef cp(lsts):\n return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n \n for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),\n ((1, 2, 3), (30,), (500, 100)),\n ((1, 2, 3), (), (500, 100))]:\n print(lists, '=>')\n pp(cp(lists), indent=2)", "Go": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n p := make([]pair, len(a)*len(b))\n i := 0\n for _, a := range a {\n for _, b := range b {\n p[i] = pair{a, b}\n i++\n }\n }\n return p\n}\n\nfunc main() {\n fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n fmt.Println(cart2([]int{1, 2}, nil))\n fmt.Println(cart2(nil, []int{1, 2}))\n}"} +{"id": 35, "output": "Test case base = 10, begin = 1, end = 100:\nSubset: [1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99 100]\nKaprekar: [1 9 45 55 99]\nValid subset.\n\nTest case base = 17, begin = 10, end = gg:\nSubset: [10 1f 1g 2e 2f 3d 3e 4c 4d 5b 5c 6a 6b 79 7a 88 89 97 98 a6 a7 b5 b6 c4 c5 d3 d4 e2 e3 f1 f2 g0 g1 gg]\nKaprekar: [3d d4 gg]\nValid subset.", "Python": "def CastOut(Base=10, Start=1, End=999999):\n ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]\n x,y = divmod(Start, Base-1)\n while True:\n for n in ran:\n k = (Base-1)*x + n\n if k < Start:\n continue\n if k > End:\n return\n yield k\n x += 1\n\nfor V in CastOut(Base=16,Start=1,End=255):\n print(V, end=' ')", "Go": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n)\n\nfunc co9Peterson(base int) (cob func(string) (byte, error), err error) {\n if base < 2 || base > 36 {\n return nil, fmt.Errorf(\"co9Peterson: %d invalid base\", base)\n }\n \n addDigits := func(a, b byte) (string, error) {\n ai, err := strconv.ParseInt(string(a), base, 64)\n if err != nil {\n return \"\", err\n }\n bi, err := strconv.ParseInt(string(b), base, 64)\n if err != nil {\n return \"\", err\n }\n return strconv.FormatInt(ai+bi, base), nil\n }\n // a '9' in the specified base. that is, the greatest digit.\n s9 := strconv.FormatInt(int64(base-1), base)\n b9 := s9[0]\n \n cob = func(n string) (r byte, err error) {\n r = '0'\n for i := 0; i < len(n); i++ { // for each digit of the number\n d := n[i]\n switch {\n case d == b9: // if the digit is '9' of the base, cast it out\n continue\n // if the result so far is 0, the digit becomes the result\n case r == '0':\n r = d\n continue\n }\n // otherwise, add the new digit to the result digit\n s, err := addDigits(r, d)\n if err != nil {\n return 0, err\n }\n switch {\n case s == s9: // if the sum is \"9\" of the base, cast it out\n r = '0'\n continue\n // if the sum is a single digit, it becomes the result\n case len(s) == 1:\n r = s[0]\n continue\n }\n \n r, err = cob(s)\n if err != nil {\n return 0, err\n }\n }\n return\n }\n return\n}\n\n\nfunc subset(base int, begin, end string) (s []string, err error) {\n // convert begin, end to native integer types for easier iteration\n begin64, err := strconv.ParseInt(begin, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset begin: %v\", err)\n }\n end64, err := strconv.ParseInt(end, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset end: %v\", err)\n }\n // generate casting out nines function for specified base\n cob, err := co9Peterson(base)\n if err != nil {\n return\n }\n for k := begin64; k <= end64; k++ {\n ks := strconv.FormatInt(k, base)\n rk, err := cob(ks)\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n rk2, err := cob(strconv.FormatInt(k*k, base))\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n // test for candidate Kaprekar number\n if rk == rk2 {\n s = append(s, ks)\n }\n }\n return\n}\n\nvar testCases = []struct {\n base int\n begin, end string\n kaprekar []string\n}{\n {10, \"1\", \"100\", []string{\"1\", \"9\", \"45\", \"55\", \"99\"}},\n {17, \"10\", \"gg\", []string{\"3d\", \"d4\", \"gg\"}},\n}\n \nfunc main() {\n for _, tc := range testCases {\n fmt.Printf(\"\\nTest case base = %d, begin = %s, end = %s:\\n\",\n tc.base, tc.begin, tc.end)\n s, err := subset(tc.base, tc.begin, tc.end)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(\"Subset: \", s)\n fmt.Println(\"Kaprekar:\", tc.kaprekar)\n sx := 0\n for _, k := range tc.kaprekar {\n for {\n if sx == len(s) {\n fmt.Printf(\"Fail:\", k, \"not in subset\")\n return\n }\n if s[sx] == k {\n sx++\n break\n }\n sx++\n }\n }\n fmt.Println(\"Valid subset.\")\n }\n}"} +{"id": 36, "output": "three -> 3\nfour -> 4\nthree + four -> 7\nthree * four -> 12\nthree ^ four -> 81\nfour ^ three -> 64\n5 -> five -> 5", "Python": "from itertools import repeat\nfrom functools import reduce\n\n\n# ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------\n\ndef churchZero():\n '''The identity function.\n No applications of any supplied f\n to its argument.\n '''\n return lambda f: identity\n\n\ndef churchSucc(cn):\n '''The successor of a given\n Church numeral. One additional\n application of f. Equivalent to\n the arithmetic addition of one.\n '''\n return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n '''The arithmetic sum of two Church numerals.'''\n return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n '''The arithmetic product of two Church numerals.'''\n return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n '''Exponentiation of Church numerals. m^n'''\n return lambda n: n(m)\n\n\ndef churchFromInt(n):\n '''The Church numeral equivalent of\n a given integer.\n '''\n return lambda f: (\n foldl\n (compose)\n (identity)\n (replicate(n)(f))\n )\n\n\n# OR, alternatively:\ndef churchFromInt_(n):\n '''The Church numeral equivalent of a given\n integer, by explicit recursion.\n '''\n if 0 == n:\n return churchZero()\n else:\n return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n '''The integer equivalent of a\n given Church numeral.\n '''\n return cn(succ)(0)\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\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# ------------------ GENERIC FUNCTIONS -------------------\n\n# compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c\ndef compose(f):\n '''A left to right composition of two\n functions f and g'''\n return lambda g: lambda x: g(f(x))\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\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# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# replicate :: Int -> a -> [a]\ndef replicate(n):\n '''A list of length n in which every\n element has the value x.\n '''\n return lambda x: repeat(x, n)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\nif __name__ == '__main__':\n main()", "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}"} +{"id": 37, "output": "func #0: 0\nfunc #3: 9", "Python": "funcs = [(lambda i: lambda: i)(i * i) for i in range(10)]\nprint funcs[3]() # prints 9", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fs := make([]func() int, 10)\n for i := range fs {\n i := i\n fs[i] = func() int {\n return i * i\n }\n }\n fmt.Println(\"func #0:\", fs[0]())\n fmt.Println(\"func #3:\", fs[3]())\n}"} +{"id": 38, "output": "Police Sanitation Fire\n------ ---------- ----\n 2 3 7\n 2 4 6\n 2 6 4\n 2 7 3\n 4 1 7\n 4 2 6\n 4 3 5\n 4 5 3\n 4 6 2\n 4 7 1\n 6 1 5\n 6 2 4\n 6 4 2\n 6 5 1\n\n14 valid combinations", "Python": "from itertools import permutations\n \ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n \nif __name__ == '__main__':\n solve()", "Go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Police Sanitation Fire\")\n fmt.Println(\"------ ---------- ----\")\n count := 0\n for i := 2; i < 7; i += 2 {\n for j := 1; j < 8; j++ {\n if j == i { continue }\n for k := 1; k < 8; k++ {\n if k == i || k == j { continue }\n if i + j + k != 12 { continue }\n fmt.Printf(\" %d %d %d\\n\", i, j, k)\n count++\n }\n }\n }\n fmt.Printf(\"\\n%d valid combinations\\n\", count)\n}"} +{"id": 39, "output": "9: 123456789\n7: 1234567\n6: abcdef\n4: abcd", "Python": "def _(message):\n \"\"\"Translate: an placeholder for i18n and l10n gettext or similar.\"\"\"\n return message\n\n\ndef compare_and_report_length(*objects, sorted_=True, reverse=True):\n lengths = list(map(len, objects))\n max_length = max(lengths)\n min_length = min(lengths)\n lengths_and_objects = zip(lengths, objects)\n\n # Longer phrases make translations into other natural languages easier.\n #\n has_length = _('has length')\n if all(isinstance(obj, str) for obj in objects):\n predicate_max = _('and is the longest string')\n predicate_min = _('and is the shortest string')\n predicate_ave = _('and is neither the longest nor the shortest string')\n else:\n predicate_max = _('and is the longest object')\n predicate_min = _('and is the shortest object')\n predicate_ave = _('and is neither the longest nor the shortest object')\n\n if sorted_:\n lengths_and_objects = sorted(lengths_and_objects, reverse=reverse)\n\n for length, obj in lengths_and_objects:\n if length == max_length:\n predicate = predicate_max\n elif length == min_length:\n predicate = predicate_min\n else:\n predicate = predicate_ave\n print(obj, has_length, length, predicate)\n\n\nA = 'I am string'\nB = 'I am string too'\nLIST = [\"abcd\", \"123456789\", \"abcdef\", \"1234567\"]\n\n\nprint('Two strings')\nprint()\ncompare_and_report_length(A, B)\nprint()\n\nprint('A list of strings')\nprint()\ncompare_and_report_length(*LIST)\nprint()", "Go": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\t// If no command-line arguments are specified when running the program, use example data\n\tif len(os.Args) == 1 {\n\t\tcompareStrings(\"abcd\", \"123456789\", \"abcdef\", \"1234567\")\n\t} else {\n\t\t// First argument, os.Args[0], is program name. Command-line arguments start from 1\n\t\tstrings := os.Args[1:]\n\t\tcompareStrings(strings...)\n\t}\n}\n\n// Variadic function that takes any number of string arguments for comparison\nfunc compareStrings(strings ...string) {\n\t// \"strings\" slice is sorted in place\n\t// sort.SliceStable keeps strings in their original order when elements are of equal length (unlike sort.Slice)\n\tsort.SliceStable(strings, func(i, j int) bool {\n\t\treturn len(strings[i]) > len(strings[j])\n\t})\n\n\tfor _, s := range strings {\n\t\tfmt.Printf(\"%d: %s\\n\", len(s), s)\n\t}\n}"} +{"id": 0, "output": "Door 1: open\nDoor 2: closed\nDoor 3: closed\nDoor 4: open\nDoor 5: closed\nDoor 6: closed\nDoor 7: closed\nDoor 8: closed\nDoor 9: open\nDoor 10: closed", "Python": "doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\" % (i+1), 'open' if doors[i] else 'close')", "PHP": ""} +{"id": 1, "output": "10 bottles of beer on the wall,\n10 bottles of beer!\nTake one down, pass it around!\n9 bottles of beer on the wall!\n\n9 bottles of beer on the wall,\n9 bottles of beer!\nTake one down, pass it around!\n8 bottles of beer on the wall!\n\n8 bottles of beer on the wall,\n8 bottles of beer!\nTake one down, pass it around!\n7 bottles of beer on the wall!\n\n7 bottles of beer on the wall,\n7 bottles of beer!\nTake one down, pass it around!\n6 bottles of beer on the wall!\n\n6 bottles of beer on the wall,\n6 bottles of beer!\nTake one down, pass it around!\n5 bottles of beer on the wall!\n\n5 bottles of beer on the wall,\n5 bottles of beer!\nTake one down, pass it around!\n4 bottles of beer on the wall!\n\n4 bottles of beer on the wall,\n4 bottles of beer!\nTake one down, pass it around!\n3 bottles of beer on the wall!\n\n3 bottles of beer on the wall,\n3 bottles of beer!\nTake one down, pass it around!\n2 bottles of beer on the wall!\n\n2 bottles of beer on the wall,\n2 bottles of beer!\nTake one down, pass it around!\n1 bottle of beer on the wall!\n\n1 bottle of beer on the wall,\n1 bottle of beer!\nTake one down, pass it around!\nNo more bottles of beer on the wall!", "Python": "for i in range(10, 0, -1):b='bottles of beer';w=f' {b} on the wall';print(f'{i}{w}, {i} {b}\\nTake one down and pass it around, {i-1}{w}.\\n')", "PHP": " 1)\n echo ($i - 1) . \" bottle$plural of beer on the wall!\\n\\n\";\n else\n echo \"No more bottles of beer on the wall!\\n\";\n}\n?>"} +{"id": 2, "output": "A: True\nBARK: True\nBOOK: False\nTREAT: True\nCOMMON: False\nSQUAD: True\nConfuse: True", "Python": "blocks = [(\"B\", \"O\"),\n (\"X\", \"K\"),\n (\"D\", \"Q\"),\n (\"C\", \"P\"),\n (\"N\", \"A\"),\n (\"G\", \"T\"),\n (\"R\", \"E\"),\n (\"T\", \"G\"),\n (\"Q\", \"D\"),\n (\"F\", \"S\"),\n (\"J\", \"W\"),\n (\"H\", \"U\"),\n (\"V\", \"I\"),\n (\"A\", \"N\"),\n (\"O\", \"B\"),\n (\"E\", \"R\"),\n (\"F\", \"S\"),\n (\"L\", \"Y\"),\n (\"P\", \"C\"),\n (\"Z\", \"M\")]\n\n\ndef can_make_word(word, block_collection=blocks):\n \"\"\"\n Return True if `word` can be made from the blocks in `block_collection`.\n\n >>> can_make_word(\"\")\n False\n >>> can_make_word(\"a\")\n True\n >>> can_make_word(\"bark\")\n True\n >>> can_make_word(\"book\")\n False\n >>> can_make_word(\"treat\")\n True\n >>> can_make_word(\"common\")\n False\n >>> can_make_word(\"squad\")\n True\n >>> can_make_word(\"coNFused\")\n True\n \"\"\"\n if not word:\n return False\n\n blocks_remaining = block_collection[:]\n for char in word.upper():\n for block in blocks_remaining:\n if char in block:\n blocks_remaining.remove(block)\n break\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n \"COMMON\", \"squad\", \"Confused\"]))", "PHP": " $block) {\n if (strpos($block, $char) !== FALSE) {\n unset($blocks[$k]);\n continue(2);\n }\n }\n return false;\n }\n return true;\n}\n\nforeach ($words as $word) {\n echo $word.': ';\n echo canMakeWord($word) ? \"True\" : \"False\";\n echo \"\\r\\n\";\n}"} +{"id": 3, "output": "k = 1: 2 3 5 7 11 13 17 19 23 29\nk = 2: 4 6 9 10 14 15 21 22 25 26\nk = 3: 8 12 18 20 27 28 30 42 44 45\nk = 4: 16 24 36 40 54 56 60 81 84 88\nk = 5: 32 48 72 80 108 112 120 162 168 176", "Python": "from prime_decomposition import decompose\nfrom itertools import islice, count\ntry: \n from functools import reduce\nexcept: \n pass\n\n\ndef almostprime(n, k=2):\n d = decompose(n)\n try:\n terms = [next(d) for i in range(k)]\n return reduce(int.__mul__, terms, 1) == n\n except:\n return False\n\nif __name__ == '__main__':\n for k in range(1,6):\n print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))", "PHP": ""} +{"id": 4, "output": "220 284
1184 1210
2620 2924
5020 5564
6232 6368
10744 10856
12285 14595
17296 18416
", "Python": "from itertools import chain\nfrom math import sqrt\n\n\n# amicablePairsUpTo :: Int -> [(Int, Int)]\ndef amicablePairsUpTo(n):\n '''List of all amicable pairs\n of integers below n.\n '''\n sigma = compose(sum)(properDivisors)\n\n def amicable(x):\n y = sigma(x)\n return [(x, y)] if (x < y and x == sigma(y)) else []\n\n return concatMap(amicable)(\n enumFromTo(1)(n)\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Amicable pairs of integers up to 20000'''\n\n for x in amicablePairsUpTo(20000):\n print(x)\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list or string over which a function f\n has been mapped.\n The list monad can be derived by using an (a -> [b])\n function which wraps its output in a list (using an\n empty list to represent computational failure).\n '''\n return lambda xs: (''.join if isinstance(xs, str) else list)(\n chain.from_iterable(map(f, xs))\n )\n\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n '''Enumeration of integer values [m..n]'''\n def go(n):\n return list(range(m, 1 + n))\n return lambda n: go(n)\n\n\n# properDivisors :: Int -> [Int]\ndef properDivisors(n):\n '''Positive divisors of n, excluding n itself'''\n root_ = sqrt(n)\n intRoot = int(root_)\n blnSqr = root_ == intRoot\n lows = [x for x in range(1, 1 + intRoot) if 0 == n % x]\n return lows + [\n n // x for x in reversed(\n lows[1:-1] if blnSqr else lows[1:]\n )\n ]\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "PHP": " $n) {\n if (sumDivs($m) == $n) echo $n.\" \".$m.\"
\";\n }\n}\n\n?>"} +{"id": 5, "output": "4 6 8 10 12 14 15 18 20 21 22 26 27 28 30 32 33 34 35 36 38 39 42 44 45 46 48 50 51 52 55 57 58 62 63 65 66 68 69 70 74 75 76 77 78 80 82 85 86 87 91 92 93 94 95 98 99 100 102 105 106 108 110 111 112 114 115 116 117 118 119 120 ", "Python": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,121):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,", "PHP": ""} +{"id": 6, "output": "The mean time of day is 23:47:43 (angle 356.9306730355).", "Python": "from cmath import rect, phase\nfrom math import radians, degrees\n\n\ndef mean_angle(deg):\n return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n\ndef mean_time(times):\n t = (time.split(':') for time in times)\n seconds = ((float(s) + int(m) * 60 + int(h) * 3600) \n for h, m, s in t)\n day = 24 * 60 * 60\n to_angles = [s * 360. / day for s in seconds]\n mean_as_angle = mean_angle(to_angles)\n mean_seconds = mean_as_angle * day / 360.\n if mean_seconds < 0:\n mean_seconds += day\n h, m = divmod(mean_seconds, 3600)\n m, s = divmod(m, 60)\n return '%02i:%02i:%02i' % (h, m, s)\n\n\nif __name__ == '__main__':\n print( mean_time([\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"]) )", "PHP": ""} +{"id": 7, "output": "Arithmetic: 5.5\nGeometric: 4.5287286881168\nHarmonic: 3.4141715214741", "Python": "from operator import mul\nfrom functools import reduce\n\n\ndef amean(num):\n return sum(num) / len(num)\n\n\ndef gmean(num):\n return reduce(mul, num, 1)**(1 / len(num))\n\n\ndef hmean(num):\n return len(num) / sum(1 / n for n in num)\n\n\nnumbers = range(1, 11) # 1..10\na, g, h = amean(numbers), gmean(numbers), hmean(numbers)\nprint(a, g, h)\nassert a >= g >= h", "PHP": " Float\ndef rootMeanSquare(xs):\n return sqrt(reduce(lambda a, x: a + x * x, xs, 0) / len(xs))\n\n\nprint(\n rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n)", "PHP": "10}' for n\n in islice(catalans3(), 15)\n ])\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# pred :: Int -> Int\ndef pred(n):\n '''Predecessor function'''\n return n - 1\n\n\n# succ :: Int -> Int\ndef succ(n):\n '''Successor function'''\n return 1 + n\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "PHP": " 1);\n \n private function fill_cache($i)\n {\n $accum = 0;\n $n = $i-1;\n for($k = 0; $k <= $n; $k++)\n {\n $accum += $this->item($k)*$this->item($n-$k);\n } \n self::$cache[$i] = $accum;\n }\n function item($i)\n {\n if (!isset(self::$cache[$i]))\n {\n $this->fill_cache($i);\n }\n return self::$cache[$i];\n }\n}\n\n$cn = new CatalanNumbersSerie();\nfor($i = 0; $i <= 15;$i++)\n{\n $r = $cn->item($i);\n echo \"$i = $r\\r\\n\";\n}\n?>"} +{"id": 12, "output": "7\n12\n81\n64\n", "Python": "from itertools import repeat\nfrom functools import reduce\n\n\n# ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------\n\ndef churchZero():\n '''The identity function.\n No applications of any supplied f\n to its argument.\n '''\n return lambda f: identity\n\n\ndef churchSucc(cn):\n '''The successor of a given\n Church numeral. One additional\n application of f. Equivalent to\n the arithmetic addition of one.\n '''\n return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n '''The arithmetic sum of two Church numerals.'''\n return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n '''The arithmetic product of two Church numerals.'''\n return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n '''Exponentiation of Church numerals. m^n'''\n return lambda n: n(m)\n\n\ndef churchFromInt(n):\n '''The Church numeral equivalent of\n a given integer.\n '''\n return lambda f: (\n foldl\n (compose)\n (identity)\n (replicate(n)(f))\n )\n\n\n# OR, alternatively:\ndef churchFromInt_(n):\n '''The Church numeral equivalent of a given\n integer, by explicit recursion.\n '''\n if 0 == n:\n return churchZero()\n else:\n return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n '''The integer equivalent of a\n given Church numeral.\n '''\n return cn(succ)(0)\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\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# ------------------ GENERIC FUNCTIONS -------------------\n\n# compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c\ndef compose(f):\n '''A left to right composition of two\n functions f and g'''\n return lambda g: lambda x: g(f(x))\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\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# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# replicate :: Int -> a -> [a]\ndef replicate(n):\n '''A list of length n in which every\n element has the value x.\n '''\n return lambda x: repeat(x, n)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\nif __name__ == '__main__':\n main()", "PHP": ""} +{"id": 13, "output": "9", "Python": "funcs = []\nfor i in range(10):\n funcs.append(lambda i=i: i * i)\nprint funcs[3]() # prints 9", "PHP": ""} +{"id": 14, "output": "5724 is valid
5727 is invalid
112946 is valid
112949 is invalid
", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "PHP": "\";\n}\n?>"} +{"id": 15, "output": "25 Dec 2011 is Sunday\n25 Dec 2016 is Sunday\n25 Dec 2022 is Sunday\n25 Dec 2033 is Sunday\n25 Dec 2039 is Sunday\n25 Dec 2044 is Sunday\n25 Dec 2050 is Sunday\n25 Dec 2061 is Sunday\n25 Dec 2067 is Sunday\n25 Dec 2072 is Sunday\n25 Dec 2078 is Sunday\n25 Dec 2089 is Sunday\n25 Dec 2095 is Sunday\n25 Dec 2101 is Sunday\n25 Dec 2107 is Sunday\n25 Dec 2112 is Sunday\n25 Dec 2118 is Sunday", "Python": "from datetime import date\nfrom itertools import islice\n\n\n# xmasIsSunday :: Int -> Bool\ndef xmasIsSunday(y):\n '''True if Dec 25 in the given year is a Sunday.'''\n return 6 == date(y, 12, 25).weekday()\n\n\n# main :: IO ()\ndef main():\n '''Years between 2008 and 2121 with 25 Dec on a Sunday'''\n\n xs = list(filter(\n xmasIsSunday,\n enumFromTo(2008)(2121)\n ))\n total = len(xs)\n print(\n fTable(main.__doc__ + ':\\n\\n' + '(Total ' + str(total) + ')\\n')(\n lambda i: str(1 + i)\n )(str)(index(xs))(\n enumFromTo(0)(total - 1)\n )\n )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# index (!!) :: [a] -> Int -> a\ndef index(xs):\n '''Item at given (zero-based) index.'''\n return lambda n: None if 0 > n else (\n xs[n] if (\n hasattr(xs, \"__getitem__\")\n ) else next(islice(xs, n, None))\n )\n\n\n\n# FORMATTING ---------------------------------------------\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\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# MAIN --\nif __name__ == '__main__':\n main()", "PHP": "format(\"w\") == 0 )\n {\n echo \"25 Dec $i is Sunday\\n\";\n }\n}\n?>"} +{"id": 16, "output": "Hello world!", "Python": "print \"Hello world!\"", "PHP": ""} +{"id": 17, "output": "0 15 3 -9 12
(empty)
4
\n", "Python": "from functools import (reduce)\n\n\n# maxSubseq :: [Int] -> [Int] -> (Int, [Int])\ndef maxSubseq(xs):\n '''Subsequence of xs with the maximum sum'''\n def go(ab, x):\n (m1, m2) = ab[0]\n hi = max((0, []), (m1 + x, m2 + [x]))\n return (hi, max(ab[1], hi))\n return reduce(go, xs, ((0, []), (0, [])))[1]\n\n\n# TEST -----------------------------------------------------------\nprint(\n maxSubseq(\n [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]\n )\n)", "PHP": " $max_sum) {\n $max_sum = $sum;\n $max_start = $sum_start;\n $max_len = $i + 1 - $max_start;\n }\n if ($sum < 0) { # start new sequence\n $sum = 0;\n $sum_start = $i + 1;\n }\n }\n return array_slice($sequence, $max_start, $max_len);\n}\n \nfunction print_array($arr) {\n if (count($arr) > 0) {\n echo join(\" \", $arr);\n } else {\n echo \"(empty)\";\n }\n echo '
';\n} \n// tests\nprint_array(max_sum_seq(array(-1, 0, 15, 3, -9, 12, -4)));\nprint_array(max_sum_seq(array(-1)));\nprint_array(max_sum_seq(array(4, -10, 3)));\n?>"} +{"id": 18, "output": "array(26) {\n [0]=>\n string(1) \"a\"\n [1]=>\n string(1) \"b\"\n [2]=>\n string(1) \"c\"\n [3]=>\n string(1) \"d\"\n [4]=>\n string(1) \"e\"\n [5]=>\n string(1) \"f\"\n [6]=>\n string(1) \"g\"\n [7]=>\n string(1) \"h\"\n [8]=>\n string(1) \"i\"\n [9]=>\n string(1) \"j\"\n [10]=>\n string(1) \"k\"\n [11]=>\n string(1) \"l\"\n [12]=>\n string(1) \"m\"\n [13]=>\n string(1) \"n\"\n [14]=>\n string(1) \"o\"\n [15]=>\n string(1) \"p\"\n [16]=>\n string(1) \"q\"\n [17]=>\n string(1) \"r\"\n [18]=>\n string(1) \"s\"\n [19]=>\n string(1) \"t\"\n [20]=>\n string(1) \"u\"\n [21]=>\n string(1) \"v\"\n [22]=>\n string(1) \"w\"\n [23]=>\n string(1) \"x\"\n [24]=>\n string(1) \"y\"\n [25]=>\n string(1) \"z\"\n}", "Python": "from string import ascii_lowercase\n\n# Generation:\nlower = [chr(i) for i in range(ord('a'), ord('z') + 1)]", "PHP": ""} +{"id": 19, "output": "1\n2\nFizz\n4\nBuzz\nFizz\nJazz\n8\nFizz\nBuzz\n11\nFizz\n13\nJazz\nFizzBuzz\n16\n17\nFizz\n19\nBuzz", "Python": "def genfizzbuzz(factorwords, numbers):\n # sort entries by factor\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)))", "PHP": " '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?>"} +{"id": 20, "output": "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz", "Python": "for i in xrange(1, 11):\n if i % 15 == 0:\n print \"FizzBuzz\"\n elif i % 3 == 0:\n print \"Fizz\"\n elif i % 5 == 0:\n print \"Buzz\"\n else:\n print i", "PHP": ""} +{"id": 21, "output": "array(8) {\n [0]=>\n int(1)\n [1]=>\n int(2)\n [2]=>\n int(3)\n [3]=>\n int(4)\n [4]=>\n int(5)\n [5]=>\n int(6)\n [6]=>\n int(7)\n [7]=>\n int(8)\n}", "Python": "def flatten(lst):\n\treturn sum( ([x] if not isinstance(x, list) else flatten(x)\n\t\t for x in lst), [] )\n\nlst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]\nflatten(lst)", "PHP": ""} +{"id": 22, "output": "Array\n(\n [20] => DBAC\n)\n", "Python": "from itertools import permutations\n\ngiven = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()\n\nallPerms = [''.join(x) for x in permutations(given[0])]\n\nmissing = list(set(allPerms) - set(given)) # ['DBAC']", "PHP": " $val){\n\t\t\t$newArr = $arr;\n\t\t\t$newres = $result;\n\t\t\t$newres[] = $val;\n\t\t\tunset($newArr[$key]);\n\t\t\tpermut($newArr,$newres);\t\t\n\t\t}\n\t}\n}\n$givenPerms = Array(\"ABCD\",\"CABD\",\"ACDB\",\"DACB\",\"BCDA\",\"ACBD\",\"ADCB\",\"CDAB\",\"DABC\",\"BCAD\",\"CADB\",\"CDBA\",\"CBAD\",\"ABDC\",\"ADBC\",\"BDCA\",\"DCBA\",\"BACD\",\"BADC\",\"BDAC\",\"CBDA\",\"DBCA\",\"DCAB\");\n$given = Array(\"A\",\"B\",\"C\",\"D\");\npermut($given);\nprint_r(array_diff($finalres,$givenPerms)); // Array ( [20] => DBAC )"} +{"id": 23, "output": "January: 2023-01-29\nFebruary: 2023-02-26\nMarch: 2023-03-26\nApril: 2023-04-30\nJune: 2023-06-25\nJuly: 2023-07-30\nAugust: 2023-08-27\nSeptember: 2023-09-24\nOctober: 2023-10-29\nNovember: 2023-11-26\nDecember: 2023-12-31", "Python": "import sys\nimport calendar\n\nyear = 2013\nif len(sys.argv) > 1:\n try:\n year = int(sys.argv[-1])\n except ValueError:\n pass\n\nfor month in range(1, 13):\n last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))\n print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sunday))", "PHP": " Array\n (\n [0] => 0\n [1] => 7\n [2] => 6\n [3] => 9\n [4] => 9\n [5] => 2\n [6] => 7\n [7] => 1\n [8] => 7\n [9] => 9\n )\n\n [1] => Array\n (\n [0] => 7\n [1] => 0\n [2] => 13\n [3] => 16\n [4] => 16\n [5] => 9\n [6] => 14\n [7] => 8\n [8] => 14\n [9] => 16\n )\n\n [2] => Array\n (\n [0] => 6\n [1] => 13\n [2] => 0\n [3] => 15\n [4] => 15\n [5] => 8\n [6] => 13\n [7] => 7\n [8] => 13\n [9] => 15\n )\n\n [3] => Array\n (\n [0] => 9\n [1] => 16\n [2] => 15\n [3] => 0\n [4] => 18\n [5] => 11\n [6] => 16\n [7] => 10\n [8] => 16\n [9] => 18\n )\n\n [4] => Array\n (\n [0] => 9\n [1] => 16\n [2] => 15\n [3] => 18\n [4] => 0\n [5] => 11\n [6] => 16\n [7] => 10\n [8] => 16\n [9] => 18\n )\n\n [5] => Array\n (\n [0] => 2\n [1] => 9\n [2] => 8\n [3] => 11\n [4] => 11\n [5] => 0\n [6] => 9\n [7] => 3\n [8] => 9\n [9] => 11\n )\n\n [6] => Array\n (\n [0] => 7\n [1] => 14\n [2] => 13\n [3] => 16\n [4] => 16\n [5] => 9\n [6] => 0\n [7] => 8\n [8] => 14\n [9] => 16\n )\n\n [7] => Array\n (\n [0] => 1\n [1] => 8\n [2] => 7\n [3] => 10\n [4] => 10\n [5] => 3\n [6] => 8\n [7] => 0\n [8] => 8\n [9] => 10\n )\n\n [8] => Array\n (\n [0] => 7\n [1] => 14\n [2] => 13\n [3] => 16\n [4] => 16\n [5] => 9\n [6] => 14\n [7] => 8\n [8] => 0\n [9] => 16\n )\n\n [9] => Array\n (\n [0] => 9\n [1] => 16\n [2] => 15\n [3] => 18\n [4] => 18\n [5] => 11\n [6] => 16\n [7] => 10\n [8] => 16\n [9] => 0\n )\n\n)", "Python": "from math import inf\nfrom itertools import product\n\ndef floyd_warshall(n, edge):\n rn = range(n)\n dist = [[inf] * n for i in rn]\n nxt = [[0] * n for i in rn]\n for i in rn:\n dist[i][i] = 0\n for u, v, w in edge:\n dist[u-1][v-1] = w\n nxt[u-1][v-1] = v-1\n for k, i, j in product(rn, repeat=3):\n sum_ik_kj = dist[i][k] + dist[k][j]\n if dist[i][j] > sum_ik_kj:\n dist[i][j] = sum_ik_kj\n nxt[i][j] = nxt[i][k]\n print(\"pair dist path\")\n for i, j in product(rn, repeat=2):\n if i != j:\n path = [i]\n while path[-1] != j:\n path.append(nxt[path[-1]][j])\n print(\"%d \u2192 %d %4d %s\" \n % (i + 1, j + 1, dist[i][j], \n ' \u2192 '.join(str(p + 1) for p in path)))\n\nif __name__ == '__main__':\n floyd_warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]])", "PHP": " $graph[$i][$k] + $graph[$k][$j])\n $graph[$i][$j] = $graph[$i][$k] + $graph[$k][$j];\n }\n }\n}\n\nprint_r($graph);\n?>"} +{"id": 25, "output": "LUCAS => 2,1,3,4,7,11,18,29,47,76,123,199,322,521,843\nFIBONACCI => 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610\nTRIBONACCI => 1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136\nTETRANACCI => 1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536\nPENTANACCI => 1,1,2,4,8,16,31,61,120,236,464,912,1793,3525,6930\nHEXANACCI => 1,1,2,4,8,16,32,63,125,248,492,976,1936,3840,7617\nHEPTANACCI => 1,1,2,4,8,16,32,64,127,253,504,1004,2000,3984,7936\nOCTONACCI => 1,1,2,4,8,16,32,64,128,255,509,1016,2028,4048,8080\nNONANACCI => 1,1,2,4,8,16,32,64,128,256,511,1021,2040,4076,8144\nDECANACCI => 1,1,2,4,8,16,32,64,128,256,512,1023,2045,4088,8172", "Python": "from itertools import chain, count, islice\n\n\n# A000032 :: () -> [Int]\ndef A000032():\n '''Non finite sequence of Lucas numbers.\n '''\n return unfoldr(recurrence(2))([2, 1])\n\n\n# nStepFibonacci :: Int -> [Int]\ndef nStepFibonacci(n):\n '''Non-finite series of N-step Fibonacci numbers,\n defined by a recurrence relation.\n '''\n return unfoldr(recurrence(n))(\n take(n)(\n chain(\n [1],\n (2 ** i for i in count(0))\n )\n )\n )\n\n\n# recurrence :: Int -> [Int] -> Int\ndef recurrence(n):\n '''Recurrence relation in Fibonacci and related series.\n '''\n def go(xs):\n h, *t = xs\n return h, t + [sum(take(n)(xs))]\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 15 terms each n-step Fibonacci(n) series\n where n is drawn from [2..8]\n '''\n labels = \"fibo tribo tetra penta hexa hepta octo nona deca\"\n table = list(\n chain(\n [['lucas:'] + [\n str(x) for x in take(15)(A000032())]\n ],\n map(\n lambda k, n: list(\n chain(\n [k + 'nacci:'],\n (\n str(x) for x\n in take(15)(nStepFibonacci(n))\n )\n )\n ),\n labels.split(),\n count(2)\n )\n )\n )\n print('Recurrence relation series:\\n')\n print(\n spacedTable(table)\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Generic anamorphism.\n A lazy (generator) list unfolded from a seed value by\n repeated application of f until no residue remains.\n Dual to fold/reduce.\n f returns either None, or just (value, residue).\n For a strict output value, wrap in list().\n '''\n def go(x):\n valueResidue = f(x)\n while None is not valueResidue:\n yield valueResidue[0]\n valueResidue = f(valueResidue[1])\n return go\n\n\n# ---------------------- FORMATTING ----------------------\n\n# spacedTable :: [[String]] -> String\ndef spacedTable(rows):\n columnWidths = [\n max([len(x) for x in col])\n for col in zip(*rows)\n ]\n return '\\n'.join([\n ' '.join(\n map(\n lambda x, w: x.rjust(w, ' '),\n row, columnWidths\n )\n )\n for row in rows\n ])\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "PHP": " $x && $count == $n) // exit point\n\t{\n\t\treturn $series;\n\t}\n\n\tif($count < $n)\n\t{\n\t\tif($count >= $x) // 4 or less\n\t\t{\n\t\t\tfib($series, $x, $count);\n\t\t\treturn fib_n_step($x, $series, $n);\n\t\t}\n\t\telse // 5 or more\n\t\t{\n\t\t\twhile(count($series) < $x )\n\t\t\t{\n\t\t\t\t$count = count($series);\n\t\t\t\tfib($series, $count, $count);\n\t\t\t}\n\t\t\treturn fib_n_step($x, $series, $n);\n\t\t}\n\t}\n\n\treturn $series;\n}\n\n/**\n * @param array $series\n * @param int $n\n * @param int $i\n */\nfunction fib(&$series, $n, $i)\n{\n\t$end = 0;\n\tfor($j = $n; $j > 0; $j--)\n\t{\n\t\t$end += $series[$i-$j];\n\t}\n\t$series[$i] = $end;\n}\n\n\n/*=================== OUTPUT ============================*/\n\nheader('Content-Type: text/plain');\n$steps = array(\n\t'LUCAS' => \t\tarray(2, \tarray(2, 1)),\n\t'FIBONACCI' => \tarray(2, \tarray(1, 1)),\n\t'TRIBONACCI' =>\tarray(3, \tarray(1, 1, 2)),\n\t'TETRANACCI' =>\tarray(4, \tarray(1, 1, 2, 4)),\n\t'PENTANACCI' =>\tarray(5,\tarray(1, 1, 2, 4)),\n\t'HEXANACCI' =>\tarray(6, \tarray(1, 1, 2, 4)),\n\t'HEPTANACCI' =>\tarray(7,\tarray(1, 1, 2, 4)),\n\t'OCTONACCI' =>\tarray(8, \tarray(1, 1, 2, 4)),\n\t'NONANACCI' =>\tarray(9, \tarray(1, 1, 2, 4)),\n\t'DECANACCI' =>\tarray(10, \tarray(1, 1, 2, 4)),\n);\n\nforeach($steps as $name=>$pair)\n{\n\t$ser = fib_n_step($pair[0],$pair[1]);\n\t$n = count($ser)-1;\n\n\techo $name.\" => \".implode(',', $ser) . \"\\n\";\n}"} +{"id": 26, "output": "Array\n(\n [6] => 29808\n [1] => 30028\n [2] => 29918\n [7] => 29880\n [8] => 30018\n [5] => 30137\n [0] => 30020\n [4] => 30165\n [3] => 30099\n [9] => 29927\n)", "Python": "from random import randrange\n\ndef s_of_n_creator(n):\n sample, i = [], 0\n def s_of_n(item):\n nonlocal i\n\n i += 1\n if i <= n:\n # Keep first n items\n sample.append(item)\n elif randrange(i) < n:\n # Keep item\n sample[randrange(n)] = item\n return sample\n return s_of_n\n\nif __name__ == '__main__':\n bin = [0]* 10\n items = range(10)\n print(\"Single run samples for n = 3:\")\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n print(\" Item: %i -> sample: %s\" % (item, sample))\n #\n for trial in range(100000):\n s_of_n = s_of_n_creator(3)\n for item in items:\n sample = s_of_n(item)\n for s in sample:\n bin[s] += 1\n print(\"\\nTest item frequencies for 100000 runs:\\n \",\n '\\n '.join(\"%i:%i\" % x for x in enumerate(bin)))", "PHP": ""} +{"id": 27, "output": "2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
", "Python": "import calendar\n\ndef last_fridays(year):\n for month in range(1, 13):\n last_friday = max(week[calendar.FRIDAY]\n for week in calendar.monthcalendar(year, month))\n print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))", "PHP": "\";\n }\n}\n \ndate_default_timezone_set(\"GMT\");\n$year = 2012;\nprint_last_fridays_of_month($year);\n?>"} +{"id": 28, "output": "Array\n(\n [0] => 2\n [1] => 4\n [2] => 5\n)\nArray\n(\n [0] => 0\n [1] => 2\n [2] => 6\n [3] => 9\n [4] => 11\n [5] => 15\n)", "Python": "def longest_increasing_subsequence(X):\n \"\"\"Returns the Longest Increasing Subsequence in the Given List/Array\"\"\"\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)))", "PHP": "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?>"} +{"id": 29, "output": "-67\nWorks ", "Python": "import 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)))", "PHP": "\nWorks "} +{"id": 30, "output": "Case 1:\n x = (from the \"Wizard of OZ\")\n y = bears, oh my!\n z = lions, tigers, and\nCase 2:\n x = -12\n y = 0\n z = 77444", "Python": "while True:\n x, y, z = eval(input('Three Python values: '))\n print(f'As read: x = {x!r}; y = {y!r}; z = {z!r}')\n x, y, z = sorted((x, y, z))\n print(f' Sorted: x = {x!r}; y = {y!r}; z = {z!r}')", "PHP": " Int\ndef nonSquare(n):\n '''Nth term in the OEIS A000037 series.'''\n return n + floor(1 / 2 + sqrt(n))\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''OEIS A000037'''\n\n def first22():\n '''First 22 terms'''\n return take(22)(A000037())\n\n def squareInFirstMillion():\n '''True if any of the first 10^6 terms are perfect squares'''\n return any(map(\n isPerfectSquare,\n take(10 ** 6)(A000037())\n ))\n\n print(\n fTable(main.__doc__)(\n lambda f: '\\n' + f.__doc__\n )(lambda x: ' ' + showList(x))(\n lambda f: f()\n )([first22, squareInFirstMillion])\n )\n\n\n# -------------------------DISPLAY-------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y + ':\\n' + 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# -------------------------GENERAL-------------------------\n\n# isPerfectSquare :: Int -> Bool\ndef isPerfectSquare(n):\n '''True if n is a perfect square.'''\n return sqrt(n).is_integer()\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Compact stringification of any list value.'''\n return '[' + ','.join(repr(x) for x in xs) + ']' if (\n isinstance(xs, list)\n ) else repr(xs)\n\n\n# take :: Int -> [a] -> [a]\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: list(islice(xs, n))\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "PHP": ""} +{"id": 32, "output": "1210\n2020\n21200\n3211000\n42101000", "Python": "def impl(d, c, m):\n if m < 0: return\n if d == c[:len(d)]: print d\n for i in range(c[len(d)],m+1):\n dd = d+[i]\n if i $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?>"} +{"id": 33, "output": "Array\n(\n [0] => 7\n [1] => 5\n [2] => 4\n [3] => 3\n [4] => 1\n [5] => 1\n [6] => 1\n)", "Python": "from itertools import zip_longest\n\n# This is wrong, it works only on specific examples\ndef beadsort(l):\n return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))\n\n\n# Demonstration code:\nprint(beadsort([5,3,1,7,4,1,1]))", "PHP": ""} +{"id": 34, "output": "Start text not found", "Python": "from sys import argv\n\n# textBetween in python\n# Get the text between two delimiters\n# Usage:\n# python textBetween.py \"hello Rosetta Code world\" \"hello \" \" world\"\n\ndef textBetween( thisText, startString, endString ):\n try:\n \tif startString is 'start':\n \t\tstartIndex = 0\n \telse:\n \t\tstartIndex = thisText.index( startString ) \n \t\n \tif not (startIndex >= 0):\n \t\treturn 'Start delimiter not found'\n \telse:\n \tif startString is not 'start':\n \t\tstartIndex = startIndex + len( startString )\n \n returnText = thisText[startIndex:]\n\n\n \tif endString is 'end':\n \t\treturn returnText\n \telse:\n \t\tendIndex = returnText.index( endString )\n\n \tif not (endIndex >= 0):\n \t\treturn 'End delimiter not found'\n \telse:\n \treturnText = returnText[:endIndex]\n\n return returnText\n except ValueError:\n return \"Value error\"\n\nscript, first, second, third = argv\n\nthisText = first\nstartString = second\nendString = third\n\nprint textBetween( thisText, startString, endString )", "PHP": ""} +{"id": 35, "output": "On the first day of Christmas, my true love gave to me\nA partridge in a pear tree\n\nOn the second day of Christmas, my true love gave to me\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the third day of Christmas, my true love gave to me\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the fourth day of Christmas, my true love gave to me\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the fifth day of Christmas, my true love gave to me\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the sixth day of Christmas, my true love gave to me\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the seventh day of Christmas, my true love gave to me\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the eighth day of Christmas, my true love gave to me\nEight maids a-milking\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the ninth day of Christmas, my true love gave to me\nNine ladies dancing\nEight maids a-milking\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the tenth day of Christmas, my true love gave to me\nTen lords a-leaping\nNine ladies dancing\nEight maids a-milking\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the eleventh day of Christmas, my true love gave to me\nEleven pipers piping\nTen lords a-leaping\nNine ladies dancing\nEight maids a-milking\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree\n\nOn the twelfth day of Christmas, my true love gave to me\nTwelve drummers drumming\nEleven pipers piping\nTen lords a-leaping\nNine ladies dancing\nEight maids a-milking\nSeven swans a-swimming\nSix geese a-laying\nFive golden rings\nFour calling birds\nThree french hens\nTwo turtle doves\nAnd a partridge in a pear tree", "Python": "gifts = '''\\\nA partridge in a pear tree.\nTwo turtle doves\nThree french hens\nFour calling birds\nFive golden rings\nSix geese a-laying\nSeven swans a-swimming\nEight maids a-milking\nNine ladies dancing\nTen lords a-leaping\nEleven pipers piping\nTwelve drummers drumming'''.split('\\n')\n\ndays = '''first second third fourth fifth\n sixth seventh eighth ninth tenth\n eleventh twelfth'''.split()\n\nfor n, day in enumerate(days, 1):\n g = gifts[:n][::-1]\n print(('\\nOn the %s day of Christmas\\nMy true love gave to me:\\n' % day) +\n '\\n'.join(g[:-1]) +\n (' and\\n' + g[-1] if n > 1 else g[-1].capitalize()))", "PHP": "= 0 ) {\n $lines[++$k] = $gifts[$j];\n $j--;\n }\n \n $verses[$i] = implode(PHP_EOL, $lines);\n \n if ( $i == 0 )\n $gifts[0] = \"And a partridge in a pear tree\";\n}\n\necho implode(PHP_EOL . PHP_EOL, $verses);\n\n?>"} +{"id": 36, "output": "Hello.How.Are.You.Today", "Python": "text = \"Hello,How,Are,You,Today\"\ntokens = text.split(',')\nprint ('.'.join(tokens))", "PHP": ""} +{"id": 37, "output": "\nA = (3.00, 4.00, 5.00)\nB = (4.00, 3.00, 5.00)\nC = (-5.00, -12.00, -13.00)\n\nA \u00b7 B = 49.00\nA \u00d7 B = (5.00, 5.00, -7.00)\nA \u00b7 (B \u00d7 C) = 6.00\nA \u00d7 (B \u00d7 C) =(-267.00, 204.00, -3.00)", "Python": "def crossp(a, b):\n '''Cross product of two 3D vectors'''\n assert len(a) == len(b) == 3, 'For 3D vectors only'\n a1, a2, a3 = a\n b1, b2, b3 = b\n return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)\n \ndef dotp(a,b):\n '''Dot product of two eqi-dimensioned vectors'''\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n \ndef scalartriplep(a, b, c):\n '''Scalar triple product of three vectors: \"a . (b x c)\"'''\n return dotp(a, crossp(b, c))\n \ndef vectortriplep(a, b, c):\n '''Vector triple product of three vectors: \"a x (b x c)\"'''\n return crossp(a, crossp(b, c))\n \nif __name__ == '__main__':\n a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)\n print(\"a = %r; b = %r; c = %r\" % (a, b, c))\n print(\"a . b = %r\" % dotp(a,b))\n print(\"a x b = %r\" % (crossp(a,b),))\n print(\"a . (b x c) = %r\" % scalartriplep(a, b, c))\n print(\"a x (b x c) = %r\" % (vectortriplep(a, b, c),))", "PHP": "values = $values;\n\t}\n\n\tpublic function getValues()\n\t{\n\t\tif ($this->values == null)\n\t\t\t$this->setValues(array (\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t));\n\t\treturn $this->values;\n\t}\n\n\tpublic function Vector(array $values)\n\t{\n\t\t$this->setValues($values);\n\t}\n\n\tpublic static function dotProduct(Vector $va, Vector $vb)\n\t{\n\t\t$a = $va->getValues();\n\t\t$b = $vb->getValues();\n\t\treturn ($a[0] * $b[0]) + ($a[1] * $b[1]) + ($a[2] * $b[2]);\n\t}\n\n\tpublic static function crossProduct(Vector $va, Vector $vb)\n\t{\n\t\t$a = $va->getValues();\n\t\t$b = $vb->getValues();\n\t\treturn new Vector(array (\n\t\t\t\t($a[1] * $b[2]) - ($a[2] * $b[1]),\n\t\t\t\t($a[2] * $b[0]) - ($a[0] * $b[2]),\n\t\t\t\t($a[0] * $b[1]) - ($a[1] * $b[0])\n\t\t));\n\t}\n\n\tpublic static function scalarTripleProduct(Vector $va, Vector $vb, Vector $vc)\n\t{\n\t\treturn self::dotProduct($va, self::crossProduct($vb, $vc));\n\t}\n\n\tpublic static function vectorTrippleProduct(Vector $va, Vector $vb, Vector $vc)\n\t{\n\t\treturn self::crossProduct($va, self::crossProduct($vb, $vc));\n\t}\n}\n\nclass Program\n{\n\n\tpublic function Program()\n\t{\n\t\t$a = array (\n\t\t\t\t3,\n\t\t\t\t4,\n\t\t\t\t5\n\t\t);\n\t\t$b = array (\n\t\t\t\t4,\n\t\t\t\t3,\n\t\t\t\t5\n\t\t);\n\t\t$c = array (\n\t\t\t\t-5,\n\t\t\t\t-12,\n\t\t\t\t-13\n\t\t);\n\t\t$va = new Vector($a);\n\t\t$vb = new Vector($b);\n\t\t$vc = new Vector($c);\n\n\t\t$result1 = Vector::dotProduct($va, $vb);\n\t\t$result2 = Vector::crossProduct($va, $vb)->getValues();\n\t\t$result3 = Vector::scalarTripleProduct($va, $vb, $vc);\n\t\t$result4 = Vector::vectorTrippleProduct($va, $vb, $vc)->getValues();\n\n\t\tprintf(\"\\n\");\n\t\tprintf(\"A = (%0.2f, %0.2f, %0.2f)\\n\", $a[0], $a[1], $a[2]);\n\t\tprintf(\"B = (%0.2f, %0.2f, %0.2f)\\n\", $b[0], $b[1], $b[2]);\n\t\tprintf(\"C = (%0.2f, %0.2f, %0.2f)\\n\", $c[0], $c[1], $c[2]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"A \u00b7 B = %0.2f\\n\", $result1);\n\t\tprintf(\"A \u00d7 B = (%0.2f, %0.2f, %0.2f)\\n\", $result2[0], $result2[1], $result2[2]);\n\t\tprintf(\"A \u00b7 (B \u00d7 C) = %0.2f\\n\", $result3);\n\t\tprintf(\"A \u00d7 (B \u00d7 C) =(%0.2f, %0.2f, %0.2f)\\n\", $result4[0], $result4[1], $result4[2]);\n\t}\n}\n\nnew Program();\n?>"} +{"id": 38, "output": "Sh ws soul strppr. Sh took my hrt!", "Python": "import re\ndef stripchars(s, chars):\n\treturn re.sub('[%s]+' % re.escape(chars), '', s)\n\nstripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n", "PHP": ""} +{"id": 39, "output": "------------ Fire and Ice ----------

Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.

... last paragraph elided ...

----------------------- Robert Frost
", "Python": " text = '''\\\n---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------'''\n\nfor line in text.split('\\n'): print(' '.join(line.split()[::-1]))", "PHP": "';\n\t }\n\n \treturn $str_inv;\n\n }\n \n $string[] = \"---------- Ice and Fire ------------\";\n $string[] = \"\";\n $string[] = \"fire, in end will world the say Some\";\n $string[] = \"ice. in say Some\";\n $string[] = \"desire of tasted I've what From\";\n $string[] = \"fire. favor who those with hold I\";\n $string[] = \"\";\n $string[] = \"... elided paragraph last ...\";\n $string[] = \"\";\n $string[] = \"Frost Robert ----------------------- \";\n\n\necho strInv($string);"} +{"id": 0, "output": "Take one down and pass it around, 5 bottles of beer on the wall.\n5 bottles of beer on the wall, 5 bottles of beer.\nTake one down and pass it around, 4 bottles of beer on the wall.\n4 bottles of beer on the wall, 4 bottles of beer.\nTake one down and pass it around, 3 bottles of beer on the wall.\n3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottles of beer on the wall.\n1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.", "Python": "Option Strict Off\n\nModule Program\n Sub Main()\n Dim a=\" bottles of beer\",b=\" on the wall\"&vbLf,c=\"Take one down, pass it around\"&vbLf,s=Function(o)o.ToString\n Console.Write(String.Join(vbLf,Enumerable.Range(1,99).Reverse.Select(Function(x)s(x)+a+b+s(x)+a+vbLf+c+s(x-1)+a+b)))\n End Sub\nEnd Module", "VB": "Module Module1\n Sub Main()\n Dim Bottles As Integer\n For Bottles = 10 To 0 Step -1\n If Bottles = 0 Then\n Console.WriteLine(\"No more bottles of beer on the wall, no more bottles of beer.\")\n Console.WriteLine(\"Go to the store and buy some more, 99 bottles of beer on the wall.\")\n Console.ReadLine()\n ElseIf Bottles = 1 Then\n Console.WriteLine(Bottles & \" bottle of beer on the wall, \" & Bottles & \" bottle of beer.\")\n Console.WriteLine(\"Take one down and pass it around, no more bottles of beer on the wall.\")\n Console.ReadLine()\n Else\n Console.WriteLine(Bottles & \" bottles of beer on the wall, \" & Bottles & \" bottles of beer.\")\n Console.WriteLine(\"Take one down and pass it around, \" & (Bottles - 1) & \" bottles of beer on the wall.\")\n Console.ReadLine()\n End If\n Next\n End Sub\nEnd Module"} +{"id": 1, "output": "The first 25 abundant odd numbers:\n 945 proper divisor sum: 975\n 1575 proper divisor sum: 1649\n 2205 proper divisor sum: 2241\n 2835 proper divisor sum: 2973\n 3465 proper divisor sum: 4023\n 4095 proper divisor sum: 4641\n 4725 proper divisor sum: 5195\n 5355 proper divisor sum: 5877\n 5775 proper divisor sum: 6129\n 5985 proper divisor sum: 6495\n 6435 proper divisor sum: 6669\n 6615 proper divisor sum: 7065\n 6825 proper divisor sum: 7063\n 7245 proper divisor sum: 7731\n 7425 proper divisor sum: 7455\n 7875 proper divisor sum: 8349\n 8085 proper divisor sum: 8331\n 8415 proper divisor sum: 8433\n 8505 proper divisor sum: 8967\n 8925 proper divisor sum: 8931\n 9135 proper divisor sum: 9585\n 9555 proper divisor sum: 9597\n 9765 proper divisor sum: 10203\n 10395 proper divisor sum: 12645\n 11025 proper divisor sum: 11946\n1000th abundant odd number:\n 492975 proper divisor sum: 519361\nFirst abundant odd number > 1 000 000 000:\n 1000000575 proper divisor sum: 1083561009", "Python": "oddNumber = 1\naCount = 0\ndSum = 0\n \nfrom math import sqrt\n \ndef divisorSum(n):\n sum = 1\n i = int(sqrt(n)+1)\n \n for d in range (2, i):\n if n % d == 0:\n sum += d\n otherD = n // d\n if otherD != d:\n sum += otherD\n return sum\n \nprint (\"The first 25 abundant odd numbers:\")\nwhile aCount < 25:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n print(\"{0:5} proper divisor sum: {1}\". format(oddNumber ,dSum ))\n oddNumber += 2\n \nwhile aCount < 1000:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n oddNumber += 2\nprint (\"\\n1000th abundant odd number:\")\nprint (\" \",(oddNumber - 2),\" proper divisor sum: \",dSum)\n \noddNumber = 1000000001\nfound = False\nwhile not found :\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n found = True\n print (\"\\nFirst abundant odd number > 1 000 000 000:\")\n print (\" \",oddNumber,\" proper divisor sum: \",dSum)\n oddNumber += 2", "VB": "Module AbundantOddNumbers\n ' find some abundant odd numbers - numbers where the sum of the proper\n ' divisors is bigger than the number\n ' itself\n\n ' returns the sum of the proper divisors of n\n Private Function divisorSum(n As Integer) As Integer\n Dim sum As Integer = 1\n For d As Integer = 2 To Math.Round(Math.Sqrt(n))\n If n Mod d = 0 Then\n sum += d\n Dim otherD As Integer = n \\ d\n IF otherD <> d Then\n sum += otherD\n End If\n End If\n Next d\n Return sum\n End Function\n\n ' find numbers required by the task\n Public Sub Main(args() As String)\n ' first 25 odd abundant numbers\n Dim oddNumber As Integer = 1\n Dim aCount As Integer = 0\n Dim dSum As Integer = 0\n Console.Out.WriteLine(\"The first 25 abundant odd numbers:\")\n Do While aCount < 25\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n aCount += 1\n Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & \" proper divisor sum: \" & dSum)\n End If\n oddNumber += 2\n Loop\n ' 1000th odd abundant number\n Do While aCount < 1000\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n aCount += 1\n End If\n oddNumber += 2\n Loop\n Console.Out.WriteLine(\"1000th abundant odd number:\")\n Console.Out.WriteLine(\" \" & (oddNumber - 2) & \" proper divisor sum: \" & dSum)\n ' first odd abundant number > one billion\n oddNumber = 1000000001\n Dim found As Boolean = False\n Do While Not found\n dSum = divisorSum(oddNumber)\n If dSum > oddNumber Then\n found = True\n Console.Out.WriteLine(\"First abundant odd number > 1 000 000 000:\")\n Console.Out.WriteLine(\" \" & oddNumber & \" proper divisor sum: \" & dSum)\n End If\n oddNumber += 2\n Loop\n End Sub\nEnd Module"} +{"id": 2, "output": "Double result: 0.847213084793979\nDecimal result: 0.8472130847939790866064991235\n", "Python": "from math import sqrt\n\ndef agm(a0, g0, tolerance=1e-10):\n \"\"\"\n Calculating the arithmetic-geometric mean of two numbers a0, g0.\n\n tolerance the tolerance for the converged \n value of the arithmetic-geometric mean\n (default value = 1e-10)\n \"\"\"\n an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)\n while abs(an - gn) > tolerance:\n an, gn = (an + gn) / 2.0, sqrt(an * gn)\n return an\n\nprint agm(1, 1 / sqrt(2))", "VB": "Imports System.Math\nImports System.Console\n\nModule Module1\n\n Function CalcAGM(ByVal a As Double, ByVal b As Double) As Double\n Dim c As Double, d As Double = 0, ld As Double = 1\n While ld <> d : c = a : a = (a + b) / 2 : b = Sqrt(c * b)\n ld = d : d = a - b : End While : Return b\n End Function\n\n Function DecSqRoot(ByVal v As Decimal) As Decimal\n Dim r As Decimal = CDec(Sqrt(CDbl(v))), t As Decimal = 0, d As Decimal = 0, ld As Decimal = 1\n While ld <> d : t = v / r : r = (r + t) / 2\n ld = d : d = t - r : End While : Return t\n End Function\n\n Function CalcAGM(ByVal a As Decimal, ByVal b As Decimal) As Decimal\n Dim c As Decimal, d As Decimal = 0, ld As Decimal = 1\n While ld <> d : c = a : a = (a + b) / 2 : b = DecSqRoot(c * b)\n ld = d : d = a - b : End While : Return b\n End Function\n\n Sub Main(ByVal args As String())\n WriteLine(\"Double result: {0}\", CalcAGM(1.0, DecSqRoot(0.5)))\n WriteLine(\"Decimal result: {0}\", CalcAGM(1D, DecSqRoot(0.5D)))\n If System.Diagnostics.Debugger.IsAttached Then ReadKey()\n End Sub\n\nEnd Module"} +{"id": 3, "output": "2", "Python": "print(len(['apple', 'orange']))", "VB": "Module ArrayLength\n\n Sub Main()\n Dim array() As String = {\"apple\", \"orange\"}\n Console.WriteLine(array.Length)\n End Sub\n\nEnd Module"} +{"id": 4, "output": "The smallest integer whose square ends in 269,696 is 25264\nThe square is 638269696", "Python": "print(next(x for x in range(30000) if pow(x, 2, 1000000) == 269696))", "VB": "Module Module1\n\n Function Right6Digits(num As Long) As Long\n Dim asString = num.ToString()\n If asString.Length < 6 Then\n Return num\n End If\n\n Dim last6 = asString.Substring(asString.Length - 6)\n Return Long.Parse(last6)\n End Function\n\n Sub Main()\n Dim bnSq = 0 'the base number squared\n Dim bn = 0 'the number to be squared\n\n Do\n bn = bn + 1\n bnSq = bn * bn\n Loop While Right6Digits(bnSq) <> 269696\n\n Console.WriteLine(\"The smallest integer whose square ends in 269,696 is {0}\", bn)\n Console.WriteLine(\"The square is {0}\", bnSq)\n End Sub\n\nEnd Module"} +{"id": 5, "output": " : OK\n [][] : OK\n [][] : OK\n ][ : NOT OK\n [[[[]]]] : OK\n [[]] : OK\n [] : OK\n [[]] : OK\n : OK\n : OK", "Python": "import numpy as np\nfrom random import shuffle\ndef gen(n):\n txt = list('[]' * n)\n shuffle(txt)\n return ''.join(txt)\n\nm = np.array([{'[': 1, ']': -1}.get(chr(c), 0) for c in range(128)])\ndef balanced(txt):\n a = np.array(txt, 'c').view(np.uint8)\n return np.all(m[a].cumsum() >= 0)\n\nfor txt in (gen(N) for N in range(10)):\n print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))", "VB": "Module Module1\n\n Private rand As New Random\n\n Sub Main()\n For numInputs As Integer = 1 To 10 '10 is the number of bracket sequences to test.\n Dim input As String = GenerateBrackets(rand.Next(0, 5)) '5 represents the number of pairs of brackets (n)\n Console.WriteLine(String.Format(\"{0} : {1}\", input.PadLeft(10, CChar(\" \")), If(IsBalanced(input) = True, \"OK\", \"NOT OK\")))\n Next\n Console.ReadLine()\n End Sub\n\n Private Function GenerateBrackets(n As Integer) As String\n\n Dim randomString As String = \"\"\n Dim numOpen, numClosed As Integer\n\n Do Until numOpen = n And numClosed = n\n If rand.Next(0, 501) Mod 2 = 0 AndAlso numOpen < n Then\n randomString = String.Format(\"{0}{1}\", randomString, \"[\")\n numOpen += 1\n ElseIf rand.Next(0, 501) Mod 2 <> 0 AndAlso numClosed < n Then\n randomString = String.Format(\"{0}{1}\", randomString, \"]\")\n numClosed += 1\n End If\n Loop\n Return randomString\n End Function\n\n Private Function IsBalanced(brackets As String) As Boolean\n\n Dim numOpen As Integer = 0\n Dim numClosed As Integer = 0\n\n For Each character As Char In brackets\n If character = \"[\"c Then numOpen += 1\n If character = \"]\"c Then\n numClosed += 1\n If numClosed > numOpen Then Return False\n End If\n Next\n Return numOpen = numClosed\n End Function\nEnd Module"} +{"id": 6, "output": "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\n\nTo err is human, but to really foul things up you need a computer.\n -- Paul R. Ehrlich", "Python": "import base64\ndata = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='\nprint(base64.b64decode(data).decode('utf-8'))", "VB": "Module Module1\n\n Sub Main()\n Dim data = \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\"\n Console.WriteLine(data)\n Console.WriteLine()\n\n Dim decoded = Text.Encoding.ASCII.GetString(Convert.FromBase64String(data))\n Console.WriteLine(decoded)\n End Sub\n\nEnd Module"} +{"id": 7, "output": "Hello World!", "Python": "print(\"Hello World!\")", "VB": "Module Module1\n\n Sub Main()\n Console.WriteLine(\"Hello World!\")\n End Sub\n\nEnd Module"} +{"id": 8, "output": "1 = 1\n2 = 2\n3 = 3\n4 = 2 x 2\n5 = 5\n6 = 2 x 3\n7 = 7\n8 = 2 x 2 x 2\n9 = 3 x 3\n10 = 2 x 5\n9991 = 97 x 103\n9992 = 2 x 2 x 2 x 1249\n9993 = 3 x 3331\n9994 = 2 x 19 x 263\n9995 = 5 x 1999\n9996 = 2 x 2 x 3 x 7 x 7 x 17\n9997 = 13 x 769\n9998 = 2 x 4999\n9999 = 3 x 3 x 11 x 101\n10000 = 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5", "Python": "from functools import lru_cache\n\nprimes = [2, 3, 5, 7, 11, 13, 17] # Will be extended\n\n@lru_cache(maxsize=2000)\ndef pfactor(n):\n if n == 1:\n return [1]\n n2 = n // 2 + 1\n for p in primes:\n if p <= n2:\n d, m = divmod(n, p)\n if m == 0:\n if d > 1:\n return [p] + pfactor(d)\n else:\n return [p]\n else:\n if n > primes[-1]:\n primes.append(n)\n return [n]\n \nif __name__ == '__main__':\n mx = 5000\n for n in range(1, mx + 1):\n factors = pfactor(n)\n if n <= 10 or n >= mx - 20:\n print( '%4i %5s %s' % (n,\n '' if factors != [n] or n == 1 else 'prime',\n 'x'.join(str(i) for i in factors)) )\n if n == 11:\n print('...')\n \n print('\\nNumber of primes gathered up to', n, 'is', len(primes))\n print(pfactor.cache_info())", "VB": "Module CountingInFactors\n\n Sub Main()\n For i As Integer = 1 To 10\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n\n For i As Integer = 9991 To 10000\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n End Sub\n\n Private Function CountingInFactors(ByVal n As Integer) As String\n If n = 1 Then Return \"1\"\n\n Dim sb As New Text.StringBuilder()\n\n CheckFactor(2, n, sb)\n If n = 1 Then Return sb.ToString()\n\n CheckFactor(3, n, sb)\n If n = 1 Then Return sb.ToString()\n\n For i As Integer = 5 To n Step 2\n If i Mod 3 = 0 Then Continue For\n\n CheckFactor(i, n, sb)\n If n = 1 Then Exit For\n Next\n\n Return sb.ToString()\n End Function\n\n Private Sub CheckFactor(ByVal mult As Integer, ByRef n As Integer, ByRef sb As Text.StringBuilder)\n Do While n Mod mult = 0\n If sb.Length > 0 Then sb.Append(\" x \")\n sb.Append(mult)\n n = n / mult\n Loop\n End Sub\n\nEnd Module"} +{"id": 9, "output": "3\n0", "Python": "def countJewels(s, j):\n return sum(x in j for x in s)\n\nprint countJewels(\"aAAbbbb\", \"aA\")\nprint countJewels(\"ZZ\", \"z\")", "VB": "Module Module1\n\n Function Count(stones As String, jewels As String) As Integer\n Dim count As Integer = 0\n For Each stone As Char In stones\n For Each jewel As Char In jewels\n If stone = jewel Then\n count += 1\n Exit For\n End If\n Next\n Next\n Return count\n End Function\n\n Sub Main()\n Console.WriteLine(Count(\"aAAbbbb\", \"Aa\"))\n Console.WriteLine(Count(\"ZZ\", \"z\"))\n End Sub\n\nEnd Module"} +{"id": 10, "output": "Kaprekar numbers below 10000\n 1 1\n 2 9\n 3 45\n 4 55\n 5 99\n 6 297\n 7 703\n 8 999\n 9 2223\n10 2728\n11 4879\n12 4950\n13 5050\n14 5292\n15 7272\n16 7777\n17 9999\n\n54 numbers below 1000000 are kaprekar numbers", "Python": "ase = 10\nN = 6\nPaddy_cnt = 1\nfor n in range(N):\n for V in CastOut(Base,Start=Base**n,End=Base**(n+1)):\n for B in range(n+1,n*2+2):\n x,y = divmod(V*V,Base**B)\n if V == x+y and 0 n Then\n Continue For\n End If\n Dim p1 As ULong = ULong.Parse(Left(sq_str, x))\n If p1 > n Then Return False\n If (p1 + p2) = n Then Return True\n Next\n\n Return False\n End Function\n\n Sub Main()\n Dim count As Integer = 0\n\n Console.WriteLine(\"Kaprekar numbers below 10000\")\n\n For n As ULong = 1 To max - 1\n If Kaprekar(n) Then\n count = count + 1\n If n < 10000 Then\n Console.WriteLine(\"{0,2} {1,4}\", count, n)\n End If\n End If\n Next\n\n Console.WriteLine()\n Console.WriteLine(\"{0} numbers below {1} are kaprekar numbers\", count, max)\n End Sub\n\nEnd Module\n"} +{"id": 11, "output": "337 355 373 535 553 733 2227 2272 2335 2353 2533 2722 3235 3253 3325 3352 3523 3532 5233 5323 5332 7222 22225 22252 22333 22522 23233 23323 23332 25222 32233 32323 32332 33223 33232 33322 52222 222223 222232 222322 223222 232222 322222", "Python": "from collections import deque\n\ndef prime_digits_sum(r):\n q = deque([(r, 0)])\n while q:\n r, n = q.popleft()\n for d in 2, 3, 5, 7:\n if d >= r:\n if d == r: yield n + d\n break\n q.append((r - d, (n + d) * 10))\n\nprint(*prime_digits_sum(13))", "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"} +{"id": 12, "output": "[7,10]\n[3,4]\n[55,77]\n[2.5,3.5]\n[28,56,105,112,161,294]", "Python": "from __future__ import annotations\nimport math\nfrom functools import lru_cache\nfrom typing import NamedTuple\n\nCACHE_SIZE = None\n\n\ndef hypotenuse(leg: float,\n other_leg: float) -> float:\n \"\"\"Returns hypotenuse for given legs\"\"\"\n return math.sqrt(leg ** 2 + other_leg ** 2)\n\n\nclass Vector(NamedTuple):\n slope: float\n length: float\n\n @property\n @lru_cache(CACHE_SIZE)\n def angle(self) -> float:\n return math.atan(self.slope)\n\n @property\n @lru_cache(CACHE_SIZE)\n def x(self) -> float:\n return self.length * math.sin(self.angle)\n\n @property\n @lru_cache(CACHE_SIZE)\n def y(self) -> float:\n return self.length * math.cos(self.angle)\n \n def __add__(self, other: Vector) -> Vector:\n \"\"\"Returns self + other\"\"\"\n new_x = self.x + other.x\n new_y = self.y + other.y\n new_length = hypotenuse(new_x, new_y)\n new_slope = new_y / new_x\n return Vector(new_slope, new_length)\n \n def __neg__(self) -> Vector:\n \"\"\"Returns -self\"\"\"\n return Vector(self.slope, -self.length)\n \n def __sub__(self, other: Vector) -> Vector:\n \"\"\"Returns self - other\"\"\"\n return self + (-other)\n \n def __mul__(self, scalar: float) -> Vector:\n \"\"\"Returns self * scalar\"\"\"\n return Vector(self.slope, self.length * scalar)\n \n def __truediv__(self, scalar: float) -> Vector:\n \"\"\"Returns self / scalar\"\"\"\n return self * (1 / scalar)\n\n\nif __name__ == '__main__':\n v1 = Vector(1, 1)\n\n print(\"Pretty print:\")\n print(v1, end='\\n' * 2)\n\n print(\"Addition:\")\n v2 = v1 + v1\n print(v1 + v1, end='\\n' * 2)\n\n print(\"Subtraction:\")\n print(v2 - v1, end='\\n' * 2)\n\n print(\"Multiplication:\")\n print(v1 * 2, end='\\n' * 2)\n\n print(\"Division:\")\n print(v2 / 2)", "VB": "Module Module1\n\n Class Vector\n Public store As Double()\n\n Public Sub New(init As IEnumerable(Of Double))\n store = init.ToArray()\n End Sub\n\n Public Sub New(x As Double, y As Double)\n store = {x, y}\n End Sub\n\n Public Overloads Shared Operator +(v1 As Vector, v2 As Vector)\n Return New Vector(v1.store.Zip(v2.store, Function(a, b) a + b))\n End Operator\n\n Public Overloads Shared Operator -(v1 As Vector, v2 As Vector)\n Return New Vector(v1.store.Zip(v2.store, Function(a, b) a - b))\n End Operator\n\n Public Overloads Shared Operator *(v1 As Vector, scalar As Double)\n Return New Vector(v1.store.Select(Function(x) x * scalar))\n End Operator\n\n Public Overloads Shared Operator /(v1 As Vector, scalar As Double)\n Return New Vector(v1.store.Select(Function(x) x / scalar))\n End Operator\n\n Public Overrides Function ToString() As String\n Return String.Format(\"[{0}]\", String.Join(\",\", store))\n End Function\n End Class\n\n Sub Main()\n Dim v1 As New Vector(5, 7)\n Dim v2 As New Vector(2, 3)\n Console.WriteLine(v1 + v2)\n Console.WriteLine(v1 - v2)\n Console.WriteLine(v1 * 11)\n Console.WriteLine(v1 / 2)\n ' Works with arbitrary size vectors, too.\n Dim lostVector As New Vector({4, 8, 15, 16, 23, 42})\n Console.WriteLine(lostVector * 7)\n End Sub\n\nEnd Module"} +{"id": 13, "output": "0\n1\n3435\n438579088", "Python": "for i in range(5000):\n if i == sum(int(x) ** int(x) for x in str(i)):\n print(i)", "VB": "Imports System\n\nModule Program\n Sub Main()\n Dim i, j, n, n1, n2, n3, n4, n5, n6, n7, n8, n9, s2, s3, s4, s5, s6, s7, s8 As Integer,\n sum, ten1 As Long, ten2 As Long = 10\n Dim pow(9) As Long, num() As Byte\n For i = 1 To 9 : pow(i) = i : For j = 2 To i : pow(i) *= i : Next : Next\n For n = 1 To 11 : For n9 = 0 To n : For n8 = 0 To n - n9 : s8 = n9 + n8 : For n7 = 0 To n - s8\n s7 = s8 + n7 : For n6 = 0 To n - s7 : s6 = s7 + n6 : For n5 = 0 To n - s6\n s5 = s6 + n5 : For n4 = 0 To n - s5 : s4 = s5 + n4 : For n3 = 0 To n - s4\n s3 = s4 + n3 : For n2 = 0 To n - s3 : s2 = s3 + n2 : For n1 = 0 To n - s2\n sum = n1 * pow(1) + n2 * pow(2) + n3 * pow(3) + n4 * pow(4) + \n n5 * pow(5) + n6 * pow(6) + n7 * pow(7) + n8 * pow(8) + n9 * pow(9)\n If sum < ten1 OrElse sum >= ten2 Then Continue For\n redim num(9)\n For Each ch As Char In sum.ToString() : num(Convert.ToByte(ch) - 48) += 1 : Next\n If n - (s2 + n1) = num(0) AndAlso n1 = num(1) AndAlso n2 = num(2) AndAlso\n n3 = num(3) AndAlso n4 = num(4) AndAlso n5 = num(5) AndAlso n6 = num(6) AndAlso\n n7 = num(7) AndAlso n8 = num(8) AndAlso n9 = num(9) Then Console.WriteLine(sum)\n Next : Next : Next : Next : Next : Next : Next : Next : Next\n ten1 = ten2 : ten2 *= 10\n Next\n End Sub\nEnd Module"} +{"id": 14, "output": "1, 3", "Python": "from itertools import (product)\n\n\n# sumTwo :: [Int] -> Int -> [(Int, Int)]\ndef sumTwo(xs):\n '''All the pairs of integers in xs which\n sum to n.\n '''\n def go(n):\n ixs = list(enumerate(xs))\n return [\n (fst(x), fst(y)) for (x, y) in (\n product(ixs, ixs[1:])\n ) if fst(x) < fst(y) and n == snd(x) + snd(y)\n ]\n return lambda n: go(n)\n\n\n# TEST ----------------------------------------------------\n\n# main :: IO ()\ndef main():\n '''Tests'''\n\n xs = [0, 2, 11, 19, 90, 10]\n\n print(\n fTable(\n 'The indices of any two integers drawn from ' + repr(xs) +\n '\\nthat sum to a given value:\\n'\n )(str)(\n lambda x: str(x) + ' = ' + ', '.join(\n ['(' + str(xs[a]) + ' + ' + str(xs[b]) + ')' for a, b in x]\n ) if x else '(none)'\n )(\n sumTwo(xs)\n )(enumFromTo(10)(25))\n )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\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# MAIN ---\nif __name__ == '__main__':\n main()", "VB": "Module Module1\n\n Function TwoSum(numbers As Integer(), sum As Integer) As Integer()\n Dim map As New Dictionary(Of Integer, Integer)\n For index = 1 To numbers.Length\n Dim i = index - 1\n ' see if the complement is stored\n Dim key = sum - numbers(i)\n If map.ContainsKey(key) Then\n Return {map(key), i}\n End If\n map.Add(numbers(i), i)\n Next\n Return Nothing\n End Function\n\n Sub Main()\n Dim arr = {0, 2, 1, 19, 90}\n Const sum = 21\n\n Dim ts = TwoSum(arr, sum)\n Console.WriteLine(If(IsNothing(ts), \"no result\", $\"{ts(0)}, {ts(1)}\"))\n End Sub\n\nEnd Module"} +{"id": 15, "output": "[6.00000000, 25.50000000, 40.00000000, 42.50000000, 49.00000000]\n[7.00000000, 15.00000000, 37.50000000, 40.00000000, 41.00000000]\n[-1.95059594, -0.67674121, 0.23324706, 0.74607095, 1.73131507]", "Python": "from __future__ import division\nimport math\nimport sys\n\ndef fivenum(array):\n n = len(array)\n if n == 0:\n print(\"you entered an empty array.\")\n sys.exit()\n x = sorted(array)\n \n n4 = math.floor((n+3.0)/2.0)/2.0\n d = [1, n4, (n+1)/2, n+1-n4, n]\n sum_array = []\n \n for e in range(5):\n floor = int(math.floor(d[e] - 1))\n ceil = int(math.ceil(d[e] - 1))\n sum_array.append(0.5 * (x[floor] + x[ceil]))\n \n return sum_array\n\nx = [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970,\n-0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163,\n1.04312009, -0.10305385, 0.75775634, 0.32566578]\n\ny = fivenum(x)\nprint(y)", "VB": "Imports System.Runtime.CompilerServices\nImports System.Text\n\nModule Module1\n\n \n Function AsString(Of T)(c As ICollection(Of T), Optional format As String = \"{0}\") As String\n Dim sb As New StringBuilder(\"[\")\n Dim it = c.GetEnumerator()\n If it.MoveNext() Then\n sb.AppendFormat(format, it.Current)\n End If\n While it.MoveNext()\n sb.Append(\", \")\n sb.AppendFormat(format, it.Current)\n End While\n Return sb.Append(\"]\").ToString()\n End Function\n\n Function Median(x As Double(), start As Integer, endInclusive As Integer) As Double\n Dim size = endInclusive - start + 1\n If size <= 0 Then\n Throw New ArgumentException(\"Array slice cannot be empty\")\n End If\n Dim m = start + size \\ 2\n Return If(size Mod 2 = 1, x(m), (x(m - 1) + x(m)) / 2.0)\n End Function\n\n Function Fivenum(x As Double()) As Double()\n For Each d In x\n If Double.IsNaN(d) Then\n Throw New ArgumentException(\"Unable to deal with arrays containing NaN\")\n End If\n Next\n\n Array.Sort(x)\n Dim result(4) As Double\n\n result(0) = x.First()\n result(2) = Median(x, 0, x.Length - 1)\n result(4) = x.Last()\n\n Dim m = x.Length \\ 2\n Dim lowerEnd = If(x.Length Mod 2 = 1, m, m - 1)\n\n result(1) = Median(x, 0, lowerEnd)\n result(3) = Median(x, m, x.Length - 1)\n\n Return result\n End Function\n\n Sub Main()\n Dim x1 = {\n New Double() {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},\n New Double() {36.0, 40.0, 7.0, 39.0, 41.0, 15.0},\n New Double() {\n 0.14082834, 0.0974879, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.4667597, -0.74621349, -0.72588772, 0.6390516, 0.61501527,\n -0.9898378, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n }\n }\n For Each x In x1\n Dim result = Fivenum(x)\n Console.WriteLine(result.AsString(\"{0:F8}\"))\n Next\n End Sub\n\nEnd Module"} +{"id": 16, "output": "Current Array:\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\nNew Filtered Array:\n2\n4\n6\n8\n10\nOrginal Array After Filtering:\n2\n4\n6\n8\n10", "Python": "values = range(10)\nevens = [x for x in values if not x & 1]\nievens = (x for x in values if not x & 1) # lazy\n# alternately but less idiomatic:\nevens = filter(lambda x: not x & 1, values)", "VB": "Module Filter\n\n Sub Main()\n Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n Dim newEvenArray() As Integer\n\n Console.WriteLine(\"Current Array:\")\n For Each i As Integer In array\n Console.WriteLine(i)\n Next\n\n newEvenArray = filterArrayIntoNewArray(array)\n\n Console.WriteLine(\"New Filtered Array:\")\n For Each i As Integer In newEvenArray\n Console.WriteLine(i)\n Next\n\n array = changeExistingArray(array)\n\n Console.WriteLine(\"Orginal Array After Filtering:\")\n For Each i As Integer In array\n Console.WriteLine(i)\n Next\n End Sub\n\n Private Function changeExistingArray(array() As Integer) As Integer()\n Return filterArrayIntoNewArray(array)\n End Function\n\n Private Function filterArrayIntoNewArray(array() As Integer) As Integer()\n Dim result As New List(Of Integer)\n For Each element As Integer In array\n If element Mod 2 = 0 Then\n result.Add(element)\n End If\n Next\n Return result.ToArray\n End Function\n\nEnd Module"} +{"id": 17, "output": "101\n110010\n10001100101000", "Python": "for i in range(16): print(bin(i)[2:])", "VB": "Module Program\n Sub Main\n For Each number In {5, 50, 9000}\n Console.WriteLine(Convert.ToString(number, 2))\n Next\n End Sub\nEnd Module"} +{"id": 18, "output": "First 20 Brazilian numbers:\n7 8 10 12 13 14 15 16 18 20 21 22 24 26 27 28 30 31 32 33 \n\nFirst 20 odd Brazilian numbers:\n7 13 15 21 27 31 33 35 39 43 45 51 55 57 63 65 69 73 75 77 \n\nFirst 20 prime Brazilian numbers:\n7 13 31 43 73 127 157 211 241 307 421 463 601 757 1093 1123 1483 1723 2551 2801 ", "Python": "from itertools import count, islice\n\n\n# isBrazil :: Int -> Bool\ndef isBrazil(n):\n '''True if n is a Brazilian number,\n in the sense of OEIS:A125134.\n '''\n return 7 <= n and (\n 0 == n % 2 or any(\n map(monoDigit(n), range(2, n - 1))\n )\n )\n\n\n# monoDigit :: Int -> Int -> Bool\ndef monoDigit(n):\n '''True if all the digits of n,\n in the given base, are the same.\n '''\n def go(base):\n def g(b, n):\n (q, d) = divmod(n, b)\n\n def p(qr):\n return d != qr[1] or 0 == qr[0]\n\n def f(qr):\n return divmod(qr[0], b)\n return d == until(p)(f)(\n (q, d)\n )[1]\n return g(base, n)\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''First 20 members each of:\n OEIS:A125134\n OEIS:A257521\n OEIS:A085104\n '''\n for kxs in ([\n (' ', count(1)),\n (' odd ', count(1, 2)),\n (' prime ', primes())\n ]):\n print(\n 'First 20' + kxs[0] + 'Brazilians:\\n' +\n showList(take(20)(filter(isBrazil, kxs[1]))) + '\\n'\n )\n\n\n# ------------------- GENERIC FUNCTIONS --------------------\n\n# primes :: [Int]\ndef primes():\n ''' Non finite sequence of prime numbers.\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# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\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# MAIN ---\nif __name__ == '__main__':\n main()", "VB": "Module Module1\n\n Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean\n Dim f As Integer = n Mod b : n \\= b : While n > 0\n If n Mod b <> f Then Return False Else n \\= b\n End While : Return True\n End Function\n\n Function isBrazilian(ByVal n As Integer) As Boolean\n If n < 7 Then Return False\n If n Mod 2 = 0 Then Return True\n For b As Integer = 2 To n - 2\n If sameDigits(n, b) Then Return True\n Next : Return False\n End Function\n\n Function isPrime(ByVal n As Integer) As Boolean\n If n < 2 Then Return False\n If n Mod 2 = 0 Then Return n = 2\n If n Mod 3 = 0 Then Return n = 3\n Dim d As Integer = 5\n While d * d <= n\n If n Mod d = 0 Then Return False Else d += 2\n If n Mod d = 0 Then Return False Else d += 4\n End While : Return True\n End Function\n\n Sub Main(args As String())\n For Each kind As String In {\" \", \" odd \", \" prime \"}\n Console.WriteLine(\"First 20{0}Brazilian numbers:\", kind)\n Dim Limit As Integer = 20, n As Integer = 7\n Do\n If isBrazilian(n) Then Console.Write(\"{0} \", n) : Limit -= 1\n Select Case kind\n Case \" \" : n += 1\n Case \" odd \" : n += 2\n Case \" prime \" : Do : n += 2 : Loop Until isPrime(n)\n End Select\n Loop While Limit > 0\n Console.Write(vbLf & vbLf)\n Next\n End Sub\n\nEnd Module"} +{"id": 19, "output": "[1, 6, 10, 15, 16, 21, 25, 30, 31, 36, 40, 45, 46, 51, 55, 60, 61, 66, 70, 75, 76, 81, 85, 90, 91, 96, 100, 105, 106, 111, 115, 120, 121, 126, 130, 135, 136, 141, 145, 150, 151, 156, 160, 165, 166, 171, 175, 180, 181, 186, 190, 195, 196, 201, 205, 210, 211, 216, 220, 225, 226, 231, 235, 240, 241, 246, 250, 255]\n[1, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 63, 64, 72, 73, 81, 82, 90, 91, 99]\n[1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97, 112, 113, 128, 129, 144, 145, 160, 161, 176, 177, 192, 193, 208, 209, 224, 225, 240, 241, 256, 257, 272, 273, 288]", "Python": "def CastOut(Base=10, Start=1, End=999999):\n ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]\n x,y = divmod(Start, Base-1)\n while True:\n for n in ran:\n k = (Base-1)*x + n\n if k < Start:\n continue\n if k > End:\n return\n yield k\n x += 1\n\nfor V in CastOut(Base=16,Start=1,End=255):\n print(V, end=' ')", "VB": "Module Module1\n Sub Print(ls As List(Of Integer))\n Dim iter = ls.GetEnumerator\n Console.Write(\"[\")\n If iter.MoveNext Then\n Console.Write(iter.Current)\n End If\n While iter.MoveNext\n Console.Write(\", \")\n Console.Write(iter.Current)\n End While\n Console.WriteLine(\"]\")\n End Sub\n\n Function CastOut(base As Integer, start As Integer, last As Integer) As List(Of Integer)\n Dim ran = Enumerable.Range(0, base - 1).Where(Function(y) y Mod (base - 1) = (y * y) Mod (base - 1)).ToArray()\n Dim x = start \\ (base - 1)\n\n Dim result As New List(Of Integer)\n While True\n For Each n In ran\n Dim k = (base - 1) * x + n\n If k < start Then\n Continue For\n End If\n If k > last Then\n Return result\n End If\n result.Add(k)\n Next\n x += 1\n End While\n Return result\n End Function\n\n Sub Main()\n Print(CastOut(16, 1, 255))\n Print(CastOut(10, 1, 99))\n Print(CastOut(17, 1, 288))\n End Sub\n\nEnd Module"} +{"id": 20, "output": "*********************************************************************************\n*************************** ***************************\n********* ********* ********* *********\n*** *** *** *** *** *** *** ***\n* * * * * * * * * * * * * * * *", "Python": "WIDTH = 81\nHEIGHT = 5\n\nlines=[]\ndef cantor(start, len, index):\n seg = len / 3\n if seg == 0:\n return None\n for it in xrange(HEIGHT-index):\n i = index + it\n for jt in xrange(seg):\n j = start + seg + jt\n pos = i * WIDTH + j\n lines[pos] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n return None\n\nlines = ['*'] * (WIDTH*HEIGHT)\ncantor(0, WIDTH, 1)\n\nfor i in xrange(HEIGHT):\n beg = WIDTH * i\n print ''.join(lines[beg : beg+WIDTH])", "VB": "Module Module1\n\n Const WIDTH = 81\n Const HEIGHT = 5\n Dim lines(HEIGHT, WIDTH) As Char\n\n Sub Init()\n For i = 0 To HEIGHT - 1\n For j = 0 To WIDTH - 1\n lines(i, j) = \"*\"\n Next\n Next\n End Sub\n\n Sub Cantor(start As Integer, len As Integer, index As Integer)\n Dim seg As Integer = len / 3\n If seg = 0 Then\n Return\n End If\n For i = index To HEIGHT - 1\n For j = start + seg To start + seg * 2 - 1\n lines(i, j) = \" \"\n Next\n Next\n Cantor(start, seg, index + 1)\n Cantor(start + seg * 2, seg, index + 1)\n End Sub\n\n Sub Main()\n Init()\n Cantor(0, WIDTH, 1)\n For i = 0 To HEIGHT - 1\n For j = 0 To WIDTH - 1\n Console.Write(lines(i, j))\n Next\n Console.WriteLine()\n Next\n End Sub\n\nEnd Module"} +{"id": 21, "output": "10 remaining.\n5 remaining.\n3 remaining.\n(July, 16)", "Python": "from itertools import groupby\nfrom re import split\n\n\n# main :: IO ()\ndef main():\n '''Derivation of the date.'''\n\n month, day = 0, 1\n print(\n # (3 :: A \"Then I also know\")\n # (A's month contains only one remaining day)\n uniquePairing(month)(\n # (2 :: B \"I know now\")\n # (B's day is paired with only one remaining month)\n uniquePairing(day)(\n # (1 :: A \"I know that Bernard does not know\")\n # (A's month is not among those with unique days)\n monthsWithUniqueDays(False)([\n # 0 :: Cheryl's list:\n tuple(x.split()) for x in\n split(\n ', ',\n 'May 15, May 16, May 19, ' +\n 'June 17, June 18, ' +\n 'July 14, July 16, ' +\n 'Aug 14, Aug 15, Aug 17'\n )\n ])\n )\n )\n )\n\n\n# ------------------- QUERY FUNCTIONS --------------------\n\n# monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\ndef monthsWithUniqueDays(blnInclude):\n '''The subset of months with (or without) unique days.\n '''\n def go(xs):\n month, day = 0, 1\n months = [fst(x) for x in uniquePairing(day)(xs)]\n return [\n md for md in xs\n if blnInclude or not (md[month] in months)\n ]\n return go\n\n\n# uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)]\ndef uniquePairing(i):\n '''Subset of months (or days) with a unique intersection.\n '''\n def go(xs):\n def inner(md):\n dct = md[i]\n uniques = [\n k for k in dct.keys()\n if 1 == len(dct[k])\n ]\n return [tpl for tpl in xs if tpl[i] in uniques]\n return inner\n return ap(bindPairs)(go)\n\n\n# bindPairs :: [(Month, Day)] ->\n# ((Dict String [String], Dict String [String])\n# -> [(Month, Day)]) -> [(Month, Day)]\ndef bindPairs(xs):\n '''List monad injection operator for lists\n of (Month, Day) pairs.\n '''\n return lambda f: f(\n (\n dictFromPairs(xs),\n dictFromPairs(\n [(b, a) for (a, b) in xs]\n )\n )\n )\n\n\n# dictFromPairs :: [(Month, Day)] -> Dict Text [Text]\ndef dictFromPairs(xs):\n '''A dictionary derived from a list of\n month day pairs.\n '''\n return {\n k: [snd(x) for x in m] for k, m in groupby(\n sorted(xs, key=fst), key=fst\n )\n }\n\n\n# ----------------------- GENERIC ------------------------\n\n# ap :: (a -> b -> c) -> (a -> b) -> a -> c\ndef ap(f):\n '''Applicative instance for functions.\n '''\n def go(g):\n def fxgx(x):\n return f(x)(\n g(x)\n )\n return fxgx\n return go\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.\n '''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second component of a pair.\n '''\n return tpl[1]\n\n\nif __name__ == '__main__':\n main()", "VB": "Module Module1\n\n Structure MonDay\n Dim month As String\n Dim day As Integer\n\n Sub New(m As String, d As Integer)\n month = m\n day = d\n End Sub\n\n Public Overrides Function ToString() As String\n Return String.Format(\"({0}, {1})\", month, day)\n End Function\n End Structure\n\n Sub Main()\n Dim dates = New HashSet(Of MonDay) From {\n New MonDay(\"May\", 15),\n New MonDay(\"May\", 16),\n New MonDay(\"May\", 19),\n New MonDay(\"June\", 17),\n New MonDay(\"June\", 18),\n New MonDay(\"July\", 14),\n New MonDay(\"July\", 16),\n New MonDay(\"August\", 14),\n New MonDay(\"August\", 15),\n New MonDay(\"August\", 17)\n }\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The month cannot have a unique day.\n Dim monthsWithUniqueDays = dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First().month).ToHashSet()\n dates.RemoveWhere(Function(d) monthsWithUniqueDays.Contains(d.month))\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The day must now be unique.\n dates.IntersectWith(dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First()))\n Console.WriteLine(\"{0} remaining.\", dates.Count)\n\n ' The month must now be unique.\n dates.IntersectWith(dates.GroupBy(Function(d) d.month).Where(Function(g) g.Count() = 1).Select(Function(g) g.First()))\n Console.WriteLine(dates.Single())\n End Sub\n\nEnd Module"} +{"id": 22, "output": "Base 2: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0\nBase 3: 0 1 2 1 2 0 2 0 1 1 2 0 2 0 1 0 1 2 2 0 1 0 1 2 1\nBase 5: 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3\nBase 11: 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 0 2 3 4\nHow many times does each get a turn in 50000 iterations?\n With 191 people: 261 or 262\n With 1377 people: 36 or 37\n With 49999 people: 1 or 2\n With 50000 people: 1\n With 50001 people: Only 50000 have a turn", "Python": "from itertools import count, islice\n\ndef _basechange_int(num, b):\n \"\"\"\n Return list of ints representing positive num in base b\n\n >>> b = 3\n >>> print(b, [_basechange_int(num, b) for num in range(11)])\n 3 [[0], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [1, 0, 0], [1, 0, 1]]\n >>>\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]}\")", "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"} +{"id": 23, "output": " i d\n 2 3.21851142\n 3 4.38567760\n 4 4.60094928\n 5 4.65513050\n 6 4.66611195\n 7 4.66854858\n 8 4.66906066\n 9 4.66917155\n10 4.66919515\n11 4.66920026\n12 4.66920098\n13 4.66920537", "Python": "max_it = 13\nmax_it_j = 10\na1 = 1.0\na2 = 0.0\nd1 = 3.2\na = 0.0\n\nprint \" i d\"\nfor i in range(2, max_it + 1):\n a = a1 + (a1 - a2) / d1\n for j in range(1, max_it_j + 1):\n x = 0.0\n y = 0.0\n for k in range(1, (1 << i) + 1):\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n a = a - x / y\n d = (a1 - a2) / (a - a1)\n print(\"{0:2d} {1:.8f}\".format(i, d))\n d1 = d\n a2 = a1\n a1 = a", "VB": "Module Module1\n\n Sub Main()\n Dim maxIt = 13\n Dim maxItJ = 10\n Dim a1 = 1.0\n Dim a2 = 0.0\n Dim d1 = 3.2\n Console.WriteLine(\" i d\")\n For i = 2 To maxIt\n Dim a = a1 + (a1 - a2) / d1\n For j = 1 To maxItJ\n Dim x = 0.0\n Dim y = 0.0\n For k = 1 To 1 << i\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n Next\n a -= x / y\n Next\n Dim d = (a1 - a2) / (a - a1)\n Console.WriteLine(\"{0,2:d} {1:f8}\", i, d)\n d1 = d\n a2 = a1\n a1 = a\n Next\n End Sub\n\nEnd Module"} +{"id": 24, "output": "Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765\ntribonacci: 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513, 35890, 66012\ntetranacci: 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536, 10671, 20569, 39648, 76424, 147312\npentanacci: 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930, 13624, 26784, 52656, 103519, 203513\nhexanacci: 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617, 15109, 29970, 59448, 117920, 233904\nLucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349", "Python": "from itertools import islice, cycle\n\ndef fiblike(tail):\n for x in tail:\n yield x\n for i in cycle(xrange(len(tail))):\n tail[i] = x = sum(tail)\n yield x\n\nfibo = fiblike([1, 1])\nprint list(islice(fibo, 10))\nlucas = fiblike([2, 1])\nprint list(islice(lucas, 10))\n\nsuffixes = \"fibo tribo tetra penta hexa hepta octo nona deca\"\nfor n, name in zip(xrange(2, 11), suffixes.split()):\n fib = fiblike([1] + [2 ** i for i in xrange(n - 1)])\n items = list(islice(fib, 15))\n print \"n=%2i, %5snacci -> %s ...\" % (n, name, items)", "VB": "Public Class FibonacciNstep\n\n Const nmax = 20\n\n Sub Main()\n Dim bonacci As String() = {\"\", \"\", \"Fibo\", \"tribo\", \"tetra\", \"penta\", \"hexa\"}\n Dim i As Integer\n 'Fibonacci:\n For i = 2 To 6\n Debug.Print(bonacci(i) & \"nacci: \" & FibonacciN(i, nmax))\n Next i\n 'Lucas:\n Debug.Print(\"Lucas: \" & FibonacciN(2, nmax, 2))\n End Sub 'Main\n\n Private Function FibonacciN(iStep As Long, Count As Long, Optional First As Long = 0) As String\n Dim i, j As Integer, Sigma As Long, c As String\n Dim T(nmax) As Long\n T(1) = IIf(First = 0, 1, First)\n T(2) = 1\n For i = 3 To Count\n Sigma = 0\n For j = i - 1 To i - iStep Step -1\n If j > 0 Then\n Sigma += T(j)\n End If\n Next j\n T(i) = Sigma\n Next i\n c = \"\"\n For i = 1 To nmax\n c &= \", \" & T(i)\n Next i\n Return Mid(c, 3)\n End Function 'FibonacciN\n\nEnd Class 'FibonacciNstep"} +{"id": 25, "output": "fibo( 0 )= 0 \nfibo( 1 )= 1 \nfibo( 2 )= 1 ", "Python": "from math import *\n\ndef analytic_fibonacci(n):\n sqrt_5 = sqrt(5);\n p = (1 + sqrt_5) / 2;\n q = 1/p;\n return int( (p**n + q**n) / sqrt_5 + 0.5 )\n\nfor i in range(1,2):\n print analytic_fibonacci(i),", "VB": "Sub fibonacci()\n Const n = 2\n Dim i As Integer\n Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal\n f1 = CDec(0): f2 = CDec(1) 'for Decimal setting\n Debug.Print \"fibo(\"; 0; \")=\"; f1\n Debug.Print \"fibo(\"; 1; \")=\"; f2\n For i = 2 To n\n f3 = f1 + f2\n Debug.Print \"fibo(\"; i; \")=\"; f3\n f1 = f2\n f2 = f3\n Next i\nEnd Sub 'fibonacci"} +{"id": 26, "output": "Arithmetic mean 5.5\n Geometric mean 4.52872868811677\n Harmonic mean 3.41417152147406", "Python": "from operator import mul\nfrom functools import reduce\n\n\ndef amean(num):\n return sum(num) / len(num)\n\n\ndef gmean(num):\n return reduce(mul, num, 1)**(1 / len(num))\n\n\ndef hmean(num):\n return len(num) / sum(1 / n for n in num)\n\n\nnumbers = range(1, 11) # 1..10\na, g, h = amean(numbers), gmean(numbers), hmean(numbers)\nprint(a, g, h)\nassert a >= g >= h", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n\n \n Function Gmean(n As IEnumerable(Of Double)) As Double\n Return Math.Pow(n.Aggregate(Function(s, i) s * i), 1.0 / n.Count())\n End Function\n\n \n Function Hmean(n As IEnumerable(Of Double)) As Double\n Return n.Count() / n.Sum(Function(i) 1.0 / i)\n End Function\n\n Sub Main()\n Dim nums = From n In Enumerable.Range(1, 10) Select CDbl(n)\n\n Dim a = nums.Average()\n Dim g = nums.Gmean()\n Dim h = nums.Hmean()\n\n Console.WriteLine(\"Arithmetic mean {0}\", a)\n Console.WriteLine(\" Geometric mean {0}\", g)\n Console.WriteLine(\" Harmonic mean {0}\", h)\n Debug.Assert(a >= g AndAlso g >= h)\n End Sub\n\nEnd Module"} +{"id": 27, "output": "0\n-90\n20", "Python": "from cmath import rect, phase\nfrom math import radians, degrees\ndef mean_angle(deg):\n return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n \nfor angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:\n print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')", "VB": "Imports System.Math\n\nModule Module1\n\n Function MeanAngle(angles As Double()) As Double\n Dim x = angles.Sum(Function(a) Cos(a * PI / 180)) / angles.Length\n Dim y = angles.Sum(Function(a) Sin(a * PI / 180)) / angles.Length\n Return Atan2(y, x) * 180 / PI\n End Function\n\n Sub Main()\n Dim printMean = Sub(x As Double()) Console.WriteLine(\"{0:0.###}\", MeanAngle(x))\n printMean({350, 10})\n printMean({90, 180, 270, 360})\n printMean({10, 20, 30})\n End Sub\n\nEnd Module"} +{"id": 28, "output": "The attractive numbers up to and including 120 are:\n 4 6 8 9 10 12 14 15 18 20 21 22 25 26 27 28 30 32 33 34\n 35 38 39 42 44 45 46 48 49 50 51 52 55 57 58 62 63 65 66 68\n 69 70 72 74 75 76 77 78 80 82 85 86 87 91 92 93 94 95 98 99\n 102 105 106 108 110 111 112 114 115 116 117 118 119 120", "Python": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,121):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,", "VB": "Module Module1\n Const MAX = 120\n\n Function IsPrime(n As Integer) As Boolean\n If n < 2 Then Return False\n If n Mod 2 = 0 Then Return n = 2\n If n Mod 3 = 0 Then Return n = 3\n Dim d = 5\n While d * d <= n\n If n Mod d = 0 Then Return False\n d += 2\n If n Mod d = 0 Then Return False\n d += 4\n End While\n Return True\n End Function\n\n Function PrimefactorCount(n As Integer) As Integer\n If n = 1 Then Return 0\n If IsPrime(n) Then Return 1\n Dim count = 0\n Dim f = 2\n While True\n If n Mod f = 0 Then\n count += 1\n n /= f\n If n = 1 Then Return count\n If IsPrime(n) Then f = n\n ElseIf f >= 3 Then\n f += 2\n Else\n f = 3\n End If\n End While\n Throw New Exception(\"Unexpected\")\n End Function\n\n Sub Main()\n Console.WriteLine(\"The attractive numbers up to and including {0} are:\", MAX)\n Dim i = 1\n Dim count = 0\n While i <= MAX\n Dim n = PrimefactorCount(i)\n If IsPrime(n) Then\n Console.Write(\"{0,4}\", 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 End Sub\n\nEnd Module"} +{"id": 29, "output": " 5724 is valid\n 5727 is invalid\n112946 is valid\n112949 is invalid", "Python": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')", "VB": "Module Module1\n\n ReadOnly table = {\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}\n }\n\n Function Damm(s As String) As Boolean\n Dim interim = 0\n For Each c In s\n interim = table(interim, AscW(c) - AscW(\"0\"))\n Next\n Return interim = 0\n End Function\n\n Sub Main()\n Dim numbers = {5724, 5727, 112946, 112949}\n For Each number In numbers\n Dim isvalid = Damm(number.ToString())\n If isvalid Then\n Console.WriteLine(\"{0,6} is valid\", number)\n Else\n Console.WriteLine(\"{0,6} is invalid\", number)\n End If\n Next\n End Sub\n\nEnd Module"} +{"id": 30, "output": "3", "Python": "from operator import (mul)\n\n\n# dotProduct :: Num a => [a] -> [a] -> Either String a\ndef dotProduct(xs):\n '''Either the dot product of xs and ys,\n or a string reporting unmatched vector sizes.\n '''\n return lambda ys: Left('vector sizes differ') if (\n len(xs) != len(ys)\n ) else Right(sum(map(mul, xs, ys)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Dot product of other vectors with [1, 3, -5]'''\n\n print(\n fTable(main.__doc__ + ':\\n')(str)(str)(\n compose(\n either(append('Undefined :: '))(str)\n )(dotProduct([1, 3, -5]))\n )([[4, -2, -1, 8], [4, -2], [4, 2, -1], [4, -2, -1]])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# append (++) :: [a] -> [a] -> [a]\n# append (++) :: String -> String -> String\ndef append(xs):\n '''Two lists or strings combined into one.'''\n return lambda ys: xs + ys\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\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# MAIN ---\nif __name__ == '__main__':\n main()", "VB": "Module Module1\n\n Function DotProduct(a As Decimal(), b As Decimal()) As Decimal\n Return a.Zip(b, Function(x, y) x * y).Sum()\n End Function\n\n Sub Main()\n Console.WriteLine(DotProduct({1, 3, -5}, {4, -2, -1}))\n Console.ReadLine()\n End Sub\n\nEnd Module"} +{"id": 31, "output": "1 = 1\n2 = 2\n3 = 3\n4 = 2 x 2\n5 = 5\n6 = 2 x 3\n7 = 7\n8 = 2 x 2 x 2\n9 = 3 x 3\n10 = 2 x 5\n9991 = 97 x 103\n9992 = 2 x 2 x 2 x 1249\n9993 = 3 x 3331\n9994 = 2 x 19 x 263\n9995 = 5 x 1999\n9996 = 2 x 2 x 3 x 7 x 7 x 17\n9997 = 13 x 769\n9998 = 2 x 4999\n9999 = 3 x 3 x 11 x 101\n10000 = 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5", "Python": "from functools import lru_cache\n\nprimes = [2, 3, 5, 7, 11, 13, 17] # Will be extended\n\n@lru_cache(maxsize=2000)\ndef pfactor(n):\n if n == 1:\n return [1]\n n2 = n // 2 + 1\n for p in primes:\n if p <= n2:\n d, m = divmod(n, p)\n if m == 0:\n if d > 1:\n return [p] + pfactor(d)\n else:\n return [p]\n else:\n if n > primes[-1]:\n primes.append(n)\n return [n]\n \nif __name__ == '__main__':\n mx = 5000\n for n in range(1, mx + 1):\n factors = pfactor(n)\n if n <= 10 or n >= mx - 20:\n print( '%4i %5s %s' % (n,\n '' if factors != [n] or n == 1 else 'prime',\n 'x'.join(str(i) for i in factors)) )\n if n == 11:\n print('...')\n \n print('\\nNumber of primes gathered up to', n, 'is', len(primes))\n print(pfactor.cache_info())", "VB": "Module CountingInFactors\n\n Sub Main()\n For i As Integer = 1 To 10\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n\n For i As Integer = 9991 To 10000\n Console.WriteLine(\"{0} = {1}\", i, CountingInFactors(i))\n Next\n End Sub\n\n Private Function CountingInFactors(ByVal n As Integer) As String\n If n = 1 Then Return \"1\"\n\n Dim sb As New Text.StringBuilder()\n\n CheckFactor(2, n, sb)\n If n = 1 Then Return sb.ToString()\n\n CheckFactor(3, n, sb)\n If n = 1 Then Return sb.ToString()\n\n For i As Integer = 5 To n Step 2\n If i Mod 3 = 0 Then Continue For\n\n CheckFactor(i, n, sb)\n If n = 1 Then Exit For\n Next\n\n Return sb.ToString()\n End Function\n\n Private Sub CheckFactor(ByVal mult As Integer, ByRef n As Integer, ByRef sb As Text.StringBuilder)\n Do While n Mod mult = 0\n If sb.Length > 0 Then sb.Append(\" x \")\n sb.Append(mult)\n n = n / mult\n Loop\n End Sub\n\nEnd Module"} +{"id": 32, "output": "3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36\n888888877 888888878 888888880 888888883 888888885 888888886", "Python": "from itertools import count, islice\n\n\n# isPernicious :: Int -> Bool\ndef isPernicious(n):\n '''True if the population count of n is\n a prime number.\n '''\n return isPrime(popCount(n))\n\n\n# oeisA052294 :: [Int]\ndef oeisA052294():\n '''A non-finite stream of pernicious numbers.\n (Numbers with a prime population count)\n '''\n return (x for x in count(1) if isPernicious(x))\n\n\n# popCount :: Int -> Int\ndef popCount(n):\n '''The count of non-zero digits in the binary\n representation of the positive integer n.\n '''\n def go(x):\n return divmod(x, 2) if 0 < x else None\n return sum(unfoldl(go)(n))\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 25, and any in the range\n [888,888,877..888,888,888]\n '''\n\n print(\n take(25)(\n oeisA052294()\n )\n )\n print([\n x for x in enumFromTo(888888877)(888888888)\n if isPernicious(x)\n ])\n\n\n# ----------------------- GENERIC ------------------------\n\n# enumFromTo :: Int -> Int -> [Int]\ndef enumFromTo(m):\n '''Enumeration of integer values [m..n]'''\n def go(n):\n return range(m, 1 + n)\n return go\n\n\n# isPrime :: Int -> Bool\ndef isPrime(n):\n '''True if n is prime.'''\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 return not any(map(\n lambda x: 0 == n % x or 0 == n % (2 + x),\n range(5, 1 + int(n ** 0.5), 6)\n ))\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\ndef unfoldl(f):\n '''A lazy (generator) list unfolded from a seed value\n by repeated application of f until no residue remains.\n Dual to fold/reduce.\n f returns either None or just (residue, value).\n For a strict output list, wrap the result with list()\n '''\n def go(v):\n residueValue = f(v)\n while residueValue:\n yield residueValue[1]\n residueValue = f(residueValue[0])\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()", "VB": "Module Module1\n\n Function PopulationCount(n As Long) As Integer\n Dim cnt = 0\n Do\n If (n Mod 2) <> 0 Then\n cnt += 1\n End If\n n >>= 1\n Loop While n > 0\n Return cnt\n End Function\n\n Function IsPrime(x As Integer) As Boolean\n If x <= 2 OrElse (x Mod 2) = 0 Then\n Return x = 2\n End If\n\n Dim limit = Math.Sqrt(x)\n For i = 3 To limit Step 2\n If x Mod i = 0 Then\n Return False\n End If\n Next\n\n Return True\n End Function\n\n Function Pernicious(start As Integer, count As Integer, take As Integer) As IEnumerable(Of Integer)\n Return Enumerable.Range(start, count).Where(Function(n) IsPrime(PopulationCount(n))).Take(take)\n End Function\n\n Sub Main()\n For Each n In Pernicious(0, Integer.MaxValue, 25)\n Console.Write(\"{0} \", n)\n Next\n Console.WriteLine()\n\n For Each n In Pernicious(888888877, 11, 11)\n Console.Write(\"{0} \", n)\n Next\n Console.WriteLine()\n End Sub\n\nEnd Module"} +{"id": 33, "output": " 3 (11 ) 10 (1010 ) 15 (1111 ) 36 (100100 ) 45 (101101 ) \n 54 (110110 ) 63 (111111 ) 136 (10001000 ) 153 (10011001 ) 170 (10101010 ) \n187 (10111011 ) 204 (11001100 ) 221 (11011101 ) 238 (11101110 ) 255 (11111111 ) \n528 (1000010000) 561 (1000110001) 594 (1001010010) 627 (1001110011) 660 (1010010100) \n693 (1010110101) 726 (1011010110) 759 (1011110111) 792 (1100011000) 825 (1100111001) \n858 (1101011010) 891 (1101111011) 924 (1110011100) 957 (1110111101) 990 (1111011110) ", "Python": "def bits(n):\n \"\"\"Count the amount of bits required to represent n\"\"\"\n r = 0\n while n:\n n >>= 1\n r += 1\n return r\n \ndef concat(n):\n \"\"\"Concatenate the binary representation of n to itself\"\"\"\n return n << bits(n) | n\n \nn = 1\nwhile concat(n) <= 1000:\n print(\"{0}: {0:b}\".format(concat(n)))\n n += 1", "VB": "Imports System.Console\nModule Module1\n Sub Main()\n Dim p, c, k, lmt as integer : p = 2 : lmt = 1000\n For n As Integer = 1 to lmt\n p += If(n >= p, p, 0) : k = n + n * p\n If k > lmt Then Exit For Else c += 1\n Write(\"{0,3} ({1,-10}) {2}\", k, Convert.ToString( k, 2),\n If(c Mod 5 = 0, vbLf, \"\"))\n Next : WriteLine(vbLf + \"Found {0} numbers whose base 2 representation is the concatenation of two identical binary strings.\", c)\n End Sub\nEnd Module"} +{"id": 34, "output": "x^2 - 61 * y^2 = 1 for x = 1,766,319,049 and y = 226,153,980\nx^2 - 109 * y^2 = 1 for x = 158,070,671,986,249 and y = 15,140,424,455,100\nx^2 - 181 * y^2 = 1 for x = 2,469,645,423,824,185,801 and y = 183,567,298,683,461,940\nx^2 - 277 * y^2 = 1 for x = 159,150,073,798,980,475,849 and y = 9,562,401,173,878,027,020", "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))", "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"} +{"id": 35, "output": "3\n2\n2\n0", "Python": "\"the three truths\".count(\"th\")\n\"ababababab\".count(\"abab\")", "VB": "Module Count_Occurrences_of_a_Substring\n Sub Main()\n Console.WriteLine(CountSubstring(\"the three truths\", \"th\"))\n Console.WriteLine(CountSubstring(\"ababababab\", \"abab\"))\n Console.WriteLine(CountSubstring(\"abaabba*bbaba*bbab\", \"a*b\"))\n Console.WriteLine(CountSubstring(\"abc\", \"\"))\n End Sub\n\n Function CountSubstring(str As String, substr As String) As Integer\n Dim count As Integer = 0\n If (Len(str) > 0) And (Len(substr) > 0) Then\n Dim p As Integer = InStr(str, substr)\n Do While p <> 0\n p = InStr(p + Len(substr), str, substr)\n count += 1\n Loop\n End If\n Return count\n End Function\nEnd Module"} +{"id": 36, "output": "First 20:\n13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389\n\nBetween 7700 and 8000:\n7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963\n\n10000th:\n948349", "Python": "from __future__ import print_function\nfrom prime_decomposition import primes, is_prime\nfrom heapq import *\nfrom itertools import islice\n\ndef emirp():\n largest = set()\n emirps = []\n heapify(emirps)\n for pr in primes():\n while emirps and pr > emirps[0]:\n yield heappop(emirps)\n if pr in largest:\n yield pr\n else:\n rp = int(str(pr)[::-1])\n if rp > pr and is_prime(rp):\n heappush(emirps, pr)\n largest.add(rp)\n\nprint('First 20:\\n ', list(islice(emirp(), 20)))\nprint('Between 7700 and 8000:\\n [', end='')\nfor pr in emirp():\n if pr >= 8000: break\n if pr >= 7700: print(pr, end=', ')\nprint(']')\nprint('10000th:\\n ', list(islice(emirp(), 10000-1, 10000)))", "VB": "Imports System.Runtime.CompilerServices\n\nModule Module1\n \n Function ToHashSet(Of T)(source As IEnumerable(Of T)) As HashSet(Of T)\n Return New HashSet(Of T)(source)\n End Function\n\n \n Function Reverse(number As Integer) As Integer\n If number < 0 Then\n Return -Reverse(-number)\n End If\n If number < 10 Then\n Return number\n End If\n\n Dim rev = 0\n While number > 0\n rev = rev * 10 + number Mod 10\n number = number \\ 10\n End While\n\n Return rev\n End Function\n\n \n Function Delimit(Of T)(source As IEnumerable(Of T), Optional seperator As String = \" \") As String\n Return String.Join(If(seperator, \" \"), source)\n End Function\n\n Iterator Function Primes(bound As Integer) As IEnumerable(Of Integer)\n If bound < 2 Then\n Return\n End If\n Yield 2\n\n Dim composite As New BitArray((bound - 1) / 2)\n Dim limit As Integer = Int((Int(Math.Sqrt(bound)) - 1) / 2)\n For i = 0 To limit - 1\n If composite(i) Then\n Continue For\n End If\n Dim prime = 2 * i + 3\n Yield prime\n\n For j As Integer = Int((prime * prime - 2) / 2) To composite.Count - 1 Step prime\n composite(j) = True\n Next\n Next\n For i = limit To composite.Count - 1\n If Not composite(i) Then\n Yield 2 * i + 3\n End If\n Next\n End Function\n\n Iterator Function FindEmirpPrimes(limit As Integer) As IEnumerable(Of Integer)\n Dim ps = Primes(limit).ToHashSet()\n\n For Each p In ps\n Dim rev = p.Reverse()\n If rev <> p AndAlso ps.Contains(rev) Then\n Yield p\n End If\n Next\n End Function\n\n Sub Main()\n Dim limit = 1_000_000\n Console.WriteLine(\"First 20:\")\n Console.WriteLine(FindEmirpPrimes(limit).Take(20).Delimit())\n Console.WriteLine()\n\n Console.WriteLine(\"Between 7700 and 8000:\")\n Console.WriteLine(FindEmirpPrimes(limit).SkipWhile(Function(p) p < 7700).TakeWhile(Function(p) p < 8000).Delimit())\n Console.WriteLine()\n\n Console.WriteLine(\"10000th:\")\n Console.WriteLine(FindEmirpPrimes(limit).ElementAt(9999))\n End Sub\n\nEnd Module"} +{"id": 37, "output": "133 110 84 27 144", "Python": "MAX = 250\np5, sum2 = {}, {}\n\nfor i in range(1, MAX):\n\tp5[i**5] = i\n\tfor j in range(i, MAX):\n\t\tsum2[i**5 + j**5] = (i, j)\n\nsk = sorted(sum2.keys())\nfor p in sorted(p5.keys()):\n\tfor s in sk:\n\t\tif p <= s: break\n\t\tif p - s in sum2:\n\t\t\tprint(p5[p], sum2[s] + sum2[p-s])\n\t\t\texit()", "VB": "Imports System.Numerics 'BigInteger\n\nPublic Class EulerPower4Sum\n\n Private Sub MyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n Dim t1, t2 As DateTime\n t1 = Now\n EulerPower45Sum() '16.7 sec\n 'EulerPower44Sum() '633 years !!\n t2 = Now\n Console.WriteLine((t2 - t1).TotalSeconds & \" sec\")\n End Sub 'Load\n\n Private Sub EulerPower45Sum()\n '30^4 + 120^4 + 272^4 + 315^4 = 353^4\n Const MaxN = 360\n Dim i, j, i1, i2, i3, i4, i5 As Int32\n Dim p4(MaxN), n, sumx As Int64\n Debug.Print(\">EulerPower45Sum\")\n For i = 1 To MaxN\n n = 1\n For j = 1 To 4\n n *= i\n Next j\n p4(i) = n\n Next i\n For i1 = 1 To MaxN\n If i1 Mod 5 = 0 Then Debug.Print(\">i1=\" & i1)\n For i2 = i1 To MaxN\n For i3 = i2 To MaxN\n For i4 = i3 To MaxN\n sumx = p4(i1) + p4(i2) + p4(i3) + p4(i4)\n i5 = i4 + 1\n While i5 <= MaxN AndAlso p4(i5) <= sumx\n If p4(i5) = sumx Then\n Debug.Print(i1 & \" \" & i2 & \" \" & i3 & \" \" & i4 & \" \" & i5)\n Exit Sub\n End If\n i5 += 1\n End While\n Next i4\n Next i3\n Next i2\n Next i1\n Debug.Print(\"Not found!\")\n End Sub 'EulerPower45Sum\n\n Private Sub EulerPower44Sum()\n '95800^4 + 217519^4 + 414560^4 = 422481^4\n Const MaxN = 500000 '500000^4 => decimal(23) => binary(76) !!\n Dim i, j, i1, i2, i3, i4 As Int32\n Dim p4(MaxN), n, sumx As BigInteger\n Dim t0 As DateTime\n Debug.Print(\">EulerPower44Sum\")\n For i = 1 To MaxN\n n = 1\n For j = 1 To 4\n n *= i\n Next j\n p4(i) = n\n Next i\n t0 = Now\n For i1 = 1 To MaxN\n Debug.Print(\">i1=\" & i1)\n For i2 = i1 To MaxN\n If i2 Mod 100 = 0 Then Debug.Print(\">i1=\" & i1 & \" i2=\" & i2 & \" \" & Int((Now - t0).TotalSeconds) & \" sec\")\n For i3 = i2 To MaxN\n sumx = p4(i1) + p4(i2) + p4(i3)\n i4 = i3 + 1\n While i4 <= MaxN AndAlso p4(i4) <= sumx\n If p4(i4) = sumx Then\n Debug.Print(i1 & \" \" & i2 & \" \" & i3 & \" \" & i4)\n Exit Sub\n End If\n i4 += 1\n End While\n Next i3\n Next i2\n Next i1\n Debug.Print(\"Not found!\")\n End Sub 'EulerPower44Sum\n\nEnd Class"} +{"id": 38, "output": "18187", "Python": "import sys\n\ndef days( y,m,d ):\n ''' input year and month are shifted to begin the year in march'''\n m = (m + 9) % 12 \n y = y - m/10\n\n ''' with (m*306 + 5)/10 the number of days from march 1 to the current 'm' month '''\n result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )\n return result\n\ndef diff(one,two):\n [y1,m1,d1] = one.split('-')\n [y2,m2,d2] = two.split('-')\n # strings to integers\n year2 = days( int(y2),int(m2),int(d2))\n year1 = days( int(y1), int(m1), int(d1) )\n return year2 - year1\n\nif __name__ == \"__main__\":\n one = sys.argv[1]\n two = sys.argv[2]\n print diff(one,two)", "VB": "Imports System.Globalization\n\nModule Module1\n\n Function DateDiff(d1 As String, d2 As String) As Integer\n Dim a = DateTime.ParseExact(d1, \"yyyy-MM-dd\", CultureInfo.InvariantCulture)\n Dim b = DateTime.ParseExact(d2, \"yyyy-MM-dd\", CultureInfo.InvariantCulture)\n Return (b - a).TotalDays\n End Function\n\n Sub Main()\n Console.WriteLine(DateDiff(\"1970-01-01\", \"2019-10-18\"))\n End Sub\n\nEnd Module"} +{"id": 39, "output": "The first 20 anti-primes are:\n1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560", "Python": "from itertools import chain, count, cycle, islice, accumulate\n \ndef factors(n):\n def prime_powers(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\n \ndef antiprimes():\n mx = 0\n yield 1\n for c in count(2,2):\n if c >= 58: break\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln\n for c in count(60,30):\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln \n\nif __name__ == '__main__':\n print(*islice(antiprimes(), 40)))", "VB": "Module Module1\n\n Function CountDivisors(n As Integer) As Integer\n If n < 2 Then\n Return 1\n End If\n Dim count = 2 '1 and n\n For i = 2 To n \\ 2\n If n Mod i = 0 Then\n count += 1\n End If\n Next\n Return count\n End Function\n\n Sub Main()\n Dim maxDiv, count As Integer\n Console.WriteLine(\"The first 20 anti-primes are:\")\n\n Dim n = 1\n While count < 20\n Dim d = CountDivisors(n)\n\n If d > maxDiv Then\n Console.Write(\"{0} \", n)\n maxDiv = d\n count += 1\n End If\n n += 1\n End While\n\n Console.WriteLine()\n End Sub\n\nEnd Module"} +{"id": 40, "output": "25\n90\n175\n-175\n170\n-170\n-118.1184\n-80.7109\n-139.5832831234\n-72.3439185184\n-161.50295230785\n37.2988555882", "Python": "from __future__ import print_function\n \ndef getDifference(b1, b2):\n\tr = (b2 - b1) % 360.0\n\t# Python modulus has same sign as divisor, which is positive here,\n\t# so no need to consider negative case\n\tif r >= 180.0:\n\t\tr -= 360.0\n\treturn r\n \nif __name__ == \"__main__\":\n\tprint (\"Input in -180 to +180 range\")\n\tprint (getDifference(20.0, 45.0))\n\tprint (getDifference(-45.0, 45.0))\n\tprint (getDifference(-85.0, 90.0))\n\tprint (getDifference(-95.0, 90.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(29.4803, -88.6381))\n\tprint (getDifference(-78.3251, -159.036))\n \n\tprint (\"Input in wider range\")\n\tprint (getDifference(-70099.74233810938, 29840.67437876723))\n\tprint (getDifference(-165313.6666297357, 33693.9894517456))\n\tprint (getDifference(1174.8380510598456, -154146.66490124757))\n\tprint (getDifference(60175.77306795546, 42213.07192354373))", "VB": "Module Module1\n\n Function Delta_Bearing(b1 As Decimal, b2 As Decimal) As Decimal\n Dim d As Decimal = 0\n\n ' Convert bearing to W.C.B\n While b1 < 0\n b1 += 360\n End While\n While b1 > 360\n b1 -= 360\n End While\n\n While b2 < 0\n b2 += 360\n End While\n While b2 > 0\n b2 -= 360\n End While\n\n ' Calculate delta bearing\n d = (b2 - b1) Mod 360\n ' Convert result to Q.B\n If d > 180 Then\n d -= 360\n ElseIf d < -180 Then\n d += 360\n End If\n\n Return d\n End Function\n\n Sub Main()\n ' Calculate standard test cases\n Console.WriteLine(Delta_Bearing(20, 45))\n Console.WriteLine(Delta_Bearing(-45, 45))\n Console.WriteLine(Delta_Bearing(-85, 90))\n Console.WriteLine(Delta_Bearing(-95, 90))\n Console.WriteLine(Delta_Bearing(-45, 125))\n Console.WriteLine(Delta_Bearing(-45, 145))\n Console.WriteLine(Delta_Bearing(29.4803, -88.6381))\n Console.WriteLine(Delta_Bearing(-78.3251, -159.036))\n\n ' Calculate optional test cases\n Console.WriteLine(Delta_Bearing(-70099.742338109383, 29840.674378767231))\n Console.WriteLine(Delta_Bearing(-165313.6666297357, 33693.9894517456))\n Console.WriteLine(Delta_Bearing(1174.8380510598456, -154146.66490124757))\n Console.WriteLine(Delta_Bearing(60175.773067955459, 42213.071923543728))\n End Sub\n\nEnd Module"} +{"id": 41, "output": "The first 15 items In the Stern-Brocot sequence: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4\n\nThe locations of where the selected numbers (1-to-10, & 100) first appear:\n 1: 1\n 2: 3\n 3: 5\n 4: 9\n 5: 11\n 6: 33\n 7: 19\n 8: 21\n 9: 35\n 10: 39\n100: 1,179\n\nThe greatest common divisor of all the two consecutive items of the series up to the 1000th item is always one.", "Python": "def stern_brocot(predicate=lambda series: len(series) < 20):\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 # The following would be much faster. Note that new values always occur at odd indices\n # len(stern_brocot(lambda series: n_occur != series[-2])) - 1)\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'", "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"} +{"id": 42, "output": "Move disk 1 from 1 to 3\nMove disk 2 from 1 to 2\nMove disk 1 from 3 to 2\nMove disk 3 from 1 to 3\nMove disk 1 from 2 to 1\nMove disk 2 from 2 to 3\nMove disk 1 from 1 to 3\nMove disk 4 from 1 to 2\nMove disk 1 from 3 to 2\nMove disk 2 from 3 to 1\nMove disk 1 from 2 to 1\nMove disk 3 from 3 to 2\nMove disk 1 from 1 to 3\nMove disk 2 from 1 to 2\nMove disk 1 from 3 to 2", "Python": "def hanoi(ndisks, startPeg=1, endPeg=3):\n if ndisks:\n hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)\n print(f\"Move disk {ndisks} from peg {startPeg} to peg {endPeg}\")\n hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)\n \nhanoi(4)", "VB": "Module TowersOfHanoi\n Sub MoveTowerDisks(ByVal disks As Integer, ByVal fromTower As Integer, ByVal toTower As Integer, ByVal viaTower As Integer)\n If disks > 0 Then\n MoveTowerDisks(disks - 1, fromTower, viaTower, toTower)\n System.Console.WriteLine(\"Move disk {0} from {1} to {2}\", disks, fromTower, toTower)\n MoveTowerDisks(disks - 1, viaTower, toTower, fromTower)\n End If\n End Sub\n\n Sub Main()\n MoveTowerDisks(4, 1, 2, 3)\n End Sub\nEnd Module"} +{"id": 43, "output": "True", "Python": "def is_palindrome(s):\n return s == s[::-1]", "VB": "Module Module1\n\n Function IsPalindrome(p As String) As Boolean\n Dim temp = p.ToLower().Replace(\" \", \"\")\n Return StrReverse(temp) = temp\n End Function\n\n Sub Main()\n Console.WriteLine(IsPalindrome(\"In girum imus nocte et consumimur igni\"))\n End Sub\n\nEnd Module"} +{"id": 44, "output": " 1 \n 1 1 \n 1 2 1 \n 1 3 3 1 \n 1 4 6 4 1 \n 1 5 10 10 5 1 \n 1 6 15 20 15 6 1 \n 1 7 21 35 35 21 7 1\n 1 8 28 56 70 56 28 8 1\n 1 9 36 84 126 126 84 36 9 1", "Python": "def scan(op, seq, it):\n a = []\n result = it\n a.append(it)\n for x in seq:\n result = op(result, x)\n a.append(result)\n return a\n\ndef pascal(n):\n def nextrow(row, x):\n return [l+r for l,r in zip(row+[0,],[0,]+row)]\n\n return scan(nextrow, range(n-1), [1,])\n\nfor row in pascal(4):\n print(row)", "VB": "Imports System.Numerics\n\nModule Module1\n Iterator Function GetRow(rowNumber As BigInteger) As IEnumerable(Of BigInteger)\n Dim denominator As BigInteger = 1\n Dim numerator = rowNumber\n\n Dim currentValue As BigInteger = 1\n For counter = 0 To rowNumber\n Yield currentValue\n currentValue = currentValue * numerator\n numerator = numerator - 1\n currentValue = currentValue / denominator\n denominator = denominator + 1\n Next\n End Function\n\n Function GetTriangle(quantityOfRows As Integer) As IEnumerable(Of BigInteger())\n Dim range = Enumerable.Range(0, quantityOfRows).Select(Function(num) New BigInteger(num))\n Return range.Select(Function(num) GetRow(num).ToArray())\n End Function\n\n Function CenterString(text As String, width As Integer)\n Dim spaces = width - text.Length\n Dim padLeft = (spaces / 2) + text.Length\n Return text.PadLeft(padLeft).PadRight(width)\n End Function\n\n Function FormatTriangleString(triangle As IEnumerable(Of BigInteger())) As String\n Dim maxDigitWidth = triangle.Last().Max().ToString().Length\n Dim rows = triangle.Select(Function(arr) String.Join(\" \", arr.Select(Function(array) CenterString(array.ToString(), maxDigitWidth))))\n Dim maxRowWidth = rows.Last().Length\n Return String.Join(Environment.NewLine, rows.Select(Function(row) CenterString(row, maxRowWidth)))\n End Function\n\n Sub Main()\n Dim triangle = GetTriangle(20)\n Dim output = FormatTriangleString(triangle)\n Console.WriteLine(output)\n End Sub\n\nEnd Module"} +{"id": 45, "output": "3, 4, 5\n5, 12, 13\n6, 8, 10\n8, 15, 17\n9, 12, 15\n12, 16, 20", "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]", "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"} +{"id": 46, "output": "1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2\n1 3 2 1 4 2 1 3 2 1 4 2 1 3 2 1 4 2 1 3\n1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6\n1 3 5 1 4 3 1 4 5 1 3 4 1 3 5 1 4 3 1 4", "Python": "from itertools import islice\n\nclass INW():\n \"\"\"\n Intersecting Number Wheels\n represented as a dict mapping\n name to tuple of values.\n \"\"\"\n\n def __init__(self, **wheels):\n self._wheels = wheels\n self.isect = {name: self._wstate(name, wheel) \n for name, wheel in wheels.items()}\n \n def _wstate(self, name, wheel):\n \"Wheel state holder\"\n assert all(val in self._wheels for val in wheel if type(val) == str), \\\n f\"ERROR: Interconnected wheel not found in {name}: {wheel}\"\n pos = 0\n ln = len(wheel)\n while True:\n nxt, pos = wheel[pos % ln], pos + 1\n yield next(self.isect[nxt]) if type(nxt) == str else nxt\n \n def __iter__(self):\n base_wheel_name = next(self.isect.__iter__())\n yield from self.isect[base_wheel_name]\n \n def __repr__(self):\n return f\"{self.__class__.__name__}({self._wheels})\"\n \n def __str__(self):\n txt = \"Intersecting Number Wheel group:\"\n for name, wheel in self._wheels.items():\n txt += f\"\\n {name+':':4}\" + ' '.join(str(v) for v in wheel)\n return txt\n\ndef first(iter, n):\n \"Pretty print first few terms\"\n return ' '.join(f\"{nxt}\" for nxt in islice(iter, n))\n\nif __name__ == '__main__':\n for group in[\n {'A': (1, 2, 3)},\n {'A': (1, 'B', 2),\n 'B': (3, 4)},\n {'A': (1, 'D', 'D'),\n 'D': (6, 7, 8)},\n {'A': (1, 'B', 'C'),\n 'B': (3, 4),\n 'C': (5, 'B')}, # 135143145...\n ]:\n w = INW(**group)\n print(f\"{w}\\n Generates:\\n {first(w, 20)} ...\\n\")", "VB": "Module Module1\n\n \n Iterator Function Loopy(Of T)(seq As IEnumerable(Of T)) As IEnumerable(Of T)\n While True\n For Each element In seq\n Yield element\n Next\n End While\n End Function\n\n Iterator Function TurnWheels(ParamArray wheels As (name As Char, values As String)()) As IEnumerable(Of Char)\n Dim data = wheels.ToDictionary(Function(wheel) wheel.name, Function(wheel) wheel.values.Loopy.GetEnumerator)\n Dim primary = data(wheels(0).name)\n\n Dim Turn As Func(Of IEnumerator(Of Char), Char) = Function(sequence As IEnumerator(Of Char))\n sequence.MoveNext()\n Dim c = sequence.Current\n Return If(Char.IsDigit(c), c, Turn(data(c)))\n End Function\n\n While True\n Yield Turn(primary)\n End While\n End Function\n\n \n Sub Print(sequence As IEnumerable(Of Char))\n Console.WriteLine(String.Join(\" \", sequence))\n End Sub\n\n Sub Main()\n TurnWheels((\"A\", \"123\")).Take(20).Print()\n TurnWheels((\"A\", \"1B2\"), (\"B\", \"34\")).Take(20).Print()\n TurnWheels((\"A\", \"1DD\"), (\"D\", \"678\")).Take(20).Print()\n TurnWheels((\"A\", \"1BC\"), (\"B\", \"34\"), (\"C\", \"5B\")).Take(20).Print()\n End Sub\n\nEnd Module"} +{"id": 47, "output": "The first 15 terms of the Recam\u00e1n sequence are: (0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9)\nThe first duplicated term is a(24) = 42\nTerms up to a(328002) are needed to generate 0 to 1000", "Python": "from itertools import islice\n\nclass Recamans():\n \"Recam\u00e1n's sequence generator callable class\"\n def __init__(self):\n self.a = None # Set of results so far\n self.n = None # n'th term (counting from zero)\n \n def __call__(self):\n \"Recam\u00e1n'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)) # The target set of numbers to be covered\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", "VB": "Imports System\nImports System.Collections.Generic\n\nModule Module1\n Sub Main(ByVal args As String())\n Dim a As List(Of Integer) = New List(Of Integer)() From { 0 },\n used As HashSet(Of Integer) = New HashSet(Of Integer)() From { 0 },\n used1000 As HashSet(Of Integer) = used.ToHashSet(),\n foundDup As Boolean = False\n For n As Integer = 1 to Integer.MaxValue\n Dim nv As Integer = a(n - 1) - n\n If nv < 1 OrElse used.Contains(nv) Then nv += 2 * n\n Dim alreadyUsed As Boolean = used.Contains(nv) : a.Add(nv)\n If Not alreadyUsed Then used.Add(nv) : If nv > 0 AndAlso nv <= 1000 Then used1000.Add(nv)\n If Not foundDup Then\n If a.Count = 15 Then _\n Console.WriteLine(\"The first 15 terms of the Recam\u00e1n sequence are: ({0})\", String.Join(\", \", a))\n If alreadyUsed Then _\n Console.WriteLine(\"The first duplicated term is a({0}) = {1}\", n, nv) : foundDup = True\n End If\n If used1000.Count = 1001 Then _\n Console.WriteLine(\"Terms up to a({0}) are needed to generate 0 to 1000\", n) : Exit For\n Next\n End Sub\nEnd Module"} +{"id": 48, "output": "Epsilon = 1.110223E-16\n(a + b) + c = 1\nKahan sum = 1", "Python": "from decimal import *\n\ngetcontext().prec = 6\ndef kahansum(input):\n summ = c = 0\n for num in input:\n y = num - c\n t = summ + y\n c = (t - summ) - y\n summ = t\n return summ\n\na, b, c = [Decimal(n) for n in '10000.0 3.14159 2.71828'.split()]\n\n(a + b) + c\nkahansum([a, b, c])\n\nsum([a, b, c])\n\n\ngetcontext()\nContext(prec=6, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])\n\n\ngetcontext().prec = 20\n(a + b) + c\n", "VB": "Module Module1\n\n Function KahanSum(ParamArray fa As Single()) As Single\n Dim sum = 0.0F\n Dim c = 0.0F\n For Each f In fa\n Dim y = f - c\n Dim t = sum + y\n c = (t - sum) - y\n sum = t\n Next\n Return sum\n End Function\n\n Function Epsilon() As Single\n Dim eps = 1.0F\n While 1.0F + eps <> 1.0F\n eps /= 2.0F\n End While\n Return eps\n End Function\n\n Sub Main()\n Dim a = 1.0F\n Dim b = Epsilon()\n Dim c = -b\n Console.WriteLine(\"Epsilon = {0}\", b)\n Console.WriteLine(\"(a + b) + c = {0}\", (a + b) + c)\n Console.WriteLine(\"Kahan sum = {0}\", KahanSum(a, b, c))\n End Sub\n\nEnd Module"} +{"id": 49, "output": "Given a polygon with vertices [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)],\nits area is 30.", "Python": "from itertools import cycle, islice\nfrom functools import reduce\nfrom operator import sub\n\n# --------- SHOELACE FORMULA FOR POLYGONAL AREA ----------\n\n# shoelaceArea :: [(Float, Float)] -> Float\ndef shoelaceArea(xys):\n '''Area of polygon with vertices\n at (x, y) points in xys.\n '''\n def go(a, tpl):\n l, r = a\n (x, y), (dx, dy) = tpl\n return l + x * dy, r + y * dx\n\n return abs(sub(*reduce(\n go,\n zip(\n xys,\n islice(cycle(xys), 1, None)\n ),\n (0, 0)\n ))) / 2\n\n\n# ------------------------- TEST -------------------------\n# main :: IO()\ndef main():\n '''Sample calculation'''\n\n ps = [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)]\n print(__doc__ + ':')\n print(repr(ps) + ' -> ' + str(shoelaceArea(ps)))\n\n\nif __name__ == '__main__':\n main()", "VB": "Option Strict On\n\nImports Point = System.Tuple(Of Double, Double)\n\nModule Module1\n\n Function ShoelaceArea(v As List(Of Point)) As Double\n Dim n = v.Count\n Dim a = 0.0\n For i = 0 To n - 2\n a += v(i).Item1 * v(i + 1).Item2 - v(i + 1).Item1 * v(i).Item2\n Next\n Return Math.Abs(a + v(n - 1).Item1 * v(0).Item2 - v(0).Item1 * v(n - 1).Item2) / 2.0\n End Function\n\n Sub Main()\n Dim v As New List(Of Point) From {\n New Point(3, 4),\n New Point(5, 11),\n New Point(12, 8),\n New Point(9, 5),\n New Point(5, 6)\n }\n Dim area = ShoelaceArea(v)\n Console.WriteLine(\"Given a polygon with vertices [{0}],\", String.Join(\", \", v))\n Console.WriteLine(\"its area is {0}.\", area)\n End Sub\n\nEnd Module"}