From b8ad75b0b4d105a5be61028ada901076f4fe0e9c Mon Sep 17 00:00:00 2001 From: JJ <35242550+j-james@users.noreply.github.com> Date: Thu, 8 Dec 2022 05:50:13 -0800 Subject: [PATCH] Add Nim language (code) (#3810) j-james --- frontend/static/languages/_groups.json | 1 + frontend/static/languages/_list.json | 1 + frontend/static/languages/code_nim.json | 106 + frontend/static/quotes/code_nim.json | 8477 +++++++++++++++++++++++ 4 files changed, 8585 insertions(+) create mode 100644 frontend/static/languages/code_nim.json create mode 100644 frontend/static/quotes/code_nim.json diff --git a/frontend/static/languages/_groups.json b/frontend/static/languages/_groups.json index 474debe66..88a9d37f6 100644 --- a/frontend/static/languages/_groups.json +++ b/frontend/static/languages/_groups.json @@ -407,6 +407,7 @@ "code_julia", "code_haskell", "code_html", + "code_nim", "code_pascal", "code_java", "code_kotlin", diff --git a/frontend/static/languages/_list.json b/frontend/static/languages/_list.json index c945ae5da..92a70549e 100644 --- a/frontend/static/languages/_list.json +++ b/frontend/static/languages/_list.json @@ -230,6 +230,7 @@ ,"code_julia" ,"code_haskell" ,"code_html" + ,"code_nim" ,"code_pascal" ,"code_java" ,"code_kotlin" diff --git a/frontend/static/languages/code_nim.json b/frontend/static/languages/code_nim.json new file mode 100644 index 000000000..3b13cc002 --- /dev/null +++ b/frontend/static/languages/code_nim.json @@ -0,0 +1,106 @@ +{ + "name": "code_nim", + "leftToRight": true, + "noLazyMode": true, + "words": [ + "addr", + "and", + "as", + "asm", + "bind", + "block", + "break", + "case", + "cast", + "concept", + "const", + "continue", + "converter", + "defer", + "discard", + "distinct", + "div", + "do", + "elif", + "else", + "end", + "enum", + "except", + "export", + "finally", + "for", + "from", + "func", + "if", + "import", + "in", + "include", + "interface", + "is", + "isnot", + "iterator", + "let", + "macro", + "method", + "mixin", + "mod", + "nil", + "not", + "notin", + "object", + "of", + "or", + "out", + "proc", + "ptr", + "raise", + "ref", + "return", + "shl", + "shr", + "static", + "template", + "try", + "tuple", + "type", + "using", + "var", + "when", + "while", + "xor", + "yield", + "bool", + "int", + "char", + "string", + ">", + "<", + ">=", + "<=", + "=", + "==", + "+", + "-", + "*", + "/", + "^", + "~", + "&", + "!", + "$", + "%", + "?", + ":", + "|", + ".", + "..", + "..<", + "#", + "=>", + "->", + "~>", + "+=", + "-=", + "&=" + ] +} diff --git a/frontend/static/quotes/code_nim.json b/frontend/static/quotes/code_nim.json new file mode 100644 index 000000000..9fc398934 --- /dev/null +++ b/frontend/static/quotes/code_nim.json @@ -0,0 +1,8477 @@ +{ + "language": "code_nim", + "groups": [ + [0, 100], + [101, 300], + [301, 600], + [601, 9999] + ], + "quotes": [ + { + "id": 1, + "length": 45, + "source": "Rosetta Code", + "text": "import os\n\"input.txt\".copyfile(\"output.txt\")\n" + }, + { + "id": 2, + "length": 57, + "source": "Rosetta Code", + "text": "let x = readFile(\"input.txt\")\nwriteFile(\"output.txt\", x)\n" + }, + { + "id": 3, + "length": 54, + "source": "Rosetta Code", + "text": "echo(\"Hello world!\")\nstdout.writeLine(\"Hello world!\")\n" + }, + { + "id": 4, + "length": 70, + "source": "Rosetta Code", + "text": "var j: set[char]\nj.incl('X')\n\nvar k = {'a'..'z', '0'..'9'}\n\nj = j + k\n" + }, + { + "id": 5, + "length": 109, + "source": "Rosetta Code", + "text": "import sequtils\nvar arr = @[1, 2, 3, 4]\narr.apply proc(some: var int) = echo(some, \" squared = \", some*some)\n" + }, + { + "id": 6, + "length": 62, + "source": "Rosetta Code", + "text": "import os\n\nfor file in walkFiles \"/foo/bar/*.mp3\":\n\techo file\n" + }, + { + "id": 7, + "length": 107, + "source": "Rosetta Code", + "text": "type Foo = ref object\n\tx, y: float\n\nvar f: Foo\nnew f\n\necho f[]\necho f[].x\n\nf[].y = 12\necho f.y\n\nf.x = 13.5\n" + }, + { + "id": 8, + "length": 44, + "source": "Rosetta Code", + "text": "var x = 3\nvar p = addr x\n\necho p[]\np[] = 42\n" + }, + { + "id": 9, + "length": 30, + "source": "Rosetta Code", + "text": "var y = 12\np = addr y\np = nil\n" + }, + { + "id": 10, + "length": 71, + "source": "Rosetta Code", + "text": "if x == 0:\n\tfoo()\nelif x == 1:\n\tbar()\nelif x == 2:\n\tbaz()\nelse:\n\tboz()\n" + }, + { + "id": 11, + "length": 86, + "source": "Rosetta Code", + "text": "block outer:\n\tfor i in 0..1000:\n\t\tfor j in 0..1000:\n\t\t\tif i + j == 3:\n\t\t\t\tbreak outer\n" + }, + { + "id": 12, + "length": 99, + "source": "Rosetta Code", + "text": "type SillyError = object of Exception\n\nproc spam() =\n\traise newException(SillyError, \"Some error\")\n" + }, + { + "id": 13, + "length": 83, + "source": "Rosetta Code", + "text": "import os, re\n\nfor file in walkDirRec \"/\":\n\tif file.match re\".*\\.mp3\":\n\t\techo file\n" + }, + { + "id": 14, + "length": 84, + "source": "Rosetta Code", + "text": "import osproc\n\nlet exitCode = execCmd \"ls\"\nlet (output, exitCode2) = execCmdEx \"ls\"\n" + }, + { + "id": 15, + "length": 40, + "source": "Rosetta Code", + "text": "import nativesockets\necho getHostName()\n" + }, + { + "id": 16, + "length": 62, + "source": "Rosetta Code", + "text": "var\n\tc = \"This is a string\"\n\td = c # Copy c into a new string\n" + }, + { + "id": 17, + "length": 50, + "source": "Rosetta Code", + "text": "import strutils\nlet next = $(parseInt(\"123\") + 1)\n" + }, + { + "id": 18, + "length": 88, + "source": "Rosetta Code", + "text": "type Point = tuple[x, y: int]\n\nvar p: Point = (12, 13)\nvar p2: Point = (x: 100, y: 200)\n" + }, + { + "id": 19, + "length": 54, + "source": "Rosetta Code", + "text": "type\n\tMyBitfield = object\n\t\tflag {.bitsize:1.}: cuint\n" + }, + { + "id": 20, + "length": 48, + "source": "Rosetta Code", + "text": "echo \"An int contains \", sizeof(int), \" bytes.\"\n" + }, + { + "id": 21, + "length": 69, + "source": "Rosetta Code", + "text": "import os\necho getFileSize \"input.txt\"\necho getFileSize \"/input.txt\"\n" + }, + { + "id": 22, + "length": 96, + "source": "Rosetta Code", + "text": "import os\nremoveFile(\"input.txt\")\nremoveFile(\"/input.txt\")\nremoveDir(\"docs\")\nremoveDir(\"/docs\")\n" + }, + { + "id": 23, + "length": 81, + "source": "Rosetta Code", + "text": "type\n\tNode[T] = ref TNode[T]\n\n\tTNode[T] = object\n\t\tnext, prev: Node[T]\n\t\tdata: T\n" + }, + { + "id": 24, + "length": 98, + "source": "Rosetta Code", + "text": "import times\n\nvar t = now()\necho(t.format(\"yyyy-MM-dd\"))\necho(t.format(\"dddd',' MMMM d',' yyyy\"))\n" + }, + { + "id": 25, + "length": 11, + "source": "Rosetta Code", + "text": "swap(a, b)\n" + }, + { + "id": 26, + "length": 134, + "source": "Rosetta Code", + "text": "proc multiply(a, b: int): int =\n\tresult = a * b\n\nproc multiply(a, b: int): int =\n\treturn a * b\n\nproc multiply(a, b: int): int = a * b\n" + }, + { + "id": 27, + "length": 117, + "source": "Rosetta Code", + "text": "import algorithm\n\nlet s = @[2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 25, 27, 30]\necho binarySearch(s, 10)\n" + }, + { + "id": 28, + "length": 71, + "source": "Rosetta Code", + "text": "var f = open(r\"C:\\texts\\text.txt\") # a raw string, so ``\\t`` is no tab\n" + }, + { + "id": 29, + "length": 78, + "source": "Rosetta Code", + "text": "import md5\n\necho toMD5(\"The quick brown fox jumped over the lazy dog's back\")\n" + }, + { + "id": 30, + "length": 96, + "source": "Rosetta Code", + "text": "import sequtils\n\nlet\n\txs = [1, 2, 3, 4, 5, 6]\n\tsum = xs.foldl(a + b)\n\tproduct = xs.foldl(a * b)\n" + }, + { + "id": 31, + "length": 19, + "source": "Rosetta Code", + "text": "var f = Inf\necho f\n" + }, + { + "id": 32, + "length": 94, + "source": "Rosetta Code", + "text": "type Singleton = object # Singleton* would export\n\tfoo*: int\n\nvar single* = Singleton(foo: 0)\n" + }, + { + "id": 33, + "length": 50, + "source": "Rosetta Code", + "text": "import singleton\n\nsingle.foo = 12\necho single.foo\n" + }, + { + "id": 34, + "length": 64, + "source": "Rosetta Code", + "text": "import dialogs, gtk2\ngtk2.nim_init()\n\ninfo(nil, \"Hello world!\")\n" + }, + { + "id": 35, + "length": 53, + "source": "Rosetta Code", + "text": "var line = \"\"\nwhile stdin.readLine(line):\n\techo line\n" + }, + { + "id": 36, + "length": 87, + "source": "Rosetta Code", + "text": "import strutils\n\nvar lines = stdin.readAll()\nfor line in lines.split(\"\\n\"):\n\techo line\n" + }, + { + "id": 37, + "length": 90, + "source": "Rosetta Code", + "text": "var file = open(\"input.txt\")\nfor line in file.lines:\n\tdiscard # process line\nfile.close()\n" + }, + { + "id": 38, + "length": 54, + "source": "Rosetta Code", + "text": "var s = 0.0\nfor n in 1..1000: s += 1 / (n * n)\necho s\n" + }, + { + "id": 39, + "length": 25, + "source": "Rosetta Code", + "text": "while true:\n\techo \"SPAM\"\n" + }, + { + "id": 40, + "length": 61, + "source": "Rosetta Code", + "text": "for i in 1..5:\n\tfor j in 1..i:\n\t\tstdout.write(\"*\")\n\techo(\"\")\n" + }, + { + "id": 41, + "length": 53, + "source": "Rosetta Code", + "text": "var n: int = 1024\nwhile n > 0:\n\techo(n)\n\tn = n div 2\n" + }, + { + "id": 42, + "length": 68, + "source": "Rosetta Code", + "text": "let list = [\"lorem\", \"ipsum\", \"dolor\"]\nfor item in list:\n\techo item\n" + }, + { + "id": 43, + "length": 69, + "source": "Rosetta Code", + "text": "var val = 0\nwhile true:\n\tinc val\n\techo val\n\tif val mod 6 == 0: break\n" + }, + { + "id": 44, + "length": 75, + "source": "Rosetta Code", + "text": "var s = \"\"\nfor i in 1..10:\n\ts.add $i\n\tif i == 10: break\n\ts.add \", \"\necho s\n" + }, + { + "id": 45, + "length": 35, + "source": "Rosetta Code", + "text": "for x in countdown(10, 0): echo(x)\n" + }, + { + "id": 46, + "length": 85, + "source": "Rosetta Code", + "text": "if problem1:\n\tquit QuitFailure\n\nif problem2:\n\tquit \"There is a problem\", QuitFailure\n" + }, + { + "id": 47, + "length": 76, + "source": "Rosetta Code", + "text": "for i in 1..10:\n\tif i mod 5 == 0:\n\t\techo i\n\t\tcontinue\n\tstdout.write i, \", \"\n" + }, + { + "id": 48, + "length": 29, + "source": "Rosetta Code", + "text": "echo max([2, 3, 4, 5, 6, 1])\n" + }, + { + "id": 49, + "length": 62, + "source": "Rosetta Code", + "text": "proc print(xs: varargs[string, `$`]) =\n\tfor x in xs:\n\t\techo x\n" + }, + { + "id": 50, + "length": 100, + "source": "Rosetta Code", + "text": "let s: pointer = nil\n\n{.experimental: \"notnil\".}\nlet ns: pointer not nil = nil # Compile time error\n" + }, + { + "id": 51, + "length": 32, + "source": "Rosetta Code", + "text": "import math\nlet i: int = fac(x)\n" + }, + { + "id": 52, + "length": 66, + "source": "Rosetta Code", + "text": "proc factorial(x): int =\n\tif x > 0: x * factorial(x - 1)\n\telse: 1\n" + }, + { + "id": 53, + "length": 72, + "source": "Rosetta Code", + "text": "proc factorial(x: int): int =\n\tresult = 1\n\tfor i in 2..x:\n\t\tresult *= i\n" + }, + { + "id": 54, + "length": 105, + "source": "Rosetta Code", + "text": "import locks\n\nvar mutex: Lock\ninitLock mutex\nacquire mutex\nrelease mutex\n\nlet success = tryAcquire mutex\n" + }, + { + "id": 55, + "length": 93, + "source": "Rosetta Code", + "text": "import httpclient\n\nvar client = newHttpClient()\necho client.getContent \"https://example.org\"\n" + }, + { + "id": 56, + "length": 36, + "source": "Rosetta Code", + "text": "echo cpuEndian\necho sizeof(int) * 8\n" + }, + { + "id": 57, + "length": 42, + "source": "Rosetta Code", + "text": "let str = \"String\"\necho str & \" literal.\"\n" + }, + { + "id": 58, + "length": 86, + "source": "Rosetta Code", + "text": "import strutils\nvar str = \"String\"\necho join([str, \" literal.\", \"HelloWorld!\"], \"~~\")\n" + }, + { + "id": 59, + "length": 30, + "source": "Rosetta Code", + "text": "import os\necho getEnv(\"HOME\")\n" + }, + { + "id": 60, + "length": 61, + "source": "Rosetta Code", + "text": "stderr.writeln \"Hello world!\"\nstdout.write \"Goodbye, World!\"\n" + }, + { + "id": 61, + "length": 98, + "source": "Rosetta Code", + "text": "import strutils\n\nfor i in 0..33:\n\techo toBin(i, 6),\" \",toOct(i, 3),\" \",align($i,2),\" \",toHex(i,2)\n" + }, + { + "id": 62, + "length": 38, + "source": "Rosetta Code", + "text": "var a = 42\nassert(a == 42, \"Not 42!\")\n" + }, + { + "id": 63, + "length": 40, + "source": "Rosetta Code", + "text": "var a = 42\ndoAssert(a == 42, \"Not 42!\")\n" + }, + { + "id": 64, + "length": 98, + "source": "Rosetta Code", + "text": "import httpclient\n\nvar client = newHttpClient()\necho client.getContent(\"https://sourceforge.net\")\n" + }, + { + "id": 65, + "length": 35, + "source": "Rosetta Code", + "text": "for x in countup(1, 10, 4): echo x\n" + }, + { + "id": 66, + "length": 64, + "source": "Rosetta Code", + "text": "var\n\tx = @[1, 2, 3, 4, 5, 6]\n\ty = @[7, 8, 9, 10, 11]\n\tz = x & y\n" + }, + { + "id": 67, + "length": 96, + "source": "Rosetta Code", + "text": "var\n\ta = [1, 2, 3, 4, 5, 6]\n\tb = [7, 8, 9, 10, 11]\n\tc: array[11, int]\n\nc[0..5] = a\nc[6..10] = b\n" + }, + { + "id": 68, + "length": 43, + "source": "Rosetta Code", + "text": "proc stepUp = (while not step(): stepUp())\n" + }, + { + "id": 69, + "length": 66, + "source": "Rosetta Code", + "text": "proc recurse(i: int): int =\n\techo i\n\trecurse(i+1)\necho recurse(0)\n" + }, + { + "id": 70, + "length": 19, + "source": "Rosetta Code", + "text": "readFile(filename)\n" + }, + { + "id": 71, + "length": 11, + "source": "Rosetta Code", + "text": "readAll(f)\n" + }, + { + "id": 72, + "length": 72, + "source": "Rosetta Code", + "text": "var lp = open(\"/dev/lp0\", fmWrite)\nlp.writeln \"Hello world!\"\nlp.close()\n" + }, + { + "id": 73, + "length": 72, + "source": "Rosetta Code", + "text": "import terminal\n\neraseScreen() # puts cursor at down\nsetCursorPos(0, 0)\n" + }, + { + "id": 74, + "length": 48, + "source": "Rosetta Code", + "text": "import terminal\nsetCursorPos(3, 6)\necho \"Hello\"\n" + }, + { + "id": 75, + "length": 97, + "source": "Rosetta Code", + "text": "import terminal\n\nstdout.styledWrite(\"normal \", styleReverse, \"inverse\", resetStyle, \" normal\\n\")\n" + }, + { + "id": 76, + "length": 51, + "source": "Rosetta Code", + "text": "static:\n\techo \"Hello compile time world: \", 2 ^ 10\n" + }, + { + "id": 77, + "length": 17, + "source": "Rosetta Code", + "text": "const x = 2 ^ 10\n" + }, + { + "id": 78, + "length": 84, + "source": "Rosetta Code", + "text": "template log(msg: string) =\n\tif debug:\n\t\techo msg\n\nfor i in 1..10:\n\tlog expensive()\n" + }, + { + "id": 79, + "length": 90, + "source": "Rosetta Code", + "text": "var f = open(\"/dev/urandom\")\nvar r: int32\ndiscard f.readBuffer(addr r, 4)\nclose(f)\necho r\n" + }, + { + "id": 80, + "length": 65, + "source": "Rosetta Code", + "text": "import bigints\n\nvar i = 0.initBigInt\nwhile true:\n\ti += 1\n\techo i\n" + }, + { + "id": 81, + "length": 42, + "source": "Rosetta Code", + "text": "for line in lines \"input.txt\":\n\techo line\n" + }, + { + "id": 82, + "length": 56, + "source": "Rosetta Code", + "text": "import osproc\n\ndiscard execCmd(\"espeak 'Hello world!'\")\n" + }, + { + "id": 83, + "length": 86, + "source": "Rosetta Code", + "text": "block outer:\n\tfor i in 0..1000:\n\t\tfor j in 0..1000:\n\t\t\tif i + j == 3:\n\t\t\t\tbreak outer\n" + }, + { + "id": 84, + "length": 56, + "source": "Rosetta Code", + "text": "func foo(value: int): int =\n\tresult = value\necho foo(5)\n" + }, + { + "id": 85, + "length": 60, + "source": "Rosetta Code", + "text": "import strutils\nfor i in 0 ..< int.high:\n\techo toOct(i, 16)\n" + }, + { + "id": 86, + "length": 51, + "source": "Rosetta Code", + "text": "import strformat\n\nfor n in 0..15:\n\techo fmt\"{n:b}\"\n" + }, + { + "id": 87, + "length": 49, + "source": "Rosetta Code", + "text": "import posix\n\ndiscard truncate(\"filename\", 1024)\n" + }, + { + "id": 88, + "length": 37, + "source": "Rosetta Code", + "text": "deepCopy(newObj, obj)\necho repr(obj)\n" + }, + { + "id": 89, + "length": 75, + "source": "Rosetta Code", + "text": "import random\nrandomize()\n\nlet ls = @[\"foo\", \"bar\", \"baz\"]\necho sample(ls)\n" + }, + { + "id": 90, + "length": 38, + "source": "Rosetta Code", + "text": "var x = @[1, 2, 3]\nadd(x, 4)\nx.add(5)\n" + }, + { + "id": 91, + "length": 82, + "source": "Rosetta Code", + "text": "proc addsub(x, y: int): (int, int) =\n\t(x + y, x - y)\n\nvar (a, b) = addsub(12, 15)\n" + }, + { + "id": 92, + "length": 98, + "source": "Rosetta Code", + "text": "proc addsub(x, y: int; a, b: var int) =\n\ta = x + y\n\tb = x - y\n\nvar a, b: int\naddsub(12, 15, a, b)\n" + }, + { + "id": 93, + "length": 64, + "source": "Rosetta Code", + "text": "import os, base64\nlet source = paramStr(1)\necho source.decode()\n" + }, + { + "id": 94, + "length": 20, + "source": "Rosetta Code", + "text": "echo \"Hello world!\"\n" + }, + { + "id": 95, + "length": 49, + "source": "Rosetta Code", + "text": "import std/sha1\n\necho secureHash(\"Hello world!\")\n" + }, + { + "id": 96, + "length": 93, + "source": "Rosetta Code", + "text": "import terminal\n\necho if stdin.isatty: \"stdin is a terminal\" else: \"stdin is not a terminal\"\n" + }, + { + "id": 97, + "length": 64, + "source": "Rosetta Code", + "text": "var t = open(\"/dev/tape\", fmWrite)\nt.writeln \"Hi Tape!\"\nt.close\n" + }, + { + "id": 98, + "length": 53, + "source": "Rosetta Code", + "text": "import nimcrypto\n\necho sha256.digest(\"Hello world!\")\n" + }, + { + "id": 99, + "length": 37, + "source": "Rosetta Code", + "text": "for _ in 1..10:\n\techo \"Hello world!\"\n" + }, + { + "id": 100, + "length": 96, + "source": "Rosetta Code", + "text": "import sequtils\nlet x = [1, 2, 3, 4, 5]\nlet y = x.mapIt(it * it)\nassert y == @[1, 4, 9, 16, 25]\n" + }, + { + "id": 101, + "length": 84, + "source": "Rosetta Code", + "text": "proc addN[T](n: T): auto = (proc(x: T): T = x + n)\n\nlet add2 = addN(2)\necho add2(7)\n" + }, + { + "id": 102, + "length": 90, + "source": "Rosetta Code", + "text": "import sugar\n\nproc addM[T](n: T): auto = (x: T) => x + n\n\nlet add3 = addM(3)\necho add3(7)\n" + }, + { + "id": 103, + "length": 65, + "source": "Rosetta Code", + "text": "import math\n\nfunc isqrt(n: Natural): int =\n\tint(sqrt(n.toFloat))\n" + }, + { + "id": 104, + "length": 85, + "source": "Rosetta Code", + "text": "let fruit = [\"apple\", \"orange\"]\necho \"The length of the fruit array is \", len(fruit)\n" + }, + { + "id": 105, + "length": 49, + "source": "Rosetta Code", + "text": "writeFile(\"filename.txt\", \"An arbitrary string\")\n" + }, + { + "id": 106, + "length": 70, + "source": "Rosetta Code", + "text": "type Foo = object\n\nproc bar(f: Foo) =\n\techo \"bar\"\n\nvar f: Foo\nf.bar()\n" + }, + { + "id": 107, + "length": 81, + "source": "Rosetta Code", + "text": "import math, complex\n\necho \"exp(ipi) + 1 = \", exp(complex(0.0, PI)) + 1, \" ~= 0\"\n" + }, + { + "id": 108, + "length": 192, + "source": "Rosetta Code", + "text": "when defined(debug):\n\techo \"Debugging info: $1 $2 $3\".format(x, y, z)\n\nwhen not defined(release):\n\techo \"Debugging info: \", x, \" \", y, \" \", z\n\ndebug \"Debugging info: $1 $2 $3\".format(x, y, z)\n" + }, + { + "id": 109, + "length": 98, + "source": "Rosetta Code", + "text": "import algorithm\n\nlet list = @[1, 2, 3, 4, 5, 6, 7, 8, 9]\necho list, \" -> \", rotatedLeft(list, 3)\n" + }, + { + "id": 110, + "length": 74, + "source": "Rosetta Code", + "text": "type T = object\n\tcase i: 0..2\n\tof 0: value: int\n\tof 1: discard\n\tof 2: nil\n" + }, + { + "id": 111, + "length": 73, + "source": "Rosetta Code", + "text": "type\n\tPathComponent = enum\n\t\tpcDir\n\t\tpcLinkToDir\n\t\tpcFile\n\t\tpcLinkToFile\n" + }, + { + "id": 112, + "length": 74, + "source": "Rosetta Code", + "text": "type\n\tPathComponent {.pure.} = enum\n\t\tDir\n\t\tLinkToDir\n\t\tFile\n\t\tLinkToFile\n" + }, + { + "id": 113, + "length": 122, + "source": "Rosetta Code", + "text": "var\n\ti = open(\"input.txt\")\n\to = open(\"output.txt\", fmWrite)\n\nfor line in i.lines:\n\to.writeLine(line)\n\ni.close()\no.close()\n" + }, + { + "id": 114, + "length": 204, + "source": "Rosetta Code", + "text": "const size = 4096\n\nvar\n\ti = open(\"input.txt\")\n\to = open(\"output.txt\", fmWrite)\n\tbuf: array[size, char]\n\nwhile i.readBuffer(buf.addr, size) > 0:\n\tdiscard o.writeBuffer(buf.addr, size)\n\ni.close()\no.close()\n" + }, + { + "id": 115, + "length": 184, + "source": "Rosetta Code", + "text": "import memfiles\n\nvar\n\ti = memfiles.open(\"input.txt\")\n\to = system.open(\"output.txt\", fmWrite)\n\nvar written = o.writeBuffer(i.mem, i.size)\nassert(written == i.size)\n\ni.close()\no.close()\n" + }, + { + "id": 116, + "length": 258, + "source": "Rosetta Code", + "text": "import glut\n\nvar win: int = 0\n\nproc myOnKeyPress(c: int8, v1, v2: cint) {.cdecl.} =\n\t echo(c)\n\t if c == 27:\n\t\t\tglutDestroyWindow(win)\n\nglutInit()\nwin = glutCreateWindow(\"Goodbye, World!\")\nglutKeyboardFunc(TGlut1Char2IntCallback(myOnKeyPress))\nglutMainLoop()\n" + }, + { + "id": 117, + "length": 277, + "source": "Rosetta Code", + "text": "import strutils\n\nproc isNumeric(s: string): bool =\n\ttry:\n\t\tdiscard s.parseFloat()\n\t\tresult = true\n\texcept ValueError:\n\t\tresult = false\n\nconst Strings = [\"1\", \"3.14\", \"-100\", \"1e2\", \"Inf\", \"rose\"]\n\nfor s in Strings:\n\techo s, \" is \", if s.isNumeric(): \"\" else: \"not \", \"numeric\"\n" + }, + { + "id": 118, + "length": 235, + "source": "Rosetta Code", + "text": "import parseutils\n\nproc isNumeric(s: string): bool =\n\tvar x: float\n\ts.parseFloat(x) == s.len\n\nconst Strings = [\"1\", \"3.14\", \"-100\", \"1e2\", \"Inf\", \"rose\"]\n\nfor s in Strings:\n\techo s, \" is \", if s.isNumeric(): \"\" else: \"not \", \"numeric\"\n" + }, + { + "id": 119, + "length": 265, + "source": "Rosetta Code", + "text": "proc bubbleSort[T](a: var openarray[T]) =\n\tvar t = true\n\tfor n in countdown(a.len-2, 0):\n\t\tif not t: break\n\t\tt = false\n\t\tfor j in 0..n:\n\t\t\tif a[j] <= a[j+1]: continue\n\t\t\tswap a[j], a[j+1]\n\t\t\tt = true\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nbubbleSort a\necho a\n" + }, + { + "id": 120, + "length": 149, + "source": "Rosetta Code", + "text": "var a = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nvar b: array[128, int]\nb[9] = 10\nb[0..8] = a\nvar c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3]\nc['b'] = 10000\n" + }, + { + "id": 121, + "length": 166, + "source": "Rosetta Code", + "text": "var d = @[1, 2, 3, 5, 6, 7, 8, 9]\nd.add(10)\nd.add([11, 12, 13, 14])\nd[0] = 0\n\nvar e: seq[float] = @[]\ne.add(15.5)\n\nvar f = newSeq[string]()\nf.add(\"foo\")\nf.add(\"bar\")\n" + }, + { + "id": 122, + "length": 147, + "source": "Rosetta Code", + "text": "var g = (13, 13, 14)\ng[0] = 12\n\nvar h: tuple[key: string, val: int] = (\"foo\", 100)\n\n# A sequence of key-val tuples:\nvar i = {\"foo\": 12, \"bar\": 13}\n" + }, + { + "id": 123, + "length": 129, + "source": "Rosetta Code", + "text": "import tables\nvar l = initTable[string, int]()\nl[\"foo\"] = 12\nl[\"bar\"] = 13\n\nvar m = {\"foo\": 12, \"bar\": 13}.toTable\nm[\"baz\"] = 14\n" + }, + { + "id": 124, + "length": 106, + "source": "Rosetta Code", + "text": "import sets\nvar n = initSet[string]()\nn.incl(\"foo\")\n\nvar o = [\"foo\", \"bar\", \"baz\"].toSet\no.incl(\"foobar\")\n" + }, + { + "id": 125, + "length": 103, + "source": "Rosetta Code", + "text": "import deques\nvar p = initDeque[int]()\np.addLast(12)\np.addFirst(13)\necho p.popFirst()\necho p.popLast()\n" + }, + { + "id": 126, + "length": 114, + "source": "Rosetta Code", + "text": "import tables, sequtils\n\nlet keys = @['a','b','c']\nlet values = @[1, 2, 3]\n\nlet table = toTable zip(keys, values)\n" + }, + { + "id": 127, + "length": 140, + "source": "Rosetta Code", + "text": "import re\n\nvar s = \"This is a string\"\n\nif s.find(re\"string$\") > -1:\n\techo \"Ends with string.\"\n\ns = s.replace(re\"\\ a\\ \", \" another \")\necho s\n" + }, + { + "id": 128, + "length": 104, + "source": "Rosetta Code", + "text": "proc first(fn: proc): auto =\n\treturn fn()\n\nproc second(): string =\n\treturn \"second\"\n\necho first(second)\n" + }, + { + "id": 129, + "length": 268, + "source": "Rosetta Code", + "text": "proc hanoi(disks: int; fromTower, toTower, viaTower: string) =\n\tif disks != 0:\n\t\thanoi(disks - 1, fromTower, viaTower, toTower)\n\t\techo(\"Move disk \", disks, \" from \", fromTower, \" to \", toTower)\n\t\thanoi(disks - 1, viaTower, toTower, fromTower)\n\nhanoi(4, \"1\", \"2\", \"3\")\n" + }, + { + "id": 130, + "length": 106, + "source": "Rosetta Code", + "text": "case x\nof 0:\n\tfoo()\nof 2, 5, 9:\n\tbaz()\nof 10..20, 40..50:\n\tbaz()\nelse: # All cases must be covered\n\tboz()\n" + }, + { + "id": 131, + "length": 111, + "source": "Rosetta Code", + "text": "var f = open \"input.txt\"\ntry:\n\tvar s = readLine f\nexcept IOError:\n\techo \"An error occurred!\"\nfinally:\n\tclose f\n" + }, + { + "id": 132, + "length": 159, + "source": "Rosetta Code", + "text": "try:\n\tspam()\nexcept SillyError:\n\techo \"Got SillyError with message: \", getCurrentExceptionMsg()\nexcept:\n\techo \"Got another exception\"\nfinally:\n\techo \"Finally\"\n" + }, + { + "id": 133, + "length": 110, + "source": "Rosetta Code", + "text": "import algorithm\n\nvar a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]\na.sort(Ascending)\nfor x in a:\n\techo x\n" + }, + { + "id": 134, + "length": 230, + "source": "Rosetta Code", + "text": "import strutils, algorithm\n\nvar strings = \"Here are some sample strings to be sorted\".split(' ')\n\nstrings.sort(proc (x, y: string): int =\n\tresult = cmp(y.len, x.len)\n\tif result == 0:\n\t\tresult = cmpIgnoreCase(x, y)\n)\n\necho strings\n" + }, + { + "id": 135, + "length": 105, + "source": "Rosetta Code", + "text": "import strutils\n\nlet text = \"Hello,How,Are,You,Today\"\nlet tokens = text.split(',')\necho tokens.join(\".\")\n" + }, + { + "id": 136, + "length": 188, + "source": "Rosetta Code", + "text": "const str = [\"Hello\", \"world\", \"!\"]\n\nvar thr: array[3, Thread[int32]]\n\nproc f(i:int32) {.thread.} =\n\techo str[i]\n\nfor i in 0..thr.high:\n\tcreateThread(thr[i], f, int32(i))\njoinThreads(thr)\n" + }, + { + "id": 137, + "length": 138, + "source": "Rosetta Code", + "text": "import threadpool\nconst str = [\"Hello\", \"world\", \"!\"]\n\nproc f(i: int) {.thread.} =\n\techo str[i]\n\nfor i in 0..str.high:\n\tspawn f(i)\nsync()\n" + }, + { + "id": 138, + "length": 249, + "source": "Rosetta Code", + "text": "import posix\n\nvar pid = fork()\nif pid < 0:\n\t\techo \"Error forking a child\"\nelif pid > 0:\n\t\techo \"This is the parent process and its child has id \", pid, '.'\n\t\t# Further parent stuff.\nelse:\n\t\techo \"This is the child process.\"\n\t\t# Further child stuff.\n" + }, + { + "id": 139, + "length": 265, + "source": "Rosetta Code", + "text": "import strutils\n\nvar s: string = \"alphaBETA_123\"\necho s, \" as upper case: \", toUpperAscii(s)\necho s, \" as lower case: \", toLowerAscii(s)\necho s, \" as capitalized: \", capitalizeAscii(s)\necho s, \" as normal case: \", normalize(s) # to lower case without underscores.\n" + }, + { + "id": 140, + "length": 120, + "source": "Rosetta Code", + "text": "import strformat\nconst r = 7.125\necho r\necho fmt\"{-r:9.3f}\"\necho fmt\"{r:9.3f}\"\necho fmt\"{-r:09.3f}\"\necho fmt\"{r:09.3f}\"\n" + }, + { + "id": 141, + "length": 110, + "source": "Rosetta Code", + "text": "import os\necho \"program name: \", getAppFilename()\necho \"Arguments:\"\nfor arg in commandLineParams():\n\techo arg\n" + }, + { + "id": 142, + "length": 139, + "source": "Rosetta Code", + "text": "var x = 12\nvar xptr = addr(x) # Get address of variable\necho cast[int](xptr) # and print it\nxptr = cast[ptr int](0xFFFE) # Set the address\n" + }, + { + "id": 143, + "length": 269, + "source": "Rosetta Code", + "text": "type Node[T] = ref object\n\tnext: Node[T]\n\tdata: T\n\nproc newNode[T](data: T): Node[T] =\n\tNode[T](data: data)\n\nvar a = newNode 12\nvar b = newNode 13\nvar c = newNode 14\n\nproc insertAppend(a, n: var Node) =\n\tn.next = a.next\n\ta.next = n\n\na.insertAppend(b)\nb.insertAppend(c)\n" + }, + { + "id": 144, + "length": 252, + "source": "Rosetta Code", + "text": "import rdstdin, strutils\nvar a = parseInt(readLineFromStdin \"Enter value of a: \")\nvar b = parseInt(readLineFromStdin \"Enter value of b: \")\n\nif a < b:\n\techo \"a is less than b\"\nelif a > b:\n\techo \"a is greater than b\"\nelif a == b:\n\techo \"a is equal to b\"\n" + }, + { + "id": 145, + "length": 192, + "source": "Rosetta Code", + "text": "import random, stats, strformat\n\nvar rs: RunningStat\n\nrandomize()\n\nfor _ in 1..5:\n\tfor _ in 1..1000: rs.push gauss(1.0, 0.5)\n\techo &\"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}\"\n" + }, + { + "id": 146, + "length": 113, + "source": "Rosetta Code", + "text": "import os\n\necho fileExists \"input.txt\"\necho fileExists \"/input.txt\"\necho dirExists \"docs\"\necho dirExists \"/docs\"\n" + }, + { + "id": 147, + "length": 138, + "source": "Rosetta Code", + "text": "import os\n\nopen(\"output.txt\", fmWrite).close()\ncreateDir(\"docs\")\n\nopen(DirSep & \"output.txt\", fmWrite).close()\ncreateDir(DirSep & \"docs\")\n" + }, + { + "id": 148, + "length": 152, + "source": "Rosetta Code", + "text": "import os\nconst directories = [\"/\", \"./\"]\nfor directory in directories:\n\topen(directory & \"output.txt\", fmWrite).close()\n\tcreateDir(directory & \"docs\")\n" + }, + { + "id": 149, + "length": 174, + "source": "Rosetta Code", + "text": "import os\n\nmoveFile(\"input.txt\", \"output.txt\")\nmoveFile(\"docs\", \"mydocs\")\n\nmoveFile(DirSep & \"input.txt\", DirSep & \"output.txt\")\nmoveFile(DirSep & \"docs\", DirSep & \"mydocs\")\n" + }, + { + "id": 150, + "length": 282, + "source": "Rosetta Code", + "text": "import httpclient, base64\n\nconst\n\tUser = \"admin\"\n\tPassword = \"admin\"\n\nlet headers = newHttpHeaders({\"Authorization\": \"Basic \" & base64.encode(User & \":\" & Password)})\nlet client = newHttpClient(headers = headers)\necho client.getContent(\"https://httpbin.org/basic-auth/admin/admin\")\n" + }, + { + "id": 151, + "length": 211, + "source": "Rosetta Code", + "text": "proc maxsum(s: openArray[int]): int =\n\tvar maxendinghere = 0\n\tfor x in s:\n\t\tmaxendinghere = max(maxendinghere + x, 0)\n\t\tresult = max(result, maxendinghere)\n\necho maxsum(@[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1])\n" + }, + { + "id": 152, + "length": 139, + "source": "Rosetta Code", + "text": "proc insertAfter[T](l: var List[T], r, n: Node[T]) =\n\tn.prev = r\n\tn.next = r.next\n\tn.next.prev = n\n\tr.next = n\n\tif r == l.tail: l.tail = n\n" + }, + { + "id": 153, + "length": 125, + "source": "Rosetta Code", + "text": "import algorithm, sugar\n\nvar people = @{\"joe\": 120, \"foo\": 31, \"bar\": 51}\nsort(people, (x,y) => cmp(x[0], y[0]))\necho people\n" + }, + { + "id": 154, + "length": 294, + "source": "Rosetta Code", + "text": "{.experimental: \"dotOperators\".}\nimport json\n\ntemplate `.=`(js: JsonNode, field: untyped, value: untyped) =\n\tjs[astToStr(field)] = %value\ntemplate `.`(js: JsonNode, field: untyped): JsonNode =\n\tjs[astToStr(field)]\n\nvar obj = newJObject()\nobj.foo = \"bar\"\necho(obj.foo)\nobj.key = 3\necho(obj.key)\n" + }, + { + "id": 155, + "length": 234, + "source": "Rosetta Code", + "text": "import sequtils,sugar\n\nfunc sorted[T](xs:seq[T]): seq[T] =\n\tif xs.len==0: @[] else: concat(\n\t\txs[1..^1].filter(x=>xx>=xs[0]).sorted\n\t)\n\n@[4, 65, 2, -31, 0, 99, 2, 83, 782].sorted.echo\n" + }, + { + "id": 156, + "length": 142, + "source": "Rosetta Code", + "text": "for i in 1..100:\n\tif i mod 15 == 0:\n\t\techo(\"FizzBuzz\")\n\telif i mod 3 == 0:\n\t\techo(\"Fizz\")\n\telif i mod 5 == 0:\n\t\techo(\"Buzz\")\n\telse:\n\t\techo(i)\n" + }, + { + "id": 157, + "length": 173, + "source": "Rosetta Code", + "text": "var messages = @[\"\", \"Fizz\", \"Buzz\", \"FizzBuzz\"]\nvar acc = 810092048\nfor i in 1..100:\n\tvar c = acc and 3\n\techo(if c == 0: $i else: messages[c])\n\tacc = acc shr 2 or c shl 28\n" + }, + { + "id": 158, + "length": 283, + "source": "Rosetta Code", + "text": "from strutils import `%`\n\nconst numDoors = 100\nvar doors: array[1..numDoors, bool]\n\nfor pass in 1..numDoors:\n\tfor door in countup(pass, numDoors, pass):\n\t\tdoors[door] = not doors[door]\n\nfor door in 1..numDoors:\n\techo \"Door $1 is $2.\" % [$door, if doors[door]: \"open\" else: \"closed\"]\n" + }, + { + "id": 159, + "length": 227, + "source": "Rosetta Code", + "text": "import std/[os, tempfiles]\n\nlet (file, path) = createTempFile(prefix = \"\", suffix = \"\")\necho path, \" created.\"\nfile.writeLine(\"This is a secure temporary file.\")\nfile.close()\nfor line in path.lines:\n\techo line\nremoveFile(path)\n" + }, + { + "id": 160, + "length": 166, + "source": "Rosetta Code", + "text": "import sugar, math\n\nlet n = 20\nlet triplets = collect(newSeq):\n\tfor x in 1..n:\n\t\tfor y in x..n:\n\t\t\tfor z in y..n:\n\t\t\t\tif x^2 + y^2 == z^2:\n\t\t\t\t\t(x,y,z)\necho triplets\n" + }, + { + "id": 161, + "length": 225, + "source": "Rosetta Code", + "text": "proc binarySearch[T](a: openArray[T], key: T): int =\n\tvar b = len(a)\n\twhile result < b:\n\t\tvar mid = (result + b) div 2\n\t\tif a[mid] < key: result = mid + 1\n\t\telse: b = mid\n\tif result >= len(a) or a[result] != key: result = -1\n" + }, + { + "id": 162, + "length": 118, + "source": "Rosetta Code", + "text": "var x = \"var x = echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. ^1]\"\necho x[0..7],chr(34),x,chr(34),chr(10),x[8 .. ^1]\n" + }, + { + "id": 163, + "length": 123, + "source": "Rosetta Code", + "text": "import strutils; let a = \"import strutils; let a = $#; echo a % (chr(34) & a & chr(34))\"; echo a % (chr(34) & a & chr(34))\n" + }, + { + "id": 164, + "length": 249, + "source": "Rosetta Code", + "text": "const x = \"const x = |const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. ^1]|static: echo y|echo y\"\nconst y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. ^1]\nstatic: echo y\necho y\n" + }, + { + "id": 165, + "length": 236, + "source": "Rosetta Code", + "text": "proc insertSort[T](a: var openarray[T]) =\n\tfor i in 1 .. a.high:\n\t\tlet value = a[i]\n\t\tvar j = i\n\t\twhile j > 0 and value < a[j-1]:\n\t\t\ta[j] = a[j-1]\n\t\t\tdec j\n\t\ta[j] = value\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\ninsertSort a\necho a\n" + }, + { + "id": 166, + "length": 117, + "source": "Rosetta Code", + "text": "var c = 'c'\nvar s = \"foobar\"\nvar l = \"\"\"foobar\nand even\nmore test here\"\"\"\n\nvar f = r\"C:\\texts\\text.txt\" # Raw string\n" + }, + { + "id": 167, + "length": 127, + "source": "Rosetta Code", + "text": "proc logic(a, b: bool) =\n\techo \"a and b: \", a and b\n\techo \"a or b: \", a or b\n\techo \"not a: \", not a\n\techo \"a xor b: \", a xor b\n" + }, + { + "id": 168, + "length": 176, + "source": "Rosetta Code", + "text": "proc bitwise(a, b) =\n\techo \"a and b: \" , a and b\n\techo \"a or b: \", a or b\n\techo \"a xor b: \", a xor b\n\techo \"not a: \", not a\n\techo \"a << b: \", a shl b\n\techo \"a >> b: \", a shr b\n" + }, + { + "id": 169, + "length": 192, + "source": "Rosetta Code", + "text": "import json\n\nvar data = parseJson(\"\"\"{ \"foo\": 1, \"bar\": [10, \"apples\"] }\"\"\")\necho data[\"foo\"]\necho data[\"bar\"]\n\nvar js = %* [{\"name\": \"John\", \"age\": 30}, {\"name\": \"Susan\", \"age\": 31}]\necho js\n" + }, + { + "id": 170, + "length": 105, + "source": "Rosetta Code", + "text": "import net\n\nvar s = newSocket()\ns.connect(\"localhost\", Port(256))\ns.send(\"Hello Socket World\")\ns.close()\n" + }, + { + "id": 171, + "length": 100, + "source": "Rosetta Code", + "text": "var xs = [1, 2, 3, 4, 5, 6]\nvar sum, product: int\nproduct = 1\n\nfor x in xs:\n\tsum += x\n\tproduct *= x\n" + }, + { + "id": 172, + "length": 111, + "source": "Rosetta Code", + "text": "import math\n\nlet numbers = [1, 5, 4]\nlet total = sum(numbers)\n\nvar product = 1\nfor n in numbers:\n\tproduct *= n\n" + }, + { + "id": 173, + "length": 160, + "source": "Rosetta Code", + "text": "import os, strutils\n\necho \"Enter how long I should sleep (in milliseconds):\"\nvar timed = stdin.readLine.parseInt()\necho \"Sleeping...\"\nsleep timed\necho \"Awake!\"\n" + }, + { + "id": 174, + "length": 216, + "source": "Rosetta Code", + "text": "import math, sequtils\n\nproc sumSquares[T: SomeNumber](a: openArray[T]): T =\n\ta.mapIt(it * it).sum()\n\nlet a1 = [1, 2, 3, 4, 5]\necho a1, \" -> \", sumSquares(a1)\n\nlet a2: seq[float] = @[]\necho a2, \" -> \", sumSquares(a2)\n" + }, + { + "id": 175, + "length": 280, + "source": "Rosetta Code", + "text": "import strutils\n\nproc mean(xs: openArray[float]): float =\n\tfor x in xs:\n\t\tresult += x\n\tresult = result / float(xs.len)\n\nvar v = @[1.0, 2.0, 2.718, 3.0, 3.142]\nfor i in 0..5:\n\techo \"mean of first \", v.len, \" = \", formatFloat(mean(v), precision = 0)\n\tif v.len > 0: v.setLen(v.high)\n" + }, + { + "id": 176, + "length": 258, + "source": "Rosetta Code", + "text": "func gcd_recursive*(u, v: SomeSignedInt): int64 =\n\t\tif u mod v != 0:\n\t\t\t\tresult = gcd_recursive(v, u mod v)\n\t\telse:\n\t\t\t\tresult = abs(v)\n\nwhen isMainModule:\n\timport strformat\n\tlet (x, y) = (49865, 69811)\n\techo &\"gcd({x}, {y}) = {gcd_recursive(49865, 69811)}\"\n" + }, + { + "id": 177, + "length": 255, + "source": "Rosetta Code", + "text": "func gcd_iterative*(u, v: SomeSignedInt): int64 =\n\tvar u = u\n\tvar v = v\n\twhile v != 0:\n\t\t\tu = u mod v\n\t\t\tswap u, v\n\tresult = abs(u)\n\nwhen isMainModule:\n\timport strformat\n\tlet (x, y) = (49865, 69811)\n\techo &\"gcd({x}, {y}) = {gcd_iterative(49865, 69811)}\")\n" + }, + { + "id": 178, + "length": 225, + "source": "Rosetta Code", + "text": "import sugar\n\nproc a(k: int; x1, x2, x3, x4, x5: proc(): int): int =\n\tvar k = k\n\tproc b(): int =\n\t\tdec k\n\t\ta(k, b, x1, x2, x3, x4)\n\tif k <= 0: x4() + x5()\n\telse: b()\n\necho a(10, () => 1, () => -1, () => -1, () => 1, () => 0)\n" + }, + { + "id": 179, + "length": 259, + "source": "Rosetta Code", + "text": "import times, strutils\n\nproc doWork(x: int) =\n\tvar n = x\n\tfor i in 0..10000000:\n\t\tn += i\n\ntemplate time(statement: untyped): float =\n\tlet t0 = cpuTime()\n\tstatement\n\tcpuTime() - t0\n\necho \"Time = \", time(doWork(100)).formatFloat(ffDecimal, precision = 3), \" s\"\n" + }, + { + "id": 180, + "length": 237, + "source": "Rosetta Code", + "text": "import gnuplot\n\nlet\n\tx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ty = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\nplot(x, y, \"Coordinate pairs\")\ndiscard stdin.readChar # Needed as when the program exits, \"gnuplot\" is closed.\n" + }, + { + "id": 181, + "length": 112, + "source": "Rosetta Code", + "text": "import times\n\necho getDateStr()\necho getClockStr()\necho getTime()\necho now() # shorthand for \"getTime().local\"\n" + }, + { + "id": 182, + "length": 195, + "source": "Rosetta Code", + "text": "{.push overflowChecks: on.}\nproc divCheck(x, y): bool =\n\ttry:\n\t\tdiscard x div y\n\texcept DivByZeroDefect:\n\t\treturn true\n\treturn false\n{.pop.} # Restore default check settings\n\necho divCheck(2, 0)\n" + }, + { + "id": 183, + "length": 174, + "source": "Rosetta Code", + "text": "proc Fibonacci(n: int): int64 =\n\tvar fn = float64(n)\n\tvar p: float64 = (1.0 + sqrt(5.0)) / 2.0\n\tvar q: float64 = 1.0 / p\n\treturn int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))\n" + }, + { + "id": 184, + "length": 136, + "source": "Rosetta Code", + "text": "proc Fibonacci(n: int): int =\n\tvar\n\t\tfirst = 0\n\t\tsecond = 1\n\n\tfor i in 0 .. 0:\n\t\th = h div 2\n\t\tfor i in h ..< a.len:\n\t\t\tlet k = a[i]\n\t\t\tvar j = i\n\t\t\twhile j >= h and k < a[j-h]:\n\t\t\t\ta[j] = a[j-h]\n\t\t\t\tj -= h\n\t\t\ta[j] = k\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nshellSort a\necho a\n" + }, + { + "id": 194, + "length": 108, + "source": "Rosetta Code", + "text": "var p: ptr int\nif p == nil: echo \"it is nil\"\nif p != nil: echo \"it is not nil\"\nif p.isNil: echo \"it is nil\"\n" + }, + { + "id": 195, + "length": 241, + "source": "Rosetta Code", + "text": "import math\n\nproc isPerfect(n: int): bool =\n\tvar sum: int = 1\n\tfor d in 2 .. int(n.toFloat.sqrt):\n\t\tif n mod d == 0:\n\t\t\tinc sum, d\n\t\t\tlet q = n div d\n\t\t\tif q != d: inc sum, q\n\tresult = n == sum\n\nfor n in 2..10_000:\n\tif n.isPerfect:\n\t\techo n\n" + }, + { + "id": 196, + "length": 246, + "source": "Rosetta Code", + "text": "import math, random\n\nrandomize()\n\nproc pi(nthrows: float): float =\n\tvar inside = 0.0\n\tfor i in 1..int64(nthrows):\n\t\tif hypot(rand(1.0), rand(1.0)) < 1:\n\t\t\tinside += 1\n\tresult = 4 * inside / nthrows\n\nfor n in [10e4, 10e6, 10e7, 10e8]:\n\techo pi(n)\n" + }, + { + "id": 197, + "length": 259, + "source": "Rosetta Code", + "text": "let haystack = [\"Zig\",\"Zag\",\"Wally\",\"Ronald\",\"Bush\",\"Krusty\",\"Charlie\",\"Bush\",\"Bozo\"]\n\nfor needle in [\"Bush\", \"Washington\"]:\n\tlet f = haystack.find(needle)\n\tif f >= 0:\n\t\techo f, \" \", needle\n\telse:\n\t\traise newException(ValueError, needle & \" not in haystack\")\n" + }, + { + "id": 198, + "length": 160, + "source": "Rosetta Code", + "text": "type\n\tComparable = concept x, y\n\t\t(x < y) is bool\n\n\tStack[T] = concept s, var v\n\t\ts.pop() is T\n\t\tv.push(T)\n\n\t\ts.len is Ordinal\n\n\t\tfor value in s:\n\t\t\tvalue is T\n" + }, + { + "id": 199, + "length": 226, + "source": "Rosetta Code", + "text": "proc selectionSort[T](a: var openarray[T]) =\n\tlet n = a.len\n\tfor i in 0 ..< n:\n\t\tvar m = i\n\t\tfor j in i ..< n:\n\t\t\tif a[j] < a[m]:\n\t\t\t\tm = j\n\t\tswap a[i], a[m]\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nselectionSort a\necho a\n" + }, + { + "id": 200, + "length": 183, + "source": "Rosetta Code", + "text": "var i: int\n\nproc harmonicSum(i: var int; lo, hi: int; term: proc: float): float =\n\ti = lo\n\twhile i <= hi:\n\t\tresult += term()\n\t\tinc i\n\necho harmonicSum(i, 1, 100, proc: float = 1 / i)\n" + }, + { + "id": 201, + "length": 113, + "source": "Rosetta Code", + "text": "import times\n\nfor year in 2008..2121:\n\tif getDayOfWeek(25, mDec, year) == dSun:\n\t\tstdout.write year, ' '\necho \"\"\n" + }, + { + "id": 202, + "length": 209, + "source": "Rosetta Code", + "text": "import strutils\n\nvar str = \"String\"\necho \"$# $# $#\" % [str, \"literal.\", \"HelloWorld!\"]\n\n# Alternate form providing automatic conversion of arguments to strings.\necho \"$# $# $#\".format(str, 123, \"HelloWorld!\")\n" + }, + { + "id": 203, + "length": 245, + "source": "Rosetta Code", + "text": "import times, os, strutils\n\nlet t = epochTime()\n\nproc handler() {.noconv.} =\n\techo \"Program has run for \", formatFloat(epochTime() - t, precision = 0), \" seconds.\"\n\tquit 0\n\nsetControlCHook(handler)\n\nfor n in 1 ..< int64.high:\n\tsleep 500\n\techo n\n" + }, + { + "id": 204, + "length": 271, + "source": "Rosetta Code", + "text": "import deques\n\nvar queue = initDeque[int]()\n\nqueue.addLast(26)\nqueue.addLast(99)\nqueue.addLast(2)\necho \"Queue size: \", queue.len()\necho \"Popping: \", queue.popFirst()\necho \"Popping: \", queue.popFirst()\necho \"Popping: \", queue.popFirst()\necho \"Popping: \", queue.popFirst()\n" + }, + { + "id": 205, + "length": 126, + "source": "Rosetta Code", + "text": "import macros, strformat\n\nmacro eval(s, x: static[string]): untyped =\n\tparseStmt(&\"let x={x}\\n{s}\")\n\necho(eval(\"x+1\", \"3.1\"))\n" + }, + { + "id": 206, + "length": 110, + "source": "Rosetta Code", + "text": "import ../compiler/[nimeval, llstream]\n\nrunRepl(llStreamOpenStdIn().repl, [findNimStdLibCompileTime()], true)\n" + }, + { + "id": 207, + "length": 223, + "source": "Rosetta Code", + "text": "import sugar\n\nproc compose[A,B,C](f: B -> C, g: A -> B): A -> C = (x: A) => f(g(x))\n\nproc plustwo(x: int): int = x + 2\nproc minustwo(x: int): int = x - 2\n\nvar plusminustwo = compose(plustwo, minustwo)\necho plusminustwo(10)\n" + }, + { + "id": 208, + "length": 139, + "source": "Rosetta Code", + "text": "proc openimage(s: cstring): cint {.importc, dynlib: \"./fakeimglib.so\".}\n\necho openimage(\"foo\")\necho openimage(\"bar\")\necho openimage(\"baz\")\n" + }, + { + "id": 209, + "length": 137, + "source": "Rosetta Code", + "text": "proc openimage(s: string): int {.importc, dynlib: \"./libfakeimg.so\".}\n\necho openimage(\"foo\")\necho openimage(\"bar\")\necho openimage(\"baz\")\n" + }, + { + "id": 210, + "length": 162, + "source": "Rosetta Code", + "text": "# nim c --app:lib fakeimg.nim\nvar handle = 100\n\nproc openimage*(s: string): int {.exportc, dynlib.} =\n\tstderr.writeln \"opening \", s\n\tresult = handle\n\tinc(handle)\n" + }, + { + "id": 211, + "length": 177, + "source": "Rosetta Code", + "text": "proc m(n: int): int\n\nproc f(n: int): int =\n\tif n == 0: 1\n\telse: n - m(f(n-1))\n\nproc m(n: int): int =\n\tif n == 0: 0\n\telse: n - f(m(n-1))\n\nfor i in 1 .. 10:\n\techo f(i)\n\techo m(i)\n" + }, + { + "id": 212, + "length": 240, + "source": "Rosetta Code", + "text": "proc gnomeSort[T](a: var openarray[T]) =\n\tvar\n\t\tn = a.len\n\t\ti = 1\n\t\tj = 2\n\twhile i < n:\n\t\tif a[i-1] > a[i]:\n\t\t\tswap a[i-1], a[i]\n\t\t\tdec i\n\t\t\tif i > 0: continue\n\t\ti = j\n\t\tinc j\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\ngnomeSort a\necho a\n" + }, + { + "id": 213, + "length": 271, + "source": "Rosetta Code", + "text": "import intsets\n\nproc happy(n: int): bool =\n\tvar\n\t\tn = n\n\t\tpast = initIntSet()\n\twhile n != 1:\n\t\tlet s = $n\n\t\tn = 0\n\t\tfor c in s:\n\t\t\tlet i = ord(c) - ord('0')\n\t\t\tn += i * i\n\t\tif n in past:\n\t\t\treturn false\n\t\tpast.incl(n)\n\treturn true\n\nfor x in 0..31:\n\tif happy(x):\n\t\techo x\n" + }, + { + "id": 214, + "length": 260, + "source": "Rosetta Code", + "text": "proc g() =\n\t# Writes the current stack trace to stderr.\n\twriteStackTrace()\n\t# Or fetch the stack trace entries for the current stack trace:\n\techo \"----\"\n\tfor e in getStackTraceEntries():\n\t\techo e.filename, \"@\", e.line, \" in \", e.procname\n\nproc f() =\n\tg()\n\nf()\n" + }, + { + "id": 215, + "length": 193, + "source": "Rosetta Code", + "text": "import random\nrandomize()\n\nproc shuffle[T](x: var openArray[T]) =\n\tfor i in countdown(x.high, 1):\n\t\tlet j = rand(i)\n\t\tswap(x[i], x[j])\n\nvar x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nshuffle(x)\necho x\n" + }, + { + "id": 216, + "length": 146, + "source": "Rosetta Code", + "text": "import httpclient, net\nvar client = newHttpClient(sslContext = newContext(certFile = \"mycert.pem\"))\nvar r = client.get(\"https://www.example.com\")\n" + }, + { + "id": 217, + "length": 104, + "source": "Rosetta Code", + "text": "import random\n\nwhile true:\n\tlet a = random(19)\n\techo a\n\tif a == 10:\n\t\tbreak\n\tlet b = random(19)\n\techo b\n" + }, + { + "id": 218, + "length": 253, + "source": "Rosetta Code", + "text": "type\n\tMyObject = object\n\t\tx: int\n\t\ty: float\n\nvar\n\tmem = alloc(sizeof(MyObject))\n\tobjPtr = cast[ptr MyObject](mem)\necho \"object at \", cast[int](mem), \": \", objPtr[]\n\nobjPtr[] = MyObject(x: 42, y: 3.1415)\necho \"object at \", cast[int](mem), \": \", objPtr[]\n" + }, + { + "id": 219, + "length": 103, + "source": "Rosetta Code", + "text": "var x: int = 3\nvar p: ptr int\n\np = cast[ptr int](addr(x))\n\necho \"Before \", x\np[] = 5\necho \"After: \", x\n" + }, + { + "id": 220, + "length": 169, + "source": "Rosetta Code", + "text": "import strutils\n\necho parseInt \"10\" # 10\n\necho parseHexInt \"0x10\" # 16\necho parseHexInt \"10\" # 16\n\necho parseOctInt \"0o120\" # 80\necho parseOctInt \"120\" # 80\n" + }, + { + "id": 221, + "length": 270, + "source": "Rosetta Code", + "text": "import posix\n\nvar p: array[2, cint]\ndiscard pipe p\nif fork() > 0:\n\tdiscard close p[0]\n\tdiscard sleep 1\n\tdiscard p[1].write(addr p[0], 1)\n\tvar x: cint = 0\n\tdiscard wait (addr x)\nelse:\n\tdiscard close p[1]\n\tdiscard p[0].read(addr p[1], 1)\n\techo \"received signal from pipe\"\n" + }, + { + "id": 222, + "length": 143, + "source": "Rosetta Code", + "text": "proc foo = echo \"foo\" # hidden\nproc bar* = echo \"bar\" # acessible\n\ntype MyObject = object\n\tname*: string # accessible\n\tsecretAge: int # hidden\n" + }, + { + "id": 223, + "length": 202, + "source": "Rosetta Code", + "text": "import osproc\n\nlet args = [\"-m\", \"-v\", \"0.75\", \"a.wav\", \"-v\", \"0.25\", \"b.wav\",\n\t\t\t\t\t\t\"-d\", \"trim\", \"4\", \"6\", \"repeat\", \"5\"]\necho execProcess(\"sox\", args = args, options = {poStdErrToStdOut, poUsePath})\n" + }, + { + "id": 224, + "length": 214, + "source": "Rosetta Code", + "text": "import tables\n\nproc modes[T](xs: openArray[T]): T =\n\tvar count = initCountTable[T]()\n\tfor x in xs:\n\t\tcount.inc(x)\n\tlargest(count).key\n\necho modes(@[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])\necho modes(@[1, 1, 2, 4, 4])\n" + }, + { + "id": 225, + "length": 272, + "source": "Rosetta Code", + "text": "import math, strutils\n\nvar sdSum, sdSum2, sdN = 0.0\n\nproc sd(x: float): float =\n\tsdN += 1\n\tsdSum += x\n\tsdSum2 += x * x\n\tsqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))\n\nfor value in [float 2, 4, 4, 4, 5, 5, 7, 9]:\n\techo value, \" \", formatFloat(sd(value), precision = -1)\n" + }, + { + "id": 226, + "length": 150, + "source": "Rosetta Code", + "text": "proc subtract(x, y): auto = x - y\n\necho subtract(5, 3) # used as positional parameters\necho subtract(y = 3, x = 5) # used as named parameters\n" + }, + { + "id": 227, + "length": 132, + "source": "Rosetta Code", + "text": "import rdstdin, strutils\n\nlet str = readLineFromStdin \"Input a string: \"\nlet num = parseInt(readLineFromStdin \"Input an integer: \")\n" + }, + { + "id": 228, + "length": 115, + "source": "Rosetta Code", + "text": "if true: echo \"yes\"\nif false: echo \"no\"\n\n# Other objects never represent true or false:\nif 2: echo \"compile error\"\n" + }, + { + "id": 229, + "length": 258, + "source": "Rosetta Code", + "text": "proc halve(x: int): int = x div 2\nproc double(x: int): int = x * 2\nproc odd(x: int): bool = x mod 2 != 0\n\nproc ethiopian(x, y: int): int =\n\tvar x = x\n\tvar y = y\n\n\twhile x >= 1:\n\t\tif odd(x):\n\t\t\tresult += y\n\t\tx = halve x\n\t\ty = double y\n\necho ethiopian(17, 34)\n" + }, + { + "id": 230, + "length": 259, + "source": "Rosetta Code", + "text": "import math\n\nproc nthRoot(a: float; n: int): float =\n\tvar n = float(n)\n\tresult = a\n\tvar x = a / n\n\twhile abs(result-x) > 1e-15:\n\t\tx = result\n\t\tresult = (1/n) * (((n-1)*x) + (a / pow(x, n-1)))\n\necho nthRoot(34.0, 5)\necho nthRoot(42.0, 10)\necho nthRoot(5.0, 2)\n" + }, + { + "id": 231, + "length": 99, + "source": "Rosetta Code", + "text": "let\n\ta = @['a','b','c']\n\tb = @[\"A\",\"B\",\"C\"]\n\tc = @[1, 2, 3]\n\nfor i in 0..2:\n\techo a[i], b[i], c[i]\n" + }, + { + "id": 232, + "length": 232, + "source": "Rosetta Code", + "text": "proc strcmp(a, b: cstring): cint {.importc: \"strcmp\", nodecl.}\necho strcmp(\"abc\", \"def\")\necho strcmp(\"hello\", \"hello\")\n\nproc printf(formatstr: cstring) {.header: \"\", varargs.}\n\nvar x = \"foo\"\nprintf(\"Hello %d %s!\\n\", 12, x)\n" + }, + { + "id": 233, + "length": 215, + "source": "Rosetta Code", + "text": "proc Query*(data: var array[1024, char], length: var cint): cint {.exportc.} =\n\tconst text = \"Here am I\"\n\tif length < text.len:\n\t\treturn 0\n\n\tfor i in 0 .. text.high:\n\t\tdata[i] = text[i]\n\tlength = text.len\n\treturn 1\n" + }, + { + "id": 234, + "length": 235, + "source": "Rosetta Code", + "text": "import intsets, math, algorithm\n\nproc factors(n: int): seq[int] =\n\tvar fs: IntSet\n\tfor x in 1 .. int(sqrt(float(n))):\n\t\tif n mod x == 0:\n\t\t\tfs.incl(x)\n\t\t\tfs.incl(n div x)\n\n\tfor x in fs:\n\t\tresult.add(x)\n\tresult.sort()\n\necho factors(45)\n" + }, + { + "id": 235, + "length": 262, + "source": "Rosetta Code", + "text": "type TPerson* = object\n\t## This type contains a description of a person\n\tname: string\n\tage: int\n\nvar numValues*: int ## \\\n\t## `numValues` stores the number of values\n\nproc helloWorld*(times: int) =\n\t## A useful procedure\n\tfor i in 1..times:\n\t\techo \"hello world\"\n" + }, + { + "id": 236, + "length": 135, + "source": "Rosetta Code", + "text": "import strutils\n\n# Repeat a char.\necho repeat('a', 5) # -> \"aaaaa\".\n\n# Repeat a string.\necho repeat(\"ha\", 5) # -> \"hahahahaha\".\n" + }, + { + "id": 237, + "length": 180, + "source": "Rosetta Code", + "text": "var a {.noInit.}: array[1_000_000, int]\n\n# For a proc, {.noInit.} means that the result is not initialized.\nproc p(): array[1000, int] {.noInit.} =\n\tfor i in 0..999: result[i] = i\n" + }, + { + "id": 238, + "length": 229, + "source": "Rosetta Code", + "text": "import sets\n\nvar setA = [\"John\", \"Bob\", \"Mary\", \"Serena\"].toHashSet\nvar setB = [\"Jim\", \"Mary\", \"John\", \"Bob\"].toHashSet\necho setA -+- setB # Symmetric difference\necho setA - setB # Difference\necho setB - setA # Difference\n" + }, + { + "id": 239, + "length": 269, + "source": "Rosetta Code", + "text": "import strfmt\n\nconst n = 12\n\nfor j in 1..n:\n\tstdout.write \"{:3d}{:s}\".fmt(j, if n-j>0: \" \" else: \"\\n\")\nfor j in 0..n:\n\tstdout.write if n-j>0: \"----\" else: \"+\\n\"\nfor i in 1..n:\n\tfor j in 1..n:\n\t\tstdout.write if j 1:\n\t\tlet t = (j - i + 1) div 3\n\t\tstoogeSort(a, i, j - t)\n\t\tstoogeSort(a, i + t, j)\n\t\tstoogeSort(a, i, j - t)\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nstoogeSort a, 0, a.high\necho a\n" + }, + { + "id": 252, + "length": 194, + "source": "Rosetta Code", + "text": "proc a(x): bool =\n\techo \"a called\"\n\tresult = x\n\nproc b(x): bool =\n\techo \"b called\"\n\tresult = x\n\nlet x = a(false) and b(true) # prints \"a called\"\nlet y = a(true) or b(true) # prints \"a called\"\n" + }, + { + "id": 253, + "length": 104, + "source": "Rosetta Code", + "text": "import algorithm\nvar v = [1, 2, 3] # List has to start sorted\necho v\nwhile v.nextPermutation():\n\techo v\n" + }, + { + "id": 254, + "length": 119, + "source": "Rosetta Code", + "text": "import terminal\n\nlet (width, height) = terminalSize()\n\necho \"Terminal width: \", width\necho \"Terminal height: \", height\n" + }, + { + "id": 255, + "length": 149, + "source": "Rosetta Code", + "text": "const TCIFLUSH: cint = 0\nproc tcflush(fd, queue_selector: cint): cint {.header: \"termios.h\".}\n\ndiscard tcflush(cint(getFileHandle(stdin)), TCIFLUSH)\n" + }, + { + "id": 256, + "length": 243, + "source": "Rosetta Code", + "text": "import os, illwill\n\nillwillInit(fullscreen=false)\n\nwhile true:\n\tvar key = getKey()\n\tcase key\n\tof Key.None:\n\t\techo \"not received a key, I can do other stuff here\"\n\tof Key.Escape, Key.Q:\n\t\tbreak\n\telse:\n\t\techo \"Key pressed: \", $key\n\n\tsleep(1000)\n" + }, + { + "id": 257, + "length": 137, + "source": "Rosetta Code", + "text": "import terminal\n\necho \"Cursor hidden. Press a key to show the cursor and exit.\"\nstdout.hideCursor()\ndiscard getCh()\nstdout.showCursor()\n" + }, + { + "id": 258, + "length": 275, + "source": "Rosetta Code", + "text": "import strutils, random\n\nrandomize()\nvar chosen = rand(1..10)\necho \"I have thought of a number. Try to guess it!\"\n\nvar guess = parseInt(readLine(stdin))\n\nwhile guess != chosen:\n\techo \"Your guess was wrong. Try again!\"\n\tguess = parseInt(readLine(stdin))\n\necho \"Well guessed!\"\n" + }, + { + "id": 259, + "length": 154, + "source": "Rosetta Code", + "text": "import strutils\n\nlet fr = \"Goodbye London!\"\nlet to = \"Hello, New York!\"\n\nfor fn in [\"a.txt\", \"b.txt\", \"c.txt\"]:\n\tfn.writeFile fn.readFile.replace(fr, to)\n" + }, + { + "id": 260, + "length": 200, + "source": "Rosetta Code", + "text": "proc `^`*[T: SomeInteger](base, exp: T): T =\n\tvar (base, exp) = (base, exp)\n\tresult = 1\n\n\twhile exp != 0:\n\t\tif (exp and 1) != 0:\n\t\t\tresult *= base\n\t\texp = exp shr 1\n\t\tbase *= base\n\necho 2 ^ 10 # 1024\n" + }, + { + "id": 261, + "length": 183, + "source": "Rosetta Code", + "text": "when defined windows:\n\techo \"Call some Windows specific functions here\"\nelif defined linux:\n\techo \"Call some Linux specific functions here\"\nelse:\n\techo \"Code for the other platforms\"\n" + }, + { + "id": 262, + "length": 191, + "source": "Rosetta Code", + "text": "import os\n\nconst debug = false\n\nproc expensive: string =\n\tsleep(milsecs = 100)\n\tresult = \"That was difficult\"\n\nproc log(msg: string) =\n\tif debug:\n\t\techo msg\n\nfor i in 1..10:\n\tlog expensive()\n" + }, + { + "id": 263, + "length": 125, + "source": "Rosetta Code", + "text": "template times(x, y: untyped): untyped =\n\tfor i in 1..x:\n\t\ty\n\n10.times: # or times 10: or times(10):\n\techo \"hi\"\n\techo \"bye\"\n" + }, + { + "id": 264, + "length": 256, + "source": "Rosetta Code", + "text": "template optLog1{a and a}(a): auto = a\ntemplate optLog2{a and (b or (not b))}(a,b): auto = a\ntemplate optLog3{a and not a}(a: int): auto = 0\n\nvar\n\tx = 12\n\ts = x and x\n\tr = (x and x) and ((s or s) or (not (s or s)))\n\tq = (s and not x) and not (s and not x)\n" + }, + { + "id": 265, + "length": 95, + "source": "Rosetta Code", + "text": "import macros\n\ndumpTree:\n\tif x:\n\t\tif y:\n\t\t\tp0\n\t\telse:\n\t\t\tp1\n\telse:\n\t\tif y:\n\t\t\tp2\n\t\telse:\n\t\t\tp3\n" + }, + { + "id": 266, + "length": 108, + "source": "Rosetta Code", + "text": "import gtk2, gdk2\n\nnim_init()\nvar w = gdk2.screen_width()\nvar h = gdk2.screen_height()\necho(\"WxH=\",w,\"x\",h)\n" + }, + { + "id": 267, + "length": 241, + "source": "Rosetta Code", + "text": "# Using scoped function fibI inside fib\nproc fib(x: int): int =\n\tproc fibI(n: int): int =\n\t\tif n < 2: n else: fibI(n-2) + fibI(n-1)\n\tif x < 0:\n\t\traise newException(ValueError, \"Invalid argument\")\n\treturn fibI(x)\n\nfor i in 0..4:\n\techo fib(i)\n" + }, + { + "id": 268, + "length": 256, + "source": "Rosetta Code", + "text": "import strformat\n\ntype FloatRange = tuple[s, e: float]\n\nproc mapRange(a, b: FloatRange; s: float): float =\n\tb.s + (s - a.s) * (b.e - b.s) / (a.e - a.s)\n\nfor i in 0..10:\n\tlet m = mapRange((0.0, 10.0), (-1.0, 0.0), float(i))\n\techo &\"{i:>2} maps to {m:4.1f}\"\n" + }, + { + "id": 269, + "length": 284, + "source": "Rosetta Code", + "text": "var x = \"mutablefoo\" # Mutable variable\nlet y = \"immutablefoo\" # Immutable variable, at runtime\nconst z = \"constantfoo\" # Immutable constant, at compile time\n\nx[0] = 'M'\ny[0] = 'I' # Compile error: 'y[0]' cannot be assigned to\nz[0] = 'C' # Compile error: 'z[0]' cannot be assigned to\n" + }, + { + "id": 270, + "length": 119, + "source": "Rosetta Code", + "text": "import std/editdistance\n\necho editDistanceAscii(\"kitten\", \"sitting\")\necho editDistanceAscii(\"arthur\", \"raisethysword\")\n" + }, + { + "id": 271, + "length": 279, + "source": "Rosetta Code", + "text": "import random, htmlgen\nrandomize()\n\ntemplate randTD(): string = td($rand(1000..9999))\nproc randTR(x: int): string =\n\ttr(td($x, style=\"font-weight: bold\"), randTD, randTD, randTD)\n\necho table(\n\ttr(th\"\", th\"X\", th\"Y\", th\"Z\"),\n\trandTR 1,\n\trandTR 2,\n\trandTR 3,\n\trandTR 4,\n\trandTR 5)\n" + }, + { + "id": 272, + "length": 280, + "source": "Rosetta Code", + "text": "import hailstone, tables\n\nvar t = initCountTable[int]()\n\nfor i in 1 ..< 100_000:\n\tt.inc(hailstone(i).len)\n\nlet (val, cnt) = t.largest()\necho \"The length of hailstone sequence that is most common for\"\necho \"hailstone(n) where 1<=n<100000, is \", val, \". It occurs \", cnt, \" times.\"\n" + }, + { + "id": 273, + "length": 155, + "source": "Rosetta Code", + "text": "proc grayEncode(n: int): int =\n\tn xor (n shr 1)\n\nproc grayDecode(n: int): int =\n\tresult = n\n\tvar t = n\n\twhile t > 0:\n\t\tt = t shr 1\n\t\tresult = result xor t\n" + }, + { + "id": 274, + "length": 141, + "source": "Rosetta Code", + "text": "import os\n\necho \"\\e[?1049h\\e[H\"\necho \"Alternate buffer!\"\n\nfor i in countdown(5, 1):\n\techo \"Going back in: \", i\n\tsleep 1000\n\necho \"\\e[?1049l\"\n" + }, + { + "id": 275, + "length": 186, + "source": "Rosetta Code", + "text": "proc gcd(u, v: int): auto =\n\tvar\n\t\tu = u\n\t\tv = v\n\twhile v != 0:\n\t\tu = u %% v\n\t\tswap u, v\n\tabs(u)\n\nproc lcm(a, b: int): auto = abs(a * b) div gcd(a, b)\n\necho lcm(12, 18)\necho lcm(-6, 14)\n" + }, + { + "id": 276, + "length": 149, + "source": "Rosetta Code", + "text": "import someModule\nimport strutils except parseInt\nimport strutils as su, sequtils as qu # su.x works\nimport pure/os, \"pure/times\" # still strutils.x\n" + }, + { + "id": 277, + "length": 251, + "source": "Rosetta Code", + "text": "import strutils\n\nproc count(s, sub: string): int =\n\tvar i = 0\n\twhile true:\n\t\ti = s.find(sub, i)\n\t\tif i < 0:\n\t\t\tbreak\n\t\ti += sub.len # i += 1 for overlapping substrings\n\t\tinc result\n\necho count(\"the three truths\",\"th\")\n\necho count(\"ababababab\",\"abab\")\n" + }, + { + "id": 278, + "length": 219, + "source": "Rosetta Code", + "text": "import os, strutils\n\nproc single(n: int) =\n\tsleep n\n\techo n\n\nproc main =\n\tvar thr = newSeq[TThread[int]](paramCount())\n\tfor i,c in commandLineParams():\n\t\tthr[i].createThread(single, c.parseInt)\n\tthr.joinThreads\n\nmain()\n" + }, + { + "id": 279, + "length": 186, + "source": "Rosetta Code", + "text": "import asynchttpserver, asyncdispatch\n\nproc cb(req: Request) {.async.} =\n\tawait req.respond(Http200, \"Hello, World!\")\n\nasyncCheck newAsyncHttpServer().serve(Port(8080), cb)\nrunForever()\n" + }, + { + "id": 280, + "length": 147, + "source": "Rosetta Code", + "text": "var x = \"\"\n\nif x == \"\":\n\techo \"empty\"\nif x != \"\":\n\techo \"not empty\"\n\n# Alternatively:\nif x.len == 0:\n\techo \"empty\"\nif x.len > 0:\n\techo \"not empty\"\n" + }, + { + "id": 281, + "length": 290, + "source": "Rosetta Code", + "text": "import strformat\n\nproc readLine(f: File; num: Positive): string =\n\tfor n in 1..num:\n\t\ttry:\n\t\t\tresult = f.readLine()\n\t\texcept EOFError:\n\t\t\traise newException(IOError, &\"Not enough lines in file; expected {num}, found {n - 1}.\")\n\nlet f = open(\"test.txt\", fmRead)\necho f.readLine(7)\nf.close()\n" + }, + { + "id": 282, + "length": 160, + "source": "Rosetta Code", + "text": "var funcs: seq[proc(): int] = @[]\n\nfor i in 0..9:\n\t(proc =\n\t\tlet x = i\n\t\tfuncs.add(proc (): int = x * x))()\n\nfor i in 0..8:\n\techo \"func[\", i, \"]: \", funcs[i]()\n" + }, + { + "id": 283, + "length": 232, + "source": "Rosetta Code", + "text": "import HeapQueue\n\nvar pq = newHeapQueue[(int, string)]()\n\npq.push((3, \"Clear drains\"))\npq.push((4, \"Feed cat\"))\npq.push((5, \"Make tea\"))\npq.push((1, \"Solve RC tasks\"))\npq.push((2, \"Tax return\"))\n\nwhile pq.len() > 0:\n\t\techo pq.pop()\n" + }, + { + "id": 284, + "length": 281, + "source": "Rosetta Code", + "text": "import tables\n\nvar\n\tpq = initTable[int, string]()\n\nproc main() =\n\tpq.add(3, \"Clear drains\")\n\tpq.add(4, \"Feed cat\")\n\tpq.add(5, \"Make tea\")\n\tpq.add(1, \"Solve RC tasks\")\n\tpq.add(2, \"Tax return\")\n\n\tfor i in countUp(1, 5):\n\t\tif pq.hasKey(i):\n\t\t\techo i, \": \", pq[i]\n\t\t\tpq.del(i)\n\nmain()\n" + }, + { + "id": 285, + "length": 110, + "source": "Rosetta Code", + "text": "import os\necho getAppFilename() # Prints the full path of the executed file\necho paramStr(0) # Prints argv[0]\n" + }, + { + "id": 286, + "length": 105, + "source": "Rosetta Code", + "text": "type Foo* = object\n\ta: string\n\tb: string\n\tc: int\n\nproc createFoo*(a, b, c): Foo =\n\tFoo(a: a, b: b, c: c)\n" + }, + { + "id": 287, + "length": 119, + "source": "Rosetta Code", + "text": "import times\n\necho \"Epoch for Posix systems: \", fromUnix(0).utc\necho \"Epoch for Windows system: \", fromWinTime(0).utc\n" + }, + { + "id": 288, + "length": 263, + "source": "Rosetta Code", + "text": "import os\n\nproc metronome(tempo, pattern: Positive) =\n\tlet delay = 60_000 div tempo # In milliseconds.\n\tvar beats = 0\n\twhile true:\n\t\tstdout.write if beats mod pattern == 0: \"\\nTICK\" else: \" tick\"\n\t\tstdout.flushFile\n\t\tinc beats\n\t\tsleep(delay)\n\nmetronome(72, 4)\n" + }, + { + "id": 289, + "length": 279, + "source": "Rosetta Code", + "text": "import random\nrandomize()\n\nproc oneOfN(n: int): int =\n\tresult = 0\n\tfor x in 0 ..< n:\n\t\tif random(x) == 0:\n\t\t\tresult = x\n\nproc oneOfNTest(n = 10, trials = 1_000_000): seq[int] =\n\tresult = newSeq[int](n)\n\tif n > 0:\n\t\tfor i in 1..trials:\n\t\t\tinc result[oneOfN(n)]\n\necho oneOfNTest()\n" + }, + { + "id": 290, + "length": 109, + "source": "Rosetta Code", + "text": "import tables, os\n\nvar t = initCountTable[char]()\nfor l in paramStr(1).lines:\n\tfor c in l:\n\t\tt.inc(c)\necho t\n" + }, + { + "id": 291, + "length": 263, + "source": "Rosetta Code", + "text": "var q = @[1, 1]\nfor n in 2 ..< 100_000: q.add q[n-q[n-1]] + q[n-q[n-2]]\n\necho q[0..9]\nassert q[0..9] == @[1, 1, 2, 3, 3, 4, 5, 5, 6, 6]\n\necho q[999]\nassert q[999] == 502\n\nvar lessCount = 0\nfor n in 1 ..< 100_000:\n\tif q[n] < q[n-1]:\n\t\tinc lessCount\necho lessCount\n" + }, + { + "id": 292, + "length": 263, + "source": "Rosetta Code", + "text": "proc changes(amount: int, coins: openArray[int]): int =\n\tvar ways = @[1]\n\tways.setLen(amount+1)\n\tfor coin in coins:\n\t\tfor j in coin..amount:\n\t\t\tways[j] += ways[j-coin]\n\tways[amount]\n\necho changes(100, [1, 5, 10, 25])\necho changes(100000, [1, 5, 10, 25, 50, 100])\n" + }, + { + "id": 293, + "length": 207, + "source": "Rosetta Code", + "text": "proc `<`[T](a, b: openarray[T]): bool =\n\tfor i in 0 .. min(a.len, b.len):\n\t\tif a[i] < b[i]: return true\n\t\tif a[i] > b[i]: return false\n\treturn a.len < b.len\n\necho([1, 2, 1, 3, 2] < [1, 2, 0, 4, 4, 0, 0, 0])\n" + }, + { + "id": 294, + "length": 121, + "source": "Rosetta Code", + "text": "import os, rdstdin\n\nvar empty = true\nfor f in walkDir(readLineFromStdin \"directory: \"):\n\tempty = false\n\tbreak\necho empty\n" + }, + { + "id": 295, + "length": 217, + "source": "Rosetta Code", + "text": "import os, sequtils\n\nproc isEmptyDir(dir: string): bool =\n\ttoSeq(walkdir dir).len == 0\n\necho isEmptyDir(\"/tmp\") # false - there is always something in \"/tmp\"\necho isEmptyDir(\"/temp\") # true - \"/temp\" does not exist\n" + }, + { + "id": 296, + "length": 276, + "source": "Rosetta Code", + "text": "import math\n\nproc agm(a, g: float,delta: float = 1.0e-15): float =\n\tvar\n\t\taNew: float = 0\n\t\taOld: float = a\n\t\tgOld: float = g\n\twhile (abs(aOld - gOld) > delta):\n\t\taNew = 0.5 * (aOld + gOld)\n\t\tgOld = sqrt(aOld * gOld)\n\t\taOld = aNew\n\tresult = aOld\n\necho agm(1.0, 1.0/sqrt(2.0))\n" + }, + { + "id": 297, + "length": 147, + "source": "Rosetta Code", + "text": "proc identityMatrix(n: Positive): auto =\n\tresult = newSeq[seq[int]](n)\n\tfor i in 0 ..< result.len:\n\t\tresult[i] = newSeq[int](n)\n\t\tresult[i][i] = 1\n" + }, + { + "id": 298, + "length": 236, + "source": "Rosetta Code", + "text": "proc sumdigits(n, base: Natural): Natural =\n\tvar n = n\n\twhile n > 0:\n\t\tresult += n mod base\n\t\tn = n div base\n\necho sumDigits(1, 10)\necho sumDigits(12345, 10)\necho sumDigits(123045, 10)\necho sumDigits(0xfe, 16)\necho sumDigits(0xf0e, 16)\n" + }, + { + "id": 299, + "length": 238, + "source": "Rosetta Code", + "text": "proc modInv(a0, b0: int): int =\n\tvar (a, b, x0) = (a0, b0, 0)\n\tresult = 1\n\tif b == 1: return\n\twhile a > 1:\n\t\tresult = result - (a div b) * x0\n\t\ta = a mod b\n\t\tswap a, b\n\t\tswap x0, result\n\tif result < 0: result += b0\n\necho modInv(42, 2017)\n" + }, + { + "id": 300, + "length": 216, + "source": "Rosetta Code", + "text": "import rdstdin, strutils, strfmt\n\nwhile true:\n\tlet k = parseFloat readLineFromStdin \"K ? \"\n\techo \"{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees\".fmt(\n\t\tk, k - 273.15, k * 1.8 - 459.67, k * 1.8)\n" + }, + { + "id": 301, + "length": 190, + "source": "Rosetta Code", + "text": "import tables, math\n\nproc entropy(s: string): float =\n\tvar t = initCountTable[char]()\n\tfor c in s: t.inc(c)\n\tfor x in t.values: result -= x/s.len * log2(x/s.len)\n\necho entropy(\"1223334444\")\n" + }, + { + "id": 302, + "length": 108, + "source": "Rosetta Code", + "text": "import terminal\n\nstderr.write if stdout.isatty: \"stdout is a terminal\\n\" else: \"stdout is not a terminal\\n\"\n" + }, + { + "id": 303, + "length": 222, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils, sugar\n\nproc maxNum(x: seq[int]): string =\n\tvar c = x.mapIt($it)\n\tc.sort((x, y) => cmp(y&x, x&y))\n\tc.join()\n\necho maxNum(@[1, 34, 3, 98, 9, 76, 45, 4])\necho maxNum(@[54, 546, 548, 60])\n" + }, + { + "id": 304, + "length": 217, + "source": "Rosetta Code", + "text": "const n = 15\nvar t = newSeq[int](n + 2)\n\nt[1] = 1\nfor i in 1..n:\n\tfor j in countdown(i, 1): t[j] += t[j-1]\n\tt[i+1] = t[i]\n\tfor j in countdown(i+1, 1): t[j] += t[j-1]\n\tstdout.write t[i+1] - t[i], \" \"\nstdout.write '\\n'\n" + }, + { + "id": 305, + "length": 113, + "source": "Rosetta Code", + "text": "proc sum35(n: int): int =\n\tfor x in 0 ..< n:\n\t\tif x mod 3 == 0 or x mod 5 == 0:\n\t\t\tresult += x\n\necho sum35(1000)\n" + }, + { + "id": 306, + "length": 255, + "source": "Rosetta Code", + "text": "import base64\nimport httpclient\n\nvar client = newHttpClient()\nlet content = client.getContent(\"https://en.wikipedia.org/favicon.ico\")\nlet encoded = encode(content)\n\nif encoded.len <= 64:\n\techo encoded\nelse:\n\techo encoded[0..31] & \"...\" & encoded[^32..^1]\n" + }, + { + "id": 307, + "length": 104, + "source": "Rosetta Code", + "text": "var str = \"123456\"\nstr.add(\"78\") # Using procedure \"add\".\nstr &= \"9!\" # Using operator \"&=\".\necho str\n" + }, + { + "id": 308, + "length": 116, + "source": "Rosetta Code", + "text": "# Direct way.\nvar str1, str2 = \"12345678\"\nstr1 = \"0\" & str1\necho str1\n\n# Using \"insert\".\nstr2.insert(\"0\")\necho str2\n" + }, + { + "id": 309, + "length": 286, + "source": "Rosetta Code", + "text": "proc commaQuibble(s: openArray[string]): string =\n\tresult = \"\"\n\tfor i, c in s:\n\t\tif i > 0: result.add (if i < s.high: \", \" else: \" and \")\n\t\tresult.add c\n\tresult = \"{\" & result & \"}\"\n\nvar s = @[@[], @[\"ABC\"], @[\"ABC\", \"DEF\"], @[\"ABC\", \"DEF\", \"G\", \"H\"]]\nfor i in s:\n\techo commaQuibble(i)\n" + }, + { + "id": 310, + "length": 239, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nlet lineCount = stdin.readLine.parseInt()\nfor _ in 1..lineCount:\n\tlet line = stdin.readLine()\n\tlet fields = line.splitWhitespace()\n\tassert fields.len == 2\n\tlet pair = fields.map(parseInt)\n\techo pair[0] + pair[1]\n" + }, + { + "id": 311, + "length": 164, + "source": "Rosetta Code", + "text": "import strutils\n\nproc write(line: string) =\n\techo line\n\nlet lineCount = stdin.readLine.parseInt()\nfor _ in 1..lineCount:\n\tlet line = stdin.readLine()\n\tline.write()\n" + }, + { + "id": 312, + "length": 261, + "source": "Rosetta Code", + "text": "proc isSemiPrime(k: int): bool =\n var\n\ti = 2\n\tcount = 0\n\tx = k\n while i <= x and count < 3:\n\tif x mod i == 0:\n\t x = x div i\n\t inc count\n\telse:\n\t inc i\n result = count == 2\n\nfor k in 1675..1680:\n echo k, (if k.isSemiPrime(): \" is\" else: \" isn't\"), \" semi-prime\"\n" + }, + { + "id": 313, + "length": 262, + "source": "Rosetta Code", + "text": "const Suffix = [\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"]\n\nproc nth(n: Natural): string =\n\t$n & \"'\" & (if n mod 100 in 11..20: \"th\" else: Suffix[n mod 10])\n\nfor j in countup(0, 1000, 250):\n\tfor i in j..j+24:\n\t\tstdout.write nth(i), \" \"\n\techo \"\"\n" + }, + { + "id": 314, + "length": 212, + "source": "Rosetta Code", + "text": "import math, sequtils\n\necho \"5^3^2 = \", 5^3^2\necho \"(5^3)^2 = \", (5^3)^2\necho \"5^(3^2) = \", 5^(3^2)\necho \"foldl([5, 3, 2], a^b) = \", foldl([5, 3, 2], a^b)\necho \"foldr([5, 3, 2], a^b) = \", foldr([5, 3, 2], a^b)\n" + }, + { + "id": 315, + "length": 112, + "source": "Rosetta Code", + "text": "import math\n\necho pow(0.0, 0.0) # Floating point exponentiation.\necho 0 ^ 0 # Integer exponentiation.\n" + }, + { + "id": 316, + "length": 149, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\necho \"Lowercase characters:\"\necho toSeq('a'..'z').join()\necho \"\"\necho \"Uppercase characters:\"\necho toSeq('A'..'Z').join()\n" + }, + { + "id": 317, + "length": 194, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\necho \"Allowed starting characters for identifiers:\"\necho toSeq(IdentStartChars).join()\necho \"\"\necho \"Allowed characters in identifiers:\"\necho toSeq(IdentChars).join()\n" + }, + { + "id": 318, + "length": 227, + "source": "Rosetta Code", + "text": "import osproc\n\n# Output string and error code\nlet (lsalStr, errCode) = execCmdEx(\"ls -al\")\n\necho \"Error code: \" & $errCode\necho \"Output: \" & lsalStr\n\n\n# Output string only\nlet lsStr = execProcess(\"ls\")\n\necho \"Output: \" & lsStr\n" + }, + { + "id": 319, + "length": 139, + "source": "Rosetta Code", + "text": "from algorithm import sorted\nfrom os import walkPattern\nfrom sequtils import toSeq\n\nfor path in toSeq(walkPattern(\"*\")).sorted:\n\techo path\n" + }, + { + "id": 320, + "length": 197, + "source": "Rosetta Code", + "text": "import sequtils\n\nfunc allEqual(s: openArray[string]): bool =\n\tallIt(s, it == s[0])\n\ndoAssert allEqual([\"abc\", \"abc\", \"abc\"])\ndoAssert not allEqual([\"abc\", \"abd\", \"abc\"])\ndoAssert allEqual([\"abc\"])\n" + }, + { + "id": 321, + "length": 123, + "source": "Rosetta Code", + "text": "try:\n\tvar x: int32 = -2147483647\n\tx = -(x - 1) # Raise overflow.\n\techo x\nexcept OverflowDefect:\n\techo \"Overflow detected\"\n" + }, + { + "id": 322, + "length": 232, + "source": "Rosetta Code", + "text": "{.push overflowChecks: off.}\ntry:\n\tvar x: int32 = -2147483647\n\tx = -(x - 1)\n\techo x # -2147483648 - Wrong result as 2147483648 doesn't fit in an int32.\nexcept OverflowDefect:\n\techo \"Overflow detected\" # Not executed.\n{.pop.}\n" + }, + { + "id": 323, + "length": 130, + "source": "Rosetta Code", + "text": "import os\n\ntry:\n\tcreateDir(\"./path/to/dir\")\n\techo \"Directory now exists.\"\nexcept OSError:\n\techo \"Failed to create the directory.\"\n" + }, + { + "id": 324, + "length": 116, + "source": "Rosetta Code", + "text": "import math\n\nfunc isqrt(n: int): int =\n\tassert n >= 0, \"argument of isqrt cannot be negative\"\n\tint(sqrt(n.toFloat))\n" + }, + { + "id": 325, + "length": 255, + "source": "Rosetta Code", + "text": "import algorithm\n\nfunc jortSort[T](a: openArray[T]): bool =\n\ta == a.sorted()\n\nproc test[T](a: openArray[T]) =\n\techo a, \" is \", if a.jortSort(): \"\" else: \"not \", \"sorted\"\n\ntest([1, 2, 3])\ntest([2, 3, 1])\necho \"\"\ntest(['a', 'b', 'c'])\ntest(['c', 'a', 'b'])\n" + }, + { + "id": 326, + "length": 247, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\niterator thueMorse(maxSteps = int.high): string =\n\tvar val = @[0]\n\tvar count = 0\n\twhile true:\n\t\tyield val.join()\n\t\tinc count\n\t\tif count == maxSteps: break\n\t\tval &= val.mapIt(1 - it)\n\nfor bits in thueMorse(6):\n\techo bits\n" + }, + { + "id": 327, + "length": 244, + "source": "Rosetta Code", + "text": "type Bit = 0..1\n\nproc thueMorse(seqLength: Positive): string =\n\tvar val = Bit(0)\n\tfor n in 0.. 0:\n\t\tvar digit = number mod 10\n\t\tsum += digit ^ digit\n\t\tnumber = number div 10\n\tif sum == i:\n\t\techo i\n" + }, + { + "id": 332, + "length": 144, + "source": "Rosetta Code", + "text": "import httpclient\n\nfor mac in [\"FC-A1-3E\", \"FC:FB:FB:01:FA:21\", \"BC:5F:F4\"]:\n\techo newHttpClient().getContent(\"http://api.macvendors.com/\"&mac)\n" + }, + { + "id": 333, + "length": 235, + "source": "Rosetta Code", + "text": "let start = getTime()\nvar solver = initSolver([Value 15, 14, 1, 6,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t9, 11, 4, 12,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, 10, 7, 3,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 13, 8, 5, 2])\nsolver.run()\necho fmt\"Execution time: {(getTime() - start).toString}.\"\n" + }, + { + "id": 334, + "length": 235, + "source": "Rosetta Code", + "text": "let start = getTime()\nvar solver = initSolver([Value 0, 12, 9, 13,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 15, 11, 10, 14,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t3, 7, 2, 5,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t4, 8, 6, 1])\nsolver.run()\necho fmt\"Execution time: {(getTime() - start).toString}.\"\n" + }, + { + "id": 335, + "length": 119, + "source": "Rosetta Code", + "text": "import bignum\n\nvar p = newInt(2)\nfor e in 1..10_000:\n\tif probablyPrime(p - 1, 25) != 0:\n\t\techo \"2^\", e, \" - 1\"\n\tp *= 2\n" + }, + { + "id": 336, + "length": 210, + "source": "Rosetta Code", + "text": "import strscans\n\nfor line in \"data.txt\".lines:\n\tvar date, name: string\n\tvar magnitude: float\n\tif scanf(line, \"$+ $s$+ $s$f\", date, name, magnitude):\n\t\tif magnitude > 6:\n\t\t\techo line\n\t# else wrong line: ignore.\n" + }, + { + "id": 337, + "length": 131, + "source": "Rosetta Code", + "text": "import strutils\n\nfor line in \"data.txt\".lines:\n\tlet magnitude = line.rsplit(' ', 1)[1]\n\tif magnitude.parseFloat() > 6:\n\t\techo line\n" + }, + { + "id": 338, + "length": 218, + "source": "Rosetta Code", + "text": "const epsilon : float64 = 1.0e-15\nvar fact : int64 = 1\nvar e : float64 = 2.0\nvar e0 : float64 = 0.0\nvar n : int64 = 2\n\nwhile abs(e - e0) >= epsilon:\n\te0 = e\n\tfact = fact * n\n\tinc(n)\n\te = e + 1.0 / fact.float64\n\necho e\n" + }, + { + "id": 339, + "length": 162, + "source": "Rosetta Code", + "text": "import sequtils\n\nfunc countJewels(stones, jewels: string): Natural =\n\tstones.countIt(it in jewels)\n\necho countJewels(\"aAAbbbb\", \"aA\")\necho countJewels(\"ZZ\", \"z\")\n" + }, + { + "id": 340, + "length": 142, + "source": "Rosetta Code", + "text": "import algorithm, sequtils\n\nfor n in [0, 5, 13, 21, -22]:\n\tlet s = if n > 1: toSeq(1..n) else: toSeq(countdown(1, n))\n\techo s.sortedByIt($it)\n" + }, + { + "id": 341, + "length": 213, + "source": "Rosetta Code", + "text": "import strformat\n\nfor i in 0..15:\n\tfor j in countup(32 + i, 127, step = 16):\n\t\tlet k = case j\n\t\t\t\t\t\tof 32: \"Spc\"\n\t\t\t\t\t\tof 127: \"Del\"\n\t\t\t\t\t\telse: $chr(j)\n\t\twrite(stdout, fmt\"{j:3d} : {k:<6s}\")\n\twrite(stdout, \"\\n\")\n" + }, + { + "id": 342, + "length": 190, + "source": "Rosetta Code", + "text": "var count = 0\nvar n, c, c3 = 1\n\nwhile count < 30:\n\tvar sq = n * n\n\twhile c3 < sq:\n\t\tinc c\n\t\tc3 = c * c * c\n\tif c3 == sq:\n\t\techo sq, \" is square and cube\"\n\telse:\n\t\techo sq\n\t\tinc count\n\tinc n\n" + }, + { + "id": 343, + "length": 240, + "source": "Rosetta Code", + "text": "for j in loop((-three, 3^3, three),\n\t\t\t\t\t\t\t(-seven, seven, x),\n\t\t\t\t\t\t\t(555, 550 - y),\n\t\t\t\t\t\t\t(22, -28, three),\n\t\t\t\t\t\t\t(1927, 1939, 1),\n\t\t\t\t\t\t\t(x, y, -z),\n\t\t\t\t\t\t\t(11^x, 11^x + one)):\n\tsum += abs(j)\n\tif abs(prod) < 2^27 and j != 0: prod *= j\n" + }, + { + "id": 344, + "length": 265, + "source": "Rosetta Code", + "text": "proc rpn(voltage:float, s:string): Node = calculate(voltage, s.split ' ')\nvar node = rpn(18, \"10 2 + 6 * 8 + 6 * 4 + 8 * 4 + 8 * 6 +\")\nassert 10 == node.res\nassert 18 == node.voltage\nassert 1.8 == node.current()\nassert 32.4 == node.effect()\nassert '+' == node.kind\n" + }, + { + "id": 345, + "length": 282, + "source": "Rosetta Code", + "text": "const max = 1000\nvar a: array[max, int]\nfor n in countup(0, max - 2):\n\tfor m in countdown(n - 1, 0):\n\t\tif a[m] == a[n]:\n\t\t\ta[n + 1] = n - m\n\t\t\tbreak\n\necho \"The first ten terms of the Van Eck sequence are:\"\necho a[..9]\necho \"\\nTerms 991 to 1000 of the sequence are:\"\necho a[990..^1]\n" + }, + { + "id": 346, + "length": 248, + "source": "Rosetta Code", + "text": "import tables\n\nlet t1 = {\"name\": \"Rocket Skates\", \"price\": \"12.75\", \"color\": \"yellow\"}.toTable\nlet t2 = {\"price\": \"15.25\", \"color\": \"red\", \"year\": \"1974\"}.toTable\n\nvar t3 = t1 # Makes a copy.\nfor key, value in t2.pairs:\n\tt3[key] = value\n\necho t3\n" + }, + { + "id": 347, + "length": 122, + "source": "Rosetta Code", + "text": "import os\n\nlet execFile = getAppFilename()\nlet sourceFile = execFile.addFileExt(\"nim\")\nstdout.write sourceFile.readFile()\n" + }, + { + "id": 348, + "length": 291, + "source": "Rosetta Code", + "text": "import random\nimport imageman\n\nconst Size = 500\n\nrandomize()\nvar image = initImage[ColorRGBU](Size, Size)\nfor x in 0.. 11 and word.contains(\"the\"):\n\t\tinc count\n\t\techo ($count).align(2), ' ', word\n" + }, + { + "id": 351, + "length": 274, + "source": "Rosetta Code", + "text": "import math, strutils\n\nproc divisors(n: Positive): seq[int] =\n\tfor d in 1..sqrt(n.toFloat).int:\n\t\tif n mod d == 0:\n\t\t\tresult.add d\n\t\t\tif n div d != d:\n\t\t\t\tresult.add n div d\n\nfor n in 1..100:\n\tstdout.write ($sum(n.divisors)).align(3), if (n + 1) mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 352, + "length": 147, + "source": "Rosetta Code", + "text": "for a in [@[1, 2, 0], @[3, 4, -1, 1], @[7, 8, 9, 11, 12], @[-5, -2, -6, -1]]:\n\tfor n in 1..int.high:\n\t\tif n notin a:\n\t\t\techo a, \" -> \", n\n\t\t\tbreak\n" + }, + { + "id": 353, + "length": 216, + "source": "Rosetta Code", + "text": "import algorithm, sequtils\n\nproc commonSortedList(list: openArray[seq[int]]): seq[int] =\n\tlist.concat().sorted().deduplicate(true)\n\necho commonSortedList([@[5, 1, 3, 8, 9, 4, 8, 7], @[3, 5, 9, 8, 4], @[1, 3, 7, 9]])\n" + }, + { + "id": 354, + "length": 275, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\nproc rn(n, k: Positive): seq[int] =\n\tassert k >= 2\n\tresult = if n == 2: @[1, 1, 1] else: rn(n - 1, n + 1)\n\twhile result.len != k:\n\t\tresult.add sum(result[^(n + 1)..^2])\n\nfor n in 2..8:\n\techo n, \": \", rn(n, 15).mapIt(($it).align(3)).join(\" \")\n" + }, + { + "id": 355, + "length": 219, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc isConcat(s: string): bool =\n\tif (s.len and 1) != 0: return false\n\tlet half = s.len shr 1\n\tresult = s[0..= 50: break\n\tlist.add n\n\necho list.join(\" \")\n" + }, + { + "id": 360, + "length": 127, + "source": "Rosetta Code", + "text": "import strutils\n\nvar s = 0\nfor n in 0..49:\n\ts += n * n * n\n\tstdout.write ($s).align(7), if (n + 1) mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 361, + "length": 249, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc largestProperDivisor(n: Positive): int =\n\tfor d in 2..sqrt(float(n)).int:\n\t\tif n mod d == 0: return n div d\n\tresult = 1\n\nfor n in 1..100:\n\tstdout.write ($n.largestProperDivisor).align(2), if n mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 362, + "length": 279, + "source": "Rosetta Code", + "text": "import strutils, std/monotimes\nimport bignum\n\nlet t0 = getMonoTime()\nvar sum = 0.0\nvar f = newInt(1)\nvar lim = 100\nfor n in 1..10_000:\n\tf *= n\n\tlet str = $f\n\tsum += str.count('0') / str.len\n\tif n == lim:\n\t\techo n, \":\\t\", sum / float(n)\n\t\tlim *= 10\necho()\necho getMonoTime() - t0\n" + }, + { + "id": 363, + "length": 177, + "source": "Rosetta Code", + "text": "import sugar, strutils\n\nlet result = collect(newSeq):\n\t\t\t\t\t\t\t for n in 1..<1000:\n\t\t\t\t\t\t\t\t if count($n, '1') == 2: n\necho \"Found \", result.len, \" numbers:\"\necho result.join(\" \")\n" + }, + { + "id": 364, + "length": 275, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for n in 0..500:\n\t\t\t\t\t\t\t if not n.toHex.allCharsInSet(Digits): n\n\necho \"Found \", list.len, \" numbers between 0 and 500:\\n\"\nfor i, n in list:\n\tstdout.write ($n).align(3), if (i + 1) mod 19 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 365, + "length": 175, + "source": "Rosetta Code", + "text": "import algorithm, math, sequtils, strutils, sugar\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for a in 2..5:\n\t\t\t\t\t\t\t for b in 2..5: a^b\n\necho sorted(list).deduplicate(true).join(\" \")\n" + }, + { + "id": 366, + "length": 178, + "source": "Rosetta Code", + "text": "type Vector = tuple[x, y, z: float]\n\nfunc `+`(a, b: Vector): Vector = (a.x + b.x, a.y + b.y, a.z + b.z)\n\necho (1.0, 2.0, 3.0) + (4.0, 5.0, 6.0) # print (x: 5.0, y: 7.0, z: 9.0)\n" + }, + { + "id": 367, + "length": 251, + "source": "Rosetta Code", + "text": "const\n\tNumbers1 = [ 5, 45, 23, 21, 67]\n\tNumbers2 = [43, 22, 78, 46, 38]\n\tNumbers3 = [ 9, 98, 12, 98, 53]\n\nvar numbers: array[0..Numbers1.high, int]\n\nfor i in 0..numbers.high:\n\tnumbers[i] = min(min(Numbers1[i], Numbers2[i]), Numbers3[i])\n\necho numbers\n" + }, + { + "id": 368, + "length": 105, + "source": "Rosetta Code", + "text": "import std/math\n\nconst n = 1e6\nvar result = 1.0\n\nfor i in 2..int(n):\n\tresult += 1/i\n\necho result - ln(n)\n" + }, + { + "id": 369, + "length": 131, + "source": "Rosetta Code", + "text": "proc rand:int =\n\tvar seed {.global.} = 675248\n\tseed = int(seed*seed) div 1000 mod 1000000\n\treturn seed\n\nfor _ in 1..5: echo rand()\n" + }, + { + "id": 370, + "length": 230, + "source": "Rosetta Code", + "text": "import strutils\n\nproc rot13(c: char): char =\n\tcase toLowerAscii(c)\n\tof 'a'..'m': chr(ord(c) + 13)\n\tof 'n'..'z': chr(ord(c) - 13)\n\telse: c\n\nfor line in stdin.lines:\n\tfor c in line:\n\t\tstdout.write rot13(c)\n\tstdout.write \"\\n\"\n" + }, + { + "id": 371, + "length": 302, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio]\n\nproc activate(app: Application) =\n\tlet window = newApplicationWindow(app)\n\twindow.setTitle(\"Window\")\n\twindow.setSizeRequest(640, 480)\n\twindow.showAll()\n\nlet app = newApplication(Application, \"Window\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 372, + "length": 316, + "source": "Rosetta Code", + "text": "{.experimental.}\nimport wx\n\nconst\n\tTITLE = \"Window Creation in Nim\"\n\tWIDTH = 300\n\tHEIGHT = 300\n\nlet\n\tPOSITION = construct_wxPoint(100,100)\n\tSIZE = construct_wxSize(WIDTH,HEIGHT)\n\nlet window = cnew construct_wxFrame(nil, wxID_ANY, TITLE, POSITION, SIZE)\n\nwindow.show(true)\n\nrun_main_loop()\n" + }, + { + "id": 373, + "length": 544, + "source": "Rosetta Code", + "text": "import sequtils\n\nlet values = toSeq(0..9)\n\n# Filtering by returning a new sequence.\n# - using an explicit filtering procedure.\necho \"Even values: \", values.filter(proc(x: int): bool = x mod 2 == 0)\n# - using a predicate.\necho \"Odd values: \", values.filterIt(it mod 2 == 1)\n\n# Filtering by modifying the sequence.\n\n# - using an explicit filtering procedure.\nvar v1 = toSeq(0..9)\nv1.keepIf(proc(x: int): bool = x mod 2 == 0)\necho \"Even values: \", v1\n\n# - using a predicate.\nvar v2 = toSeq(0..9)\nv2.keepItIf(it mod 2 != 0)\necho \"Odd values: \", v2\n" + }, + { + "id": 374, + "length": 401, + "source": "Rosetta Code", + "text": "import db_sqlite as db\n#import db_mysql as db\n#import db_postgres as db\n\nconst\n\tconnection = \":memory:\"\n\tuser = \"foo\"\n\tpass = \"bar\"\n\tdatabase = \"db\"\n\nvar c = open(connection, user, pass, database)\nc.exec sql\"\"\"CREATE TABLE address (\n\taddrID INTEGER PRIMARY KEY AUTOINCREMENT,\n\taddrStreet TEXT NOT NULL,\n\taddrCity TEXT NOT NULL,\n\taddrState TEXT NOT NULL,\n\taddrZIP TEXT NOT NULL)\"\"\"\nc.close()\n" + }, + { + "id": 375, + "length": 305, + "source": "Rosetta Code", + "text": "import xmldom\n\nvar\n\tdom = getDOM()\n\tdocument = dom.createDocument(\"\", \"root\")\n\ttopElement = document.documentElement\n\tfirstElement = document.createElement \"element\"\n\ttextNode = document.createTextNode \"Some text here\"\n\ntopElement.appendChild firstElement\nfirstElement.appendChild textNode\n\necho document\n" + }, + { + "id": 376, + "length": 557, + "source": "Rosetta Code", + "text": "var msgs: Channel[string]\nvar count: Channel[int]\n\nconst FILE = \"input.txt\"\n\nproc read() {.thread.} =\n\tfor line in FILE.lines:\n\t\tmsgs.send(line)\n\tmsgs.send(\"\")\n\techo count.recv()\n\tcount.close()\n\nproc print() {.thread.} =\n\tvar n = 0\n\twhile true:\n\t\tvar msg = msgs.recv()\n\t\tif msg.len == 0:\n\t\t\tbreak\n\t\techo msg\n\t\tn += 1\n\tmsgs.close()\n\tcount.send(n)\n\nvar reader_thread = Thread[void]()\nvar printer_thread = Thread[void]()\n\nmsgs.open()\ncount.open()\ncreateThread(reader_thread, read)\ncreateThread(printer_thread, print)\njoinThreads(reader_thread, printer_thread)\n" + }, + { + "id": 377, + "length": 520, + "source": "Rosetta Code", + "text": "import gtk2\n\nnim_init()\n\nvar\n\twin = windowNew WINDOW_TOPLEVEL\n\tbutton = buttonNew \"Click me\"\n\tlabel = labelNew \"There have been no clicks yet\"\n\tvbox = vboxNew(true, 1)\n\tcounter = 0\n\nproc clickedMe(o: var PButton, l: PLabel) =\n\tinc counter\n\tl.setText \"You clicked me \" & $counter & \" times\"\n\nwin.setTitle \"Click me\"\nvbox.add label\nvbox.add button\nwin.add vbox\ndiscard win.signal_connect(\"delete-event\", SignalFunc mainQuit, nil)\ndiscard button.signal_connect(\"clicked\", SignalFunc clickedMe, label)\nwin.showAll()\nmain()\n" + }, + { + "id": 378, + "length": 368, + "source": "Rosetta Code", + "text": "import strutils, rdstdin\n\nlet\n\tw = readLineFromStdin(\"Width: \").parseInt()\n\th = readLineFromStdin(\"Height: \").parseInt()\n\n# Create the rows.\nvar s = newSeq[seq[int]](h)\n\n# Create the columns.\nfor i in 0 ..< h:\n\ts[i].newSeq(w)\n\n# Store a value in an element.\ns[0][0] = 5\n\n# Retrieve and print it.\necho s[0][0]\n\n# The allocated memory is freed by the garbage collector.\n" + }, + { + "id": 379, + "length": 441, + "source": "Rosetta Code", + "text": "type\n\trs232Data = enum\n\t\tcarrierDetect,\n\t\treceivedData,\n\t\ttransmittedData,\n\t\tdataTerminalReady,\n\t\tsignalGround,\n\t\tdataSetReady,\n\t\trequestToSend,\n\t\tclearToSend,\n\t\tringIndicator\n\n# Bit vector of 9 bits\nvar bv = {carrierDetect, signalGround, ringIndicator}\necho cast[uint16](bv) # Conversion of bitvector to 2 bytes for writing\n\nlet readValue: uint16 = 123\nbv = cast[set[rs232Data]](readValue) # Conversion of a read value to bitvector\necho bv\n" + }, + { + "id": 380, + "length": 520, + "source": "Rosetta Code", + "text": "import marshal, streams\n\ntype\n\tBase = object of RootObj\n\t\tname: string\n\tDescendant = object of Base\nproc newBase(): Base = Base(name: \"base\")\nproc newDescendant(): Descendant = Descendant(name: \"descend\")\nproc print(obj: Base) =\n\techo(obj.name)\n\nvar\n\tbase = newBase()\n\tdescendant = newDescendant()\nprint(base)\nprint(descendant)\n\nvar strm = newFileStream(\"objects.dat\", fmWrite)\nstore(strm, (base, descendant))\nstrm.close()\n\nvar t: (Base, Descendant)\nload(newFileStream(\"objects.dat\", fmRead), t)\nprint(t[0])\nprint(t[1])\n" + }, + { + "id": 381, + "length": 384, + "source": "Rosetta Code", + "text": "import os, strutils, times\n\nif paramCount() == 0: quit(QuitSuccess)\nlet fileName = paramStr(1)\n\n# Get and display last modification time.\nvar mtime = fileName.getLastModificationTime()\necho \"File \\\"$1\\\" last modification time: $2\".format(fileName, mtime.format(\"YYYY-MM-dd HH:mm:ss\"))\n\n# Change last modification time to current time.\nfileName.setLastModificationTime(now().toTime())\n" + }, + { + "id": 382, + "length": 549, + "source": "Rosetta Code", + "text": "proc quickSortImpl[T](a: var openarray[T], start, stop: int) =\n\tif stop - start > 0:\n\t\tlet pivot = a[start]\n\t\tvar left = start\n\t\tvar right = stop\n\t\twhile left <= right:\n\t\t\twhile cmp(a[left], pivot) < 0:\n\t\t\t\tinc(left)\n\t\t\twhile cmp(a[right], pivot) > 0:\n\t\t\t\tdec(right)\n\t\t\tif left <= right:\n\t\t\t\tswap(a[left], a[right])\n\t\t\t\tinc(left)\n\t\t\t\tdec(right)\n\t\tquickSortImpl(a, start, right)\n\t\tquickSortImpl(a, left, stop)\n\nproc quickSort[T](a: var openarray[T]) =\n\tquickSortImpl(a, 0, a.len - 1)\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\na.quickSort()\necho a\n" + }, + { + "id": 383, + "length": 317, + "source": "Rosetta Code", + "text": "import macros\nmacro FizzBuzz(N): untyped =\n\tvar source = \"\"\n\tfor i in 1..N.intVal:\n\t\tsource &= \"echo \\\"\"\n\t\tif i mod 15 == 0:\n\t\t\tsource &= \"FizzBuzz\"\n\t\telif i mod 3 == 0:\n\t\t\tsource &= \"Fizz\"\n\t\telif i mod 5 == 0:\n\t\t\tsource &= \"Buzz\"\n\t\telse:\n\t\t\tsource &= $i\n\t\tsource &= \"\\\"\\n\"\n\tresult = parseStmt(source)\n\nFizzBuzz(100)\n" + }, + { + "id": 384, + "length": 400, + "source": "Rosetta Code", + "text": "from strutils import `%`\n\nconst numDoors = 100\nvar doors {.compileTime.}: array[1..numDoors, bool]\n\nproc calcDoors(): string =\n\tfor pass in 1..numDoors:\n\t\tfor door in countup(pass, numDoors, pass):\n\t\t\tdoors[door] = not doors[door]\n\tfor door in 1..numDoors:\n\t\tresult.add(\"Door $1 is $2.\\n\" % [$door, if doors[door]: \"open\" else: \"closed\"])\n\nconst outputString: string = calcDoors()\n\necho outputString\n" + }, + { + "id": 385, + "length": 570, + "source": "Rosetta Code", + "text": "iterator isoe_upto(top: uint): uint =\n\tlet topndx = int((top - 3) div 2)\n\tlet sqrtndx = (int(sqrt float64(top)) - 3) div 2\n\tvar cmpsts = newSeq[uint32](topndx div 32 + 1)\n\tfor i in 0 .. sqrtndx: # cull composites for primes\n\t\tif (cmpsts[i shr 5] and (1u32 shl (i and 31))) == 0:\n\t\t\tlet p = i + i + 3\n\t\t\tfor j in countup((p * p - 3) div 2, topndx, p):\n\t\t\t\tcmpsts[j shr 5] = cmpsts[j shr 5] or (1u32 shl (j and 31))\n\tyield 2 # separate culling above and iteration here\n\tfor i in 0 .. topndx:\n\t\tif (cmpsts[i shr 5] and (1u32 shl (i and 31))) == 0:\n\t\t\tyield uint(i + i + 3)\n" + }, + { + "id": 386, + "length": 382, + "source": "Rosetta Code", + "text": "type Node[T] = ref object\n\tnext: Node[T]\n\tdata: T\n\nproc newNode[T](data: T): Node[T] =\n\tNode[T](data: data)\n\nvar a = newNode 12\nvar b = newNode 13\nvar c = newNode 14\n\nproc insertAppend(a, n: var Node) =\n\tn.next = a.next\n\ta.next = n\n\na.insertAppend(b)\nb.insertAppend(c)\n\niterator items(a: Node) =\n\tvar x = a\n\twhile not x.isNil:\n\t\tyield x\n\t\tx = x.next\n\nfor item in a:\n\techo item.data\n" + }, + { + "id": 387, + "length": 442, + "source": "Rosetta Code", + "text": "import os, posix\n\nlet fn = getHomeDir() & \"lock\"\nproc ooiUnlink {.noconv.} = discard unlink fn\n\nproc onlyOneInstance =\n\tvar fl = TFlock(lType: F_WRLCK.cshort, lWhence: SEEK_SET.cshort)\n\tvar fd = getFileHandle fn.open fmReadWrite\n\tif fcntl(fd, F_SETLK, addr fl) < 0:\n\t\tstderr.writeLine \"Another instance of this program is running\"\n\t\tquit 1\n\taddQuitProc ooiUnlink\n\nonlyOneInstance()\n\nfor i in countdown(10, 1):\n\techo i\n\tsleep 1000\necho \"Fin!\"\n" + }, + { + "id": 388, + "length": 514, + "source": "Rosetta Code", + "text": "import sequtils, math\n\nproc prime(a: int): bool =\n\tif a == 2: return true\n\tif a < 2 or a mod 2 == 0: return false\n\tfor i in countup(3, sqrt(a.float).int, 2):\n\t\tif a mod i == 0:\n\t\t\treturn false\n\treturn true\n\nproc prime2(a: int): bool =\n\tresult = not (a < 2 or any(toSeq(2 .. sqrt(a.float).int), a mod it == 0))\n\nproc prime3(a: int): bool =\n\tif a == 2: return true\n\tif a < 2 or a mod 2 == 0: return false\n\treturn not any(toSeq countup(3, sqrt(a.float).int, 2), a mod it == 0)\n\nfor i in 2..30:\n\techo i, \" \", prime(i)\n" + }, + { + "id": 389, + "length": 346, + "source": "Rosetta Code", + "text": "iterator comb(m, n: int): seq[int] =\n\tvar c = newSeq[int](n)\n\tfor i in 0 ..< n: c[i] = i\n\n\tblock outer:\n\t\twhile true:\n\t\t\tyield c\n\n\t\t\tvar i = n - 1\n\t\t\tinc c[i]\n\t\t\tif c[i] <= m - 1: continue\n\n\t\t\twhile c[i] >= m - n + i:\n\t\t\t\tdec i\n\t\t\t\tif i < 0: break outer\n\t\t\tinc c[i]\n\t\t\twhile i < n-1:\n\t\t\t\tc[i+1] = c[i] + 1\n\t\t\t\tinc i\n\nfor i in comb(5, 3):\n\techo i\n" + }, + { + "id": 390, + "length": 368, + "source": "Rosetta Code", + "text": "iterator combinations(m: int, n: int): seq[int] =\n\n\tvar result = newSeq[int](n)\n\tvar stack = newSeq[int]()\n\tstack.add 0\n\n\twhile stack.len > 0:\n\t\tvar index = stack.high\n\t\tvar value = stack.pop()\n\n\t\twhile value < m:\n\t\t\tresult[index] = value\n\t\t\tinc value\n\t\t\tinc index\n\t\t\tstack.add value\n\n\t\t\tif index == n:\n\t\t\t\tyield result\n\t\t\t\tbreak\n\nfor i in combinations(5, 3):\n\techo i\n" + }, + { + "id": 391, + "length": 324, + "source": "Rosetta Code", + "text": "import complex, math, sequtils, strformat, strutils\n\nproc roots(n: Positive): seq[Complex64] =\n\tfor k in 0.. 0: difn(dif(s), n-1)\n\telse: s\n\nconst s = @[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]\necho difn(s, 0)\necho difn(s, 1)\necho difn(s, 2)\n" + }, + { + "id": 393, + "length": 510, + "source": "Rosetta Code", + "text": "template isEven(n: int64): bool = (n and 1) == 0\n\nfunc gcd_binary*(u, v: int64): int64 =\n\n\tvar u = abs(u)\n\tvar v = abs(v)\n\tif u < v: swap u, v\n\n\tif v == 0: return u\n\n\tvar k = 1\n\twhile u.isEven and v.isEven:\n\t\tu = u shr 1\n\t\tv = v shr 1\n\t\tk = k shl 1\n\tvar t = if u.isEven: u else: -v\n\twhile t != 0:\n\t\twhile t.isEven: t = ashr(t, 1)\n\t\tif t > 0: u = t\n\t\telse: v = -t\n\t\tt = u - v\n\tresult = u * k\n\nwhen isMainModule:\n\timport strformat\n\tlet (x, y) = (49865, 69811)\n\techo &\"gcd({x}, {y}) = {gcd_binary(49865, 69811)}\"\n" + }, + { + "id": 394, + "length": 435, + "source": "Rosetta Code", + "text": "import strutils, math, sequtils\n\nconst OutFileName = \"floatarr2file.txt\"\n\nconst\n\t XPrecision = 3\n\t Yprecision = 5\n\nlet a = [1.0, 2.0, 3.0, 100_000_000_000.0]\nlet b = [sqrt(a[0]), sqrt(a[1]), sqrt(a[2]), sqrt(a[3])]\nvar res = \"\"\nfor t in zip(a, b):\n\t\tres.add formatFloat(t[0], ffDefault, Xprecision) & \" \" &\n\t\t\t\t\t\tformatFloat(t[1], ffDefault, Yprecision) & \"\\n\"\n\nOutFileName.writeFile res\nvar res2 = OutFileName.readFile()\necho res2\n" + }, + { + "id": 395, + "length": 296, + "source": "Rosetta Code", + "text": "import ggplotnim\n\nlet\n\tx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ty = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]\n\nlet df = seqsToDf(x, y) # Build a dataframe.\n\ndf.ggplot(aes(\"x\", \"y\")) +\n\tggtitle(\"Coordinate pairs\") +\n\tgeomLine() +\n\tthemeOpaque() +\n\tggsave(\"coordinate_pairs.png\")\n" + }, + { + "id": 396, + "length": 307, + "source": "Rosetta Code", + "text": "proc transpose[X, Y; T](s: array[Y, array[X, T]]): array[X, array[Y, T]] =\n\tfor i in low(X)..high(X):\n\t\tfor j in low(Y)..high(Y):\n\t\t\tresult[i][j] = s[j][i]\n\nlet b = [[ 0, 1, 2, 3, 4],\n\t\t\t\t [ 5, 6, 7, 8, 9],\n\t\t\t\t [ 1, 0, 0, 0,42]]\nlet c = transpose(b)\nfor r in c:\n\tfor i in r:\n\t\tstdout.write i, \" \"\n\techo \"\"\n" + }, + { + "id": 397, + "length": 290, + "source": "Rosetta Code", + "text": "proc transpose[T](s: seq[seq[T]]): seq[seq[T]] =\n\tresult = newSeq[seq[T]](s[0].len)\n\tfor i in 0 .. s[0].high:\n\t\tresult[i] = newSeq[T](s.len)\n\t\tfor j in 0 .. s.high:\n\t\t\tresult[i][j] = s[j][i]\n\nlet a = @[@[ 0, 1, 2, 3, 4],\n\t\t\t\t\t@[ 5, 6, 7, 8, 9],\n\t\t\t\t\t@[ 1, 0, 0, 0, 42]]\necho transpose(a)\n" + }, + { + "id": 398, + "length": 520, + "source": "Rosetta Code", + "text": "import math\n\nproc isPrime(a: int): bool =\n\tif a == 2: return true\n\tif a < 2 or a mod 2 == 0: return false\n\tfor i in countup(3, int sqrt(float a), 2):\n\t\tif a mod i == 0:\n\t\t\treturn false\n\treturn true\n\nproc isMersennePrime(p: int): bool =\n\tif p == 2: return true\n\tlet mp = (1'i64 shl p) - 1\n\tvar s = 4'i64\n\tfor i in 3 .. p:\n\t\ts = (s * s - 2) mod mp\n\tresult = s == 0\n\nlet upb = int((log2 float int64.high) / 2)\necho \" Mersenne primes:\"\nfor p in 2 .. upb:\n\tif isPrime(p) and isMersennePrime(p):\n\t\tstdout.write \" M\",p\necho \"\"\n" + }, + { + "id": 399, + "length": 442, + "source": "Rosetta Code", + "text": "proc `^`[T: float|int](base: T; exp: int): T =\n\tvar (base, exp) = (base, exp)\n\tresult = 1\n\n\tif exp < 0:\n\t\twhen T is int:\n\t\t\tif base * base != 1: return 0\n\t\t\telif (exp and 1) == 0: return 1\n\t\t\telse: return base\n\t\telse:\n\t\t\tbase = 1.0 / base\n\t\t\texp = -exp\n\n\twhile exp != 0:\n\t\tif (exp and 1) != 0:\n\t\t\tresult *= base\n\t\texp = exp shr 1\n\t\tbase *= base\n\necho \"2^6 = \", 2^6\necho \"2^-6 = \", 2 ^ -6\necho \"2.71^6 = \", 2.71^6\necho \"2.71^-6 = \", 2.71 ^ -6\n" + }, + { + "id": 400, + "length": 338, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\nfunc f(x: float): float = x ^ 3 - 3 * x ^ 2 + 2 * x\n\nvar\n\tstep = 0.01\n\tstart = -1.0\n\tstop = 3.0\n\tsign = f(start) > 0\n\tx = start\n\nwhile x <= stop:\n\tvar value = f(x)\n\n\tif value == 0:\n\t\techo fmt\"Root found at {x:.5f}\"\n\telif (value > 0) != sign:\n\t\techo fmt\"Root found near {x:.5f}\"\n\n\tsign = value > 0\n\tx += step\n" + }, + { + "id": 401, + "length": 336, + "source": "Rosetta Code", + "text": "import math\n\nproc inCarpet(x, y: int): bool =\n\tvar x = x\n\tvar y = y\n\twhile true:\n\t\tif x == 0 or y == 0:\n\t\t\treturn true\n\t\tif x mod 3 == 1 and y mod 3 == 1:\n\t\t\treturn false\n\t\tx = x div 3\n\t\ty = y div 3\n\nproc carpet(n: int) =\n\tfor i in 0 ..< 3^n:\n\t\tfor j in 0 ..< 3^n:\n\t\t\tstdout.write if inCarpet(i, j): \"* \" else: \" \"\n\t\techo()\n\ncarpet(3)\n" + }, + { + "id": 402, + "length": 455, + "source": "Rosetta Code", + "text": "import sequtils\n\nproc ncsub[T](se: seq[T], s = 0): seq[seq[T]] =\n\tresult = @[]\n\tif se.len > 0:\n\t\tlet\n\t\t\tx = se[0..0]\n\t\t\txs = se[1 .. ^1]\n\t\t\tp2 = s mod 2\n\t\t\tp1 = (s + 1) mod 2\n\t\tfor ys in ncsub(xs, s + p1):\n\t\t\tresult.add(x & ys)\n\t\tresult.add(ncsub(xs, s + p2))\n\telif s >= 3:\n\t\tresult.add(@[])\n\necho \"ncsub(\", toSeq 1.. 3, \") = \", ncsub(toSeq 1..3)\necho \"ncsub(\", toSeq 1.. 4, \") = \", ncsub(toSeq 1..4)\necho \"ncsub(\", toSeq 1.. 5, \") = \", ncsub(toSeq 1..5)\n" + }, + { + "id": 403, + "length": 304, + "source": "Rosetta Code", + "text": "type\n\tCamera = ref object of RootObj\n\tMobilePhone = ref object of RootObj\n\tCameraPhone = object\n\t\tcamera: Camera\n\t\tphone: MobilePhone\nproc `is`(cp: CameraPhone, t: typedesc): bool =\n\tfor field in cp.fields():\n\t\tif field of t:\n\t\t\treturn true\nvar cp: CameraPhone\necho(cp is Camera)\necho(cp is MobilePhone)\n" + }, + { + "id": 404, + "length": 294, + "source": "Rosetta Code", + "text": "import random\n\nrandomize()\n\nproc isSorted[T](s: openarray[T]): bool =\n\tvar last = low(T)\n\tfor c in s:\n\t\tif c < last:\n\t\t\treturn false\n\t\tlast = c\n\treturn true\n\nproc bogoSort[T](a: var openarray[T]) =\n\twhile not isSorted a: shuffle a\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nbogoSort a\necho a\n" + }, + { + "id": 405, + "length": 312, + "source": "Rosetta Code", + "text": "proc lcs(x, y: string): string =\n\tif x == \"\" or y == \"\":\n\t\treturn \"\"\n\n\tif x[0] == y[0]:\n\t\treturn x[0] & lcs(x[1..x.high], y[1..y.high])\n\n\tlet a = lcs(x, y[1..y.high])\n\tlet b = lcs(x[1..x.high], y)\n\tresult = if a.len > b.len: a else: b\n\necho lcs(\"1234\", \"1224533324\")\necho lcs(\"thisisatest\", \"testing123testing\")\n" + }, + { + "id": 406, + "length": 405, + "source": "Rosetta Code", + "text": "import sets, hashes\n\nproc hash(x: HashSet[int]): Hash =\n\tvar h = 0\n\tfor i in x: h = h !& hash(i)\n\tresult = !$h\n\nproc powerset[T](inset: HashSet[T]): HashSet[HashSet[T]] =\n\tresult.incl(initHashSet[T]()) # Initialized with empty set.\n\tfor val in inset:\n\t\tlet previous = result\n\t\tfor aSet in previous:\n\t\t\tvar newSet = aSet\n\t\t\tnewSet.incl(val)\n\t\t\tresult.incl(newSet)\n\necho powerset([1, 2, 3, 4].toHashSet())\n" + }, + { + "id": 407, + "length": 418, + "source": "Rosetta Code", + "text": "const ROWS = 10\nconst TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression\nvar triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations\n\nproc printPascalTri(row: Natural, result: var seq[Natural]) =\n\tadd(result, 1)\n\tfor i in 2..row-1: add(result, result[^row] + result[^(row-1)])\n\tadd(result, 1)\n\n\techo result[^row..^1]\n\tif row + 1 <= ROWS: printPascalTri(row + 1, result)\n\nprintPascalTri(1, triangle)\n" + }, + { + "id": 408, + "length": 476, + "source": "Rosetta Code", + "text": "proc c2v(c: char): int =\n\tassert c notin \"AEIOU\"\n\tif c < 'A': ord(c) - ord('0') else: ord(c) - ord('7')\n\nconst weight = [1, 3, 1, 7, 3, 9]\n\nproc checksum(sedol: string): char =\n\tvar val = 0\n\tfor i, ch in sedol:\n\t\tval += c2v(ch) * weight[i]\n\tresult = chr((10 - val mod 10) mod 10 + ord('0'))\n\nfor sedol in [\"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\",\n\t\t\t\t\t\t\t\"228276\", \"B0YBKL\", \"557910\", \"B0YBKR\",\n\t\t\t\t\t\t\t\"585284\", \"B0YBKT\", \"B00030\"]:\n\techo sedol, \" -> \", sedol & checksum(sedol)\n" + }, + { + "id": 409, + "length": 581, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc sumTo(n: Natural): Natural = n * (n+1) div 2\n\nfunc coord2num(row, col, N: Natural): Natural =\n\tvar start, offset: Natural\n\tlet diag = col + row\n\tif diag < N:\n\t\tstart = sumTo(diag)\n\t\toffset = if diag mod 2 == 0: col else: row\n\telse:\n\t\t# N * (2*diag+1-N) - sumTo(diag), but with smaller itermediates\n\t\tstart = N*N - sumTo(2*N-1-diag)\n\t\toffset = N-1 - (if diag mod 2 == 0: row else: col)\n\tstart + offset\n\nlet N = 6\nlet width = (N*N).`$`.len + 1\nfor row in 0 ..< N:\n\tfor col in 0 ..< N:\n\t\tstdout.write(coord2num(row, col, N).`$`.align(width))\n\tstdout.write(\"\\n\")\n" + }, + { + "id": 410, + "length": 526, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nproc `$`(m: seq[seq[int]]): string =\n\tfor r in m:\n\t\tlet lg = result.len\n\t\tfor c in r:\n\t\t\tresult.addSep(\" \", lg)\n\t\t\tresult.add align($c, 2)\n\t\tresult.add '\\n'\n\nproc spiral(n: Positive): seq[seq[int]] =\n\tresult = newSeqWith(n, repeat(-1, n))\n\tvar dx = 1\n\tvar dy, x, y = 0\n\tfor i in 0 ..< (n * n):\n\t\tresult[y][x] = i\n\t\tlet (nx, ny) = (x+dx, y+dy)\n\t\tif nx in 0 ..< n and ny in 0 ..< n and result[ny][nx] == -1:\n\t\t\tx = nx\n\t\t\ty = ny\n\t\telse:\n\t\t\tswap dx, dy\n\t\t\tdx = -dx\n\t\t\tx += dx\n\t\t\ty += dy\n\necho spiral(5)\n" + }, + { + "id": 411, + "length": 345, + "source": "Rosetta Code", + "text": "import httpclient, strutils\n\nvar client = newHttpClient()\n\nvar res: string\nfor line in client.getContent(\"https://en.wikipedia.org/wiki/Talk:Web_scraping\").splitLines:\n\tlet k = line.find(\"UTC\")\n\tif k >= 0:\n\t\tres = line[0..(k - 3)]\n\t\tlet k = res.rfind(\"\")\n\t\tres = res[(k + 6)..^1]\n\t\tbreak\necho if res.len > 0: res else: \"No date/time found.\"\n" + }, + { + "id": 412, + "length": 377, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc nosqr(n: int): seq[int] =\n\tresult = newSeq[int](n)\n\tfor i in 1..n:\n\t\tresult[i - 1] = i + i.float.sqrt.toInt\n\nfunc issqr(n: int): bool =\n\tsqrt(float(n)).splitDecimal().floatpart < 1e-7\n\necho \"Sequence for n = 22:\"\necho nosqr(22).join(\" \")\n\nfor i in nosqr(1_000_000 - 1):\n\tassert not issqr(i)\necho \"\\nNo squares were found for n less than 1_000_000.\"\n" + }, + { + "id": 413, + "length": 380, + "source": "Rosetta Code", + "text": "import tables, strutils, algorithm\n\nproc main() =\n\t\tvar\n\t\t\t\tcount = 0\n\t\t\t\tanagrams = initTable[string, seq[string]]()\n\n\t\tfor word in \"unixdict.txt\".lines():\n\t\t\t\tvar key = word\n\t\t\t\tkey.sort(cmp[char])\n\t\t\t\tanagrams.mgetOrPut(key, newSeq[string]()).add(word)\n\t\t\t\tcount = max(count, anagrams[key].len)\n\n\t\tfor _, v in anagrams:\n\t\t\t\tif v.len == count:\n\t\t\t\t\t\tv.join(\" \").echo\n\nmain()\n" + }, + { + "id": 414, + "length": 377, + "source": "Rosetta Code", + "text": "import strutils\n\nvar\n\tcurOut = 0\n\tmaxOut = -1\n\tmaxTimes = newSeq[string]()\n\nfor job in lines \"mlijobs.txt\":\n\tif \"OUT\" in job: inc curOut else: dec curOut\n\tif curOut > maxOut:\n\t\tmaxOut = curOut\n\t\tmaxTimes.setLen(0)\n\tif curOut == maxOut:\n\t\tmaxTimes.add job.split[3]\n\necho \"Maximum simultaneous license use is \", maxOut, \" at the following times:\"\nfor i in maxTimes: echo \" \", i\n" + }, + { + "id": 415, + "length": 544, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\ts_init: string = \"_###_##_#_#_#_#__#__\"\n\tarrLen: int = 20\n\nvar q0: string = s_init & repeat('_',arrLen-20)\nvar q1: string = q0\n\nproc life(s: string): char =\n\t var str: string = s\n\t if len(normalize(str)) == 2: # normalize eliminates underscores\n\t\t\treturn '#'\n\t return '_'\n\nproc evolve(q: string): string =\n\t result = repeat('_',arrLen)\n\t #result[0] = '_'\n\t for i in 1 .. q.len-1:\n\t\t\tresult[i] = life(substr(q & '_',i-1,i+1))\n\necho(q1)\nq1 = evolve(q0)\necho(q1)\nwhile q1 != q0:\n\t q0 = q1\n\t q1 = evolve(q0)\n\t echo(q1)\n" + }, + { + "id": 416, + "length": 450, + "source": "Rosetta Code", + "text": "proc cellAutomata =\n\tproc evolveInto(x, t : var string) =\n\t\tfor i in x.low..x.high:\n\t\t\tlet\n\t\t\t\talive = x[i] == 'o'\n\t\t\t\tleft = if i == x.low: false else: x[i - 1] == 'o'\n\t\t\t\tright = if i == x.high: false else: x[i + 1] == 'o'\n\t\t\tt[i] =\n\t\t\t\tif alive: (if left xor right: 'o' else: '.')\n\t\t\t\telse: (if left and right: 'o' else: '.')\n\n\tvar\n\t\tx = \".ooo.oo.o.o.o.o..o..\"\n\t\tt = x\n\n\tfor i in 1..10:\n\t\tx.echo\n\t\tx.evolveInto t\n\t\tswap t, x\n\ncellAutomata()\n" + }, + { + "id": 417, + "length": 328, + "source": "Rosetta Code", + "text": "template trySwap(): untyped =\n\tif a[i] < a[i-1]:\n\t\tswap a[i], a[i-1]\n\t\tt = false\n\nproc cocktailSort[T](a: var openarray[T]) =\n\tvar t = false\n\tvar l = a.len\n\twhile not t:\n\t\tt = true\n\t\tfor i in 1 ..< l: trySwap\n\t\tif t: break\n\t\tfor i in countdown(l-1, 1): trySwap\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\ncocktailSort a\necho a\n" + }, + { + "id": 418, + "length": 338, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\nfunc f(x: float): float = x ^ 3 - 3 * x ^ 2 + 2 * x\n\nvar\n\tstep = 0.01\n\tstart = -1.0\n\tstop = 3.0\n\tsign = f(start) > 0\n\tx = start\n\nwhile x <= stop:\n\tvar value = f(x)\n\n\tif value == 0:\n\t\techo fmt\"Root found at {x:.5f}\"\n\telif (value > 0) != sign:\n\t\techo fmt\"Root found near {x:.5f}\"\n\n\tsign = value > 0\n\tx += step\n" + }, + { + "id": 419, + "length": 398, + "source": "Rosetta Code", + "text": "type\n\tEatable = concept e\n\t\teat(e)\n\n\tFoodBox[e: Eatable] = seq[e]\n\n\tFood = object\n\t\tname: string\n\t\tcount: int\n\nproc eat(x: int) = echo \"Eating the int: \", x\nproc eat(x: Food) = echo \"Eating \", x.count, \" \", x.name, \"s\"\n\nvar ints = FoodBox[int](@[1, 2, 3, 4, 5])\nvar fs = FoodBox[Food](@[])\n\nfs.add Food(name: \"Hamburger\", count: 3)\nfs.add Food(name: \"Cheeseburger\", count: 5)\n\nfor f in fs:\n\teat(f)\n" + }, + { + "id": 420, + "length": 339, + "source": "Rosetta Code", + "text": "import bitmap\nimport osproc\nimport ppm_read\nimport streams\n\n# Launch Netpbm \"jpegtopnm\".\n# Input is taken from \"input.jpeg\" and result sent to stdout.\nlet p = startProcess(\"jpegtopnm\", args = [\"input.jpeg\"], options = {poUsePath})\nlet stream = FileStream(p.outputStream())\nlet image = stream.readPPM()\necho image.w, \" \", image.h\np.close()\n" + }, + { + "id": 421, + "length": 483, + "source": "Rosetta Code", + "text": "import math\n\nproc isPrime(a: int): bool =\n\tif a == 2: return true\n\tif a < 2 or a mod 2 == 0: return false\n\tfor i in countup(3, int sqrt(float a), 2):\n\t\tif a mod i == 0:\n\t\t\treturn false\n\treturn true\n\nconst q = 929\nif not isPrime q: quit 1\nvar r = q\nwhile r > 0: r = r shl 1\nvar d = 2 * q + 1\nwhile true:\n\tvar i = 1\n\tvar p = r\n\twhile p != 0:\n\t\ti = (i * i) mod d\n\t\tif p < 0: i *= 2\n\t\tif i > d: i -= d\n\t\tp = p shl 1\n\tif i != 1: d += 2 * q\n\telse: break\necho \"2^\",q,\" - 1 = 0 (mod \",d,\")\"\n" + }, + { + "id": 422, + "length": 386, + "source": "Rosetta Code", + "text": "import times, os, strutils\n\ntype EKeyboardInterrupt = object of CatchableError\n\nproc handler() {.noconv.} =\n\traise newException(EKeyboardInterrupt, \"Keyboard Interrupt\")\n\nsetControlCHook(handler)\n\nlet t = epochTime()\n\ntry:\n\tfor n in 1 ..< int64.high:\n\t\tsleep 500\n\t\techo n\nexcept EKeyboardInterrupt:\n\techo \"Program has run for \", formatFloat(epochTime() - t, precision = 0), \" seconds.\"\n" + }, + { + "id": 423, + "length": 393, + "source": "Rosetta Code", + "text": "import xmltree, strtabs, sequtils\n\nproc charsToXML(names, remarks: seq[string]): XmlNode =\n\tresult = <>CharacterRemarks()\n\tfor name, remark in items zip(names, remarks):\n\t\tresult.add <>Character(name=name, remark.newText)\n\necho charsToXML(@[\"April\", \"Tam O'Shanter\", \"Emily\"],\n\t@[\"Bubbly: I'm > Tam and <= Emily\",\n\t\t\"Burns: \\\"When chapman billies leave the street ...\\\"\",\n\t\t\"Short & shrift\"])\n" + }, + { + "id": 424, + "length": 340, + "source": "Rosetta Code", + "text": "var x: int\nx = 0b1011010111\nx = 0b10_1101_0111\nx = 0o1327\nx = 0o13_27\nx = 727\nx = 727_000_000\nx = 0x2d7\nx = 0x2d7_2d7\n\n# Literals of specific size:\nvar a = -127'i8 # 8 bit Integer\nvar b = -128'i16\nvar c = -129'i32\nvar d = -129'i64\nvar e = 126'u # Unsigned Integer\nvar f = 127'u8 # 8 bit uint\nvar g = 128'u16\nvar h = 129'u32\nvar i = 130'u64\n" + }, + { + "id": 425, + "length": 551, + "source": "Rosetta Code", + "text": "from math import nil # Require qualifier to access functions.\n\ntype MF64 = proc(x: float64): float64\n\nproc cube(x: float64) : float64 =\n\tmath.pow(x, 3)\n\nproc cuberoot(x: float64) : float64 =\n\tmath.pow(x, 1/3)\n\nproc compose[A](f: proc(x: A): A, g: proc(x: A): A) : (proc(x: A): A) =\n\tproc c(x: A): A =\n\t\tf(g(x))\n\treturn c\n\nproc sin(x: float64) : float64 =\n\tmath.sin(x)\n\nproc acos(x: float64) : float64 =\n\tmath.arccos(x)\n\nvar fun = @[sin, math.cos, cube]\nvar inv = @[MF64 math.arcsin, acos, cuberoot]\n\nfor i in 0..2:\n\techo compose(inv[i], fun[i])(0.5)\n" + }, + { + "id": 426, + "length": 303, + "source": "Rosetta Code", + "text": "type U0 = object of Exception\ntype U1 = object of Exception\n\nproc baz(i) =\n\tif i > 0: raise newException(U1, \"Some error\")\n\telse: raise newException(U0, \"Another error\")\n\nproc bar(i) =\n\tbaz(i)\n\nproc foo() =\n\tfor i in 0..1:\n\t\ttry:\n\t\t\tbar(i)\n\t\texcept U0:\n\t\t\techo \"Function foo caught exception U0\"\n\nfoo()\n" + }, + { + "id": 427, + "length": 361, + "source": "Rosetta Code", + "text": "iterator lookAndSay(n: int): string =\n\tvar current = \"1\"\n\tyield current\n\tfor round in 2..n:\n\t\tvar ch = current[0]\n\t\tvar count = 1\n\t\tvar next = \"\"\n\t\tfor i in 1..current.high:\n\t\t\tif current[i] == ch:\n\t\t\t\tinc count\n\t\t\telse:\n\t\t\t\tnext.add $count & ch\n\t\t\t\tch = current[i]\n\t\t\t\tcount = 1\n\t\tcurrent = next & $count & ch\n\t\tyield current\n\nfor s in lookAndSay(12):\n\techo s\n" + }, + { + "id": 428, + "length": 452, + "source": "Rosetta Code", + "text": "import asyncnet, asyncdispatch\n\nproc processClient(client: AsyncSocket) {.async.} =\n\twhile true:\n\t\tlet line = await client.recvLine()\n\t\tawait client.send(line & \"\\c\\L\")\n\nproc serve() {.async.} =\n\tvar server = newAsyncSocket()\n\tserver.bindAddr(Port(12321))\n\tserver.listen()\n\n\twhile true:\n\t\tlet client = await server.accept()\n\t\techo \"Accepting connection from client\", client.getLocalAddr[0]\n\t\tdiscard processClient(client)\n\ndiscard serve()\nrunForever()\n" + }, + { + "id": 429, + "length": 352, + "source": "Rosetta Code", + "text": "import times\n\nconst Date = \"March 7 2009 7:30pm EST\"\necho \"Original date is: \", Date\n\nvar dt = Date.replace(\"EST\", \"-05:00\").parse(\"MMMM d yyyy h:mmtt zzz\")\necho \"Original date in UTC is: \", dt.utc().format(\"MMMM d yyyy h:mmtt zzz\")\n\ndt = dt + initDuration(hours = 12)\necho \"Date 12 hours later is: \", dt.utc().format(\"MMMM d yyyy h:mmtt zzz\")\n" + }, + { + "id": 430, + "length": 316, + "source": "Rosetta Code", + "text": "proc countingSort[T](a: var openarray[T]; min, max: int) =\n\tlet range = max - min + 1\n\tvar count = newSeq[T](range)\n\tvar z = 0\n\n\tfor i in 0 ..< a.len: inc count[a[i] - min]\n\n\tfor i in min .. max:\n\t\tfor j in 0 ..< count[i - min]:\n\t\t\ta[z] = i\n\t\t\tinc z\n\nvar a = @[5, 3, 1, 7, 4, 1, 1, 20]\ncountingSort(a, 1, 20)\necho a\n" + }, + { + "id": 431, + "length": 549, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio]\nimport gintro/gdk except Window\n\nproc onButtonPress(window: ApplicationWindow; event: Event; data: pointer): bool =\n\techo event.getCoords()\n\tresult = true\n\nproc activate(app: Application) =\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"Mouse position\")\n\twindow.setSizeRequest(640, 480)\n\n\tdiscard window.connect(\"button-press-event\", onButtonPress, pointer(nil))\n\twindow.showAll()\n\nlet app = newApplication(Application, \"MousePosition\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 432, + "length": 362, + "source": "Rosetta Code", + "text": "import gtk2, gdk2, gdk2pixbuf\n\ntype Color = tuple[r, g, b: byte]\n\ngtk2.nim_init()\n\nproc getPixelColor(x, y: int32): Color =\n\tvar p = pixbufNew(COLORSPACE_RGB, false, 8, 1, 1)\n\tdiscard p.getFromDrawable(getDefaultRootWindow().Drawable,\n\t\tgetDefaultScreen().getSystemColormap(), x, y, 0, 0, 1, 1)\n\tresult = cast[ptr Color](p.getPixels)[]\n\necho getPixelColor(0, 0)\n" + }, + { + "id": 433, + "length": 438, + "source": "Rosetta Code", + "text": "import gintro/[gtk, gobject, gio, gdk, gdkpixbuf]\n\ntype Color = tuple[r, g, b: byte]\n\nproc getPixelColor(x, y: int32): Color =\n\tvar pixbuf = pixbufGetFromWindow(getDefaultRootWindow(), x, y, 1, 1)\n\tresult = cast[ptr Color](pixbuf.readPixels())[]\n\nproc activate(app: Application) =\n\t## Needed by GTK3.\n\tdiscard\n\nlet app = newApplication(\"org.gtk.example\")\nconnect(app, \"activate\", activate)\ndiscard run(app)\n\necho getPixelColor(1500, 800)\n" + }, + { + "id": 434, + "length": 457, + "source": "Rosetta Code", + "text": "proc reversed(s: string): string =\n\tresult = newString(s.len)\n\tfor i, c in s:\n\t\tresult[s.high - i] = c\n\nproc isPalindrome(s: string): bool =\n\ts == reversed(s)\n\nwhen isMainModule:\n\tassert(isPalindrome(\"\"))\n\tassert(isPalindrome(\"a\"))\n\tassert(isPalindrome(\"aa\"))\n\tassert(not isPalindrome(\"baa\"))\n\tassert(isPalindrome(\"baab\"))\n\tassert(isPalindrome(\"ba_ab\"))\n\tassert(not isPalindrome(\"ba_ ab\"))\n\tassert(isPalindrome(\"ba _ ab\"))\n\tassert(not isPalindrome(\"abab\"))\n" + }, + { + "id": 435, + "length": 499, + "source": "Rosetta Code", + "text": "import unittest\n\nproc reversed(s: string): string =\n\tresult = newString(s.len)\n\tfor i, c in s:\n\t\tresult[s.high - i] = c\n\nproc isPalindrome(s: string): bool =\n\ts == reversed(s)\n\nwhen isMainModule:\n\tsuite \"palindrome\":\n\t\ttest \"empty string\":\n\t\t\tcheck isPalindrome \"\"\n\n\t\ttest \"string of length 1\":\n\t\t\tcheck isPalindrome \"a\"\n\n\t\ttest \"string of length 2\":\n\t\t\tcheck isPalindrome \"aa\"\n\n\t\ttest \"string of length 3\":\n\t\t\tcheck isPalindrome \"aaa\"\n\n\t\ttest \"no palindrome\":\n\t\t\tcheck isPalindrome(\"foo\") == false\n" + }, + { + "id": 436, + "length": 332, + "source": "Rosetta Code", + "text": "import tables\n\nvar\n\ttheVar: int = 5\n\tvarMap = initTable[string, pointer]()\n\nproc ptrToInt(p: pointer): int =\n\tresult = cast[ptr int](p)[]\n\nproc main() =\n\twrite(stdout, \"Enter a var name: \")\n\tlet sVar = readLine(stdin)\n\tvarMap[$svar] = theVar.addr\n\techo \"Variable \", sVar, \" is \", ptrToInt(varMap[$sVar])\n\nwhen isMainModule:\n\tmain()\n" + }, + { + "id": 437, + "length": 532, + "source": "Rosetta Code", + "text": "import algorithm\n\nconst Records = [(country: \"UK\", city: \"London\"),\n\t\t\t\t\t\t\t\t (country: \"US\", city: \"New York\"),\n\t\t\t\t\t\t\t\t (country: \"US\", city: \"Birmingham\"),\n\t\t\t\t\t\t\t\t (country: \"UK\", city: \"Birmingham\")]\n\necho \"Original order:\"\nfor record in Records:\n\techo record.country, \" \", record.city\necho()\n\necho \"Sorted by city name:\"\nfor record in Records.sortedByIt(it.city):\n\techo record.country, \" \", record.city\necho()\n\necho \"Sorted by country name:\"\nfor record in Records.sortedByIt(it.country):\n\techo record.country, \" \", record.city\n" + }, + { + "id": 438, + "length": 561, + "source": "Rosetta Code", + "text": "import locks\nfrom os import sleep\nimport times\nfrom strformat import fmt\n\nvar\n\t# condition variable which shared across threads\n\tcond: Cond\n\tlock: Lock\n\tthreadproc: Thread[void]\n\nproc waiting {.thread.} =\n\techo \"spawned waiting proc\"\n\tlet start = getTime()\n\tcond.wait lock\n\techo fmt\"thread ended after waiting {getTime() - start}.\"\n\nproc main =\n\tinitCond cond\n\tinitLock lock\n\tthreadproc.createThread waiting\n\techo \"in main proc\"\n\tos.sleep 1000\n\techo \"send signal/event notification\"\n\tsignal cond\n\tjoinThread threadproc\n\tdeinitCond cond\n\tdeinitLock lock\n\nmain()\n" + }, + { + "id": 439, + "length": 490, + "source": "Rosetta Code", + "text": "import random, strutils\n\nconst ArrSize = 10\n\nvar a: array[ArrSize, array[ArrSize, int]]\nvar s = \"\"\n\nrandomize() # Different results each time this runs.\n\n# Initialize using loops on items rather than indexes.\nfor row in a.mitems:\n\tfor item in row.mitems:\n\t\titem = rand(1..20)\n\nblock outer:\n\t# Loop using indexes.\n\tfor i in 0.. 0\n\n\tvar\n\t\tsumm, n = 0.0\n\t\tvalues: Deque[float]\n\tfor i in 1..period:\n\t\tvalues.addLast(0)\n\n\tproc sma(x: float): float =\n\t\tvalues.addLast(x)\n\t\tsumm += x - values.popFirst()\n\t\tn = min(n+1, float(period))\n\t\tresult = summ / n\n\n\treturn sma\n\nvar sma = simplemovingaverage(3)\nfor i in 1..5: echo sma(float(i))\nfor i in countdown(5,1): echo sma(float(i))\n\necho \"\"\n\nvar sma2 = simplemovingaverage(5)\nfor i in 1..5: echo sma2(float(i))\nfor i in countdown(5,1): echo sma2(float(i))\n" + }, + { + "id": 444, + "length": 488, + "source": "Rosetta Code", + "text": "# Using Wikipedia data sample.\n\nimport math\nimport arraymancer, sequtils\n\nvar\n\theight = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65,\n\t\t\t\t\t\t1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83].toTensor()\n\n\tweight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29,\n\t\t\t\t\t\t63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46].toTensor()\n\n# Create Vandermonde matrix.\nvar a = stack(height.ones_like, height, height *. height, axis = 1)\n\necho toSeq(least_squares_solver(a, weight).solution.items)\n" + }, + { + "id": 445, + "length": 534, + "source": "Rosetta Code", + "text": "var # fixed size arrays\n\tx = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred\n\ty: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0\n\tz: array['a'..'z', int] # indexed using characters\n\nx[0] = x[1] + 1\necho x[0]\necho z['d']\n\nx[7..9] = y[3..5] # copy part of array\n\nvar # variable size sequences\n\ta = @[1,2,3,4,5,6,7,8,9,10]\n\tb: seq[int] = @[1,2,3,4,5]\n\na[0] = a[1] + 1\necho a[0]\n\na.add(b) # append another sequence\na.add(200) # append another element\necho a.pop() # pop last item, removing and returning it\necho a\n" + }, + { + "id": 446, + "length": 381, + "source": "Rosetta Code", + "text": "import tables\n\nvar t: Table[int,string]\n\nt[1] = \"one\"\nt[2] = \"two\"\nt[3] = \"three\"\nt[4] = \"four\"\n\necho \"t has \" & $t.len & \" elements\"\n\necho \"has t key 4? \" & $t.hasKey(4)\necho \"has t key 5? \" & $t.hasKey(5)\n\n# iterate keys\necho \"key iteration:\"\nfor k in t.keys:\n\techo \"at[\" & $k & \"]=\" & t[k]\n\n# iterate pairs\necho \"pair iteration:\"\nfor k,v in t.pairs:\n\techo \"at[\" & $k & \"]=\" & v\n" + }, + { + "id": 447, + "length": 356, + "source": "Rosetta Code", + "text": "func multiplier(a, b: float): auto =\n\tlet ab = a * b\n\tresult = func(c: float): float = ab * c\n\nlet\n\tx = 2.0\n\txi = 0.5\n\ty = 4.0\n\tyi = 0.25\n\tz = x + y\n\tzi = 1.0 / ( x + y )\n\nlet list = [x, y, z]\nlet invlist = [xi, yi, zi]\n\nfor i in 0..list.high:\n\t# Create a multiplier function...\n\tlet f = multiplier(list[i], invlist[i])\n\t# ... and apply it.\n\techo f(0.5)\n" + }, + { + "id": 448, + "length": 535, + "source": "Rosetta Code", + "text": "import fenv, strutils\n\nproc `++`(a, b: float): tuple[lower, upper: float] =\n\tlet\n\t\ta {.volatile.} = a\n\t\tb {.volatile.} = b\n\t\torig = fegetround()\n\tdiscard fesetround FE_DOWNWARD\n\tresult.lower = a + b\n\tdiscard fesetround FE_UPWARD\n\tresult.upper = a + b\n\tdiscard fesetround orig\n\nproc ff(a: float): string = a.formatFloat(ffDefault, 17)\n\nfor x, y in [(1.0, 2.0), (0.1, 0.2), (1e100, 1e-100), (1e308, 1e308)].items:\n\tlet (d,u) = x ++ y\n\techo x.ff, \" + \", y.ff, \" =\"\n\techo \" [\", d.ff, \", \", u.ff, \"]\"\n\techo \" size \", (u - d).ff, \"\\n\"\n" + }, + { + "id": 449, + "length": 502, + "source": "Rosetta Code", + "text": "type\n\tTreeList[T] = object\n\t\tcase isLeaf: bool\n\t\tof true: data: T\n\t\tof false: list: seq[TreeList[T]]\n\nproc L[T](list: varargs[TreeList[T]]): TreeList[T] =\n\tfor x in list:\n\t\tresult.list.add x\n\nproc N[T](data: T): TreeList[T] =\n\tTreeList[T](isLeaf: true, data: data)\n\nproc flatten[T](n: TreeList[T]): seq[T] =\n\tif n.isLeaf: result = @[n.data]\n\telse:\n\t\tfor x in n.list:\n\t\t\tresult.add flatten x\n\nvar x = L(L(N 1), N 2, L(L(N 3, N 4), N 5), L(L(L[int]())), L(L(L(N 6))), N 7, N 8, L[int]())\necho flatten(x)\n" + }, + { + "id": 450, + "length": 434, + "source": "Rosetta Code", + "text": "import db_sqlite\n\nlet db = open(\":memory:\", \"\", \"\", \"\")\n\n# Setup\ndb.exec(sql\"CREATE TABLE players (name, score, active, jerseyNum)\")\ndb.exec(sql\"INSERT INTO players VALUES (?, ?, ?, ?)\", \"name\", 0, \"false\", 99)\n\n# Update the row.\ndb.exec(sql\"UPDATE players SET name=?, score=?, active=? WHERE jerseyNum=?\",\n\t\t\t\t\"Smith, Steve\", 42, true, 99)\n\n# Display result.\nfor row in db.fastRows(sql\"SELECT * FROM players\"):\n\techo row\n\ndb.close()\n" + }, + { + "id": 451, + "length": 360, + "source": "Rosetta Code", + "text": "import sugar, std/monotimes, times\n\ntype Func[T] = (T) -> T\n\nfunc cube(n: int): int = n * n * n\n\nproc benchmark[T](n: int; f: Func[T]; arg: T): seq[Duration] =\n\tresult.setLen(n)\n\tfor i in 0.. 1 or swapped:\n\t\tgap = gap * 10 div 13\n\t\tif gap == 9 or gap == 10: gap = 11\n\t\tif gap < 1: gap = 1\n\t\tswapped = false\n\t\tvar i = 0\n\t\tfor j in gap ..< a.len:\n\t\t\tif a[i] > a[j]:\n\t\t\t\tswap a[i], a[j]\n\t\t\t\tswapped = true\n\t\t\tinc i\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\ncombSort a\necho a\n" + }, + { + "id": 454, + "length": 536, + "source": "Rosetta Code", + "text": "proc deconv(g, f: openArray[float]): seq[float] =\n\tvar h: seq[float] = newSeq[float](len(g) - len(f) + 1)\n\tfor n in 0..= len(f):\n\t\t\tlower = n - len(f) + 1\n\t\tfor i in lower.. list[maxNumPos]:\n\t\t\t\tmaxNumPos = a\n\n\t\tif maxNumPos == i - 1: continue\n\n\t\tif maxNumPos > 0:\n\t\t\tinc moves\n\t\t\treverse(list, 0, maxNumPos)\n\n\t\tinc moves\n\t\treverse(list, 0, i - 1)\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\npancakeSort a\necho a\n" + }, + { + "id": 461, + "length": 599, + "source": "Rosetta Code", + "text": "import rdstdin, strutils, math, strformat\n\nlet lat = parseFloat readLineFromStdin \"Enter latitude => \"\nlet lng = parseFloat readLineFromStdin \"Enter longitude => \"\nlet med = parseFloat readLineFromStdin \"Enter legal meridian => \"\necho \"\"\n\nlet slat = sin lat.degToRad\necho &\" sine of latitude: {slat:.3f}\"\necho &\" diff longitude: {lng-med:.3f}\"\necho \"\"\necho \"Hour, sun hour angle, dial hour line angle from 6am to 6pm\"\n\nfor h in -6..6:\n\tlet hra = float(15 * h) - lng + med\n\tlet hla = arctan(slat * tan(hra.degToRad)).radToDeg\n\techo &\"HR={h:3d}; HRA={hra:7.3f}; HLA={hla:7.3f}\"\n" + }, + { + "id": 462, + "length": 542, + "source": "Rosetta Code", + "text": "proc beadSort[T](a: var openarray[T]) =\n\tvar max = low(T)\n\tvar sum = 0\n\n\tfor x in a:\n\t\tif x > max: max = x\n\n\tvar beads = newSeq[int](max * a.len)\n\n\tfor i in 0 ..< a.len:\n\t\tfor j in 0 ..< a[i]:\n\t\t\tbeads[i * max + j] = 1\n\n\tfor j in 0 ..< max:\n\t\tsum = 0\n\t\tfor i in 0 ..< a.len:\n\t\t\tsum += beads[i * max + j]\n\t\t\tbeads[i * max + j] = 0\n\n\t\tfor i in a.len - sum ..< a.len:\n\t\t\tbeads[i * max + j] = 1\n\n\tfor i in 0 ..< a.len:\n\t\tvar j = 0\n\t\twhile j < max and beads[i * max + j] > 0: inc j\n\t\ta[i] = j\n\nvar a = @[5, 3, 1, 7, 4, 1, 1, 20]\nbeadSort a\necho a\n" + }, + { + "id": 463, + "length": 497, + "source": "Rosetta Code", + "text": "import tables, math, complex, random\n\ntype Point = tuple[x, y: int]\n\nvar world = initCountTable[Point]()\nvar possiblePoints = newSeq[Point]()\n\nfor x in -15..15:\n\tfor y in -15..15:\n\t\tif abs(complex(x.float, y.float)) in 10.0..15.0:\n\t\t\tpossiblePoints.add((x,y))\n\nrandomize()\nfor i in 0..100: world.inc possiblePoints.sample\n\nfor x in -15..15:\n\tfor y in -15..15:\n\t\tlet key = (x, y)\n\t\tif key in world and world[key] > 0:\n\t\t\tstdout.write ' ' & $min(9, world[key])\n\t\telse:\n\t\t\tstdout.write \" \"\n\techo \"\"\n" + }, + { + "id": 464, + "length": 441, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\niterator eqindex(data: openArray[int]): int =\n\tvar suml, ddelayed = 0\n\tvar sumr = sum(data)\n\tfor i,d in data:\n\t\tsuml += ddelayed\n\t\tsumr -= d\n\t\tddelayed = d\n\t\tif suml == sumr:\n\t\t\tyield i\n\nconst d = @[@[-7, 1, 5, 2, -4, 3, 0],\n\t\t\t\t\t\t@[2, 4, 6],\n\t\t\t\t\t\t@[2, 9, 2],\n\t\t\t\t\t\t@[1, -1, 1, -1, 1, -1, 1]]\n\nfor data in d:\n\techo \"d = [\", data.join(\", \"), ']'\n\techo \"eqIndex(d) -> [\", toSeq(eqindex(data)).join(\", \"), ']'\n" + }, + { + "id": 465, + "length": 398, + "source": "Rosetta Code", + "text": "import random\n\nimport rapid/gfx\n\nvar\n\twindow = initRWindow()\n\t\t.size(320, 240)\n\t\t.title(\"image noise\")\n\t\t.open()\n\tsurface = window.openGfx()\n\nsurface.loop:\n\tdraw ctx, step:\n\t\tctx.clear(gray(0))\n\t\tctx.begin()\n\t\tfor y in 0..window.height:\n\t\t\tfor x in 0..window.width:\n\t\t\t\tif rand(0..1) == 0:\n\t\t\t\t\tctx.point((x.float, y.float))\n\t\tctx.draw(prPoints)\n\t\techo 1 / (step / 60)\n\tupdate step:\n\t\tdiscard step\n" + }, + { + "id": 466, + "length": 449, + "source": "Rosetta Code", + "text": "iterator inplacePermutations[T](xs: var seq[T]): var seq[T] =\n\t\tassert xs.len <= 24, \"permutation of array longer than 24 is not supported\"\n\n\t\tlet n = xs.len - 1\n\t\tvar\n\t\t\tc: array[24, int8]\n\t\t\ti: int = 0\n\n\t\tfor i in 0 .. n: c[i] = int8(i+1)\n\n\t\twhile true:\n\t\t\tyield xs\n\t\t\tif i >= n: break\n\n\t\t\tc[i] -= 1\n\t\t\tlet j = if (i and 1) == 1: 0 else: int(c[i])\n\t\t\tswap(xs[i+1], xs[j])\n\n\t\t\ti = 0\n\t\t\twhile c[i] == 0:\n\t\t\t\tlet t = i+1\n\t\t\t\tc[i] = int8(t)\n\t\t\t\ti = t\n" + }, + { + "id": 467, + "length": 457, + "source": "Rosetta Code", + "text": "# Iterative Boothroyd method\niterator permutations[T](ys: openarray[T]): seq[T] =\n\tvar\n\t\td = 1\n\t\tc = newSeq[int](ys.len)\n\t\txs = newSeq[T](ys.len)\n\n\tfor i, y in ys: xs[i] = y\n\tyield xs\n\n\tblock outer:\n\t\twhile true:\n\t\t\twhile d > 1:\n\t\t\t\tdec d\n\t\t\t\tc[d] = 0\n\t\t\twhile c[d] >= d:\n\t\t\t\tinc d\n\t\t\t\tif d >= ys.len: break outer\n\t\t\tlet i = if (d and 1) == 1: c[d] else: 0\n\t\t\tswap xs[i], xs[d]\n\t\t\tyield xs\n\t\t\tinc c[d]\n\nvar x = @[1, 2, 3]\n\nfor i in permutations(x):\n\techo i\n" + }, + { + "id": 468, + "length": 462, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\nimport ncurses\n\nrandomize()\n\nlet win = initscr()\nassert not win.isNil, \"Unable to initialize.\"\n\nfor y in 0..9:\n\tmvaddstr(y.cint, 0, newSeqWith(10, sample({'0'..'9', 'a'..'z'})).join())\n\nlet row = rand(9).cint\nlet col = rand(9).cint\nlet ch = win.mvwinch(row, col)\n\nmvaddstr(row, col + 11, \"The character at ($1, $2) is $3.\".format(row, col, chr(ch)))\nmvaddstr(11, 0, \"Press any key to quit.\")\nrefresh()\ndiscard getch()\n\nendwin()\n" + }, + { + "id": 469, + "length": 553, + "source": "Rosetta Code", + "text": "import strformat\n\nproc toSeq(x: uint64): seq[uint8] =\n\tvar x = x\n\tvar f = 0u64\n\tfor i in countdown(9u64, 1):\n\t\tif (x and 127'u64 shl (i * 7)) > 0:\n\t\t\tf = i\n\t\t\tbreak\n\tfor j in 0u64..f:\n\t\tresult.add uint8((x shr ((f - j) * 7)) and 127) or 128\n\n\tresult[f] = result[f] xor 128'u8\n\nproc fromSeq(xs: openArray[uint8]): uint64 =\n\tfor x in xs:\n\t\tresult = (result shl 7) or (x and 127)\n\nfor x in [0x7f'u64, 0x4000'u64, 0'u64, 0x3ffffe'u64, 0x1fffff'u64,\n\t\t\t\t\t0x200000'u64, 0x3311a1234df31413'u64]:\n\tlet c = toSeq(x)\n\techo &\"seq from {x}: {c} back: {fromSeq(c)}\"\n" + }, + { + "id": 470, + "length": 409, + "source": "Rosetta Code", + "text": "import strutils\n\nlet s = \"The quick brown fox\"\nif s.startsWith(\"The quick\"):\n\techo \"Starts with The quick.\"\nif s.endsWith(\"brown Fox\"):\n\techo \"Ends with brown fox.\"\nif s.contains(\" brown \"):\n\techo \"Contains brown .\"\nif \"quick\" in s:\n\techo \"Contains quick.\" # Alternate form for \"contains\".\n\nlet pos = find(s, \" brown \") # -1 if not found.\nif pos >= 0:\n\techo \" brown is located at position: \" & $pos\n" + }, + { + "id": 471, + "length": 336, + "source": "Rosetta Code", + "text": "import times\n\nconst LongMonths = {mJan, mMar, mMay, mJul, mAug, mOct, mDec}\n\nvar sumNone = 0\nfor year in 1900..2100:\n\tvar none = true\n\tfor month in LongMonths:\n\t\tif initDateTime(1, month, year, 0, 0, 0).weekday == dFri:\n\t\t\techo month, \" \", year\n\t\t\tnone = false\n\tif none: inc sumNone\n\necho \"\\nYears without a 5 weekend month: \", sumNone\n" + }, + { + "id": 472, + "length": 347, + "source": "Rosetta Code", + "text": "import strutils\n\nproc removeComments(line: string; sep: char): string =\n\tline.split(sep)[0].strip(leading = false)\n\nconst\n\tStr1 = \"apples, pears # and bananas\"\n\tStr2 = \"apples, pears ; and bananas\"\n\necho \"Original: $#\" % Str1\necho \"Stripped: $#\" % Str1.removeComments('#')\necho \"Original: $#\" % Str2\necho \"Stripped: $#\" % Str2.removeComments(';')\n" + }, + { + "id": 473, + "length": 365, + "source": "Rosetta Code", + "text": "import strutils\n\nconst DictFile = \"unixdict.txt\"\n\nfunc isSorted(s: string): bool =\n\tvar last = char.low\n\tfor c in s:\n\t\tif c < last: return false\n\t\tlast = c\n\tresult = true\n\nvar\n\tmx = 0\n\twords: seq[string]\n\nfor word in DictFile.lines:\n\tif word.len >= mx and word.isSorted:\n\t\tif word.len > mx:\n\t\t\twords.setLen(0)\n\t\t\tmx = word.len\n\t\twords.add word\necho words.join(\" \")\n" + }, + { + "id": 474, + "length": 306, + "source": "Rosetta Code", + "text": "import sugar, sequtils\n\nproc combsReps[T](lst: seq[T], k: int): seq[seq[T]] =\n\tif k == 0:\n\t\t@[newSeq[T]()]\n\telif lst.len == 0:\n\t\t@[]\n\telse:\n\t\tlst.combsReps(k - 1).map((x: seq[T]) => lst[0] & x) &\n\t\t\tlst[1 .. ^1].combsReps(k)\n\necho(@[\"iced\", \"jam\", \"plain\"].combsReps(2))\necho toSeq(1..10).combsReps(3).len\n" + }, + { + "id": 475, + "length": 345, + "source": "Rosetta Code", + "text": "import glib2, gtk2\n\nproc printSize(window: PWindow): guint {.cdecl.} =\n\tvar width, height: gint\n\twindow.get_size(addr(width), addr(height))\n\techo \"W x H = \", width, \" x \", height\n\tmain_quit()\n\nnim_init()\n\nlet window = window_new(WINDOW_TOPLEVEL)\nwindow.maximize()\nwindow.show_all()\n\ndiscard g_timeout_add(100, printSize, addr(window[]))\n\nmain()\n" + }, + { + "id": 476, + "length": 535, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio]\n\nvar window: ApplicationWindow\n\nproc printSize(data: pointer): gboolean {.cdecl.} =\n\tvar width, height: int\n\twindow.getSize(width, height)\n\techo \"W x H = \", width, \" x \", height\n\twindow.destroy()\n\nproc activate(app: Application) =\n\twindow = app.newApplicationWindow()\n\twindow.maximize()\n\twindow.showAll()\n\n\tdiscard timeoutAdd(PRIORITY_DEFAULT, 100, SourceFunc(printSize), nil, nil)\n\nlet app = newApplication(Application, \"ScreenSize\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 477, + "length": 467, + "source": "Rosetta Code", + "text": "import strutils\n\nproc cline(n, x, y: int, cde: string) =\n\techo cde[0..0].align n+1,\n\t\trepeat(cde[1], 9*x-1),\n\t\tcde[0],\n\t\tif cde.len > 2: cde[2..2].align y+1 else: \"\"\n\nproc cuboid(x, y, z: int) =\n\tcline y+1, x, 0, \"+-\"\n\tfor i in 1..y: cline y-i+1, x, i-1, \"/ |\"\n\tcline 0, x, y, \"+-|\"\n\tfor i in 0..4*z-y-3: cline 0, x, y, \"| |\"\n\tcline 0, x, y, \"| +\"\n\tfor i in countdown(y-1, 0): cline 0, x, i, \"| /\"\n\tcline 0, x, 0, \"+-\\n\"\n\ncuboid 2, 3, 4\ncuboid 1, 1, 1\ncuboid 6, 2, 1\n" + }, + { + "id": 478, + "length": 385, + "source": "Rosetta Code", + "text": "import strutils\n\nconst nim = \"\"\"\n\t\t\t\t\t\t# # ##### # #\n\t\t\t\t\t\t## # # ## ##\n\t\t\t\t\t\t# # # # # ## #\n\t\t\t\t\t\t# # # # # #\n\t\t\t\t\t\t# ## # # #\n\t\t\t\t\t\t# # ##### # #\n\t\t\t\t\t\t\"\"\"\nlet lines = nim.dedent.multiReplace((\"#\", \"<<<\"), (\" \", \" \"), (\"< \", \"<>\"), (\"<\\n\", \"<>\\n\")).splitLines\nfor i, line in lines:\n\techo spaces(lines.len - i), line\n" + }, + { + "id": 479, + "length": 332, + "source": "Rosetta Code", + "text": "var dog, Dog: string\n(dog, Dog, DOG) = (\"Benjamin\", \"Samba\", \"Bernie\")\n\nif dog == Dog:\n\tif dog == DOG:\n\t\techo \"There is only one dog, \", DOG)\n\telse:\n\t\techo \"There are two dogs: \", dog, \" and \", DOG\nelif Dog == DOG :\n\techo \"There are two dogs: \", dog, \" and \", DOG\nelse:\n\techo \"There are three dogs: \", dog, \", \", Dog, \" and \", DOG\n" + }, + { + "id": 480, + "length": 380, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\nproc catalan1(n: int): int =\n\tbinom(2 * n, n) div (n + 1)\n\nproc catalan2(n: int): int =\n\tif n == 0:\n\t\treturn 1\n\tfor i in 0.. 0: 2 * (2 * n - 1) * catalan3(n - 1) div (1 + n)\n\telse: 1\n\nfor i in 0..15:\n\techo &\"{i:7} {catalan1(i):7} {catalan2(i):7} {catalan3(i):7}\"\n" + }, + { + "id": 481, + "length": 334, + "source": "Rosetta Code", + "text": "import algorithm\n\nproc sortDisjoinSublist[T](data: var seq[T], indices: seq[int]) =\n\tvar indices = indices\n\tsort indices, cmp[T]\n\n\tvar values: seq[T] = @[]\n\tfor i in indices: values.add data[i]\n\tsort values, cmp[T]\n\n\tfor j, i in indices: data[i] = values[j]\n\nvar d = @[7, 6, 5, 4, 3, 2, 1, 0]\nsortDisjoinSublist(d, @[6, 1, 7])\necho d\n" + }, + { + "id": 482, + "length": 423, + "source": "Rosetta Code", + "text": "from random import random, randomize, shuffle\nfrom strutils import repeat\n\nrandomize()\n\nproc gen(n: int): string =\n\tresult = \"[]\".repeat(n)\n\tshuffle(result)\n\nproc balanced(txt: string): bool =\n\tvar b = 0\n\tfor c in txt:\n\t\tcase c\n\t\tof '[':\n\t\t\tinc(b)\n\t\tof ']':\n\t\t\tdec(b)\n\t\t\tif b < 0: return false\n\t\telse: discard\n\tb == 0\n\nfor n in 0..9:\n\tlet s = gen(n)\n\techo \"'\", s, \"' is \", (if balanced(s): \"balanced\" else: \"not balanced\")\n" + }, + { + "id": 483, + "length": 549, + "source": "Rosetta Code", + "text": "import strutils\n\niterator tokenize(text: string; sep: openArray[string]): tuple[token: string, isSep: bool] =\n\tvar i, lastMatch = 0\n\twhile i < text.len:\n\t\tfor j, s in sep:\n\t\t\tif text[i..text.high].startsWith s:\n\t\t\t\tif i > lastMatch: yield (text[lastMatch ..< i], false)\n\t\t\t\tyield (s, true)\n\t\t\t\tlastMatch = i + s.len\n\t\t\t\ti += s.high\n\t\t\t\tbreak\n\t\tinc i\n\tif i > lastMatch: yield (text[lastMatch ..< i], false)\n\nfor token, isSep in \"a!===b=!=c\".tokenize([\"==\", \"!=\", \"=\"]):\n\tif isSep: stdout.write '{',token,'}'\n\telse: stdout.write token\necho \"\"\n" + }, + { + "id": 484, + "length": 327, + "source": "Rosetta Code", + "text": "import strutils\n\nproc euler(f: proc (x,y: float): float; y0, a, b, h: float) =\n\tvar (t,y) = (a,y0)\n\twhile t < b:\n\t\techo formatFloat(t, ffDecimal, 3), \" \", formatFloat(y, ffDecimal, 3)\n\t\tt += h\n\t\ty += h * f(t,y)\n\nproc newtoncooling(time, temp: float): float =\n\t-0.07 * (temp - 20)\n\neuler(newtoncooling, 100.0, 0.0, 100.0, 10.0)\n" + }, + { + "id": 485, + "length": 359, + "source": "Rosetta Code", + "text": "import rationals, strutils, sugar\n\ntype Fract = Rational[int]\n\nproc corput(n: int; base: Positive): Fract =\n\tresult = 0.toRational\n\tvar b = 1 // base\n\tvar n = n\n\twhile n != 0:\n\t\tresult += n mod base * b\n\t\tn = n div base\n\t\tb /= base\n\nfor base in 2..5:\n\tlet list = collect(newSeq, for n in 1..10: corput(n, base))\n\techo \"Base $#: \".format(base), list.join(\" \")\n" + }, + { + "id": 486, + "length": 470, + "source": "Rosetta Code", + "text": "proc hailstone*(n: int): auto =\n\tresult = @[n]\n\tvar n = n\n\twhile n > 1:\n\t\tif (n and 1) == 1:\n\t\t\tn = 3 * n + 1\n\t\telse:\n\t\t\tn = n div 2\n\t\tresult.add n\n\nwhen isMainModule:\n\tlet h = hailstone 27\n\tassert h.len == 112 and h[0..3] == @[27, 82, 41, 124] and h[h.high-3..h.high] == @[8, 4, 2, 1]\n\tvar m, mi = 0\n\tfor i in 1 ..< 100_000:\n\t\tlet n = hailstone(i).len\n\t\tif n > m:\n\t\t\tm = n\n\t\t\tmi = i\n\techo \"Maximum length \", m, \" was found for hailstone(\", mi, \") for numbers <100,000\"\n" + }, + { + "id": 487, + "length": 570, + "source": "Rosetta Code", + "text": "import sequtils\n\ntype\n\n\tFunc = proc(n: int): int\n\tFuncS = proc(f: Func; s: seq[int]): seq[int]\n\nproc fs(f: Func; s: seq[int]): seq[int] = s.map(f)\n\nproc partial(fs: FuncS; f: Func): auto =\n\tresult = proc(s: seq[int]): seq[int] = fs(f, s)\n\nproc f1(n: int): int = 2 * n\nproc f2(n: int): int = n * n\n\nwhen isMainModule:\n\n\tconst Seqs = @[@[0, 1, 2, 3], @[2, 4, 6, 8]]\n\n\tlet fsf1 = partial(fs, f1)\n\tlet fsf2 = partial(fs, f2)\n\n\tfor s in Seqs:\n\t\techo fs(f1, s) # Normal.\n\t\techo fsf1(s) # Partial.\n\t\techo fs(f2, s) # Normal.\n\t\techo fsf2(s) # Partial.\n\t\techo \"\"\n" + }, + { + "id": 488, + "length": 503, + "source": "Rosetta Code", + "text": "import bignum\n\nproc calcPi() =\n\tvar\n\t\tq = newInt(1)\n\t\tr = newInt(0)\n\t\tt = newInt(1)\n\t\tk = newInt(1)\n\t\tn = newInt(3)\n\t\tl = newInt(3)\n\n\tvar count = 0\n\twhile true:\n\t\tif 4 * q + r - t < n * t:\n\t\t\tstdout.write n\n\t\t\tinc count\n\t\t\tif count == 40: (echo \"\"; count = 0)\n\t\t\tlet nr = 10 * (r - n * t)\n\t\t\tn = 10 * (3 * q + r) div t - 10 * n\n\t\t\tq *= 10\n\t\t\tr = nr\n\t\telse:\n\t\t\tlet nr = (2 * q + r) * l\n\t\t\tlet nn = (7 * q * k + 2 + r * l) div (t * l)\n\t\t\tq *= k\n\t\t\tt *= l\n\t\t\tl += 2\n\t\t\tk += 1\n\t\t\tn = nn\n\t\t\tr = nr\n\ncalcPi()\n" + }, + { + "id": 489, + "length": 387, + "source": "Rosetta Code", + "text": "import os, osproc, strutils\n\nconst S = \"Actions speak louder than words.\"\n\nvar prev, bs = \"\"\nvar prevlen = 0\n\nfor word in S.splitWhitespace():\n\tdiscard execProcess(\"espeak \" & word)\n\tif prevlen > 0:\n\t\tbs = repeat('\\b', prevlen)\n\tstdout.write bs, prev, word.toUpper, ' '\n\tstdout.flushFile()\n\tprev = word & ' '\n\tprevlen = word.len + 1\n\nbs = repeat('\\b', prevlen)\nsleep(1000)\necho bs, prev\n" + }, + { + "id": 490, + "length": 533, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, std/monotimes, times\n\ntype Digit = 0..9\n\nvar digits = newSeqOfCap[Digit](10)\n\nproc getDigits(n: Positive) =\n\tdigits.setLen(0)\n\tvar n = n.int\n\twhile n != 0:\n\t\tdigits.add n mod 10\n\t\tn = n div 10\n\tdigits.reverse()\n\nproc isSelfDescribing(n: Natural): bool =\n\tn.getDigits()\n\tfor i, d in digits:\n\t\tif digits.count(i) != d:\n\t\t\treturn false\n\tresult = true\n\nlet t0 = getMonoTime()\nfor n in 1 .. 1_000_000_000:\n\tif n.isSelfDescribing:\n\t\techo n, \" in \", getMonoTime() - t0\n\necho \"\\nTotal time: \", getMonoTime() - t0\n" + }, + { + "id": 491, + "length": 369, + "source": "Rosetta Code", + "text": "import tables\n\nlet rdecode = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}.toTable\n\nproc decode(roman: string): int =\n\tfor i in 0 ..< roman.high:\n\t\tlet (rd, rd1) = (rdecode[roman[i]], rdecode[roman[i+1]])\n\t\tresult += (if rd < rd1: -rd else: rd)\n\tresult += rdecode[roman[roman.high]]\n\nfor r in [\"MCMXC\", \"MMVIII\", \"MDCLXVI\"]:\n\techo r, \" \", decode(r)\n" + }, + { + "id": 492, + "length": 344, + "source": "Rosetta Code", + "text": "import nativesockets\n\niterator items(ai: ptr AddrInfo): ptr AddrInfo =\n\tvar current = ai\n\twhile current != nil:\n\t\tyield current\n\t\tcurrent = current.aiNext\n\nproc main() =\n\tlet addrInfos = getAddrInfo(\"www.kame.net\", Port 80, AfUnspec)\n\tdefer: freeAddrInfo addrInfos\n\n\tfor i in addrInfos:\n\t\techo getAddrString i.aiAddr\n\nwhen isMainModule: main()\n" + }, + { + "id": 493, + "length": 349, + "source": "Rosetta Code", + "text": "# If statements\ntemplate `?`(expression, condition) =\n\tif condition:\n\t\texpression\n\nlet raining = true\nvar needUmbrella: bool\n# Normal syntax\nif raining: needUmbrella = true\n# Inverted syntax\n(needUmbrella = true) ? (raining == true)\n\n# Assignments\ntemplate `~=`(right, left) =\n\tleft = right\n\nvar a = 3\n# Normal syntax\na = 6\n# Inverted syntax\n6 ~= a\n" + }, + { + "id": 494, + "length": 322, + "source": "Rosetta Code", + "text": "import strutils\n\nlet s = \"\\t \\v \\r String with spaces \\n \\t \\f\"\necho \"\", s, \"\"\necho(\"*** Stripped of leading spaces ***\")\necho \"\", s.strip(trailing = false), \"\"\necho(\"*** Stripped of trailing spaces ***\")\necho \"\", s.strip(leading = false), \"\"\necho(\"*** Stripped of leading and trailing spaces ***\")\necho \"\", s.strip(), \"\"\n" + }, + { + "id": 495, + "length": 342, + "source": "Rosetta Code", + "text": "import strutils\n\necho \"She was a soul stripper. She took my heart!\".split({'a','e','i'}).join()\n\necho \"She was a soul stripper. She took my heart!\".multiReplace(\n\t(\"a\", \"\"),\n\t(\"e\", \"\"),\n\t(\"i\", \"\")\n)\n\n# And another way using module \"sequtils\".\nimport sequtils\necho \"She was a soul stripper. She took my heart!\".filterIt(it notin \"aei\").join()\n" + }, + { + "id": 496, + "length": 312, + "source": "Rosetta Code", + "text": "import strutils, sequtils\n\nproc k(n: int): bool =\n\tlet n2 = $(n.int64 * n)\n\tfor i in 0 .. n2.high:\n\t\tlet a = if i > 0: parseBiggestInt n2[0 ..< i] else: 0\n\t\tlet b = parseBiggestInt n2[i .. n2.high]\n\t\tif b > 0 and a + b == n:\n\t\t\treturn true\n\necho toSeq(1..10_000).filter(k)\necho len toSeq(1..1_000_000).filter(k)\n" + }, + { + "id": 497, + "length": 369, + "source": "Rosetta Code", + "text": "import strutils\n\nproc caesar(s: string, k: int, decode = false): string =\n\tvar k = if decode: 26 - k else: k\n\tresult = \"\"\n\tfor i in toUpper(s):\n\t\tif ord(i) >= 65 and ord(i) <= 90:\n\t\t\tresult.add(chr((ord(i) - 65 + k) mod 26 + 65))\n\nlet msg = \"The quick brown fox jumped over the lazy dogs\"\necho msg\nlet enc = caesar(msg, 11)\necho enc\necho caesar(enc, 11, decode = true)\n" + }, + { + "id": 498, + "length": 564, + "source": "Rosetta Code", + "text": "import algorithm\n\ntype\n\n\tPerson {.pure.} = enum Baker, Cooper, Fletcher, Miller, Smith\n\tFloor = range[1..5]\n\nvar floors: array[Person, Floor] = [Floor 1, 2, 3, 4, 5]\n\nwhile true:\n\tif floors[Baker] != 5 and\n\t\t floors[Cooper] != 1 and\n\t\t floors[Fletcher] notin [1, 5] and\n\t\t floors[Miller] > floors[Cooper] and\n\t\t abs(floors[Smith] - floors[Fletcher]) != 1 and\n\t\t abs(floors[Fletcher] - floors[Cooper]) != 1:\n\t\t\t for person, floor in floors:\n\t\t\t\t echo person, \" lives on floor \", floor\n\t\t\t break\n\tif not floors.nextPermutation():\n\t\techo \"No solution found.\"\n\t\tbreak\n" + }, + { + "id": 499, + "length": 473, + "source": "Rosetta Code", + "text": "# Procedure declarations. All are named\nproc noargs(): int\nproc twoargs(a, b: int): int\nproc anyargs(x: varargs[int]): int\nproc optargs(a, b: int = 10): int\n\n# Usage\ndiscard noargs()\ndiscard twoargs(1, 2)\ndiscard anyargs(1, 2, 3, 4, 5, 6, 7, 8)\ndiscard optargs(5)\n\n# Procedure definitions\nproc noargs(): int = echo \"noargs\"\nproc twoargs(a, b: int): int = echo \"twoargs\"\nproc anyargs(x: varargs[int]): int = echo \"anyargs\"\nproc optargs(a: int, b = 10): int = echo \"optargs\"\n" + }, + { + "id": 500, + "length": 299, + "source": "Rosetta Code", + "text": "import typeinfo\n\nfor key, val in fields(toAny(x)):\n\techo \"Key \", key\n\tcase val.kind\n\tof akString:\n\t\techo \" is a string with value: \", val.getString\n\tof akInt..akInt64, akUint..akUint64:\n\t\techo \" is an integer with value: \", val.getBiggestInt\n\telse:\n\t\techo \" is an unknown with value: \", val.repr\n" + }, + { + "id": 501, + "length": 473, + "source": "Rosetta Code", + "text": "import Terminal\nsetForegroundColor(fgRed)\necho \"FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic\"\n\nsetBackgroundColor(bgBlue)\nsetForegroundColor(fgYellow)\nstdout.write \"This is an \"\nwriteStyled \"important\"\nstdout.write \" word\"\nresetAttributes()\nstdout.write \"\\n\"\n\nsetForegroundColor(fgYellow)\necho \"Hello world!\"\n\nsetForegroundColor(fgCyan)\necho \"Hello world!\"\n\nsetForegroundColor(fgGreen)\necho \"Hello world!\"\n\nsetForegroundColor(fgMagenta)\necho \"Hello world!\"\n" + }, + { + "id": 502, + "length": 564, + "source": "Rosetta Code", + "text": "import unicode\n\ntype Proc = proc(): bool {.closure.}\n\nvar nothing: Proc = proc(): bool {.closure.} = false\n\nproc odd(prev = nothing): bool =\n\tlet a = stdin.readChar()\n\tif not isAlpha(Rune(ord(a))):\n\t\tdiscard prev()\n\t\tstdout.write(a)\n\t\treturn a != '.'\n\n\t# delay action until later, in the shape of a closure\n\tproc clos(): bool =\n\t\tstdout.write(a)\n\t\tprev()\n\n\treturn odd(clos)\n\nproc even(): bool =\n\twhile true:\n\t\tlet c = stdin.readChar()\n\t\tstdout.write(c)\n\t\tif not isAlpha(Rune(ord(c))):\n\t\t\treturn c != '.'\n\nvar e = false\nwhile (if e: odd() else: even()):\n\te = not e\n" + }, + { + "id": 503, + "length": 429, + "source": "Rosetta Code", + "text": "import strutils\n\nproc reverseWord(ch: var char) =\n\tvar nextch = stdin.readChar()\n\tif nextch.isAlphaAscii():\n\t\treverseWord(nextch)\n\tstdout.write(ch)\n\tch = nextch\n\nproc normalWord(ch: var char) =\n\tstdout.write(ch)\n\tch = stdin.readChar()\n\tif ch.isAlphaAscii():\n\t\tnormalWord(ch)\n\nvar ch = stdin.readChar()\n\nwhile ch != '.':\n\tnormalWord(ch)\n\tif ch != '.':\n\t\tstdout.write(ch)\n\t\tch = stdin.readChar()\n\t\treverseWord(ch)\nstdout.write(ch)\n" + }, + { + "id": 504, + "length": 450, + "source": "Rosetta Code", + "text": "import os, strutils, times\n\nconst\n\tDaysInMonth: array[Month, int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\tDayDiffs: array[WeekDay, int] = [3, 4, 5, 6, 0, 1, 2]\n\nlet year = paramStr(1).parseInt\n\nfor month in mJan..mDec:\n\tvar lastDay = DaysInMonth[month]\n\tif month == mFeb and year.isLeapYear: lastDay = 29\n\tvar date = initDateTime(lastDay, month, year, 0, 0, 0)\n\tdate = date - days(DayDiffs[date.weekday])\n\techo date.format(\"yyyy-MM-dd\")\n" + }, + { + "id": 505, + "length": 358, + "source": "Rosetta Code", + "text": "# Least signficant bit:\nproc isOdd(i: int): bool = (i and 1) != 0\nproc isEven(i: int): bool = (i and 1) == 0\n\n# Modulo:\nproc isOdd2(i: int): bool = (i mod 2) != 0\nproc isEven2(i: int): bool = (i mod 2) == 0\n\n# Bit Shifting:\nproc isOdd3(n: int): bool = n != ((n shr 1) shl 1)\nproc isEven3(n: int): bool = n == ((n shr 1) shl 1)\n\necho isEven(1)\necho isOdd2(5)\n" + }, + { + "id": 506, + "length": 348, + "source": "Rosetta Code", + "text": "import random\nimport imageman\n\nrandomize()\n\n# Build a color table.\nvar colors: array[256, ColorRGBU]\nfor color in colors.mitems:\n\tcolor = ColorRGBU [byte rand(255), byte rand(255), byte rand(255)]\n\nvar image = initImage[ColorRGBU](256, 256)\n\nfor i in 0..255:\n\tfor j in 0..255:\n\t\timage[i, j] = colors[i xor j]\n\nimage.savePNG(\"munching_squares.png\")\n" + }, + { + "id": 507, + "length": 423, + "source": "Rosetta Code", + "text": "import math\n\nproc radians(x): float = x * Pi / 180\n\nproc haversine(lat1, lon1, lat2, lon2): float =\n\tconst r = 6372.8 # Earth radius in kilometers\n\tlet\n\t\tdLat = radians(lat2 - lat1)\n\t\tdLon = radians(lon2 - lon1)\n\t\tlat1 = radians(lat1)\n\t\tlat2 = radians(lat2)\n\n\t\ta = sin(dLat/2)*sin(dLat/2) + cos(lat1)*cos(lat2)*sin(dLon/2)*sin(dLon/2)\n\t\tc = 2*arcsin(sqrt(a))\n\n\tresult = r * c\n\necho haversine(36.12, -86.67, 33.94, -118.40)\n" + }, + { + "id": 508, + "length": 432, + "source": "Rosetta Code", + "text": "from math import sqrt\nfrom strutils import parseFloat, formatFloat, ffDecimal\n\nproc agm(x,y: float): tuple[resA,resG: float] =\n\tvar\n\t\ta,g: array[0 .. 23,float]\n\n\ta[0] = x\n\tg[0] = y\n\n\tfor n in 1 .. 23:\n\t\ta[n] = 0.5 * (a[n - 1] + g[n - 1])\n\t\tg[n] = sqrt(a[n - 1] * g[n - 1])\n\n\t(a[23], g[23])\n\nvar t = agm(1, 1/sqrt(2.0))\n\necho(\"Result A: \" & formatFloat(t.resA, ffDecimal, 24))\necho(\"Result G: \" & formatFloat(t.resG, ffDecimal, 24))\n" + }, + { + "id": 509, + "length": 314, + "source": "Rosetta Code", + "text": "import strutils\n\nconst MD4Len = 16\n\nproc MD4(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: \"libssl.so\", importc.}\n\nproc MD4(s: string): string =\n\tresult = \"\"\n\tvar s = MD4(s.cstring, s.len.culong)\n\tfor i in 0 ..< MD4Len:\n\t\tresult.add s[i].BiggestInt.toHex(2).toLower\n\necho MD4(\"Hello world!\")\n" + }, + { + "id": 510, + "length": 413, + "source": "Rosetta Code", + "text": "import std/wordwrap\n\nlet txt = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.\"\necho txt.wrapWords()\necho \"\"\necho txt.wrapWords(45)\n" + }, + { + "id": 511, + "length": 451, + "source": "Rosetta Code", + "text": "proc consolidate(sets: varargs[set[char]]): seq[set[char]] =\n\tif len(sets) < 2:\n\t\treturn @sets\n\tvar (r, b) = (@[sets[0]], consolidate(sets[1..^1]))\n\tfor x in b:\n\t\tif len(r[0] * x) != 0:\n\t\t\tr[0] = r[0] + x\n\t\telse:\n\t\t\tr.add(x)\n\tr\n\necho consolidate({'A', 'B'}, {'C', 'D'})\necho consolidate({'A', 'B'}, {'B', 'D'})\necho consolidate({'A', 'B'}, {'C', 'D'}, {'D', 'B'})\necho consolidate({'H', 'I', 'K'}, {'A', 'B'}, {'C', 'D'}, {'D', 'B'}, {'F', 'G', 'H'})\n" + }, + { + "id": 512, + "length": 318, + "source": "Rosetta Code", + "text": "import math, rdstdin, strutils, algorithm, sequtils\n\nproc f(x: float): float = x.abs.pow(0.5) + 5 * x.pow(3)\n\nproc ask: seq[float] =\n\treadLineFromStdin(\"11 numbers: \").strip.split[0..10].map(parseFloat)\n\nvar s = ask()\nreverse s\nfor x in s:\n\tlet result = f(x)\n\techo x, \": \", if result > 400: \"TOO LARGE!\" else: $result\n" + }, + { + "id": 513, + "length": 469, + "source": "Rosetta Code", + "text": "import sequtils\n\niterator castOut(base = 10, start = 1, ending = 999_999): int =\n\tvar ran: seq[int] = @[]\n\tfor y in 0 ..< base-1:\n\t\tif y mod (base - 1) == (y*y) mod (base - 1):\n\t\t\tran.add(y)\n\n\tvar x = start div (base - 1)\n\tvar y = start mod (base - 1)\n\n\tblock outer:\n\t\twhile true:\n\t\t\tfor n in ran:\n\t\t\t\tlet k = (base - 1) * x + n\n\t\t\t\tif k < start:\n\t\t\t\t\tcontinue\n\t\t\t\tif k > ending:\n\t\t\t\t\tbreak outer\n\t\t\t\tyield k\n\t\t\tinc x\n\necho toSeq(castOut(base=16, start=1, ending=255))\n" + }, + { + "id": 514, + "length": 507, + "source": "Rosetta Code", + "text": "import strutils\n\nproc floyd(rowcount = 5): seq[seq[int]] =\n\tresult = @[@[1]]\n\twhile result.len < rowcount:\n\t\tlet n = result[result.high][result.high] + 1\n\t\tvar row = newSeq[int]()\n\t\tfor i in n .. n + result[result.high].len:\n\t\t\trow.add i\n\t\tresult.add row\n\nproc pfloyd(rows: seq[seq[int]]) =\n\tvar colspace = newSeq[int]()\n\tfor n in rows[rows.high]: colspace.add(($n).len)\n\tfor row in rows:\n\t\tfor i, x in row:\n\t\t\tstdout.write align($x, colspace[i]),\" \"\n\t\techo \"\"\n\nfor i in [5, 14]:\n\tpfloyd(floyd(i))\n\techo \"\"\n" + }, + { + "id": 515, + "length": 401, + "source": "Rosetta Code", + "text": "import math, complex\n\nproc meanAngle(deg: openArray[float]): float =\n\tvar c: Complex[float]\n\tfor d in deg:\n\t\tc += rect(1.0, degToRad(d))\n\tradToDeg(phase(c / float(deg.len)))\n\necho \"The 1st mean angle is: \", meanAngle([350.0, 10.0]), \" degrees\"\necho \"The 2nd mean angle is: \", meanAngle([90.0, 180.0, 270.0, 360.0]), \" degrees\"\necho \"The 3rd mean angle is: \", meanAngle([10.0, 20.0, 30.0]), \" degrees\"\n" + }, + { + "id": 516, + "length": 357, + "source": "Rosetta Code", + "text": "import strutils\n\nproc droot(n: int64): auto =\n\tvar x = @[n]\n\twhile x[x.high] > 10:\n\t\tvar s = 0'i64\n\t\tfor dig in $x[x.high]:\n\t\t\ts += parseInt(\"\" & dig)\n\t\tx.add s\n\treturn (x.len - 1, x[x.high])\n\nfor n in [627615'i64, 39390'i64, 588225'i64, 393900588225'i64]:\n\tlet (a, d) = droot(n)\n\techo align($n, 12),\" has additive persistence \",a,\" and digital root of \",d\n" + }, + { + "id": 517, + "length": 515, + "source": "Rosetta Code", + "text": "import strutils\n\ntype\n\tNode[T] = ref object\n\t\tdata: T\n\t\tleft, right: Node[T]\n\nproc n[T](data: T; left, right: Node[T] = nil): Node[T] =\n\tNode[T](data: data, left: left, right: right)\n\nproc indent[T](n: Node[T]): seq[string] =\n\tif n == nil: return @[\"-- (null)\"]\n\n\tresult = @[\"--\" & $n.data]\n\n\tfor a in indent n.left: result.add \" |\" & a\n\n\tlet r = indent n.right\n\tresult.add \" `\" & r[0]\n\tfor a in r[1..r.high]: result.add \" \" & a\n\nlet tree = 1.n(2.n(4.n(7.n),5.n),3.n(6.n(8.n,9.n)))\n\necho tree.indent.join(\"\\n\")\n" + }, + { + "id": 518, + "length": 441, + "source": "Rosetta Code", + "text": "import strutils, sequtils, sets, algorithm\n\nproc reversed(s: string): string =\n\tresult = newString(s.len)\n\tfor i, c in s:\n\t\tresult[s.high - i] = c\n\nlet\n\twords = readFile(\"unixdict.txt\").strip().splitLines()\n\twordset = words.toHashSet\n\trevs = words.map(reversed)\nvar pairs = zip(words, revs).filterIt(it[0] < it[1] and it[1] in wordset)\n\necho \"Total number of semordnilaps: \", pairs.len\npairs = pairs.sortedByIt(it[0].len)\necho pairs[^5..^1]\n" + }, + { + "id": 519, + "length": 462, + "source": "Rosetta Code", + "text": "import sequtils\n\nblock:\n\tlet\n\t\tnumbers = @[5, 9, 11]\n\t\taddition = foldl(numbers, a + b)\n\t\tsubstraction = foldl(numbers, a - b)\n\t\tmultiplication = foldl(numbers, a * b)\n\t\twords = @[\"nim\", \"is\", \"cool\"]\n\t\tconcatenation = foldl(words, a & b)\n\nblock:\n\tlet\n\t\tnumbers = @[5, 9, 11]\n\t\taddition = foldr(numbers, a + b)\n\t\tsubstraction = foldr(numbers, a - b)\n\t\tmultiplication = foldr(numbers, a * b)\n\t\twords = @[\"nim\", \"is\", \"cool\"]\n\t\tconcatenation = foldr(words, a & b)\n" + }, + { + "id": 520, + "length": 341, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nproc z(n: Natural): string =\n\tif n == 0: return \"0\"\n\tvar fib = @[2,1]\n\tvar n = n\n\twhile fib[0] < n: fib.insert(fib[0] + fib[1])\n\tfor f in fib:\n\t\tif f <= n:\n\t\t\tresult.add '1'\n\t\t\tdec n, f\n\t\telse:\n\t\t\tresult.add '0'\n\tif result[0] == '0':\n\t\tresult = result[1..result.high]\n\nfor i in 0 .. 20:\n\techo &\"{i:>3} {z(i):>8}\"\n" + }, + { + "id": 521, + "length": 359, + "source": "Rosetta Code", + "text": "import sequtils, strutils, sugar\n\nproc j(n, k: int): string =\n\tvar\n\t\tp = toSeq(0 ..< n)\n\t\ti = 0\n\t\ts = newSeq[int]()\n\n\twhile p.len > 0:\n\t\ti = (i + k - 1) mod p.len\n\t\ts.add p[i]\n\t\tsystem.delete(p, i)\n\n\tresult = \"Prisoner killing order: \"\n\tresult.add s.map((x: int) => $x).join(\", \")\n\tresult.add \".\\nSurvivor: \"\n\tresult.add($s[s.high])\n\necho j(5,2)\necho j(41,3)\n" + }, + { + "id": 522, + "length": 323, + "source": "Rosetta Code", + "text": "func prisonerPos(n, k: Positive): int =\n\t## The result is computed backwards. We start from the winner at\n\t## position 0 on last round and compute its position on previous rounds.\n\tvar pos = 0\n\tfor i in 2..n:\n\t\tpos = (pos + k) mod i\n\tresult = pos\n\necho \"Survivor: \", prisonerPos(5, 2)\necho \"Survivor: \", prisonerPos(41, 3)\n" + }, + { + "id": 523, + "length": 332, + "source": "Rosetta Code", + "text": "import strutils\n\nconst SHA256Len = 32\n\nproc SHA256(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: \"libssl.so\", importc.}\n\nproc SHA256(s: string): string =\n\tresult = \"\"\n\tlet s = SHA256(s.cstring, s.len.culong)\n\tfor i in 0 ..< SHA256Len:\n\t\tresult.add s[i].BiggestInt.toHex(2).toLower\n\necho SHA256(\"Hello world!\")\n" + }, + { + "id": 524, + "length": 355, + "source": "Rosetta Code", + "text": "# Recursive\nproc multifact(n, deg: int): int =\n\tresult = (if n <= deg: n else: n * multifact(n - deg, deg))\n\n# Iterative\nproc multifactI(n, deg: int): int =\n\tresult = n\n\tvar n = n\n\twhile n >= deg + 1:\n\t\tresult *= n - deg\n\t\tn -= deg\n\nfor i in 1..5:\n\tstdout.write \"Degree \", i, \": \"\n\tfor j in 1..10:\n\t\tstdout.write multifactI(j, i), \" \"\n\tstdout.write('\\n')\n" + }, + { + "id": 525, + "length": 516, + "source": "Rosetta Code", + "text": "proc middleThreeDigits(i: int): string =\n\tvar s = $abs(i)\n\tif s.len < 3 or s.len mod 2 == 0:\n\t\traise newException(ValueError, \"Need odd and >= 3 digits\")\n\tlet mid = s.len div 2\n\treturn s[mid-1..mid+1]\n\nconst passing = @[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]\nconst failing = @[1, 2, -1, -10, 2002, -2002, 0]\n\nfor i in passing & failing:\n\tvar answer = try: middleThreeDigits(i)\n\t\t\t\t\t\t\t except ValueError: getCurrentExceptionMsg()\n\techo \"middleThreeDigits(\", i, \") returned: \", answer\n" + }, + { + "id": 526, + "length": 553, + "source": "Rosetta Code", + "text": "import strformat, terminal\n\nproc eraseLineEnd() = stdout.write(\"\\e[K\")\n\nproc inputXYUpto(row, col, cmax: int; width = cmax): string =\n\twhile result.len < cmax and not ((let c = getch(); c) in ['\\xff', '\\f', '\\r']):\n\t\tsetCursorPos(row, col)\n\t\teraseLineEnd()\n\t\tif c in ['\\b', '\\x7f'] and result.len > 0:\n\t\t\tresult.setLen(result.len - 1)\n\t\telse:\n\t\t\tresult.add c\n\t\tstdout.write result[(if result.len > width: result.len - width else: 0)..result.high]\n\neraseScreen()\nsetCursorPos(3, 5)\nlet s = inputXYUpto(3, 5, 8)\necho &\"\\n\\n\\nResult: You entered <<{s}>>\"\n" + }, + { + "id": 527, + "length": 557, + "source": "Rosetta Code", + "text": "import strformat, terminal\n\nproc eraseLineEnd() = stdout.write(\"\\e[K\")\n\nproc inputXYUpto(row, col, cmax: int; width = cmax): string =\n\twhile result.len < cmax and not ((let c = getch(); c) in ['\\xff', '\\f', '\\r']):\n\t\tsetCursorPos(row, col)\n\t\teraseLineEnd()\n\t\tif c in ['\\b', '\\x7f'] and result.len > 0:\n\t\t\tresult.setLen(result.len - 1)\n\t\telse:\n\t\t\tresult.add c\n\t\tstdout.write result[(if result.len > width: result.len - width else: 0)..result.high]\n\neraseScreen()\nsetCursorPos(3, 5)\nlet s = inputXYUpto(3, 5, 80, 8)\necho &\"\\n\\n\\nResult: You entered <<{s}>>\"\n" + }, + { + "id": 528, + "length": 337, + "source": "Rosetta Code", + "text": "import strutils\n\nvar s1: string = \"The quick brown\"\nvar s2: string = \"The Quick Brown\"\necho(\"== : \", s1 == s2)\necho(\"!= : \", s1 != s2)\necho(\"< : \", s1 < s2)\necho(\"<= : \", s1 <= s2)\necho(\"> : \", s1 > s2)\necho(\">= : \", s1 >= s2)\n# cmpIgnoreCase(a, b) => 0 if a == b; < 0 if a < b; > 0 if a > b\necho(\"cmpIgnoreCase :\", s1.cmpIgnoreCase s2)\n" + }, + { + "id": 529, + "length": 468, + "source": "Rosetta Code", + "text": "import os, math, strutils, tables\n\nlet execName = getAppFilename().splitPath().tail\nlet srcName = execName & \".nim\"\n\nfunc entropy(str: string): float =\n\tvar counts: CountTable[char]\n\tfor ch in str:\n\t\tcounts.inc(ch)\n\tfor count in counts.values:\n\t\tresult -= count / str.len * log2(count / str.len)\n\necho \"Source file entropy: \", srcName.readFile().entropy().formatFloat(ffDecimal, 5)\necho \"Binary file entropy: \", execName.readFile().entropy().formatFloat(ffDecimal, 5)\n" + }, + { + "id": 530, + "length": 409, + "source": "Rosetta Code", + "text": "import unicode\n\nproc readUtf8(f: File): string =\n\t## Return next UTF-8 character as a string.\n\twhile true:\n\t\tresult.add f.readChar()\n\t\tif result.validateUtf8() == -1: break\n\niterator readUtf8(f: File): string =\n\t## Yield successive UTF-8 characters from file \"f\".\n\tvar res: string\n\twhile not f.endOfFile:\n\t\tres.setLen(0)\n\t\twhile true:\n\t\t\tres.add f.readChar()\n\t\t\tif res.validateUtf8() == -1: break\n\t\tyield res\n" + }, + { + "id": 531, + "length": 397, + "source": "Rosetta Code", + "text": "proc slice[T](iter: iterator(): T {.closure.}; sl: Slice[T]): seq[T] =\n\tvar i = 0\n\tfor n in iter():\n\t\tif i > sl.b: break\n\t\tif i >= sl.a: result.add(n)\n\t\tinc i\n\niterator harshad(): int {.closure.} =\n\tfor n in 1 ..< int.high:\n\t\tvar sum = 0\n\t\tfor ch in $n:\n\t\t\tsum += ord(ch) - ord('0')\n\t\tif n mod sum == 0:\n\t\t\tyield n\n\necho harshad.slice 0 ..< 20\n\nfor n in harshad():\n\tif n > 1000:\n\t\techo n\n\t\tbreak\n" + }, + { + "id": 532, + "length": 372, + "source": "Rosetta Code", + "text": "import strutils\n\nlet input = \"\"\">Example_1\n\t\tTHERECANBENOSPACE\n\t\t>Example_2\n\t\tTHERECANBESEVERAL\n\t\tLINESBUTTHEYALLMUST\n\t\tBECONCATENATED\"\"\".unindent\n\nproc fasta*(input: string) =\n\t\tvar row = \"\"\n\t\tfor line in input.splitLines:\n\t\t\t\tif line.startsWith(\">\"):\n\t\t\t\t\t\tif row != \"\": echo row\n\t\t\t\t\t\trow = line[1..^1] & \": \"\n\t\t\t\telse:\n\t\t\t\t\t\trow &= line.strip\n\t\techo row\n\nfasta(input)\n" + }, + { + "id": 533, + "length": 326, + "source": "Rosetta Code", + "text": "import bigints\n\nproc perm(n, k: int32): BigInt =\n\tresult = initBigInt 1\n\tvar\n\t\tk = n - k\n\t\tn = n\n\twhile n > k:\n\t\tresult *= n\n\t\tdec n\n\nproc comb(n, k: int32): BigInt =\n\tresult = perm(n, k)\n\tvar k = k\n\twhile k > 0:\n\t\tresult = result div k\n\t\tdec k\n\necho \"P(1000, 969) = \", perm(1000, 969)\necho \"C(1000, 969) = \", comb(1000, 969)\n" + }, + { + "id": 534, + "length": 450, + "source": "Rosetta Code", + "text": "import os, strutils, times\n\nconst\n\tDaysInMonth: array[Month, int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\tDayDiffs: array[WeekDay, int] = [1, 2, 3, 4, 5, 6, 0]\n\nlet year = paramStr(1).parseInt\n\nfor month in mJan..mDec:\n\tvar lastDay = DaysInMonth[month]\n\tif month == mFeb and year.isLeapYear: lastDay = 29\n\tvar date = initDateTime(lastDay, month, year, 0, 0, 0)\n\tdate = date - days(DayDiffs[date.weekday])\n\techo date.format(\"yyyy-MM-dd\")\n" + }, + { + "id": 535, + "length": 467, + "source": "Rosetta Code", + "text": "import bigints\n\nvar cache = @[@[1.initBigInt]]\n\nproc cumu(n: int): seq[BigInt] =\n\tfor m in cache.len .. n:\n\t\tvar r = @[0.initBigInt]\n\t\tfor x in 1..m:\n\t\t\tr.add r[r.high] + cache[m-x][min(x, m-x)]\n\t\tcache.add r\n\tresult = cache[n]\n\nproc row(n: int): seq[BigInt] =\n\tlet r = cumu n\n\tresult = @[]\n\tfor i in 0 ..< n:\n\t\tresult.add r[i+1] - r[i]\n\necho \"rows:\"\nfor x in 1..10:\n\techo row x\n\necho \"sums:\"\nfor x in [23, 123, 1234, 12345]:\n\tlet c = cumu(x)\n\techo x, \" \", c[c.high]\n" + }, + { + "id": 536, + "length": 452, + "source": "Rosetta Code", + "text": "import bigints\n\nvar p = @[1.initBigInt]\n\nproc partitions(n): BigInt =\n\tp.add 0.initBigInt\n\n\tfor k in 1..n:\n\t\tvar d = n - k * (3 * k - 1) div 2\n\t\tif d < 0:\n\t\t\tbreak\n\n\t\tif (k and 1) != 0:\n\t\t\tp[n] += p[d]\n\t\telse:\n\t\t\tp[n] -= p[d]\n\n\t\td -= k\n\t\tif d < 0:\n\t\t\tbreak\n\n\t\tif (k and 1) != 0:\n\t\t\tp[n] += p[d]\n\t\telse:\n\t\t\tp[n] -= p[d]\n\n\tresult = p[p.high]\n\nconst ns = [23, 123, 1234, 12345]\nfor i in 1 .. max(ns):\n\tlet p = partitions(i)\n\tif i in ns:\n\t\techo i, \": \", p\n" + }, + { + "id": 537, + "length": 446, + "source": "Rosetta Code", + "text": "import strutils\n\nproc isRepeated(text: string): int =\n\tfor x in countdown(text.len div 2, 0):\n\t\tif text.startsWith(text[x..text.high]): return x\n\nconst matchstr = \"\"\"\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\"\"\"\n\nfor line in matchstr.split():\n\tlet ln = isRepeated(line)\n\techo \"'\", line, \"' has a repetition length of \", ln, \" i.e \",\n\t\t(if ln > 0: \"'\" & line[0 ..< ln] & \"'\" else: \"*not* a rep-string\")\n" + }, + { + "id": 538, + "length": 368, + "source": "Rosetta Code", + "text": "import bigints\n\nproc sumMults(first: int32, limit: BigInt): BigInt =\n\tvar last = limit - 1\n\tlast -= last mod first\n\t(last div first) * (last + first) div 2\n\nproc sum35(n: BigInt): BigInt =\n\tresult = sumMults(3, n)\n\tresult += sumMults(5, n)\n\tresult -= sumMults(15, n)\n\nvar x = 1.initBigInt\nwhile x < \"1000000000000000000000000000000\".initBigInt:\n\techo sum35 x\n\tx *= 10\n" + }, + { + "id": 539, + "length": 491, + "source": "Rosetta Code", + "text": "import random, strformat\n\nconst T = 100\n\nvar\n\tpList = [0.1, 0.3, 0.5, 0.7, 0.9]\n\tnList = [100, 1_000, 10_000, 100_000]\n\nfor p in pList:\n\n\tlet theory = p * (1 - p)\n\techo &\"\\np: {p:.4f} theory: {theory:.4f} t: {T}\"\n\techo \" n sim sim-theory\"\n\n\tfor n in nList:\n\t\tvar sum = 0\n\t\tfor _ in 1..T:\n\t\t\tvar run = false\n\t\t\tfor _ in 1..n:\n\t\t\t\tlet one = rand(1.0) < p\n\t\t\t\tif one and not run: inc sum\n\t\t\t\trun = one\n\n\t\tlet k = sum / (T * n)\n\t\techo &\"{n:9} {k:15.4f} {k - theory:10.6f}\"\n" + }, + { + "id": 540, + "length": 408, + "source": "Rosetta Code", + "text": "proc longestIncreasingSubsequence[T](d: seq[T]): seq[T] =\n\tvar l: seq[seq[T]]\n\tfor i in 0 .. d.high:\n\t\tvar x: seq[T]\n\t\tfor j in 0 ..< i:\n\t\t\tif l[j][l[j].high] < d[i] and l[j].len > x.len:\n\t\t\t\tx = l[j]\n\t\tl.add x & @[d[i]]\n\tfor x in l:\n\t\tif x.len > result.len:\n\t\t\tresult = x\n\nfor 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\techo \"A L.I.S. of \", d, \" is \", longestIncreasingSubsequence(d)\n" + }, + { + "id": 541, + "length": 511, + "source": "Rosetta Code", + "text": "import os, strutils\necho commandLineParams().join(\" \")\n#################################################\nproc qselect[T](a: var openarray[T]; k: int, inl = 0, inr = -1): T =\n\tvar r = if inr >= 0: inr else: a.high\n\tvar st = 0\n\tfor i in 0 ..< r:\n\t\tif a[i] > a[r]: continue\n\t\tswap a[i], a[st]\n\t\tinc st\n\n\tswap a[r], a[st]\n\n\tif k == st: a[st]\n\telif st > k: qselect(a, k, 0, st - 1)\n\telse: qselect(a, k, st, inr)\n\nlet x = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]\n\nfor i in 0..9:\n\tvar y = x\n\techo i, \": \", qselect(y, i)\n" + }, + { + "id": 542, + "length": 459, + "source": "Rosetta Code", + "text": "proc mulInv(a0, b0: int): int =\n\tvar (a, b, x0) = (a0, b0, 0)\n\tresult = 1\n\tif b == 1: return\n\twhile a > 1:\n\t\tlet q = a div b\n\t\ta = a mod b\n\t\tswap a, b\n\t\tresult = result - q * x0\n\t\tswap x0, result\n\tif result < 0: result += b0\n\nproc chineseRemainder[T](n, a: T): int =\n\tvar prod = 1\n\tvar sum = 0\n\tfor x in n: prod *= x\n\n\tfor i in 0.. 9:\n\t\tvar n = 1\n\t\tfor dig in $mdr[mdr.high]:\n\t\t\tn *= parseInt($dig)\n\t\tmdr.add n\n\t(mdr.high, mdr[mdr.high])\n\nfor n in [123321, 7739, 893, 899998]:\n\techo align($n, 6),\" \",mdroot(n)\necho \"\"\n\nvar table = newSeqWith(10, newSeq[int]())\nfor n in 0..int.high:\n\tif table.map((x: seq[int]) => x.len).min >= 5: break\n\ttable[mdroot(n).mdr].add n\n\nfor mp, val in table:\n\techo mp, \": \", val[0..4]\n" + }, + { + "id": 552, + "length": 416, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils\nimport itertools\n\nconst Scoring = [0, 1, 3]\n\nvar histo: array[4, array[10, int]]\n\nfor results in product([0, 1, 2], repeat = 6):\n\tvar s: array[4, int]\n\tfor (r, g) in zip(results, toSeq(combinations([0, 1, 2, 3], 2))):\n\t\ts[g[0]] += Scoring[r]\n\t\ts[g[1]] += Scoring[2 - r]\n\tfor i, v in sorted(s):\n\t\tinc histo[i][v]\n\nfor x in reversed(histo):\n\techo x.mapIt(($it).align(3)).join(\" \")\n" + }, + { + "id": 553, + "length": 383, + "source": "Rosetta Code", + "text": "import streams\n\nproc tokenize(s: Stream, sep: static[char] = '|', esc: static[char] = '^'): seq[string] =\n\tvar buff = \"\"\n\twhile not s.atEnd():\n\t\tlet c = s.readChar\n\t\tcase c\n\t\tof sep:\n\t\t\tresult.add buff\n\t\t\tbuff = \"\"\n\t\tof esc:\n\t\t\tbuff.add s.readChar\n\t\telse:\n\t\t\tbuff.add c\n\tresult.add buff\n\nfor i, s in tokenize(newStringStream \"one^|uno||three^^^^|four^^^|^cuatro|\"):\n\t\techo i, \":\", s\n" + }, + { + "id": 554, + "length": 470, + "source": "Rosetta Code", + "text": "func allEqual(s: openArray[string]): bool =\n\n\tfor i in 1..s.high:\n\t\tif s[i] != s[0]:\n\t\t\treturn false\n\tresult = true\n\nfunc ascending(s: openArray[string]): bool =\n\n\tfor i in 1..s.high:\n\t\tif s[i] <= s[i - 1]:\n\t\t\treturn false\n\tresult = true\n\ndoAssert allEqual([\"abc\", \"abc\", \"abc\"])\ndoAssert not allEqual([\"abc\", \"abd\", \"abc\"])\n\ndoAssert ascending([\"abc\", \"abd\", \"abe\"])\ndoAssert not ascending([\"abc\", \"abe\", \"abd\"])\n\ndoAssert allEqual([\"abc\"])\ndoAssert ascending([\"abc\"])\n" + }, + { + "id": 555, + "length": 435, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc isPrime(n: int): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\ttrue\n\nvar count = 1\nwrite(stdout, \" 2\")\nfor i in countup(3, 1999, 2):\n\tif isPrime(i):\n\t\tinc count\n\t\twrite(stdout, fmt\"{i:5}\")\n\t\tif count mod 15 == 0:\n\t\t\twrite(stdout, \"\\n\")\necho()\n" + }, + { + "id": 556, + "length": 310, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils\n\nconst Phrase = \"phrase reversal\"\n\necho \"Phrase: \", Phrase\necho \"Reversed phrase: \", reversed(Phrase).join()\necho \"Reversed words: \", Phrase.split().mapIt(reversed(it).join()).join(\" \")\necho \"Reversed word order: \", reversed(Phrase.split()).join(\" \")\n" + }, + { + "id": 557, + "length": 523, + "source": "Rosetta Code", + "text": "from math import sqrt\n\nconst N = 524_000_000.int32\n\nproc sumProperDivisors(someNum: int32, chk4less: bool): int32 =\n\t\tresult = 1\n\t\tlet maxPD = sqrt(someNum.float).int32\n\t\tlet offset = someNum mod 2\n\t\tfor divNum in countup(2 + offset, maxPD, 1 + offset):\n\t\t\t\tif someNum mod divNum == 0:\n\t\t\t\t\t\tresult += divNum + someNum div divNum\n\t\t\t\t\t\tif chk4less and result >= someNum:\n\t\t\t\t\t\t\t\treturn 0\n\nfor n in countdown(N, 2):\n\t\tlet m = sumProperDivisors(n, true)\n\t\tif m != 0 and n == sumProperDivisors(m, false):\n\t\t\t\techo $n, \" \", $m\n" + }, + { + "id": 558, + "length": 288, + "source": "Rosetta Code", + "text": "from math import sqrt\n\nconst N = 524_000_000.int32\nvar x = newSeq[int32](N+1)\n\nfor i in 2..sqrt(N.float).int32:\n\tvar p = i*i\n\tx[p] += i\n\tvar j = i + i\n\twhile (p += i; p <= N):\n\t\tj.inc\n\t\tx[p] += j\n\nfor m in 4..N:\n\tlet n = x[m] + 1\n\tif n < m and n != 0 and m == x[n] + 1:\n\t\t\techo n, \" \", m\n" + }, + { + "id": 559, + "length": 513, + "source": "Rosetta Code", + "text": "proc sumProperDivisors(number: int) : int =\n\tif number < 2 : return 0\n\tfor i in 1 .. number div 2 :\n\t\tif number mod i == 0 : result += i\n\nvar\n\tsum : int\n\tdeficient = 0\n\tperfect = 0\n\tabundant = 0\n\nfor n in 1 .. 20000 :\n\tsum = sumProperDivisors(n)\n\tif sum < n :\n\t\tinc(deficient)\n\telif sum == n :\n\t\tinc(perfect)\n\telse :\n\t\tinc(abundant)\n\necho \"The classification of the numbers between 1 and 20,000 is as follows :\\n\"\necho \" Deficient = \" , deficient\necho \" Perfect = \" , perfect\necho \" Abundant = \" , abundant\n" + }, + { + "id": 560, + "length": 444, + "source": "Rosetta Code", + "text": "# Longest common substring.\n\nimport sequtils\n\nfunc lcs(a, b: string): string =\n\tvar lengths = newSeqWith(a.len, newSeq[int](b.len))\n\tvar greatestLength = 0\n\tfor i, x in a:\n\t\tfor j, y in b:\n\t\t\tif x == y:\n\t\t\t\tlengths[i][j] = if i == 0 or j == 0: 1 else: lengths[i - 1][j - 1] + 1\n\t\t\t\tif lengths[i][j] > greatestLength:\n\t\t\t\t\tgreatestLength = lengths[i][j]\n\t\t\t\t\tresult = a[(i - greatestLength + 1)..i]\n\necho lcs(\"thisisatest\", \"testing123testing\")\n" + }, + { + "id": 561, + "length": 327, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\nlet firstLine = \"/proc/stat\".readLines(1)[0]\nlet values = firstLine.splitWhitespace()[1..^1].map(parseInt)\nlet totalTime = sum(values)\nlet idleFrac = values[3] / totalTime\nlet notIdlePerc = (1 - idleFrac) * 100\necho \"CPU utilization = \", notIdlePerc.formatFloat(ffDecimal, precision = 1), \" %\"\n" + }, + { + "id": 562, + "length": 552, + "source": "Rosetta Code", + "text": "from strutils import addSep\n\nconst\n\tUnits = [\" wk\", \" d\", \" hr\", \" min\", \" sec\"]\n\tQuantities = [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]\n\nproc `$$`*(sec: int): string =\n\t## Convert a duration in seconds to a friendly string.\n\n\tdoAssert(sec > 0)\n\n\tvar duration = sec\n\tvar idx = 0\n\twhile duration != 0:\n\t\tlet q = duration div Quantities[idx]\n\t\tif q != 0:\n\t\t\tduration = duration mod Quantities[idx]\n\t\t\tresult.addSep(\", \", 0)\n\t\t\tresult.add($q & Units[idx])\n\t\tinc idx\n\nwhen isMainModule:\n\tfor sec in [7259, 86400, 6000000]:\n\t\techo sec, \"s = \", $$sec\n" + }, + { + "id": 563, + "length": 564, + "source": "Rosetta Code", + "text": "import times\nfrom algorithm import reversed\nfrom strutils import addSep\n\nconst Units = [\" wk\", \" d\", \" hr\", \" min\", \" sec\"]\n\nproc `$$`*(sec: int): string =\n\t## Convert a duration in seconds to a friendly string.\n\t## Similar to `$` but with other conventions.\n\n\tdoAssert(sec > 0)\n\n\tvar duration = initDuration(seconds = sec)\n\tlet parts = reversed(duration.toParts[Seconds..Weeks])\n\n\tfor idx, part in parts:\n\t\tif part != 0:\n\t\t\tresult.addSep(\", \", 0)\n\t\t\tresult.add($part & Units[idx])\n\nwhen isMainModule:\n\tfor sec in [7259, 86400, 6000000]:\n\t\techo sec, \"s = \", $$sec\n" + }, + { + "id": 564, + "length": 363, + "source": "Rosetta Code", + "text": "type Kind = enum kString, kFile\n\ntype Source = object\n\tcase kind: Kind\n\tof kString: str: string\n\tof kFile: file: File\n\nproc writeText(source: Source) =\n\tcase source.kind\n\tof kString: echo source.str\n\tof kFile: echo source.file.readAll()\n\nlet s1 = Source(kind: kString, str: \"Hello world!\")\nlet s2 = Source(kind: kFile, file: stdin)\n\ns1.writeText()\ns2.writeText()\n" + }, + { + "id": 565, + "length": 440, + "source": "Rosetta Code", + "text": "import math, sequtils, sugar, strformat\nfunc root(x: float): seq[float] = @[sqrt(x),-sqrt(x)]\nfunc asin(x: float): seq[float] = @[arcsin(x),arcsin(x)+TAU,arcsin(x)-TAU]\nfunc format(x: float): seq[string] = @[\"{x:.2f}\"]\n\n#'bind' is a nim keyword, how about an infix operator instead\n#our bind is the standard map+cat\nfunc `-->`[T,U](input: openArray[T],f: T -> seq[U]): seq[U] =\n\tinput.map(f).concat\n\necho [0.5] --> root --> asin --> format\n" + }, + { + "id": 566, + "length": 515, + "source": "Rosetta Code", + "text": "from math import sqrt\nfrom sugar import `=>`, `->`\n\ntype\n\tWriterUnit = (float, string)\n\tWriterBind = proc(a: WriterUnit): WriterUnit\n\nproc bindWith(f: (x: float) -> float; log: string): WriterBind =\n\tresult = (a: WriterUnit) => (f(a[0]), a[1] & log)\n\nfunc doneWith(x: int): WriterUnit =\n\t(x.float, \"\")\n\nvar\n\tlogRoot = sqrt.bindWith \"obtained square root, \"\n\tlogAddOne = ((x: float) => x+1'f).bindWith \"added 1, \"\n\tlogHalf = ((x: float) => x/2'f).bindWith \"divided by 2, \"\n\necho 5.doneWith.logRoot.logAddOne.logHalf\n" + }, + { + "id": 567, + "length": 432, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\nconst\n\tWidth = 400\n\tHeight = 400\n\nvar img = initImage[ColorRGBF](Width, Height)\nfor x in 0.. stream2.peekLine.parseInt: stream2.readLine else: stream1.readLine)\n\nfor line in stream1.lines:\n\techo line\nfor line in stream2.lines:\n\techo line\n" + }, + { + "id": 570, + "length": 344, + "source": "Rosetta Code", + "text": "import macros, strformat\n\nproc f(arg: int): int = arg+1\n\nmacro getSource(source: static[string]) =\n\tlet module = parseStmt(source)\n\tfor node in module.children:\n\t\tif node.kind == nnkProcDef:\n\t\t\techo(\"source of procedure {node.name} is:\\n{toStrLit(node).strVal}\")\n\nproc g(arg: float): float = arg*arg\n\ngetSource(staticRead(currentSourcePath()))\n" + }, + { + "id": 571, + "length": 551, + "source": "Rosetta Code", + "text": "import random\n\nproc sattoloCycle[T](a: var openArray[T]) =\n\tfor i in countdown(a.high, 1):\n\t\tlet j = rand(int.high) mod i\n\t\tswap a[j], a[i]\n\nvar a: seq[int] = @[]\nvar b: seq[int] = @[10]\nvar c: seq[int] = @[10, 20]\nvar d: seq[int] = @[10, 20, 30]\nvar e: seq[int] = @[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]\n\nrandomize()\n\na.sattoloCycle()\necho \"Shuffled a = \", $a\n\nb.sattoloCycle()\necho \"\\nShuffled b = \", $b\n\nc.sattoloCycle()\necho \"\\nShuffled c = \", $c\n\nd.sattoloCycle()\necho \"\\nShuffled d = \", $d\n\ne.sattoloCycle()\necho \"\\nShuffled e = \", $e\n" + }, + { + "id": 572, + "length": 373, + "source": "Rosetta Code", + "text": "proc sortThree[T](a, b, c: var T) =\n\t# Bubble sort, why not?\n\twhile not (a <= b and b <= c):\n\t\tif a > b: swap a, b\n\t\tif b > c: swap b, c\n\nproc testWith[T](a, b, c: T) =\n\tvar (x, y, z) = (a, b, c)\n\techo \"Before: \", x, \", \", y, \", \", z\n\tsortThree(x, y, z)\n\techo \"After: \", x, \", \", y, \", \", z\n\ntestWith(6, 4, 2)\ntestWith(0.9, -37.1, 4.0)\ntestWith(\"lions\", \"tigers\", \"bears\")\n" + }, + { + "id": 573, + "length": 426, + "source": "Rosetta Code", + "text": "import strformat\n\nproc leonardoNumbers(count: int, L0: int = 1,\n\t\t\t\t\t\t\t\t\t\t L1: int = 1, ADD: int = 1) =\n\tvar t = 0\n\tvar (L0_loc, L1_loc) = (L0, L1)\n\tfor i in 0..2} = {($i).insertSep(sep=','):>19}\"\"\"\n\t\t\ti.inc i\n\t\t\tcontinue\n\t\tinc i\n\nmain()\n" + }, + { + "id": 584, + "length": 440, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\tWidth = 81\n\tHeight = 5\n\nvar lines: array[Height, string]\nfor line in lines.mitems: line = repeat('*', Width)\n\nproc cantor(start, length, index: Natural) =\n\tlet seg = length div 3\n\tif seg == 0: return\n\tfor i in index..= 5:\n\t\tbreak\necho \"$\\e[?25h\" # Restore the cursor.\n" + }, + { + "id": 589, + "length": 555, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\nconst\n\tSize = 600\n\tBackground = ColorRGBU [byte 0, 0, 0]\n\tForeground = ColorRGBU [byte 0, 255, 0]\n\tC = (sqrt(5.0) + 1) / 2\n\tNumberOfSeeds = 6000\n\tFn = float(NumberOfSeeds)\n\nvar image = initImage[ColorRGBU](Size, Size)\nimage.fill(Background)\n\nfor i in 0..2}, {last:>2}, {step:>2}): \"\n\n\techo if step > 0: ($toSeq(countup(first, last, step)))[1..^1]\n\t\t\t elif step < 0: ($toSeq(countdown(first, last, -step)))[1..^1]\n\t\t\t else: \"not allowed.\"\n\nfor (f, l, s) in [(-2, 2, 1), (-2, 2, 0), (-2, 2, -1),\n\t\t\t\t\t\t\t\t\t(-2, 2, 10), (2, -2, 1), (2, 2, 1),\n\t\t\t\t\t\t\t\t\t(2, 2, -1), (2, 2, 0), (0, 0, 0)]:\n\tdisplayRange(f, l, s)\n" + }, + { + "id": 591, + "length": 556, + "source": "Rosetta Code", + "text": "import algorithm\n\nproc reverse(infile, outfile: string) =\n\n\tlet input = infile.open(fmRead)\n\tdefer: input.close()\n\tlet output = outfile.open(fmWrite)\n\tdefer: output.close()\n\n\tvar buffer: array[80, byte]\n\twhile not input.endOfFile:\n\t\tlet countRead = input.readBytes(buffer, 0, 80)\n\t\tif countRead < 80:\n\t\t\traise newException(IOError, \"truncated data when reading\")\n\t\tbuffer.reverse()\n\t\tlet countWrite = output.writeBytes(buffer, 0, 80)\n\t\tif countWrite < 80:\n\t\t\traise newException(IOError, \"truncated data when writing\")\n\nreverse(\"infile.dat\", \"outfile.dat\")\n" + }, + { + "id": 592, + "length": 506, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc totient(n: int): int =\n\tvar tot = n\n\tvar nn = n\n\tvar i = 2\n\twhile i * i <= nn:\n\t\tif nn mod i == 0:\n\t\t\twhile nn mod i == 0:\n\t\t\t\tnn = nn div i\n\t\t\tdec tot, tot div i\n\t\tif i == 2:\n\t\t\ti = 1\n\t\tinc i, 2\n\tif nn > 1:\n\t\tdec tot, tot div nn\n\ttot\n\nvar n = 1\nvar num = 0\necho \"The first 20 perfect totient numbers are:\"\nwhile num < 20:\n\tvar tot = n\n\tvar sum = 0\n\twhile tot != 1:\n\t\ttot = totient(tot)\n\t\tinc sum, tot\n\tif sum == n:\n\t\twrite(stdout, fmt\"{n} \")\n\t\tinc num\n\tinc n, 2\nwrite(stdout, \"\\n\")\n" + }, + { + "id": 593, + "length": 445, + "source": "Rosetta Code", + "text": "# First 20 antiprimes\n\nproc countDivisors(n: int): int =\n\t\tif n < 2:\n\t\t\t\treturn 1\n\t\tvar count = 2\n\t\tfor i in countup(2, (n / 2).toInt()):\n\t\t\t\tif n %% i == 0:\n\t\t\t\t\t\tcount += 1\n\t\treturn count\n\nproc antiPrimes(n: int) =\n\t\techo(\"The first \", n, \" anti-primes:\")\n\t\tvar maxDiv = 0\n\t\tvar count = 0\n\t\tvar i = 1\n\t\twhile count < n:\n\t\t\t\tlet d = countDivisors(i)\n\t\t\t\tif d > maxDiv:\n\t\t\t\t\t\techo(i)\n\t\t\t\t\t\tmaxDiv = d\n\t\t\t\t\t\tcount += 1\n\t\t\t\ti += 1\n\nantiPrimes(20)\n" + }, + { + "id": 594, + "length": 537, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc fusc(n: int): int =\n\tif n == 0 or n == 1:\n\t\tn\n\telif n mod 2 == 0:\n\t\tfusc(n div 2)\n\telse:\n\t\tfusc((n - 1) div 2) + fusc((n + 1) div 2)\n\necho \"The first 61 Fusc numbers:\"\nfor i in 0..61:\n\twrite(stdout, fmt\"{fusc(i)} \")\necho \"\\n\\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:\"\necho fmt\" n fusc(n)\"\necho \"--------- ---------\"\nvar maxLength = 0\nfor i in 0..700_000:\n\tvar f = fusc(i)\n\tvar length = len($f)\n\tif length > maxLength:\n\t\tmaxLength = length\n\t\techo fmt\"{i:9} {f:9}\"\n" + }, + { + "id": 595, + "length": 391, + "source": "Rosetta Code", + "text": "import strformat\n\nconst MAX = 15\n\nfunc countDivisors(n: int): int =\n\tvar i = 1\n\tvar count = 0\n\twhile i * i <= n:\n\t\tif n mod i == 0:\n\t\t\tif i == n div i:\n\t\t\t\tinc count\n\t\t\telse:\n\t\t\t\tinc count, 2\n\t\tinc i\n\tcount\n\nvar i, next = 1\necho fmt\"The first {MAX} terms of the sequence are:\"\nwhile next <= MAX:\n\tif next == countDivisors(i):\n\t\twrite(stdout, fmt\"{i} \")\n\t\tinc next\n\tinc i\nwrite(stdout, \"\\n\")\n" + }, + { + "id": 596, + "length": 445, + "source": "Rosetta Code", + "text": "import strformat\n\nconst MAX = 15\n\nfunc countDivisors(n: int): int =\n\tvar count = 0\n\tvar i = 1\n\twhile i * i <= n:\n\t\tif n mod i == 0:\n\t\t\tif i == n div i:\n\t\t\t\tinc count, 1\n\t\t\telse:\n\t\t\t\tinc count, 2\n\t\tinc i\n\tcount\n\nvar sequence: array[MAX, int]\necho fmt\"The first {MAX} terms of the sequence are:\"\nvar i = 1\nvar n = 0\nwhile n < MAX:\n\tvar k = countDivisors(i)\n\tif k <= MAX and sequence[k - 1] == 0:\n\t\tsequence[k - 1] = i\n\t\tinc n\n\tinc i\necho sequence\n" + }, + { + "id": 597, + "length": 480, + "source": "Rosetta Code", + "text": "type\n\tUnionKind = enum\n\t\tnkInt, nkFloat, nkString\n\tUnion = object\n\t\tcase kind: UnionKind\n\t\tof nkInt:\n\t\t\tintval: int\n\t\tof nkFloat:\n\t\t\tfloatval: float\n\t\tof nkString:\n\t\t\tstringval: string\nproc `$`(u: Union): string =\n\tcase u.kind\n\tof nkInt:\n\t\t$u.intval\n\tof nkFloat:\n\t\t$u.floatval\n\tof nkString:\n\t\t'\"' & $u.stringval & '\"'\nwhen isMainModule:\n\tlet\n\t\tu = Union(kind: nkInt, intval: 3)\n\t\tv = Union(kind: nkFloat, floatval: 3.14)\n\t\tw = Union(kind: nkString, stringval: \"pi\")\n\techo [u,v,w]\n" + }, + { + "id": 598, + "length": 473, + "source": "Rosetta Code", + "text": "import math\n\niterator b(): int =\n\t## Iterator yielding the bell numbers.\n\tvar numbers = @[1]\n\tyield 1\n\tvar n = 0\n\twhile true:\n\t\tvar next = 0\n\t\tfor k in 0..n:\n\t\t\tnext += binom(n, k) * numbers[k]\n\t\tnumbers.add(next)\n\t\tyield next\n\t\tinc n\n\nwhen isMainModule:\n\n\timport strformat\n\n\tconst Limit = 25 # Maximum index beyond which an overflow occurs.\n\n\techo \"Bell numbers from B0 to B25:\"\n\tvar i = 0\n\tfor n in b():\n\t\techo fmt\"{i:2d}: {n:>20d}\"\n\t\tinc i\n\t\tif i > Limit:\n\t\t\tbreak\n" + }, + { + "id": 599, + "length": 353, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nproc s1(n, k: Natural): Natural =\n\tif k == 0: return ord(n == 0)\n\tif k > n: return 0\n\ts1(n - 1, k - 1) + (n - 1) * s1(n - 1, k)\n\necho \" k \", toSeq(0..12).mapIt(($it).align(2)).join(\" \")\necho \" n\"\nfor n in 0..12:\n\tstdout.write ($n).align(2)\n\tfor k in 0..n:\n\t\tstdout.write ($s1(n, k)).align(10)\n\tstdout.write '\\n'\n" + }, + { + "id": 600, + "length": 453, + "source": "Rosetta Code", + "text": "import tables\nimport bignum\n\nvar cache: Table[(Natural, Natural), Int]\n\nproc s1(n, k: Natural): Int =\n\tif k == 0: return newInt(ord(n == 0))\n\tif k > n: return newInt(0)\n\tif (n, k) in cache: return cache[(n, k)]\n\tresult = s1(n - 1, k - 1) + (n - 1) * s1(n - 1, k)\n\tcache[(n, k)] = result\n\nvar max = newInt(-1)\nfor k in 0..100:\n\tlet s = s1(100, k)\n\tif s > max: max = s\n\telse: break\n\necho \"Maximum Stirling number of the first kind with n = 100:\"\necho max\n" + }, + { + "id": 601, + "length": 343, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nproc s2(n, k: Natural): Natural =\n\tif n == k: return 1\n\tif n == 0 or k == 0: return 0\n\tk * s2(n - 1, k) + s2(n - 1, k - 1)\n\necho \" k \", toSeq(0..12).mapIt(($it).align(2)).join(\" \")\necho \" n\"\nfor n in 0..12:\n\tstdout.write ($n).align(2)\n\tfor k in 0..n:\n\t\tstdout.write ($s2(n, k)).align(8)\n\tstdout.write '\\n'\n" + }, + { + "id": 602, + "length": 449, + "source": "Rosetta Code", + "text": "import tables\nimport bignum\n\nvar cache: Table[(Natural, Natural), Int]\n\nproc s2(n, k: Natural): Int =\n\tif n == k: return newInt(1)\n\tif n == 0 or k == 0: return newInt(0)\n\tif (n, k) in cache: return cache[(n, k)]\n\tresult = k * s2(n - 1, k) + s2(n - 1, k - 1)\n\tcache[(n, k)] = result\n\nvar max = newInt(-1)\nfor k in 0..100:\n\tlet s = s2(100, k)\n\tif s > max: max = s\n\telse: break\n\necho \"Maximum Stirling number of the second kind with n = 100:\"\necho max\n" + }, + { + "id": 603, + "length": 539, + "source": "Rosetta Code", + "text": "import times\n\nproc daysBetween(date1, date2: string): int64 =\n\tconst Fmt = initTimeFormat(\"yyyy-MM-dd\")\n\t(date2.parse(Fmt, utc()) - date1.parse(Fmt, utc())).inDays\n\nconst Dates = [(\"1995-11-21\",\"1995-11-21\"),\n\t\t\t\t\t\t\t (\"2019-01-01\",\"2019-01-02\"),\n\t\t\t\t\t\t\t (\"2019-01-02\",\"2019-01-01\"),\n\t\t\t\t\t\t\t (\"2019-01-01\",\"2019-03-01\"),\n\t\t\t\t\t\t\t (\"2020-01-01\",\"2020-03-01\"),\n\t\t\t\t\t\t\t (\"1902-01-01\",\"1968-12-25\"),\n\t\t\t\t\t\t\t (\"2090-01-01\",\"2098-12-25\")]\n\nfor (date1, date2) in Dates:\n\techo \"Days between \", date1, \" and \", date2, \": \", daysBetween(date1, date2)\n" + }, + { + "id": 604, + "length": 483, + "source": "Rosetta Code", + "text": "import sequtils, strutils, times\nimport bignum\n\niterator superDNumbers(d, maxCount: Positive): Natural =\n\tvar count = 0\n\tvar n = 2\n\tlet e = culong(d) # Bignum ^ requires a culong as exponent.\n\tlet pattern = repeat(chr(d + ord('0')), d)\n\twhile count != maxCount:\n\t\tif pattern in $(d * n ^ e):\n\t\t\tyield n\n\t\t\tinc count\n\t\tinc n, 1\n\nlet t0 = getTime()\nfor d in 2..9:\n\techo \"First 10 super-$# numbers:\".format(d)\n\techo toSeq(superDNumbers(d, 10)).join(\" \")\necho \"Time: \", getTime() - t0\n" + }, + { + "id": 605, + "length": 508, + "source": "Rosetta Code", + "text": "import strformat\n\nproc analyze(str: string) =\n\t\tif str.len() > 1:\n\t\t\t\tvar first = str[0]\n\t\t\t\tfor i, c in str:\n\t\t\t\t\t\tif c != first:\n\t\t\t\t\t\t\t\techo \"'\", str, \"': [len: \", str.len(), \"] not all characters are the same. starts to differ at index \",\n\t\t\t\t\t\t\t\t\t\ti, &\": '\", first, &\"' != '\", c, &\"' [\", fmt\"{ord(c):#x}\", \"]\"\n\t\t\t\t\t\t\t\treturn\n\t\techo \"'\", str, \"': [len: \", str.len(), \"] all characters are the same\"\n\nvar strings = @[\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\"]\nfor str in strings:\n\t\tanalyze(str)\n" + }, + { + "id": 606, + "length": 501, + "source": "Rosetta Code", + "text": "import strutils, strformat\n\nfunc is_isbn*(s: string): bool =\n\tvar sum, len: int\n\tfor c in s:\n\t\tif is_digit(c):\n\t\t\tsum += (ord(c) - ord('0')) * (if len mod 2 == 0: 1 else: 3)\n\t\t\tlen += 1\n\t\telif c != ' ' and c != '-':\n\t\t\treturn false\n\treturn (len == 13) and (sum mod 10 == 0)\n\nwhen is_main_module:\n\tlet isbns = [ \"978-1734314502\", \"978-1734314509\",\n\t\t\t\t\t\t\t\t\"978-1788399081\", \"978-1788399083\" ]\n\tfor isbn in isbns:\n\t\tvar quality: string = if is_isbn(isbn): \"good\" else: \"bad\"\n\t\techo &\"{isbn}: {quality}\"\n" + }, + { + "id": 607, + "length": 348, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nproc facmod(n, m: int): int =\n\t## Compute (n - 1)! mod m.\n\tresult = 1\n\tfor k in 2..n:\n\t\tresult = (result * k) mod m\n\nfunc isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0\n\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t for n in 2..100:\n\t\t\t\t\t\t\t\t if n.isPrime: n\n\necho \"Prime numbers between 2 and 100:\"\necho primes.join(\" \")\n" + }, + { + "id": 608, + "length": 353, + "source": "Rosetta Code", + "text": "import times\n\nproc has53weeks(year: Positive): bool =\n\tlet dt = initDateTime(monthday = 1, month = mJan, year = year, hour = 0, minute = 0, second= 0)\n\tresult = dt.weekday == dThu or year.isLeapYear and dt.weekday == dWed\n\nwhen isMainModule:\n\techo \"Years with 53 weeks between 2000 and 2100:\"\n\tfor year in 2000..2100:\n\t\tif year.has53weeks:\n\t\t\techo year\n" + }, + { + "id": 609, + "length": 470, + "source": "Rosetta Code", + "text": "import strformat, times\n\nfunc digits(n: int): seq[int] =\n\tvar n = n\n\twhile n != 0:\n\t\tresult.add n mod 10\n\t\tn = n div 10\n\necho \"First 15 palindrome dates after 2020-02-02:\"\nvar count = 0\nvar year = 2021\nwhile count != 15:\n\tlet d = year.digits\n\tlet monthNum = 10 * d[0] + d[1]\n\tlet dayNum = 10 * d[2] + d[3]\n\tif monthNum in 1..12:\n\t\tif dayNum <= getDaysInMonth(Month(monthNum), year):\n\t\t\t# Date is valid.\n\t\t\techo &\"{year}-{monthNum:02}-{dayNum:02}\"\n\t\t\tinc count\n\tinc year\n" + }, + { + "id": 610, + "length": 429, + "source": "Rosetta Code", + "text": "import math\n\nproc yellowstone(n: int): seq[int] =\n\tassert n >= 3\n\tresult = @[1, 2, 3]\n\tvar present = {1, 2, 3}\n\tvar start = 4\n\twhile result.len < n:\n\t\tvar candidate = start\n\t\twhile true:\n\t\t\tif candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1:\n\t\t\t\tresult.add candidate\n\t\t\t\tpresent.incl candidate\n\t\t\t\twhile start in present: inc start\n\t\t\t\tbreak\n\t\t\tinc candidate\n\necho yellowstone(30)\n" + }, + { + "id": 611, + "length": 533, + "source": "Rosetta Code", + "text": "import math, sets\n\niterator yellowstone(n: int): int =\n\tassert n >= 3\n\tfor i in 1..3: yield i\n\tvar present = [1, 2, 3].toHashSet\n\tvar prevLast = 2\n\tvar last = 3\n\tvar start = 4\n\tfor _ in 4..n:\n\t\tvar candidate = start\n\t\twhile true:\n\t\t\tif candidate notin present and gcd(candidate, last) == 1 and gcd(candidate, prevLast) != 1:\n\t\t\t\tyield candidate\n\t\t\t\tpresent.incl candidate\n\t\t\t\tprevLast = last\n\t\t\t\tlast = candidate\n\t\t\t\twhile start in present: inc start\n\t\t\t\tbreak\n\t\t\tinc candidate\n\nfor n in yellowstone(30):\n\tstdout.write \" \", n\necho()\n" + }, + { + "id": 612, + "length": 354, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst TwoPi = 2 * Pi\n\nfunc arcLength(r, a, b: float): float =\n\t## Return the length of the major arc in a circle of radius \"r\"\n\t## between angles \"a\" and \"b\" expressed in radians.\n\tlet d = abs(a - b) mod TwoPi\n\tresult = r * (if d >= Pi: d else: TwoPi - d)\n\necho &\"Arc length: {arcLength(10, degToRad(10.0), degToRad(120.0)):.5f}\"\n" + }, + { + "id": 613, + "length": 506, + "source": "Rosetta Code", + "text": "proc cocktailShakerSort[T](a: var openarray[T]) =\n\n\tvar beginIdx = 0\n\tvar endIdx = a.len - 2\n\n\twhile beginIdx <= endIdx:\n\t\tvar newBeginIdx = endIdx\n\t\tvar newEndIdx = beginIdx\n\t\tfor i in beginIdx..endIdx:\n\t\t\tif a[i] > a[i + 1]:\n\t\t\t\tswap a[i], a[i + 1]\n\t\t\t\tnewEndIdx = i\n\n\t\tendIdx = newEndIdx - 1\n\n\t\tfor i in countdown(endIdx, beginIdx):\n\t\t\tif a[i] > a[i + 1]:\n\t\t\t\tswap a[i], a[i + 1]\n\t\t\t\tnewBeginIdx = i\n\n\t\tbeginIdx = newBeginIdx + 1\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\ncocktailShakerSort a\necho a\n" + }, + { + "id": 614, + "length": 491, + "source": "Rosetta Code", + "text": "import strutils, sugar, tables\n\nconst Grid = \"\"\"N D E\n\t\t\t\t\t\t\t\tO K G\n\t\t\t\t\t\t\t\tE L W\"\"\"\n\nlet letters = Grid.toLowerAscii.splitWhitespace.join()\n\nlet words = collect(newSeq):\n\t\t\t\t\t\t\tfor word in \"unixdict.txt\".lines:\n\t\t\t\t\t\t\t\tif word.len in 3..9:\n\t\t\t\t\t\t\t\t\tword\n\nlet midLetter = letters[4]\n\nlet gridCount = letters.toCountTable\nfor word in words:\n\tblock checkWord:\n\t\tif midLetter in word:\n\t\t\tfor ch, count in word.toCountTable.pairs:\n\t\t\t\tif count > gridCount[ch]:\n\t\t\t\t\tbreak checkWord\n\t\t\techo word\n" + }, + { + "id": 615, + "length": 429, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nconst Vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n\nproc removeVowels(str: var string; vowels: set[char]) =\n\t## Remove vowels from string \"str\".\n\tvar start = 0\n\twhile true:\n\t\tlet pos = str.find(vowels, start)\n\t\tif pos < 0: break\n\t\tstr.delete(pos, pos)\n\t\tstart = pos\n\nconst TestString = \"The quick brown fox jumps over the lazy dog\"\necho TestString\necho TestString.dup(removeVowels(Vowels))\n" + }, + { + "id": 616, + "length": 499, + "source": "Rosetta Code", + "text": "import std/editdistance, sequtils, strformat, strutils\n\nlet search = \"complition\"\nlet words = toSeq(\"unixdict.txt\".lines)\nvar lev: array[4, seq[string]]\nfor word in words:\n\tlet ld = editDistance(search, word)\n\tif ld < 4:\n\t\tlev[ld].add word\necho &\"Input word: {search}\\n\"\n\nlet length = float(search.len)\nfor i in 0..3:\n\tif lev[i].len == 0: continue # No result.\n\tlet similarity = (length - float(i)) * 100 / length\n\techo &\"Words which are {similarity:4.1f}% similar:\"\n\techo lev[i].join(\" \")\n\techo()\n" + }, + { + "id": 617, + "length": 313, + "source": "Rosetta Code", + "text": "import math\nimport bignum\n\nvar\n\ti = newInt(2)\n\tj = newInt(sqrt(2.0).int)\n\tk, d = j\n\tn = 500\nlet n0 = n\nwhile true:\n\tstdout.write d\n\ti = (i - k * d) * 100\n\tk = 20 * j\n\td = newInt(1)\n\twhile d <= 10:\n\t\tif (k + d) * d > i:\n\t\t\tdec d, 1\n\t\t\tbreak\n\t\tinc d, 1\n\tj = j * 10 + d\n\tinc k, d\n\tif n0 > 0: dec n\n\tif n == 0: break\n" + }, + { + "id": 618, + "length": 334, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nfunc pancake(n: int): int =\n\tvar\n\t\tgap, sumGaps = 2\n\t\tpg = 1\n\t\tadj = -1\n\twhile sumGaps < n:\n\t\tinc adj\n\t\tinc pg, gap\n\t\tswap pg, gap\n\t\tinc sumGaps, gap\n\tresult = n + adj\n\nvar line = \"\"\nfor n in 1..20:\n\tline.addSep(\" \")\n\tline.add &\"p({n:>2}) = {pancake(n):>2}\"\n\tif n mod 5 == 0: (echo line; line.setLen(0))\n" + }, + { + "id": 619, + "length": 546, + "source": "Rosetta Code", + "text": "import algorithm, sets, strutils, sugar\n\nproc alternatingWords(word: string): array[2, string] =\n\t## Return the candidate alternating words of a word.\n\tfor i, c in word:\n\t\tresult[i and 1].add c\n\nlet words = collect(HashSet, for word in \"unixdict.txt\".lines: {word})\n\nvar result: seq[string]\nfor word in words:\n\tif word.len >= 6:\n\t\tlet altWords = alternatingWords(word)\n\t\tif altWords[0] in words and altWords[1] in words:\n\t\t\tresult.add word.align(8) & \" -> $1 $2\" % altWords\nresult.sort()\nfor i, line in result: echo ($(i+1)).align(2), \": \", line\n" + }, + { + "id": 620, + "length": 529, + "source": "Rosetta Code", + "text": "import strformat, times\n\nfunc ulam(n: Positive): int =\n\tvar\n\t\tulams = @[1, 2]\n\t\tsieve = @[1, 1]\n\t\tu = 2\n\twhile ulams.len < n:\n\t\tlet s = u + ulams[^2]\n\t\tsieve.setLen(s)\n\t\tfor i in 0.. 4 and oddWord in words:\n\t\tinc count\n\t\techo &\"{count:2}: {word:12} -> {oddWord}\"\n" + }, + { + "id": 623, + "length": 489, + "source": "Rosetta Code", + "text": "import std/editdistance, sugar\n\n# Build list of words with length >= 12.\nlet words = collect(newSeq):\n\t\t\t\t\t\t\tfor word in \"unixdict.txt\".lines:\n\t\t\t\t\t\t\t\tif word.len >= 12:\n\t\t\t\t\t\t\t\t\tword\n\necho \"List of changeable words:\\n\"\nvar count = 0\nfor i in 0.. \", word2\n\t\t\tinc count, 2\n\necho \"\\nFound \", count, \" changeable words.\"\n" + }, + { + "id": 624, + "length": 302, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc divcount(n: Natural): Natural =\n\tfor i in 1..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tinc result\n\t\t\tif n div i != i: inc result\n\necho \"Count of divisors for the first 100 positive integers:\"\nfor i in 1..100:\n\tstdout.write ($divcount(i)).align(3)\n\tif i mod 20 == 0: echo()\n" + }, + { + "id": 625, + "length": 425, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc divcount(n: Natural): Natural =\n\tfor i in 1..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tinc result\n\t\t\tif n div i != i: inc result\n\nvar count = 0\nvar n = 1\nvar tauNumbers: seq[Natural]\nwhile true:\n\tif n mod divcount(n) == 0:\n\t\ttauNumbers.add n\n\t\tinc count\n\t\tif count == 100: break\n\tinc n\n\necho \"First 100 tau numbers:\"\nfor i, n in tauNumbers:\n\tstdout.write ($n).align(5)\n\tif i mod 20 == 19: echo()\n" + }, + { + "id": 626, + "length": 351, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc divisors(n: Positive): seq[int] =\n\tresult = @[1, n]\n\tfor i in 2..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tlet j = n div i\n\t\t\tresult.add i\n\t\t\tif i != j: result.add j\n\necho \"Product of divisors for the first 50 positive numbers:\"\nfor n in 1..50:\n\tstdout.write ($prod(n.divisors)).align(10), if n mod 5 == 0: '\\n' else: ' '\n" + }, + { + "id": 627, + "length": 443, + "source": "Rosetta Code", + "text": "import strutils\n\nconst Vowels = {'a', 'e', 'i', 'o', 'u'}\n\nvar count = 0\nfor word in \"unixdict.txt\".lines:\n\tif word.len > 9:\n\t\tblock checkWord:\n\t\t\tlet first = word[0] in Vowels\n\t\t\tfor i in countup(2, word.high, 2):\n\t\t\t\tif word[i] in Vowels != first: break checkWord\n\t\t\tfor i in countup(1, word.high, 2):\n\t\t\t\tif word[i] in Vowels == first: break checkWord\n\t\t\tinc count\n\t\t\tstdout.write word.align(14), if count mod 7 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 628, + "length": 463, + "source": "Rosetta Code", + "text": "import sets, strutils, sugar\n\n# Build list and set of words with length >= 9.\nlet words = collect(newSeq):\n\t\t\t\t\t\t\tfor word in \"unixdict.txt\".lines:\n\t\t\t\t\t\t\t\tif word.len >= 9: word\nlet wordSet = words.toHashSet\n\nvar lastWord = \"\"\nvar newWord = newString(9)\nvar count = 0\nfor i in 0..words.high-9:\n\tfor j in 0..8: newWord[j] = words[i+j][j]\n\tif newWord in wordSet:\n\t\tif newWord != lastWord:\n\t\t\tinc count\n\t\t\techo ($count).align(2), ' ', newWord\n\t\t\tlastWord = newWord\n" + }, + { + "id": 629, + "length": 310, + "source": "Rosetta Code", + "text": "import strutils\n\nconst NonEVowels = ['a', 'i', 'o', 'u']\n\nvar count = 0\nfor word in \"unixdict.txt\".lines:\n\tblock checkWord:\n\t\tif word.count('e') <= 3: break checkWord\n\t\tfor vowel in NonEVowels:\n\t\t\tif vowel in word: break checkWord\n\t\tinc count\n\t\tstdout.write word.align(14), if count mod 4 == 0: '\\n' else: ' '\n" + }, + { + "id": 630, + "length": 302, + "source": "Rosetta Code", + "text": "import strutils\n\nconst Vowels = ['a', 'e', 'i', 'o', 'u']\n\nvar count = 0\nfor word in \"unixdict.txt\".lines:\n\tif word.len > 10:\n\t\tblock checkWord:\n\t\t\tfor vowel in Vowels:\n\t\t\t\tif word.count(vowel) != 1:\n\t\t\t\t\tbreak checkWord\n\t\t\tinc count\n\t\t\tstdout.write word.align(15), if count mod 5 == 0: '\\n' else: ' '\n" + }, + { + "id": 631, + "length": 296, + "source": "Rosetta Code", + "text": "const Primes = {2, 3, 5, 7, 11, 13, 17}\n\nproc digits(n: 100..999): array[3, int] =\n\t[n div 100, n div 10 mod 10, n mod 10]\n\nvar count = 0\nfor n in 101..<500:\n\tlet d = n.digits\n\tif d[0] + d[1] in Primes and d[1] + d[2] in Primes:\n\t\tinc count\n\t\tstdout.write n, if count mod 13 == 0: '\\n' else: ' '\n" + }, + { + "id": 632, + "length": 407, + "source": "Rosetta Code", + "text": "import algorithm, sequtils\n\nproc commonElements(list: openArray[seq[int]]): seq[int] =\n\tvar list = sortedByIt(list, it.len) # Start with the shortest array.\n\tfor val in list[0].deduplicate(): # Check values only once.\n\t\tblock checkVal:\n\t\t\tfor i in 1..list.high:\n\t\t\t\tif val notin list[i]:\n\t\t\t\t\tbreak checkVal\n\t\t\tresult.add val\n\necho commonElements([@[2,5,1,3,8,9,4,6], @[3,5,6,2,9,8,4], @[1,3,7,6,9]])\n" + }, + { + "id": 633, + "length": 359, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc isPrime(n: Positive): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nfor n in 1..<200:\n\tlet p = n * n * n + 2\n\tif p.isPrime:\n\t\techo ($n).align(3), \" -> \", p\n" + }, + { + "id": 634, + "length": 492, + "source": "Rosetta Code", + "text": "import std/monotimes, strformat, strutils\nimport bignum\n\nfunc sum25(p: string; rm, res: Natural): Natural =\n\tresult = res\n\tif rm == 0:\n\t\tif p[^1] in \"1379\" and probablyPrime(newInt(p), 25) != 0:\n\t\t\tinc result\n\telse:\n\t\tfor i in 1..min(rm, 9):\n\t\t\tresult = sum25(p & chr(i + ord('0')), rm - i, result)\n\nlet t0 = getMonoTime()\nlet count = $sum25(\"\", 25, 0)\necho &\"There are {count.insertSep()} primes whose digits sum to 25 without any zero digits.\"\necho \"\\nExecution time: \", getMonoTime() - t0\n" + }, + { + "id": 635, + "length": 561, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nfunc isPrime(n: Positive): bool =\n\tif (n and 1) == 0: return n == 2\n\tvar m = 3\n\twhile m * m <= n:\n\t\tif n mod m == 0: return false\n\t\tinc m, 2\n\tresult = true\n\niterator nextSpecialPrimes(lim: Positive): int =\n\tassert lim >= 3\n\tyield 2\n\tyield 3\n\tvar last = 3\n\tvar lastGap = 1\n\tfor n in countup(5, lim, 2):\n\t\tif not n.isPrime: continue\n\t\tif n - last > lastGap:\n\t\t\tlastGap = n - last\n\t\t\tlast = n\n\t\t\tyield n\n\nlet list = collect(newSeq, for p in nextSpecialPrimes(1050): p)\necho \"List of next special primes less than 1050:\"\necho list.join(\" \")\n" + }, + { + "id": 636, + "length": 525, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc reversed(n: Positive): int =\n\tvar n = n.int\n\twhile n != 0:\n\t\tresult = 10 * result + n mod 10\n\t\tn = n div 10\n\nfunc divisors(n: Positive): seq[int] =\n\tresult = @[1, n]\n\tvar d = 2\n\twhile d * d <= n:\n\t\tif n mod d == 0:\n\t\t\tresult.add d\n\t\t\tif d * d != n:\n\t\t\t\tresult.add n div d\n\t\tinc d\n\nvar count = 0\nfor n in 1..<200:\n\tlet revn = reversed(n)\n\tblock check:\n\t\tfor d in divisors(n):\n\t\t\tif revn mod reversed(d) != 0:\n\t\t\t\tbreak check\n\t\tinc count\n\t\tstdout.write ($n).align(3), if count mod 12 == 0: '\\n' else: ' '\n" + }, + { + "id": 637, + "length": 425, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc isPrime(n: Natural): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nvar pi = 0\nvar n = 1\nwhile true:\n\tstdout.write ($pi).align(2), if n mod 10 == 0: '\\n' else: ' '\n\tinc n\n\tif n.isPrime:\n\t\tinc pi\n\t\tif pi == 22: break\necho()\n" + }, + { + "id": 638, + "length": 574, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc isPrime(n: Positive): bool =\n\tif n == 1: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\treturn true\n\nfunc digitSum(n, b: Natural): int =\n\tvar n = n\n\twhile n != 0:\n\t\tresult += n mod b\n\t\tn = n div b\n\nvar count = 0\nfor n in 2..<200:\n\tif digitSum(n, 2).isPrime and digitSum(n, 3).isPrime:\n\t\tinc count\n\t\tstdout.write ($n).align(3), if count mod 16 == 0: '\\n' else: ' '\necho()\necho \"Found \", count, \" numbers.\"\n" + }, + { + "id": 639, + "length": 382, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\nvar toFind = {0..21}\nvar results: array[0..21, (int, string)]\nvar p = newInt(1)\nvar k = 0\nwhile toFind.card > 0:\n\tlet str = $p\n\tfor n in toFind:\n\t\tif str.find($n) >= 0:\n\t\t\tresults[n] = (k, str)\n\t\t\ttoFind.excl(n)\n\tp *= 6\n\tinc k\n\necho \"Smallest values of k such that 6^k contains n:\"\nfor n, (k, s) in results:\n\techo &\"{n:2}: 6^{k:<2} = {s}\"\n" + }, + { + "id": 640, + "length": 550, + "source": "Rosetta Code", + "text": "import strutils\n\nconst N = 999\n\nfunc isPrime(n: Positive): bool =\n\tif (n and 1) == 0: return n == 2\n\tvar m = 3\n\twhile m * m <= n:\n\t\tif n mod m == 0: return false\n\t\tinc m, 2\n\tresult = true\n\nfunc reversed(n: Positive): int =\n\tvar n = n.int\n\twhile n != 0:\n\t\tresult = 10 * result + n mod 10\n\t\tn = n div 10\n\nfunc isPalindromic(n: Positive): bool =\n\tn == reversed(n)\n\nvar result: seq[int]\nfor n in 2..N:\n\tif n.isPrime and n.isPalindromic:\n\t\tresult.add n\n\nfor i, n in result:\n\tstdout.write ($n).align(3)\n\tstdout.write if (i + 1) mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 641, + "length": 422, + "source": "Rosetta Code", + "text": "import strutils\n\niterator digits(n: Positive): int =\n\tvar n = n.int\n\twhile n != 0:\n\t\tyield n mod 10\n\t\tn = n div 10\n\nvar result: seq[int]\nfor n in 1..1000:\n\tblock check:\n\t\tvar m = 1\n\t\tfor d in n.digits:\n\t\t\tif d == 0 or n mod d != 0: break check\n\t\t\tm *= d\n\t\tif n mod m != 0: result.add n\n\necho \"Found \", result.len, \" matching numbers.\"\nfor i, n in result:\n\tstdout.write ($n).align(3), if (i + 1) mod 9 == 0: '\\n' else: ' '\n" + }, + { + "id": 642, + "length": 404, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\nvar k = 1u\nvar toFind = {0..50}\nvar results: array[0..50, uint]\nwhile toFind.card > 0:\n\tlet str = $(pow(newInt(k), k))\n\tfor n in toFind:\n\t\tif str.find($n) >= 0:\n\t\t\tresults[n] = k\n\t\t\ttoFind.excl(n)\n\tinc k\n\necho \"Smallest values of k such that k^k contains n:\"\nfor n, k in results:\n\tstdout.write &\"{n:2} -> {k:<2} \", if (n + 1) mod 9 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 643, + "length": 540, + "source": "Rosetta Code", + "text": "import algorithm, strformat, strutils\n\nlet list = [\"violet\", \"red\", \"green\", \"indigo\", \"blue\", \"yellow\", \"orange\"]\n\nvar count = 0\n\nproc comp(x, y: string): int =\n\tif x == y: return 0\n\tinc count\n\twhile true:\n\t\tstdout.write &\"{count:>2}) Is {x} less than {y} (y/n)? \"\n\t\tlet answer = stdin.readLine()[0]\n\t\tcase answer\n\t\tof 'y': return -1\n\t\tof 'n': return 1\n\t\telse: echo \"Incorrect answer.\"\n\nvar sortedList: seq[string]\n\nfor elem in list:\n\tsortedList.insert(elem, sortedList.upperBound(elem, comp))\n\necho \"Sorted list: \", sortedList.join(\", \")\n" + }, + { + "id": 644, + "length": 433, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst N = 999\n\nfunc isPrime(n: Positive): bool =\n\tif (n and 1) == 0: return n == 2\n\tif (n mod 3) == 0: return n == 3\n\tvar d = 5\n\tvar delta = 2\n\twhile d <= sqrt(n.toFloat).int:\n\t\tif n mod d == 0: return false\n\t\tinc d, delta\n\t\tdelta = 6 - delta\n\tresult = true\n\necho \"index prime prime sum\"\nvar s = 0\nvar idx = 0\nfor n in 2..N:\n\tif n.isPrime:\n\t\tinc idx\n\t\ts += n\n\t\tif s.isPrime: echo &\"{idx:3} {n:5} {s:7}\"\n" + }, + { + "id": 645, + "length": 295, + "source": "Rosetta Code", + "text": "import algorithm, sugar, tables\n\nvar charCount: CountTable[char]\n\nfor str in [\"133252abcdeeffd\", \"a6789798st\", \"yxcdfgxcyz\"]:\n\tcharCount.merge str.toCountTable\n\nlet uniqueChars = collect(newSeq):\n\t\t\t\t\t\t\t\t\t\tfor ch, count in charCount.pairs:\n\t\t\t\t\t\t\t\t\t\t\tif count == 1: ch\n\necho sorted(uniqueChars)\n" + }, + { + "id": 646, + "length": 389, + "source": "Rosetta Code", + "text": "import random\n\nconst N = 1_000_000\n\ntype Side {.pure.} = enum Heads, Tails\n\nconst Sides = [Heads, Tails]\n\nrandomize()\nvar onHeads, wakenings = 0\nfor _ in 1..N:\n\tlet side = sample(Sides)\n\tinc wakenings\n\tif side == Heads:\n\t\tinc onHeads\n\telse:\n\t\tinc wakenings\n\necho \"Wakenings over \", N, \" experiments: \", wakenings\necho \"Sleeping Beauty should estimate a credence of: \", onHeads / wakenings\n" + }, + { + "id": 647, + "length": 382, + "source": "Rosetta Code", + "text": "import strutils, tables\n\nvar result = AllChars\nfor str in [\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"]:\n\tlet charCount = str.toCountTable # Mapping char -> count.\n\tvar uniqueChars: set[char] # Set of unique chars.\n\tfor ch, count in charCount.pairs:\n\t\tif count == 1: uniqueChars.incl ch\n\tresult = result * uniqueChars # Intersection.\n\necho result\n" + }, + { + "id": 648, + "length": 462, + "source": "Rosetta Code", + "text": "import strformat\n\niterator h(): (int, float) =\n\t## Yield the index of the term and its value.\n\tvar n = 1\n\tvar r = 0.0\n\twhile true:\n\t\tr += 1 / n\n\t\tyield (n, r)\n\t\tinc n\n\necho \"First 20 terms of the harmonic series:\"\nfor (idx, val) in h():\n\techo &\"{idx:2}: {val}\"\n\tif idx == 20: break\necho()\n\nvar target = 1.0\nfor (idx, val) in h():\n\tif val > target:\n\t\techo &\"Index of the first term greater than {target.int:2}: {idx}\"\n\t\tif target == 10: break\n\t\telse: target += 1\n" + }, + { + "id": 649, + "length": 432, + "source": "Rosetta Code", + "text": "import strformat\nimport bignum\n\niterator h(): (int, Rat) =\n\tvar n = 1\n\tvar r = newRat()\n\twhile true:\n\t\tr += newRat(1, n)\n\t\tyield (n, r)\n\t\tinc n\n\necho \"First 20 terms of the harmonic series:\"\nfor (idx, val) in h():\n\techo &\"{idx:2}: {val}\"\n\tif idx == 20: break\necho()\n\nvar target = 1\nfor (idx, val) in h():\n\tif val > target:\n\t\techo &\"Index of the first term greater than {target:2}: {idx}\"\n\t\tif target == 10: break\n\t\telse: inc target\n" + }, + { + "id": 650, + "length": 439, + "source": "Rosetta Code", + "text": "import math\nimport bignum\n\nfunc isPrime(n: Positive): bool =\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d <= sqrt(n.toFloat).int:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\necho \"Wieferich primes less than 5000:\"\nlet two = newInt(2)\nfor p in 2u..<5000:\n\tif p.isPrime:\n\t\tif exp(two, p - 1, p * p) == 1: # Modular exponentiation.\n\t\t\techo p\n" + }, + { + "id": 651, + "length": 386, + "source": "Rosetta Code", + "text": "import sequtils\nimport bignum\n\nproc sylverster(lim: Positive): seq[Int] =\n\tresult.add(newInt(2))\n\tfor _ in 2..lim:\n\t\tresult.add result.foldl(a * b) + 1\n\nlet list = sylverster(10)\necho \"First 10 terms of the Sylvester sequence:\"\nfor item in list: echo item\n\nvar sum = newRat()\nfor item in list: sum += newRat(1, item)\necho \"\\nSum of the reciprocals of the first 10 terms: \", sum.toFloat\n" + }, + { + "id": 652, + "length": 472, + "source": "Rosetta Code", + "text": "import strutils, std/monotimes\nimport bignum\n\nlet t0 = getMonoTime()\nvar sum = 0.0\nvar first = 0\nvar f = newInt(1)\nvar count0 = 0\nfor n in 1..<50_000:\n\tf *= n\n\twhile f mod 10 == 0: # Reduce the length of \"f\".\n\t\tf = f div 10\n\t\tinc count0\n\tlet str = $f\n\tsum += (str.count('0') + count0) / (str.len + count0)\n\tif sum / float(n) < 0.16:\n\t\tif first == 0: first = n\n\telse:\n\t\tfirst = 0\n\necho \"Permanently below 0.16 at n = \", first\necho \"Execution time: \", getMonoTime() - t0\n" + }, + { + "id": 653, + "length": 572, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nfunc isPalindromic(s: string): bool =\n\tfor i in 1..s.len:\n\t\tif s[i-1] != s[^i]: return false\n\tresult = true\n\nfunc isPrime(n: Natural): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\treturn true\n\nvar list: seq[string]\nfor n in 0..<500:\n\tlet h = &\"{n:x}\"\n\tif h.isPalindromic and n.isPrime: list.add h\n\necho \"Found \", list.len, \" palindromic primes in base 16:\"\necho list.join(\" \")\n" + }, + { + "id": 654, + "length": 341, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for d1 in {0, 10..15}:\n\t\t\t\t\t\t\t for d2 in {10..15}:\n\t\t\t\t\t\t\t\t if (let n = 16 * d1 + d2; n < 500): n\n\necho \"Found \", list.len, \" numbers < 500 which cannot be written in base 16 with decimal digits:\"\nfor i, n in list:\n\tstdout.write ($n).align(3), if (i + 1) mod 7 == 0: '\\n' else: ' '\n" + }, + { + "id": 655, + "length": 362, + "source": "Rosetta Code", + "text": "type SquareMatrix[T: SomeNumber; N: static Positive] = array[N, array[N, T]]\n\nfunc sumBelowDiagonal[T, N](m: SquareMatrix[T, N]): T =\n\tfor i in 1..>>>> Input file:\"\n\tstdout.write infile.readAll()\n\tinfile.setFilePos(0)\n\techo \">>>>>\"\n\techo '\\n'\n\techo \">>>>> Output file:\"\n\treverseLines(infile, stdout)\n\techo \">>>>>\"\n" + }, + { + "id": 659, + "length": 363, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\tCoins = [200, 100, 50, 20, 10, 5, 2, 1]\n\tTarget = 988\n\necho &\"Minimal number of coins to make a value of {Target}:\"\nvar count = 0\nvar remaining = Target\nfor coin in Coins:\n\tlet n = remaining div coin\n\tif n != 0:\n\t\tinc count, n\n\t\techo &\"coins of {coin:3}: {n}\"\n\t\tdec remaining, n * coin\n\t\tif remaining == 0: break\n\necho \"\\nTotal: \", count\n" + }, + { + "id": 660, + "length": 361, + "source": "Rosetta Code", + "text": "from algorithm import sorted\n\nfunc search(): int =\n\tvar start = 100\n\twhile true:\n\t\tfor i in countup(start + 2, 10 * start div 6, 3):\n\t\t\tlet digits = sorted($i)\n\t\t\tblock check:\n\t\t\t\tfor j in 2..6:\n\t\t\t\t\tif sorted($(i * j)) != digits:\n\t\t\t\t\t\tbreak check\n\t\t\t\t# Found.\n\t\t\t\treturn i\n\t\tstart *= 10\n\nlet n = search()\necho \" n = \", n\nfor k in 2..6:\n\techo k, \"n = \", k * n\n" + }, + { + "id": 661, + "length": 488, + "source": "Rosetta Code", + "text": "import math, strformat\n\nfunc juggler(n: Positive): tuple[count: int; max: uint64; maxIdx: int] =\n\tvar a = n.uint64\n\tresult = (0, a, 0)\n\twhile a != 1:\n\t\tlet f = float(a)\n\t\ta = if (a and 1) == 0: sqrt(f).uint64\n\t\t\t\telse: uint64(f * sqrt(f))\n\t\tinc result.count\n\t\tif a > result.max:\n\t\t\tresult.max = a\n\t\t\tresult.maxIdx = result.count\n\necho \"n l[n] h[n] i[n]\"\necho \"------------------------------\"\nfor n in 20..39:\n\tlet (l, h, i) = juggler(n)\n\techo &\"{n} {l:2} {h:14} {i}\"\n" + }, + { + "id": 662, + "length": 338, + "source": "Rosetta Code", + "text": "import random\n\nrandomize()\n\nproc generate(s: Slice[int]): seq[int] =\n\tassert s.a <= s.b\n\tvar count = s.b - s.a + 1\n\tvar generated = newSeq[bool](count) # Initialized to false.\n\twhile count != 0:\n\t\tlet n = rand(s)\n\t\tif not generated[n - s.a]:\n\t\t\tgenerated[n - s.a] = true\n\t\t\tresult.add n\n\t\t\tdec count\n\nfor i in 1..5:\n\techo generate(1..20)\n" + }, + { + "id": 663, + "length": 340, + "source": "Rosetta Code", + "text": "import strformat\nfrom math import floor, sqrt\n\nvar\n\tp, s, c : int\n\tr: float\n\nfor i in countdown(499, 1):\n\ts = 1000 - i\n\tp = 1000 * (500 - i)\n\tlet delta = float(s * s - 4 * p)\n\tr = sqrt(delta)\n\tif floor(r) == r:\n\t\tc = i\n\t\tbreak\n\necho fmt\"Product: {p * c}\"\necho fmt\"a: {(s - int(r)) div 2}\"\necho fmt\"b: {(s + int(r)) div 2}\"\necho fmt\"c: {c}\"\n" + }, + { + "id": 664, + "length": 438, + "source": "Rosetta Code", + "text": "# With sorting.\nimport algorithm, strformat\n\nproc extractAndAddTwoSmallest(list: var seq[int]) =\n\tlist.sort(Descending)\n\tstdout.write &\"Descending sorted list: {list}\"\n\tlet min1 = list.pop()\n\tlet min2 = list.pop()\n\techo &\"; two smallest: {min1} and {min2}; sum = {min1 + min2}\"\n\tlist.add min1 + min2\n\nvar list = @[6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nwhile list.len >= 2:\n\tlist.extractAndAddTwoSmallest()\necho &\"Last item is {list[0]}.\"\n" + }, + { + "id": 665, + "length": 293, + "source": "Rosetta Code", + "text": "import strutils\nimport math\n\nproc is_disarium(num: int): bool =\n\tlet n = intToStr(num)\n\tvar sum = 0\n\tfor i in 0..len(n)-1:\n\t\tsum += int((int(n[i])-48) ^ (i+1))\n\treturn sum == num\n\nvar i = 0\nvar count = 0\nwhile count < 19:\n\tif is_disarium(i):\n\t\tstdout.write i, \" \"\n\t\tcount += 1\n\ti += 1\necho \"\"\n" + }, + { + "id": 666, + "length": 529, + "source": "Rosetta Code", + "text": "import parseopt, strutils\n\nvar\n\topt: OptParser = initOptParser()\n\tstr = opt.cmdLineRest.split\n\ta: int = 0\n\tb: int = 0\n\ntry:\n\ta = parseInt(str[0])\n\tb = parseInt(str[1])\nexcept ValueError:\n\tquit(\"Invalid params. Two integers are expected.\")\n\necho(\"a : \" & $a)\necho(\"b : \" & $b)\necho(\"a + b : \" & $(a+b))\necho(\"a - b : \" & $(a-b))\necho(\"a * b : \" & $(a*b))\necho(\"a div b: \" & $(a div b)) # div rounds towards zero\necho(\"a mod b: \" & $(a mod b)) # sign(a mod b)==sign(a) if sign(a)!=sign(b)\necho(\"a ^ b : \" & $(a ^ b))\n" + }, + { + "id": 667, + "length": 602, + "source": "Rosetta Code", + "text": "import db_sqlite\n\nlet dbc = open(\":memory:\", \"\", \"\", \"\")\ndbc.exec(sql\"create table stocks(date text, trans text, symbol text, qty real, price real)\")\n\n# Insert a row of data.\ndbc.exec(sql\"insert into stocks values ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)\")\n\nfor v in [(\"2006-03-28\", \"BUY\", \"IBM\", 1000, 45.00),\n\t\t\t\t\t(\"2006-04-05\", \"BUY\", \"MSOFT\", 1000, 72.00),\n\t\t\t\t\t(\"2006-04-06\", \"SELL\", \"IBM\", 500, 53.00)]:\n\tdbc.exec(sql\"insert into stocks values (?, ?, ?, ?, ?)\", v[0], v[1], v[2], v[3], v[4])\n\n# Data retrieval.\nfor row in dbc.fastRows(sql\"select * from stocks order by price\"):\n\techo row\n" + }, + { + "id": 668, + "length": 1489, + "source": "Rosetta Code", + "text": "import gdk2, glib2, gtk2\n\nconst\n\tInside = \"Mouse is over label\"\n\tOutSide = \"Mouse is not over label\"\n\n# Context transmitted to callback.\ntype Context = object\n\tlabel: PLabel\n\toverButton: bool\n\n\nproc changeLabel(p: PWidget; event: gdk2.PEventCrossing; context: var Context) {.cdecl.} =\n\tcontext.label.set_text(if context.overButton: OutSide else: Inside)\n\tcontext.overButton = not context.overButton\n\nproc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} =\n\tmain_quit()\n\n\nvar context: Context\nnim_init()\n\nlet window = window_new(gtk2.WINDOW_TOPLEVEL)\nlet stackbox = vbox_new(true, 10)\nlet button1 = button_new(\"Move mouse over button\")\nlet buttonstyle = copy(button1.get_style())\nbuttonstyle.bg[STATE_PRELIGHT] = TColor(pixel: 0, red: 255, green: 0, blue: 0)\nbutton1.set_style(buttonstyle)\nlet button2 = button_new()\ncontext = Context(label: label_new(Outside), overButton: false)\nlet button3 = button_new(\"Quit\")\n\nbutton2.add(context.label)\nstackbox.pack_start(button1, true, true, 0)\nstackbox.pack_start(button2, true, true, 0)\nstackbox.pack_start(button3, true, true, 0)\nwindow.set_border_width(5)\nwindow.add(stackbox)\n\ndiscard window.signal_connect(\"destroy\", SIGNAL_FUNC(thisDestroy), nil)\ndiscard button1.signal_connect(\"enter_notify_event\", SIGNAL_FUNC(changeLabel), addr(context))\ndiscard button1.signal_connect(\"leave_notify_event\", SIGNAL_FUNC(changeLabel), addr(context))\ndiscard button3.signal_connect(\"clicked\", SIGNAL_FUNC(thisDestroy), nil)\n\nwindow.show_all()\nmain()\n" + }, + { + "id": 669, + "length": 917, + "source": "Rosetta Code", + "text": "import sdl, sdl_image, colors\n\nvar\n\tscreen, greeting: PSurface\n\tr: TRect\n\tevent: TEvent\n\tbgColor = colChocolate.int32\n\nif init(INIT_VIDEO) != 0:\n\tquit \"SDL failed to initialize!\"\n\nscreen = SetVideoMode(640, 480, 16, SWSURFACE or ANYFORMAT)\nif screen.isNil:\n\tquit($sdl.getError())\n\ngreeting = IMG_load(\"tux.png\")\nif greeting.isNil:\n\techo \"Failed to load tux.png\"\nelse:\n\t## convert the image to alpha and free the old one\n\tvar s = greeting.displayFormatAlpha()\n\tswap(greeting, s)\n\ts.freeSurface()\n\nr.x = 0\nr.y = 0\n\nblock game_loop:\n\twhile true:\n\n\t\twhile pollEvent(addr event) > 0:\n\t\t\tcase event.kind\n\t\t\tof QUITEV:\n\t\t\t\tbreak game_loop\n\t\t\tof KEYDOWN:\n\t\t\t\tif EvKeyboard(addr event).keysym.sym == K_ESCAPE:\n\t\t\t\t\tbreak game_loop\n\t\t\telse:\n\t\t\t\tdiscard\n\n\t\tdiscard fillRect(screen, nil, bgColor)\n\t\tdiscard blitSurface(greeting, nil, screen, addr r)\n\t\tdiscard flip(screen)\n\ngreeting.freeSurface()\nscreen.freeSurface()\nsdl.Quit()\n" + }, + { + "id": 670, + "length": 1833, + "source": "Rosetta Code", + "text": "import x11/[xlib, xutil, x]\n\nconst\n\tWINDOW_WIDTH = 400\n\tWINDOW_HEIGHT = 300\n\ntype WindowData = tuple[display: PDisplay; window: Window]\n\nproc createWindow: WindowData =\n\tlet width: cuint = WINDOW_WIDTH\n\tlet height: cuint = WINDOW_HEIGHT\n\tvar sizeHints: XSizeHints\n\n\tlet display = XOpenDisplay(nil)\n\tif display == nil:\n\t\techo \"Connection to X server failed.\"\n\t\tquit QuitFailure\n\n\tlet screen = XDefaultScreen(display)\n\tvar rootwin = XRootWindow(display, screen)\n\tlet win = XCreateSimpleWindow(display, rootwin, 100, 10, width, height, 5,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tXBlackPixel(display, screen), XWhitePixel(display, screen))\n\tsizeHints.flags = PSize or PMinSize or PMaxSize\n\tsizeHints.min_width = width.cint\n\tsizeHints.max_width = width.cint\n\tsizeHints.min_height = height.cint\n\tsizeHints.max_height = height.cint\n\tdiscard XSetStandardProperties(\n\t\t\t\t\tdisplay, win, \"Simple Window\", \"window\", 0, nil, 0, addr(sizeHints))\n\tdiscard XSelectInput(display, win, ButtonPressMask or KeyPressMask or PointerMotionMask)\n\tdiscard XMapWindow(display, win)\n\tresult = (display, win)\n\nproc closeWindow(data: WindowData) =\n\tdiscard XDestroyWindow(data.display, data.window)\n\tdiscard XCloseDisplay(data.display)\n\nproc processEvent(xev: var XEvent) =\n\tvar key: KeySym\n\tcase xev.theType.int\n\tof KeyPress:\n\t\tkey = XLookupKeysym(cast[ptr XKeyEvent](addr(xev)), 0)\n\t\tif key.int != 0:\n\t\t\techo \"keyboard event \", key.int\n\t\tif key.int == 65307: # \n\t\t\tquit QuitSuccess\n\tof ButtonPressMask, PointerMotionMask:\n\t\techo \"Mouse event\"\n\telse:\n\t\tdiscard\n\nproc eventloop(data: WindowData) =\n\tvar xev: XEvent\n\tdiscard XFlush(data.display)\n\tvar numEvents = XPending(data.display).int\n\twhile numEvents != 0:\n\t\tdec numEvents\n\t\tdiscard XNextEvent(data.display, addr(xev))\n\t\tprocessEvent(xev)\n\nlet windata = createWindow()\nwhile true:\n\teventloop(windata)\nwindata.closeWindow()\n" + }, + { + "id": 671, + "length": 835, + "source": "Rosetta Code", + "text": "import tables\n\nvar\n\thash = initTable[string, int]() # empty hash table\n\thash1: Table[string, int] # empty hash table (implicit initialization).\n\thash2 = {\"key1\": 1, \"key2\": 2}.toTable # hash table with two keys\n\thash3 = [(\"key1\", 1), (\"key2\", 2)].toTable # hash table from tuple array\n\thash4 = @[(\"key1\", 1), (\"key2\", 2)].toTable # hash table from tuple seq\n\tvalue = hash2[\"key1\"]\n\nhash[\"spam\"] = 1\nhash[\"eggs\"] = 2\nhash[\"foo\"] = 3\n\necho \"hash has \", hash.len, \" elements\"\necho \"hash has key foo? \", hash.hasKey(\"foo\")\necho \"hash has key bar? \", hash.hasKey(\"bar\")\n\necho \"iterate pairs:\" # iterating over (key, value) pairs\nfor key, value in hash:\n\techo key, \": \", value\n\necho \"iterate keys:\" # iterating over keys\nfor key in hash.keys:\n\techo key\n\necho \"iterate values:\" # iterating over values\nfor key in hash.values:\n\techo key\n" + }, + { + "id": 672, + "length": 4512, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nconst LibXml = \"libxml2.so\"\n\ntype\n\tXmlDocPtr = pointer\n\n\tXmlXPathContextPtr = pointer\n\n\tXmlElementKind = enum\n\t\txmlElementNode = 1\n\t\txmlAttributeNode = 2\n\t\txmlTextNode = 3\n\t\txmlCdataSectionNode = 4\n\t\txmlEntityRefNode = 5\n\t\txmlEntityNode = 6\n\t\txmlPiNode = 7\n\t\txmlCommentNode = 8\n\t\txmlDocumentNode = 9\n\t\txmlDocumentTypeNode = 10\n\t\txmlDocumentFragNode = 11\n\t\txmlNotationNode = 12\n\t\txmlHtmlDocumentNode = 13\n\t\txmlDtdNode = 14\n\t\txmlElementDecl = 15\n\t\txmlAttributeDecl = 16\n\t\txmlEntityDecl = 17\n\t\txmlNamespaceDecl = 18\n\t\txmlXincludeStart = 19\n\t\txmlXincludeEnd = 20\n\n\tXmlNsKind = XmlElementKind\n\n\tXmlNsPtr = ptr XmlNs\n\tXmlNs = object\n\t\tnext: XmlNsPtr\n\t\tkind: XmlNsKind\n\t\thref: cstring\n\t\tprefix: cstring\n\t\tprivate: pointer\n\t\tcontext: XmlDocPtr\n\n\tXmlAttrPtr = pointer\n\n\tXmlNodePtr = ptr XmlNode\n\tXmlNode = object\n\t\tprivate: pointer\n\t\tkind: XmlElementKind\n\t\tname: cstring\n\t\tchildren: XmlNodePtr\n\t\tlast: XmlNodePtr\n\t\tparent: XmlNodePtr\n\t\tnext: XmlNodePtr\n\t\tprev: XmlNodePtr\n\t\tdoc: XmlDocPtr\n\t\tns: XmlNsPtr\n\t\tcontent: cstring\n\t\tproperties: XmlAttrPtr\n\t\tnsDef: XmlNsPtr\n\t\tpsvi: pointer\n\t\tline: cushort\n\t\textra: cushort\n\n\tXmlNodeSetPtr = ptr XmlNodeSet\n\tXmlNodeSet = object\n\t\tnodeNr: cint\n\t\tnodeMax: cint\n\t\tnodeTab: ptr UncheckedArray[XmlNodePtr]\n\n\tXmlPathObjectKind = enum\n\t\t\txpathUndefined\n\t\t\txpathNodeset\n\t\t\txpathBoolean\n\t\t\txpathNumber\n\t\t\txpathString\n\t\t\txpathPoint\n\t\t\txpathRange\n\t\t\txpathLocationset\n\t\t\txpathUsers\n\t\t\txpathXsltTree\n\n\tXmlXPathObjectPtr = ptr XmlXPathObject\n\tXmlXPathObject = object\n\t\tkind: XmlPathObjectKind\n\t\tnodeSetVal: XmlNodeSetPtr\n\t\tboolVal: cint\n\t\tfloatVal: cdouble\n\t\tstringVal: cstring\n\t\tuser: pointer\n\t\tindex: cint\n\t\tuser2: pointer\n\t\tindex2: cint\n\n\tXmlSaveCtxtPtr = pointer\n\n\tXmlBufferPtr = pointer\n\n\n# Declaration of needed \"libxml2\" procedures.\nproc xmlParseFile(docName: cstring): XmlDocPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlParseFile\".}\n\nproc xmlXPathNewContext(doc: XmlDocPtr): XmlXPathContextPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlXPathNewContext\".}\n\nproc xmlXPathEvalExpression(str: cstring; ctxt: XmlXPathContextPtr): XmlXPathObjectPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlXPathEvalExpression\".}\n\nproc xmlXPathFreeContext(ctxt: XmlXPathContextPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlXPathFreeContext\".}\n\nproc xmlXPathFreeObject(obj: XmlXPathObjectPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlXPathFreeObject\".}\n\nproc xmlSaveToBuffer(vuffer: XmlBufferPtr; encoding: cstring; options: cint): XmlSaveCtxtPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSaveToBuffer\".}\n\nproc xmlBufferCreate(): XmlBufferPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlBufferCreate\".}\n\nproc xmlBufferFree(buf: XmlBufferPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlBufferCreate\".}\n\nproc xmlBufferContent(buf: XmlBufferPtr): cstring\n\t{.cdecl, dynlib: LibXml, importc: \"xmlBufferContent\".}\n\nproc xmlSaveTree(ctxt: XmlSaveCtxtPtr; cur: XmlNodePtr): clong\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSaveTree\".}\n\nproc xmlSaveClose(ctxt: XmlSaveCtxtPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSaveClose\".}\n\n\nproc `$`(node: XmlNodePtr): string =\n\t## Return the representation of a node.\n\tlet buffer = xmlBufferCreate()\n\tlet saveContext = xmlSaveToBuffer(buffer, nil, 0)\n\tdiscard saveContext.xmlSaveTree(node)\n\tsaveContext.xmlSaveClose()\n\tresult = $buffer.xmlBufferContent()\n\txmlBufferFree(buffer)\n\n\niterator nodes(xpath: string; context: XmlXPathContextPtr): XmlNodePtr =\n\t## Yield the nodes which fit the XPath request.\n\tlet xpathObj = xmlXPathEvalExpression(xpath, context)\n\tif xpathObj.isNil:\n\t\tquit \"Failed to evaluate XPath: \" & xpath, QuitFailure\n\tassert xpathObj.kind == xpathNodeset\n\tlet nodeSet = xpathObj.nodeSetVal\n\tif not nodeSet.isNil:\n\t\tfor i in 0.. \")\n\nvar list: SinglyLinkedList[int]\n\nfor i in 1..5: list.append(i)\nfor i in 6..10: list.prepend(i)\necho \"List: \", list\n" + }, + { + "id": 682, + "length": 799, + "source": "Rosetta Code", + "text": "import opengl, opengl/glut\n\nproc paint() {.cdecl.} =\n\tglClearColor(0.3,0.3,0.3,0.0)\n\tglClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)\n\n\tglShadeModel(GL_SMOOTH)\n\n\tglLoadIdentity()\n\tglTranslatef(-15.0, -15.0, 0.0)\n\n\tglBegin(GL_TRIANGLES)\n\tglColor3f(1.0, 0.0, 0.0)\n\tglVertex2f(0.0, 0.0)\n\tglColor3f(0.0, 1.0, 0.0)\n\tglVertex2f(30.0, 0.0)\n\tglColor3f(0.0, 0.0, 1.0)\n\tglVertex2f(0.0, 30.0)\n\tglEnd()\n\n\tglFlush()\n\nproc reshape(width, height: cint) {.cdecl.} =\n\tglViewport(0, 0, width, height)\n\tglMatrixMode(GL_PROJECTION)\n\tglLoadIdentity()\n\tglOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)\n\tglMatrixMode(GL_MODELVIEW)\n\nenableAutoGlErrorCheck(false)\nloadExtensions()\nglutInit()\nglutInitWindowSize(640, 480)\ndiscard glutCreateWindow(\"Triangle\")\n\nglutDisplayFunc(paint)\nglutReshapeFunc(reshape)\n\nglutMainLoop()\n" + }, + { + "id": 683, + "length": 907, + "source": "Rosetta Code", + "text": "import os, nanomsg\n\nproc sendMsg(s: cint, msg: string) =\n\techo \"SENDING \\\"\",msg,\"\\\"\"\n\tlet bytes = s.send(msg.cstring, msg.len + 1, 0)\n\tassert bytes == msg.len + 1\n\nproc recvMsg(s: cint) =\n\tvar buf: cstring\n\tlet bytes = s.recv(addr buf, MSG, 0)\n\tif bytes > 0:\n\t\techo \"RECEIVED \\\"\",buf,\"\\\"\"\n\t\tdiscard freemsg buf\n\nproc sendRecv(s: cint, msg: string) =\n\tvar to: cint = 100\n\tdiscard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to)\n\twhile true:\n\t\ts.recvMsg\n\t\tsleep 1000\n\t\ts.sendMsg msg\n\nproc node0(url: string) =\n\tvar s = socket(AF_SP, nanomsg.PAIR)\n\tassert s >= 0\n\tlet res = s.bindd url\n\tassert res >= 0\n\ts.sendRecv \"node0\"\n\tdiscard s.shutdown 0\n\nproc node1(url: string) =\n\tvar s = socket(AF_SP, nanomsg.PAIR)\n\tassert s >= 0\n\tlet res = s.connect url\n\tassert res >= 0\n\ts.sendRecv \"node1\"\n\tdiscard s.shutdown 0\n\nif paramStr(1) == \"node0\":\n\tnode0 paramStr(2)\nelif paramStr(1) == \"node1\":\n\tnode1 paramStr(2)\n" + }, + { + "id": 684, + "length": 1119, + "source": "Rosetta Code", + "text": "# Base delegate.\n\ntype Delegate = ref object of RootObj\n\tnil\n\nmethod thing(d: Delegate): string {.base.} =\n\t## Default implementation of \"thing\".\n\t## Using a method rather than a proc allows dynamic dispatch.\n\t\"default implementation\"\n\n\n# Delegator.\n\ntype Delegator = object\n\tdelegate: Delegate\n\nproc initDelegator(d: Delegate = nil): Delegator =\n\t## Create a delegator with given delegate or nil.\n\tif d.isNil:\n\t\tDelegator(delegate: Delegate()) # Will use a default delegate instance.\n\telse:\n\t\tDelegator(delegate: d) # Use the provided delegate instance.\n\nproc operation(d: Delegator): string =\n\t## Calls the delegate.\n\td.delegate.thing()\n\n\n# Usage.\n\nlet d = initDelegator()\necho \"Without any delegate: \", d.operation()\n\ntype Delegate1 = ref object of Delegate\n\nlet d1 = initDelegator(Delegate1())\necho \"With a delegate which doesn't provide the \\\"thing\\\" method: \", d1.operation()\n\ntype Delegate2 = ref object of Delegate\n\nmethod thing(d: Delegate2): string =\n\t\"delegate implementation\"\n\nlet d2 = initDelegator(Delegate2())\necho \"With a delegate which provided the \\\"thing\\\" method: \", d2.operation()\n" + }, + { + "id": 685, + "length": 649, + "source": "Rosetta Code", + "text": "from math import sqrt\n\niterator primesUpto(limit: int): int =\n\tlet sqrtLimit = int(sqrt(float64(limit)))\n\tvar composites = newSeq[bool](limit + 1)\n\tfor n in 2 .. sqrtLimit: # cull to square root of limit\n\t\tif not composites[n]: # if prime -> cull its composites\n\t\t\tfor c in countup(n * n, limit, n): # start at ``n`` squared\n\t\t\t\tcomposites[c] = true\n\tfor n in 2 .. limit: # separate iteration over results\n\t\tif not composites[n]:\n\t\t\tyield n\n\nstdout.write \"The primes up to 100 are: \"\nfor x in primesUpto(100):\n\t stdout.write(x, \" \")\necho()\n\nvar count = 0\nfor p in primesUpto(1000000):\n\tcount += 1\necho \"There are \", count, \" primes up to 1000000.\"\n" + }, + { + "id": 686, + "length": 2122, + "source": "Rosetta Code", + "text": "import sugar\nfrom times import epochTime\n\ntype PrimeType = int\niterator primesTreeFolding(): PrimeType {.closure.} =\n\t# needs a Co Inductive Stream - CIS...\n\ttype\n\t\tCIS[T] = ref object\n\t\t\thead: T\n\t\t\ttail: () -> CIS[T]\n\n\tproc merge(xs, ys: CIS[PrimeType]): CIS[PrimeType] =\n\t\tlet x = xs.head;\n\t\tlet y = ys.head\n\t\tif x < y:\n\t\t\tCIS[PrimeType](head: x, tail: () => merge(xs.tail(), ys))\n\t\telif y < x:\n\t\t\tCIS[PrimeType](\n\t\t\t\thead: y,\n\t\t\t\ttail: () => merge(xs, ys.tail()))\n\t\telse:\n\t\t\tCIS[PrimeType](\n\t\t\t\thead: x,\n\t\t\t\ttail: () => merge(xs.tail(), ys.tail()))\n\n\tproc pmults(p: PrimeType): CIS[PrimeType] =\n\t\tlet inc = p + p\n\t\tproc mlts(c: PrimeType): CIS[PrimeType] =\n\t\t\tCIS[PrimeType](head: c, tail: () => mlts(c + inc))\n\t\tmlts(p * p)\n\n\tproc allmults(ps: CIS[PrimeType]): CIS[CIS[PrimeType]] =\n\t\tCIS[CIS[PrimeType]](\n\t\t\thead: pmults(ps.head),\n\t\t\ttail: () => allmults(ps.tail()))\n\n\tproc pairs(css: CIS[CIS[PrimeType]]): CIS[CIS[PrimeType]] =\n\t\tlet cs0 = css.head;\n\t\tlet rest0 = css.tail()\n\t\tCIS[CIS[PrimeType]](\n\t\t\thead: merge(cs0, rest0.head),\n\t\t\ttail: () => pairs(rest0.tail()))\n\n\tproc cmpsts(css: CIS[CIS[PrimeType]]): CIS[PrimeType] =\n\t\tlet cs0 = css.head\n\t\tCIS[PrimeType](\n\t\t\thead: cs0.head,\n\t\t\ttail: () => merge(cs0.tail(), css.tail().pairs.cmpsts))\n\n\tproc minusAt(n: PrimeType, cs: CIS[PrimeType]): CIS[PrimeType] =\n\t\tvar nn = n;\n\t\tvar ncs = cs\n\t\twhile nn >= ncs.head:\n\t\t\tnn += 2;\n\t\t\tncs = ncs.tail()\n\t\tCIS[PrimeType](head: nn, tail: () => minusAt(nn + 2, ncs))\n\n\tproc oddprms(): CIS[PrimeType] =\n\t\tCIS[PrimeType](\n\t\t\thead: 3.PrimeType,\n\t\t\ttail: () => minusAt(5.PrimeType, oddprms().allmults.cmpsts))\n\n\tvar prms = CIS[PrimeType](head: 2.PrimeType, tail: () => oddprms())\n\twhile true:\n\t\tyield prms.head;\n\t\tprms = prms.tail()\n\nstdout.write \"The first 25 primes are: \"\nvar counter = 0\nfor p in primesTreeFolding():\n\tif counter >= 25: break\n\tstdout.write(p, \" \"); counter += 1\necho()\n\nlet start = epochTime()\ncounter = 0\nfor p in primesTreeFolding():\n\tif p > 1000000: break\n\telse: counter += 1\nlet elapsed = epochTime() - start\necho \"There are \", counter, \" primes up to 1000000.\"\necho \"This test took \", elapsed, \" seconds.\"\n" + }, + { + "id": 687, + "length": 1264, + "source": "Rosetta Code", + "text": "import tables, times\n\ntype PrimeType = int\nproc primesHashTable(): iterator(): PrimeType {.closure.} =\n\titerator output(): PrimeType {.closure.} =\n\t\t# some initial values to avoid race and reduce initializations...\n\t\tyield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType\n\t\tvar h = initTable[PrimeType,PrimeType]()\n\t\tvar n = 9.PrimeType\n\t\tlet bps = primesHashTable()\n\t\tvar bp = bps() # advance past 2\n\t\tbp = bps()\n\t\tvar q = bp * bp # to initialize with 3\n\t\twhile true:\n\t\t\tif n >= q:\n\t\t\t\tlet incr = bp + bp\n\t\t\t\th[n + incr] = incr\n\t\t\t\tbp = bps()\n\t\t\t\tq = bp * bp\n\t\t\telif h.hasKey(n):\n\t\t\t\tvar incr: PrimeType\n\t\t\t\tdiscard h.take(n, incr)\n\t\t\t\tvar nxt = n + incr\n\t\t\t\twhile h.hasKey(nxt):\n\t\t\t\t\tnxt += incr # ensure no duplicates\n\t\t\t\th[nxt] = incr\n\t\t\telse:\n\t\t\t\tyield n\n\t\t\tn += 2.PrimeType\n\toutput\n\nstdout.write \"The first 25 primes are: \"\nvar counter = 0\nvar iter = primesHashTable()\nfor p in iter():\n\tif counter >= 25:\n\t\tbreak\n\telse:\n\t\tstdout.write(p, \" \")\n\t\tcounter += 1\necho \"\"\nlet start = epochTime()\ncounter = 0\niter = primesHashTable()\nfor p in iter():\n\tif p > 1000000: break\n\telse: counter += 1\nlet elapsed = epochTime() - start\necho \"The number of primes up to a million is: \", counter\nstdout.write(\"This test took \", elapsed, \" seconds.\\n\")\n" + }, + { + "id": 688, + "length": 7008, + "source": "Rosetta Code", + "text": "# a Page Segmented Odd-Only Bit-Packed Sieve of Eratosthenes...\n\nfrom times import epochTime # for testing\nfrom bitops import popCount\n\ntype Prime = uint64\n\nlet LIMIT = 1_000_000_000.Prime\nlet CPUL1CACHE = 16384 # in bytes\n\nconst FRSTSVPRM = 3.Prime\n\ntype\n\tBasePrime = uint32\n\tBasePrimeArray = seq[BasePrime]\n\tSieveBuffer = seq[byte] # byte size gives the most potential efficiency...\n\n# define a general purpose lazy list to use as secondary base prime arrays feed\n# NOT thread safe; needs a Mutex gate to make it so, but not threaded (yet)...\ntype\n\tBasePrimeArrayLazyList = ref object\n\t\thead: BasePrimeArray\n\t\ttailf: proc (): BasePrimeArrayLazyList {.closure.}\n\t\ttail: BasePrimeArrayLazyList\ntemplate makeBasePrimeArrayLazyList(hd: BasePrimeArray;\n\t\t\t\t\t\t\t\t\t\t\tbody: untyped): untyped = # factory constructor\n\tlet thnk = proc (): BasePrimeArrayLazyList {.closure.} = body\n\tBasePrimeArrayLazyList(head: hd, tailf: thnk)\nproc rest(lzylst: sink BasePrimeArrayLazyList): BasePrimeArrayLazyList {.inline.} =\n\tif lzylst.tailf != nil: lzylst.tail = lzylst.tailf(); lzylst.tailf = nil\n\treturn lzylst.tail\niterator items(lzylst: BasePrimeArrayLazyList): BasePrime {.inline.} =\n\tvar ll = lzylst\n\twhile ll != nil:\n\t\tfor bp in ll.head: yield bp\n\t\tll = ll.rest\n\n# count the number of zero bits (primes) in a SieveBuffer,\n# uses native popCount for extreme speed;\n# counts up to the bit index of the last bit to be counted...\nproc countSieveBuffer(lsti: int; cmpsts: SieveBuffer): int =\n\tlet lstw = (lsti shr 3) and -8; let lstm = lsti and 63 # last word and bit index!\n\tresult = (lstw shl 3) + 64 # preset for all ones!\n\tlet cmpstsa = cast[int](cmpsts[0].unsafeAddr)\n\tlet cmpstslsta = cmpstsa + lstw\n\tfor csa in countup(cmpstsa, cmpstslsta - 1, 8):\n\t\tresult -= cast[ptr uint64](csa)[].popCount # subtract number of found ones!\n\tlet msk = (0'u64 - 2'u64) shl lstm # mask for the unused bits in last word!\n\tresult -= (cast[ptr uint64](cmpstslsta)[] or msk).popCount\n\n# a fast fill SieveBuffer routine using pointers...\nproc fillSieveBuffer(sb: var SieveBuffer) = zeroMem(sb[0].unsafeAddr, sb.len)\n\nconst BITMASK = [1'u8, 2, 4, 8, 16, 32, 64, 128] # faster than shifting!\n\n# do sieving work, based on low starting value for the given buffer and\n# the given lazy list of base prime arrays...\nproc cullSieveBuffer(lwi: int; bpas: BasePrimeArrayLazyList;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sb: var SieveBuffer) =\n\tlet len = sb.len; let szbits = len shl 3; let nxti = lwi + szbits\n\tfor bp in bpas:\n\t\tlet bpwi = ((bp.Prime - FRSTSVPRM) shr 1).int\n\t\tvar s = (bpwi shl 1) * (bpwi + FRSTSVPRM.int) + FRSTSVPRM.int\n\t\tif s >= nxti: break\n\t\tif s >= lwi: s -= lwi\n\t\telse:\n\t\t\tlet r = (lwi - s) mod bp.int\n\t\t\ts = (if r == 0: 0 else: bp.int - r)\n\t\tlet clmt = szbits - (bp.int shl 3)\n# if len == CPUL1CACHE: continue\n\t\tif s < clmt:\n\t\t\tlet slmt = s + (bp.int shl 3)\n\t\t\twhile s < slmt:\n\t\t\t\tlet msk = BITMASK[s and 7]\n\t\t\t\tfor c in countup(s shr 3, len - 1, bp.int):\n\t\t\t\t\tsb[c] = sb[c] or msk\n\t\t\t\ts += bp.int\n\t\t\tcontinue\n\t\twhile s < szbits:\n\t\t\tlet w = s shr 3; sb[w] = sb[w] or BITMASK[s and 7]; s += bp.int # (1'u8 shl (s and 7))\n\nproc makeBasePrimeArrays(): BasePrimeArrayLazyList # forward reference!\n\n# an iterator over successive sieved buffer composite arrays,\n# returning whatever type the cnvrtr produces from\n# the low index and the culled SieveBuffer...\nproc makePrimePages[T](\n\t\tstrtwi, sz: int; cnvrtrf: proc (li: int; sb: var SieveBuffer): T {.closure.}\n\t\t\t): (iterator(): T {.closure.}) =\n\tvar lwi = strtwi; let bpas = makeBasePrimeArrays(); var cmpsts = newSeq[byte](sz)\n\treturn iterator(): T {.closure.} =\n\t\twhile true:\n\t\t\tfillSieveBuffer(cmpsts); cullSieveBuffer(lwi, bpas, cmpsts)\n\t\t\tyield cnvrtrf(lwi, cmpsts); lwi += cmpsts.len shl 3\n\n# starts the secondary base primes feed with minimum size in bits set to 4K...\n# thus, for the first buffer primes up to 8293,\n# the seeded primes easily cover it as 97 squared is 9409.\nproc makeBasePrimeArrays(): BasePrimeArrayLazyList =\n\t# converts an entire sieved array of bytes into an array of base primes,\n\t# to be used as a source of base primes as part of the Lazy List...\n\tproc sb2bpa(li: int; sb: var SieveBuffer): BasePrimeArray =\n\t\tlet szbits = sb.len shl 3; let len = countSieveBuffer(szbits - 1, sb)\n\t\tresult = newSeq[BasePrime](len); var j = 0\n\t\tfor i in 0 ..< szbits:\n\t\t\tif (sb[i shr 3] and BITMASK[i and 7]) == 0'u8:\n\t\t\t\tresult[j] = FRSTSVPRM.BasePrime + ((li + i) shl 1).BasePrime; j.inc\n\tproc nxtbparr(\n\t\t\tpgen: iterator (): BasePrimeArray {.closure.}): BasePrimeArrayLazyList =\n\t\treturn makeBasePrimeArrayLazyList(pgen()): nxtbparr(pgen)\n\t# pre-seeding first array breaks recursive race,\n\t# dummy primes of all odd numbers starting at FRSTSVPRM (unculled)...\n\tvar cmpsts = newSeq[byte](512)\n\tlet dummybparr = sb2bpa(0, cmpsts)\n\tlet fakebps = makeBasePrimeArrayLazyList(dummybparr): nil # used just once here!\n\tcullSieveBuffer(0, fakebps, cmpsts)\n\treturn makeBasePrimeArrayLazyList(sb2bpa(0, cmpsts)):\n\t\tnxtbparr(makePrimePages(4096, 512, sb2bpa)) # lazy recursive call breaks race!\n\n# iterator over primes from above page iterator;\n# takes at least as long to enumerate the primes as sieve them...\niterator primesPaged(): Prime {.inline.} =\n\tyield 2\n\tproc mkprmarr(li: int; sb: var SieveBuffer): seq[Prime] =\n\t\tlet szbits = sb.len shl 3; let low = FRSTSVPRM + (li + li).Prime; var j = 0\n\t\tlet len = countSieveBuffer(szbits - 1, sb); result = newSeq[Prime](len)\n\t\tfor i in 0 ..< szbits:\n\t\t\tif (sb[i shr 3] and BITMASK[i and 7]) == 0'u8:\n\t\t\t\tresult[j] = low + (i + i).Prime; j.inc\n\tlet gen = makePrimePages(0, CPUL1CACHE, mkprmarr)\n\tfor prmpg in gen():\n\t\tfor prm in prmpg: yield prm\n\nproc countPrimesTo(range: Prime): int64 =\n\tif range < FRSTSVPRM: return (if range < 2: 0 else: 1)\n\tresult = 1; let rngi = ((range - FRSTSVPRM) shr 1).int\n\tproc cntr(li: int; sb: var SieveBuffer): (int, int) {.closure.} =\n\t\tlet szbits = sb.len shl 3; let nxti = li + szbits; result = (0, nxti)\n\t\tif nxti <= rngi: result[0] += countSieveBuffer(szbits - 1, sb)\n\t\telse: result[0] += countSieveBuffer(rngi - li, sb)\n\tlet gen = makePrimePages(0, CPUL1CACHE, cntr)\n\tfor count, nxti in gen():\n\t\tresult += count; if nxti > rngi: break\n\n# showing results...\necho \"Page Segmented Bit-Packed Odds-Only Sieve of Eratosthenes\"\necho \"Needs at least \", CPUL1CACHE, \" bytes of CPU L1 cache memory.\\n\"\n\nstdout.write \"First 25 primes: \"\nvar counter0 = 0\nfor p in primesPaged():\n\tif counter0 >= 25: break\n\tstdout.write(p, \" \"); counter0.inc\necho \"\"\n\nstdout.write \"The number of primes up to a million is: \"\nvar counter1 = 0\nfor p in primesPaged():\n\tif p > 1_000_000.Prime: break else: counter1.inc\nstdout.write counter1, \" - these both found by (slower) enumeration.\\n\"\n\nlet start = epochTime()\n# slow way to count primes takes as long to enumerate as sieve!\nvar counter = 0\nfor p in primesPaged():\n\tif p > LIMIT: break else: counter.inc\n\nlet counter = countPrimesTo LIMIT # the fast way using native popCount!\nlet elpsd = epochTime() - start\n\necho \"Found \", counter, \" primes up to \", LIMIT, \" in \", elpsd, \" seconds.\"\n" + }, + { + "id": 689, + "length": 1037, + "source": "Rosetta Code", + "text": "type\n\n\tNode[T] = ref object\n\t\tvalue: T\n\t\tnext: Node[T]\n\n\tQueue*[T] = object\n\t\thead, tail: Node[T]\n\t\tlength: Natural\n\nfunc initQueue*[T](): Queue[T] = Queue[T]()\n\nfunc len*(queue: Queue): Natural =\n\tqueue.length\n\nfunc isEmpty*(queue: Queue): bool {.inline.} =\n\tqueue.len == 0\n\nfunc push*[T](queue: var Queue[T]; value: T) =\n\tlet node = Node[T](value: value, next: nil)\n\tif queue.isEmpty: queue.head = node\n\telse: queue.tail.next = node\n\tqueue.tail = node\n\tinc queue.length\n\nfunc pop*[T](queue: var Queue[T]): T =\n\tif queue.isEmpty:\n\t\traise newException(ValueError, \"popping from empty queue.\")\n\tresult = queue.head.value\n\tqueue.head = queue.head.next\n\tdec queue.length\n\tif queue.isEmpty: queue.tail = nil\n\n\nwhen isMainModule:\n\n\tvar fifo = initQueue[int]()\n\n\tfifo.push(26)\n\tfifo.push(99)\n\tfifo.push(2)\n\techo \"Fifo size: \", fifo.len()\n\ttry:\n\t\techo \"Popping: \", fifo.pop()\n\t\techo \"Popping: \", fifo.pop()\n\t\techo \"Popping: \", fifo.pop()\n\t\techo \"Popping: \", fifo.pop()\n\texcept ValueError:\n\t\techo \"Exception catched: \", getCurrentExceptionMsg()\n" + }, + { + "id": 690, + "length": 1324, + "source": "Rosetta Code", + "text": "import fusion/matching\n{.experimental: \"caseStmtMacros\".}\n\ntype\n\tColour = enum Empty, Red, Black\n\tRBTree[T] = ref object\n\t\tcolour: Colour\n\t\tleft, right: RBTree[T]\n\t\tvalue: T\n\nproc `[]`[T](r: RBTree[T], idx: static[FieldIndex]): auto =\n\t## enables tuple syntax for unpacking and matching\n\twhen idx == 0: r.colour\n\telif idx == 1: r.left\n\telif idx == 2: r.value\n\telif idx == 3: r.right\n\ntemplate B[T](l: untyped, v: T, r): RBTree[T] =\n\tRBTree[T](colour: Black, left: l, value: v, right: r)\n\ntemplate R[T](l: untyped, v: T, r): RBTree[T] =\n\tRBTree[T](colour: Red, left: l, value: v, right: r)\n\ntemplate balImpl[T](t: typed): untyped =\n\tcase t\n\tof (colour: Red | Empty): discard\n\tof (Black, (Red, (Red, @a, @x, @b), @y, @c), @z, @d) |\n\t\t(Black, (Red, @a, @x, (Red, @b, @y, @c)), @z, @d) |\n\t\t(Black, @a, @x, (Red, (Red, @b, @y, @c), @z, @d)) |\n\t\t(Black, @a, @x, (Red, @b, @y, (Red, @c, @z, @d))):\n\t\tt = R(B(a, x, b), y, B(c, z, d))\n\nproc balance*[T](t: var RBTree[T]) = balImpl[T](t)\n\ntemplate insImpl[T](t, x: typed): untyped =\n\ttemplate E: RBTree[T] = RBTree[T]()\n\tcase t\n\tof (colour: Empty): t = R(E, x, E)\n\tof (value: > x): t.left.ins(x); t.balance()\n\tof (value: < x): t.right.ins(x); t.balance()\n\nproc insert*[T](tt: var RBTree[T], xx: T) =\n\tproc ins(t: var RBTree[T], x: T) = insImpl[T](t, x)\n\ttt.ins(xx)\n\ttt.colour = Black\n" + }, + { + "id": 691, + "length": 1179, + "source": "Rosetta Code", + "text": "import macros\n\ntype ListComprehension = object\nvar lc*: ListComprehension\n\nmacro `[]`*(lc: ListComprehension, x, t): untyped =\n\texpectLen(x, 3)\n\texpectKind(x, nnkInfix)\n\texpectKind(x[0], nnkIdent)\n\tassert($x[0].strVal == \"|\")\n\n\tresult = newCall(\n\t\tnewDotExpr(\n\t\t\tnewIdentNode(\"result\"),\n\t\t\tnewIdentNode(\"add\")),\n\t\tx[1])\n\n\tfor i in countdown(x[2].len-1, 0):\n\t\tlet y = x[2][i]\n\t\texpectKind(y, nnkInfix)\n\t\texpectMinLen(y, 1)\n\t\tif y[0].kind == nnkIdent and $y[0].strVal == \"<-\":\n\t\t\texpectLen(y, 3)\n\t\t\tresult = newNimNode(nnkForStmt).add(y[1], y[2], result)\n\t\telse:\n\t\t\tresult = newIfStmt((y, result))\n\n\tresult = newNimNode(nnkCall).add(\n\t\tnewNimNode(nnkPar).add(\n\t\t\tnewNimNode(nnkLambda).add(\n\t\t\t\tnewEmptyNode(),\n\t\t\t\tnewEmptyNode(),\n\t\t\t\tnewEmptyNode(),\n\t\t\t\tnewNimNode(nnkFormalParams).add(\n\t\t\t\t\tnewNimNode(nnkBracketExpr).add(\n\t\t\t\t\t\tnewIdentNode(\"seq\"),\n\t\t\t\t\t\tt)),\n\t\t\t\tnewEmptyNode(),\n\t\t\t\tnewEmptyNode(),\n\t\t\t\tnewStmtList(\n\t\t\t\t\tnewAssignment(\n\t\t\t\t\t\tnewIdentNode(\"result\"),\n\t\t\t\t\t\tnewNimNode(nnkPrefix).add(\n\t\t\t\t\t\t\tnewIdentNode(\"@\"),\n\t\t\t\t\t\t\tnewNimNode(nnkBracket))),\n\t\t\t\t\tresult))))\n\nconst n = 20\necho lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]\n" + }, + { + "id": 692, + "length": 1052, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\ntype Tree[T] = ref object\n\tvalue: T\n\tleft, right: Tree[T]\n\n\nproc newTree[T](value = default(T)): Tree[T] =\n\t## Create a tree with a single node with the given value.\n\tTree[T](value: value)\n\n\nproc map[T, U](tree: Tree[T]; f: (T) -> U): Tree[U] =\n\t## Apply function \"f\" to each element of a tree, building\n\t## another tree.\n\tresult = newTree[U](f(tree.value))\n\tif not tree.left.isNil:\n\t\tresult.left = tree.left.map(f)\n\tif not tree.right.isNil:\n\t\tresult.right = tree.right.map(f)\n\n\nproc print(tree: Tree; indent = 0) =\n\t## Print a tree.\n\tlet start = repeat(' ', indent)\n\techo start, \"value: \", tree.value\n\tif tree.left.isNil:\n\t\techo start, \" nil\"\n\telse:\n\t\tprint(tree.left, indent + 2)\n\tif tree.right.isNil:\n\t\techo start, \" nil\"\n\telse:\n\t\tprint(tree.right, indent + 2)\n\n\nwhen isMainModule:\n\n\techo \"Initial tree:\"\n\tvar tree = newTree[int](5)\n\ttree.left = newTree[int](2)\n\ttree.right = newTree[int](7)\n\tprint(tree)\n\n\techo \"\"\n\techo \"Tree created by applying a function to each node:\"\n\tlet tree1 = tree.map((x) => 1 / x)\n\tprint(tree1)\n" + }, + { + "id": 693, + "length": 831, + "source": "Rosetta Code", + "text": "import options, os\nfrom net import newSocket, bindUnix\nfrom nativesockets import AF_UNIX, SOCK_DGRAM, IPPROTO_IP\nfrom posix import EADDRINUSE\n\nconst sockAddr = \"\\0com.myapp.sock\" # Linux will delete this when the application ends\n# notice the prefixed null byte, it's the Linux abstract namespace\n\nproc server()=\n\techo \"Unique instance detected\"\n\nproc client()=\n\techo \"Duplicate instance detected\"\n\nwhen isMainModule:\n\tvar\n\t\tsock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP)\n\t\tisUnique: Option[bool]\n\n\ttry:\n\t\tsock.bindUnix(sock_addr)\n\t\tis_unique = some true\n\texcept OSError:\n\t\t\tif cint(osLastError()) == EADDRINUSE:\n\t\t\t\tisUnique = some false\n\t\t\telse:\n\t\t\t\traise getCurrentException()\n\n\tif unlikely is_unique.isNone:\n\t\techo \"Error detecting uniqueness\" # unreachable\n\telse:\n\t\tif isUnique.unsafeGet():\n\t\t\tserver()\n\t\telse:\n\t\t\tclient()\n" + }, + { + "id": 694, + "length": 582, + "source": "Rosetta Code", + "text": "import os\n\nvar\n\tcode = if paramCount() > 0: readFile paramStr 1\n\t\t\t\t else: readAll stdin\n\ttape = newSeq[char]()\n\td = 0\n\ti = 0\n\nproc run(skip = false): bool =\n\twhile d >= 0 and i < code.len:\n\t\tif d >= tape.len: tape.add '\\0'\n\n\t\tif code[i] == '[':\n\t\t\tinc i\n\t\t\tlet p = i\n\t\t\twhile run(tape[d] == '\\0'): i = p\n\t\telif code[i] == ']':\n\t\t\treturn tape[d] != '\\0'\n\t\telif not skip:\n\t\t\tcase code[i]\n\t\t\tof '+': inc tape[d]\n\t\t\tof '-': dec tape[d]\n\t\t\tof '>': inc d\n\t\t\tof '<': dec d\n\t\t\tof '.': stdout.write tape[d]\n\t\t\tof ',': tape[d] = stdin.readChar\n\t\t\telse: discard\n\n\t\tinc i\n\ndiscard run()\n" + }, + { + "id": 695, + "length": 1624, + "source": "Rosetta Code", + "text": "import strformat\nimport bignum\n\ntype PExp = tuple[prime: Int; exp: uint]\n\nlet\n\tone = newInt(1)\n\ttwo = newInt(2)\n\tten = newInt(10)\n\n\nfunc sqrt(n: Int): Int =\n\tvar s = n\n\twhile true:\n\t\tresult = s\n\t\ts = (n div result + result) shr 1\n\t\tif s >= result: break\n\n\nproc factor(n: Int): seq[PExp] =\n\tvar n = n\n\tvar e = 0u\n\twhile n.bit(e) == 0: inc e\n\tif e != 0:\n\t\tn = n shr e\n\t\tresult.add (two, e)\n\tvar s = sqrt(n)\n\tvar d = newInt(3)\n\twhile n > one:\n\t\tif d > s: d = n\n\t\te = 0u\n\t\twhile true:\n\t\t\tlet (q, r) = divMod(n, d)\n\t\t\tif not r.isZero: break\n\t\t\tn = q\n\t\t\tinc e\n\t\tif e != 0:\n\t\t\tresult.add (d.clone, e)\n\t\t\ts = sqrt(n)\n\t\tinc d, two\n\n\nproc moBachShallit58(a, n: Int; pf: seq[PExp]): Int =\n\tlet n = abs(n)\n\tlet n1 = n - one\n\tresult = newInt(1)\n\tfor pe in pf:\n\t\tlet y = n1 div pe.prime.pow(pe.exp)\n\t\tvar o = 0u\n\t\tvar x = a.exp(y.toInt.uint, n)\n\t\twhile x > one:\n\t\t\tx = x.exp(pe.prime.toInt.uint, n)\n\t\t\tinc o\n\t\tvar o1 = pe.prime.pow(o)\n\t\to1 = o1 div gcd(result, o1)\n\t\tresult *= o1\n\n\nproc moTest(a, n: Int) =\n\tif n.probablyPrime(25) == 0:\n\t\techo \"Not computed. Modulus must be prime for this algorithm.\"\n\t\treturn\n\n\tstdout.write if a.bitLen < 100: \"ord({a})\" else: \"ord([big])\"\n\tstdout.write if n.bitlen < 100: \" mod {n}\" else: \" mod [big]\"\n\tlet mob = moBachShallit58(a, n, factor(n - one))\n\techo \" = {mob}\"\n\n\nwhen isMainModule:\n\tmoTest(newInt(37), newInt(3343))\n\n\tvar b = ten.pow(100) + one\n\tmotest(b, newInt(7919))\n\n\tb = ten.pow(1000) + one\n\tmoTest(b, newInt(\"15485863\"))\n\n\tb = ten.pow(10000) - one\n\tmoTest(b, newInt(\"22801763489\"))\n\n\tmoTest(newInt(\"1511678068\"), newInt(\"7379191741\"))\n\n\tmoTest(newInt(\"3047753288\"), newInt(\"2257683301\"))\n" + }, + { + "id": 696, + "length": 798, + "source": "Rosetta Code", + "text": "import strfmt\n\ntype Matrix[M, N: static[int]] = array[M, array[N, float]]\n\nlet a = [[1.0, 1.0, 1.0, 1.0],\n\t\t\t\t [2.0, 4.0, 8.0, 16.0],\n\t\t\t\t [3.0, 9.0, 27.0, 81.0],\n\t\t\t\t [4.0, 16.0, 64.0, 256.0]]\n\nlet b = [[ 4.0, -3.0 , 4/3.0, -1/4.0],\n\t\t\t\t [-13/3.0, 19/4.0, -7/3.0, 11/24.0],\n\t\t\t\t [ 3/2.0, -2.0 , 7/6.0, -1/4.0],\n\t\t\t\t [ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]\n\nproc `$`(m: Matrix): string =\n\tresult = \"([\"\n\tfor r in m:\n\t\tif result.len > 2: result.add \"]\\n [\"\n\t\tfor val in r: result.add val.format(\"8.2f\")\n\tresult.add \"])\"\n\nproc `*`[M, P, N](a: Matrix[M, P]; b: Matrix[P, N]): Matrix[M, N] =\n\tfor i in result.low .. result.high:\n\t\tfor j in result[0].low .. result[0].high:\n\t\t\tfor k in a[0].low .. a[0].high:\n\t\t\t\tresult[i][j] += a[i][k] * b[k][j]\n\necho a\necho b\necho a * b\necho b * a\n" + }, + { + "id": 697, + "length": 4113, + "source": "Rosetta Code", + "text": "import strutils\nimport os\n\n#--\n# Lexer\n#--\n\ntype\n\tTokenKind = enum\n\t\ttokNumber\n\t\ttokPlus = \"+\", tokMinus = \"-\", tokStar = \"*\", tokSlash = \"/\"\n\t\ttokLPar, tokRPar\n\t\ttokEnd\n\tToken = object\n\t\tcase kind: TokenKind\n\t\tof tokNumber: value: float\n\t\telse: discard\n\nproc lex(input: string): seq[Token] =\n\t# Here we go through the entire input string and collect all the tokens into\n\t# a sequence.\n\tvar pos = 0\n\twhile pos < input.len:\n\t\tcase input[pos]\n\t\tof '0'..'9':\n\t\t\t# Digits consist of three parts: the integer part, the delimiting decimal\n\t\t\t# point, and the decimal part.\n\t\t\tvar numStr = \"\"\n\t\t\twhile pos < input.len and input[pos] in Digits:\n\t\t\t\tnumStr.add(input[pos])\n\t\t\t\tinc(pos)\n\t\t\tif pos < input.len and input[pos] == '.':\n\t\t\t\tnumStr.add('.')\n\t\t\t\tinc(pos)\n\t\t\t\twhile pos < input.len and input[pos] in Digits:\n\t\t\t\t\tnumStr.add(input[pos])\n\t\t\t\t\tinc(pos)\n\t\t\tresult.add(Token(kind: tokNumber, value: numStr.parseFloat()))\n\t\tof '+': inc(pos); result.add(Token(kind: tokPlus))\n\t\tof '-': inc(pos); result.add(Token(kind: tokMinus))\n\t\tof '*': inc(pos); result.add(Token(kind: tokStar))\n\t\tof '/': inc(pos); result.add(Token(kind: tokSlash))\n\t\tof '(': inc(pos); result.add(Token(kind: tokLPar))\n\t\tof ')': inc(pos); result.add(Token(kind: tokRPar))\n\t\tof ' ': inc(pos)\n\t\telse: raise newException(ArithmeticError,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"Unexpected character '\" & input[pos] & '\\'')\n\t# We append an 'end' token to the end of our token sequence, to mark where the\n\t# sequence ends.\n\tresult.add(Token(kind: tokEnd))\n\n#--\n# Parser\n#--\n\ntype\n\tExprKind = enum\n\t\texprNumber\n\t\texprBinary\n\tExpr = ref object\n\t\tcase kind: ExprKind\n\t\tof exprNumber: value: float\n\t\tof exprBinary:\n\t\t\tleft, right: Expr\n\t\t\toperator: TokenKind\n\nproc `$`(ex: Expr): string =\n\t# This proc returns a lisp representation of the expression.\n\tcase ex.kind\n\tof exprNumber: $ex.value\n\tof exprBinary: '(' & $ex.operator & ' ' & $ex.left & ' ' & $ex.right & ')'\n\nvar\n\t# The input to the program is provided via command line parameters.\n\ttokens = lex(commandLineParams().join(\" \"))\n\tpos = 0\n\n# This table stores the precedence level of each infix operator. For tokens\n# this does not apply to, the precedence is set to 0.\nconst Precedence: array[low(TokenKind)..high(TokenKind), int] = [\n\ttokNumber: 0,\n\ttokPlus: 1,\n\ttokMinus: 1,\n\ttokStar: 2,\n\ttokSlash: 2,\n\ttokLPar: 0,\n\ttokRPar: 0,\n\ttokEnd: 0\n]\n\n# We use a Pratt parser, so the two primary components are the prefix part, and\n# the infix part. We start with a prefix token, and when we're done, we continue\n# with an infix token.\n\nproc parse(prec = 0): Expr\n\nproc parseNumber(token: Token): Expr =\n\tresult = Expr(kind: exprNumber, value: token.value)\n\nproc parseParen(token: Token): Expr =\n\tresult = parse()\n\tif tokens[pos].kind != tokRPar:\n\t\traise newException(ArithmeticError, \"Unbalanced parenthesis\")\n\tinc(pos)\n\nproc parseBinary(left: Expr, token: Token): Expr =\n\tresult = Expr(kind: exprBinary, left: left, right: parse(),\n\t\t\t\t\t\t\t\toperator: token.kind)\n\nproc parsePrefix(token: Token): Expr =\n\tcase token.kind\n\tof tokNumber: result = parseNumber(token)\n\tof tokLPar: result = parseParen(token)\n\telse: discard\n\nproc parseInfix(left: Expr, token: Token): Expr =\n\tcase token.kind\n\tof tokPlus, tokMinus, tokStar, tokSlash: result = parseBinary(left, token)\n\telse: discard\n\nproc parse(prec = 0): Expr =\n\t# This procedure is the heart of a Pratt parser, it puts the whole expression\n\t# together into one abstract syntax tree, properly dealing with precedence.\n\tvar token = tokens[pos]\n\tinc(pos)\n\tresult = parsePrefix(token)\n\twhile prec < Precedence[tokens[pos].kind]:\n\t\ttoken = tokens[pos]\n\t\tif token.kind == tokEnd:\n\t\t\t# When we hit the end token, we're done.\n\t\t\tbreak\n\t\tinc(pos)\n\t\tresult = parseInfix(result, token)\n\nlet ast = parse()\n\nproc `==`(ex: Expr): float =\n\t# This proc recursively evaluates the given expression.\n\tresult =\n\t\tcase ex.kind\n\t\tof exprNumber: ex.value\n\t\tof exprBinary:\n\t\t\tcase ex.operator\n\t\t\tof tokPlus: ==ex.left + ==ex.right\n\t\t\tof tokMinus: ==ex.left - ==ex.right\n\t\t\tof tokStar: ==ex.left * ==ex.right\n\t\t\tof tokSlash: ==ex.left / ==ex.right\n\t\t\telse: 0.0\n\n# In the end, we print out the result.\necho ==ast\n" + }, + { + "id": 698, + "length": 1243, + "source": "Rosetta Code", + "text": "type Function = proc(x: float): float\ntype Rule = proc(f: Function; x, h: float): float\n\nproc leftRect(f: Function; x, h: float): float =\n\tf(x)\n\nproc midRect(f: Function; x, h: float): float =\n\tf(x + h/2.0)\n\nproc rightRect(f: Function; x, h: float): float =\n\tf(x + h)\n\nproc trapezium(f: Function; x, h: float): float =\n\t(f(x) + f(x+h)) / 2.0\n\nproc simpson(f: Function, x, h: float): float =\n\t(f(x) + 4.0*f(x+h/2.0) + f(x+h)) / 6.0\n\nproc cube(x: float): float =\n\tx * x * x\n\nproc reciprocal(x: float): float =\n\t1.0 / x\n\nproc identity(x: float): float =\n\tx\n\nproc integrate(f: Function; a, b: float; steps: int; meth: Rule): float =\n\tlet h = (b-a) / float(steps)\n\tfor i in 0 ..< steps:\n\t\tresult += meth(f, a+float(i)*h, h)\n\tresult = h * result\n\nfor fName, a, b, steps, fun in items(\n\t [(\"cube\", 0, 1, 100, cube),\n\t\t(\"reciprocal\", 1, 100, 1000, reciprocal),\n\t\t(\"identity\", 0, 5000, 5_000_000, identity),\n\t\t(\"identity\", 0, 6000, 6_000_000, identity)]):\n\n\tfor rName, rule in items({\"leftRect\": leftRect, \"midRect\": midRect,\n\t\t\t\"rightRect\": rightRect, \"trapezium\": trapezium, \"simpson\": simpson}):\n\n\t\techo fName, \" integrated using \", rName\n\t\techo \" from \", a, \" to \", b, \" (\", steps, \" steps) = \",\n\t\t\tintegrate(fun, float(a), float(b), steps, rule)\n" + }, + { + "id": 699, + "length": 3248, + "source": "Rosetta Code", + "text": "import strformat, sugar\n\ntype\n\n\t# Natural number.\n\tNumber = ref object\n\t\tpred: Number\n\n\t# Even natural number: 2 x half.\n\tEvenNumber = ref object\n\t\thalf: Number\n\n\t# Odd natural number: 2 x half + 1.\n\tOddNumber = ref object\n\t\thalf: Number\n\nconst Zero: Number = nil\n\n# Contructors.\nfunc newNumber(pred: Number): auto = Number(pred: pred)\nfunc newEvenNumber(half: Number): auto = EvenNumber(half: half)\nfunc newOddNumber(half: Number): auto = OddNumber(half: half)\n\nfunc isZero(n: Number): bool =\n\t## Test whether a natural number is zero.\n\tn.isNil\n\nfunc inc(n: Number): Number =\n\t## Increment a natural number.\n\tnewNumber(n)\n\nfunc dec(n: Number): Number =\n\t## Decrement a natural number.\n\tn.pred\n\nfunc `+`(x, y: Number): Number =\n\t## Add two natural numbers.\n\tif y.isZero: x else: x.inc + y.dec\n\nfunc `+`(x, y: EvenNumber): EvenNumber =\n\t## Add two even natural numbers.\n\tif y.half.isZero: x else: newEvenNumber(x.half + y.half)\n\nfunc `+`(x, y: OddNumber): EvenNumber =\n\t## Add two odd natural numbers.\n\tnewEvenNumber(inc(x.half + y.half))\n\nfunc newNumber(n: Natural): Number =\n\t## Build a natural number from a Nim Natural.\n\tif n > 0: inc(newNumber(n - 1)) else: Zero\n\nfunc count(n: Number): Natural =\n\t## Return the integer representation of a natural number.\n\tif n.isZero: 0 else: count(dec(n)) + 1\n\nfunc count(n: EvenNumber): Natural =\n\t## Return the integer representation of an even natural number.\n\tn.half.count * 2\n\nfunc count(n: OddNumber): Natural =\n\t## Return the integer representation of an odd natural number.\n\tn.half.count * 2 + 1\n\nproc testCommutative(e1, e2: EvenNumber) =\n\t## Test if even number addition is commutative for given numbers.\n\tlet c1 = e1.count\n\tlet c2 = e2.count\n\tlet passed = count(e1 + e2) == count(e2 + e1)\n\tlet symbol = if passed: \"==\" else: \"!=\"\n\techo \"\\n{c1} + {c2} {symbol} {c2} + {c1}\"\n\nproc testAssociative(e1, e2, e3: EvenNumber) =\n\t## Test if even number arithmetic is associative.\n\tlet c1 = e1.count\n\tlet c2 = e2.count\n\tlet c3 = e3.count\n\tlet passed = count((e1 + e2) + e3) == count(e1 + (e2 + e3))\n\tlet symbol = if passed: \"==\" else: \"!=\"\n\techo \"\\n({c1} + {c2}) + {c3} {symbol} {c1} + ({c2} + {c3})\"\n\n\nlet numbers = collect(newSeq, for i in 0..9: newNumber(i))\n\necho \"The first 10 even natural numbers are:\"\nfor i, n in numbers:\n\tstdout.write n.count, if i == 9: '\\n' else: ' '\n\necho \"\\nThe first 10 even natural numbers are:\"\nfor i, n in numbers:\n\tstdout.write newEvenNumber(n).count, if i == 9: '\\n' else: ' '\n\necho \"\\nThe first 10 odd natural numbers are:\"\nfor i, n in numbers:\n\tstdout.write newOddNumber(n).count, if i == 9: '\\n' else: ' '\n\nvar sum = Zero\nfor n in numbers: sum = sum + n\necho \"\\nThe sum of the first 10 natural numbers is: {sum.count}\"\n\nvar evenSum = newEvenNumber(Zero)\nfor n in numbers: evenSum = evenSum + newEvenNumber(n)\necho \"\\nThe sum of the first 10 even natural numbers (increasing order) is: {evenSum.count}\"\n\nevenSum = newEvenNumber(Zero)\nfor i in countdown(9, 0): evenSum = evenSum + newEvenNumber(numbers[i])\necho \"\\nThe sum of the first 10 even natural numbers (decreasing order) is: {evenSum.count}\"\n\ntestCommutative(newEvenNumber(numbers[8]), newEvenNumber(numbers[9]))\n\ntestAssociative(newEvenNumber(numbers[7]), newEvenNumber(numbers[8]), newEvenNumber(numbers[9]))\n" + }, + { + "id": 700, + "length": 950, + "source": "Rosetta Code", + "text": "import lenientops, sequtils, stats, strformat\n\nproc polyRegression(x, y: openArray[int]) =\n\n\tlet xm = mean(x)\n\tlet ym = mean(y)\n\tlet x2m = mean(x.mapIt(it * it))\n\tlet x3m = mean(x.mapIt(it * it * it))\n\tlet x4m = mean(x.mapIt(it * it * it * it))\n\tlet xym = mean(zip(x, y).mapIt(it[0] * it[1]))\n\tlet x2ym = mean(zip(x, y).mapIt(it[0] * it[0] * it[1]))\n\n\tlet sxx = x2m - xm * xm\n\tlet sxy = xym - xm * ym\n\tlet sxx2 = x3m - xm * x2m\n\tlet sx2x2 = x4m - x2m * x2m\n\tlet sx2y = x2ym - x2m * ym\n\n\tlet b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)\n\tlet c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)\n\tlet a = ym - b * xm - c * x2m\n\n\tfunc abc(x: int): float = a + b * x + c * x * x\n\n\techo \"y = {a} + {b}x + {c}x^2\\n\"\n\techo \" Input Approximation\"\n\techo \" x y y1\"\n\tfor (xi, yi) in zip(x, y):\n\t\techo \"{xi:2} {yi:3} {abc(xi):5}\"\n\n\nlet x = toSeq(0..10)\nlet y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]\npolyRegression(x, y)\n" + }, + { + "id": 701, + "length": 3095, + "source": "Rosetta Code", + "text": "import algorithm\nimport random\nimport sequtils\nimport times\n\n\n# Data.\n\nproc oneSeq(n: int): seq[int] = repeat(1, n)\n\n\nproc shuffledSeq(n: int): seq[int] =\n\tresult.setLen(n)\n\tfor item in result.mitems: item = rand(1..(10 * n))\n\n\nproc ascendingSeq(n: int): seq[int] = sorted(shuffledSeq(n))\n\n\n# Algorithms.\n\nfunc bubbleSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\tvar n = a.len\n\twhile true:\n\t\tvar n2 = 0\n\t\tfor i in 1.. a[i]:\n\t\t\t\tswap a[i], a[i - 1]\n\t\t\t\tn2 = i\n\t\tn = n2\n\t\tif n == 0: break\n\n\nfunc insertionSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\tfor index in 1..a.high:\n\t\tlet value = a[index]\n\t\tvar subIndex = index - 1\n\t\twhile subIndex >= 0 and a[subIndex] > value:\n\t\t\ta[subIndex + 1] = a[subIndex]\n\t\t\tdec subIndex\n\t\ta[subIndex + 1] = value\n\n\nfunc quickSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n\tfunc sorter(a: var openArray[int]; first, last: int) =\n\t\tif last - first < 1: return\n\t\tlet pivot = a[first + (last - first) div 2]\n\t\tvar left = first\n\t\tvar right = last\n\t\twhile left <= right:\n\t\t\twhile a[left] < pivot: inc left\n\t\t\twhile a[right] > pivot: dec right\n\t\t\tif left <= right:\n\t\t\t\tswap a[left], a[right]\n\t\t\t\tinc left\n\t\t\t\tdec right\n\t\tif first < right: a.sorter(first, right)\n\t\tif left < last: a.sorter(left, last)\n\n\ta.sorter(0, a.high)\n\n\nfunc radixSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n\tvar tmp = newSeq[int](a.len)\n\n\tfor shift in countdown(63, 0):\n\t\tfor item in tmp.mitems: item = 0\n\t\tvar j = 0\n\t\tfor i in 0..a.high:\n\t\t\tlet move = a[i] shl shift >= 0\n\t\t\tlet toBeMoved = if shift == 0: not move else: move\n\t\t\tif toBeMoved:\n\t\t\t\ttmp[j] = a[i]\n\t\t\t\tinc j\n\t\t\telse:\n\t\t\t\ta[i - j] = a[i]\n\t\tfor i in j..tmp.high: tmp[i] = a[i - j]\n\t\tfor i in 0..a.high: a[i] = tmp[i]\n\n\nfunc shellSort(a: var openArray[int]) {.locks: \"unknown\".} =\n\n\tconst Gaps = [701, 301, 132, 57, 23, 10, 4, 1]\n\n\tfor gap in Gaps:\n\t\tfor i in gap..a.high:\n\t\t\tlet temp = a[i]\n\t\t\tvar j = i\n\t\t\twhile j >= gap and a[j - gap] > temp:\n\t\t\t\ta[j] = a[j - gap]\n\t\t\t\tdec j, gap\n\t\t\ta[j] = temp\n\n\nfunc standardSort(a: var openArray[int]) =\n\ta.sort()\n\n\n# Main code.\n\nimport strformat\n\nconst\n\n\tRuns = 10\n\tLengths = [1, 10, 100, 1_000, 10_000, 100_000]\n\n\tSorts = [bubbleSort, insertionSort, quickSort, radixSort, shellSort, standardSort]\n\nconst\n\tSortTitles = [\"Bubble\", \"Insert\", \"Quick \", \"Radix \", \"Shell \", \"Standard\"]\n\tSeqTitles = [\"All Ones\", \"Ascending\", \"Shuffled\"]\n\nvar totals: array[SeqTitles.len, array[Sorts.len, array[Lengths.len, Duration]]]\n\nrandomize()\n\nfor k, n in Lengths:\n\tlet seqs = [oneSeq(n), ascendingSeq(n), shuffledSeq(n)]\n\tfor _ in 1..Runs:\n\t\tfor i, s in seqs:\n\t\t\tfor j, sort in Sorts:\n\t\t\t\tvar s = s\n\t\t\t\tlet t0 = getTime()\n\t\t\t\ts.sort()\n\t\t\t\ttotals[i][j][k] += getTime() - t0\n\necho \"All timings in microseconds\\n\"\nstdout.write \"Sequence length \"\nfor length in Lengths:\n\tstdout.write \"{length:6d} \"\necho '\\n'\nfor i in 0..SeqTitles.high:\n\techo \" {SeqTitles[i]}:\"\n\tfor j in 0..Sorts.high:\n\t\tstdout.write \" {SortTitles[j]:8s} \"\n\t\tfor k in 0..Lengths.high:\n\t\t\tlet time = totals[i][j][k].inMicroseconds div Runs\n\t\t\tstdout.write \"{time:8d} \"\n\t\techo \"\"\n\techo '\\n'\n" + }, + { + "id": 702, + "length": 1004, + "source": "Rosetta Code", + "text": "import math, sequtils, strformat, strutils, times\n\nproc getStep(n: int64): int64 {.inline.} =\n\tresult = 1 + n shl 2 - n shr 1 shl 1\n\nproc primeFac(n: int64): seq[int64] =\n\tvar maxq = int64(sqrt(float(n)))\n\tvar d = 1\n\tvar q: int64 = 2 + (n and 1) # Start with 2 or 3 according to oddity.\n\twhile q <= maxq and n %% q != 0:\n\t\tq = getStep(d)\n\t\tinc d\n\tif q <= maxq:\n\t\tlet q1 = primeFac(n /% q)\n\t\tlet q2 = primeFac(q)\n\t\tresult = concat(q2, q1, result)\n\telse:\n\t\tresult.add(n)\n\niterator primes(limit: int): int =\n\tvar isPrime = newSeq[bool](limit + 1)\n\tfor n in 2..limit: isPrime[n] = true\n\tfor n in 2..limit:\n\t\tif isPrime[n]:\n\t\t\tyield n\n\t\t\tfor i in countup(n *% n, limit, n):\n\t\t\t\tisPrime[i] = false\n\nwhen isMainModule:\n\n\t# Example: calculate factors of Mersenne numbers from M2 to M59.\n\tfor m in primes(59):\n\t\tlet p = 2i64^m - 1\n\t\tlet s = \"2^{m}-1\"\n\t\tstdout.write \"{s:<6} = {p} with factors: \"\n\t\tlet start = cpuTime()\n\t\tstdout.write primeFac(p).join(\", \")\n\t\techo \" => {(1000 * (cpuTime() - start)).toInt} ms\"\n" + }, + { + "id": 703, + "length": 914, + "source": "Rosetta Code", + "text": "proc merge[T](a, b: var openarray[T]; left, middle, right: int) =\n\tlet\n\t\tleftLen = middle - left\n\t\trightLen = right - middle\n\tvar\n\t\tl = 0\n\t\tr = leftLen\n\n\tfor i in left ..< middle:\n\t\tb[l] = a[i]\n\t\tinc l\n\tfor i in middle ..< right:\n\t\tb[r] = a[i]\n\t\tinc r\n\n\tl = 0\n\tr = leftLen\n\tvar i = left\n\n\twhile l < leftLen and r < leftLen + rightLen:\n\t\tif b[l] < b[r]:\n\t\t\ta[i] = b[l]\n\t\t\tinc l\n\t\telse:\n\t\t\ta[i] = b[r]\n\t\t\tinc r\n\t\tinc i\n\n\twhile l < leftLen:\n\t\ta[i] = b[l]\n\t\tinc l\n\t\tinc i\n\twhile r < leftLen + rightLen:\n\t\ta[i] = b[r]\n\t\tinc r\n\t\tinc i\n\nproc mergeSort[T](a, b: var openarray[T]; left, right: int) =\n\tif right - left <= 1: return\n\n\tlet middle = (left + right) div 2\n\tmergeSort(a, b, left, middle)\n\tmergeSort(a, b, middle, right)\n\tmerge(a, b, left, middle, right)\n\nproc mergeSort[T](a: var openarray[T]) =\n\tvar b = newSeq[T](a.len)\n\tmergeSort(a, b, 0, a.len)\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nmergeSort a\necho a\n" + }, + { + "id": 704, + "length": 1061, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\ntype Matrix[N: static int; T] = array[1..N, array[1..N, T]]\n\nfunc `*`[N, T](a, b: Matrix[N, T]): Matrix[N, T] =\n\tfor i in 1..N:\n\t\tfor j in 1..N:\n\t\t\tfor k in 1..N:\n\t\t\t\tresult[i][j] += a[i][k] * b[k][j]\n\n\nfunc identityMatrix[N; T](): Matrix[N, T] =\n\tfor i in 1..N:\n\t\tresult[i][i] = T(1)\n\n\nfunc `^`[N, T](m: Matrix[N, T]; n: Natural): Matrix[N, T] =\n\tif n == 0: return identityMatrix[N, T]()\n\tif n == 1: return m\n\tvar n = n\n\tvar m = m\n\tresult = identityMatrix[N, T]()\n\twhile n > 0:\n\t\tif (n and 1) != 0:\n\t\t\tresult = result * m\n\t\tn = n shr 1\n\t\tm = m * m\n\n\nproc `$`(m: Matrix): string =\n\tvar lg = 0\n\tfor i in 1..m.N:\n\t\tfor j in 1..m.N:\n\t\t\tlg = max(lg, len($m[i][j]))\n\tfor i in 1..m.N:\n\t\techo m[i].mapIt(align($it, lg)).join(\" \")\n\n\nwhen isMainModule:\n\n\tlet m1: Matrix[3, int] = [[ 3, 2, -1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[-1, 0, 5],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[ 2, -1, 3]]\n\techo m1^10\n\n\timport math\n\tconst\n\t\tC30 = sqrt(3.0) / 2\n\t\tS30 = 1 / 2\n\tlet m2: Matrix[2, float] = [[C30, -S30], [S30, C30]] # 30deg rotation matrix.\n\techo m2^12 # Nearly the identity matrix.\n" + }, + { + "id": 705, + "length": 742, + "source": "Rosetta Code", + "text": "import strutils\n\nproc reverse(a: string): string =\n\tresult = newString(a.len)\n\tfor i, c in a:\n\t\tresult[a.high - i] = c\n\nconst digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\nproc toBase[T](num: T, base: range[2..36]): string =\n\tif num == 0: return \"0\"\n\tresult = \"\"\n\tif num < 0: result.add '-'\n\tvar tmp = abs(num)\n\tvar s = \"\"\n\twhile tmp > 0:\n\t\ts.add digits[int(tmp mod base)]\n\t\ttmp = tmp div base\n\tresult.add s.reverse\n\nproc fromBase(str: string, base: range[2..36]): BiggestInt =\n\tvar str = str\n\tlet first = if str[0] == '-': 1 else: 0\n\n\tfor i in first .. str.high:\n\t\tlet c = str[i].toLowerAscii\n\t\tassert c in digits[0 ..< base]\n\t\tresult = result * base + digits.find c\n\n\tif first == 1: result *= -1\n\necho 26.toBase 16\necho \"1a\".fromBase 16\n" + }, + { + "id": 706, + "length": 1736, + "source": "Rosetta Code", + "text": "import strutils\n\ntype\n\n\tBlockValue = object\n\t\tknown: int\n\t\tx, y, z: int\n\n\tVariables = tuple[x, y, z: int]\n\nfunc `+=`(left: var BlockValue; right: BlockValue) =\n\t## Symbolically add one block to another.\n\tleft.known += right.known\n\tleft.x += right.x - right.z # Z is excluded as n(Y - X - Z) = 0.\n\tleft.y += right.y + right.z\n\nproc toString(n: BlockValue; vars: Variables): string =\n\t## Return the representation of the block value, when X, Y, Z are known.\n\tresult = $(n.known + n.x * vars.x + n.y * vars.y + n.z * vars.z)\n\nproc Solve2x2(a11, a12, b1, a21, a22, b2: int): Variables =\n\t## Solve a puzzle, supposing an integer solution exists.\n\tif a22 == 0:\n\t\tresult.x = b2 div a21\n\t\tresult.y = (b1 - a11 * result.x) div a12\n\telse:\n\t\tresult.x = (b1 * a22 - b2 * a12) div (a11 * a22 - a21 * a12)\n\t\tresult.y = (b1 - a11 * result.x) div a12\n\tresult.z = result.y - result.x\n\nvar blocks : array[1..5, array[1..5, BlockValue]] # The lower triangle contains blocks.\n\n# The bottom blocks.\nblocks[5][1] = BlockValue(x: 1)\nblocks[5][2] = BlockValue(known: 11)\nblocks[5][3] = BlockValue(y: 1)\nblocks[5][4] = BlockValue(known: 4)\nblocks[5][5] = BlockValue(z: 1)\n\n# Upward run.\nfor row in countdown(4, 1):\n\tfor column in 1..row:\n\t\tblocks[row][column] += blocks[row + 1][column]\n\t\tblocks[row][column] += blocks[row + 1][column + 1]\n\n# Now have known blocks 40=[3][1], 151=[1][1] and Y=X+Z to determine X,Y,Z.\nlet vars = Solve2x2(blocks[1][1].x,\n\t\t\t\t\t\t\t\t\t\tblocks[1][1].y,\n\t\t\t\t\t\t\t\t\t\t151 - blocks[1][1].known,\n\t\t\t\t\t\t\t\t\t\tblocks[3][1].x,\n\t\t\t\t\t\t\t\t\t\tblocks[3][1].y,\n\t\t\t\t\t\t\t\t\t\t40 - blocks[3][1].known)\n\n# Print the results.\nfor row in 1..5:\n\tvar line = \"\"\n\tfor column in 1..row:\n\t\tline.addSep(\" \")\n\t\tline.add toString(blocks[row][column], vars)\n\techo line\n" + }, + { + "id": 707, + "length": 895, + "source": "Rosetta Code", + "text": "import sugar, strutils\n\nproc amb(comp: proc(a, b: string): bool,\n\t\t\t\t options: seq[seq[string]],\n\t\t\t\t prev: string = \"\"): seq[string] =\n\n\tif options.len == 0: return @[]\n\n\tfor opt in options[0]:\n\t\t# If this is the base call, prev is nil and we need to continue.\n\t\tif prev.len != 0 and not comp(prev, opt): continue\n\n\t\t# Take care of the case where we have no options left.\n\t\tif options.len == 1: return @[opt]\n\n\t\t# Traverse into the tree.\n\t\tlet res = amb(comp, options[1..options.high], opt)\n\n\t\t# If it was a failure, try the next one.\n\t\tif res.len > 0: return opt & res # We have a match.\n\n\treturn @[]\n\nconst sets = @[@[\"the\", \"that\", \"a\"],\n\t\t\t\t\t\t\t @[\"frog\", \"elephant\", \"thing\"],\n\t\t\t\t\t\t\t @[\"walked\", \"treaded\", \"grows\"],\n\t\t\t\t\t\t\t @[\"slowly\", \"quickly\"]]\n\nlet result = amb((s, t: string) => (s[s.high] == t[0]), sets)\nif result.len == 0:\n\techo \"No matches found!\"\nelse:\n\techo result.join \" \"\n" + }, + { + "id": 708, + "length": 977, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\nconst\n\t## Separation of the two endpoints.\n\t## Make this a power of 2 for prettier output.\n\tSep = 512\n\t## Depth of recursion. Adjust as desired for different visual effects.\n\tDepth = 18\n\n\tS = sqrt(2.0) / 2\n\tSin = [float 0, S, 1, S, 0, -S, -1, -S]\n\tCos = [float 1, S, 0, -S, -1, -S, 0, S]\n\n\tLineColor = ColorRGBU [byte 64, 192, 96]\n\tWidth = Sep * 11 div 6\n\tHeight = Sep * 4 div 3\n\n\tOutput = \"dragon.png\"\n\n\nfunc dragon(img: var Image; n, a, t: int; d, x, y: float) =\n\tif n <= 1:\n\t\timg.drawLine((x.toInt, y.toInt), ((x + d * Cos[a]).toInt, (y + d * Sin[a]).toInt), LineColor)\n\t\treturn\n\tlet d = d * S\n\tlet a1 = (a - t) and 7\n\tlet a2 = (a + t) and 7\n\timg.dragon(n - 1, a1, 1, d, x, y)\n\timg.dragon(n - 1, a2, -1, d, x + d * Cos[a1], y + d * Sin[a1])\n\n\nvar image = initImage[ColorRGBU](Width, Height)\nimage.fill(ColorRGBU [byte 0, 0, 0])\nimage.dragon(Depth, 0, 1, Sep, Sep / 2, Sep * 5 / 6)\n\n# Save into a PNG file.\nimage.savePNG(Output, compression = 9)\n" + }, + { + "id": 709, + "length": 628, + "source": "Rosetta Code", + "text": "import strutils\n\nconst nums = [(1000, \"M\"), (900, \"CM\"), (500, \"D\"), (400, \"CD\"), (100, \"C\"), (90, \"XC\"),\n\t\t\t\t\t\t\t(50, \"L\"), (40, \"XL\"), (10, \"X\"), (9, \"IX\"), (5, \"V\"), (4, \"IV\"), (1, \"I\")]\n\nproc toRoman(n: Positive): string =\n\tvar n = n.int\n\tfor (a, r) in nums:\n\t\tresult.add(repeat(r, n div a))\n\t\tn = n mod a\n\nfor i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n\t\t\t\t\t11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n\t\t\t\t\t25, 30, 40, 50, 60, 69, 70, 80, 90, 99,\n\t\t\t\t\t100, 200, 300, 400, 500, 600, 666, 700, 800, 900,\n\t\t\t\t\t1000, 1009, 1444, 1666, 1945, 1997, 1999,\n\t\t\t\t\t2000, 2008, 2010, 2011, 2500, 3000, 3999]:\n\techo ($i).align(4), \": \", i.toRoman\n" + }, + { + "id": 710, + "length": 1291, + "source": "Rosetta Code", + "text": "import strutils\n\n# Requires 5 bytes of data store.\nconst Hw = r\"\"\"\n/++++!/===========?\\>++.>+.+++++++..+++\\\n\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n\t\t\t\\==-<<<<+>+++/ /=.>.+>.--------.-/\"\"\"\n\n\nproc snusp(dsLen: int; code: string) =\n\t## The interpreter.\n\n\tvar\n\t\tds = newSeq[byte](dsLen) # Data store.\n\t\tdp = 0 # Data pointer.\n\t\tcs = code.splitLines() # Two dimensional code store.\n\t\tipr, ipc = 0 # Instruction pointers in row ans column.\n\t\tdir = 0 # Direction (0 = right, 1 = down, 2 = left, 3 = up).\n\n\t# Initialize instruction pointers.\n\tfor r, row in cs:\n\t\tipc = row.find('$')\n\t\tif ipc >= 0:\n\t\t\tipr = r\n\t\t\tbreak\n\n\tfunc step() =\n\t\t## Update the instruction pointers acccording to the direction.\n\n\t\tif (dir and 1) == 0:\n\t\t\tinc ipc, 1 - (dir and 2)\n\t\telse:\n\t\t\tinc ipr, 1 - (dir and 2)\n\n\t# Interpreter loop.\n\twhile ipr in 0..cs.high and ipc in 0..cs[ipr].high:\n\t\tcase cs[ipr][ipc]\n\t\tof '>': inc dp\n\t\tof '<': dec dp\n\t\tof '+': inc ds[dp]\n\t\tof '-': dec ds[dp]\n\t\tof '.': stdout.write chr(ds[dp])\n\t\tof ',': ds[dp] = byte(stdin.readLine()[0])\n\t\tof '/': dir = not dir\n\t\tof '\\\\': dir = dir xor 1\n\t\tof '!': step()\n\t\tof '?': (if ds[dp] == 0: step())\n\t\telse: discard\n\t\tstep()\n\n\nwhen isMainModule:\n\tsnusp(5, Hw)\n" + }, + { + "id": 711, + "length": 555, + "source": "Rosetta Code", + "text": "proc lcs(a, b: string): string =\n\tvar ls = newSeq[seq[int]](a.len+1)\n\tfor i in 0 .. a.len:\n\t\tls[i].newSeq(b.len+1)\n\n\tfor i, x in a:\n\t\tfor j, y in b:\n\t\t\tif x == y:\n\t\t\t\tls[i+1][j+1] = ls[i][j] + 1\n\t\t\telse:\n\t\t\t\tls[i+1][j+1] = max(ls[i+1][j], ls[i][j+1])\n\n\tresult = \"\"\n\tvar x = a.len\n\tvar y = b.len\n\twhile x > 0 and y > 0:\n\t\tif ls[x][y] == ls[x-1][y]:\n\t\t\tdec x\n\t\telif ls[x][y] == ls[x][y-1]:\n\t\t\tdec y\n\t\telse:\n\t\t\tassert a[x-1] == b[y-1]\n\t\t\tresult = a[x-1] & result\n\t\t\tdec x\n\t\t\tdec y\n\necho lcs(\"1234\", \"1224533324\")\necho lcs(\"thisisatest\", \"testing123testing\")\n" + }, + { + "id": 712, + "length": 667, + "source": "Rosetta Code", + "text": "iterator permutations[T](ys: openarray[T]): seq[T] =\n\tvar\n\t\td = 1\n\t\tc = newSeq[int](ys.len)\n\t\txs = newSeq[T](ys.len)\n\n\tfor i, y in ys: xs[i] = y\n\tyield xs\n\n\tblock outter:\n\t\twhile true:\n\t\t\twhile d > 1:\n\t\t\t\tdec d\n\t\t\t\tc[d] = 0\n\t\t\twhile c[d] >= d:\n\t\t\t\tinc d\n\t\t\t\tif d >= ys.len: break outter\n\n\t\t\tlet i = if (d and 1) == 1: c[d] else: 0\n\t\t\tswap xs[i], xs[d]\n\t\t\tyield xs\n\t\t\tinc c[d]\n\nproc isSorted[T](s: openarray[T]): bool =\n\tvar last = low(T)\n\tfor c in s:\n\t\tif c < last:\n\t\t\treturn false\n\t\tlast = c\n\treturn true\n\nproc permSort[T](a: openarray[T]): seq[T] =\n\tfor p in a.permutations:\n\t\tif p.isSorted:\n\t\t\treturn p\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\necho a.permSort\n" + }, + { + "id": 713, + "length": 636, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nproc printPascalTriangle(n: int) =\n\t## Print a Pascal triangle.\n\n\t# Build the triangle.\n\tvar triangle: seq[seq[int]]\n\ttriangle.add @[1]\n\tfor _ in 1.. 0: result.add dictionary[w]\n\n\nproc decompress*(compressed: var seq[int]): string =\n\n\t# Build the dictionary.\n\tvar dictionary: Table[int, string]\n\tfor i in 0..255: dictionary[i] = $chr(i)\n\n\tvar w = dictionary[compressed[0]]\n\tcompressed.delete(0)\n\n\tresult = w\n\tfor k in compressed:\n\t\tvar entry: string\n\t\tif k in dictionary:\n\t\t\tentry = dictionary[k]\n\t\telif k == dictionary.len:\n\t\t\tentry = w & w[0]\n\t\telse:\n\t\t\traise newException(ValueError, \"Bad compressed k: \" & $k)\n\t\tresult.add entry\n\t\t# New sequence: add it to the dictionary.\n\t\tdictionary[dictionary.len] = w & entry[0]\n\t\tw = entry\n\n\nwhen isMainModule:\n\tvar compressed = compress(\"TOBEORNOTTOBEORTOBEORNOT\")\n\techo compressed\n\tvar decompressed = decompress(compressed)\n\techo decompressed\n" + }, + { + "id": 717, + "length": 602, + "source": "Rosetta Code", + "text": "from strutils import parseInt\n\nproc ackermann(m, n: int64): int64 =\n\tif m == 0:\n\t\tresult = n + 1\n\telif n == 0:\n\t\tresult = ackermann(m - 1, 1)\n\telse:\n\t\tresult = ackermann(m - 1, ackermann(m, n - 1))\n\nproc getNumber(): int =\n\ttry:\n\t\tresult = stdin.readLine.parseInt\n\texcept ValueError:\n\t\techo \"An integer, please!\"\n\t\tresult = getNumber()\n\tif result < 0:\n\t\techo \"Please Enter a non-negative Integer: \"\n\t\tresult = getNumber()\n\necho \"First non-negative Integer please: \"\nlet first = getNumber()\necho \"Second non-negative Integer please: \"\nlet second = getNumber()\necho \"Result: \", $ackermann(first, second)\n" + }, + { + "id": 718, + "length": 1869, + "source": "Rosetta Code", + "text": "import strutils, algorithm\n\nconst\n\ttens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\",\n\t\t\t\t\t\"eighty\", \"ninety\"]\n\tsmall = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\",\n\t\t\t\t\t \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\t\t\t\t \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\thuge = [\"\", \"\", \"million\", \"billion\", \"trillion\", \"quadrillion\",\n\t\t\t\t\t\"quintillion\", \"sextillion\", \"septillion\", \"octillion\", \"nonillion\",\n\t\t\t\t\t\"decillion\"]\n\n# Forward reference.\nproc spellInteger(n: int64): string\n\nproc nonzero(c: string; n: int64; connect = \"\"): string =\n\tif n == 0: \"\" else: connect & c & spellInteger(n)\n\nproc lastAnd(num: string): string =\n\tif ',' in num:\n\t\tlet pos = num.rfind(',')\n\t\tvar (pre, last) = if pos >= 0: (num[0 ..< pos], num[pos+1 .. num.high])\n\t\t\t\t\t\t\t\t\t\t\telse: (\"\", num)\n\t\tif \" and \" notin last: last = \" and\" & last\n\t\tresult = [pre, \",\", last].join()\n\telse:\n\t\tresult = num\n\nproc big(e, n: int64): string =\n\tif e == 0:\n\t\tspellInteger(n)\n\telif e == 1:\n\t\tspellInteger(n) & \" thousand\"\n\telse:\n\t\tspellInteger(n) & \" \" & huge[e]\n\niterator base1000Rev(n: int64): int64 =\n\tvar n = n\n\twhile n != 0:\n\t\tlet r = n mod 1000\n\t\tn = n div 1000\n\t\tyield r\n\nproc spellInteger(n: int64): string =\n\tif n < 0:\n\t\t\"minus \" & spellInteger(-n)\n\telif n < 20:\n\t\tsmall[int(n)]\n\telif n < 100:\n\t\tlet a = n div 10\n\t\tlet b = n mod 10\n\t\ttens[int(a)] & nonzero(\"-\", b)\n\telif n < 1000:\n\t\tlet a = n div 100\n\t\tlet b = n mod 100\n\t\tsmall[int(a)] & \" hundred\" & nonzero(\" \", b, \" and\")\n\telse:\n\t\tvar sq = newSeq[string]()\n\t\tvar e = 0\n\t\tfor x in base1000Rev(n):\n\t\t\tif x > 0: sq.add big(e, x)\n\t\t\tinc e\n\t\treverse sq\n\t\tlastAnd(sq.join(\", \"))\n\nfor n in [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]:\n\techo align($n, 4),\" -> \",spellInteger(n)\n\nvar n = 201021002001\nwhile n != 0:\n\techo align($n, 14),\" -> \",spellInteger(n)\n\tn = n div -10\n" + }, + { + "id": 719, + "length": 893, + "source": "Rosetta Code", + "text": "import random\n\n\ntype\n\tBoolArray = array[30, bool]\n\tSymbols = array[bool, char]\n\n\nproc neighbours(map: BoolArray, i: int): int =\n\tif i > 0: inc(result, int(map[i - 1]))\n\tif i + 1 < len(map): inc(result, int(map[i + 1]))\n\nproc print(map: BoolArray, symbols: Symbols) =\n\tfor i in map: write(stdout, symbols[i])\n\twrite(stdout, \"\\l\")\n\nproc randomMap: BoolArray =\n\trandomize()\n\tfor i in mitems(result): i = sample([true, false])\n\n\nconst\n\tnum_turns = 20\n\tsymbols = ['_', '#']\n\n\tT = true\n\tF = false\n\nvar map =\n\t[F, T, T, T, F, T, T, F, T, F, T, F, T, F, T,\n\t\tF, F, T, F, F, F, F, F, F, F, F, F, F, F, F]\n\n# map = randomMap() # uncomment for random start\n\nprint(map, symbols)\n\nfor _ in 0 ..< num_turns:\n\tvar map2 = map\n\n\tfor i, v in pairs(map):\n\t\tmap2[i] =\n\t\t\tif v: neighbours(map, i) == 1\n\t\t\telse: neighbours(map, i) == 2\n\n\tprint(map2, symbols)\n\n\tif map2 == map: break\n\tmap = map2\n" + }, + { + "id": 720, + "length": 769, + "source": "Rosetta Code", + "text": "import os, strutils, random\n\nrandomize()\nvar w, h: int\nif paramCount() >= 2:\n\tw = parseInt(paramStr(1))\n\th = parseInt(paramStr(2))\nif w <= 0: w = 30\nif h <= 0: h = 30\n\n# Initialize\nvar univ, utmp = newSeq[seq[bool]](h)\nfor y in 0.. 0:\n\t\t\t\t\tnodataMaxLine.add date\n\t\t\t\tif nodataMax < nodata and nodata > 0:\n\t\t\t\t\tnodataMax = nodata\n\t\t\t\t\tnodataMaxLine = @[date]\n\t\t\t\tnodata = 0\n\t\t\t\ttotLine += datum\n\t\t\t\tinc numLine\n\n\t\ttotFile += totLine\n\t\tnumFile += numLine\n\n\t\tlet average = if numLine > 0: totLine / float(numLine) else: 0.0\n\t\techo \"Line: {date} Reject: {data.len - numLine:2} Accept: {numLine:2} \",\n\t\t\t\t \"LineTot: {totLine:6.2f} LineAvg: {average:4.2f}\"\n\necho()\necho \"\"\"File(s) = {commandLineParams().join(\" \")}\"\"\"\necho \"Total = {totFile:.2f}\"\necho \"Readings = {numFile}\"\necho \"Average = {totFile / float(numFile):.2f}\"\necho \"\"\necho \"Maximum run(s) of {nodataMax} consecutive false readings \",\n\t\t \"\"\"ends at line starting with date(s): {nodataMaxLine.join(\" \")}.\"\"\"\n" + }, + { + "id": 725, + "length": 1906, + "source": "Rosetta Code", + "text": "import x11/[xlib,xutil,x]\n\nconst\n\twindowWidth = 1000\n\twindowHeight = 600\n\tborderWidth = 5\n\teventMask = ButtonPressMask or KeyPressMask or ExposureMask\n\nvar\n\tdisplay: PDisplay\n\twindow: Window\n\tdeleteMessage: Atom\n\tgraphicsContext: GC\n\nproc init() =\n\tdisplay = XOpenDisplay(nil)\n\tif display == nil:\n\t\tquit \"Failed to open display\"\n\n\tlet\n\t\tscreen = XDefaultScreen(display)\n\t\trootWindow = XRootWindow(display, screen)\n\t\tforegroundColor = XBlackPixel(display, screen)\n\t\tbackgroundColor = XWhitePixel(display, screen)\n\n\twindow = XCreateSimpleWindow(display, rootWindow, -1, -1, windowWidth,\n\t\t\twindowHeight, borderWidth, foregroundColor, backgroundColor)\n\n\tdiscard XSetStandardProperties(display, window, \"X11 Example\", \"window\", 0,\n\t\t\tnil, 0, nil)\n\n\tdiscard XSelectInput(display, window, eventMask)\n\tdiscard XMapWindow(display, window)\n\n\tdeleteMessage = XInternAtom(display, \"WM_DELETE_WINDOW\", false.XBool)\n\tdiscard XSetWMProtocols(display, window, deleteMessage.addr, 1)\n\n\tgraphicsContext = XDefaultGC(display, screen)\n\n\nproc drawWindow() =\n\tconst text = \"Hello, Nim programmers.\"\n\tdiscard XDrawString(display, window, graphicsContext, 10, 50, text, text.len)\n\tdiscard XFillRectangle(display, window, graphicsContext, 20, 20, 10, 10)\n\n\nproc mainLoop() =\n\t## Process events until the quit event is received\n\tvar event: XEvent\n\twhile true:\n\t\tdiscard XNextEvent(display, event.addr)\n\t\tcase event.theType\n\t\tof Expose:\n\t\t\tdrawWindow()\n\t\tof ClientMessage:\n\t\t\tif cast[Atom](event.xclient.data.l[0]) == deleteMessage:\n\t\t\t\tbreak\n\t\tof KeyPress:\n\t\t\tlet key = XLookupKeysym(cast[PXKeyEvent](event.addr), 0)\n\t\t\tif key != 0:\n\t\t\t\techo \"Key \", key, \" pressed\"\n\t\tof ButtonPressMask:\n\t\t\techo \"Mouse button \", event.xbutton.button, \" pressed at \",\n\t\t\t\t\tevent.xbutton.x, \",\", event.xbutton.y\n\t\telse:\n\t\t\tdiscard\n\n\nproc main() =\n\tinit()\n\tmainLoop()\n\tdiscard XDestroyWindow(display, window)\n\tdiscard XCloseDisplay(display)\n\n\nmain()\n" + }, + { + "id": 726, + "length": 1804, + "source": "Rosetta Code", + "text": "import strutils, tables\n\nconst NumFields = 49\nconst DateField = 0\nconst FlagGoodValue = 1\n\nvar badRecords: int # Number of records that have invalid formatted values.\nvar totalRecords: int # Total number of records in the file.\nvar badInstruments: int # Total number of records that have at least one instrument showing error.\nvar seenDates: Table[string, bool] # Table to keep track of what dates we have seen.\n\nproc checkFloats(floats: seq[string]): bool =\n\t## Ensure we can parse all records as floats (except the date stamp).\n\tfor index in 1.. maxValue and current.weight <= Sack.weight and current.volume <= Sack.volume:\n\t\t\t\tmaxvalue = current.value\n\t\t\t\ttotalweight = current.weight\n\t\t\t\ttotalvolume = current.volume\n\t\t\t\tn = [i, j, k]\n\necho fmt\"Maximum value achievable is {maxValue}.\"\necho fmt\"This is achieved by carrying {n[1]} panacea, {n[2]} ichor and {n[3]} gold items.\"\necho fmt\"The weight of this carry is {totalWeight:6.3f} and the volume used is {totalVolume:6.4f}.\"\n" + }, + { + "id": 730, + "length": 1179, + "source": "Rosetta Code", + "text": "import algorithm\n\ntype Record = tuple[name, id: string; salary: int; department: string]\n\nvar people = [(\"Tyler Bennett\", \"E10297\", 32000, \"D101\"),\n\t\t\t\t\t\t\t(\"John Rappl\", \"E21437\", 47000, \"D050\"),\n\t\t\t\t\t\t\t(\"George Woltman\", \"E00127\", 53500, \"D101\"),\n\t\t\t\t\t\t\t(\"Adam Smith\", \"E63535\", 18000, \"D202\"),\n\t\t\t\t\t\t\t(\"Claire Buckman\", \"E39876\", 27800, \"D202\"),\n\t\t\t\t\t\t\t(\"David McClellan\", \"E04242\", 41500, \"D101\"),\n\t\t\t\t\t\t\t(\"Rich Holcomb\", \"E01234\", 49500, \"D202\"),\n\t\t\t\t\t\t\t(\"Nathan Adams\", \"E41298\", 21900, \"D050\"),\n\t\t\t\t\t\t\t(\"Richard Potter\", \"E43128\", 15900, \"D101\"),\n\t\t\t\t\t\t\t(\"David Motsinger\", \"E27002\", 19250, \"D202\"),\n\t\t\t\t\t\t\t(\"Tim Sampair\", \"E03033\", 27000, \"D101\"),\n\t\t\t\t\t\t\t(\"Kim Arlich\", \"E10001\", 57000, \"D190\"),\n\t\t\t\t\t\t\t(\"Timothy Grove\", \"E16398\", 29900, \"D190\")]\n\nproc pcmp(a, b: Record): int =\n\tresult = cmp(a.department, b.department)\n\tif result == 0:\n\t\tresult = cmp(b.salary, a.salary)\n\nproc printTop(people: openArray[Record]; n: Positive) =\n\tvar people = sorted(people, pcmp)\n\tvar rank = 0\n\tfor i, p in people:\n\t\tif i > 0 and p.department != people[i-1].department:\n\t\t\trank = 0\n\t\t\techo()\n\t\tif rank < n:\n\t\t\techo p.department, \" \", p.salary, \" \", p.name\n\t\tinc rank\n\npeople.printTop(2)\n" + }, + { + "id": 731, + "length": 1417, + "source": "Rosetta Code", + "text": "type\n\tLuminance* = uint8\n\tIndex* = int\n\n\tColor* = tuple\n\t\tr, g, b: Luminance\n\n\tImage* = ref object\n\t\tw*, h*: Index\n\t\tpixels*: seq[Color]\n\n\tPoint* = tuple\n\t\tx, y: Index\n\nproc color*(r, g, b: SomeInteger): Color =\n\t## Build a color value from R, G and B values.\n\tresult.r = r.uint8\n\tresult.g = g.uint8\n\tresult.b = b.uint8\n\nconst\n\tBlack* = color( 0, 0, 0)\n\tWhite* = color(255, 255, 255)\n\nproc newImage*(width, height: int): Image =\n\t## Create an image with given width and height.\n\tnew(result)\n\tresult.w = width\n\tresult.h = height\n\tresult.pixels.setLen(width * height)\n\niterator indices*(img: Image): Point =\n\t## Yield the pixels coordinates as tuples.\n\tfor y in 0 ..< img.h:\n\t\tfor x in 0 ..< img.w:\n\t\t\tyield (x, y)\n\nproc `[]`*(img: Image; x, y: int): Color =\n\t## Get a pixel RGB value.\n\timg.pixels[y * img.w + x]\n\nproc `[]=`*(img: Image; x, y: int; c: Color) =\n\t## Set a pixel RGB value to given color.\n\timg.pixels[y * img.w + x] = c\n\nproc fill*(img: Image; color: Color) =\n\t## Fill the image with a color.\n\tfor x, y in img.indices:\n\t\timg[x, y] = color\n\nproc print*(img: Image) =\n\t## Output an ASCII representation of the image.\n\tfor x, y in img.indices:\n\t\tif x mod img.w == 0:\n\t\t\tstdout.write '\\n'\n\t\tstdout.write if img[x, y] == White: '.' else: 'H'\n\tstdout.write '\\n'\n\nwhen isMainModule:\n\tvar img = newImage(100, 20)\n\timg.fill color(255, 255, 255)\n\timg[1, 2] = color(255, 0, 0)\n\timg[3, 4] = img[1, 2]\n\timg.print\n" + }, + { + "id": 732, + "length": 631, + "source": "Rosetta Code", + "text": "import bitmap\nimport bresenham\nimport lenientops\n\nproc drawQuadraticBezier*(\n\t\t\t\timage: Image; pt1, pt2, pt3: Point; color: Color; nseg: Positive = 20) =\n\n\tvar points = newSeq[Point](nseg + 1)\n\n\tfor i in 0..nseg:\n\t\tlet t = i / nseg\n\t\tlet a = (1 - t) * (1 - t)\n\t\tlet b = 2 * t * (1 - t)\n\t\tlet c = t * t\n\n\t\tpoints[i] = (x: (a * pt1.x + b * pt2.x + c * pt3.x).toInt,\n\t\t\t\t\t\t\t\t y: (a * pt1.y + b * pt2.y + c * pt3.y).toInt)\n\n\tfor i in 1..points.high:\n\t\timage.drawLine(points[i - 1], points[i], color)\n\n\nwhen isMainModule:\n\tvar img = newImage(16, 12)\n\timg.fill(White)\n\timg.drawQuadraticBezier((1, 7), (7, 12), (14, 1), Black)\n\timg.print\n" + }, + { + "id": 733, + "length": 638, + "source": "Rosetta Code", + "text": "import bitmap\n\nproc drawLine*(img: Image; p, q: Point; color: Color) =\n\tlet\n\t\tdx = abs(q.x - p.x)\n\t\tsx = if p.x < q.x: 1 else: -1\n\t\tdy = abs(q.y - p.y)\n\t\tsy = if p.y < q.y: 1 else: -1\n\n\tvar\n\t\tp = p\n\t\tq = q\n\t\terr = (if dx > dy: dx else: -dy) div 2\n\t\te2 = 0\n\n\twhile true:\n\t\timg[p.x, p.y] = color\n\t\tif p == q:\n\t\t\tbreak\n\t\te2 = err\n\t\tif e2 > -dx:\n\t\t\terr -= dy\n\t\t\tp.x += sx\n\t\tif e2 < dy:\n\t\t\terr += dx\n\t\t\tp.y += sy\n\nwhen isMainModule:\n\tvar img = newImage(16, 16)\n\timg.fill(White)\n\timg.drawLine((0, 7), (7, 15), Black)\n\timg.drawLine((7, 15), (15, 7), Black)\n\timg.drawLine((15, 7), (7, 0), Black)\n\timg.drawLine((7, 0), (0, 7), Black)\n\timg.print()\n" + }, + { + "id": 734, + "length": 768, + "source": "Rosetta Code", + "text": "import bitmap\nimport ppm_write\nimport osproc\n\n# Build an image.\nvar image = newImage(100, 50)\nimage.fill(color(255, 0, 0))\nfor row in 10..20:\n\tfor col in 0..output2.jpeg\", options = {poUsePath, poEvalCommand})\nstream = p.inputStream()\nimage.writePPM(stream)\np.close()\n" + }, + { + "id": 735, + "length": 1246, + "source": "Rosetta Code", + "text": "import bitmap\n\nproc setPixel(img: Image; x, y: int; color: Color) {.inline.} =\n\t# Set a pixel at a given color.\n\t# Ignore if the point is outside of the image.\n\tif x in 0..= 0:\n\t\t\tdec y\n\t\t\tinc ddFY, 2\n\t\t\tinc f, ddFY\n\t\tinc x\n\t\tinc ddFX, 2\n\t\tinc f, ddFX + 1\n\n\t\timg.setPixel(center.x + x, center.y + y, color)\n\t\timg.setPixel(center.x - x, center.y + y, color)\n\t\timg.setPixel(center.x + x, center.y - y, color)\n\t\timg.setPixel(center.x - x, center.y - y, color)\n\t\timg.setPixel(center.x + y, center.y + x, color)\n\t\timg.setPixel(center.x - y, center.y + x, color)\n\t\timg.setPixel(center.x + y, center.y - x, color)\n\t\timg.setPixel(center.x - y, center.y - x, color)\n\n\nwhen isMainModule:\n\tvar img = newImage(16, 16)\n\timg.fill(White)\n\timg.drawCircle((7, 7), 5, Black)\n\timg.print()\n" + }, + { + "id": 736, + "length": 714, + "source": "Rosetta Code", + "text": "import bitmap\nimport bresenham\nimport lenientops\n\nproc drawCubicBezier*(\n\t\t\t\timage: Image; pt1, pt2, pt3, pt4: Point; color: Color; nseg: Positive = 20) =\n\n\tvar points = newSeq[Point](nseg + 1)\n\n\tfor i in 0..nseg:\n\t\tlet t = i / nseg\n\t\tlet u = (1 - t) * (1 - t)\n\t\tlet a = (1 - t) * u\n\t\tlet b = 3 * t * u\n\t\tlet c = 3 * (t * t) * (1 - t)\n\t\tlet d = t * t * t\n\n\t\tpoints[i] = (x: (a * pt1.x + b * pt2.x + c * pt3.x + d * pt4.x).toInt,\n\t\t\t\t\t\t\t\t y: (a * pt1.y + b * pt2.y + c * pt3.y + d * pt4.y).toInt)\n\n\tfor i in 1..points.high:\n\t\timage.drawLine(points[i - 1], points[i], color)\n\n\nwhen isMainModule:\n\tvar img = newImage(16, 16)\n\timg.fill(White)\n\timg.drawCubicBezier((0, 15), (3, 0), (15, 2), (10, 14), Black)\n\timg.print\n" + }, + { + "id": 737, + "length": 1858, + "source": "Rosetta Code", + "text": "import bitmap\nimport lenientops\n\ntype\n\n\tGrayImage* = object\n\t\tw*, h*: Index\n\t\tpixels*: seq[Luminance]\n\nproc newGrayImage*(width, height: int): GrayImage =\n\t## Create a gray image with given width and height.\n\tnew(result)\n\tresult.w = width\n\tresult.h = height\n\tresult.pixels.setLen(width * height)\n\niterator indices*(img: GrayImage): Point =\n\t## Yield the pixels coordinates as tuples.\n\tfor y in 0 ..< img.h:\n\t\tfor x in 0 ..< img.w:\n\t\t\tyield (x, y)\n\nproc `[]`*(img: GrayImage; x, y: int): Luminance =\n\t## Get a pixel luminance value.\n\timg.pixels[y * img.w + x]\n\nproc `[]=`*(img: GrayImage; x, y: int; lum: Luminance) =\n\t## Set a pixel luminance to given value.\n\timg.pixels[y * img.w + x] = lum\n\nproc fill*(img: GrayImage; lum: Luminance) =\n\t## Set the pixels to a given luminance.\n\tfor x, y in img.indices:\n\t\timg[x, y] = lum\n\nfunc toGrayLuminance(color: Color): Luminance =\n\t## Compute the luminance from RGB value.\n\tLuminance(0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b + 0.5)\n\nfunc toGrayImage*(img: Image): GrayImage =\n\t##\n\tresult = newGrayImage(img.w, img.h)\n\tfor pt in img.indices:\n\t\tresult[pt.x, pt.y] = img[pt.x, pt.y].toGrayLuminance()\n\nfunc toImage*(img: GrayImage): Image =\n\tresult = newImage(img.w, img.h)\n\tfor pt in img.indices:\n\t\tlet lum = img[pt.x, pt.y]\n\t\tresult[pt.x, pt.y] = (lum, lum, lum)\n\n\nwhen isMainModule:\n\n\timport ppm_write\n\n\t# Create a RGB image.\n\tvar image = newImage(100, 50)\n\timage.fill(color(128, 128, 128))\n\tfor row in 10..20:\n\t\tfor col in 0.. 0: result.add(\" -> \")\n\t\tresult.add($n.data)\n\t\tn = n.next\n\nvar l = initList[int]()\nvar n = newNode(12)\nvar m = newNode(13)\nvar i = newNode(14)\nvar j = newNode(15)\nl.append(n)\nl.prepend(m)\nl.insertAfter(m, i)\nl.prepend(j)\nl.remove(m)\necho l\n\nvar l2 = initList[string]()\nl2.prepend newNode(\"hello\")\nl2.append newNode(\"world\")\necho l2\n" + }, + { + "id": 743, + "length": 999, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\n# Creating a sequence containing sequences of integers.\nvar s1 = newSeq[seq[int]](5)\nfor item in s1.mitems: item = @[1]\necho \"s1 = \", s1 # @[@[1], @[1], @[1], @[1], @[1]]\ns1[0].add 2\necho \"s1 = \", s1 # @[@[1, 2], @[1], @[1], @[1], @[1]]\n\n# Using newSeqWith.\nvar s2 = newSeqWith(5, @[1])\necho \"s2 = \", s2 # @[@[1], @[1], @[1], @[1], @[1]]\ns2[0].add 2\necho \"s2 = \", s2 # @[@[1, 2], @[1], @[1], @[1], @[1]]\n\n# Creating a sequence containing pointers.\nproc newInt(n: int): ref int =\n\tnew(result)\n\tresult[] = n\nvar s3 = newSeqWith(5, newInt(1))\necho \"s3 contains references to \", s3.mapIt(it[]).join(\", \") # 1, 1, 1, 1, 1\ns3[0][] = 2\necho \"s3 contains references to \", s3.mapIt(it[]).join(\", \") # 2, 1, 1, 1, 1\n\n# How to create non distinct elements.\nlet p = newInt(1)\nvar s4 = newSeqWith(5, p)\necho \"s4 contains references to \", s4.mapIt(it[]).join(\", \") # 1, 1, 1, 1, 1\ns4[0][] = 2\necho \"s4 contains references to \", s4.mapIt(it[]).join(\", \") # 2, 2, 2, 2, 2\n" + }, + { + "id": 744, + "length": 2120, + "source": "Rosetta Code", + "text": "import math\n\nproc `^`[T](base, exp: T): T =\n\tvar (base, exp) = (base, exp)\n\tresult = 1\n\n\twhile exp != 0:\n\t\tif (exp and 1) != 0:\n\t\t\tresult *= base\n\t\texp = exp shr 1\n\t\tbase *= base\n\nproc gcd[T](u, v: T): T =\n\tif v != 0:\n\t\tgcd(v, u mod v)\n\telse:\n\t\tu.abs\n\nproc lcm[T](a, b: T): T =\n\ta div gcd(a, b) * b\n\ntype Rational* = tuple[num, den: int64]\n\nproc fromInt*(x: SomeInteger): Rational =\n\tresult.num = x\n\tresult.den = 1\n\nproc frac*(x: var Rational) =\n\tlet common = gcd(x.num, x.den)\n\tx.num = x.num div common\n\tx.den = x.den div common\n\nproc `+` *(x, y: Rational): Rational =\n\tlet common = lcm(x.den, y.den)\n\tresult.num = common div x.den * x.num + common div y.den * y.num\n\tresult.den = common\n\tresult.frac\n\nproc `+=` *(x: var Rational, y: Rational) =\n\tlet common = lcm(x.den, y.den)\n\tx.num = common div x.den * x.num + common div y.den * y.num\n\tx.den = common\n\tx.frac\n\nproc `-` *(x: Rational): Rational =\n\tresult.num = -x.num\n\tresult.den = x.den\n\nproc `-` *(x, y: Rational): Rational =\n\tx + -y\n\nproc `-=` *(x: var Rational, y: Rational) =\n\tx += -y\n\nproc `*` *(x, y: Rational): Rational =\n\tresult.num = x.num * y.num\n\tresult.den = x.den * y.den\n\tresult.frac\n\nproc `*=` *(x: var Rational, y: Rational) =\n\tx.num *= y.num\n\tx.den *= y.den\n\tx.frac\n\nproc reciprocal*(x: Rational): Rational =\n\tresult.num = x.den\n\tresult.den = x.num\n\nproc `div`*(x, y: Rational): Rational =\n\tx * y.reciprocal\n\nproc toFloat*(x: Rational): float =\n\tx.num.float / x.den.float\n\nproc toInt*(x: Rational): int64 =\n\tx.num div x.den\n\nproc cmp*(x, y: Rational): int =\n\tcmp x.toFloat, y.toFloat\n\nproc `<` *(x, y: Rational): bool =\n\tx.toFloat < y.toFloat\n\nproc `<=` *(x, y: Rational): bool =\n\tx.toFloat <= y.toFloat\n\nproc abs*(x: Rational): Rational =\n\tresult.num = abs x.num\n\tresult.den = abs x.den\n\nfor candidate in 2'i64 .. <((2'i64)^19):\n\tvar sum: Rational = (1'i64, candidate)\n\tfor factor in 2'i64 .. pow(candidate.float, 0.5).int64:\n\t\tif candidate mod factor == 0:\n\t\t\tsum += (1'i64, factor) + (1'i64, candidate div factor)\n\tif sum.den == 1:\n\t\techo \"Sum of recipr. factors of \",candidate,\" = \",sum.num,\" exactly \",\n\t\t\tif sum.num == 1: \"perfect!\" else: \"\"\n" + }, + { + "id": 745, + "length": 1272, + "source": "Rosetta Code", + "text": "import ../compiler/[nimeval, llstream, ast], strformat, os\n\nlet std = findNimStdLibCompileTime()\nlet modules = [std, std / \"pure\", std / \"std\", std / \"core\"]\nvar intr = createInterpreter(\"script\", modules)\n\n#dynamic variable\nlet varname = commandLineParams()[0]\nlet expr = commandLineParams()[1]\n\n#wrap the naked variable name and expression in a definition and proc,respectively to create valid code\n#for simplicity, the variable will always be an int, but one could of course define the type at runtime\n#globals and procs must be exported with * to be accessable\n#we also need to import any modules needed by the runtime code\nintr.evalScript(llStreamOpen(\"import math,sugar; var {varname}*:int; proc output*():auto = {expr}\"))\n\nfor i in 0..2:\n\t#set 'varname' to a value\n\tintr.getGlobalValue(intr.selectUniqueSymbol(varname)).intval = i\n\t#evaluate the expression and get the result\n\tlet output = intr.callRoutine(intr.selectRoutine(\"output\"), [])\n\t#depending on the expression, the result could be any type\n\t#as an example, here we check for int,float,or string\n\tcase output.kind\n\tof nkIntLit:\n\t\techo expr, \" = \", output.intval\n\tof nkFloatLit:\n\t\techo expr, \" = \", output.floatval\n\tof nkStrLit:\n\t\techo expr, \" = \", output.strval\n\telse:\n\t\tdiscard\n\ndestroyInterpreter(intr)\n" + }, + { + "id": 746, + "length": 1435, + "source": "Rosetta Code", + "text": "import asyncdispatch, options, strutils\ntype\n\tPrinter = ref object\n\t\tinkLevel, id: int\n\t\tbackup: Option[Printer]\n\tOutOfInkException = object of IOError\nproc print(p: Printer, line: string){.async.} =\n\tif p.inkLevel <= 0:\n\t\tif p.backup.isNone():\n\t\t\traise newException(OutOfInkException, \"out of ink\")\n\t\telse:\n\t\t\tawait p.backup.get().print(line)\n\telse:\n\t\tp.inkLevel-=1\n\t\tstdout.writeLine(\"$1:$2\".format(p.id, line))\n\t\tawait sleepAsync(100)\nproc newPrinter(inkLevel, id: int, backup: Option[Printer]): Printer =\n\tnew(result)\n\tresult.inkLevel = inkLevel\n\tresult.id = id\n\tresult.backup = backup\n\nproc print(p: Printer, msg: seq[string]){.async.} =\n\tfor line in msg:\n\t\ttry:\n\t\t\tawait p.print(line)\n\t\texcept OutOfInkException as e:\n\t\t\techo(\"out of ink\")\n\t\t\tbreak\nconst\n\thumptyLines = @[\n\t\t\"Humpty Dumpty sat on a wall.\",\n\t\t\"Humpty Dumpty had a great fall.\",\n\t\t\"All the king's horses and all the king's men,\",\n\t\t\"Couldn't put Humpty together again.\",\n\t\t]\n\tgooseLines = @[\n\t\t\t\t\"Old Mother Goose,\",\n\t\t\t\t\"When she wanted to wander,\",\n\t\t\t\t\"Would ride through the air,\",\n\t\t\t\t\"On a very fine gander.\",\n\t\t\t\t\"Jack's mother came in,\",\n\t\t\t\t\"And caught the goose soon,\",\n\t\t\t\t\"And mounting its back,\",\n\t\t\t\t\"Flew up to the moon.\",\n\t\t]\nproc main(){.async.} =\n\tvar\n\t\treservePrinter = newPrinter(5, 2, none(Printer))\n\t\tmainPrinter = newPrinter(5, 1, some(reservePrinter))\n\tawait mainPrinter.print(gooseLines) and mainPrinter.print(humptyLines)\n\nwaitFor main()\n" + }, + { + "id": 747, + "length": 1306, + "source": "Rosetta Code", + "text": "import bitmap\n\nproc floodFill*(img: Image; initPoint: Point; targetColor, replaceColor: Color) =\n\n\tvar stack: seq[Point]\n\tlet width = img.w\n\tlet height = img.h\n\n\tif img[initPoint.x, initPoint.y] != targetColor:\n\t\treturn\n\n\tstack.add(initPoint)\n\n\twhile stack.len > 0:\n\t\tvar w, e: Point\n\t\tlet pt = stack.pop()\n\t\tif img[pt.x, pt.y] == targetColor:\n\t\t\tw = pt\n\t\t\te = if pt.x + 1 < width: (pt.x + 1, pt.y) else: pt\n\t\telse:\n\t\t\tcontinue # Already processed.\n\n\t\t# Move west until color of node does not match \"targetColor\".\n\t\twhile w.x >= 0 and img[w.x, w.y] == targetColor:\n\t\t\timg[w.x, w.y] = replaceColor\n\t\t\tif w.y + 1 < height and img[w.x, w.y + 1] == targetColor:\n\t\t\t\tstack.add((w.x, w.y + 1))\n\t\t\tif w.y - 1 >= 0 and img[w.x, w.y - 1] == targetColor:\n\t\t\t\tstack.add((w.x, w.y - 1))\n\t\t\tdec w.x\n\n\t\t# Move east until color of node does not match \"targetColor\".\n\t\twhile e.x < width and img[e.x, e.y] == targetColor:\n\t\t\timg[e.x, e.y] = replaceColor\n\t\t\tif e.y + 1 < height and img[e.x, e.y + 1] == targetColor:\n\t\t\t\tstack.add((e.x, e.y + 1))\n\t\t\tif e.y - 1 >= 0 and img[e.x, e.y - 1] == targetColor:\n\t\t\t\tstack.add((e.x, e.y - 1))\n\t\t\tinc e.x\n\n\nwhen isMainModule:\n\n\timport ppm_read, ppm_write\n\n\tvar img = readPPM(\"Unfilledcirc.ppm\")\n\timg.floodFill((30, 122), White, color(255, 0, 0))\n\timg.writePPM(\"Unfilledcirc_red.ppm\")\n" + }, + { + "id": 748, + "length": 922, + "source": "Rosetta Code", + "text": "import strutils\n\nproc ti(a: char): int = ord(a) - ord('0')\n\nproc longmulti(a, b: string): string =\n\tvar\n\t\ti, j = 0\n\t\tk = false\n\n\t# either is zero, return \"0\"\n\tif a == \"0\" or b == \"0\":\n\t\treturn \"0\"\n\n\t# see if either a or b is negative\n\tif a[0] == '-':\n\t\ti = 1; k = not k\n\tif b[0] == '-':\n\t\tj = 1; k = not k\n\n\t# if yes, prepend minus sign if needed and skip the sign\n\tif i > 0 or j > 0:\n\t\tresult = if k: \"-\" else: \"\"\n\t\tresult.add longmulti(a[i..a.high], b[j..b.high])\n\t\treturn\n\n\tresult = repeat('0', a.len + b.len)\n\n\tfor i in countdown(a.high, 0):\n\t\tvar carry = 0\n\t\tvar k = i + b.len\n\t\tfor j in countdown(b.high, 0):\n\t\t\tlet n = ti(a[i]) * ti(b[j]) + ti(result[k]) + carry\n\t\t\tcarry = n div 10\n\t\t\tresult[k] = chr(n mod 10 + ord('0'))\n\t\t\tdec k\n\t\tresult[k] = chr(ord(result[k]) + carry)\n\n\tif result[0] == '0':\n\t\tresult[0..result.high-1] = result[1..result.high]\n\necho longmulti(\"-18446744073709551616\", \"-18446744073709551616\")\n" + }, + { + "id": 749, + "length": 2145, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\ntemplate ipart(x: float): float = floor(x)\ntemplate fpart(x: float): float = x - ipart(x)\ntemplate rfpart(x: float): float = 1 - fpart(x)\n\nconst\n\tBG = ColorRGBF64([0.0, 0.0, 0.0])\n\tFG = ColorRGBF64([1.0, 1.0, 1.0])\n\nfunc plot(img: var Image; x, y: int; c: float) =\n\t## Draw a point with brigthness c.\n\tlet d = 1 - c\n\timg[x, y] = ColorRGBF64([BG.r * d + FG.r * c, BG.g * d + FG.g * c, BG.b * d + FG.b * c])\n\n\nfunc drawLine(img: var Image; x0, y0, x1, y1: float) =\n\t## Draw an anti-aliased line from (x0, y0) to (x1, y1).\n\n\tvar (x0, y0, x1, y1) = (x0, y0, x1, y1)\n\tlet steep = abs(y1 - y0) > abs(x1 - x0)\n\tif steep:\n\t\tswap x0, y0\n\t\tswap x1, y1\n\tif x0 > x1:\n\t\tswap x0, x1\n\t\tswap y0, y1\n\n\tlet dx = x1 - x0\n\tlet dy = y1 - y0\n\tvar gradient = dy / dx\n\tif dx == 0:\n\t\tgradient = 1\n\n\t# Handle first endpoint.\n\tvar xend = round(x0)\n\tvar yend = y0 + gradient * (xend - x0)\n\tvar xgap = rfpart(x0 + 0.5)\n\tlet xpxl1 = xend.toInt\n\tlet ypxl1 = yend.toInt\n\tif steep:\n\t\timg.plot(ypxl1, xpxl1, rfpart(yend) * xgap)\n\t\timg.plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)\n\telse:\n\t\timg.plot(xpxl1, ypxl1, rfpart(yend) * xgap)\n\t\timg.plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)\n\tvar intery = yend + gradient # First y-intersection for the main loop.\n\n\t# Handle second endpoint.\n\txend = round(x1)\n\tyend = y1 + gradient * (xend - x1)\n\txgap = fpart(x1 + 0.5)\n\tlet xpxl2 = xend.toInt\n\tlet ypxl2 = yend.toInt\n\tif steep:\n\t\timg.plot(ypxl2, xpxl2, rfpart(yend) * xgap)\n\t\timg.plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)\n\telse:\n\t\timg.plot(xpxl2, ypxl2, rfpart(yend) * xgap)\n\t\timg.plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)\n\n\t# Main loop.\n\tif steep:\n\t\tfor x in (xpxl1 + 1)..(xpxl2 - 1):\n\t\t\timg.plot(intery.int, x, rfpart(intery))\n\t\t\timg.plot(intery.int + 1, x, fpart(intery))\n\t\t\tintery += gradient\n\telse:\n\t\tfor x in (xpxl1 + 1)..(xpxl2 - 1):\n\t\t\timg.plot(x, intery.int, rfpart(intery))\n\t\t\timg.plot(x, intery.int + 1, fpart(intery))\n\t\t\tintery += gradient\n\n\nwhen isMainModule:\n\tvar img = initImage[ColorRGBF64](800, 800)\n\timg.fill(BG)\n\tfor x1 in countup(100, 700, 60):\n\t\timg.drawLine(400, 700, x1.toFloat, 100)\n\timg.savePNG(\"xiaoling_wu.png\", compression = 9)\n" + }, + { + "id": 750, + "length": 1564, + "source": "Rosetta Code", + "text": "# Pool of objects.\ntype\n\tBlock[Size: static Positive, T] = ref array[Size, T]\n\tPool[BlockSize: static Positive, T] = ref object\n\t\tblocks: seq[Block[BlockSize, T]] # List of blocks.\n\t\tlastindex: int # Last object index in the last block.\n\n\nproc newPool(S: static Positive; T: typedesc): Pool[S, T] =\n\t## Create a pool with blocks of \"S\" type \"T\" objects.\n\n\tnew(result)\n\tresult.blocks = @[new(Block[S, T])]\n\tresult.lastindex = -1\n\n\nproc getItem(pool: Pool): ptr pool.T =\n\t## Return a pointer on a node from the pool.\n\n\tinc pool.lastindex\n\tif pool.lastindex == pool.BlockSize:\n\t\t# Allocate a new block. It is initialized with zeroes.\n\t\tpool.blocks.add(new(Block[pool.BlockSize, pool.T]))\n\t\tpool.lastindex = 0\n\tresult = cast[ptr pool.T](addr(pool.blocks[^1][pool.lastindex]))\n\ntype\n\tNodePtr = ptr Node\n\tNode = object\n\t\tvalue: int\n\t\tprev: NodePtr\n\t\tnext: NodePtr\n\ntype NodePool = Pool[5000, Node]\n\nproc newNode(pool: NodePool; value: int): NodePtr =\n\t## Create a new node.\n\n\tresult = pool.getItem()\n\tresult.value = value\n\tresult.prev = nil # Not needed, allocated memory being initialized to 0.\n\tresult.next = nil\n\nproc test() =\n\t## Build a circular list of nodes managed in a pool.\n\n\tlet pool = newPool(NodePool.BlockSize, Node)\n\tvar head = pool.newNode(0)\n\tvar prev = head\n\tfor i in 1..11999:\n\t\tlet node = pool.newNode(i)\n\t\tnode.prev = prev\n\t\tprev.next = node\n\t# Display information about the pool state.\n\techo \"Number of allocated blocks: \", pool.blocks.len\n\techo \"Number of nodes in the last block: \", pool.lastindex + 1\n\ntest()\n" + }, + { + "id": 751, + "length": 2417, + "source": "Rosetta Code", + "text": "import tables, sequtils\n\ntype\n\tCodeSymbol = range[0..1]\n\n\tHuffCode = seq[CodeSymbol]\n\n\tNode = ref object\n\t\tf: int\n\t\tparent: Node\n\t\tcase isLeaf: bool\n\t\tof true:\n\t\t\tc: char\n\t\telse:\n\t\t\tchilds: array[CodeSymbol, Node]\n\nfunc `<`(a: Node, b: Node): bool =\n\t# For min operator.\n\ta.f < b.f\n\nfunc `$`(hc: HuffCode): string =\n\tresult = \"\"\n\tfor symbol in hc:\n\t\tresult &= $symbol\n\nfunc freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] =\n\t## Constructs a sequence of nodes which can be adopted\n\t## Optional parent parameter can be set to ensure node will not adopt itself\n\tfor node in tree:\n\t\tif node.parent.isNil and node != parent: result.add(node)\n\nfunc connect(parent: Node, child: Node) =\n\t# Only call this proc when sure that parent has a free child slot\n\tchild.parent = parent\n\tparent.f += child.f\n\tfor i in parent.childs.low..parent.childs.high:\n\t\tif parent.childs[i] == nil:\n\t\t\tparent.childs[i] = child\n\t\t\treturn\n\nfunc generateCodes(codes: TableRef[char, HuffCode],\n\t\t\t\t\t\t\t\t\t currentNode: Node, currentCode: HuffCode = @[]) =\n\tif currentNode.isLeaf:\n\t\tlet key = currentNode.c\n\t\tcodes[key] = currentCode\n\t\treturn\n\n\tfor i in currentNode.childs.low..currentNode.childs.high:\n\t\tif not currentNode.childs[i].isNil:\n\t\t\tlet newCode = currentCode & i\n\t\t\tgenerateCodes(codes, currentNode.childs[i], newCode)\n\n\nfunc buildTree(frequencies: CountTable[char]): seq[Node] =\n\tresult = newSeq[Node](frequencies.len)\n\tfor i in result.low..result.high:\n\t\tlet key = toSeq(frequencies.keys)[i]\n\t\tresult[i] = Node(f: frequencies[key], isLeaf: true, c: key)\n\n\twhile result.freeChildList.len > 1:\n\t\tlet currentNode = new Node\n\t\tresult.add(currentNode)\n\t\tfor c in currentNode.childs:\n\t\t\tcurrentNode.connect(min(result.freeChildList(currentNode)))\n\t\t\tif result.freeChildList.len <= 1: break\n\nwhen isMainModule:\n\timport algorithm, strformat\n\n\tconst\n\t\tSampleString = \"this is an example for huffman encoding\"\n\t\tSampleFrequencies = SampleString.toCountTable()\n\n\tfunc `<`(code1, code2: HuffCode): bool =\n\t\t# Used to sort the result.\n\t\tif code1.len == code2.len:\n\t\t\tresult = false\n\t\t\tfor (c1, c2) in zip(code1, code2):\n\t\t\t\tif c1 != c2: return c1 < c2\n\t\telse:\n\t\t\tresult = code1.len < code2.len\n\n\tlet\n\t\ttree = buildTree(SampleFrequencies)\n\t\troot = tree.freeChildList[0]\n\n\tvar huffCodes = newTable[char, HuffCode]()\n\tgenerateCodes(huffCodes, root)\n\n\tfor (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]):\n\t\techo \"'{key}' -> {value}\"\n" + }, + { + "id": 752, + "length": 627, + "source": "Rosetta Code", + "text": "import complex\n\nproc inMandelbrotSet(c: Complex, maxEscapeIterations = 50): bool =\n\tresult = true; var z: Complex\n\tfor i in 0..maxEscapeIterations:\n\t\tz = z * z + c\n\t\tif abs2(z) > 4: return false\n\niterator steps(start, step: float, numPixels: int): float =\n\tfor i in 0..numPixels:\n\t\tyield start + i.float * step\n\nproc mandelbrotImage(yStart, yStep, xStart, xStep: float, height, width: int): string =\n\tfor y in steps(yStart, yStep, height):\n\t\tfor x in steps(xStart, xStep, width):\n\t\t\tresult.add(if complex(x, y).inMandelbrotSet: '*'\n\t\t\t\t\t\t\t\t else: ' ')\n\t\tresult.add('\\n')\n\necho mandelbrotImage(1.0, -0.05, -2.0, 0.0315, 40, 80)\n" + }, + { + "id": 753, + "length": 886, + "source": "Rosetta Code", + "text": "import math, complex, lenientops\nimport imageman\n\nconst\n\tW = 800\n\tH = 600\n\tZoom = 0.5\n\tMoveX = -0.5\n\tMoveY = 0.0\n\tMaxIter = 30\n\nfunc hsvToRgb(h, s, v: float): array[3, float] =\n\tlet c = v * s\n\tlet x = c * (1 - abs(((h / 60) mod 2) - 1))\n\tlet m = v - c\n\tlet (r, g, b) = if h < 60: (c, x, 0.0)\n\t\t\t\t\t\t\t\t\telif h < 120: (x, c, 0.0)\n\t\t\t\t\t\t\t\t\telif h < 180: (0.0, c, x)\n\t\t\t\t\t\t\t\t\telif h < 240: (0.0, x, c)\n\t\t\t\t\t\t\t\t\telif x < 300: (x, 0.0, c)\n\t\t\t\t\t\t\t\t\telse: (c, 0.0, x)\n\tresult = [r + m, g + m, b + m]\n\n\nvar img = initImage[ColorRGBF64](W, H)\nfor x in 1..W:\n\tfor y in 1..H:\n\t\tvar i = MaxIter - 1\n\t\tlet c = complex((2 * x - W) / (W * Zoom) + MoveX, (2 * y - H) / (H * Zoom) + MoveY)\n\t\tvar z = c\n\t\twhile abs(z) < 2 and i > 0:\n\t\t\tz = z * z + c\n\t\t\tdec i\n\t\tlet color = hsvToRgb(i / MaxIter * 360, 1, i / MaxIter)\n\t\timg[x - 1, y - 1] = ColorRGBF64(color)\n\nimg.savePNG(\"mandelbrot.png\", compression = 9)\n" + }, + { + "id": 754, + "length": 1143, + "source": "Rosetta Code", + "text": "proc isPrime*(n: uint32): bool =\n\t# bases of 2, 7, 61 are sufficient to cover 2^32\n\tcase n\n\tof 0, 1: return false\n\tof 2, 7, 61: return true\n\telse: discard\n\n\tvar\n\t\tnm1 = n-1\n\t\td = nm1.int\n\t\ts = 0\n\t\tn = n.uint64\n\n\twhile d mod 2 == 0:\n\t\td = d shr 1\n\t\ts += 1\n\n\tfor a in [2, 7, 61]:\n\t\tvar\n\t\t\tx = 1.uint64\n\t\t\tp = a.uint64\n\t\t\tdr = d\n\n\t\twhile dr > 0:\n\t\t\tif dr mod 2 == 1:\n\t\t\t\tx = x * p mod n\n\t\t\tp = p * p mod n\n\t\t\tdr = dr shr 1\n\n\t\tif x == 1 or x.uint32 == nm1:\n\t\t\tcontinue\n\n\t\tvar r = 1\n\t\twhile true:\n\t\t\tif r >= s:\n\t\t\t\treturn false\n\t\t\tx = x * x mod n\n\t\t\tif x == 1:\n\t\t\t\treturn false\n\t\t\tif x.uint32 == nm1:\n\t\t\t\tbreak\n\t\t\tr += 1\n\n\treturn true\n\nproc isPrime*(n: int32): bool =\n\t## Overload for int32\n\tn >= 0 and n.uint32.isPrime\n\nwhen isMainModule:\n\tconst primeNumber1000 = 7919 # source: https://en.wikipedia.org/wiki/List_of_prime_numbers\n\tvar\n\t\ti = 0u32\n\t\tnumberPrimes = 0\n\twhile true:\n\t\tif isPrime(i):\n\t\t\tif numberPrimes == 999:\n\t\t\t\tbreak\n\t\t\tnumberPrimes += 1\n\t\ti += 1\n\n\tassert i == primeNumber1000\n\tassert isPrime(2u32)\n\tassert isPrime(31u32)\n\tassert isPrime(37u32)\n\tassert isPrime(1123u32)\n\tassert isPrime(492366587u32)\n\tassert isPrime(1645333507u32)\n" + }, + { + "id": 755, + "length": 1659, + "source": "Rosetta Code", + "text": "import httpclient, strutils, htmlparser, xmltree, strtabs\nconst\n\tPageSize = 7\n\tYahooURLPattern = \"https://search.yahoo.com/search?fr=opensearch&b=$$#&pz=$#&p=\".format(PageSize)\ntype\n\tSearchResult = ref object\n\t\turl, title, content: string\n\tSearchInterface = ref object\n\t\tclient: HttpClient\n\t\turlPattern: string\n\t\tpage: int\n\t\tresults: array[PageSize+2, SearchResult]\nproc newSearchInterface(question: string): SearchInterface =\n\tnew result\n\tresult.client = newHttpClient()\n# result.client = newHttpClient(proxy = newProxy(\n# \"http://localhost:40001\")) # only http_proxy supported\n\tresult.urlPattern = YahooURLPattern&question\nproc search(si: SearchInterface) =\n\tlet html = parseHtml(si.client.getContent(si.urlPattern.format(\n\t\t\tsi.page*PageSize+1)))\n\tvar\n\t\ti: int\n\t\tattrs: XmlAttributes\n\tfor d in html.findAll(\"div\"):\n\t\tattrs = d.attrs\n\t\tif attrs != nil and attrs.getOrDefault(\"class\").startsWith(\"dd algo algo-sr relsrch\"):\n\t\t\tlet d_inner = d.child(\"div\")\n\t\t\tfor a in d_inner.findAll(\"a\"):\n\t\t\t\tattrs = a.attrs\n\t\t\t\tif attrs != nil and attrs.getOrDefault(\"class\") == \" ac-algo fz-l ac-21th lh-24\":\n\t\t\t\t\tsi.results[i] = SearchResult(url: attrs[\"href\"], title: a.innerText,\n\t\t\t\t\t\t\tcontent: d.findAll(\"p\")[0].innerText)\n\t\t\t\t\ti+=1\n\t\t\t\t\tbreak\n\twhile i < len(si.results) and si.results[i] != nil:\n\t\tsi.results[i] = nil\n\t\ti+=1\nproc nextPage(si: SearchInterface) =\n\tsi.page+=1\n\tsi.search()\n\nproc echoResult(si: SearchInterface) =\n\tfor res in si.results:\n\t\tif res == nil:\n\t\t\tbreak\n\t\techo(res[])\n\nvar searchInf = newSearchInterface(\"weather\")\nsearchInf.search()\nsearchInf.echoResult()\necho(\"searching for next page...\")\nsearchInf.nextPage()\nsearchInf.echoResult()\n" + }, + { + "id": 756, + "length": 1190, + "source": "Rosetta Code", + "text": "import random, strutils, strformat, sequtils\nrandomize()\n\nconst\n\tDigits = \"123456789\"\n\tDigitSet = {Digits[0]..Digits[^1]}\n\tSize = 4\n\nproc sample(s: string; n: Positive): string =\n\t## Return a random sample of \"n\" characters extracted from string \"s\".\n\tvar s = s\n\ts.shuffle()\n\tresult = s[0.. 1: \"s\" else: \"\"\n\nlet chosen = Digits.sample(Size)\n\necho \"I have chosen a number from {Size} unique digits from 1 to 9 arranged in a random order.\"\necho \"You need to input a {Size} digit, unique digit number as a guess at what I have chosen.\"\n\nvar guesses = 0\nwhile true:\n\tinc guesses\n\tvar guess = \"\"\n\twhile true:\n\t\tstdout.write(\"\\nNext guess {guesses}: \")\n\t\tguess = stdin.readLine().strip()\n\t\tif guess.len == Size and allCharsInSet(guess, DigitSet) and guess.deduplicate.len == Size:\n\t\t\tbreak\n\t\techo \"Problem, try again. You need to enter {Size} unique digits from 1 to 9.\"\n\tif guess == chosen:\n\t\techo \"\\nCongratulations! You guessed correctly in {guesses} attempts.\"\n\t\tbreak\n\tvar bulls, cows = 0\n\tfor i in 0..= 2, \"At least two points required.\")\n\n\tresult.minDist = Inf\n\tfor i in 0..= 2, \"At least two points required.\")\n\n\tresult = closestPair(xP, yP)\n\n\nimport random, times, strformat\n\nrandomize()\n\nconst N = 50_000\nconst Max = 10_000.0\nvar points: array[N, Point]\nfor pt in points.mitems: pt = (rand(Max), rand(Max))\n\necho \"Sample contains \", N, \" random points.\"\necho \"\"\n\nlet t0 = getTime()\necho \"Brute force algorithm:\"\necho points.bruteForceClosestPair()\nlet t1 = getTime()\necho \"Optimized algorithm:\"\necho points.closestPair()\nlet t2 = getTime()\n\necho \"\"\necho fmt\"Execution time for brute force algorithm: {(t1 - t0).inMilliseconds:>4} ms\"\necho fmt\"Execution time for optimized algorithm: {(t2 - t1).inMilliseconds:>4} ms\"\n" + }, + { + "id": 758, + "length": 2748, + "source": "Rosetta Code", + "text": "import locks, math, os, random\n\nconst N = 10\nconst MaxInit = 99\n\nvar buckets: array[1..N, Natural]\nvar bucketLocks: array[1..N, Lock]\nvar randomLock: Lock\nvar terminate: array[3, Channel[bool]]\n\n\nproc getTwoIndexes(): tuple[a, b: int] =\n\t## Get two indexes from the random number generator.\n\n\tresult.a = rand(1..N)\n\tresult.b = rand(2..N)\n\tif result.b == result.a: result.b = 1\n\n\nproc equalize(num: int) {.thread.} =\n\t## Try to equalize two buckets.\n\n\tvar b1, b2: int\n\twhile true:\n\n\t\t# Select the two buckets to \"equalize\".\n\t\twithLock randomLock:\n\t\t (b1, b2) = getTwoIndexes()\n\t\tif b1 > b2: swap b1, b2 # We want \"b1 < b2\" to avoid deadlocks.\n\n\t\t# Perform equalization.\n\t\twithLock bucketLocks[b1]:\n\t\t\twithLock bucketLocks[b2]:\n\t\t\t\tlet target = (buckets[b1] + buckets[b2]) div 2\n\t\t\t\tlet delta = target - buckets[b1]\n\t\t\t\tinc buckets[b1], delta\n\t\t\t\tdec buckets[b2], delta\n\n\t\t# Check termination.\n\t\tlet (available, stop) = tryRecv terminate[num]\n\t\tif available and stop: break\n\n\nproc distribute(num: int) {.thread.} =\n\t## Redistribute contents of two buckets.\n\n\tvar b1, b2: int\n\tvar factor: float\n\twhile true:\n\t\t# Select the two buckets for redistribution and the redistribution factor.\n\t\twithLock randomLock:\n\t\t\t(b1, b2) = getTwoIndexes()\n\t\t\tfactor = rand(0.0..1.0)\n\t\tif b1 > b2: swap b1, b2 # We want \"b1 < b2\" to avoid deadlocks..\n\n\t\t# Perform redistribution.\n\t\twithLock bucketLocks[b1]:\n\t\t\twithLock bucketLocks[b2]:\n\t\t\t\tlet sum = buckets[b1] + buckets[b2]\n\t\t\t\tlet value = (sum.toFloat * factor).toInt\n\t\t\t\tbuckets[b1] = value\n\t\t\t\tbuckets[b2] = sum - value\n\n\t\t# Check termination.\n\t\tlet (available, stop) = tryRecv terminate[num]\n\t\tif available and stop: break\n\n\nproc display(num: int) {.thread.} =\n\t## Display the content of buckets and the sum (which should be constant).\n\n\twhile true:\n\t\tfor i in 1..N: acquire bucketLocks[i]\n\t\techo buckets, \" Total = \", sum(buckets)\n\t\tfor i in countdown(N, 1): release bucketLocks[i]\n\t\tos.sleep(1000)\n\n\t\t# Check termination.\n\t\tlet (available, stop) = tryRecv terminate[num]\n\t\tif available and stop: break\n\n\nrandomize()\n\n# Initialize the buckets with a random value.\nfor bucket in buckets.mitems:\n\tbucket = rand(1..MaxInit)\n\n# Initialize the locks.\nrandomLock.initLock()\nfor lock in bucketLocks.mitems:\n\tlock.initLock()\n\n# Open the channels.\nfor c in terminate.mitems:\n\tc.open()\n\n# Create and launch the threads.\nvar tequal, tdist, tdisp: Thread[int]\ntequal.createThread(equalize, 0)\ntdist.createThread(distribute, 1)\ntdisp.createThread(display, 2)\n\nsleep(10000)\n\n# Ask the threads to stop.\nfor c in terminate.mitems:\n\tc.send(true)\n\njoinThreads([tequal, tdist, tdisp])\n\n# Free resources.\nrandomLock.deinitLock()\nfor lock in bucketLocks.mitems:\n\tlock.deinitLock()\nfor c in terminate.mitems:\n\tc.close()\n" + }, + { + "id": 759, + "length": 766, + "source": "Rosetta Code", + "text": "import algorithm, strutils, sugar\n\nproc printTable(a: seq[seq[string]]) =\n\tfor row in a:\n\t\tfor x in row: stdout.write x, repeat(' ', 4 - x.len)\n\t\techo \"\"\n\techo \"\"\n\nproc sortTable(a: seq[seq[string]], column = 0, reverse = false,\n\t\tordering: (proc(a,b: string): int) = system.cmp) : seq[seq[string]] =\n\tlet order = if reverse: Descending else: Ascending\n\tresult = a\n\tresult.sort(proc(x,y:seq[string]):int = ordering(x[column],y[column]), order)\n\nconst data = @[@[\"a\", \"b\", \"c\"], @[\"\", \"q\", \"z\"], @[\"zap\", \"zip\", \"Zot\"]]\n\nprintTable data\nprintTable sortTable(data)\nprintTable sortTable(data, column = 2)\nprintTable sortTable(data, column = 1)\nprintTable sortTable(data, column = 1, reverse = true)\nprintTable sortTable(data, ordering = (a,b) => cmp[int](b.len,a.len))\n" + }, + { + "id": 760, + "length": 574, + "source": "Rosetta Code", + "text": "# Allocate thread local heap memory\nvar a = alloc(1000)\ndealloc(a)\n\n# Allocate memory block on shared heap\nvar b = allocShared(1000)\ndeallocShared(b)\n\n# Allocate and dellocate a single int on the thread local heap\nvar p = create(int, sizeof(int)) # allocate memory\necho p[] # 0\np[] = 123 # assign a value\necho p[] # 123\ndiscard resize(p, 0) # deallocate it\n# p is now invalid. Let's set it to nil\np = nil # set pointer to nil\necho isNil(p) # true\n" + }, + { + "id": 761, + "length": 1628, + "source": "Rosetta Code", + "text": "import tables\n\nimport gintro/[glib, gobject, gio]\nimport gintro/gtk except Table\nimport gintro/gdk except Window\n\ntype\n\tMacroProc = proc(app: App)\n\tMacroTable = Table[int, MacroProc] # Mapping key values -> procedures.\n\n\tApp = ref object of Application\n\t\tdispatchTable: MacroTable\n\t\tlabel: Label\n\n\nproc addMacro(app: App; ch: char; macroProc: MacroProc) =\n\t## Assign a procedure to a key.\n\t## If the key is already assigned, nothing is done.\n\tlet keyval = ord(ch)\n\tif keyval notin app.dispatchTable:\n\t\tapp.dispatchTable[keyval] = macroProc\n\n# Macro procedures.\n\nproc proc1(app: App) =\n\tapp.label.setText(\"You called macro 1\")\n\nproc proc2(app: App) =\n\tapp.label.setText(\"You called macro 2\")\n\nproc proc3(app: App) =\n\tapp.label.setText(\"You called macro 3\")\n\n\nproc onKeyPress(window: ApplicationWindow; event: Event; app: App): bool =\n\tvar keyval: int\n\tif not event.getKeyval(keyval): return false\n\tif keyval in app.dispatchTable:\n\t\tapp.dispatchTable[keyval](app)\n\tresult = true\n\n\nproc activate(app: App) =\n\t## Activate the application.\n\n\tapp.addMacro('1', proc1)\n\tapp.addMacro('2', proc2)\n\tapp.addMacro('3', proc3)\n\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"Keyboard macros\")\n\n\tlet hbox = newBox(Orientation.horizontal, 10)\n\twindow.add(hbox)\n\tlet vbox = newBox(Orientation.vertical, 10)\n\thbox.packStart(vbox, true, true, 10)\n\n\tapp.label = newLabel()\n\tapp.label.setWidthChars(18)\n\tvbox.packStart(app.label, true, true, 5)\n\n\tdiscard window.connect(\"key-press-event\", onKeyPress, app)\n\n\twindow.showAll()\n\n\nlet app = newApplication(App, \"KeyboardMacros\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 762, + "length": 2095, + "source": "Rosetta Code", + "text": "import os\nimport gintro/[glib, gobject, gtk, gio]\nfrom gintro/gdk import processAllUpdates\n\ntype MyWindow = ref object of ApplicationWindow\n\tisShifted: bool\n\n\nproc wMaximize(button: Button; window: MyWindow) =\n\twindow.maximize()\n\nproc wUnmaximize(button: Button; window: MyWindow) =\n\twindow.unmaximize()\n\nproc wIconify(button: Button; window: MyWindow) =\n\twindow.iconify()\n\nproc wDeiconify(button: Button; window: MyWindow) =\n\twindow.deiconify()\n\nproc wHide(button: Button; window: MyWindow) =\n\twindow.hide()\n\tprocessAllUpdates()\n\tos.sleep(2000)\n\twindow.show()\n\nproc wShow(button: Button; window: MyWindow) =\n\twindow.show()\n\nproc wMove(button: Button; window: MyWindow) =\n\tvar x, y: int\n\twindow.getPosition(x, y)\n\tif window.isShifted:\n\t\twindow.move(x - 10, y - 10)\n\telse:\n\t\twindow.move(x + 10, y + 10)\n\twindow.isShifted = not window.isShifted\n\nproc wQuit(button: Button; window: MyWindow) =\n\twindow.destroy()\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = newApplicationWindow(MyWindow, app)\n\twindow.setTitle(\"Window management\")\n\n\tlet stackBox = newBox(Orientation.vertical, 10)\n\tstackBox.setHomogeneous(true)\n\n\tlet\n\t\tbMax = newButton(\"maximize\")\n\t\tbUnmax = newButton(\"unmaximize\")\n\t\tbIcon = newButton(\"iconize\")\n\t\tbDeicon = newButton(\"deiconize\")\n\t\tbHide = newButton(\"hide\")\n\t\tbShow = newButton(\"show\")\n\t\tbMove = newButton(\"move\")\n\t\tbQuit = newButton(\"Quit\")\n\n\tfor button in [bMax, bUnmax, bIcon, bDeicon, bHide, bShow, bMove, bQuit]:\n\t\tstackBox.add button\n\n\twindow.setBorderWidth(5)\n\twindow.add(stackBox)\n\n\tdiscard bMax.connect(\"clicked\", wMaximize, window)\n\tdiscard bUnmax.connect(\"clicked\", wUnmaximize, window)\n\tdiscard bIcon.connect(\"clicked\", wIconify, window)\n\tdiscard bDeicon.connect(\"clicked\", wDeiconify, window)\n\tdiscard bHide.connect(\"clicked\", wHide, window)\n\tdiscard bShow.connect(\"clicked\", wShow, window)\n\tdiscard bMove.connect(\"clicked\", wMove, window)\n\tdiscard bQuit.connect(\"clicked\", wQuit, window)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Window.Management\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 763, + "length": 2003, + "source": "Rosetta Code", + "text": "when defined(windows):\n\timport winlean\nelse:\n\t{.error: \"not supported os\".}\n\ntype\n\tInputType = enum\n\t\titMouse itKeyboard itHardware\n\tKeyEvent = enum\n\t\tkeExtendedKey = 0x0001\n\t\tkeKeyUp = 0x0002\n\t\tkeUnicode = 0x0004\n\t\tkeScanCode = 0x0008\n\n\n\tMouseInput {.importc: \"MOUSEINPUT\".} = object\n\t\tdx, dy: clong\n\t\tmouseData, dwFlags, time: culong\n\t\tdwExtraInfo: int # ULONG_PTR\n\n\tKeybdInput {.importc: \"KEYBDINPUT\".} = object\n\t\twVk, wScan: cint\n\t\tdwFlags, time: culong\n\t\tdwExtraInfo: int\n\n\tHardwareInput {.importc: \"HARDWAREINPUT\".} = object\n\t\tuMsg: clong\n\t\twParamL, wParamH: cint\n\n\tInputUnion {.union.} = object\n\t\thi: HardwareInput\n\t\tmi: MouseInput\n\t\tki: KeybdInput\n\tInput = object\n\t\t`type`: clong\n\t\thwin: InputUnion\n\nproc sendInput(total: cint, inp: ptr Input, size: cint) {.importc: \"SendInput\", header: \"\".}\n\nproc initKey(keycode: int): Input =\n\tresult = Input(`type`: itKeyboard.clong)\n\tvar keybd = KeybdInput(wVk: keycode.cint, wScan: 0, time: 0,\n\t\tdwExtraInfo: 0, dwFlags: 0)\n\tresult.hwin = InputUnion(ki: keybd)\n\nproc pressKey(input: var Input) =\n\tinput.hwin.ki.dwFlags = keExtendedKey.culong\n\tsendInput(cint 1, addr input, sizeof(Input).cint)\n\nproc releaseKey(input: var Input) =\n\tinput.hwin.ki.dwFlags = keExtendedKey.culong or keKeyUp.culong\n\tsendInput(cint 1, addr input, sizeof(Input).cint)\n\nproc pressRelease(input: var Input) =\n\tinput.pressKey\n\tinput.releaseKey\n\nproc pressReleaseKeycode(input: var Input, code: int) =\n\tinput.hwin.ki.wVk = code.cint\n\tinput.pressRelease\n\nproc main =\n\tvar\n\t\tshift = initKey 0xa0 # VK_LSHIFT\n\t\tkey = initKey 0x48\n\n\tpressKey shift\n\tpressRelease key\n\treleaseKey shift\n\tkey.pressReleaseKeycode 0x45 # e key\n\tkey.pressReleaseKeycode 0x4c # l key\n\tkey.pressReleaseKeycode 0x4c # l key\n\tkey.pressReleaseKeycode 0x4f # o key\n\tkey.pressReleaseKeycode 0x20 # VK_SPACE\n\tkey.pressReleaseKeycode 0x57 # w key\n\tkey.pressReleaseKeycode 0x4f # o key\n\tkey.pressReleaseKeycode 0x52 # r key\n\tkey.pressReleaseKeycode 0x4c # l key\n\tkey.pressReleaseKeycode 0x44 # d key\n\nmain()\n" + }, + { + "id": 764, + "length": 609, + "source": "Rosetta Code", + "text": "import strutils, rdstdin\n\nproc menu(xs: openArray[string]) =\n\tfor i, x in xs: echo \" \", i, \") \", x\n\nproc ok(reply: string; count: Positive): bool =\n\ttry:\n\t\tlet n = parseInt(reply)\n\t\treturn 0 <= n and n < count\n\texcept: return false\n\nproc selector(xs: openArray[string]; prompt: string): string =\n\tif xs.len == 0: return \"\"\n\tvar reply = \"-1\"\n\twhile not ok(reply, xs.len):\n\t\tmenu(xs)\n\t\treply = readLineFromStdin(prompt).strip()\n\treturn xs[parseInt(reply)]\n\nconst xs = [\"fee fie\", \"huff and puff\", \"mirror mirror\", \"tick tock\"]\nlet item = selector(xs, \"Which is from the three pigs: \")\necho \"You chose: \", item\n" + }, + { + "id": 765, + "length": 1572, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gdk, gtk, gio]\n\ntype\n\n\t# Scrolling direction.\n\tScrollDirection = enum toLeft, toRight\n\n\t# Data transmitted to update callback.\n\tUpdateData = ref object\n\t\tlabel: Label\n\t\tscrollDir: ScrollDirection\n\n\nproc update(data: UpdateData): gboolean =\n\t## Update the text, scrolling to the right or to the left according to \"data.scrollDir\".\n\n\tdata.label.setText(if data.scrollDir == toRight: data.label.text[^1] & data.label.text[0..^2]\n\t\t\t\t\t\t\t\t\t\t else: data.label.text[1..^1] & data.label.text[0])\n\tresult = gboolean(1)\n\n\nproc changeScrollingDir(evtBox: EventBox; event: EventButton; data: UpdateData): bool =\n\t## Change scrolling direction.\n\n\tdata.scrollDir = ScrollDirection(1 - ord(data.scrollDir))\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(150, 50)\n\twindow.setTitle(\"Animation\")\n\n\t# Create an event box to catch the button press event.\n\tlet evtBox = newEventBox()\n\twindow.add(evtBox)\n\n\t# Create the label and add it to the event box.\n\tlet label = newLabel(\"Hello World! \")\n\tevtBox.add(label)\n\n\t# Create the update data.\n\tlet data = UpdateData(label: label, scrollDir: toRight)\n\n\t# Connect the \"button-press-event\" to the callback to change scrolling direction.\n\tdiscard evtBox.connect(\"button-press-event\", changeScrollingDir, data)\n\n\t# Create a timer to update the label and simulate scrolling.\n\ttimeoutAdd(200, update, data)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Animation\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 766, + "length": 647, + "source": "Rosetta Code", + "text": "import smtp\n\nproc sendMail(fromAddr: string; toAddrs, ccAddrs: seq[string];\n\t\t\t\t\t\t\tsubject, message, login, password: string;\n\t\t\t\t\t\t\tserver = \"smtp.gmail.com\"; port = Port 465; ssl = true) =\n\tlet msg = createMessage(subject, message, toAddrs, ccAddrs)\n\tlet session = newSmtp(useSsl = ssl, debug = true)\n\tsession.connect(server, port)\n\tsession.auth(login, password)\n\tsession.sendMail(fromAddr, toAddrs, $msg)\n\nsendMail(fromAddr = \"nim@gmail.com\",\n\t\t\t\t toAddrs = @[\"someone@example.com\"],\n\t\t\t\t ccAddrs = @[],\n\t\t\t\t subject = \"Hi from Nim\",\n\t\t\t\t message = \"Nim says hi!\\nAnd bye again!\",\n\t\t\t\t login = \"nim@gmail.com\",\n\t\t\t\t password = \"XXXXXX\")\n" + }, + { + "id": 767, + "length": 2546, + "source": "Rosetta Code", + "text": "import sequtils, strutils, sets, tables, sugar\n\ntype StringSet = HashSet[string]\n\n\nproc topSort(data: var OrderedTable[string, StringSet]) =\n\t## Topologically sort the data in place.\n\n\tvar ranks: Table[string, Natural] # Maps the keys to a rank.\n\n\t# Remove self dependencies.\n\tfor key, values in data.mpairs:\n\t\tvalues.excl key\n\n\t# Add extra items (i.e items present in values but not in keys).\n\tfor values in toSeq(data.values):\n\t\tfor value in values:\n\t\t\tif value notin data:\n\t\t\t\tdata[value] = initHashSet[string]()\n\n\t# Find ranks.\n\tvar deps = data # Working copy of the table.\n\tvar rank = 0\n\twhile deps.len > 0:\n\n\t\t# Find a key with an empty dependency set.\n\t\tvar keyToRemove: string\n\t\tfor key, values in deps.pairs:\n\t\t\tif values.card == 0:\n\t\t\t\tkeyToRemove = key\n\t\t\t\tbreak\n\t\tif keyToRemove.len == 0:\n\t\t\t# Not found: there is a cycle.\n\t\t\traise newException(ValueError, \"Unorderable items found: \" & toSeq(deps.keys).join(\", \"))\n\n\t\t# Assign a rank to the key and remove it from keys and values.\n\t\tranks[keyToRemove] = rank\n\t\tinc rank\n\t\tdeps.del keyToRemove\n\t\tfor k, v in deps.mpairs:\n\t\t\tv.excl keyToRemove\n\n\t# Sort the original data according to the ranks.\n\tdata.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))\n\n\nwhen isMainModule:\n\n\tconst Data = {\"des_system_lib\": [\"std\", \"synopsys\", \"std_cell_lib\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"des_system_lib\", \"dw02\", \"dw01\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"ramlib\", \"ieee\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw01\": [\"ieee\", \"dw01\", \"dware\", \"gtech\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw02\": [\"ieee\", \"dw02\", \"dware\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw03\": [\"std\", \"synopsys\", \"dware\", \"dw03\",\n\t\t\t\t\t\t\t\t\t\t\t\t \"dw02\", \"dw01\", \"ieee\", \"gtech\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw04\": [\"dw04\", \"ieee\", \"dw01\", \"dware\", \"gtech\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw05\": [\"dw05\", \"ieee\", \"dware\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw06\": [\"dw06\", \"ieee\", \"dware\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dw07\": [\"ieee\", \"dware\"].toHashSet,\n\t\t\t\t\t\t\t\t\"dware\": [\"ieee\", \"dware\"].toHashSet,\n\t\t\t\t\t\t\t\t\"gtech\": [\"ieee\", \"gtech\"].toHashSet,\n\t\t\t\t\t\t\t\t\"ramlib\": [\"std\", \"ieee\"].toHashSet,\n\t\t\t\t\t\t\t\t\"std_cell_lib\": [\"ieee\", \"std_cell_lib\"].toHashSet,\n\t\t\t\t\t\t\t\t\"synopsys\": initHashSet[string]()}.toOrderedTable\n\n\t# Process the original data (without cycle).\n\techo \"Data without cycle. Order after sorting:\"\n\tvar data = Data\n\ttry:\n\t\tdata.topSort()\n\t\tfor key in data.keys: echo key\n\texcept ValueError:\n\t\techo getCurrentExceptionMsg()\n\n\t# Process the modified data (with a cycle).\n\techo \"\\nData with a cycle:\"\n\tdata = Data\n\tdata[\"dw01\"].incl \"dw04\"\n\ttry:\n\t\tdata.topSort()\n\t\tfor key in data.keys: echo key\n\texcept ValueError:\n\t\techo getCurrentExceptionMsg()\n" + }, + { + "id": 768, + "length": 823, + "source": "Rosetta Code", + "text": "var x: int = 3 # Declaration with type specification and initialization.\n\nvar y = 3 # Declaration with type inferred to \"int\".\n\nvar z: int # Variable is initialized to 0.\n\nlet a = 13 # Immutable variable.\n\n# Using a var block to initialize.\nvar\n\tb, c: int = 10 # Two variables initialized to 10\n\ts* = \"foobar\" # This one is exported.\n\ntype Obj = ref object\n\ti: int\n\ts: string\n\nvar obj = Obj(i: 3, s: \"abc\") # Initialization with an implicit allocation by \"new\".\necho obj.a, \" \", obj.s # Equivalent to obj[].a and obj[].s.\n\nproc p =\n\tvar xloc = 3\n\techo x # Referencing a global variable.\n\n\tproc q =\n\t\techo xloc # Referencing a variable in the enclosing scope.\n" + }, + { + "id": 769, + "length": 2160, + "source": "Rosetta Code", + "text": "import strutils\nimport gintro/[glib, gobject, gtk, gio]\n\ntype MainWindow = ref object of ApplicationWindow\n\tstrEntry: Entry\n\tintEntry: SpinButton\n\n\nproc displayValues(strval: string; intval: int) =\n\t## Display a dialog window with the values entered by the user.\n\n\tlet dialog = newDialog()\n\tdialog.setModal(true)\n\tlet label1 = newLabel(\" String value is $1.\".format(strval))\n\tlabel1.setHalign(Align.start)\n\tdialog.contentArea.packStart(label1, true, true, 5)\n\tlet msg = \" Integer value is $1 which is \".format(intval) &\n\t\t\t\t\t\t(if intval == 75000: \"right. \" else: \"wrong (expected 75000). \")\n\tlet label2 = newLabel(msg)\n\tdialog.contentArea.packStart(label2, true, true, 5)\n\tdiscard dialog.addButton(\"OK\", ord(ResponseType.ok))\n\tdialog.showAll()\n\tdiscard dialog.run()\n\tdialog.destroy()\n\n\nproc onOk(button: Button; window: MainWindow) =\n\t## Callback executed when the OK button has been clicked.\n\tlet strval = window.strEntry.text()\n\tlet intval = window.intEntry.value().toInt\n\tdisplayValues(strval, intval)\n\tif intval == 75_000:\n\t\twindow.destroy()\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = newApplicationWindow(MainWindow, app)\n\twindow.setTitle(\"User input\")\n\n\tlet content = newBox(Orientation.vertical, 10)\n\tcontent.setHomogeneous(true)\n\tlet grid = newGrid()\n\tgrid.setColumnSpacing(30)\n\tlet bbox = newButtonBox(Orientation.horizontal)\n\tbbox.setLayout(ButtonBoxStyle.spread)\n\n\tlet strLabel = newLabel(\"Enter some text\")\n\tstrLabel.setHalign(Align.start)\n\twindow.strEntry = newEntry()\n\tgrid.attach(strLabel, 0, 0, 1, 1)\n\tgrid.attach(window.strEntry, 1, 0, 1, 1)\n\n\tlet intLabel = newLabel(\"Enter 75000\")\n\tintLabel.setHalign(Align.start)\n\twindow.intEntry = newSpinButtonWithRange(0, 80_000, 1)\n\tgrid.attach(intLabel, 0, 1, 1, 1)\n\tgrid.attach(window.intEntry, 1, 1, 1, 1)\n\n\tlet btnOk = newButton(\"OK\")\n\n\tbbox.add(btnOk)\n\n\tcontent.packStart(grid, true, true, 0)\n\tcontent.packEnd(bbox, true, true, 0)\n\n\twindow.setBorderWidth(5)\n\twindow.add(content)\n\n\tdiscard btnOk.connect(\"clicked\", onOk, window)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"UserInput\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 770, + "length": 1051, + "source": "Rosetta Code", + "text": "import deques\n\ntype\n\tNode[T] = ref object\n\t\tdata: T\n\t\tleft, right: Node[T]\n\nproc newNode[T](data: T; left, right: Node[T] = nil): Node[T] =\n\tNode[T](data: data, left: left, right: right)\n\nproc preorder[T](n: Node[T]): seq[T] =\n\tif n.isNil: @[]\n\telse: @[n.data] & preorder(n.left) & preorder(n.right)\n\nproc inorder[T](n: Node[T]): seq[T] =\n\tif n.isNil: @[]\n\telse: inorder(n.left) & @[n.data] & inorder(n.right)\n\nproc postorder[T](n: Node[T]): seq[T] =\n\tif n.isNil: @[]\n\telse: postorder(n.left) & postorder(n.right) & @[n.data]\n\nproc levelorder[T](n: Node[T]): seq[T] =\n\tvar queue: Deque[Node[T]]\n\tqueue.addLast(n)\n\twhile queue.len > 0:\n\t\tlet next = queue.popFirst()\n\t\tresult.add next.data\n\t\tif not next.left.isNil: queue.addLast(next.left)\n\t\tif not next.right.isNil: queue.addLast(next.right)\n\nlet tree = 1.newNode(\n\t\t\t\t\t\t 2.newNode(\n\t\t\t\t\t\t\t 4.newNode(\n\t\t\t\t\t\t\t\t 7.newNode),\n\t\t\t\t\t\t\t 5.newNode),\n\t\t\t\t\t\t 3.newNode(\n\t\t\t\t\t\t\t 6.newNode(\n\t\t\t\t\t\t\t\t 8.newNode,\n\t\t\t\t\t\t\t\t 9.newNode)))\n\necho preorder tree\necho inorder tree\necho postorder tree\necho levelorder tree\n" + }, + { + "id": 771, + "length": 570, + "source": "Rosetta Code", + "text": "proc siftDown[T](a: var openarray[T]; start, ending: int) =\n\tvar root = start\n\twhile root * 2 + 1 < ending:\n\t\tvar child = 2 * root + 1\n\t\tif child + 1 < ending and a[child] < a[child+1]:\n\t\t\tinc child\n\t\tif a[root] < a[child]:\n\t\t\tswap a[child], a[root]\n\t\t\troot = child\n\t\telse:\n\t\t\treturn\n\nproc heapSort[T](a: var openarray[T]) =\n\tlet count = a.len\n\tfor start in countdown((count - 2) div 2, 0):\n\t\tsiftDown(a, start, count)\n\tfor ending in countdown(count - 1, 1):\n\t\tswap a[ending], a[0]\n\t\tsiftDown(a, 0, ending)\n\nvar a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]\nheapSort a\necho a\n" + }, + { + "id": 772, + "length": 594, + "source": "Rosetta Code", + "text": "var program = \"9hHqQ+\"\nvar i = 0\n\nproc bottle(n: int): string =\n\tcase n\n\tof 0:\n\t\tresult = \"No more bottles\"\n\tof 1:\n\t\tresult = \"1 bottle\"\n\telse:\n\t\tresult = $n & \" bottles\"\n\nproc ninetyNineBottles =\n\tfor n in countdown(99, 1):\n\t\techo bottle(n), \" bottle of beer on the wall\"\n\t\techo bottle(n), \" bottle of beer\"\n\t\techo \"Take one down, pass it around\"\n\t\techo bottle(n - 1), \" of beer on the wall\"\n\nfor token in items(program):\n\tcase token\n\tof 'h', 'H':\n\t\techo(\"Hello, world!\")\n\tof 'q', 'Q':\n\t\techo(program)\n\tof '9':\n\t\tninetyNineBottles()\n\tof '+':\n\t\tinc(i)\n\telse:\n\t\techo(\"Unknown command: \", token)\n" + }, + { + "id": 773, + "length": 1450, + "source": "Rosetta Code", + "text": "{.this: self.}\n\ntype\n\tSudoku = ref object\n\t\tgrid : array[81, int]\n\t\tsolved : bool\n\nproc `$`(self: Sudoku): string =\n\tvar sb: string = \"\"\n\tfor i in 0..8:\n\t\tfor j in 0..8:\n\t\t\tsb &= $grid[i * 9 + j]\n\t\t\tsb &= \" \"\n\t\t\tif j == 2 or j == 5:\n\t\t\t\tsb &= \"| \"\n\t\tsb &= \"\\n\"\n\t\tif i == 2 or i == 5:\n\t\t\tsb &= \"------+------+------\\n\"\n\tsb\n\nproc init(self: Sudoku, rows: array[9, string]) =\n\tfor i in 0..8:\n\t\tfor j in 0..8:\n\t\t\tgrid[9 * i + j] = rows[i][j].int - '0'.int\n\nproc checkValidity(self: Sudoku, v, x, y: int): bool =\n\tfor i in 0..8:\n\t\tif grid[y * 9 + i] == v or grid[i * 9 + x] == v:\n\t\t\treturn false\n\tvar startX = (x div 3) * 3\n\tvar startY = (y div 3) * 3\n\tfor i in startY..startY + 2:\n\t\tfor j in startX..startX + 2:\n\t\t\tif grid[i * 9 + j] == v:\n\t\t\t\treturn false\n\tresult = true\n\nproc placeNumber(self: Sudoku, pos: int) =\n\tif solved:\n\t\treturn\n\tif pos == 81:\n\t\tsolved = true\n\t\treturn\n\tif grid[pos] > 0:\n\t\tplaceNumber(pos + 1)\n\t\treturn\n\tfor n in 1..9:\n\t\tif checkValidity(n, pos mod 9, pos div 9):\n\t\t\tgrid[pos] = n\n\t\t\tplaceNumber(pos + 1)\n\t\t\tif solved:\n\t\t\t\treturn\n\t\t\tgrid[pos] = 0\n\nproc solve(self: Sudoku) =\n\techo \"Starting grid:\\n\\n\", $self\n\tplaceNumber(0)\n\tif solved:\n\t\techo \"Solution:\\n\\n\", $self\n\telse:\n\t\techo \"Unsolvable!\"\n\nvar rows = [\"850002400\",\n\t\t\t\t\t\t\"720000009\",\n\t\t\t\t\t\t\"004000000\",\n\t\t\t\t\t\t\"000107002\",\n\t\t\t\t\t\t\"305000900\",\n\t\t\t\t\t\t\"040000000\",\n\t\t\t\t\t\t\"000080070\",\n\t\t\t\t\t\t\"017000000\",\n\t\t\t\t\t\t\"000036040\"]\n\nvar puzzle = Sudoku()\npuzzle.init(rows)\npuzzle.solve()\n" + }, + { + "id": 774, + "length": 2306, + "source": "Rosetta Code", + "text": "# Pendulum simulation.\n\nimport math\nimport times\n\nimport opengl\nimport opengl/glut\n\nvar\n\t# Simulation variables.\n\tlg: float # Pendulum length.\n\tg: float # Gravity (should be positive).\n\tcurrTime: Time # Current time.\n\ttheta0: float # Initial angle.\n\ttheta: float # Current angle.\n\tomega: float # Angular velocity = derivative of theta.\n\taccel: float # Angular acceleration = derivative of omega.\n\te: float # Total energy.\n\n\nproc initSimulation(length, gravitation, start: float) =\n\t## Initialize the simulation.\n\n\tlg = length\n\tg = gravitation\n\tcurrTime = getTime()\n\ttheta0 = start # Initial angle for which omega = 0.\n\ttheta = start\n\tomega = 0\n\taccel = -g / lg * sin(theta0)\n\te = g * lg * (1 - cos(theta0)) # Total energy = potential energy when starting.\n\n\nproc elapsed(): float =\n\t## Return the elapsed time since previous call, expressed in seconds.\n\n\tlet nextTime = getTime()\n\tresult = (nextTime - currTime).inMicroseconds.float / 1e6\n\tcurrTime = nextTime\n\n\nproc resize(w, h: GLsizei) =\n\t## Resize the window.\n\n\tglViewport(0, 0, w, h)\n\tglMatrixMode(GL_PROJECTION)\n\tglLoadIdentity()\n\n\tglMatrixMode(GL_MODELVIEW)\n\tglLoadIdentity()\n\tglOrtho(0, GLdouble(w), GLdouble(h), 0, -1, 1)\n\n\nproc render() {.cdecl.} =\n\t## Render the window.\n\n\t# Compute the position of the mass.\n\tvar x = 320 + 300 * sin(theta)\n\tvar y = 300 * cos(theta)\n\n\tresize(640, 320)\n\tglClear(GL_COLOR_BUFFER_BIT)\n\n\t# Draw the line from pivot to mass.\n\tglBegin(GL_LINES)\n\tglVertex2d(320, 0)\n\tglVertex2d(x, y)\n\tglEnd()\n\tglFlush()\n\n\t# Update theta and omega.\n\tlet dt = elapsed()\n\ttheta += (omega + dt * accel / 2) * dt\n\tomega += accel * dt\n\n\t# If, due to computation errors, potential energy is greater than total energy,\n\t# reset theta to +-theta0 and omega to 0.\n\tif lg * g * (1 - cos(theta)) >= e:\n\t\ttheta = sgn(theta).toFloat * theta0\n\t\tomega = 0\n\n\taccel = -g / lg * sin(theta)\n\n\nproc initGfx(argc: ptr cint; argv: pointer) =\n\t## Initialize OpenGL rendering.\n\n\tglutInit(argc, argv)\n\tglutInitDisplayMode(GLUT_RGB)\n\tglutInitWindowSize(640, 320)\n\tglutIdleFunc(render)\n\tdiscard glutCreateWindow(\"Pendulum\")\n\tglutDisplayFunc(render)\n\tloadExtensions()\n\n\ninitSimulation(length = 5, gravitation = 9.81, start = PI / 3)\n\nvar argc: cint = 0\ninitGfx(addr(argc), nil)\nglutMainLoop()\n" + }, + { + "id": 775, + "length": 3076, + "source": "Rosetta Code", + "text": "# Pendulum simulation.\n\nimport math\nimport times\n\nimport gintro/[gobject, gdk, gtk, gio, cairo]\nimport gintro/glib except Pi\n\ntype\n\n\t# Description of the simulation.\n\tSimulation = ref object\n\t\tarea: DrawingArea # Drawing area.\n\t\tlength: float # Pendulum length.\n\t\tg: float # Gravity (should be positive).\n\t\ttime: Time # Current time.\n\t\ttheta0: float # initial angle.\n\t\ttheta: float # Current angle.\n\t\tomega: float # Angular velocity = derivative of theta.\n\t\taccel: float # Angular acceleration = derivative of omega.\n\t\te: float # Total energy.\n\n\nproc newSimulation(area: DrawingArea; length, g, theta0: float): Simulation {.noInit.} =\n\t## Allocate and initialize the simulation object.\n\n\tnew(result)\n\tresult.area = area\n\tresult.length = length\n\tresult.g = g\n\tresult.time = getTime()\n\tresult.theta0 = theta0\n\tresult.theta = theta0\n\tresult.omega = 0\n\tresult.accel = -g / length * sin(theta0)\n\tresult.e = g * length * (1 - cos(theta0)) # Total energy = potential energy when starting.\n\n\ntemplate toFloat(dt: Duration): float = dt.inNanoseconds.float / 1e9\n\n\nconst Origin = (x: 320.0, y: 100.0) # Pivot coordinates.\nconst Scale = 300 # Coordinates scaling constant.\n\nproc draw(sim: Simulation; context: cairo.Context) =\n\t## Draw the pendulum.\n\n\t# Compute coordinates in drawing area.\n\tlet x = Origin.x + sin(sim.theta) * Scale\n\tlet y = Origin.y + cos(sim.theta) * Scale\n\n\t# Clear the region.\n\tcontext.moveTo(0, 0)\n\tcontext.setSource(0.0, 0.0, 0.0)\n\tcontext.paint()\n\n\t# Draw pendulum.\n\tcontext.moveTo(Origin.x, Origin.y)\n\tcontext.setSource(0.3, 1.0, 0.3)\n\tcontext.lineTo(x, y)\n\tcontext.stroke()\n\n\t# Draw pivot.\n\tcontext.setSource(0.3, 0.3, 1.0)\n\tcontext.arc(Origin.x, Origin.y, 8, 0, 2 * Pi)\n\tcontext.fill()\n\n\t# Draw mass.\n\tcontext.setSource(1.0, 0.3, 0.3)\n\tcontext.arc(x, y, 8, 0, 2 * Pi)\n\tcontext.fill()\n\n\nproc update(sim: Simulation): gboolean =\n\t## Update the simulation state.\n\n\t# compute time interval.\n\tlet nextTime = getTime()\n\tlet dt = (nextTime - sim.time).toFloat\n\tsim.time = nextTime\n\n\t# Update theta and omega.\n\tsim.theta += (sim.omega + dt * sim.accel / 2) * dt\n\tsim.omega += sim.accel * dt\n\n\t# If, due to computation errors, potential energy is greater than total energy,\n\t# reset theta to +-theta0 and omega to 0.\n\tif sim.length * sim.g * (1 - cos(sim.theta)) >= sim.e:\n\t\tsim.theta = sgn(sim.theta).toFloat * sim.theta0\n\t\tsim.omega = 0\n\n\t# Compute acceleration.\n\tsim.accel = -sim.g / sim.length * sin(sim.theta)\n\n\tresult = gboolean(1)\n\n\tsim.draw(sim.area.window.cairoCreate())\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(640, 480)\n\twindow.setTitle(\"Pendulum simulation\")\n\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\tlet sim = newSimulation(area, length = 5, g = 9.81, theta0 = PI / 3)\n\n\ttimeoutAdd(10, update, sim)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Pendulum\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 776, + "length": 919, + "source": "Rosetta Code", + "text": "import random, tables\n\n\nproc dice5(): int = rand(1..5)\n\n\nproc dice7(): int =\n\twhile true:\n\t\tlet val = 5 * dice5() + dice5() - 6\n\t\tif val < 21:\n\t\t\treturn val div 3 + 1\n\n\nproc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =\n\n\tvar counts: CountTable[int]\n\tfor _ in 1..repeat:\n\t\tcounts.inc f()\n\n\tlet expected = (repeat / counts.len).toInt # Rounded to nearest.\n\tlet allowedDelta = (expected.toFloat * tolerance / 100).toInt\n\tvar maxDelta = 0\n\tfor val, count in counts.pairs:\n\t\tlet d = abs(count - expected)\n\t\tif d > maxDelta: maxDelta = d\n\n\tlet status = if maxDelta <= allowedDelta: \"passed\" else: \"failed\"\n\techo \"Checking \", repeat, \" values with a tolerance of \", tolerance, \"%.\"\n\techo \"Random generator \", status, \" the uniformity test.\"\n\techo \"Max delta encountered = \", maxDelta, \" Allowed delta = \", allowedDelta\n\n\nwhen isMainModule:\n\timport random\n\trandomize()\n\tcheckDist(dice7, 1_000_000, 0.5)\n" + }, + { + "id": 777, + "length": 798, + "source": "Rosetta Code", + "text": "import tables\n\n\nproc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =\n\n\tvar counts: CountTable[int]\n\tfor _ in 1..repeat:\n\t\tcounts.inc f()\n\n\tlet expected = (repeat / counts.len).toInt # Rounded to nearest.\n\tlet allowedDelta = (expected.toFloat * tolerance / 100).toInt\n\tvar maxDelta = 0\n\tfor val, count in counts.pairs:\n\t\tlet d = abs(count - expected)\n\t\tif d > maxDelta: maxDelta = d\n\n\tlet status = if maxDelta <= allowedDelta: \"passed\" else: \"failed\"\n\techo \"Checking \", repeat, \" values with a tolerance of \", tolerance, \"%.\"\n\techo \"Random generator \", status, \" the uniformity test.\"\n\techo \"Max delta encountered = \", maxDelta, \" Allowed delta = \", allowedDelta\n\n\nwhen isMainModule:\n\timport random\n\trandomize()\n\tproc rand5(): int = rand(1..5)\n\tcheckDist(rand5, 1_000_000, 0.5)\n" + }, + { + "id": 778, + "length": 1524, + "source": "Rosetta Code", + "text": "import lenientops, math, stats, strformat, sugar\n\nfunc simpson38(f: (float) -> float; a, b: float; n: int): float =\n\tlet h = (b - a) / n\n\tlet h1 = h / 3\n\tvar sum = f(a) + f(b)\n\tfor i in countdown(3 * n - 1, 1):\n\t\tif i mod 3 == 0:\n\t\t\tsum += 2 * f(a + h1 * i)\n\t\telse:\n\t\t\tsum += 3 * f(a + h1 * i)\n\tresult = h * sum / 8\n\nfunc gammaIncQ(a, x: float): float =\n\tlet aa1 = a - 1\n\tfunc f(t: float): float = pow(t, aa1) * exp(-t)\n\tvar y = aa1\n\tlet h = 1.5e-2\n\twhile f(y) * (x - y) > 2e-8 and y < x:\n\t\ty += 0.4\n\tif y > x: y = x\n\tresult = 1 - simpson38(f, 0, y, (y / h / gamma(a)).toInt)\n\nfunc chi2ud(ds: openArray[int]): float =\n\tlet expected = mean(ds)\n\tvar s = 0.0\n\tfor d in ds:\n\t\tlet x = d.toFloat - expected\n\t\ts += x * x\n\tresult = s / expected\n\nfunc chi2p(dof: int; distance: float): float =\n\tgammaIncQ(0.5 * dof, 0.5 * distance)\n\nconst SigLevel = 0.05\n\nproc utest(dset: openArray[int]) =\n\n\techo \"Uniform distribution test\"\n\tlet s = sum(dset)\n\techo \" dataset:\", dset\n\techo \" samples: \", s\n\techo \" categories: \", dset.len\n\n\tlet dof = dset.len - 1\n\techo \" degrees of freedom: \", dof\n\n\tlet dist = chi2ud(dset)\n\techo \" chi square test statistic: \", dist\n\n\tlet p = chi2p(dof, dist)\n\techo \" p-value of test statistic: \", p\n\n\tlet sig = p < SigLevel\n\techo \" significant at {int(SigLevel * 100)}% level? {sig}\"\n\techo \" uniform? {not sig}\\n\"\n\n\nfor dset in [[199809, 200665, 199607, 200270, 199649],\n\t\t\t\t\t\t [522573, 244456, 139979, 71531, 21461]]:\n\tutest(dset)\n" + }, + { + "id": 779, + "length": 715, + "source": "Rosetta Code", + "text": "import strutils, os\n\nvar world, world2 = \"\"\"\n+-----------+\n|tH.........|\n|. . |\n| ... |\n|. . |\n|Ht.. ......|\n+-----------+\"\"\"\n\nlet h = world.splitLines.len\nlet w = world.splitLines[0].len\n\ntemplate isH(x, y): int = int(s[i + w * y + x] == 'H')\n\nproc next(o: var string, s: string, w: int) =\n\tfor i, c in s:\n\t\to[i] = case c\n\t\t\tof ' ': ' '\n\t\t\tof 't': '.'\n\t\t\tof 'H': 't'\n\t\t\tof '.':\n\t\t\t\tif (isH(-1, -1) + isH(0, -1) + isH(1, -1) +\n\t\t\t\t\t\tisH(-1, 0) + isH(1, 0) +\n\t\t\t\t\t\tisH(-1, 1) + isH(0, 1) + isH(1, 1)\n\t\t\t\t\t ) in 1..2: 'H' else: '.'\n\t\t\telse: c\n\nwhile true:\n\techo world\n\tstdout.write \"\\x1b[\",h,\"A\"\n\tstdout.write \"\\x1b[\",w,\"D\"\n\tsleep 100\n\n\tworld2.next(world, w)\n\tswap world, world2\n" + }, + { + "id": 780, + "length": 772, + "source": "Rosetta Code", + "text": "const BoardSize = 8\n\nproc underAttack(col: int; queens: seq[int]): bool =\n\tif col in queens: return true\n\tfor i, x in queens:\n\t\tif abs(col - x) == queens.len - i:\n\t\t\treturn true\n\treturn false\n\nproc solve(n: int): seq[seq[int]] =\n\tresult = newSeq[seq[int]]()\n\tresult.add(@[])\n\tvar newSolutions = newSeq[seq[int]]()\n\tfor row in 1..n:\n\t\tfor solution in result:\n\t\t\tfor i in 1..BoardSize:\n\t\t\t\tif not underAttack(i, solution):\n\t\t\t\t\tnewSolutions.add(solution & i)\n\t\tswap result, newSolutions\n\t\tnewSolutions.setLen(0)\n\necho \"Solutions for a chessboard of size \", BoardSize, 'x', BoardSize\necho \"\"\n\nfor i, answer in solve(BoardSize):\n\tfor row, col in answer:\n\t\tif row > 0: stdout.write ' '\n\t\tstdout.write chr(ord('a') + row), col\n\tstdout.write if i mod 4 == 3: \"\\n\" else: \" \"\n" + }, + { + "id": 781, + "length": 717, + "source": "Rosetta Code", + "text": "import random\n\nconst\n\tTarget = \"METHINKS IT IS LIKE A WEASEL\"\n\tAlphabet = \" ABCDEFGHIJLKLMNOPQRSTUVWXYZ\"\n\tP = 0.05\n\tC = 100\n\nproc negFitness(trial: string): int =\n\tfor i in 0 .. trial.high:\n\t\tif Target[i] != trial[i]:\n\t\t\tinc result\n\nproc mutate(parent: string): string =\n\tfor c in parent:\n\t\tresult.add (if rand(1.0) < P: sample(Alphabet) else: c)\n\nrandomize()\n\nvar parent = \"\"\nfor _ in 1..Target.len:\n\tparent.add sample(Alphabet)\n\nvar i = 0\nwhile parent != Target:\n\tvar copies = newSeq[string](C)\n\tfor i in 0 .. copies.high:\n\t\tcopies[i] = parent.mutate()\n\n\tvar best = copies[0]\n\tfor i in 1 .. copies.high:\n\t\tif negFitness(copies[i]) < negFitness(best):\n\t\t\tbest = copies[i]\n\tparent = best\n\n\techo i, \" \", parent\n\tinc i\n" + }, + { + "id": 782, + "length": 1503, + "source": "Rosetta Code", + "text": "type\n\tList[T] = object\n\t\thead, tail: Node[T]\n\n\tNode[T] = ref TNode[T]\n\n\tTNode[T] = object\n\t\tnext, prev: Node[T]\n\t\tdata: T\n\nproc initList[T](): List[T] = discard\n\nproc newNode[T](data: T): Node[T] =\n\tnew(result)\n\tresult.data = data\n\nproc prepend[T](l: var List[T], n: Node[T]) =\n\tn.next = l.head\n\tif l.head != nil: l.head.prev = n\n\tl.head = n\n\tif l.tail == nil: l.tail = n\n\nproc append[T](l: var List[T], n: Node[T]) =\n\tn.next = nil\n\tn.prev = l.tail\n\tif l.tail != nil:\n\t\tl.tail.next = n\n\tl.tail = n\n\tif l.head == nil:\n\t\tl.head = n\n\nproc insertAfter[T](l: var List[T], r, n: Node[T]) =\n\tn.prev = r\n\tn.next = r.next\n\tn.next.prev = n\n\tr.next = n\n\tif r == l.tail: l.tail = n\n\nproc remove[T](l: var List[T], n: Node[T]) =\n\tif n == l.tail: l.tail = n.prev\n\tif n == l.head: l.head = n.next\n\tif n.next != nil: n.next.prev = n.prev\n\tif n.prev != nil: n.prev.next = n.next\n\nproc `$`[T](l: var List[T]): string =\n\tresult = \"\"\n\tvar n = l.head\n\twhile n != nil:\n\t\tif result.len > 0: result.add(\" -> \")\n\t\tresult.add($n.data)\n\t\tn = n.next\n\niterator traverseForward[T](l: List[T]): T =\n\tvar n = l.head\n\twhile n != nil:\n\t\tyield n.data\n\t\tn = n.next\n\niterator traverseBackward[T](l: List[T]): T =\n\tvar n = l.tail\n\twhile n != nil:\n\t\tyield n.data\n\t\tn = n.prev\n\nvar l = initList[int]()\nvar n = newNode(12)\nvar m = newNode(13)\nvar i = newNode(14)\nvar j = newNode(15)\nl.append(n)\nl.prepend(m)\nl.insertAfter(m, i)\nl.prepend(j)\nl.remove(m)\n\nfor i in l.traverseForward():\n\techo \"> \", i\n\nfor i in l.traverseBackward():\n\techo \"< \", i\n" + }, + { + "id": 783, + "length": 1460, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat\n\ntype\n\tOperation = enum\n\t\topAdd = \"+\"\n\t\topSub = \"-\"\n\t\topMul = \"*\"\n\t\topDiv = \"/\"\n\nconst Ops = @[opAdd, opSub, opMul, opDiv]\n\nfunc opr(o: Operation, a, b: float): float =\n\tcase o\n\tof opAdd: a + b\n\tof opSub: a - b\n\tof opMul: a * b\n\tof opDiv: a / b\n\nfunc solve(nums: array[4, int]): string =\n\tfunc `~=`(a, b: float): bool =\n\t\tabs(a - b) <= 1e-5\n\n\tresult = \"not found\"\n\tlet sortedNums = nums.sorted.mapIt float it\n\tfor i in product Ops.repeat 3:\n\t\tlet (x, y, z) = (i[0], i[1], i[2])\n\t\tvar nums = sortedNums\n\t\twhile true:\n\t\t\tlet (a, b, c, d) = (nums[0], nums[1], nums[2], nums[3])\n\t\t\tif x.opr(y.opr(a, b), z.opr(c, d)) ~= 24.0:\n\t\t\t\treturn fmt\"({a:0} {y} {b:0}) {x} ({c:0} {z} {d:0})\"\n\t\t\tif x.opr(a, y.opr(b, z.opr(c, d))) ~= 24.0:\n\t\t\t\treturn fmt\"{a:0} {x} ({b:0} {y} ({c:0} {z} {d:0}))\"\n\t\t\tif x.opr(y.opr(z.opr(c, d), b), a) ~= 24.0:\n\t\t\t\treturn fmt\"(({c:0} {z} {d:0}) {y} {b:0}) {x} {a:0}\"\n\t\t\tif x.opr(y.opr(b, z.opr(c, d)), a) ~= 24.0:\n\t\t\t\treturn fmt\"({b:0} {y} ({c:0} {z} {d:0})) {x} {a:0}\"\n\t\t\tif not nextPermutation(nums): break\n\nproc main() =\n\tfor nums in [\n\t\t\t\t\t\t\t [9, 4, 4, 5],\n\t\t\t\t\t\t\t [1, 7, 2, 7],\n\t\t\t\t\t\t\t [5, 7, 5, 4],\n\t\t\t\t\t\t\t [1, 4, 6, 6],\n\t\t\t\t\t\t\t [2, 3, 7, 3],\n\t\t\t\t\t\t\t [8, 7, 9, 7],\n\t\t\t\t\t\t\t [1, 6, 2, 6],\n\t\t\t\t\t\t\t [7, 9, 4, 1],\n\t\t\t\t\t\t\t [6, 4, 2, 2],\n\t\t\t\t\t\t\t [5, 7, 9, 7],\n\t\t\t\t\t\t\t [3, 3, 8, 8], # Difficult case requiring precise division\n\t\t\t\t\t\t\t]:\n\t\techo fmt\"solve({nums}) -> {solve(nums)}\"\n\nwhen isMainModule: main()\n" + }, + { + "id": 784, + "length": 1114, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\tWovel = 'W' # Character code used to specify a wovel.\n\tIgnore = ' ' # Character code used to specify a character to ignore ('h', 'w' or non-letter).\n\n\nproc code(ch: char): char =\n\t## Return the soundex code for a character.\n\tcase ch.toLowerAscii()\n\tof 'b', 'f', 'p', 'v': '1'\n\tof 'c', 'g', 'j', 'k', 'q', 's', 'x', 'z': '2'\n\tof 'd', 't': '3'\n\tof 'l': '4'\n\tof 'm', 'n': '5'\n\tof 'r': '6'\n\tof 'a', 'e', 'i', 'o', 'u', 'y': Wovel\n\telse: Ignore\n\nproc soundex(str: string): string =\n\t## Return the soundex for the given string.\n\n\tresult.add str[0] # Store the first letter.\n\n\t# Process characters.\n\tvar prev = code(str[0])\n\tfor i in 1..str.high:\n\t\tlet curr = code(str[i])\n\t\tif curr != Ignore:\n\t\t\tif curr != Wovel and curr != prev:\n\t\t\t\tresult.add curr\n\t\t\tprev = curr\n\n\t# Make sure the result has four characters.\n\tif result.len > 4:\n\t\tresult.setLen(4)\n\telse:\n\t\tfor _ in result.len..3:\n\t\t\tresult.add '0'\n\n\nfor name in [\"Robert\", \"Rupert\", \"Rubin\", \"Ashcraft\", \"Ashcroft\", \"Tymczak\",\n\t\t\t\t\t\t \"Pfister\", \"Honeyman\", \"Moses\", \"O'Mally\", \"O'Hara\", \"D day\"]:\n\techo name.align(8), \" \", soundex(name)\n" + }, + { + "id": 785, + "length": 612, + "source": "Rosetta Code", + "text": "import bigints\n\nproc min(a: varargs[BigInt]): BigInt =\n\tresult = a[0]\n\tfor i in 1..a.high:\n\t\tif a[i] < result: result = a[i]\n\nproc hamming(limit: int): BigInt =\n\tvar\n\t\th = newSeq[BigInt](limit)\n\t\tx2 = initBigInt(2)\n\t\tx3 = initBigInt(3)\n\t\tx5 = initBigInt(5)\n\t\ti, j, k = 0\n\tfor i in 0..h.high: h[i] = initBigInt(1)\n\n\tfor n in 1 ..< limit:\n\t\th[n] = min(x2, x3, x5)\n\t\tif x2 == h[n]:\n\t\t\tinc i\n\t\t\tx2 = h[i] * 2\n\t\tif x3 == h[n]:\n\t\t\tinc j\n\t\t\tx3 = h[j] * 3\n\t\tif x5 == h[n]:\n\t\t\tinc k\n\t\t\tx5 = h[k] * 5\n\n\tresult = h[h.high]\n\nfor i in 1 .. 20:\n\tstdout.write hamming(i), \" \"\necho \"\"\necho hamming(1691)\necho hamming(1_000_000)\n" + }, + { + "id": 786, + "length": 888, + "source": "Rosetta Code", + "text": "import bigints, times\n\nproc hamming(limit: int): BigInt =\n\tdoAssert limit > 0\n\tvar\n\t\th = newSeq[BigInt](limit)\n\t\tx2 = initBigInt(2)\n\t\tx3 = initBigInt(3)\n\t\tx5 = initBigInt(5)\n\t\ti, j, k = 0\n\th[0] = initBigInt(1)\n\n\t# BigInt comparisons are expensive, reduce them...\n\tproc min3(x, y, z: BigInt): (int, BigInt) =\n\t\tlet (cs, r1) = if y == z: (6, y)\n\t\t\t\t\t\t\t\t\t elif y < z: (2, y) else: (4, z)\n\t\tif x == r1: (cs or 1, x)\n\t\telif x < r1: (1, x) else: (cs, r1)\n\n\tfor n in 1 ..< limit:\n\t\tlet (cs, e1) = min3(x2, x3, x5)\n\t\th[n] = e1\n\t\tif (cs and 1) != 0: i += 1; x2 = h[i] * 2\n\t\tif (cs and 2) != 0: j += 1; x3 = h[j] * 3\n\t\tif (cs and 4) != 0: k += 1; x5 = h[k] * 5\n\n\th[h.high]\n\nfor i in 1 .. 20:\n\tstdout.write hamming(i), \" \"\necho \"\"\necho hamming(1691)\n\nlet strt = epochTime()\nlet rslt = hamming(1_000_000)\nlet stop = epochTime()\n\necho rslt\necho \"This last took \", (stop - strt)*1000, \" milliseconds.\"\n" + }, + { + "id": 787, + "length": 1858, + "source": "Rosetta Code", + "text": "import bigints, times\n\niterator func_hamming() : BigInt =\n\ttype Thunk[T] = proc(): T {.closure.}\n\ttype Lazy[T] = ref object of RootObj # tuple[val: T, thnk: Thunk[T]]\n\t\tval: T\n\t\tthnk: Thunk[T]\n\tproc force[T](me: var Lazy[T]): T = # not thread-safe; needs lock on thunk\n\t\tif me.thnk != nil: me.val = me.thnk(); me.thnk = nil\n\t\tme.val\n\ttype LazyList[T] = ref object of RootObj # tuple[hd: T, tl: Lazy[LazyList[T]]]\n\t\thd: T\n\t\ttl: Lazy[LazyList[T]]\n\ttype Mytype = LazyList[BigInt]\n\tproc merge(x, y: Mytype): Mytype =\n\t\tlet xh = x.hd; let yh = y.hd\n\t\tif xh < yh:\n\t\t\tlet mthnk = proc(): Mytype = merge x.tl.force, y\n\t\t\tlet mlzy = Lazy[Mytype](thnk: mthnk)\n\t\t\tMytype(hd: xh, tl: mlzy)\n\t\telse:\n\t\t\tlet mthnk = proc(): Mytype = merge x, y.tl.force\n\t\t\tlet mlzy = Lazy[Mytype](thnk: mthnk)\n\t\t\tMytype(hd: yh, tl: mlzy)\n\tproc smult(m: int32, s: Mytype): Mytype =\n\t\tproc smults(ss: Mytype): Mytype =\n\t\t\tlet mthnk = proc(): Mytype = ss.tl.force.smults\n\t\t\tlet mlzy = Lazy[Mytype](thnk: mthnk)\n\t\t\tMytype(hd: ss.hd * m, tl: mlzy)\n\t\ts.smults\n\tproc u(s: Mytype, n: int32): Mytype =\n\t\tvar r: Mytype\n\t\tlet mthnk = proc(): Mytype = r\n\t\tlet mlzy = Lazy[Mytype](thnk: mthnk)\n\t\tlet frst = Mytype(hd: initBigInt 1, tl: mlzy)\n\t\tif s == nil: r = smult(n, frst) else: r = merge(s, smult(n, frst))\n\t\tr\n\tvar hmg: Mytype = nil\n\tfor p in [5i32, 3i32, 2i32]: hmg = u(hmg, p)\n\tyield initBigInt 1\n\twhile true: # loop almost forever\n\t\tyield initBigInt hmg.hd\n\t\thmg = hmg.tl.force\n\nvar cnt = 1\nfor h in func_hamming():\n\tif cnt > 20: break\n\twrite stdout, h, \" \"; cnt += 1\necho \"\"\ncnt = 1\nfor h in func_hamming():\n\tif cnt < 1691: cnt += 1; continue\n\telse: echo h; break\n\nlet strt = epochTime()\nvar rslt: BigInt\ncnt = 1\nfor h in func_hamming():\n\tif cnt < 1000000: cnt += 1; continue\n\telse: rslt = h; break\nlet stop = epochTime()\n\necho rslt\necho \"This last took \", (stop - strt)*1000, \" milliseconds.\"\n" + }, + { + "id": 788, + "length": 2559, + "source": "Rosetta Code", + "text": "from times import inMilliseconds\nimport std/monotimes, bigints\nfrom math import log2\n\ntype TriVal = (uint32, uint32, uint32)\ntype LogRep = (float64, TriVal)\ntype LogRepf = proc(x: LogRep): LogRep\nconst one: LogRep = (0.0f64, (0'u32, 0'u32, 0'u32))\nproc `<`(me: LogRep, othr: LogRep): bool = me[0] < othr[0]\n\nproc convertTrival2BigInt(tv: TriVal): BigInt =\n\tproc xpnd(bs: uint, v: uint32): BigInt =\n\t\tresult = initBigInt 1;\n\t\tvar bsm = initBigInt bs;\n\t\tvar vm = v.uint\n\t\twhile vm > 0:\n\t\t\tif (vm and 1) != 0: result *= bsm\n\t\t\tbsm = bsm * bsm # bsm *= bsm crashes.\n\t\t\tvm = vm shr 1\n\tresult = (2.xpnd tv[0]) * (3.xpnd tv[1]) * (5.xpnd tv[2])\n\nconst lb2 = 1.0'f64\nconst lb3 = 3.0'f64.log2\nconst lb5 = 5.0'f64.log2\n\nproc mul2(me: LogRep): LogRep =\n\tlet (lr, tpl) = me; let (x2, x3, x5) = tpl\n\t(lr + lb2, (x2 + 1, x3, x5))\n\nproc mul3(me: LogRep): LogRep =\n\tlet (lr, tpl) = me; let (x2, x3, x5) = tpl\n\t(lr + lb3, (x2, x3 + 1, x5))\n\nproc mul5(me: LogRep): LogRep =\n\tlet (lr, tpl) = me; let (x2, x3, x5) = tpl\n\t(lr + lb5, (x2, x3, x5 + 1))\n\ntype\n\tLazyList = ref object\n\t\thd: LogRep\n\t\ttlf: proc(): LazyList {.closure.}\n\t\ttl: LazyList\n\nproc rest(ll: LazyList): LazyList = # not thread-safe; needs lock on thunk\n\tif ll.tlf != nil: ll.tl = ll.tlf(); ll.tlf = nil\n\tll.tl\n\niterator log_func_hammings(until: int): TriVal =\n\tproc merge(x, y: LazyList): LazyList =\n\t\tlet xh = x.hd\n\t\tlet yh = y.hd\n\t\tif xh < yh: LazyList(hd: xh, tlf: proc(): auto = merge x.rest, y)\n\t\telse: LazyList(hd: yh, tlf: proc(): auto = merge x, y.rest)\n\tproc smult(mltf: LogRepf; s: LazyList): LazyList =\n\t\tproc smults(ss: LazyList): LazyList =\n\t\t\tLazyList(hd: ss.hd.mltf, tlf: proc(): auto = ss.rest.smults)\n\t\ts.smults\n\tproc unnsm(s: LazyList, mltf: LogRepf): LazyList =\n\t\tvar r: LazyList = nil\n\t\tlet frst = LazyList(hd: one, tlf: proc(): LazyList = r)\n\t\tr = if s == nil: smult mltf, frst else: s.merge smult(mltf, frst)\n\t\tr\n\tyield one[1]\n\tvar hmpll: LazyList = ((nil.unnsm mul5).unnsm mul3).unnsm mul2\n\tfor _ in 2 .. until:\n\t\tyield hmpll.hd[1]; hmpll = hmpll.rest # almost forever\n\nproc main =\n\tstdout.write \"The first 20 hammings are: \"\n\tfor h in log_func_hammings(20): stdout.write h.convertTrival2BigInt, \" \"\n\n\tvar lsth: TriVal\n\tfor h in log_func_hammings(1691): lsth = h\n\techo \"\\r\\nThe 1691st Hamming number is: \", lsth.convertTriVal2BigInt\n\n\tlet strt = getMonotime()\n\tfor h in log_func_hammings(1000000): lsth = h\n\tlet elpsd = (getMonotime() - strt).inMilliseconds\n\techo \"The millionth Hamming number is: \", lsth.convertTriVal2BigInt\n\techo \"This last took \", elpsd, \" milliseconds.\"\n\nmain()\n" + }, + { + "id": 789, + "length": 1455, + "source": "Rosetta Code", + "text": "import bigints, times\n\niterator nodups_hamming(): BigInt =\n\tvar\n\t\tm = newSeq[BigInt](1) # give it two values so doubling size works\n\t\th = newSeq[BigInt](1) # reasonably size\n\t\tx5 = initBigInt 5\n\t\tmrg = initBigInt 3\n\t\tx53 = initBigInt 9 # already advanced one step\n\t\tx532 = initBigInt 2\n\t\tih, jm, i, j = 0\n\n\tyield initBigInt 1 # trivial case of 1\n\twhile true:\n\t\tlet cph = h.len # move in-place to avoid allocation\n\t\tif i >= cph div 2: # move in-place to avoid allocation\n\t\t\tvar s = i; var d = 0\n\t\t\twhile s < ih: shallowCopy(h[d], h[s]); s += 1; d += 1\n\t\t\tih -= i; i = 0\n\t\tif ih >= cph: h.setLen(2 * cph)\n\t\tif x532 < mrg: h[ih] = x532; x532 = h[i] * 2; i += 1\n\t\telse:\n\t\t\th[ih] = mrg\n\t\t\tlet cpm = m.len\n\t\t\tif j >= cpm div 2: # move in-place to avoid allocation\n\t\t\t\tvar s = j; var d = 0\n\t\t\t\twhile s < jm: shallowCopy(m[d], m[s]); s += 1; d += 1\n\t\t\t\tjm -= j; j = 0\n\t\t\tif jm >= cpm: m.setLen(2 * cpm)\n\t\t\tif x53 < x5: mrg = x53; x53 = m[j] * 3; j += 1\n\t\t\telse: mrg = x5; x5 = x5 * 5\n\t\t\tm[jm] = mrg\n\t\t\tjm += 1\n\t\tih += 1\n\n\t\tyield h[ih - 1]\n\n\nvar cnt = 1\nfor h in nodups_hamming():\n\tif cnt > 20: break\n\twrite stdout, h, \" \"; cnt += 1\necho \"\"\ncnt = 1\nfor h in nodups_hamming():\n\tif cnt < 1691: cnt += 1; continue\n\telse: echo h; break\n\nlet strt = epochTime()\nvar rslt: BigInt\ncnt = 1\nfor h in nodups_hamming():\n\tif cnt < 1000000: cnt += 1; continue\n\telse: rslt = h; break\nlet stop = epochTime()\n\necho rslt\necho \"This last took \", (stop - strt)*1000, \" milliseconds.\"\n" + }, + { + "id": 790, + "length": 2990, + "source": "Rosetta Code", + "text": "# HammingsLogImp.nim\n# compile with: nim c -d:danger -t:-march=native -d:LTO --gc:arc HammingsLogImp\n\nimport bigints, std/math\nfrom std/times import inMicroseconds\nfrom std/monotimes import getMonoTime, `-`\n\ntype LogRep = (float64, uint32, uint32, uint32)\n\nlet one: LogRep = (0.0, 0'u32, 0'u32, 0'u32)\n\nlet lb2 = 1.0'f64; let lb3 = 3.0.log2; let lb5 = 5.0.log2\nproc mul2(me: Logrep): Logrep {.inline.} =\n\t(me[0] + lb2, me[1] + 1, me[2], me[3])\nproc mul3(me: Logrep): Logrep {.inline.} =\n\t(me[0] + lb3, me[1], me[2] + 1, me[3])\nproc mul5(me: Logrep): Logrep {.inline.} =\n\t(me[0] + lb5, me[1], me[2], me[3] + 1)\n\nproc lr2BigInt(lr: Logrep): BigInt =\n\tproc xpnd(bs: uint, v: uint32): BigInt =\n\t\tresult = initBigInt 1\n\t\tvar bsm = initBigInt bs;\n\t\tvar vm = v.uint\n\t\twhile vm > 0:\n\t\t\tif (vm and 1) != 0: result *= bsm\n\t\t\tbsm *= bsm; vm = vm shr 1\n\txpnd(2, lr[1]) * xpnd(3, lr[2]) * xpnd(5, lr[3])\n\niterator hammingsLogImp(): LogRep =\n\tvar\n\t\ts2 = newSeq[Logrep](1024) # give it size one so doubling size works\n\t\ts3 = newSeq[Logrep](1024) # reasonably sized\n\t\ts5 = one.mul5 # initBigInt 5\n\t\tmrg = one.mul3 # initBigInt 3\n\t\ts2hdi, s2tli, s3hdi, s3tli = 0\n\n\tyield one\n\ts2[0] = one.mul2; s3[0] = one.mul3\n\twhile true:\n\t\ts2tli += 1\n\t\tif s2hdi + s2hdi >= s2tli: # move in-place to avoid allocation\n\t\t\tcopyMem(addr(s2[0]), addr(s2[s2hdi]), sizeof(LogRep) * (s2tli - s2hdi))\n\t\t\ts2tli -= s2hdi; s2hdi = 0\n\t\tlet cps2 = s2.len # move in-place to avoid allocation\n\t\tif s2tli >= cps2: s2.setLen(cps2 + cps2)\n\t\tvar rsltp = addr(s2[s2hdi])\n\t\tif rsltp[][0] < mrg[0]: s2[s2tli] = rsltp[].mul2; s2hdi += 1; yield rsltp[]\n\t\telse:\n\t\t\ts3tli += 1\n\t\t\tif s3hdi + s3hdi >= s3tli: # move in-place to avoid allocation\n\t\t\t\tcopyMem(addr(s3[0]), addr(s3[s3hdi]), sizeof(LogRep) * (s3tli - s3hdi))\n\t\t\t\ts3tli -= s3hdi; s3hdi = 0\n\t\t\tlet cps3 = s3.len\n\t\t\tif s3tli >= cps3: s3.setLen(cps3 + cps3)\n\t\t\ts2[s2tli] = mrg.mul2; s3[s3tli] = mrg.mul3; s3hdi += 1\n\t\t\tlet arsltp = addr(s3[s3hdi])\n\t\t\tlet rslt = mrg\n\t\t\tif arsltp[][0] < s5[0]: mrg = arsltp[]\n\t\t\telse: mrg = s5; s5 = s5.mul5; s3hdi -= 1\n\t\t\tyield rslt\n\nvar cnt = 0\nfor h in hammingsLogImp():\n\twrite stdout, h.lr2BigInt, \" \"; cnt += 1\n\tif cnt >= 20: break\necho \"\"\ncnt = 0\nfor h in hammingsLogImp():\n\tcnt += 1\n\tif cnt >= 1691: echo h.lr2BigInt; break\n\nlet strt = getMonoTime()\nvar rslt: LogRep\ncnt = 0\nfor h in hammingsLogImp():\n\tcnt += 1\n\tif cnt >= 1_000_000: rslt = h; break # \"\"\"\nlet elpsd = (getMonoTime() - strt).inMicroseconds\n\nlet (_, x2, x3, x5) = rslt\nwriteLine stdout, \"2^\", x2, \" + 3^\", x3, \" + 5^\", x5\nlet lgrslt = (x2.float64 + x3.float64 * 3.0f64.log2 +\n\t\t\t\t\t\t\t x5.float64 * 5.0f64.log2) * 2.0f64.log10\nlet (whl, frac) = lgrslt.splitDecimal\necho \"Approximately: \", 10.0f64.pow(frac), \"E+\", whl.uint64\nlet brslt = rslt.lr2BigInt()\nlet s = brslt.to_string\nlet ls = s.len\necho \"Number of digits: \", ls\nif ls <= 2000:\n\tfor i in countup(0, ls - 1, 100):\n\t\tif i + 100 < ls: echo s[i .. i + 99]\n\t\telse: echo s[i .. ls - 1]\necho \"This last took \", elpsd, \" microseconds.\"\n" + }, + { + "id": 791, + "length": 2649, + "source": "Rosetta Code", + "text": "import bigints, math, algorithm, times\n\ntype TriVal = (uint32, uint32, uint32)\n\nproc convertTrival2BigInt(tv: TriVal): BigInt =\n\n\tproc xpnd(bs: uint, v: uint32): BigInt =\n\t\tresult = initBigInt 1\n\t\tvar bsm = initBigInt bs\n\t\tvar vm = v.uint\n\t\twhile vm > 0:\n\t\t\tif (vm and 1) != 0: result *= bsm\n\t\t\tbsm = bsm * bsm # bsm *= bsm causes a crash.\n\t\t\tvm = vm shr 1\n\n\tresult = (2.xpnd tv[0]) * (3.xpnd tv[1]) * (5.xpnd tv[2])\n\nproc nth_hamming(n: uint64): TriVal =\n\tdoAssert n > 0u64\n\tif n < 2: return (0'u32, 0'u32, 0'u32) # trivial case for 1\n\n\ttype LogRep = (float64, uint32, uint32, uint32)\n\n\tlet lb3 = 3.0'f64.log2; let lb5 = 5.0'f64.log2; let fctr = 6.0'f64*lb3*lb5\n\tlet\n\t\tcrctn = 30.0'f64.sqrt().log2 # log base 2 of sqrt 30\n\t\tlgest = (fctr * n.float64).pow(1.0'f64/3.0'f64) - crctn # from WP formula\n\t\tfrctn = if n < 1000000000: 0.509'f64 else: 0.105'f64\n\t\tlghi = (fctr * (n.float64 + frctn * lgest)).pow(1.0'f64/3.0'f64) - crctn\n\t\tlglo = 2.0'f64 * lgest - lghi # and a lower limit of the upper \"band\"\n\tvar count = 0'u64 # need to use extended precision, might go over\n\tvar bnd = newSeq[LogRep](1) # give itone value so doubling size works\n\tlet klmt = (lghi / lb5).uint32 + 1\n\tfor k in 0 ..< klmt: # i, j, k values can be just u32 values\n\t\tlet p = k.float64 * lb5; let jlmt = ((lghi - p) / lb3).uint32 + 1\n\t\tfor j in 0 ..< jlmt:\n\t\t\tlet q = p + j.float64 * lb3\n\t\t\tlet ir = lghi - q; let lg = q + ir.floor # current log value (estimated)\n\t\t\tcount += ir.uint64 + 1;\n\t\t\tif lg >= lglo: bnd.add((lg, ir.uint32, j, k))\n\tif n > count: raise newException(Exception, \"nth_hamming: band high estimate is too low!\")\n\tlet ndx = (count - n).int\n\tif ndx >= bnd.len: raise newException(Exception, \"nth_hamming: band low estimate is too high!\")\n\tbnd.sort((proc (a, b: LogRep): int = a[0].cmp b[0]), SortOrder.Descending)\n\n\tlet rslt = bnd[ndx]; (rslt[1], rslt[2], rslt[3])\n\nfor i in 1 .. 20:\n\twrite stdout, nth_hamming(i.uint64).convertTrival2BigInt, \" \"\necho \"\"\necho nth_hamming(1691).convertTrival2BigInt\n\nlet strt = epochTime()\nlet rslt = nth_hamming(1_000_000'u64)\nlet stop = epochTime()\n\nlet (x2, x3, x5) = rslt\nwriteLine stdout, \"2^\", x2, \" + 3^\", x3, \" + 5^\", x5\nlet lgrslt = (x2.float64 + x3.float64 * 3.0f64.log2 +\n\t\t\t\t\t\t\t x5.float64 * 5.0f64.log2) * 2.0f64.log10\nlet (whl, frac) = lgrslt.splitDecimal\necho \"Approximately: \", 10.0f64.pow(frac), \"E+\", whl.uint64\nlet brslt = rslt.convertTrival2BigInt()\nlet s = brslt.to_string\nlet ls = s.len\necho \"Number of digits: \", ls\nif ls <= 2000:\n\tfor i in countup(0, ls - 1, 100):\n\t\tif i + 100 < ls: echo s[i .. i + 99]\n\t\telse: echo s[i .. ls - 1]\n\necho \"This last took \", (stop - strt) * 1000, \" milliseconds.\"\n" + }, + { + "id": 792, + "length": 3048, + "source": "Rosetta Code", + "text": "import bigints, math, algorithm, times\n\ntype TriVal = (uint32, uint32, uint32)\n\nproc convertTrival2BigInt(tv: TriVal): BigInt =\n\n\tproc xpnd(bs: uint, v: uint32): BigInt =\n\t\tresult = initBigInt 1\n\t\tvar bsm = initBigInt bs\n\t\tvar vm = v.uint\n\t\twhile vm > 0:\n\t\t\tif (vm and 1) != 0: result *= bsm\n\t\t\tbsm = bsm * bsm # bsm *= bsm causes a crash.\n\t\t\tvm = vm shr 1\n\n\tresult = (2.xpnd tv[0]) * (3.xpnd tv[1]) * (5.xpnd tv[2])\n\nproc nth_hamming(n: uint64): TriVal =\n\tdoAssert n > 0u64\n\tif n < 2: return (0'u32, 0'u32, 0'u32) # trivial case for 1\n\n\ttype LogRep = (BigInt, uint32, uint32, uint32)\n\n\tlet lb3 = 3.0'f64.log2; let lb5 = 5.0'f64.log2; let fctr = 6.0'f64*lb3*lb5\n\tlet # manually produce the BigInt \"limb's\"!\n\t\tbglb2 = initBigInt @[0'u32, 0, 0, 16] # 1267650600228229401496703205376\n\t\t# 2009178665378409109047848542368\n\t\tbglb3 = initBigInt @[11608224'u32, 3177740794'u32, 1543611295, 25]\n\t\t# 2943393543170754072109742145491\n\t\tbglb5 = initBigInt @[1258143699'u32, 1189265298, 647893747, 37]\n\t\tcrctn = 30.0'f64.sqrt().log2 # log base 2 of sqrt 30\n\t\tlgest = (fctr * n.float64).pow(1.0'f64/3.0'f64) - crctn # from WP formula\n\t\tfrctn = if n < 1000000000: 0.509'f64 else: 0.105'f64\n\t\tlghi = (fctr * (n.float64 + frctn * lgest)).pow(1.0'f64/3.0'f64) - crctn\n\t\tlglo = 2.0'f64 * lgest - lghi # and a lower limit of the upper \"band\"\n\tvar count = 0'u64 # need to use extended precision, might go over\n\tvar bnd = newSeq[LogRep](1) # give it one value so doubling size works\n\tlet klmt = (lghi / lb5).uint32 + 1\n\tfor k in 0 ..< klmt: # i, j, k values can be just u32 values\n\t\tlet p = k.float64 * lb5; let jlmt = ((lghi - p) / lb3).uint32 + 1\n\t\tfor j in 0 ..< jlmt:\n\t\t\tlet q = p + j.float64 * lb3\n\t\t\tlet ir = lghi - q; let lg = q + ir.floor # current log value (estimated)\n\t\t\tcount += ir.uint64 + 1;\n\t\t\tif lg >= lglo:\n\t\t\t\tlet bglg = bglb2 * ir.int32 + bglb3 * j.int32 + bglb5 * k.int32\n\t\t\t\tbnd.add((bglg, ir.uint32, j, k))\n\tif n > count: raise newException(Exception, \"nth_hamming: band high estimate is too low!\")\n\tlet ndx = (count - n).int\n\tif ndx >= bnd.len: raise newException(Exception, \"nth_hamming: band low estimate is too high!\")\n\tbnd.sort((proc (a, b: LogRep): int = (a[0].cmp b[0]).int), SortOrder.Descending)\n\n\tlet rslt = bnd[ndx]; (rslt[1], rslt[2], rslt[3])\n\nfor i in 1 .. 20:\n\twrite stdout, nth_hamming(i.uint64).convertTrival2BigInt, \" \"\necho \"\"\necho nth_hamming(1691).convertTrival2BigInt\n\nlet strt = epochTime()\nlet rslt = nth_hamming(1_000_000'u64)\nlet stop = epochTime()\n\nlet (x2, x3, x5) = rslt\nwriteLine stdout, \"2^\", x2, \" + 3^\", x3, \" + 5^\", x5\nlet lgrslt = (x2.float64 + x3.float64 * 3.0f64.log2 +\n\t\t\t\t\t\t\t x5.float64 * 5.0f64.log2) * 2.0f64.log10\nlet (whl, frac) = lgrslt.splitDecimal\necho \"Approximately: \", 10.0f64.pow(frac), \"E+\", whl.uint64\nlet brslt = rslt.convertTrival2BigInt()\nlet s = brslt.to_string\nlet ls = s.len\necho \"Number of digits: \", ls\nif ls <= 2000:\n\tfor i in countup(0, ls - 1, 100):\n\t\tif i + 100 < ls: echo s[i .. i + 99]\n\t\telse: echo s[i .. ls - 1]\n\necho \"This last took \", (stop - strt) * 1000, \" milliseconds.\"\n" + }, + { + "id": 793, + "length": 2030, + "source": "Rosetta Code", + "text": "import tables\nimport math\nimport strutils\nimport algorithm\n\ntype\n\tStemLeafPlot = ref object\n\t\tleafDigits: int\n\t\tmultiplier: int\n\t\tplot: TableRef[int, seq[int]]\n\nproc `$`(s: seq[int]): string =\n\tresult = \"\"\n\tfor item in s:\n\t\tresult &= $item & \" \"\n\nproc `$`(self: StemLeafPlot): string =\n\tresult = \"\"\n\tvar keys: seq[int] = @[]\n\tfor stem, _ in self.plot:\n\t\tkeys.add(stem)\n\tfor printedStem in keys.min..keys.max:\n\t\tresult &= align($printedStem & \" | \", ($keys.max).len + 4)\n\t\tif printedStem in keys:\n\t\t\tself.plot[printedStem].sort(system.cmp[int])\n\t\t\tresult &= $self.plot[printedStem]\n\t\tresult &= \"\\n\"\n\nproc parse(self: StemLeafPlot, value: int): tuple[stem, leaf: int] =\n\t(value div self.multiplier, abs(value mod self.multiplier))\n\nproc init[T](self: StemLeafPlot, leafDigits: int, data: openArray[T]) =\n\tself.leafDigits = leafDigits\n\tself.multiplier = 10 ^ leafDigits\n\tself.plot = newTable[int, seq[int]]()\n\tfor value in data:\n\t\tlet (stem, leaf) = self.parse(value)\n\t\tif stem notin self.plot:\n\t\t\tself.plot[stem] = @[leaf]\n\t\telse:\n\t\t\tself.plot[stem].add(leaf)\n\nvar taskData = @[12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124,\n\t\t\t\t\t\t\t\t 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123,\n\t\t\t\t\t\t\t\t 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105,\n\t\t\t\t\t\t\t\t 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58,\n\t\t\t\t\t\t\t\t 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43,\n\t\t\t\t\t\t\t\t 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118,\n\t\t\t\t\t\t\t\t 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122,\n\t\t\t\t\t\t\t\t 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114,\n\t\t\t\t\t\t\t\t 34, 133, 45, 120, 30, 127, 31, 116, 146]\n\nvar negativeData = @[-24, -12, -3, 4, 6, 6, 17, 25, 57]\n\necho \"Using the Task's Test Data\"\nvar taskPlot = StemLeafPlot()\ntaskPlot.init(1, taskData)\necho taskPlot\n\necho \"Test with Negative Stem\"\nvar negativePlot = StemLeafPlot()\nnegativePlot.init(1, negativeData)\necho negativePlot\n" + }, + { + "id": 794, + "length": 1654, + "source": "Rosetta Code", + "text": "type\n\n\t# Kind of numbers. We limit this example to \"int\" and \"float\".\n\tNumberKind = enum kInt, kFloat\n\n\t# Customized number type (using variants).\n\tNumber = object\n\t\tcase kind: NumberKind\n\t\tof kInt:\n\t\t\tival: int\n\t\tof kFloat:\n\t\t\tfval: float\n\n# The converters allow transparent conversion from int or float to Number.\nconverter toNumber(n: int): Number = Number(kind: kInt, ival: n)\nconverter toNumber(n: float): Number = Number(kind: kFloat, fval: n)\n\n\nproc accumulator[T: int|float](x: T): auto =\n\t## Factory procedure.\n\n\t# Allocate the accumulator storage.\n\twhen T is int:\n\t\tvar sum = Number(kind: kInt, ival: x)\n\telif T is float:\n\t\tvar sum = Number(kind: kFloat, fval: x)\n\n\t# Create the accumulator procedure.\n\tresult = proc (n: Number): Number =\n\t\t# Create the accumulator procedure.\n\tresult = proc (n: Number): Number =\n\t\t\t\t\t\t case sum.kind\n\t\t\t\t\t\t of kInt:\n\t\t\t\t\t\t\t case n.kind\n\t\t\t\t\t\t\t of kInt:\n\t\t\t\t\t\t\t\t # Add an int to an int.\n\t\t\t\t\t\t\t\t sum.ival += n.ival\n\t\t\t\t\t\t\t of kFloat:\n\t\t\t\t\t\t\t\t # Add a float to an int => change the kind of accumulator to float.\n\t\t\t\t\t\t\t\t sum = Number(kind: kFloat, fval: sum.ival.toFloat + n.fval)\n\t\t\t\t\t\t of kFloat:\n\t\t\t\t\t\t\t case n.kind\n\t\t\t\t\t\t\t of kInt:\n\t\t\t\t\t\t\t\t # Add an int to a float.\n\t\t\t\t\t\t\t\t sum.fval += n.ival.toFloat\n\t\t\t\t\t\t\t of kFloat:\n\t\t\t\t\t\t\t\t # Add a float to a float.\n\t\t\t\t\t\t\t\t sum.fval += n.fval\n\t\t\t\t\t\t result = sum\n\n\nproc `$`(n: Number): string =\n\t## Display the accumulator contents as an int or a float depending of its kind.\n\tcase n.kind\n\tof kInt: $n.ival\n\tof kFloat: $n.fval\n\n\nlet acc = accumulator(1)\necho acc(5) # 6\ndiscard accumulator(3) # Create another accumulator.\necho acc(2.3) # 8.3\n" + }, + { + "id": 795, + "length": 2840, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strtabs, strutils, xmlparser, xmltree\n\ntype\n\n\tAnimation = object\n\t\tattrName: string # Attribute to animate.\n\t\tfromValues: seq[float] # List of \"from\" values.\n\t\ttoValues: seq[float] # List of \"to\" values.\n\t\tbegin: float # Animation starting time.\n\t\tduration: float # Animation duration.\n\n\nfunc getAnim(node: XmlNode): Animation =\n\t## Build an animation object from an XML node.\n\n\tresult.attrName = node.attr(\"attributeName\")\n\tif result.attrName.len == 0:\n\t\traise newException(ValueError, \"missing 'attributeName' attribute\")\n\tvar str = node.attr(\"from\")\n\tif str.len == 0:\n\t\traise newException(ValueError, \"missing 'from' attribute\")\n\tresult.fromValues = str.splitWhitespace().map(parseFloat)\n\tstr = node.attr(\"to\")\n\tif str.len == 0:\n\t\traise newException(ValueError, \"missing 'to' attribute\")\n\tresult.toValues = str.splitWhitespace().map(parseFloat)\n\tif result.fromValues.len != result.toValues.len:\n\t\traise newException(ValueError, \"inconsistent number of values\")\n\tstr = node.attr(\"begin\")\n\tif str.len == 0:\n\t\traise newException(ValueError, \"missing 'begin' attribute\")\n\tif str[^1] != 's':\n\t\traise newException(ValueError, \"missing unit\")\n\tresult.begin = parseFloat(str[0..^2])\n\tstr = node.attr(\"dur\")\n\tif str.len == 0:\n\t\traise newException(ValueError, \"missing 'dur' attribute\")\n\tif str[^1] != 's':\n\t\traise newException(ValueError, \"missing unit\")\n\tresult.duration = parseFloat(str[0..^2])\n\n\nfunc buildXml(node: XmlNode; t: float): XmlNode =\n\t## Build the XML tree of a SMIL animation at time \"t\".\n\n\tif node.len > 0 and node[0].tag == \"animate\":\n\t\t# Child is an animate node.\n\t\tlet anim = node[0].getAnim()\n\t\t# Check attribute name.\n\t\tif node.attr(anim.attrName).len == 0:\n\t\t\traise newException(ValueError, \"unable to find attribute '{anim.attrName}'\")\n\t\t# Check time.\n\t\tif t notin anim.begin..(anim.begin + anim.duration):\n\t\t\traise newException(ValueError, \"time value out of range\")\n\t\t# Build attribute value.\n\t\tvar aVal = newSeq[float](anim.fromValues.len)\n\t\tfor i in 0..aVal.high:\n\t\t\taVal[i] = (anim.fromValues[i] * (anim.begin + anim.duration - t) +\n\t\t\t\t\t\t\t\t anim.toValues[i] * (t - anim.begin)) / anim.duration\n\t\t# Set attributes.\n\t\tlet a = node.attrs\n\t\ta[anim.attrName] = aVal.mapIt(it.formatFloat(ffDefault, 2)).join(\" \")\n\t\tresult = newElement(node.tag)\n\t\tresult.attrs = a\n\n\telse:\n\t\t# Node child (if any) is not an animate node: copy the node and process children.\n\t\tresult = newElement(node.tag)\n\t\tresult.attrs = node.attrs\n\t\tfor child in node:\n\t\t\tresult.add child.buildXml(t)\n\n\nwhen isMainModule:\n\tlet smil = loadXml(\"smil.xml\")\n\tif smil.tag != \"smil\":\n\t\traise newException(ValueError, \"not a SMIL file\")\n\tlet newRoot = smil[0]\n\techo \"At time 0 second:\\n\"\n\techo xmlHeader, newRoot.buildXml(0)\n\techo \"\\nAt time 2 seconds:\\n\"\n\techo xmlHeader, newRoot.buildXml(2)\n" + }, + { + "id": 796, + "length": 1543, + "source": "Rosetta Code", + "text": "import lenientops, math\nimport grayscale_image\n\nconst White = 255\n\nfunc houghTransform*(img: GrayImage; hx = 460; hy = 360): GrayImage =\n\tassert not img.isNil\n\tassert hx > 0 and hy > 0\n\tassert (hy and 1) == 0, \"hy argument must be even\"\n\n\tresult = newGrayImage(hx, hy)\n\tresult.fill(White)\n\n\tlet rMax = hypot(img.w.toFloat, img.h.toFloat)\n\tlet dr = rMax / (hy / 2)\n\tlet dTh = PI / hx\n\n\tfor y in 0.. 0:\n\t\t\t\t\tresult[iTh, iry] = result[iTh, iry] - 1\n\n\nwhen isMainModule:\n\timport nimPNG\n\timport bitmap\n\n\tconst Input = \"Pentagon.png\"\n\tconst Output = \"Hough.png\"\n\n\tlet pngImage = loadPNG24(seq[byte], Input).get()\n\tlet grayImage = newGrayImage(pngImage.width, pngImage.height)\n\n\t# Convert to grayscale.\n\tfor i in 0..grayImage.pixels.high:\n\t\tgrayImage.pixels[i] = Luminance(0.2126 * pngImage.data[3 * i] +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0.7152 * pngImage.data[3 * i + 1] +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0.0722 * pngImage.data[3 * i + 2] + 0.5)\n\n\t# Apply Hough transform and convert to an RGB image.\n\tlet houghImage = grayImage.houghTransform().toImage()\n\n\t# Save into a PNG file.\n\t# As nimPNG expects a sequence of bytes, not a sequence of colors, we have to make a copy.\n\tvar data = newSeqOfCap[byte](houghImage.pixels.len * 3)\n\tfor color in houghImage.pixels:\n\t\tdata.add([color.r, color.g, color.b])\n\tdiscard savePNG24(Output, data, houghImage.w, houghImage.h)\n" + }, + { + "id": 797, + "length": 695, + "source": "Rosetta Code", + "text": "import math, sequtils, sugar\n\nproc amean(num: seq[float]): float =\n\tsum(num) / float(len(num))\n\nproc gmean(num: seq[float]): float =\n\tresult = 1\n\tfor n in num: result *= n\n\tresult = pow(result, 1.0 / float(num.len))\n\nproc hmean(num: seq[float]): float =\n\tfor n in num: result += 1.0 / n\n\tresult = float(num.len) / result\n\nproc ameanFunctional(num: seq[float]): float =\n\tsum(num) / float(num.len)\n\nproc gmeanFunctional(num: seq[float]): float =\n\tnum.foldl(a * b).pow(1.0 / float(num.len))\n\nproc hmeanFunctional(num: seq[float]): float =\n\tfloat(num.len) / sum(num.mapIt(1.0 / it))\n\nlet numbers = toSeq(1..10).map((x: int) => float(x))\necho amean(numbers), \" \", gmean(numbers), \" \", hmean(numbers)\n" + }, + { + "id": 798, + "length": 4201, + "source": "Rosetta Code", + "text": "import sequtils, typetraits\n\ntype Size = uint64\n\ntype M[T: SomeNumber] = object\n\tdims: seq[Size]\n\tsubsizes: seq[Size]\n\tdata: seq[T]\n\n# Miscellaneous.\n\nfunc dotProduct[T: SomeNumber](a, b: openArray[T]): T =\n\tassert a.len == b.len\n\tfor i in 0..a.high:\n\t\tresult += a[i] * b[i]\n\n\n# Operations on M objects.\n\nfunc setDimensions(m: var M; dimensions: varargs[Size]) =\n\n\tfor dim in dimensions:\n\t\tif dim == 0:\n\t\t\traise newException(IndexDefect, \"wrong dimension: 0\")\n\n\tm.dims = @dimensions\n\tm.subsizes = m.dims\n\tfor i in 0..dimensions.high:\n\t\tm.subsizes[i] = m.dims[(i+1)..^1].foldl(a * b, Size(1))\n\n\tlet dlength = m.dims[0] * m.subsizes[0]\n\tif Size(m.data.len) != dlength:\n\t\tm.data.setLen(dlength)\n\n\nfunc initM(m: var M; dimensions: varargs[Size]) =\n\tm.setDimensions(dimensions)\n\n\nfunc set1DArray(m: var M; t: varargs[m.T]) =\n\n\tlet minLen = min(m.data.len, t.len)\n\tm.data.setLen(minLen)\n\tm.data[0.. m.dims.len:\n\t\treturn false\n\n\tfor i, dim in indexes:\n\t\tif dim >= m.dims[i]:\n\t\t\treturn false\n\n\tresult = true\n\n\nfunc `[]`(m: M; indexes: varargs[Size]): m.T =\n\n\tif not m.checkBounds(indexes):\n\t\traise newException(IndexDefect, \"index out of range: \" & $indexes)\n\n\tm.data[dotProduct(indexes, m.subsizes)]\n\n\nfunc `[]=`(m: M; indexes: varargs[int]; val: m.T) =\n\n\tif not m.checkBounds(indexes):\n\t\traise newException(IndexDefect, \"index out of range: \" & $indexes)\n\n\tm.data[dotProduct(indexes, m.subsizes)] = val\n\n\nfunc `==`(a, b: M): bool = a.dims == b.dims and a.data == b.data\n\n\nfunc `$`(m: M): string = $m.data\n\n\n# Convolution/deconvolution.\n\nfunc convolute(h, f: M): M =\n\t## Result is \"g\".\n\n\tvar dims = h.dims\n\tfor i in 0..dims.high:\n\t\tdims[i] += f.dims[i] - 1\n\tresult.initM(dims)\n\n\tlet bound = result.size\n\tfor i in 0.. 1:\n\t\tif (n and 1) == 1:\n\t\t\tn = 3 * n + 1\n\t\telse:\n\t\t\tn = n div 2\n\t\tresult.add n\n\n\nwhen isMainModule:\n\timport strformat, strutils\n\tlet h = hailstone(27)\n\techo \"Hailstone sequence for number 27 has {h.len} elements.\"\n\tlet first = h[0..3].join(\", \")\n\tlet last = h[^4..^1].join(\", \")\n\techo \"This sequence begins with {first} and ends with {last}.\"\n\n\tvar m, mi = 0\n\tfor i in 1..<100_000:\n\t\tlet n = hailstone(i).len\n\t\tif n > m:\n\t\t\tm = n\n\t\t\tmi = i\n\techo \"\\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi}).\"\n" + }, + { + "id": 801, + "length": 1083, + "source": "Rosetta Code", + "text": "import random, strformat\n\n# Representation of a standard value as an int (actual value * 100).\ntype StandardValue = distinct int\n\nproc `<`(a, b: StandardValue): bool {.borrow.}\n\nconst Pricemap = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]\n\n\nproc toStandardValue(f: float): StandardValue =\n\t## Convert a float to a standard value (decimal value multiplied by 100).\n\t## Index: 0.01..0.05 -> 0, 0.06..0.10 -> 1, 0.11..0.15 -> 2...\n\tvar value = int(f * 100)\n\tif value == 0: return StandardValue(10)\n\tdec value\n\t# Increment index every 5 of value, so value in 1..100 translates to index in 0..19.\n\tlet index = 2 * (value div 10) + (value mod 10) div 5\n\tresult = StandardValue(Pricemap[index])\n\n\nproc `$`(price: StandardValue): string =\n\t## Return the string representation of a standard value.\n\tif price < StandardValue(10): \"0.0\" & $int(price)\n\telif price < StandardValue(100): \"0.\" & $int(price)\n\telse: \"1.00\"\n\n\nwhen isMainModule:\n\trandomize()\n\tfor _ in 0 .. 10:\n\t\tlet price = rand(1.01)\n\t\techo \"Price for {price:.2f} is {price.toStandardValue()}\"\n" + }, + { + "id": 802, + "length": 2584, + "source": "Rosetta Code", + "text": "import sequtils, strformat\n\ntype\n\tVec2 = tuple[x, y: float]\n\tEdge = tuple[p, q: Vec2]\n\tPolygon = seq[Vec2]\n\n\nfunc `-`(a, b: Vec2): Vec2 = (a.x - b.x, a.y - b.y)\n\nfunc cross(a, b: Vec2): float = a.x * b.y - a.y * b.x\n\nfunc isInside(p: Vec2; edge: Edge): bool =\n\t(edge.q.x - edge.p.x) * (p.y - edge.p.y) > (edge.q.y - edge.p.y) * (p.x - edge.p.x)\n\n\nfunc intersection(sEdge, cEdge: Edge): Vec2 =\n\tlet\n\t\tdc = cEdge.p - cEdge.q\n\t\tdp = sEdge.p - sEdge.q\n\t\tn1 = cEdge.p.cross(cEdge.q)\n\t\tn2 = sEdge.p.cross(sEdge.q)\n\t\tn3 = 1 / dc.cross(dp)\n\tresult = ((n1 * dp.x - n2 * dc.x) * n3, (n1 * dp.y - n2 * dc.y) * n3)\n\n\nfunc edges(poly: Polygon): seq[Edge] =\n\t(poly[^1] & poly).zip(poly)\n\n\nfunc clip(subjectPolygon, clipPolygon: Polygon): Polygon =\n\tassert subjectPolygon.len > 1\n\tassert clipPolygon.len > 1\n\n\tresult = subjectPolygon\n\tfor clipEdge in clipPolygon.edges:\n\t\tlet inputList = move(result)\n\t\tresult.reset()\n\t\tfor inEdge in inputList.edges:\n\t\t\tif inEdge.q.isInside(clipEdge):\n\t\t\t\tif not inEdge.p.isInside(clipEdge):\n\t\t\t\t\tresult.add intersection(inEdge, clipEdge)\n\t\t\t\tresult.add inEdge.q\n\t\t\telif inEdge.p.isInside(clipEdge):\n\t\t\t\tresult.add intersection(inEdge, clipEdge)\n\n\nproc saveEpsImage(filename: string; subject, clip, clipped: Polygon) =\n\tlet eps = open(filename, fmWrite)\n\teps.write \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n/l {lineto} def\\n/m {moveto} def\\n\",\n\t\t\t\t\t\t\"/s {setrgbcolor} def\\n/c {closepath} def\\n/gs {fill grestore stroke} def\\n\"\n\n\teps.write \"0 setlinewidth {clip[0].x} {clip[0].y} m \"\n\tfor i in 1..clip.high:\n\t\teps.write \"{clip[i].x} {clip[i].y} l \"\n\teps.writeLine \"c 0.5 0 0 s gsave 1 0.7 0.7 s gs\"\n\n\teps.write \"{subject[0].x} {subject[0].y} m \"\n\tfor i in 1..subject.high:\n\t\teps.write \"{subject[i].x} {subject[i].y} l \"\n\teps.writeLine \"c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs\"\n\n\teps.write \"2 setlinewidth [10 8] 0 setdash {clipped[0].x} {clipped[0].y} m \"\n\tfor i in 1..clipped.high:\n\t\teps.write \"{clipped[i].x} {clipped[i].y} l \"\n\teps.writeLine \"c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs\"\n\n\teps.writeLine \"%%%%EOF\"\n\teps.close()\n\techo \"File {filename} written.\"\n\n\nwhen isMainModule:\n\n\tlet\n\t\tsubjectPolygon = @[(50.0, 150.0), (200.0, 50.0), (350.0, 150.0),\n\t\t\t\t\t\t\t\t\t\t\t(350.0, 300.0), (250.0, 300.0), (200.0, 250.0),\n\t\t\t\t\t\t\t\t\t\t\t(150.0, 350.0), (100.0, 250.0), (100.0, 200.0)]\n\t\tclippingPolygon = @[(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)]\n\n\t\tclipped = subjectPolygon.clip(clippingPolygon)\n\n\tfor point in clipped:\n\t\techo \"({point.x:.3f}, {point.y:.3f})\"\n\tsaveEpsImage(\"sutherland_hodgman_clipping_out.eps\", subjectPolygon, clippingPolygon, clipped)\n" + }, + { + "id": 803, + "length": 876, + "source": "Rosetta Code", + "text": "import random, rdstdin, strutils, algorithm\nrandomize()\n\nproc isSorted[T](s: openarray[T]): bool =\n\tvar last = low(T)\n\tfor c in s:\n\t\tif c < last:\n\t\t\treturn false\n\t\tlast = c\n\treturn true\n\nproc toString[T](s: openarray[T]): string =\n\tresult = \"\"\n\tfor i, x in s:\n\t\tif i > 0:\n\t\t\tresult.add \" \"\n\t\tresult.add($x)\n\necho \"\"\"number reversal game\n\t\tGiven a jumbled list of the numbers 1 to 9\n\t\tShow the list.\n\t\tAsk the player how many digits from the left to reverse.\n\t\tReverse those digits then ask again.\n\t\tuntil all the digits end up in ascending order.\"\"\"\n\nvar data = @[1,2,3,4,5,6,7,8,9]\nvar trials = 0\nwhile isSorted data:\n\tshuffle data\nwhile not isSorted data:\n\tinc trials\n\tvar flip = parseInt readLineFromStdin(\n\t\t\"#\" & $trials & \": List: '\" & toString(data) & \"' Flip how many?: \")\n\treverse(data, 0, flip - 1)\n\necho \"You took \", trials, \" attempts to put the digits in order!\"\n" + }, + { + "id": 804, + "length": 1045, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\nconst\n\tWidth = 1000\n\tHeight = 1000\n\tTrunkLength = 400\n\tScaleFactor = 0.6\n\tStartingAngle = 1.5 * PI\n\tDeltaAngle = 0.2 * PI\n\nproc drawTree(outfile: File; x, y, len, theta: float) =\n\tif len >= 1:\n\t\tlet x2 = x + len * cos(theta)\n\t\tlet y2 = y + len * sin(theta)\n\t\toutfile.write(\n\t\t\tfmt\"\\n\")\n\t\toutfile.drawTree(x2, y2, len * ScaleFactor, theta + DeltaAngle)\n\t\toutFile.drawTree(x2, y2, len * ScaleFactor, theta - DeltaAngle)\n\nlet outsvg = open(\"tree.svg\", fmWrite)\noutsvg.write(\"\"\"\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\\n\n\t\t\t\t\t\t\t\t\\n\"\"\")\n\noutsvg.drawTree(0.5 * Width, Height, TrunkLength, StartingAngle)\noutsvg.write(\"\\n\") # View file tree.svg in browser.\n" + }, + { + "id": 805, + "length": 3144, + "source": "Rosetta Code", + "text": "import parseutils\nimport random\nimport sequtils\nimport strformat\nimport strutils\n\nconst\n\tDigits = \"123456789\"\n\tDigitSet = {Digits[0]..Digits[^1]}\n\tSize = 4\n\tInvalidScore = -1\n\ntype\n\n\tDigit = range['1'..'9']\n\tScore = tuple[bulls, cows: int]\n\tHistItem = tuple[guess: string, bulls, cows: int]\n\n\nproc buildChoices(digits: set[Digit]; size: Natural): seq[string] =\n\t## Build the list of choices when starting the game.\n\n\tif size == 0:\n\t\treturn @[\"\"]\n\tfor d in digits:\n\t\tfor s in buildChoices(digits - {d}, size - 1):\n\t\t\tresult.add(d & s)\n\n\nproc getValues(): Score =\n\t## Read the number of bulls and cows provided by the user.\n\n\tlet input = stdin.readLine().strip()\n\tlet fields = input.splitWhitespace()\n\tif fields.len != 2 or\n\t\t fields[0].parseInt(result.bulls, 0) == 0 or result.bulls notin 0..Size or\n\t\t fields[1].parseInt(result.cows, 0) == 0 or result.cows notin 0..Size:\n\t\techo \"Wrong input; expected two number between 0 and {Size}\"\n\t\treturn (InvalidScore, InvalidScore)\n\tif result.bulls + result.cows > Size:\n\t\techo \"Total number of bulls and cows exceeds {Size}\"\n\t\treturn (InvalidScore, InvalidScore)\n\n\nfunc score(value, guess: string): Score =\n\t## Return the score of \"guess\" against \"value\".\n\n\tfor idx, digit in guess:\n\t\tif digit == value[idx]:\n\t\t\tinc result.bulls\n\t\telif digit in value:\n\t\t\tinc result.cows\n\n\nproc findError(history: seq[HistItem]) =\n\t## Find the scoring error.\n\n\tvar value: string\n\n\t## Get the number to find.\n\twhile true:\n\t\tstdout.write(\"What was the number to find? \")\n\t\tvalue = stdin.readLine().strip()\n\t\tif value.len == Size and allCharsInSet(value, DigitSet) and value.deduplicate.len == Size:\n\t\t\tbreak\n\n\t# Find inconsistencies.\n\tfor (guess, userbulls, usercows) in history:\n\t\tlet (bulls, cows) = score(guess, value)\n\t\tif userbulls != bulls or usercows != cows:\n\t\t\techo \"For guess {guess}, score was wrong:\"\n\t\t\techo \" Expected {bulls} / {cows}, got {userBulls} / {userCows}.\"\n\n\nfunc suffix(n: Positive): string =\n\t## Return the suffix for an ordinal.\n\n\tcase n\n\tof 1: \"st\"\n\tof 2: \"nd\"\n\tof 3: \"rd\"\n\telse: \"th\"\n\n\nvar history: seq[HistItem]\n\nrandomize()\n\nvar choices = buildChoices(DigitSet, Size)\nchoices.shuffle()\n\necho \"Choose a number with four unique digits between 1 and 9.\"\necho \"Give the number of bulls and cows separated by one or more spaces.\"\n\nvar guesses = 0\nvar remaining: seq[string]\n\nwhile true:\n\tinc guesses\n\tvar userbulls, usercows: int\n\tlet guess = choices.pop()\n\techo \"My {guesses}{suffix(guesses)} guess is {guess}\"\n\n\t# Get scoring.\n\twhile true:\n\t\tstdout.write(\"How many bulls and cows? \")\n\t\t(userbulls, usercows) = getValues()\n\t\tif userbulls != InvalidScore and usercows != InvalidScore:\n\t\t\tbreak\n\n\tif userbulls == Size:\n\t\t\techo \"Victory! I found the number in {guesses} attempts.\"\n\t\t\tbreak\n\n\thistory.add((guess, userbulls, usercows))\n\n\t# Eliminate incompatible choices.\n\tremaining.setLen(0)\n\tfor choice in choices:\n\t\tlet (bulls, cows) = score(guess, choice)\n\t\tif bulls == userbulls and cows == usercows:\n\t\t\tremaining.add(choice)\n\tif remaining.len == 0:\n\t\techo \"There is an impossibility. For some guess you made an error in scoring.\"\n\t\thistory.findError()\n\t\tbreak\n\tchoices.shallowCopy(remaining)\n" + }, + { + "id": 806, + "length": 721, + "source": "Rosetta Code", + "text": "type\n\n\tBools[N: static int] = array[N, bool]\n\tSumCarry = tuple[sum, carry: bool]\n\nproc ha(a, b: bool): SumCarry = (a xor b, a and b)\n\nproc fa(a, b, ci: bool): SumCarry =\n\tlet a = ha(ci, a)\n\tlet b = ha(a[0], b)\n\tresult = (b[0], a[1] or b[1])\n\nproc fa4(a, b: Bools[4]): Bools[5] =\n\tvar co, s: Bools[4]\n\tfor i in 0..3:\n\t\tlet r = fa(a[i], b[i], if i > 0: co[i-1] else: false)\n\t\ts[i] = r[0]\n\t\tco[i] = r[1]\n\tresult[0..3] = s\n\tresult[4] = co[3]\n\nproc int2bus(n: int): Bools[4] =\n\tvar n = n\n\tfor i in 0..result.high:\n\t\tresult[i] = (n and 1) == 1\n\t\tn = n shr 1\n\nproc bus2int(b: Bools): int =\n\tfor i, x in b:\n\t\tresult += (if x: 1 else: 0) shl i\n\nfor a in 0..7:\n\tfor b in 0..7:\n\t\tassert a + b == bus2int fa4(int2bus(a), int2bus(b))\n" + }, + { + "id": 807, + "length": 1199, + "source": "Rosetta Code", + "text": "import strformat, strutils, times\n\nconst HolidayOffsets = {\"Easter\": 0, \"Ascension\": 39, \"Pentecost\": 49,\n\t\t\t\t\t\t\t\t\t\t\t\t\"Trinity\": 56, \"C/Christi\": 60}\n\n\nproc easterDate(year: int): DateTime =\n\tlet a = year mod 19\n\tlet b = year div 100\n\tlet c = year mod 100\n\tlet d = b div 4\n\tlet e = b mod 4\n\tlet f = (b + 8) div 25\n\tlet g = (b - f + 1) div 3\n\tlet h = (19 * a + b - d - g + 15) mod 30\n\tlet i = c div 4\n\tlet k = c mod 4\n\tlet l = (32 + 2 * e + 2 * i - h - k) mod 7\n\tlet m = (a + 11 * h + 22 * l) div 451\n\tlet n = h + l - 7 * m + 114\n\tlet month = n div 31\n\tlet day = n mod 31 + 1\n\tresult = initDateTime(day, Month(month), year, 0, 0, 0)\n\n\nproc outputHolidays(year: int) =\n\tlet edate = easterDate(year)\n\tstdout.write \"{year:4d} \"\n\tfor (holiday, offset) in HolidayOffsets:\n\t\tlet date = edate + initDuration(days = offset)\n\t\tlet s = date.format(\"dd MMM\").center(holiday.len)\n\t\tstdout.write \"{s} \"\n\techo \"\"\n\n\necho \"Year Easter Ascension Pentecost Trinity C/Christi\"\necho \" CE Sunday Thursday Sunday Sunday Thursday \"\necho \"---- ------ --------- ---------- ------- ---------\"\nfor year in countup(400, 2100, 100): outputHolidays(year)\necho \"\"\nfor year in 2010..2020: outputHolidays(year)\n" + }, + { + "id": 808, + "length": 4387, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, strscans, strutils\n\nconst LMargin = 4\n\ntype\n\n\tCell = object\n\t\tisMine: bool\n\t\tdisplay: char\n\n\tGrid = seq[seq[Cell]]\n\n\tGame = object\n\t\tgrid: Grid\n\t\tmineCount: Natural\n\t\tminesMarked: Natural\n\t\tisOver: bool\n\n\nproc initGame(m, n: Positive): Game =\n\tresult.grid = newSeqWith(m, repeat(Cell(isMine: false, display: '.'), n))\n\tlet min = (float(m * n) * 0.1).toInt\n\tlet max = (float(m * n) * 0.2).toInt\n\tresult.mineCount = min + rand(max - min)\n\tvar rm = result.mineCount\n\twhile rm > 0:\n\t\tlet x = rand(m - 1)\n\t\tlet y = rand(n - 1)\n\t\tif not result.grid[x][y].isMine:\n\t\t\tdec rm\n\t\t\tresult.grid[x][y].isMine = true\n\tresult.minesMarked = 0\n\n\ntemplate `[]`(grid: Grid; x, y: int): Cell = grid[x][y]\n\n\niterator cells(grid: var Grid): var Cell =\n\tfor y in 0..grid[0].high:\n\t\tfor x in 0..grid.high:\n\t\t\tyield grid[x, y]\n\n\nproc display(game: Game; endOfGame: bool) =\n\tif not endOfGame:\n\t\techo \"Grid has {game.mineCount} mine(s), {game.minesMarked} mine(s) marked.\"\n\tlet margin = repeat(' ', LMargin)\n\techo margin, toSeq(1..game.grid.len).join()\n\techo margin, repeat('-', game.grid.len)\n\tfor y in 0..game.grid[0].high:\n\t\tstdout.write align($(y + 1), LMargin)\n\t\tfor x in 0..game.grid.high:\n\t\t\tstdout.write game.grid[x][y].display\n\t\tstdout.write '\\n'\n\n\nproc terminate(game: var Game; msg: string) =\n\tgame.isOver = true\n\techo msg\n\tvar answer = \"\"\n\twhile answer notin [\"y\", \"n\"]:\n\t\tstdout.write \"Another game (y/n)? \"\n\t\tanswer = try: stdin.readLine().toLowerAscii\n\t\t\t\t\t\t except EOFError: \"n\"\n\t\tif answer == \"y\":\n\t\t\tgame = initGame(6, 4)\n\t\t\tgame.display(false)\n\n\nproc resign(game: var Game) =\n\tvar found = 0\n\tfor cell in game.grid.cells:\n\t\tif cell.isMine:\n\t\t\tif cell.display == '?':\n\t\t\t\tcell.display = 'Y'\n\t\t\t\tinc found\n\t\t\telif cell.display == 'x':\n\t\t\t\tcell.display = 'N'\n\tgame.display(true)\n\tlet msg = \"You found {found} out of {game.mineCount} mine(s).\"\n\tgame.terminate(msg)\n\n\nproc markCell(game: var Game; x, y: int) =\n\tif game.grid[x, y].display == '?':\n\t\tdec game.minesMarked\n\t\tgame.grid[x, y].display = '.'\n\telif game.grid[x, y].display == '.':\n\t\tinc game.minesMarked\n\t\tgame.grid[x, y].display = '?'\n\n\nproc countAdjMines(game: Game; x, y: Natural): int =\n\tfor j in (y - 1)..(y + 1):\n\t\tif j in 0..game.grid[0].high:\n\t\t\tfor i in (x - 1)..(x + 1):\n\t\t\t\tif i in 0..game.grid.high:\n\t\t\t\t\tif game.grid[i, j].isMine:\n\t\t\t\t\t\tinc result\n\n\nproc clearCell(game: var Game; x, y: int): bool =\n\n\tif x in 0..game.grid.high and y in 0..game.grid[0].high:\n\t\tif game.grid[x, y].display == '.':\n\n\t\t\tif game.grid[x, y].isMine:\n\t\t\t\tgame.grid[x][y].display = 'x'\n\t\t\t\techo \"Kaboom! You lost!\"\n\t\t\t\treturn false\n\n\t\t\tlet count = game.countAdjMines(x, y)\n\t\t\tif count > 0:\n\t\t\t\tgame.grid[x][y].display = chr(ord('0') + count)\n\t\t\telse:\n\t\t\t\tgame.grid[x][y].display = ' '\n\t\t\t\tfor dx in -1..1:\n\t\t\t\t\tfor dy in -1..1:\n\t\t\t\t\t\tif dx != 0 or dy != 0:\n\t\t\t\t\t\t\tdiscard game.clearCell(x + dx, y + dy)\n\n\tresult = true\n\n\nproc testForWin(game: var Game): bool =\n\tif game.minesMarked != game.mineCount: return false\n\tfor cell in game.grid.cells:\n\t\tif cell.display == '.': return false\n\tresult = true\n\techo \"You won!\"\n\n\nproc splitAction(game: Game; action: string): tuple[x, y: int; ok: bool] =\n\tvar command: string\n\tif not action.scanf(\"$w $s$i $s$i$s$.\", command, result.x, result.y): return\n\tif command.len != 1: return\n\tif result.x notin 1..game.grid.len or result.y notin 1..game.grid.len: return\n\tresult.ok = true\n\n\nproc printUsage() =\n\techo \"h or ? - this help,\"\n\techo \"c x y - clear cell (x,y),\"\n\techo \"m x y - marks (toggles) cell (x,y),\"\n\techo \"n - start a new game,\"\n\techo \"q - quit/resign the game,\"\n\techo \"where 'x' is the (horizontal) column number and 'y' is the (vertical) row number.\\n\"\n\n\nrandomize()\nprintUsage()\nvar game = initGame(6, 4)\ngame.display(false)\n\nwhile not game.isOver:\n\tstdout.write \"\\n>\"\n\tlet action = try: stdin.readLine().toLowerAscii\n\t\t\t\t\t\t\t except EOFError: \"q\"\n\tcase action[0]\n\n\tof 'h', '?':\n\t\tprintUsage()\n\n\tof 'n':\n\t\tgame = initGame(6, 4)\n\t\tgame.display(false)\n\n\tof 'c':\n\t\tlet (x, y, ok) = game.splitAction(action)\n\t\tif not ok: continue\n\t\tif game.clearCell(x - 1, y - 1):\n\t\t\tgame.display(false)\n\t\t\tif game.testForwin(): game.resign()\n\t\telse:\n\t\t\tgame.resign()\n\n\tof 'm':\n\t\tlet (x, y, ok) = game.splitAction(action)\n\t\tif not ok: continue\n\t\tgame.markCell(x - 1, y - 1)\n\t\tgame.display(false)\n\t\tif game.testForWin(): game.resign()\n\n\tof 'q':\n\t\tgame.resign()\n\n\telse:\n\t\tcontinue\n" + }, + { + "id": 809, + "length": 1181, + "source": "Rosetta Code", + "text": "import random, os, sequtils, strutils\n\nrandomize()\n\ntype State {.pure.} = enum Empty, Tree, Fire\n\nconst\n\tDisp: array[State, string] = [\" \", \"\\e[32m/\\\\\\e[m\", \"\\e[07;31m/\\\\\\e[m\"]\n\tTreeProb = 0.01\n\tBurnProb = 0.001\n\nproc chance(prob: float): bool {.inline.} = rand(1.0) < prob\n\n# Set the size\nvar w, h: int\nif paramCount() >= 2:\n\tw = paramStr(1).parseInt\n\th = paramStr(2).parseInt\nif w <= 0: w = 30\nif h <= 0: h = 30\n\niterator fields(a = (0, 0), b = (h-1, w-1)): tuple[y, x: int] =\n\t## Iterate over fields in the universe\n\tfor y in max(a[0], 0) .. min(b[0], h-1):\n\t\tfor x in max(a[1], 0) .. min(b[1], w-1):\n\t\t\tyield (y, x)\n\n# Initialize\nvar univ, univNew = newSeqWith(h, newSeq[State](w))\n\nwhile true:\n\n\t# Show.\n\tstdout.write \"\\e[H\"\n\tfor y, x in fields():\n\t\tstdout.write Disp[univ[y][x]]\n\t\tif x == 0: stdout.write \"\\e[E\"\n\tstdout.flushFile\n\n\t# Evolve.\n\tfor y, x in fields():\n\t\tcase univ[y][x]\n\t\tof Fire:\n\t\t\tunivNew[y][x] = Empty\n\t\tof Empty:\n\t\t\tif chance(TreeProb): univNew[y][x] = Tree\n\t\tof Tree:\n\t\t\tfor y1, x1 in fields((y-1, x-1), (y+1, x+1)):\n\t\t\t\tif univ[y1][x1] == Fire:\n\t\t\t\t\tunivNew[y][x] = Fire\n\t\t\t\t\tbreak\n\t\t\tif chance(BurnProb): univNew[y][x] = Fire\n\tuniv = univNew\n\tsleep 200\n" + }, + { + "id": 810, + "length": 916, + "source": "Rosetta Code", + "text": "import parseutils, re, strutils, sequtils\n\nproc extractRange(input: string): string =\n\tvar list = input.replace(re\"\\s+\").split(',').map(parseInt)\n\tvar ranges: seq[string]\n\tvar i = 0\n\twhile i < list.len:\n\t\tvar first = list[i] # first element in the current range\n\t\tvar offset = i\n\t\twhile True: # skip ahead to the end of the current range\n\t\t\tif i + 1 >= list.len:\n\t\t\t\t# reached end of the list\n\t\t\t\tbreak\n\t\t\tif list[i + 1] - (i + 1) != first - offset:\n\t\t\t\t# next element isn't in the current range\n\t\t\t\tbreak\n\t\t\ti.inc\n\t\tvar last = list[i] # last element in the current range\n\t\tcase last - first\n\t\t\tof 0: ranges.add($first)\n\t\t\tof 1: ranges.add(\"$1,$2\".format(first, last))\n\t\t\telse: ranges.add(\"$1-$2\".format(first, last))\n\t\ti.inc\n\treturn ranges.join(\",\")\n\necho(\"\"\"\n\t\t0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n\t 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n\t 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n\t 37, 38, 39\"\"\".extractRange)\n" + }, + { + "id": 811, + "length": 571, + "source": "Rosetta Code", + "text": "import parseutils, strutils\n\nproc expandRange(input: string): string =\n\tvar output: seq[string]\n\tfor range in input.split(','):\n\t\tvar sep = range.find('-', 1)\n\t\tif sep > 0: # parse range\n\t\t\tvar first = -1\n\t\t\tif range.substr(0, sep-1).parseInt(first) == 0:\n\t\t\t\tbreak\n\t\t\tvar last = -1\n\t\t\tif range.substr(sep+1).parseInt(last) == 0:\n\t\t\t\tbreak\n\t\t\tfor i in first..last:\n\t\t\t\toutput.add($i)\n\t\telse: # parse single number\n\t\t\tvar n = -1\n\t\t\tif range.parseInt(n) > 0:\n\t\t\t\toutput.add($n)\n\t\t\telse:\n\t\t\t\tbreak\n\treturn output.join(\",\")\n\necho(\"-6,-3--1,3-5,7-11,14,15,17-20\".expandRange)\n" + }, + { + "id": 812, + "length": 2219, + "source": "Rosetta Code", + "text": "import times, strformat\n\nconst\n\n\tDiscordianOrigin = -1166\n\tSaintTibsDay = \"St. Tib's Day\"\n\ntype\n\n\tSeason = enum\n\t\tsCha = (1, \"Chaos\"), sDis = \"Discord\", sCon = \"Confusion\",\n\t\tsBur = \"Bureaucracy\", sAft = \"The Aftermath\"\n\n\tErisianWeekDay = enum\n\t\teSwe = \"Sweetmorn\", eBoo = \"Boomtime\", ePun = \"Pungenday\",\n\t\tePri = \"Prickle-Prickle\", eSet = \"Setting Orange\"\n\n\tSeasonDayRange = range[1..73]\n\n\t# Description of a discordian date.\n\tDiscordianDate = object\n\t\tyear: int\n\t\tyearday: YeardayRange\n\t\tcase isSaintTibsDay: bool\n\t\tof false:\n\t\t\tseasondayZero: int\n\t\t\tseasonZero: int\n\t\t\tweekday: ErisianWeekDay\n\t\telse:\n\t\t\tnil\n\n\nproc toDiscordianDate(gdate: DateTime): DiscordianDate =\n\t## Convert a DateTime to a discordian date.\n\t## All the time fields are ignored.\n\n\t# Create the object.\n\tresult = DiscordianDate(isSaintTibsDay: gdate.isLeapDay)\n\n\t# The yearday field is unchanged.\n\tresult.yearday = gdate.yearday\n\n\t# The year is simply translated.\n\tresult.year = gdate.year - DiscordianOrigin\n\n\t# For remaining fields, we must take in account leap years.\n\tif not result.isSaintTibsDay:\n\t\tvar yearday = result.yearday\n\t\tif gdate.year.isLeapYear and result.yearday > 59:\n\t\t\tdec yearday\n\t\t# Now, we have simply to use division and modulo using the corrected yearday.\n\t\tresult.seasonZero = yearday div SeasonDayRange.high\n\t\tresult.seasondayZero = yearday mod SeasonDayRange.high\n\t\tresult.weekday = ErisianWeekDay(yearday mod 5)\n\n\nproc `$`(date: DiscordianDate): string =\n\t## Convert a discordian date to a string.\n\tif date.isSaintTibsDay:\n\t\tresult = SaintTibsDay\n\telse:\n\t\tresult = fmt\"{date.weekday}, {Season(date.seasonZero + 1)} {date.seasondayZero + 1}\"\n\tresult &= fmt\", {date.year} YOLD\"\n\n\nproc showDiscordianDate(year, month, day: Natural) =\n\t## Show the discordian date corresponding to a gregorian date.\n\tlet gdate = initDateTime(year = year, month = Month(month), monthday = day,\n\t\t\t\t\t\t\t\t\t\t\t\t\t hour = 0, minute = 0, second = 0)\n\techo gdate.format(\"YYYY-MM-dd\"), \": \", $gdate.toDiscordianDate()\n\n\nshowDiscordianDate(2100, 12, 31)\nshowDiscordianDate(2012, 02, 28)\nshowDiscordianDate(2012, 02, 29)\nshowDiscordianDate(2012, 03, 01)\nshowDiscordianDate(2010, 07, 22)\nshowDiscordianDate(2012, 09, 02)\nshowDiscordianDate(2012, 12, 31)\n" + }, + { + "id": 813, + "length": 2086, + "source": "Rosetta Code", + "text": "import locks\nimport os\nimport random\nimport strformat\n\nconst\n\tNWorkers = 3 # Number of workers.\n\tNTasks = 4 # Number of tasks.\n\tStopOrder = 0 # Order 0 is the request to stop.\n\nvar\n\trandLock: Lock # Lock to access random number generator.\n\torders: array[1..NWorkers, Channel[int]] # Channel to send orders to workers.\n\tresponses: Channel[int] # Channel to receive responses from workers.\n\tworking: int # Current number of workers actually working.\n\tthreads: array[1..NWorkers, Thread[int]] # Array of running threads.\n\n\nproc worker(num: int) {.thread.} =\n\t## Worker thread.\n\n\twhile true:\n\t\t# Wait for order from main thread (this is the checkpoint).\n\t\tlet order = orders[num].recv\n\t\tif order == StopOrder: break\n\t\t# Get a random time to complete the task.\n\t\tvar time: int\n\t\twithLock(randLock): time = rand(200..1000)\n\t\techo fmt\"Worker {num}: starting task number {order}\"\n\t\t# Work on task during \"time\" ms.\n\t\tsleep(time)\n\t\techo fmt\"Worker {num}: task number {order} terminated after {time} ms\"\n\t\t# Send message to indicate that the task is terminated.\n\t\tresponses.send(num)\n\n\n# Initializations.\nrandomize()\nrandLock.initLock()\nfor num in 1..NWorkers:\n\torders[num].open()\nresponses.open()\n\n# Create the worker threads.\nfor num in 1..NWorkers:\n\tcreateThread(threads[num], worker, num)\n\n# Send orders and wait for responses.\nfor task in 1..NTasks:\n\techo fmt\"Sending order to start task number {task}\"\n\t# Send order (task number) to workers.\n\tfor num in 1..NWorkers:\n\t\torders[num].send(task)\n\tworking = NWorkers # All workers are now working.\n\t# Wait to receive responses from workers.\n\twhile working > 0:\n\t\tdiscard responses.recv() # Here, we don't care about the message content.\n\t\tdec working\n\n# We have terminated: send stop order to workers.\necho \"Sending stop order to workers.\"\nfor num in 1..NWorkers:\n\torders[num].send(StopOrder)\njoinThreads(threads)\necho \"All workers stopped.\"\n\n# Clean up.\nfor num in 1..NWorkers:\n\torders[num].close()\nresponses.close()\ndeinitLock(randLock)\n" + }, + { + "id": 814, + "length": 1051, + "source": "Rosetta Code", + "text": "import math\n\ntype Circle = tuple[x, y, r: float]\n\nproc solveApollonius(c1, c2, c3: Circle; s1, s2, s3: float): Circle =\n\tlet\n\t\tv11 = 2*c2.x - 2*c1.x\n\t\tv12 = 2*c2.y - 2*c1.y\n\t\tv13 = c1.x*c1.x - c2.x*c2.x + c1.y*c1.y - c2.y*c2.y - c1.r*c1.r + c2.r*c2.r\n\t\tv14 = 2*s2*c2.r - 2*s1*c1.r\n\n\t\tv21 = 2*c3.x - 2*c2.x\n\t\tv22 = 2*c3.y - 2*c2.y\n\t\tv23 = c2.x*c2.x - c3.x*c3.x + c2.y*c2.y - c3.y*c3.y - c2.r*c2.r + c3.r*c3.r\n\t\tv24 = 2*s3*c3.r - 2*s2*c2.r\n\n\t\tw12 = v12/v11\n\t\tw13 = v13/v11\n\t\tw14 = v14/v11\n\n\t\tw22 = v22/v21-w12\n\t\tw23 = v23/v21-w13\n\t\tw24 = v24/v21-w14\n\n\t\tp = -w23/w22\n\t\tq = w24/w22\n\t\tm = -w12*p-w13\n\t\tn = w14 - w12*q\n\n\t\ta = n*n + q*q - 1\n\t\tb = 2*m*n - 2*n*c1.x + 2*p*q - 2*q*c1.y + 2*s1*c1.r\n\t\tc = c1.x*c1.x + m*m - 2*m*c1.x + p*p + c1.y*c1.y - 2*p*c1.y - c1.r*c1.r\n\n\t\td = b*b-4*a*c\n\t\trs = (-b-sqrt(d))/(2*a)\n\n\t\txs = m+n*rs\n\t\tys = p+q*rs\n\n\treturn (xs, ys, rs)\n\nlet\n\tc1: Circle = (0.0, 0.0, 1.0)\n\tc2: Circle = (4.0, 0.0, 1.0)\n\tc3: Circle = (2.0, 4.0, 2.0)\n\necho solveApollonius(c1, c2, c3, 1.0, 1.0, 1.0)\necho solveApollonius(c1, c2, c3, -1.0, -1.0, -1.0)\n" + }, + { + "id": 815, + "length": 1724, + "source": "Rosetta Code", + "text": "import gtk2, glib2, strutils, random\n\nvar valu: int = 0\n\nproc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} =\n\tmain_quit()\n\nrandomize()\nnim_init()\nvar win = window_new(gtk2.WINDOW_TOPLEVEL)\nvar content = vbox_new(true,10)\nvar hbox1 = hbox_new(true,10)\nvar hbox2 = hbox_new(false,1)\nvar lbl = label_new(\"Value:\")\nvar entry_fld = entry_new()\nentry_fld.set_text(\"0\")\nvar btn_quit = button_new(\"Quit\")\nvar btn_inc = button_new(\"Increment\")\nvar btn_rnd = button_new(\"Random\")\nadd(hbox2,lbl)\nadd(hbox2,entry_fld)\nadd(hbox1,btn_inc)\nadd(hbox1,btn_rnd)\npack_start(content, hbox2, true, true, 0)\npack_start(content, hbox1, true, true, 0)\npack_start(content, btn_quit, true, true, 0)\nset_border_width(win, 5)\nadd(win, content)\n\nproc on_question_clicked: bool =\n\tvar dialog = win.message_dialog_new(0, MESSAGE_QUESTION,\n\t\tBUTTONS_YES_NO, \"Use a Random number?\")\n\tvar response = dialog.run()\n\tresult = response == RESPONSE_YES\n\tdialog.destroy()\n\nproc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =\n\tinc(valu)\n\tentry_fld.set_text($valu)\n\nproc thisRnd(widget: PWidget, data: Pgpointer){.cdecl.} =\n\tif on_question_clicked():\n\t\tvalu = rand(20)\n\t\tentry_fld.set_text($valu)\n\nproc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} =\n\ttry:\n\t\tvalu = parseInt($entry_fld.get_text())\n\texcept ValueError:\n\t\tentry_fld.set_text($valu)\n\ndiscard signal_connect(win, \"destroy\", SIGNAL_FUNC(thisDestroy), nil)\ndiscard signal_connect(btn_quit, \"clicked\", SIGNAL_FUNC(thisDestroy), nil)\ndiscard signal_connect(btn_inc, \"clicked\", SIGNAL_FUNC(thisInc), nil)\ndiscard signal_connect(btn_rnd, \"clicked\", SIGNAL_FUNC(thisRnd), nil)\ndiscard signal_connect(entry_fld, \"changed\", SIGNAL_FUNC(thisTextChanged), nil)\n\nwin.show_all()\nmain()\n" + }, + { + "id": 816, + "length": 2214, + "source": "Rosetta Code", + "text": "import random, strutils\nimport gintro/[glib, gobject, gtk, gio]\n\ntype Context = ref object\n\tvalue: int\n\tentry: Entry\n\n\nproc onQuestionClicked(): bool =\n\n\t# As \"gintro\" doesn't provide \"MessageDialog\" yet, we will use a simple dialog.\n\tlet dialog = newDialog()\n\tdialog.setModal(true)\n\tlet label = newLabel(\"Use a Random number?\")\n\tdialog.contentArea.add(label)\n\tdiscard dialog.addButton(\"No\", ord(ResponseType.no))\n\tdiscard dialog.addButton(\"Yes\", ord(ResponseType.yes))\n\tdialog.showAll()\n\tresult = dialog.run() == ord(ResponseType.yes)\n\tdialog.destroy()\n\n\nproc onQuit(button: Button; window: ApplicationWindow) =\n\twindow.destroy()\n\n\nproc onIncr(button: Button; ctx: Context) =\n\tinc ctx.value\n\tctx.entry.setText($ctx.value)\n\n\nproc onRand(button: Button; ctx: Context) =\n\tif onQuestionClicked():\n\t\tctx.value = rand(20)\n\t\tctx.entry.setText($ctx.value)\n\n\nproc onEntryChange(entry: Entry; ctx: Context) =\n\ttry:\n\t\tctx.value = entry.text().parseInt()\n\texcept ValueError:\n\t\tentry.setText($ctx.value)\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"Component interaction\")\n\n\tlet content = newBox(Orientation.vertical, 10)\n\tcontent.setHomogeneous(true)\n\tlet hbox1 = newBox(Orientation.horizontal, 10)\n\thbox1.setHomogeneous(true)\n\tlet hbox2 = newBox(Orientation.horizontal, 1)\n\thbox2.setHomogeneous(false)\n\tlet label = newLabel(\"Value:\")\n\tlet entry = newEntry()\n\tentry.setText(\"0\")\n\tlet btnQuit = newButton(\"Quit\")\n\tlet btnIncr = newButton(\"Increment\")\n\tlet btnRand = newButton(\"Random\")\n\n\thbox2.add(label)\n\thbox2.add(entry)\n\thbox1.add(btnIncr)\n\thbox1.add(btnRand)\n\n\tcontent.packStart(hbox2, true, true, 0)\n\tcontent.packStart(hbox1, true, true, 0)\n\tcontent.packStart(btnQuit, true, true, 0)\n\n\twindow.setBorderWidth(5)\n\twindow.add(content)\n\n\tlet context = Context(value: 0, entry: entry)\n\n\tdiscard btnQuit.connect(\"clicked\", onQuit, window)\n\tdiscard btnIncr.connect(\"clicked\", onIncr, context)\n\tdiscard btnRand.connect(\"clicked\", onRand, context)\n\tdiscard entry.connect(\"changed\", onEntryChange, context)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"ComponentInteraction\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 817, + "length": 1627, + "source": "Rosetta Code", + "text": "import gtk2, strutils, glib2\n\nvar valu: int = 0\n\nproc thisDestroy(widget: PWidget, data: Pgpointer){.cdecl.} =\n\tmain_quit()\n\nnim_init()\nvar window = window_new(gtk2.WINDOW_TOPLEVEL)\nvar content = vbox_new(true,10)\nvar hbox1 = hbox_new(true,10)\nvar entry_fld = entry_new()\nentry_fld.set_text(\"0\")\nvar btn_quit = button_new(\"Quit\")\nvar btn_inc = button_new(\"Increment\")\nvar btn_dec = button_new(\"Decrement\")\nadd(hbox1,btn_inc)\nadd(hbox1,btn_dec)\npack_start(content, entry_fld, true, true, 0)\npack_start(content, hbox1, true, true, 0)\npack_start(content, btn_quit, true, true, 0)\nset_border_width(window, 5)\nadd(window, content)\n\nproc thisCheckBtns =\n\t set_sensitive(btn_inc, valu < 10)\n\t set_sensitive(btn_dec, valu > 0)\n\t set_sensitive(entry_fld, valu == 0)\n\nproc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =\n\tinc(valu)\n\tentry_fld.set_text($valu)\n\tthisCheckBtns()\n\nproc thisDec(widget: PWidget, data: Pgpointer){.cdecl.} =\n\tdec(valu)\n\tentry_fld.set_text($valu)\n\tthisCheckBtns()\n\nproc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} =\n\ttry:\n\t\t valu = parseInt($entry_fld.get_text())\n\texcept ValueError:\n\t\t entry_fld.set_text($valu)\n\tthisCheckBtns()\n\ndiscard signal_connect(window, \"destroy\",\n\t\t\t\t\t\t\t\t\t SIGNAL_FUNC(thisDestroy), nil)\ndiscard signal_connect(btn_quit, \"clicked\",\n\t\t\t\t\t\t\t\t\t SIGNAL_FUNC(thisDestroy), nil)\ndiscard signal_connect(btn_inc, \"clicked\",\n\t\t\t\t\t\t\t\t\t SIGNAL_FUNC(thisInc), nil)\ndiscard signal_connect(btn_dec, \"clicked\",\n\t\t\t\t\t\t\t\t\t SIGNAL_FUNC(thisDec), nil)\ndiscard signal_connect(entry_fld, \"changed\",\n\t\t\t\t\t\t\t\t\t SIGNAL_FUNC(thisTextChanged), nil)\n\nshow_all(window)\nthisCheckBtns()\nmain()\n" + }, + { + "id": 818, + "length": 2013, + "source": "Rosetta Code", + "text": "import strutils\nimport gintro/[glib, gobject, gtk, gio]\n\ntype Context = ref object\n\tvalue: int\n\tentry: Entry\n\tbtnIncr: Button\n\tbtnDecr: Button\n\n\nproc checkButtons(ctx: Context) =\n\tctx.btnIncr.setSensitive(ctx.value < 10)\n\tctx.btnDecr.setSensitive(ctx.value > 0)\n\tctx.entry.setSensitive(ctx.value == 0)\n\n\nproc onQuit(button: Button; window: ApplicationWindow) =\n\twindow.destroy()\n\n\nproc onIncr(button: Button; ctx: Context) =\n\tinc ctx.value\n\tctx.entry.setText($ctx.value)\n\tctx.checkButtons()\n\n\nproc onDecr(button: Button; ctx: Context) =\n\tdec ctx.value\n\tctx.entry.setText($ctx.value)\n\tctx.checkButtons()\n\n\nproc onEntryChange(entry: Entry; ctx: Context) =\n\ttry:\n\t\tctx.value = entry.text().parseInt()\n\texcept ValueError:\n\t\tentry.setText($ctx.value)\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"GUI controls\")\n\n\tlet content = newBox(Orientation.vertical, 10)\n\tcontent.setHomogeneous(true)\n\tlet hbox1 = newBox(Orientation.horizontal, 10)\n\thbox1.setHomogeneous(true)\n\tlet hbox2 = newBox(Orientation.horizontal, 1)\n\thbox2.setHomogeneous(false)\n\tlet label = newLabel(\"Value:\")\n\tlet entry = newEntry()\n\tentry.setText(\"0\")\n\tlet btnQuit = newButton(\"Quit\")\n\tlet btnIncr = newButton(\"Increment\")\n\tlet btnDecr = newButton(\"Decrement\")\n\n\thbox2.add(label)\n\thbox2.add(entry)\n\thbox1.add(btnIncr)\n\thbox1.add(btnDecr)\n\n\tcontent.packStart(hbox2, true, true, 0)\n\tcontent.packStart(hbox1, true, true, 0)\n\tcontent.packStart(btnQuit, true, true, 0)\n\n\twindow.setBorderWidth(5)\n\twindow.add(content)\n\n\tlet context = Context(value: 0, entry: entry, btnIncr: btnIncr, btnDecr: btnDecr)\n\n\tdiscard btnQuit.connect(\"clicked\", onQuit, window)\n\tdiscard btnIncr.connect(\"clicked\", onIncr, context)\n\tdiscard btnDecr.connect(\"clicked\", onDecr, context)\n\tdiscard entry.connect(\"changed\", onEntryChange, context)\n\n\tcontext.checkButtons()\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"GuiControls\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 819, + "length": 1011, + "source": "Rosetta Code", + "text": "import macros\n\nproc newIfElse(c, t, e: NimNode): NimNode {.compiletime.} =\n\tresult = newIfStmt((c, t))\n\tresult.add(newNimNode(nnkElse).add(e))\n\nmacro if2(x, y: bool; z: untyped): untyped =\n\tvar parts: array[4, NimNode]\n\tfor i in parts.low .. parts.high:\n\t\tparts[i] = newNimNode(nnkDiscardStmt).add(NimNode(nil))\n\n\tassert z.kind == nnkStmtList\n\tassert z.len <= 4\n\n\tfor i in 0 ..< z.len:\n\t\tassert z[i].kind == nnkCall\n\t\tassert z[i].len == 2\n\n\t\tvar j = 0\n\n\t\tcase $z[i][0]\n\t\tof \"then\": j = 0\n\t\tof \"else1\": j = 1\n\t\tof \"else2\": j = 2\n\t\tof \"else3\": j = 3\n\t\telse: assert false\n\n\t\tparts[j] = z[i][1].last\n\n\tresult = newIfElse(x,\n\t\tnewIfElse(y, parts[0], parts[1]),\n\t\tnewIfElse(y, parts[2], parts[3]))\n\nif2 2 > 1, 3 < 2:\n\tthen:\n\t\techo \"1\"\n\telse1:\n\t\techo \"2\"\n\telse2:\n\t\techo \"3\"\n\telse3:\n\t\techo \"4\"\n\n# Missing cases are supported:\nif2 2 > 1, 3 < 2:\n\tthen:\n\t\techo \"1\"\n\telse2:\n\t\techo \"3\"\n\telse3:\n\t\techo \"4\"\n\n# Order can be swapped:\nif2 2 > 1, 3 < 2:\n\tthen:\n\t\techo \"1\"\n\telse2:\n\t\techo \"3\"\n\telse1:\n\t\techo \"2\"\n\telse3:\n\t\techo \"4\"\n" + }, + { + "id": 820, + "length": 779, + "source": "Rosetta Code", + "text": "import sets, strutils, algorithm\n\nproc primes(n: int64): seq[int64] =\n\tvar multiples: HashSet[int64]\n\tfor i in 2..n:\n\t\tif i notin multiples:\n\t\t\tresult.add i\n\t\t\tfor j in countup(i*i, n, i.int):\n\t\t\t\tmultiples.incl j\n\nproc truncatablePrime(n: int64): tuple[left, right: int64] =\n\tvar\n\t\tprimelist: seq[string]\n\tfor x in primes(n):\n\t\tprimelist.add($x)\n\treverse primelist\n\tvar primeset = primelist.toHashSet\n\tfor n in primelist:\n\t\tvar alltruncs: HashSet[string]\n\t\tfor i in 0..n.high:\n\t\t\talltruncs.incl n[i..n.high]\n\t\tif alltruncs <= primeset:\n\t\t\tresult.left = parseInt(n)\n\t\t\tbreak\n\tfor n in primelist:\n\t\tvar alltruncs: HashSet[string]\n\t\tfor i in 0..n.high:\n\t\t\talltruncs.incl n[0..i]\n\t\tif alltruncs <= primeset:\n\t\t\tresult.right = parseInt(n)\n\t\t\tbreak\n\necho truncatablePrime(1000000i64)\n" + }, + { + "id": 821, + "length": 917, + "source": "Rosetta Code", + "text": "import times\n\nimport opengl\nimport opengl/glut\n\nconst\n\tW = 320\n\tH = 240\n\tSLen = W * H div sizeof(int)\n\nvar\n\tframe = 0\n\tbits: array[SLen, uint]\n\tlast, start: Time\n\n\nproc render() {.cdecl.} =\n\t## Render the window.\n\n\tvar r = bits[0] + 1\n\tfor i in countdown(bits.high, 0):\n\t\tr *= 1103515245\n\t\tbits[i] = r xor bits[i] shr 16\n\n\tglClear(GL_COLOR_BUFFER_BIT)\n\tglBitmap(W, H, 0, 0, 0, 0, cast[ptr GLubyte](bits.addr))\n\tglFlush()\n\n\tinc frame\n\tif (frame and 15) == 0:\n\t\tlet t = getTime()\n\t\tif t > last:\n\t\t\tlast = t\n\t\t\techo \"fps: \", frame.float / (t - start).inSeconds.float\n\n\nproc initGfx(argc: ptr cint; argv: pointer) =\n\t## Initialize OpenGL rendering.\n\n\tglutInit(argc, argv)\n\tglutInitDisplayMode(GLUT_RGB)\n\tglutInitWindowSize(W, H)\n\tglutIdleFunc(render)\n\tdiscard glutCreateWindow(\"Noise\")\n\tglutDisplayFunc(render)\n\tloadExtensions()\n\n\nvar argc: cint = 0\ninitGfx(addr(argc), nil)\nstart = getTime()\nlast = start\nglutMainLoop()\n" + }, + { + "id": 822, + "length": 702, + "source": "Rosetta Code", + "text": "import random\n\nimport rapid/gfx\n\nvar\n\twindow = initRWindow()\n\t\t.size(320, 240)\n\t\t.title(\"image noise\")\n\t\t.open()\n\tsurface = window.openGfx()\n\nlet\n\tnoiseShader = surface.newRProgram(RDefaultVshSrc, \"\"\"\n\t\tuniform float time;\n\n\t\tfloat rand(vec2 pos) {\n\t\t\treturn fract(sin(dot(pos.xy + time, vec2(12.9898,78.233))) * 43758.5453123);\n\t\t}\n\n\t\tvec4 rFragment(vec4 col, sampler2D tex, vec2 pos, vec2 uv) {\n\t\t\treturn vec4(vec3(step(0.5, rand(uv))), 1.0);\n\t\t}\n\t\"\"\")\n\nsurface.vsync = false\nsurface.loop:\n\tdraw ctx, step:\n\t\tnoiseShader.uniform(\"time\", time())\n\t\tctx.program = noiseShader\n\t\tctx.begin()\n\t\tctx.rect(0, 0, surface.width, surface.height)\n\t\tctx.draw()\n\t\techo 1 / (step / 60)\n\tupdate step:\n\t\tdiscard step\n" + }, + { + "id": 823, + "length": 1042, + "source": "Rosetta Code", + "text": "import tables, options\n\ntype\n\tMyTable = object\n\t\ttable: TableRef[string, int]\n\n# return empty if the key is not available\nproc `[]`(m: MyTable, key: string): Option[int] =\n\tif key in m.table: result = some m.table[key]\n\telse: result = none int\n\n# update an item, doing nothing if the key is available during first initialization\nproc `[]=`(m: var MyTable, key: string, val: int) =\n\tif key notin m.table: return\n\tm.table[key] = val\n\nproc reset(m: var MyTable) =\n\tfor _, v in m.table.mpairs: v = 0\n\n# sugar for defining MyTable object\nproc toTable(vals: openarray[(string, int)]): MyTable =\n\tresult.table = newTable vals\n\nproc main =\n\t# MyTable construction\n\tvar myobj = {\"key1\": 1, \"key2\": 2, \"key3\": 3}.toTable\n\t# test getting existing key\n\tlet val1 = myobj[\"key1\"]\n\tif val1.isSome: echo \"val1: \", val1.get\n\n\t# test adding new key\n\tmyobj[\"key4\"] = 4\n\tlet val4 = myobj[\"key4\"]\n\tif val4.isSome: echo val4.get\n\telse: echo \"val4 is empty\"\n\n\t# test reset and test whether its value is zero-ed\n\treset myobj\n\tdoAssert myobj[\"key3\"].get == 0\n\nmain()\n" + }, + { + "id": 824, + "length": 1188, + "source": "Rosetta Code", + "text": "import strformat\nimport math\n\nconst N = 32\nconst N2 = N * (N - 1) div 2\nconst STEP = 0.05\n\nvar xval = newSeq[float](N)\nvar tsin = newSeq[float](N)\nvar tcos = newSeq[float](N)\nvar ttan = newSeq[float](N)\nvar rsin = newSeq[float](N2)\nvar rcos = newSeq[float](N2)\nvar rtan = newSeq[float](N2)\n\nproc rho(x, y: openArray[float], r: var openArray[float], i, n: int): float =\n\tif n < 0:\n\t\treturn 0\n\tif n == 0:\n\t\treturn y[i]\n\n\tlet idx = (N - 1 - n) * (N - n) div 2 + i\n\tif r[idx] != r[idx]:\n\t\tr[idx] = (x[i] - x[i + n]) /\n\t\t\t(rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) +\n\t\t\t rho(x, y, r, i + 1, n - 2)\n\treturn r[idx]\n\nproc thiele(x, y: openArray[float], r: var openArray[float], xin: float, n: int): float =\n\tif n > N - 1:\n\t\treturn 1\n\treturn rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) +\n\t\t(xin - x[n]) / thiele(x, y, r, xin, n + 1)\n\nfor i in 0.. 1:\n\t\techo \"\\nThe compile order for top levels $# is...\" % topList.mapIt(\"\" & it & \"\").join(\" and \")\n\t\tprintOrder Data.topx(tops)\n" + }, + { + "id": 827, + "length": 979, + "source": "Rosetta Code", + "text": "import strformat\nimport gintro/[glib, gobject, gtk, gio]\nimport gintro/gdk except Window\n\n\nproc onKeyPress(window: ApplicationWindow; event: Event; label: Label): bool =\n\tvar keyval: int\n\tif not event.getKeyval(keyval): return false\n\tif keyval in [ord('n'), ord('y')]:\n\t\tlabel.setText(\"You pressed key '{chr(keyval)}'\")\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"Y/N response\")\n\n\tlet hbox = newBox(Orientation.horizontal, 0)\n\twindow.add(hbox)\n\tlet vbox = newBox(Orientation.vertical, 10)\n\thbox.packStart(vbox, true, true, 20)\n\n\tlet label1 = newLabel(\" Press 'y' or 'n' key \")\n\tvbox.packStart(label1, true, true, 5)\n\n\tlet label2 = newLabel()\n\tvbox.packStart(label2, true, true, 5)\n\n\tdiscard window.connect(\"key-press-event\", onKeyPress, label2)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"YNResponse\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 828, + "length": 592, + "source": "Rosetta Code", + "text": "import random, strutils\n\nrandomize()\n\nlet iRange = 1..100\n\necho \"Guess my target number that is between \", iRange.a, \" and \", iRange.b, \" (inclusive).\"\nlet target = rand(iRange)\nvar answer, i = 0\nwhile answer != target:\n\tinc i\n\tstdout.write \"Your guess \", i, \": \"\n\tlet txt = stdin.readLine()\n\ttry: answer = parseInt(txt)\n\texcept ValueError:\n\t\techo \" I don't understand your input of '\", txt, \"'\"\n\t\tcontinue\n\tif answer notin iRange: echo \" Out of range!\"\n\telif answer < target: echo \" Too low.\"\n\telif answer > target: echo \" Too high.\"\n\telse: echo \" Ye-Haw!!\"\n\necho \"Thanks for playing.\"\n" + }, + { + "id": 829, + "length": 819, + "source": "Rosetta Code", + "text": "import strutils\n\nlet oRange = 1..10\nvar iRange = oRange\n\necho \"\"\"Think of a number between $# and $# and wait for me to guess it.\nOn every guess of mine you should state whether the guess was\ntoo high, too low, or equal to your number by typing h, l, or =\"\"\".format(iRange.a, iRange.b)\n\nvar i = 0\nwhile true:\n\tinc i\n\tlet guess = (iRange.a + iRange.b) div 2\n\tstdout.write \"Guess $# is: $#. The score for which is (h,l,=): \".format(i, guess)\n\tlet txt = stdin.readLine()\n\n\tcase txt\n\tof \"h\": iRange.b = guess - 1\n\tof \"l\": iRange.a = guess + 1\n\tof \"=\":\n\t\techo \" Ye-Haw!!\"\n\t\tbreak\n\telse: echo \" I don't understand your input of '%s'?\".format(txt)\n\n\tif iRange.a > iRange.b or iRange.a < oRange.a or iRange.b > oRange.b:\n\t\techo \"Please check your scoring as I cannot find the value\"\n\t\tbreak\n\necho \"Thanks for keeping score.\"\n" + }, + { + "id": 830, + "length": 974, + "source": "Rosetta Code", + "text": "import strutils\n\nproc commentStripper(txt: string; delim: tuple[l, r: string] = (\"/*\", \"*/\")): string =\n\tlet i = txt.find(delim.l)\n\tif i < 0: return txt\n\n\tresult = if i > 0: txt[0 ..< i] else: \"\"\n\tlet tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)\n\tlet j = tmp.find(delim.r)\n\tassert j >= 0\n\tresult &= tmp[j+delim.r.len .. tmp.high]\n\necho \"NON-NESTED BLOCK COMMENT EXAMPLE:\"\necho commentStripper(\"\"\"/**\n\t * Some comments\n\t * longer comments here that we can parse.\n\t *\n\t * Rahoo\n\t */\n\t function subroutine() {\n\t\ta = /* inline comment */ b + c ;\n\t }\n\t /*/ <-- tricky comments */\n\n\t /**\n\t\t* Another comment.\n\t\t*/\n\t\tfunction something() {\n\t\t}\"\"\")\n\necho \"\\nNESTED BLOCK COMMENT EXAMPLE:\"\necho commentStripper(\"\"\" /**\n\t * Some comments\n\t * longer comments here that we can parse.\n\t *\n\t * Rahoo\n\t *//*\n\t function subroutine() {\n\t\ta = /* inline comment */ b + c ;\n\t }\n\t /*/ <-- tricky comments */\n\t */\n\t /**\n\t\t* Another comment.\n\t\t*/\n\t\tfunction something() {\n\t\t}\"\"\")\n" + }, + { + "id": 831, + "length": 699, + "source": "Rosetta Code", + "text": "type Iterator = iterator(): int\n\nproc `^`*(base: Natural; exp: Natural): int =\n\tvar (base, exp) = (base, exp)\n\tresult = 1\n\twhile exp != 0:\n\t\tif (exp and 1) != 0:\n\t\t\tresult *= base\n\t\texp = exp shr 1\n\t\tbase *= base\n\nproc next(s: Iterator): int =\n\tfor n in s(): return n\n\nproc powers(m: Natural): Iterator =\n\titerator it(): int {.closure.} =\n\t\tfor n in 0 ..< int.high:\n\t\t\tyield n ^ m\n\tresult = it\n\niterator filtered(s1, s2: Iterator): int =\n\tvar v = next(s1)\n\tvar f = next(s2)\n\twhile true:\n\t\tif v > f:\n\t\t\tf = next(s2)\n\t\t\tcontinue\n\t\telif v < f:\n\t\t\tyield v\n\t\tv = next(s1)\n\nvar\n\tsquares = powers(2)\n\tcubes = powers(3)\n\ti = 1\nfor x in filtered(squares, cubes):\n\tif i > 20: echo x\n\tif i >= 30: break\n\tinc i\n" + }, + { + "id": 832, + "length": 1029, + "source": "Rosetta Code", + "text": "import asyncnet, asyncdispatch\n\ntype\n\tClient = tuple\n\t\tsocket: AsyncSocket\n\t\tname: string\n\t\tconnected: bool\n\nvar clients {.threadvar.}: seq[Client]\n\nproc sendOthers(client: Client, line: string) {.async.} =\n\tfor c in clients:\n\t\tif c != client and c.connected:\n\t\t\tawait c.socket.send(line & \"\\c\\L\")\n\nproc processClient(socket: AsyncSocket) {.async.} =\n\tawait socket.send(\"Please enter your name: \")\n\tvar client: Client = (socket, await socket.recvLine(), true)\n\n\tclients.add(client)\n\tasyncCheck client.sendOthers(\"+++ \" & client.name & \" arrived +++\")\n\n\twhile true:\n\t\tlet line = await client.socket.recvLine()\n\t\tif line == \"\":\n\t\t\tasyncCheck client.sendOthers(\"--- \" & client.name & \" leaves ---\")\n\t\t\tclient.connected = false\n\t\t\treturn\n\t\tasyncCheck client.sendOthers(client.name & \"> \" & line)\n\nproc serve() {.async.} =\n\tclients = @[]\n\tvar server = newAsyncSocket()\n\tserver.bindAddr(Port(4004))\n\tserver.listen()\n\n\twhile true:\n\t\tlet socket = await server.accept()\n\t\tasyncCheck processClient(socket)\n\nasyncCheck serve()\nrunForever()\n" + }, + { + "id": 833, + "length": 936, + "source": "Rosetta Code", + "text": "import times\nimport sequtils\nimport strutils\nimport random\n\nproc count(s1, s2: string): int =\n\t\tfor i, c in s1:\n\t\t\t\tif c == s2[i]:\n\t\t\t\t\t\tresult.inc\n\nproc shuffle(str: string): string =\n\t\tvar r = initRand(getTime().toUnix())\n\t\tvar chrs = toSeq(str.items)\n\t\tfor i in 0 ..< chrs.len:\n\t\t\t\tlet chosen = r.rand(chrs.len-1)\n\t\t\t\tswap(chrs[i], chrs[chosen])\n\t\treturn chrs.join(\"\")\n\nproc bestShuffle(str: string): string =\n\t\tvar chrs = toSeq(shuffle(str).items)\n\t\tfor i in chrs.low .. chrs.high:\n\t\t\t\tif chrs[i] != str[i]:\n\t\t\t\t\t\tcontinue\n\t\t\t\tfor j in chrs.low .. chrs.high:\n\t\t\t\t\t\tif chrs[i] != chrs[j] and chrs[i] != str[j] and chrs[j] != str[i]:\n\t\t\t\t\t\t\t\tswap(chrs[i], chrs[j])\n\t\t\t\t\t\t\t\tbreak\n\t\treturn chrs.join(\"\")\n\nwhen isMainModule:\n\t\tlet words = @[\"abracadabra\", \"seesaw\", \"grrrrrr\", \"pop\", \"up\", \"a\", \"antidisestablishmentarianism\"];\n\t\tfor w in words:\n\t\t\t\tlet shuffled = bestShuffle(w)\n\t\t\t\techo \"$1 $2 $3\" % [w, shuffled, $count(w, shuffled)]\n" + }, + { + "id": 834, + "length": 769, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\nrandomize()\n\niterator randomCover[T](xs: openarray[T]): T =\n\tvar js = toSeq 0..xs.high\n\tfor i in countdown(js.high, 0):\n\t\tlet j = random(i)\n\t\tswap(js[i], js[j])\n\tfor j in js:\n\t\tyield xs[j]\n\nconst\n\tw = 14\n\th = 10\n\nvar\n\tvis = newSeqWith(h, newSeq[bool](w))\n\thor = newSeqWith(h+1, newSeqWith(w, \"+---\"))\n\tver = newSeqWith(h, newSeqWith(w, \"| \") & \"|\")\n\nproc walk(x, y: int) =\n\tvis[y][x] = true\n\tfor p in [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover:\n\t\tif p[0] notin 0 ..< w or p[1] notin 0 ..< h or vis[p[1]][p[0]]: continue\n\t\tif p[0] == x: hor[max(y, p[1])][x] = \"+ \"\n\t\tif p[1] == y: ver[y][max(x, p[0])] = \" \"\n\t\twalk p[0], p[1]\n\nwalk rand(0.. 0 and maze.cells[r-1][c] == '\\0':\n\t\t\t\tmaze.hwalls[r][c] = chr(0)\n\t\t\t\tmaze.gen(r-1, c)\n\t\tof Left:\n\t\t\tif c > 0 and maze.cells[r][c-1] == '\\0':\n\t\t\t\tmaze.vwalls[r][c] = chr(0)\n\t\t\t\tmaze.gen(r, c-1)\n\t\tof Down:\n\t\t\tif r < maze.cells.high and maze.cells[r+1][c] == '\\0':\n\t\t\t\tmaze.hwalls[r+1][c] = chr(0)\n\t\t\t\tmaze.gen(r+1, c)\n\t\tof Right:\n\t\t\tif c < maze.cells[0].high and maze.cells[r][c+1] == '\\0':\n\t\t\t\tmaze.vwalls[r][c+1] = chr(0)\n\t\t\t\tmaze.gen(r, c+1)\n\n\nproc gen(maze: var Maze) =\n\t## Generate a maze, choosing a random starting point.\n\tmaze.gen(rand(maze.cells.high), rand(maze.cells[0].high))\n\n\n# Maze solving.\n\nproc solve(maze: var Maze; ra, ca, rz, cz: Natural) =\n\t## Solve a maze by finding the path from point (ra, ca) to point (rz, cz).\n\n\tproc rsolve(maze: var Maze; r, c: Natural; dir: Direction): bool {.discardable.} =\n\t\t## Recursive solver.\n\n\t\tif r == rz and c == cz:\n\t\t\tmaze.cells[r][c] = 'F'\n\t\t\treturn true\n\n\t\tif dir != Down and maze.hwalls[r][c] == '\\0':\n\t\t\tif maze.rSolve(r-1, c, Up):\n\t\t\t\tmaze.cells[r][c] = '^'\n\t\t\t\tmaze.hwalls[r][c] = '^'\n\t\t\t\treturn true\n\n\t\tif dir != Up and r < maze.hwalls.high and maze.hwalls[r+1][c] == '\\0':\n\t\t\tif maze.rSolve(r+1, c, Down):\n\t\t\t\tmaze.cells[r][c] = 'v'\n\t\t\t\tmaze.hwalls[r+1][c] = 'v'\n\t\t\t\treturn true\n\n\t\tif dir != Left and c < maze.vwalls[0].high and maze.vwalls[r][c+1] == '\\0':\n\t\t\tif maze.rSolve(r, c+1, Right):\n\t\t\t\tmaze.cells[r][c] = '>'\n\t\t\t\tmaze.vwalls[r][c+1] = '>'\n\t\t\t\treturn true\n\n\t\tif dir != Right and maze.vwalls[r][c] == '\\0':\n\t\t\tif maze.rSolve(r, c-1, Left):\n\t\t\t\tmaze.cells[r][c] = '<'\n\t\t\t\tmaze.vwalls[r][c] = '<'\n\t\t\t\treturn true\n\n\n\tmaze.rsolve(ra, ca, None)\n\tmaze.cells[ra][ca] = 'S'\n\n\n# Maze display.\n\nfunc `$`(maze: Maze): string =\n\t## Return the string representation fo a maze.\n\n\tconst\n\t\tHWall = \"+---\"\n\t\tHOpen = \"+ \"\n\t\tVWall = \"| \"\n\t\tVOpen = \" \"\n\t\tRightCorner = \"+\\n\"\n\t\tRightWall = \"|\\n\"\n\n\tfor r, hw in maze.hwalls:\n\n\t\tfor h in hw:\n\t\t\tif h == '-' or r == 0:\n\t\t\t\tresult.add HWall\n\t\t\telse:\n\t\t\t\tresult.add HOpen\n\t\t\t\tif h notin {'-', '\\0'}: result[^2] = h\n\t\tresult.add RightCorner\n\n\t\tfor c, vw in maze.vwalls[r]:\n\t\t\tif vw == '|' or c == 0:\n\t\t\t\tresult.add VWall\n\t\t\telse:\n\t\t\t\tresult.add VOpen\n\t\t\t\tif vw notin {'|', '\\0'}: result[^4] = vw\n\t\t\tif maze.cells[r][c] != '\\0': result[^2] = maze.cells[r][c]\n\t\tresult.add RightWall\n\n\tfor _ in 1..maze.hwalls[0].len:\n\t\tresult.add HWall\n\tresult.add RightCorner\n\n\n\nwhen isMainModule:\n\n\tconst\n\t\tWidth = 8\n\t\tHeight = 8\n\n\trandomize()\n\tvar maze = initMaze(Width, Height)\n\tmaze.gen()\n\tvar ra, rz = rand(Width - 1)\n\tvar ca, cz = rand(Height - 1)\n\twhile rz == ra and cz == ca:\n\t\t# Make sur starting and ending points are different.\n\t\trz = rand(Width - 1)\n\t\tcz = rand(Height - 1)\n\tmaze.solve(ra, ca , rz, cz)\n\techo maze\n" + }, + { + "id": 836, + "length": 1318, + "source": "Rosetta Code", + "text": "import strformat, strutils, threadpool\n\nconst Numbers = [576460752303423487,\n\t\t\t\t\t\t\t\t 576460752303423487,\n\t\t\t\t\t\t\t\t 576460752303423487,\n\t\t\t\t\t\t\t\t 112272537195293,\n\t\t\t\t\t\t\t\t 115284584522153,\n\t\t\t\t\t\t\t\t 115280098190773,\n\t\t\t\t\t\t\t\t 115797840077099,\n\t\t\t\t\t\t\t\t 112582718962171,\n\t\t\t\t\t\t\t\t 299866111963290359]\n\n\nproc lowestFactor(n: int64): int64 =\n\tif n mod 2 == 0: return 2\n\tif n mod 3 == 0: return 3\n\tvar p = 5\n\tvar delta = 2\n\twhile p * p < n:\n\t\tif n mod p == 0: return p\n\t\tinc p, delta\n\t\tdelta = 6 - delta\n\tresult = n\n\n\nproc factors(n, lowest: int64): seq[int64] =\n\tvar n = n\n\tvar lowest = lowest\n\twhile true:\n\t\tresult.add lowest\n\t\tn = n div lowest\n\t\tif n == 1: break\n\t\tlowest = lowestFactor(n)\n\n\n# Launch a thread for each number to process.\nvar responses: array[Numbers.len, FlowVar[int64]]\nfor i, n in Numbers:\n\tresponses[i] = spawn lowestFactor(n)\n\n# Read the results and find the largest minimum prime factor.\nvar maxMinfact = 0i64\nvar maxIdx: int\nfor i in 0..responses.high:\n\tlet minfact = ^responses[i] # Blocking read.\n\techo \"For n = {Numbers[i]}, the lowest factor is {minfact}.\"\n\tif minfact > maxMinfact:\n\t\tmaxMinfact = minfact\n\t\tmaxIdx = i\nlet result = Numbers[maxIdx]\n\necho \"\"\necho \"The first number with the largest minimum prime factor is: \", result\necho \"Its factors are: \", result.factors(maxMinfact).join(\", \")\n" + }, + { + "id": 837, + "length": 1193, + "source": "Rosetta Code", + "text": "import sequtils, strutils, threadpool\n\n{.experimental: \"parallel\".}\n\nconst Numbers = [576460752303423487,\n\t\t\t\t\t\t\t\t 576460752303423487,\n\t\t\t\t\t\t\t\t 576460752303423487,\n\t\t\t\t\t\t\t\t 112272537195293,\n\t\t\t\t\t\t\t\t 115284584522153,\n\t\t\t\t\t\t\t\t 115280098190773,\n\t\t\t\t\t\t\t\t 115797840077099,\n\t\t\t\t\t\t\t\t 112582718962171,\n\t\t\t\t\t\t\t\t 299866111963290359]\n\n\nproc lowestFactor(n: int64): int64 =\n\tif n mod 2 == 0: return 2\n\tif n mod 3 == 0: return 3\n\tvar p = 5\n\tvar delta = 2\n\twhile p * p < n:\n\t\tif n mod p == 0: return p\n\t\tinc p, delta\n\t\tdelta = 6 - delta\n\tresult = n\n\n\nproc factors(n, lowest: int64): seq[int64] =\n\tvar n = n\n\tvar lowest = lowest\n\twhile true:\n\t\tresult.add lowest\n\t\tn = n div lowest\n\t\tif n == 1: break\n\t\tlowest = lowestFactor(n)\n\n\n# Launch the threads.\nvar results: array[Numbers.len, int64] # To store the results.\nparallel:\n\tfor i, n in Numbers:\n\t\tresults[i] = spawn lowestFactor(n)\n\n# Find the minimum prime factor and the first number with this minimum factor.\nlet maxIdx = results.maxIndex()\nlet maxMinfact = results[maxIdx]\nlet result = Numbers[maxIdx]\n\necho \"\"\necho \"The first number with the largest minimum prime factor is: \", result\necho \"Its factors are: \", result.factors(maxMinfact).join(\", \")\n" + }, + { + "id": 838, + "length": 687, + "source": "Rosetta Code", + "text": "var primes = newSeq[int]()\n\nproc getPrime(idx: int): int =\n\tif idx >= primes.len:\n\t\tif primes.len == 0:\n\t\t\tprimes.add 2\n\t\t\tprimes.add 3\n\n\t\tvar last = primes[primes.high]\n\t\twhile idx >= primes.len:\n\t\t\tlast += 2\n\t\t\tfor i, p in primes:\n\t\t\t\tif p * p > last:\n\t\t\t\t\tprimes.add last\n\t\t\t\t\tbreak\n\t\t\t\tif last mod p == 0:\n\t\t\t\t\tbreak\n\n\treturn primes[idx]\n\nfor x in 1 ..< int32.high.int:\n\tstdout.write x, \" = \"\n\tvar n = x\n\tvar first = true\n\n\tfor i in 0 ..< int32.high:\n\t\tlet p = getPrime(i)\n\t\twhile n mod p == 0:\n\t\t\tn = n div p\n\t\t\tif not first: stdout.write \" x \"\n\t\t\tfirst = false\n\t\t\tstdout.write p\n\n\t\tif n <= p * p:\n\t\t\tbreak\n\n\tif first > 0: echo n\n\telif n > 1: echo \" x \", n\n\telse: echo \"\"\n" + }, + { + "id": 839, + "length": 972, + "source": "Rosetta Code", + "text": "import osproc, strutils\n\nvar name = \"\"\nwhile name.len == 0:\n\tstdout.write \"Enter output file name (without extension): \"\n\tname = stdin.readLine().strip()\nname.add \".wav\"\n\nvar rate = 0\nwhile rate notin 2000..19_200:\n\tstdout.write \"Enter sampling rate in Hz (2000 to 192000): \"\n\ttry: rate = parseInt(stdin.readLine().strip())\n\texcept ValueError: discard\n\nvar duration = 0\nwhile duration notin 5..30:\n\tstdout.write \"Enter duration in seconds (5 to 30): \"\n\ttry: duration = parseInt(stdin.readLine().strip())\n\texcept ValueError: discard\n\necho \"OK, start speaking now...\"\n# Default arguments: -c 1, -t wav. Note that only signed 16 bit format is supported.\nlet args = [\"-r\", $rate, \"-f\", \"S16_LE\", \"-d\", $duration, name]\necho execProcess(\"arecord\", args = args, options = {poStdErrToStdOut, poUsePath})\n\necho \"'$1' created on disk and will now be played back...\" % name\necho execProcess(\"aplay\", args = [name], options = {poStdErrToStdOut, poUsePath})\necho \"Playback completed\"\n" + }, + { + "id": 840, + "length": 607, + "source": "Rosetta Code", + "text": "import sequtils\n\nfunc min(a, b, c: int): int {.inline.} = min(a, min(b, c))\n\nproc levenshteinDistance(s1, s2: string): int =\n\tvar (s1, s2) = (s1, s2)\n\n\tif s1.len > s2.len:\n\t\tswap s1, s2\n\n\tvar distances = toSeq(0..s1.len)\n\n\tfor i2, c2 in s2:\n\t\tvar newDistances = @[i2+1]\n\t\tfor i1, c1 in s1:\n\t\t\tif c1 == c2:\n\t\t\t\tnewDistances.add(distances[i1])\n\t\t\telse:\n\t\t\t\tnewDistances.add(1 + min(distances[i1], distances[i1+1], newDistances[newDistances.high]))\n\n\t\tdistances = newDistances\n\tresult = distances[distances.high]\n\necho levenshteinDistance(\"kitten\",\"sitting\")\necho levenshteinDistance(\"arthur\",\"raisethysword\")\n" + }, + { + "id": 841, + "length": 1051, + "source": "Rosetta Code", + "text": "func radixSort[T](a: openArray[T]): seq[T] =\n\n\tresult = @a\n\n\t## Loop for every bit in the integers.\n\tfor shift in countdown(63, 0):\n\t\tvar tmp = newSeq[T](result.len) # The array to put the partially sorted array into.\n\t\tvar j = 0 # The number of 0s.\n\t\tfor i in 0..result.high:\n\t\t\t# If there is a 1 in the bit we are testing, the number will be negative.\n\t\t\tlet move = result[i] shl shift >= 0\n\t\t\t# If this is the last bit, negative numbers are actually lower.\n\t\t\tlet toBeMoved = if shift == 0: not move else: move\n\t\t\tif toBeMoved:\n\t\t\t\ttmp[j] = result[i]\n\t\t\t\tinc j\n\t\t\telse:\n\t\t\t\t# It's a 1, so stick it in the result array for now.\n\t\t\t\tresult[i - j] = result[i]\n\t\t# Copy over the 1s from the old array.\n\t\tfor i in j..tmp.high:\n\t\t\ttmp[i] = result[i - j]\n\t\t# And now the tmp array gets switched for another round of sorting.\n\t\tresult.shallowCopy(tmp)\n\n\nwhen isMainModule:\n\n\tconst arrays = [@[170, 45, 75, -90, -802, 24, 2, 66],\n\t\t\t\t\t\t\t\t\t@[-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]]\n\n\tfor a in arrays:\n\t\techo radixSort(a)\n" + }, + { + "id": 842, + "length": 2346, + "source": "Rosetta Code", + "text": "type\n\n\tVSeg[T] = ref object\n\t\tnext: VSeg[T]\n\t\telems: seq[T]\n\n\tVList[T] = ref object\n\t\tbase: VSeg[T]\n\t\toffset: int\n\n\nfunc newVList[T](): VList[T] = new(VList[T])\n\n\nfunc `[]`[T](v: VList[T]; k: int): T =\n\t## Primary operation 1: locate the kth element.\n\tif k >= 0:\n\t\tvar i = k + v.offset\n\t\tvar sg = v.base\n\t\twhile not sg.isNil:\n\t\t\tif i < sg.elems.len:\n\t\t\t\treturn sg.elems[i]\n\t\t\tdec i, sg.elems.len\n\t\t\tsg = sg.next\n\traise newException(IndexDefect, \"index out of range; got \" & $k)\n\n\nfunc cons[T](v: VList[T]; a: T): VList[T] =\n\t## Primary operation 2: add an element to the front of the VList.\n\tif v.base.isNil:\n\t\treturn VList[T](base: VSeg[T](elems: @[a]))\n\n\tif v.offset == 0:\n\t\tlet l2 = v.base.elems.len * 2\n\t\tvar elems = newSeq[T](l2)\n\t\telems[l2 - 1] = a\n\t\treturn VList[T](base: VSeg[T](next: v.base, elems: move(elems)), offset: l2 - 1)\n\n\tdec v.offset\n\tv.base.elems[v.offset] = a\n\tresult = v\n\n\nfunc cdr[T](v: VList[T]): VList[T] =\n\t## Primary operation 3: obtain a new array beginning at the second element of an old array.\n\tif v.base.isNil:\n\t\traise newException(NilAccessDefect, \"cdr on empty list\")\n\n\tif v.offset + 1 < v.base.elems.len:\n\t\tinc v.offset\n\t\treturn v\n\tresult = VList[T](base: v.base.next, offset: 0)\n\n\nfunc len[T](v: VList[T]): Natural =\n\t## Primary operation 4: compute the length of the list.\n\tif v.base.isNil: return 0\n\tresult = v.base.elems.len * 2 - v.offset - 1\n\n\nfunc `$`[T](v: VList[T]): string =\n\tif v.base.isNil: return \"[]\"\n\tresult = '[' & $v.base.elems[v.offset]\n\tvar sg = v.base\n\tvar sl = v.base.elems[v.offset+1..^1]\n\twhile true:\n\t\tfor e in sl: result.add ' ' & $e\n\t\tsg = sg.next\n\t\tif sg.isNil: break\n\t\tsl = sg.elems\n\tresult.add ']'\n\n\nproc printStructure[T](v: VList[T]) =\n\techo \"offset: \", v.offset\n\tvar sg = v.base\n\twhile not sg.isNil:\n\t\techo \" \", sg.elems\n\t\tsg = sg.next\n\techo()\n\n\nwhen isMainModule:\n\n\tvar v = newVList[string]()\n\n\techo \"Zero value for type. Empty vList:\", v\n\tv.printStructure()\n\n\tfor a in countdown('6', '1'): v = v.cons($a)\n\techo \"Demonstrate cons. Six elements added:\", v\n\tv.printStructure()\n\n\tv = v.cdr()\n\techo \"Demonstrate cdr. One element removed:\", v\n\tv.printStructure()\n\n\techo \"Demonstrate length. Length = \", v.len()\n\techo()\n\n\techo \"Demonstrate element access. v[3] = \", v[3]\n\techo()\n\n\tv = v.cdr().cdr()\n\techo \"Show cdr releasing segment. Two elements removed: \", v\n\tv.printStructure()\n" + }, + { + "id": 843, + "length": 2929, + "source": "Rosetta Code", + "text": "import strutils, tables\n\n# Generic defintion of the decision table.\n\ntype\n\n\tDTable[Cond, Act: Ordinal] = object\n\t\tquestions: array[Cond, string]\n\t\tanswers: array[Act, string]\n\t\trules: Table[set[Cond], seq[Act]]\n\nproc initDTable[Cond, Act](): DTable[Cond, Act] = discard\n\nproc addCondition[Cond, Act](dt: var DTable[Cond, Act]; cond: Cond; question: string) =\n\tif dt.questions[cond].len != 0:\n\t\traise newException(ValueError, \"condition already set: \" & $cond)\n\tdt.questions[cond] = question\n\nproc addAction[Cond, Act](dt: var DTable[Cond, Act]; act: Act; answer: string) =\n\tif dt.answers[act].len != 0:\n\t\traise newException(ValueError, \"action already set: \" & $act)\n\tdt.answers[act] = answer\n\nproc addRule[Cond, Act](dt: var DTable[Cond, Act]; rule: set[Cond]; acts: openArray[Act]) =\n\tif rule in dt.rules:\n\t\traise newException(ValueError, \"rule already set.\")\n\tdt.rules[rule] = @acts\n\nproc askQuestion(question: string): string =\n\twhile true:\n\t\tstdout.write question & ' '\n\t\tstdout.flushFile()\n\t\tresult = stdin.readLine().strip()\n\t\tif result in [\"y\", \"n\"]: break\n\n\nproc apply[Cond, Act](dt: DTable[Cond, Act]) =\n\n\t# Build condition set.\n\tvar conds: set[Cond]\n\techo \"Answer questions with 'y' or 'n'\"\n\tfor cond, question in dt.questions:\n\t\tif question.len == 0:\n\t\t\traise newException(ValueError, \"missing question for condition: \" & $cond)\n\t\tlet answer = askQuestion(question)\n\t\tif answer == \"y\":\n\t\t\tconds.incl cond\n\n\t# Apply rule.\n\techo()\n\tif conds in dt.rules:\n\t\techo \"Actions recommended:\"\n\t\tfor act in dt.rules[conds]:\n\t\t\techo \"- \", dt.answers[act]\n\telse:\n\t\techo \"No action recommended.\"\n\n\n# Decision table for Wikipedia printer example.\n\ntype\n\n\tCondition {.pure.} = enum PrinterPrints, RedLightFlashing, PrinterRecognized\n\tAction {.pure.} = enum CheckPowerCable, CheckPrinterCable, CheckSoftware, CheckInk, CheckPaperJam\n\nconst\n\n\tQuestions = [PrinterPrints: \"Does printer print?\",\n\t\t\t\t\t\t\t RedLightFlashing: \"Does red light is flashing?\",\n\t\t\t\t\t\t\t PrinterRecognized: \"Is printer recognized by computer?\"]\n\n\tAnswers = [CheckPowerCable: \"check the power cable\",\n\t\t\t\t\t\t CheckPrinterCable: \"check the printer-computer cable\",\n\t\t\t\t\t\t CheckSoftware: \"ensure printer software is installed\",\n\t\t\t\t\t\t CheckInk: \"check/replace ink\",\n\t\t\t\t\t\t CheckPaperJam: \"check for paper jam\"]\n\nvar dt = initDTable[Condition, Action]()\n\nfor cond, question in Questions:\n\tdt.addCondition(cond, question)\n\nfor act, answer in Answers:\n\tdt.addAction(act, answer)\n\ndt.addRule({}, [CheckPowerCable, CheckPrinterCable, CheckSoftware])\ndt.addRule({PrinterPrints}, [CheckSoftware])\ndt.addRule({RedLightFlashing}, [CheckPrinterCable, CheckSoftware, CheckInk])\ndt.addRule({PrinterRecognized}, [CheckPaperJam])\ndt.addRule({PrinterPrints, RedLightFlashing}, [CheckSoftware])\ndt.addRule({RedLightFlashing, PrinterRecognized}, [CheckInk, CheckPaperJam])\ndt.addRule({PrinterPrints, RedLightFlashing, PrinterRecognized}, [CheckInk])\n\ndt.apply()\n" + }, + { + "id": 844, + "length": 698, + "source": "Rosetta Code", + "text": "import strformat\n\nconst data = [85, 88, 75, 66, 25,\n\t\t\t\t\t\t\t29, 83, 39, 97, 68,\n\t\t\t\t\t\t\t41, 10, 49, 16, 65,\n\t\t\t\t\t\t\t32, 92, 28, 98]\n\nfunc pick(at, remain, accu, treat: int): int =\n\tif remain == 0:\n\t\treturn if accu > treat: 1 else: 0\n\treturn pick(at - 1, remain - 1, accu + data[at - 1], treat) +\n\t\t(if at > remain: pick(at - 1, remain, accu, treat) else: 0)\n\n\nvar treat = 0\nvar le, gt = 0\nvar total = 1.0\nfor i in countup(0, 8):\n\ttreat += data[i]\nfor i in countdown(19, 11):\n\ttotal *= float(i)\nfor i in countdown(9, 1):\n\ttotal /= float(i)\n\ngt = pick(19, 9, 0, treat)\nle = int(total - float(gt))\necho fmt\"<= : {100.0 * float(le) / total:.6f}% {le}\"\necho fmt\" > : {100.0 * float(gt) / total:.6f}% {gt}\"\n" + }, + { + "id": 845, + "length": 2683, + "source": "Rosetta Code", + "text": "import options, random, sequtils, strutils\n\ntype\n\tBoard = array[1..9, char]\n\tScore = (char, array[3, int])\n\nconst NoChoice = 0\n\nvar board: Board = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n\nconst Wins = [[1, 2, 3], [4, 5, 6], [7, 8, 9],\n\t\t\t\t\t\t\t[1, 4, 7], [2, 5, 8], [3, 6, 9],\n\t\t\t\t\t\t\t[1, 5, 9], [3, 5, 7]]\n\ntemplate toIndex(ch: char): int =\n\t## Convert a character to an index in board.\n\tord(ch) - ord('0')\n\nproc print(board: Board) =\n\tfor i in [1, 4, 7]:\n\t\techo board[i..(i + 2)].join(\" \")\n\nproc score(board: Board): Option[Score] =\n\tfor w in Wins:\n\t\tlet b = board[w[0]]\n\t\tif b in \"XO\" and w.allIt(board[it] == b):\n\t\t\treturn some (b, w)\n\tresult = none(Score)\n\nproc finished(board: Board): bool =\n\tboard.allIt(it in \"XO\")\n\nproc space(board: Board): seq[char] =\n\tfor b in board:\n\t\tif b notin \"XO\":\n\t\t\tresult.add b\n\nproc myTurn(board: var Board; xo: char): char =\n\tlet options = board.space()\n\tresult = options.sample()\n\tboard[result.toIndex] = xo\n\nproc myBetterTurn(board: var Board; xo: char): int =\n\tlet ox = if xo == 'X': 'O' else: 'X'\n\tvar oneBlock = NoChoice\n\tlet options = board.space.mapIt(it.toIndex)\n\tblock search:\n\t\tfor choice in options:\n\t\t\tvar brd = board\n\t\t\tbrd[choice] = xo\n\t\t\tif brd.score.isSome:\n\t\t\t\tresult = choice\n\t\t\t\tbreak search\n\t\t\tif oneBlock == NoChoice:\n\t\t\t\tbrd[choice] = ox\n\t\t\t\tif brd.score.isSome:\n\t\t\t\t\toneBlock = choice\n\t\tresult = if oneBlock != NoChoice: oneBlock else: options.sample()\n\tboard[result] = xo\n\nproc yourTurn(board: var Board; xo: char): int =\n\tlet options = board.space()\n\tvar choice: char\n\twhile true:\n\t\tstdout.write \"\\nPut your $# in any of these positions: $# \".format(xo, options.join())\n\t\tlet input = stdin.readLine().strip()\n\t\tif input.len == 1 and input[0] in options:\n\t\t\tchoice = input[0]\n\t\t\tbreak\n\t\techo \"Whoops I don't understand the input\"\n\tresult = choice.toIndex\n\tboard[result] = xo\n\nproc me(board: var Board; xo: char): Option[Score] =\n\tboard.print()\n\techo \"\\nI go at \", board.myBetterTurn(xo)\n\tresult = board.score()\n\nproc you(board: var Board; xo: char): Option[Score] =\n\tboard.print()\n\techo \"\\nYou went at \", board.yourTurn(xo)\n\tresult = board.score()\n\nproc play() =\n\twhile not board.finished():\n\t\tlet score = board.me('X')\n\t\tif score.isSome:\n\t\t\tboard.print()\n\t\t\tlet (winner, line) = score.get()\n\t\t\techo \"\\n$# wins along ($#).\".format(winner, line.join(\", \"))\n\t\t\treturn\n\t\tif not board.finished():\n\t\t\tlet score = board.you('O')\n\t\t\tif score.isSome:\n\t\t\t\tboard.print()\n\t\t\t\tlet (winner, line) = score.get()\n\t\t\t\techo \"\\n$# wins along ($#).\".format(winner, line.join(\", \"))\n\t\t\t\treturn\n\techo \"\\nA draw.\"\n\necho \"Tic-tac-toe game player.\"\necho \"Input the index of where you wish to place your mark at your turn.\"\nrandomize()\nplay()\n" + }, + { + "id": 846, + "length": 1687, + "source": "Rosetta Code", + "text": "import algorithm, math, sequtils, strutils\n\ntype Partition = seq[seq[int]]\n\n\nfunc isIncreasing(s: seq[int]): bool =\n\t## Return true if the sequence is sorted in increasing order.\n\tvar prev = 0\n\tfor val in s:\n\t\tif prev >= val: return false\n\t\tprev = val\n\tresult = true\n\n\niterator partitions(lengths: varargs[int]): Partition =\n\t## Yield the partitions for lengths \"lengths\".\n\n\t# Build the list of slices to use for partitionning.\n\tvar slices: seq[Slice[int]]\n\tvar delta = -1\n\tvar idx = 0\n\tfor length in lengths:\n\t\tassert length >= 0, \"lengths must not be negative.\"\n\t\tinc delta, length\n\t\tslices.add idx..delta\n\t\tinc idx, length\n\n\t# Build the partitions.\n\tlet n = sum(lengths)\n\tvar perm = toSeq(1..n)\n\twhile true:\n\n\t\tblock buildPartition:\n\t\t\tvar part: Partition\n\t\t\tfor slice in slices:\n\t\t\t\tlet s = perm[slice]\n\t\t\t\tif not s.isIncreasing():\n\t\t\t\t\tbreak buildPartition\n\t\t\t\tpart.add s\n\t\t\tyield part\n\n\t\tif not perm.nextPermutation():\n\t\t\tbreak\n\n\nfunc toString(part: Partition): string =\n\t## Return the string representation of a partition.\n\tresult = \"(\"\n\tfor s in part:\n\t\tresult.addSep(\", \", 1)\n\t\tresult.add '{' & s.join(\", \") & '}'\n\tresult.add ')'\n\n\nwhen isMainModule:\n\n\timport os\n\n\tproc displayPermutations(lengths: varargs[int]) =\n\t\t## Display the permutations.\n\t\techo \"Ordered permutations for (\", lengths.join(\", \"), \"):\"\n\t\tfor part in partitions(lengths):\n\t\t\techo part.toString\n\n\tif paramCount() > 0:\n\t\tvar args: seq[int]\n\t\tfor param in commandLineParams():\n\t\t\ttry:\n\t\t\t\tlet val = param.parseInt()\n\t\t\t\tif val < 0: raise newException(ValueError, \"\")\n\t\t\t\targs.add val\n\t\t\texcept ValueError:\n\t\t\t\tquit \"Wrong parameter: \" & param\n\t\tdisplayPermutations(args)\n\n\telse:\n\t\tdisplayPermutations(2, 0, 2)\n" + }, + { + "id": 847, + "length": 703, + "source": "Rosetta Code", + "text": "import math, complex, strutils\n\n# Works with floats and complex numbers as input\nproc fft[T: float | Complex[float]](x: openarray[T]): seq[Complex[float]] =\n\tlet n = x.len\n\tif n == 0: return\n\n\tresult.newSeq(n)\n\n\tif n == 1:\n\t\tresult[0] = (when T is float: complex(x[0]) else: x[0])\n\t\treturn\n\n\tvar evens, odds = newSeq[T]()\n\tfor i, v in x:\n\t\tif i mod 2 == 0: evens.add v\n\t\telse: odds.add v\n\tvar (even, odd) = (fft(evens), fft(odds))\n\n\tlet halfn = n div 2\n\n\tfor k in 0 ..< halfn:\n\t\tlet a = exp(complex(0.0, -2 * Pi * float(k) / float(n))) * odd[k]\n\t\tresult[k] = even[k] + a\n\t\tresult[k + halfn] = even[k] - a\n\nfor i in fft(@[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]):\n\techo formatFloat(abs(i), ffDecimal, 3)\n" + }, + { + "id": 848, + "length": 684, + "source": "Rosetta Code", + "text": "import re, strformat, strutils, tables\n\nvar configs: OrderedTable[string, seq[string]]\nvar parsed: seq[string]\n\nfor line in \"demo.config\".lines():\n\tlet line = line.strip()\n\tif line != \"\" and not line.startswith(re\"#|;\"):\n\t\tparsed = line.split(re\"\\s*=\\s*|\\s+\", 1)\n\t\tconfigs[parsed[0].toLower()] = if len(parsed) > 1: parsed[1].split(re\"\\s*,\\s*\") else: @[]\n\nfor key in [\"fullname\", \"favouritefruit\", \"needspeeling\", \"seedsremoved\", \"otherfamily\"]:\n\tif not configs.hasKey(key):\n\t\techo(\"{key} = false\")\n\telse:\n\t\tcase len(configs[key])\n\t\tof 0:\n\t\t\techo(\"{key} = true\")\n\t\tof 1:\n\t\t\techo(\"{key} = {configs[key][0]}\")\n\t\telse:\n\t\t\tfor i, v in configs[key].pairs():\n\t\t\t\techo(\"{key}({i+1}) = {v}\")\n" + }, + { + "id": 849, + "length": 773, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat\n\ntype randProc = proc: range[0..1]\n\nrandomize()\n\nproc randN(n: Positive): randProc =\n\tresult = proc: range[0..1] = ord(rand(n) == 0)\n\nproc unbiased(biased: randProc): range[0..1] =\n\tresult = biased()\n\tvar that = biased()\n\twhile result == that:\n\t\tresult = biased()\n\t\tthat = biased()\n\nfor n in 3..6:\n\tvar biased = randN(n)\n\tvar v = newSeqWith(1_000_000, biased())\n\tvar cnt0, cnt1 = 0\n\tfor x in v:\n\t\tif x == 0: inc cnt0 else: inc cnt1\n\techo \"Biased({n}) -> count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}\"\n\n\tv = newSeqWith(1_000_000, unbiased(biased))\n\tcnt0 = 0\n\tcnt1 = 0\n\tfor x in v:\n\t\tif x == 0: inc cnt0 else: inc cnt1\n\techo \"Unbiased -> count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}\"\n" + }, + { + "id": 850, + "length": 774, + "source": "Rosetta Code", + "text": "import math, strutils, strformat\n\ntype Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]\n\nproc cholesky[Matrix](a: Matrix): Matrix =\n\tfor i in 0 ..< a[0].len:\n\t\tfor j in 0 .. i:\n\t\t\tvar s = 0.0\n\t\t\tfor k in 0 ..< j:\n\t\t\t\ts += result[i][k] * result[j][k]\n\t\t\tresult[i][j] = if i == j: sqrt(a[i][i]-s)\n\t\t\t\t\t\t\t\t\t\t else: 1.0 / result[j][j] * (a[i][j] - s)\n\nproc `$`(a: Matrix): string =\n\tresult = \"\"\n\tfor b in a:\n\t\tvar line = \"\"\n\t\tfor c in b:\n\t\t\tline.addSep(\" \", 0)\n\t\t\tline.add fmt\"{c:8.5f}\"\n\t\tresult.add line & '\\n'\n\nlet m1 = [[25.0, 15.0, -5.0],\n\t\t\t\t\t[15.0, 18.0, 0.0],\n\t\t\t\t\t[-5.0, 0.0, 11.0]]\necho cholesky(m1)\n\nlet m2 = [[18.0, 22.0, 54.0, 42.0],\n\t\t\t\t\t[22.0, 70.0, 86.0, 62.0],\n\t\t\t\t\t[54.0, 86.0, 174.0, 134.0],\n\t\t\t\t\t[42.0, 62.0, 134.0, 106.0]]\necho cholesky(m2)\n" + }, + { + "id": 851, + "length": 2008, + "source": "Rosetta Code", + "text": "import macros, strutils\nimport strfmt\n\ntype\n\n\tMatrix[M, N: static int] = array[1..M, array[1..N, float]]\n\tSquareMatrix[N: static int] = Matrix[N, N]\n\n\n# Templates to allow to use more natural notation for indexing.\ntemplate `[]`(m: Matrix; i, j: int): float = m[i][j]\ntemplate `[]=`(m: Matrix; i, j: int; val: float) = m[i][j] = val\n\n\nfunc `*`[M, N, P: static int](a: Matrix[M, N]; b: Matrix[N, P]): Matrix[M, P] =\n\t## Matrix multiplication.\n\tfor i in 1..M:\n\t\tfor j in 1..P:\n\t\t\tfor k in 1..N:\n\t\t\t\tresult[i, j] += a[i, k] * b[k, j]\n\n\nfunc pivotize[N: static int](m: SquareMatrix[N]): SquareMatrix[N] =\n\n\tfor i in 1..N: result[i, i] = 1\n\n\tfor i in 1..N:\n\t\tvar max = m[i, i]\n\t\tvar row = i\n\t\tfor j in i..N:\n\t\t\tif m[j, i] > max:\n\t\t\t\tmax = m[j, i]\n\t\t\t\trow = j\n\t\tif i != row:\n\t\t\tswap result[i], result[row]\n\n\nfunc lu[N: static int](m: SquareMatrix[N]): tuple[l, u, p: SquareMatrix[N]] =\n\n\tresult.p = m.pivotize()\n\tlet m2 = result.p * m\n\n\tfor j in 1..N:\n\t\tresult.l[j, j] = 1\n\t\tfor i in 1..j:\n\t\t\tvar sum = 0.0\n\t\t\tfor k in 1.. 0:\n\t\t\tif len(tempChunk) == 0:\n\t\t\t\tif encrypt:\n\t\t\t\t\tresult&=powmodHexStr(pcount(chunk, '0').toHex(2)&align(chunk,\n\t\t\t\t\t\t\tchunkSize-3, '0'), key, divisor)\n\t\t\t\telse:\n\t\t\t\t\ttempChunk = align(powmodHexStr(chunk, key, divisor), chunkSize-1, '0')\n\t\t\t\t\tresidue = tempChunk[2..^1].strip(trailing = false, chars = {'0'})\n\t\t\t\t\tresult&=align(residue, fromHex[int](tempChunk[0..1])+len(residue), '0')\n\t\t\t\tbreak\n\t\t\tresult&=align(powmodHexStr(chunk, key, divisor), chunkSize-3+int(\n\t\t\t\t\tencrypt)*3, '0')\n\t\tdiscard strm.readStr(chunkSize-int(encrypt)*3)\n\t\tchunk = tempChunk\n\tstrm.close()\nfor message in messages:\n\techo(\"plaintext:\\n{message}\")\n\tvar numPlaintext = message.toHex()\n\techo(\"numerical plaintext in hex:\\n{numPlaintext}\")\n\tvar ciphertext = translate(numPlaintext, e, n)\n\techo(\"ciphertext is: \\n{ciphertext}\")\n\tvar deciphertext = translate(ciphertext, d, n, false)\n\techo(\"deciphered numerical plaintext in hex is:\\n{deciphertext}\")\n\techo(\"deciphered plaintext is:\\n{parseHexStr(deciphertext)}\\n\\n\")\n" + }, + { + "id": 853, + "length": 767, + "source": "Rosetta Code", + "text": "import math\n\ntype Point = tuple[x,y,z: float]\n\nconst shades = \".:!*oe&#%@\"\n\nproc normalize(x, y, z: float): Point =\n\tlet len = sqrt(x*x + y*y + z*z)\n\t(x / len, y / len, z / len)\n\nproc dot(a, b: Point): float =\n\tresult = max(0, - a.x*b.x - a.y*b.y - a.z*b.z)\n\nlet light = normalize(30.0, 30.0, -50.0)\n\nproc drawSphere(r: int; k, ambient: float) =\n\tfor i in -r .. r:\n\t\tlet x = i.float + 0.5\n\t\tfor j in -2*r .. 2*r:\n\t\t\tlet y = j.float / 2.0 + 0.5\n\t\t\tif x*x + y*y <= float r*r:\n\t\t\t\tlet\n\t\t\t\t\tv = normalize(x, y, sqrt(float(r*r) - x*x - y*y))\n\t\t\t\t\tb = pow(dot(light, v), k) + ambient\n\t\t\t\t\ti = clamp(int((1.0 - b) * shades.high.float), 0, shades.high)\n\t\t\t\tstdout.write shades[i]\n\t\t\telse: stdout.write ' '\n\t\tstdout.write \"\\n\"\n\ndrawSphere 20, 4.0, 0.1\ndrawSphere 10, 2.0, 0.4\n" + }, + { + "id": 854, + "length": 627, + "source": "Rosetta Code", + "text": "import bigints\n\nvar\n\ttmp1, tmp2, tmp3, acc, k = initBigInt(0)\n\tden, num, k2 = initBigInt(1)\n\nproc extractDigit(): int32 =\n\tif num > acc:\n\t\treturn -1\n\n\ttmp3 = num shl 1 + num + acc\n\ttmp1 = tmp3 div den\n\ttmp2 = tmp3 mod den + num\n\n\tif tmp2 >= den:\n\t\treturn -1\n\n\tresult = int32(tmp1.limbs[0])\n\nproc eliminateDigit(d: int32) =\n\tacc -= den * d\n\tacc *= 10\n\tnum *= 10\n\nproc nextTerm() =\n\tk += 1\n\tk2 += 2\n\tacc += num shl 1\n\tacc *= k2\n\tden *= k2\n\tnum *= k\n\nvar i = 0\n\nwhile true:\n\tvar d: int32 = -1\n\twhile d < 0:\n\t\tnextTerm()\n\t\td = extractDigit()\n\n\tstdout.write chr(ord('0') + d)\n\tinc i\n\tif i == 40:\n\t\techo \"\"\n\t\ti = 0\n\teliminateDigit d\n" + }, + { + "id": 855, + "length": 1215, + "source": "Rosetta Code", + "text": "import math, sequtils, strformat, strutils\n\nconst\n\theadingNames: array[1..32, string] = [\n\t\t\"North\", \"North by east\", \"North-northeast\", \"Northeast by north\",\n\t\t\"Northeast\", \"Northeast by east\", \"East-northeast\", \"East by north\",\n\t\t\"East\", \"East by south\", \"East-southeast\", \"Southeast by east\",\n\t\t\"Southeast\", \"Southeast by south\",\"South-southeast\", \"South by east\",\n\t\t\"South\", \"South by west\", \"South-southwest\", \"Southwest by south\",\n\t\t\"Southwest\", \"Southwest by west\", \"West-southwest\", \"West by south\",\n\t\t\"West\", \"West by north\", \"West-northwest\", \"Northwest by west\",\n\t\t\"Northwest\", \"Northwest by north\", \"North-northwest\", \"North by west\"]\n\tmaxNameLength = headingNames.mapIt(it.len).max\n\tdegreesPerHeading = 360 / 32\n\nfunc toCompassIndex(degree: float): 1..32 =\n\tvar degree = (degree + degreesPerHeading / 2).floorMod 360\n\tint(degree / degreesPerHeading) + 1\n\nfunc toCompassHeading(degree: float): string = headingNames[degree.toCompassIndex]\n\nfor i in 0..32:\n\tlet\n\t\theading = float(i) * 11.25 + (case i mod 3\n\t\t\tof 1: 5.62\n\t\t\tof 2: -5.62\n\t\t\telse: 0)\n\t\tindex = heading.toCompassIndex\n\t\tcompassHeading = heading.toCompassHeading.alignLeft(maxNameLength)\n\techo fmt\"{index:>2} {compassHeading} {heading:6.2f}\"\n" + }, + { + "id": 856, + "length": 2171, + "source": "Rosetta Code", + "text": "import math\n\nimport bitmap, grayscale_image, nimPNG\n\ntype\n\n\tVector = array[3, float]\n\n\tSphere = object\n\t\tcx, cy, cz: int\n\t\tr: int\n\n\nfunc dot(x, y: Vector): float {.inline.} =\n\tx[0] * y[0] + x[1] * y[1] + x[2] * y[2]\n\n\nfunc normalize(v: var Vector) =\n\tlet invLen = 1 / sqrt(dot(v, v))\n\tv[0] *= invLen\n\tv[1] *= invLen\n\tv[2] *= invLen\n\n\nfunc hit(s: Sphere; x, y: int): tuple[z1, z2: float; hit: bool] =\n\tlet x = x - s.cx\n\tlet y = y - s.cy\n\tlet zsq = s.r * s.r - (x * x + y * y)\n\tif zsq >= 0:\n\t\tlet zsqrt = sqrt(zsq.toFloat)\n\t\tresult = (s.cz.toFloat - zsqrt, s.cz.toFloat, true)\n\telse:\n\t\tresult = (0.0, 0.0, false)\n\n\nfunc deathStar(pos, neg: Sphere; k, amb: float; dir: Vector): GrayImage =\n\n\tlet w = pos.r * 4\n\tlet h = pos.r * 3\n\tresult = newGrayImage(w, h)\n\tvar vect: Vector\n\tlet deltaX = pos.cx - w div 2\n\tlet deltaY = pos.cy - h div 2\n\n\tlet xMax = pos.cx + pos.r\n\tlet yMax = pos.cy + pos.r\n\tfor y in (pos.cy - pos.r)..yMax:\n\t\tfor x in (pos.cx - pos.r)..xMax:\n\t\t\tlet (zb1, zb2, posHit) = pos.hit(x, y)\n\t\t\tif not posHit: continue\n\t\t\tvar (zs1, zs2, negHit) = neg.hit(x, y)\n\t\t\tif negHit:\n\t\t\t\tif zs1 > zb1: negHit = false\n\t\t\t\telif zs2 > zb2: continue\n\t\t\tif negHit:\n\t\t\t\tvect[0] = (neg.cx - x).toFloat\n\t\t\t\tvect[1] = (neg.cy - y).toFloat\n\t\t\t\tvect[2] = neg.cz.toFloat - zs2\n\t\t\telse:\n\t\t\t\tvect[0] = (x - pos.cx).toFloat\n\t\t\t\tvect[1] = (y - pos.cy).toFloat\n\t\t\t\tvect[2] = zb1 - pos.cz.toFloat\n\t\t\tvect.normalize()\n\t\t\tvar s = dot(dir, vect)\n\t\t\tif s < 0: s = 0\n\t\t\tvar lum = (255 * (s.pow(k) + amb) / (1 + amb)).toInt\n\t\t\tif lum < 0: lum = 0\n\t\t\telif lum > 255: lum = 255\n\t\t\tresult[x - deltaX, y - deltaY] = Luminance(lum)\n\n\nvar dir: Vector = [float 20, -40, -10]\ndir.normalize()\nlet pos = Sphere(cx: 0, cy: 0, cz: 0, r: 120)\nlet neg = Sphere(cx: -90, cy: -90, cz: -30, r: 100)\n\nlet grayImage = deathStar(pos, neg, 1.5, 0.2, dir)\n\n# Save to PNG. We convert to an RGB image then transform the pixels\n# in a sequence of bytes (actually a copy) in order to call \"savePNG24\".\nlet rgbImage = grayImage.toImage\nvar data = newSeqOfCap[byte](rgbImage.pixels.len * 3)\nfor color in rgbImage.pixels:\n\tdata.add([color.r, color.g, color.b])\necho savePNG24(\"death_star.png\", data, rgbImage.w, rgbImage.h)\n" + }, + { + "id": 857, + "length": 709, + "source": "Rosetta Code", + "text": "import gintro/cairo\n\nproc draw(ctx: Context; x, y, r: float) =\n\tctx.arc(x, y, r + 1, 1.571, 7.854)\n\tctx.setSource(0.0, 0.0, 0.0)\n\tctx.fill()\n\tctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712)\n\tctx.arc(x, y + r / 2, r / 2, 1.571, 4.712)\n\tctx.arcNegative(x, y, r, 4.712, 1.571)\n\tctx.setSource(1.0, 1.0, 1.0)\n\tctx.fill()\n\tctx.arc(x, y - r / 2, r / 5, 1.571, 7.854)\n\tctx.setSource(0.0, 0.0, 0.0)\n\tctx.fill()\n\tctx.arc(x, y + r / 2, r / 5, 1.571, 7.854)\n\tctx.setSource(1.0, 1.0, 1.0)\n\tctx.fill()\n\nlet surface = imageSurfaceCreate(argb32, 200, 200)\nlet context = newContext(surface)\ncontext.draw(120, 120, 75)\ncontext.draw(35, 35, 30)\nlet status = surface.writeToPng(\"yin-yang.png\")\nassert status == Status.success\n" + }, + { + "id": 858, + "length": 588, + "source": "Rosetta Code", + "text": "proc mergeList[T](a, b: var seq[T]): seq[T] =\n\tresult = @[]\n\twhile a.len > 0 and b.len > 0:\n\t\tif a[0] < b[0]:\n\t\t\tresult.add a[0]\n\t\t\ta.delete 0\n\t\telse:\n\t\t\tresult.add b[0]\n\t\t\tb.delete 0\n\tresult.add a\n\tresult.add b\n\nproc strand[T](a: var seq[T]): seq[T] =\n\tvar i = 0\n\tresult = @[a[0]]\n\ta.delete 0\n\twhile i < a.len:\n\t\tif a[i] > result[result.high]:\n\t\t\tresult.add a[i]\n\t\t\ta.delete i\n\t\telse:\n\t\t\tinc i\n\nproc strandSort[T](a: seq[T]): seq[T] =\n\tvar a = a\n\tresult = a.strand\n\twhile a.len > 0:\n\t\tvar s = a.strand\n\t\tresult = mergeList(result, s)\n\nvar a = @[1, 6, 3, 2, 1, 7, 5, 3]\necho a.strandSort\n" + }, + { + "id": 859, + "length": 938, + "source": "Rosetta Code", + "text": "import imageman\n\nconst\n\tBlack = ColorRGBU [byte 0, 0, 0] # For background.\n\tRed = ColorRGBU [byte 255, 0, 0] # For triangle.\n\nproc drawSierpinski(img: var Image; txy: array[1..6, float]; levelsYet: Natural) =\n\tvar nxy: array[1..6, float]\n\tif levelsYet > 0:\n\t\tfor i in 1..6:\n\t\t\tlet pos = if i < 5: i + 2 else: i - 4\n\t\t\tnxy[i] = (txy[i] + txy[pos]) / 2\n\t\timg.drawSierpinski([txy[1], txy[2], nxy[1], nxy[2], nxy[5], nxy[6]], levelsYet - 1)\n\t\timg.drawSierpinski([nxy[1], nxy[2], txy[3], txy[4], nxy[3], nxy[4]], levelsyet - 1)\n\t\timg.drawSierpinski([nxy[5], nxy[6], nxy[3], nxy[4], txy[5], txy[6]], levelsyet - 1)\n\telse:\n\t\timg.drawPolyline(closed = true, Red,\n\t\t\t\t(txy[1].toInt, txy[2].toInt), (txy[3].toInt, txy[4].toInt),(txy[5].toInt, txy[6].toInt))\n\nvar image = initImage[ColorRGBU](800, 800)\nimage.fill(Black)\nimage.drawSierpinski([400.0, 100.0, 700.0, 500.0, 100.0, 500.0], 7)\nimage.savePNG(\"sierpinski_triangle.png\", compression = 9)\n" + }, + { + "id": 860, + "length": 2032, + "source": "Rosetta Code", + "text": "import random, strutils\n\nconst\n\tBoxW = 41 # Galton box width.\n\tBoxH = 37 # Galton box height.\n\tPinsBaseW = 19 # Pins triangle base.\n\tNMaxBalls = 55 # Number of balls.\n\nconst CenterH = PinsBaseW + (BoxW - (PinsBaseW * 2 - 1)) div 2 - 1\n\ntype\n\n\tCell = enum\n\t\tcEmpty = \" \"\n\t\tcBall = \"o\"\n\t\tcWall = \"|\"\n\t\tcCorner = \"+\"\n\t\tcFloor = \"-\"\n\t\tcPin = \".\"\n\n\t# Galton box. Will be printed upside-down.\n\tBox = array[BoxH, array[BoxW, Cell]]\n\n\tBall = ref object\n\t\tx, y: int\n\n\nfunc initBox(): Box =\n\n\t# Set ceiling and floor.\n\tresult[0][0] = cCorner\n\tresult[0][^1] = cCorner\n\tfor i in 1..(BoxW - 2):\n\t\tresult[0][i] = cFloor\n\tresult[^1] = result[0]\n\n\t# Set walls.\n\tfor i in 1..(BoxH - 2):\n\t\tresult[i][0] = cWall\n\t\tresult[i][^1] = cWall\n\n\t# Set rest to Empty initially.\n\tfor i in 1..(BoxH - 2):\n\t\tfor j in 1..(BoxW - 2):\n\t\t\tresult[i][j] = cEmpty\n\n\t# Set pins.\n\tfor nPins in 1..PinsBaseW:\n\t\tfor p in 0..6} {!n:>6}\"\n\necho \"\\n!20 = \", !20\n" + }, + { + "id": 862, + "length": 877, + "source": "Rosetta Code", + "text": "import algorithm\nimport tables\nimport times\n\nvar anagrams: Table[seq[char], seq[string]] # Mapping sorted_list_of chars -> list of anagrams.\n\n\nfunc deranged(s1, s2: string): bool =\n\t## Return true if \"s1\" and \"s2\" are deranged anagrams.\n\n\tfor i, c in s1:\n\t\tif s2[i] == c:\n\t\t\treturn false\n\tresult = true\n\n\nlet t0 = getTime()\n\n# Build the anagrams table.\nfor word in lines(\"unixdict.txt\"):\n\tanagrams.mgetOrPut(sorted(word), @[]).add(word)\n\n# Find the longest deranged anagrams.\nvar bestLen = 0\nvar best1, best2: string\nfor (key, list) in anagrams.pairs:\n\tif key.len > bestLen:\n\t\tvar s1 = list[0]\n\t\tfor i in 1..list.high:\n\t\t\tlet s2 = list[i]\n\t\t\tif deranged(s1, s2):\n\t\t\t\t# Found a better pair.\n\t\t\t\tbest1 = s1\n\t\t\t\tbest2 = s2\n\t\t\t\tbestLen = s1.len\n\t\t\t\tbreak\n\necho \"Longest deranged anagram pair: \", best1, \" \", best2\necho \"Processing time: \", (getTime() - t0).inMilliseconds, \" ms.\"\n" + }, + { + "id": 863, + "length": 2487, + "source": "Rosetta Code", + "text": "import os, re, strutils\n\nlet regex = re(r\"^(;*)\\s*([A-Z0-9]+)\\s*([A-Z0-9]*)\", {reIgnoreCase, reStudy})\n\ntype\n\n\tEntryType {.pure.} = enum Empty, Enabled, Disabled, Comment, Ignore\n\n\tEntry = object\n\t\tetype: EntryType\n\t\tname: string\n\t\tvalue: string\n\n\tConfig = object\n\t\tentries: seq[Entry]\n\t\tpath: string\n\n\n# Forward reference.\nproc addOption*(config: var Config; name, value: string; etype = Enabled)\n\n\nproc initConfig*(path: string): Config =\n\n\tif not path.isValidFilename:\n\t\traise newException(IOError, \"invalid file name.\")\n\n\tresult.path = path\n\tif not path.fileExists: return\n\n\tfor line in path.lines:\n\t\tvar line = line.strip\n\t\tif line.len == 0:\n\t\t\tresult.entries.add Entry(etype: Empty)\n\t\telif line[0] == '#':\n\t\t\tresult.entries.add Entry(etype: Comment, value: line)\n\t\telse:\n\t\t\tline = line.replace(re\"^a-zA-Z0-9\\x20;\")\n\t\t\tvar matches = newSeq[string](3)\n\t\t\tif line.match(regex, matches) and matches[1].len != 0:\n\t\t\t\tlet etype = if matches[0].len == 0: Enabled else: Disabled\n\t\t\t\tresult.addOption(matches[1], matches[2], etype)\n\n\nproc getOptionIndex(config: Config; name: string): int =\n\tfor i, e in config.entries:\n\t\tif e.etype notin [Enabled, Disabled]: continue\n\t\tif e.name == name.toUpperAscii:\n\t\t\treturn i\n\tresult = -1\n\n\nproc enableOption*(config: var Config; name: string) =\n\tlet i = config.getOptionIndex(name)\n\tif i >= 0:\n\t\tconfig.entries[i].etype = Enabled\n\n\nproc disableOption*(config: var Config; name: string) =\n\tlet i = config.getOptionIndex(name)\n\tif i >= 0:\n\t\tconfig.entries[i].etype = Disabled\n\n\nproc setOption*(config: var Config; name, value: string) =\n\tlet i = config.getOptionIndex(name)\n\tif i >= 0:\n\t\tconfig.entries[i].value = value\n\n\nproc addOption*(config: var Config; name, value: string; etype = Enabled) =\n\tconfig.entries.add Entry(etype: etype, name: name.toUpperAscii, value: value)\n\n\nproc removeOption*(config: var Config; name: string) =\n\tlet i = config.getOptionIndex(name)\n\tif i >= 0:\n\t\tconfig.entries[i].etype = Ignore\n\n\nproc store*(config: Config) =\n\tlet f = open(config.path, fmWrite)\n\tfor e in config.entries:\n\t\tcase e.etype\n\t\tof Empty: f.writeLine(\"\")\n\t\tof Enabled: f.writeLine(e.name, ' ', e.value)\n\t\tof Disabled: f.writeLine(\"; \", e.name, ' ', e.value)\n\t\tof Comment: f.writeLine(e.value)\n\t\tof Ignore: discard\n\n\nwhen isMainModule:\n\n\tvar cfg = initConfig(\"update_demo.config\")\n\tcfg.enableOption(\"seedsremoved\")\n\tcfg.disableOption(\"needspeeling\")\n\tcfg.setOption(\"numberofbananas\", \"1024\")\n\tcfg.addOption(\"numberofstrawberries\", \"62000\")\n\tcfg.store()\n" + }, + { + "id": 864, + "length": 1243, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\tWidth = 420\n\tHeight = 420\n\nconst Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]]\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the bars.\n\n\tconst lineHeight = Height div 4\n\n\tvar y = 0.0\n\tfor lineWidth in [1.0, 2.0, 3.0, 4.0]:\n\t\tcontext.setLineWidth(lineWidth)\n\t\tvar x = 0.0\n\t\tvar colorIndex = 0\n\t\twhile x < Width:\n\t\t\tcontext.setSource(Colors[colorIndex])\n\t\t\tcontext.moveTo(x, y)\n\t\t\tcontext.lineTo(x, y + lineHeight)\n\t\t\tcontext.stroke()\n\t\t\tcolorIndex = 1 - colorIndex\n\t\t\tx += lineWidth\n\t\ty += lineHeight\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Color pinstripe\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the bars.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Pinstripe\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 865, + "length": 1221, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]]\n\n\nproc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) =\n\t## Process signal \"begin_print\", that is set the number of pages to print.\n\top.setNPages(1)\n\n\nproc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) =\n\t## Draw a page.\n\n\tlet context = printContext.getCairoContext()\n\tlet lineHeight = printContext.height / 4\n\n\tvar y = 0.0\n\tfor lineWidth in [1.0, 2.0, 3.0, 4.0]:\n\t\tcontext.setLineWidth(lineWidth)\n\t\tvar x = 0.0\n\t\tvar colorIndex = 0\n\t\twhile x < printContext.width:\n\t\t\tcontext.setSource(Colors[colorIndex])\n\t\t\tcontext.moveTo(x, y)\n\t\t\tcontext.lineTo(x, y + lineHeight)\n\t\t\tcontext.stroke()\n\t\t\tcolorIndex = 1 - colorIndex\n\t\t\tx += lineWidth\n\t\ty += lineHeight\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\t# Launch a print operation.\n\tlet op = newPrintOperation()\n\top.connect(\"begin_print\", beginPrint, pointer(nil))\n\top.connect(\"draw_page\", drawPage, pointer(nil))\n\n\t# Run the print dialog.\n\tdiscard op.run(printDialog)\n\n\nlet app = newApplication(Application, \"Pinstripe\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 866, + "length": 1254, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\tWidth = 400\n\tHeight = 300\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the color bars.\n\n\tconst Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],\n\t\t\t\t\t\t\t\t\t[0.0, 255.0, 0.0], [0.0, 0.0, 255.0],\n\t\t\t\t\t\t\t\t\t[255.0, 0.0, 255.0], [0.0, 255.0, 255.0],\n\t\t\t\t\t\t\t\t\t[255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]\n\n\tconst\n\t\tRectWidth = float(Width div Colors.len)\n\t\tRectHeight = float(Height)\n\n\tvar x = 0.0\n\tfor color in Colors:\n\t\tcontext.rectangle(x, 0, RectWidth, RectHeight)\n\t\tcontext.setSource(color)\n\t\tcontext.fill()\n\t\tx += RectWidth\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Color bars\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the spiral.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"ColorBars\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 867, + "length": 1387, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],\n\t\t\t\t\t\t\t\t[0.0, 255.0, 0.0], [0.0, 0.0, 255.0],\n\t\t\t\t\t\t\t\t[255.0, 0.0, 255.0], [0.0, 255.0, 255.0],\n\t\t\t\t\t\t\t\t[255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]\n\n\nproc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) =\n\t## Process signal \"begin_print\", that is set the number of pages to print.\n\top.setNPages(1)\n\n\nproc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) =\n\t## Draw a page.\n\n\tlet context = printContext.getCairoContext()\n\tlet lineHeight = printContext.height / 4\n\n\tvar y = 0.0\n\tfor lineWidth in [1.0, 2.0, 3.0, 4.0]:\n\t\tcontext.setLineWidth(lineWidth)\n\t\tvar x = 0.0\n\t\tvar colorIndex = 0\n\t\twhile x < printContext.width:\n\t\t\tcontext.setSource(Colors[colorIndex])\n\t\t\tcontext.moveTo(x, y)\n\t\t\tcontext.lineTo(x, y + lineHeight)\n\t\t\tcontext.stroke()\n\t\t\tcolorIndex = (colorIndex + 1) mod Colors.len\n\t\t\tx += lineWidth\n\t\ty += lineHeight\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\t# Launch a print operation.\n\tlet op = newPrintOperation()\n\top.connect(\"begin_print\", beginPrint, pointer(nil))\n\top.connect(\"draw_page\", drawPage, pointer(nil))\n\n\t# Run the print dialog.\n\tdiscard op.run(printDialog)\n\n\nlet app = newApplication(Application, \"ColorPinstripe\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 868, + "length": 1421, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\tWidth = 420\n\tHeight = 420\n\nconst Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0],\n\t\t\t\t\t\t\t\t[0.0, 255.0, 0.0], [0.0, 0.0, 255.0],\n\t\t\t\t\t\t\t\t[255.0, 0.0, 255.0], [0.0, 255.0, 255.0],\n\t\t\t\t\t\t\t\t[255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the color bars.\n\n\tconst lineHeight = Height div 4\n\n\tvar y = 0.0\n\tfor lineWidth in [1.0, 2.0, 3.0, 4.0]:\n\t\tcontext.setLineWidth(lineWidth)\n\t\tvar x = 0.0\n\t\tvar colorIndex = 0\n\t\twhile x < Width:\n\t\t\tcontext.setSource(Colors[colorIndex])\n\t\t\tcontext.moveTo(x, y)\n\t\t\tcontext.lineTo(x, y + lineHeight)\n\t\t\tcontext.stroke()\n\t\t\tcolorIndex = (colorIndex + 1) mod Colors.len\n\t\t\tx += lineWidth\n\t\ty += lineHeight\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Color pinstripe\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the color bars.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"ColorPinstripe\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 869, + "length": 1326, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\tWidth = 640\n\tHeight = 480\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the greyscale bars.\n\n\tconst\n\t\tBlack = 0.0\n\t\tWhite = 1.0\n\n\tvar y = 0.0\n\tvar nrect = 8\n\tlet rectHeight = Height / 4\n\n\t# Draw quarters.\n\tfor quarter in 0..3:\n\t\tlet rectWidth = Width / nrect\n\t\tvar x = 0.0\n\t\tvar (grey, incr) = if (quarter and 1) == 0: (Black, 1 / nrect) else: (White, -1 / nrect)\n\n\t\t# Draw rectangles.\n\t\tfor _ in 1..nrect:\n\t\t\tcontext.rectangle(x, y, rectWidth, rectHeight)\n\t\t\tcontext.setSource([grey, grey, grey])\n\t\t\tcontext.fill()\n\t\t\tx += rectWidth\n\t\t\tgrey += incr\n\n\t\ty += rectHeight\n\t\tnrect *= 2\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Greyscale bars\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the spiral.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"GreyscaleBars\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 870, + "length": 5063, + "source": "Rosetta Code", + "text": "import lenientops, math, random, sequtils, strutils, tables\n\nimport gintro/[gobject, gdk, gtk, gio, cairo]\nimport gintro/glib except PI\n\nconst\n\tSize = 308 # Size of drawing area.\n\tNHexagons = 20 # Number of hexagons.\n\tRadius = 30.0\n\tXOffset = 1 + sin(PI / 6)\n\tYOffset = cos(PI / 6)\n\ntype\n\n\tLetter = range['A'..'Z']\n\n\t# Description of a hexagon.\n\tHexagon = object\n\t\tcx, cy: float\n\t\tletter: Letter\n\t\tselected: bool\n\n\t# Description of the honeycomb.\n\tHoneyComb = ref object\n\t\thexagons: array[NHexagons, Hexagon] # List of hexagons.\n\t\tindexes: tables.Table[char, int] # Mapping letter -> index of hexagon.\n\t\tarchive: seq[Letter] # List of selected letters.\n\t\tlabel: Label # Label displaying the selected letters.\n\n\nproc newHoneyComb(): HoneyComb =\n\t## Create a honeycomb.\n\n\tnew(result)\n\tvar letters = toSeq('A'..'Z')\n\tletters.shuffle()\n\n\tfor i in 0.. results.eps\n#\nimport random, math, strutils\n\nconst\n\tFloatMax = 1.0e100\n\tnPoints = 100_000\n\tnClusters = 11\n\ntype\n\tPoint = object\n\t\tx, y: float\n\t\tgroup: int\n\tPoints = seq[Point]\n\tClusterDist = tuple[indx: int, dist: float]\n\tColorRGB = tuple[r, g, b: float]\n\nproc generatePoints(nPoints: int, radius: float): Points =\n\tresult.setLen(nPoints)\n\tfor i in 0.. d:\n\t\t\tresult.dist = d\n\t\t\tresult.indx = i\n\nproc kpp(points: var Points, clusterCenters: var Points) =\n\tlet\n\t\tchoice = points[rand(points.high)]\n\tclusterCenters[0] = choice\n\n\tvar\n\t\td: seq[float]\n\t\tsum = 0.0\n\n\td.setLen(points.len)\n\n\tfor i in 1..clusterCenters.high:\n\t\tsum = 0.0\n\t\tfor j, p in pairs(points):\n\t\t\td[j] = nearestClusterCenter(p, cluster_centers[0..i])[1]\n\t\t\tsum += d[j]\n\n\t\tsum *= rand(1.0)\n\n\t\tfor j, di in pairs(d):\n\t\t\tsum -= di\n\t\t\tif sum > 0.0:\n\t\t\t\tcontinue\n\t\t\tclusterCenters[i] = points[j]\n\t\t\tbreak\n\n\tfor _, p in mpairs(points):\n\t\tp.group = nearestClusterCenter(p, clusterCenters)[0]\n\n\nproc lloyd(points: var Points, nclusters: int): Points =\n\t#result is the cluster_centers\n\tlet lenpts10 = points.len shr 10\n\tvar\n\t\tchanged = 0\n\t\tminI = 0\n\tresult.setLen(nclusters)\n\n\t# call k++ init\n\tkpp(points, result)\n\n\twhile true:\n\t\t# group element for centroids are used as counters\n\t\tfor _, cc in mpairs(result):\n\t\t\tcc.x = 0.0\n\t\t\tcc.y = 0.0\n\t\t\tcc.group = 0\n\n\t\tfor p in points:\n\t\t\tlet i = p.group\n\t\t\tresult[i].group += 1\n\t\t\tresult[i].x += p.x\n\t\t\tresult[i].y += p.y\n\n\t\tfor _, cc in mpairs(result):\n\t\t\tcc.x /= cc.group.float\n\t\t\tcc.y /= cc.group.float\n\n\t\t# find closest centroid of each PointPtr\n\t\tchanged = 0\n\n\t\tfor _, p in mpairs(points):\n\t\t\tminI = nearest_cluster_center(p, result)[0]\n\t\t\tif minI != p.group:\n\t\t\t\tchanged += 1\n\t\t\t\tp.group = minI\n\n\t\t# stop when 99.9% of points are good\n\t\tif changed <= lenpts10:\n\t\t\tbreak\n\n\tfor i, cc in mpairs(result):\n\t\t\tcc.group = i\n\nproc printEps(points: Points, cluster_centers: Points, W: int = 400, H: int = 400) =\n\tvar\n\t\tcolors: seq[ColorRGB]\n\n\tcolors.setLen(clusterCenters.len)\n\n\t#assert((3.0 * 5.0) mod 11.0 == 4.0)\n\t#assert(3.0 * 5.0 mod 11.0 == 4.0)\n\t#assert((3.0 * 5.0 mod 11.0) / 2.0 == 2.0)\n\t#assert(3.0 * 5.0 mod 11.0 / 2.0 == 2.0)\n\n\tfor i in 0.. p.x: min_x = p.x\n\t\tif max_y < p.y: max_y = p.y\n\t\tif min_y > p.y: min_y = p.y\n\n\tlet\n\t\tscale = min(W.float / (max_x - min_x),\n\t\t\t\t\t\t\tH.float / (max_y - min_y))\n\t\tcx = (max_x + min_x) / 2.0\n\t\tcy = (max_y + min_y) / 2.0\n\n\techo \"%!PS-Adobe-3.0\\n%%BoundingBox: -5 -5 $1 $2\" % [$(W + 10), $(H + 10)]\n\n\techo \"\"\"/l {rlineto} def /m {rmoveto} def\n/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath\n\t gsave 1 setgray fill grestore gsave 3 setlinewidth\n 1 setgray stroke grestore 0 setgray stroke }def\"\"\"\n\n\tfor i, cc in pairs(clusterCenters):\n\t\techo \"$1 $2 $3 setrgbcolor\" %\n\t\t\t\t\t\t[formatFloat(colors[i].r, ffDecimal, 6),\n\t\t\t\t\t\t formatFloat(colors[i].g, ffDecimal, 6),\n\t\t\t\t\t\t formatFloat(colors[i].b, ffDecimal, 6)]\n\n\t\tfor p in points:\n\t\t\tif p.group != i:\n\t\t\t\tcontinue\n\t\t\techo \"$1 $2 c\" % [formatFloat( ((p.x - cx) * scale + W / 2), ffDecimal, 3),\n\t\t\t\t\t\t\t\t\t\t\t\tformatFloat( ((p.y - cy) * scale + H / 2), ffDecimal, 3)]\n\n\t\techo \"\\n0 setgray $1 $2 s\" % [formatFloat( ((cc.x - cx) * scale + W / 2), ffDecimal, 3),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tformatFloat( ((cc.y - cy) * scale + H / 2), ffDecimal, 3)]\n\n\techo \"\\nshowpage\\n%%EOF\"\n\n\nproc main() =\n\trandomize()\n\n\tvar\n\t\tpoints = generatePoints(nPoints, 10.0)\n\tlet\n\t\tclusterCentrs = lloyd(points, nClusters)\n\tprintEps(points, clusterCentrs)\n\nmain()\n" + }, + { + "id": 872, + "length": 2645, + "source": "Rosetta Code", + "text": "import deques, sets, strutils\n\ntype\n\n\tSokoban = object\n\t\tdestBoard: string\n\t\tcurrBoard: string\n\t\tnCols: Natural\n\t\tplayerX: Natural\n\t\tplayerY: Natural\n\n\tBoard = tuple[cur, sol: string; x, y: int]\n\n\nfunc initSokoban(board: openArray[string]): Sokoban =\n\tresult.nCols = board[0].len\n\tfor row in 0..board.high:\n\t\tfor col in 0.. 1e-12:\n\t\t\t\tx0 = x\n\t\t\t\tx -= calc x\n\n\t\tresult[i][0] = x\n\t\tresult[i][1] = 2 / ((1.0 - x^2) * (x.deriveLegendreIn n)^2)\n\nproc integ(f: proc(x: float): float; ns, p1, p2: int): float =\n\ttemplate dist: untyped =\n\t\t(p2 - p1).float / 2.0\n\ttemplate avg: untyped =\n\t\t(p1 + p2).float / 2.0\n\tresult = dist()\n\tvar\n\t\tsum = 0'f\n\t\tthenodes = newseq[float](ns)\n\t\tweights = newseq[float](ns)\n\tfor i, nw in ns.nodes:\n\t\tsum += nw[1] * f(dist() * nw[0] + avg())\n\t\tthenodes[i] = nw[0]\n\t\tweights[i] = nw[1]\n\n\tlet apos = \":\"\n\tstdout.write fmt\"\"\"{\"nodes\":>8}{apos}\"\"\"\n\tfor n in thenodes:\n\t\tstdout.write \" {n:>6.5f}\"\n\tstdout.write \"\\n\"\n\tstdout.write \"\"\"{\"weights\":>8}{apos}\"\"\"\n\tfor w in weights:\n\t\tstdout.write \" {w:>6.5f}\"\n\tstdout.write \"\\n\"\n\tresult *= sum\n\nproc main =\n\techo \"integral: \", integ(exp, 5, -3, 3)\n\nmain()\n" + }, + { + "id": 875, + "length": 1102, + "source": "Rosetta Code", + "text": "import times\nimport strformat\n\nproc printCalendar(year, nCols: int) =\n\tvar rows = 12 div nCols\n\tvar date = initDateTime(1, mJan, year, 0, 0, 0, utc())\n\tif rows mod nCols != 0:\n\t\tinc rows\n\tvar offs = getDayOfWeek(date.monthday, date.month, date.year).int\n\tvar mons: array[12, array[8, string]]\n\tfor m in 0..11:\n\t\tmons[m][0] = \"{$date.month:^21}\"\n\t\tmons[m][1] = \" Su Mo Tu We Th Fr Sa\"\n\t\tvar dim = getDaysInMonth(date.month, date.year)\n\t\tfor d in 1..42:\n\t\t\tvar day = d > offs and d <= offs + dim\n\t\t\tvar str = if day: \" {d-offs:2}\" else: \" \"\n\t\t\tmons[m][2 + (d - 1) div 7] &= str\n\t\toffs = (offs + dim) mod 7\n\t\tdate = date + months(1)\n\tvar snoopyString, yearString: string\n\tformatValue(snoopyString, \"[Snoopy Picture]\", \"^\" & $(nCols * 24 + 4))\n\tformatValue(yearString, $year, \"^\" & $(nCols * 24 + 4))\n\techo snoopyString, \"\\n\" , yearString, \"\\n\"\n\tfor r in 0.. 11:\n\t\t\t\tbreak\n\t\t\tfor i, line in mons[r * nCols + c]:\n\t\t\t\ts[i] &= \" {line}\"\n\t\tfor line in s:\n\t\t\tif line == \"\":\n\t\t\t\tbreak\n\t\t\techo line\n\t\techo \"\"\n\nprintCalendar(1969, 3)\n" + }, + { + "id": 876, + "length": 591, + "source": "Rosetta Code", + "text": "import strutils\n\nproc encrypt(msg, key: string): string =\n\tvar pos = 0\n\tfor c in msg:\n\t\tif c in Letters:\n\t\t\tresult.add chr(((ord(key[pos]) + ord(c.toUpperAscii)) mod 26) + ord('A'))\n\t\t\tpos = (pos + 1) mod key.len\n\nproc decrypt(msg, key: string): string =\n\tvar pos = 0\n\tfor c in msg:\n\t\tresult.add chr(((26 + ord(c) - ord(key[pos])) mod 26) + ord('A'))\n\t\tpos = (pos + 1) mod key.len\n\nconst text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nconst key = \"VIGENERECIPHER\"\n\nlet encr = encrypt(text, key)\nlet decr = decrypt(encr, key)\n\necho text\necho encr\necho decr\n" + }, + { + "id": 877, + "length": 4064, + "source": "Rosetta Code", + "text": "import sequtils, strutils, sugar, tables, times\n\nconst\n\n\tCipherText = \"\"\"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n\t\t\t\t\t\t\t\t\tVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n\t\t\t\t\t\t\t\t\tITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n\t\t\t\t\t\t\t\t\tFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n\t\t\t\t\t\t\t\t\tALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n\t\t\t\t\t\t\t\t\tILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n\t\t\t\t\t\t\t\t\tJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n\t\t\t\t\t\t\t\t\tLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n\t\t\t\t\t\t\t\t\tMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n\t\t\t\t\t\t\t\t\tQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n\t\t\t\t\t\t\t\t\tRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n\t\t\t\t\t\t\t\t\tTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n\t\t\t\t\t\t\t\t\tSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n\t\t\t\t\t\t\t\t\tZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n\t\t\t\t\t\t\t\t\tBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n\t\t\t\t\t\t\t\t\tBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n\t\t\t\t\t\t\t\t\tFWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\"\".splitWhitespace.join()\n\n\tFreqLetters = {'E': 12.702, 'T': 9.056, 'A': 8.167, 'O': 7.507,\n\t\t\t\t\t\t\t\t 'I': 6.966, 'N': 6.749, 'S': 6.327, 'H': 6.094,\n\t\t\t\t\t\t\t\t 'R': 5.987, 'D': 4.253, 'L': 4.025, 'C': 2.782,\n\t\t\t\t\t\t\t\t 'U': 2.758, 'M': 2.406, 'W': 2.361, 'F': 2.228,\n\t\t\t\t\t\t\t\t 'G': 2.015, 'Y': 1.974, 'P': 1.929, 'B': 1.492,\n\t\t\t\t\t\t\t\t 'V': 0.978, 'K': 0.772, 'J': 0.153, 'X': 0.150,\n\t\t\t\t\t\t\t\t 'Q': 0.095, 'Z': 0.074}.toTable\n\n\tFreqDigraphs = {\"TH\": 15.2, \"HE\": 12.8, \"IN\": 9.4, \"ER\": 9.4,\n\t\t\t\t\t\t\t\t\t\"AN\": 8.2, \"RE\": 6.8, \"ND\": 6.3, \"AT\": 5.9,\n\t\t\t\t\t\t\t\t\t\"ON\": 5.7, \"NT\": 5.6, \"HA\": 5.6, \"ES\": 5.6,\n\t\t\t\t\t\t\t\t\t\"ST\": 5.5, \"EN\": 5.5, \"ED\": 5.3, \"TO\": 5.2,\n\t\t\t\t\t\t\t\t\t\"IT\": 5.0, \"OU\": 5.0, \"EA\": 4.7, \"HI\": 4.6,\n\t\t\t\t\t\t\t\t\t\"IS\": 4.6, \"OR\": 4.3, \"TI\": 3.4, \"AS\": 3.3,\n\t\t\t\t\t\t\t\t\t\"TE\": 2.7, \"ET\": 1.9, \"NG\": 1.8, \"OF\": 1.6,\n\t\t\t\t\t\t\t\t\t\"AL\": 0.9, \"DE\": 0.9, \"SE\": 0.8, \"LE\": 0.8,\n\t\t\t\t\t\t\t\t\t\"SA\": 0.6, \"SI\": 0.5, \"AR\": 0.4, \"VE\": 0.4,\n\t\t\t\t\t\t\t\t\t\"RA\": 0.4, \"LD\": 0.2, \"UR\": 0.2}.toTable\n\n\tFreqTrigraphs = {\"THE\": 18.1, \"AND\": 7.3, \"ING\": 7.2, \"ION\": 4.2,\n\t\t\t\t\t\t\t\t\t \"ENT\": 4.2, \"HER\": 3.6, \"FOR\": 3.4, \"THA\": 3.3,\n\t\t\t\t\t\t\t\t\t \"NTH\": 3.3, \"INT\": 3.2, \"TIO\": 3.1, \"ERE\": 3.1,\n\t\t\t\t\t\t\t\t\t \"TER\": 3.0, \"EST\": 2.8, \"ERS\": 2.8, \"HAT\": 2.6,\n\t\t\t\t\t\t\t\t\t \"ATI\": 2.6, \"ATE\": 2.5, \"ALL\": 2.5, \"VER\": 2.4,\n\t\t\t\t\t\t\t\t\t \"HIS\": 2.4, \"HES\": 2.4, \"ETH\": 2.4, \"OFT\": 2.2,\n\t\t\t\t\t\t\t\t\t \"STH\": 2.1, \"RES\": 2.1, \"OTH\": 2.1, \"ITH\": 2.1,\n\t\t\t\t\t\t\t\t\t \"FTH\": 2.1, \"ONT\": 2.0}.toTable\n\nfunc decrypt(enc, key: string): string =\n\tlet encLen = enc.len\n\tlet keyLen = key.len\n\tresult.setLen(encLen)\n\tvar k = 0\n\tfor i in 0.. maxSubscore:\n\t\t\t\t\tmaxSubscore = subscore\n\t\t\t\t\tkey[i] = j\n\t\t\tfor item in idx.mitems: inc item\n\n\t\tlet dec = decrypt(enc, key)\n\t\tvar score = 0.0\n\t\tfor i in dec:\n\t\t\tscore += FreqLetters[i]\n\n\t\tfor i in 0..(encLen - 3):\n\t\t\tlet digraph = dec[i..(i+1)]\n\t\t\tlet trigraph = dec[i..(i+2)]\n\t\t\tscore += 2 * FreqDigraphs.getOrDefault(digraph)\n\t\t\tscore += 3 * FreqTrigraphs.getOrDefault(trigraph)\n\n\t\tif score > maxScore:\n\t\t\tmaxScore = score\n\t\t\tresult.maxKey = key\n\t\t\tresult.maxDec = dec\n\nlet t0 = cpuTime()\nlet (key, dec) = CipherText.cryptanalyze()\necho \"key: \", key, '\\n'\necho dec, '\\n'\necho \"Elapsed time: \", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), \" s\"\n" + }, + { + "id": 878, + "length": 1987, + "source": "Rosetta Code", + "text": "import tables\n\nconst Names = [\"audino\", \"bagon\", \"baltoy\", \"banette\", \"bidoof\", \"braviary\", \"bronzor\",\n\t\t\t\t\t\t\t \"carracosta\", \"charmeleon\", \"cresselia\", \"croagunk\", \"darmanitan\", \"deino\",\n\t\t\t\t\t\t\t \"emboar\", \"emolga\", \"exeggcute\", \"gabite\", \"girafarig\", \"gulpin\", \"haxorus\",\n\t\t\t\t\t\t\t \"heatmor\", \"heatran\", \"ivysaur\", \"jellicent\", \"jumpluff\", \"kangaskhan\",\n\t\t\t\t\t\t\t \"kricketune\", \"landorus\", \"ledyba\", \"loudred\", \"lumineon\", \"lunatone\",\n\t\t\t\t\t\t\t \"machamp\", \"magnezone\", \"mamoswine\", \"nosepass\", \"petilil\", \"pidgeotto\",\n\t\t\t\t\t\t\t \"pikachu\", \"pinsir\", \"poliwrath\", \"poochyena\", \"porygon2\", \"porygonz\",\n\t\t\t\t\t\t\t \"registeel\", \"relicanth\", \"remoraid\", \"rufflet\", \"sableye\", \"scolipede\",\n\t\t\t\t\t\t\t \"scrafty\", \"seaking\", \"sealeo\", \"silcoon\", \"simisear\", \"snivy\", \"snorlax\",\n\t\t\t\t\t\t\t \"spoink\", \"starly\", \"tirtouga\", \"trapinch\", \"treecko\", \"tyrogue\", \"vigoroth\",\n\t\t\t\t\t\t\t \"vulpix\", \"wailord\", \"wartortle\", \"whismur\", \"wingull\", \"yamask\"]\n\ntype\n\tIndex = range[0..Names.len-1]\n\tIndexSet = set[Index]\n\tSuccessors = Table[Index, IndexSet]\n\nconst All = {Index.low..Index.high} # All indexes.\n\n\nfunc initSuccessors(): Successors {.compileTime.} =\n\t## Build the mapping from name indexes to set of possible successor indexes.\n\n\tvar names: Table[char, IndexSet] # Map first char to IndexSet.\n\tfor idx, name in Names:\n\t\tnames.mgetOrPut(name[0], {}).incl(idx)\n\tfor idx, name in Names:\n\t\tresult[idx] = names.getOrDefault(name[^1]) - {idx}\n\n# Mapping name index -> set of successor indexes.\nconst Succ = initSuccessors()\n\n\nproc search(starts, available: IndexSet): seq[Index] =\n\t## Search one of the longest sequence of indexes for given\n\t## starting indexes and given available name indexes.\n\tvar maxLen = -1\n\tfor idx in starts * available:\n\t\tlet list = search(Succ[idx], available - {idx})\n\t\tif list.len > maxLen:\n\t\t\tresult = idx & list\n\t\t\tmaxLen = list.len\n\n\nlet list = search(starts = All, available = All)\necho \"Longest lists have length: \", list.len\necho \"One of these lists is:\"\nfor idx in list: echo Names[idx]\n" + }, + { + "id": 879, + "length": 2492, + "source": "Rosetta Code", + "text": "import strutils, tables\n\nconst\n\tFullStop = '.'\n\tEscape = '/'\n\ntype Checkerboard = object\n\tencryptTable: Table[char, string]\n\tdecryptTable: Table[string, char]\n\n\nproc initCheckerboard(digits: string; row1, row2, row3: string): Checkerboard =\n\t## Initialize a checkerboard with given digits in row 0 and the following given rows.\n\t## No sanity check is performed.\n\n\tvar rowChars: seq[char] # The two characters to use to identify rows 2 and 3.\n\n\t# Process row 1.\n\tfor col, ch in row1:\n\t\tif ch == ' ':\n\t\t\trowChars.add digits[col]\n\t\telse:\n\t\t\tresult.encryptTable[ch] = $digits[col]\n\tif rowChars.len != 2:\n\t\traise newException(ValueError, \"expected two blank spots in first letter row.\")\n\n\t# Add rows 2 and 3.\n\tfor col, ch in row2:\n\t\tresult.encryptTable[ch] = rowChars[0] & digits[col]\n\tfor col, ch in row3:\n\t\tresult.encryptTable[ch] = rowChars[1] & digits[col]\n\tif Escape notin result.encryptTable:\n\t\traise newException(ValueError, \"missing Escape character.\")\n\n\t# Build decrypt table from encrypt table.\n\tfor c, s in result.encryptTable.pairs:\n\t\tresult.decryptTable[s] = c\n\n\nproc encrypt(board: Checkerboard; message: string): string =\n\t## Encrypt a string.\n\n\tlet message = message.toUpperAscii\n\tfor ch in message:\n\t\tcase ch\n\t\tof 'A'..'Z', FullStop, Escape:\n\t\t\tresult.add board.encryptTable[ch]\n\t\tof '0'..'9':\n\t\t\tresult.add board.encryptTable[Escape]\n\t\t\tresult.add ch\n\t\telse:\n\t\t\tdiscard # Ignore other characters.\n\n\nproc raiseError() =\n\t## Raise a ValueError to signal a corrupt message.\n\traise newException(ValueError, \"corrupt message\")\n\n\nproc decrypt(board: Checkerboard; message: string): string =\n\t## Decrypt a message.\n\n\tvar escaped = false # Escape char previously encountered.\n\tvar str = \"\" # Current sequence of characters (contains 0, 1 or 2 chars).\n\n\tfor ch in message:\n\t\tif ch notin '0'..'9': raiseError()\n\n\t\tif escaped:\n\t\t\t# Digit is kept as is.\n\t\t\tresult.add ch\n\t\t\tescaped = false\n\t\telse:\n\t\t\t# Try to decrypt this new digit.\n\t\t\tstr.add ch\n\t\t\tif str in board.decryptTable:\n\t\t\t\tlet c = board.decryptTable[str]\n\t\t\t\tif c == Escape: escaped = true\n\t\t\t\telse: result.add c\n\t\t\t\tstr.setLen(0)\n\t\t\telif str.len == 2:\n\t\t\t\t# Illegal combination of two digits.\n\t\t\t\traiseError()\n\nwhen isMainModule:\n\tlet board = initCheckerboard(\"8752390146\", \"ET AON RIS\", \"BC/FGHJKLM\", \"PQD.VWXYZU\")\n\tlet message = \"you have put on 7.5 pounds since I saw you.\"\n\techo \"Message: \", message\n\tlet crypted = board.encrypt(message)\n\techo \"Crypted: \", crypted\n\techo \"Decrypted: \", board.decrypt(crypted)\n" + }, + { + "id": 880, + "length": 956, + "source": "Rosetta Code", + "text": "import os, osproc, strformat, strscans\n\n# Retrieve video modes.\nlet p = startProcess(\"xrandr\", \"\", [\"-q\"], nil, {poUsePath})\nvar currWidth, currHeight = 0 # Current video mode.\nvar width, height = 0 # Some other video mode.\nfor line in p.lines:\n\techo line\n\t# Find current display mode, marked by an asterisk.\n\tvar f: float\n\tif currWidth == 0:\n\t\t# Find current width and height.\n\t\tdiscard line.scanf(\" $s$ix$i $s$f*\", currWidth, currHeight, f)\n\telif width == 0:\n\t\t# Find another width and height.\n\t\tdiscard line.scanf(\" $s$ix$i $s$f\", width, height, f)\np.close()\n\n# Change video mode.\nlet newMode = \"{width}x{height}\"\nsleep 1000\necho \"\\nSwitching to \", newMode\nsleep 2000\ndiscard execProcess(\"xrandr\", \"\", [\"-s\", newMode], nil, {poUsePath})\n\n# Restore previous video mode.\nlet prevMode = \"{currWidth}x{currHeight}\"\nsleep 1000\necho \"\\nSwitching back to \", prevMode\nsleep 2000\ndiscard execProcess(\"xrandr\", \"\", [\"-s\", prevMode], nil, {poUsePath})\n" + }, + { + "id": 881, + "length": 3933, + "source": "Rosetta Code", + "text": "import os, random, sequtils\nimport ncurses\n\nconst\n\tLineLength = 5\n\tDisjoint = 0\n\ntype\n\tState {.pure.} = enum Blank, Occupied, DirNS, DirEW, DirNESW, DirNWSE, NewlyAdded, Current\n\tStates = set[State]\n\tBoard = seq[seq[States]]\n\tMove = tuple[m, s, seqnum, x, y: int]\n\nconst Ofs = [(0, 1, DirNS), (1, 0, DirEW), (1, -1, DirNESW), (1, 1, DirNWSE)]\n\n\nfunc set(board: var Board; value: State; x0, y0, x1, y1: int) =\n\tfor i in y0..y1:\n\t\tfor j in x0..x1:\n\t\t\tboard[i][j] = {value}\n\n\nfunc initBoard(): Board =\n\tlet height, width = 3 * (LineLength - 1)\n\tresult = newSeqWith(height, newSeq[States](width))\n\tresult.set(Occupied, LineLength - 1, 1, 2 * LineLength - 3, height - 2)\n\tresult.set(Occupied, 1, LineLength - 1, width - 2, 2 * LineLength - 3)\n\tresult.set(Blank, LineLength, 2, 2 * LineLength - 4, height - 3)\n\tresult.set(Blank, 2, LineLength, width - 3, 2 * LineLength - 4)\n\n\nfunc expand(board: var Board; dw, dh: int) =\n\n\t# -1: expand low index end, +1: expand high index end.\n\tlet\n\t\theight = board.len\n\t\twidth = board[0].len\n\t\tnw = width + ord(dw != 0)\n\t\tnh = height + ord(dh != 0)\n\n\tvar nboard = newSeqWith(nh, newSeq[States](nw))\n\tlet dw = -ord(dw < 0)\n\tlet dh = -ord(dh < 0)\n\n\tfor i in 0..= width or yy < 0 or yy >= height: break\n\t\t\t\tif Occupied notin board[yy][xx]: break # No piece at position.\n\t\t\t\tif dir in board[yy][xx]: break # This direction taken.\n\t\t\tif k != LineLength: continue\n\n\t\t\t# Position ok.\n\t\t\t# Rand to even each option chance of being picked.\n\t\t\tif rand(rec.seqnum) == 0:\n\t\t\t\trec.m = m; rec.s = s; rec.x = x; rec.y = y\n\t\t\tinc rec.seqnum\n\n\nproc addPiece(board: var Board; rec: Move) =\n\tlet (dx, dy, dir) = Ofs[rec.m]\n\tboard[rec.y][rec.x] = board[rec.y][rec.x] + {Current, Occupied}\n\tfor k in 0..= Disjoint or k < LineLength - Disjoint:\n\t\t\tboard[yy][xx].incl dir\n\n\nproc nextMove(board: var Board): bool {.discardable.} =\n\tvar rec: Move\n\tlet maxi = board.high\n\tlet maxj = board[0].high\n\n\t# Wipe last iteration new line markers.\n\tfor row in board.mitems:\n\t\tfor cell in row.mitems:\n\t\t\tcell = cell - {NewlyAdded, Current}\n\n\t# Randomly pick one of next legal move.\n\tfor i in 0..maxi:\n\t\tfor j in 0..maxj:\n\t\t\tboard.testPosition(i, j, rec)\n\n\t# Didn't find any move, game over.\n\tif rec.seqnum == 0: return false\n\n\tboard.addPiece(rec)\n\n\trec.x = if rec.x == maxj: 1\n\t\t\t\t\telif rec.x != 0: 0\n\t\t\t\t\telse: -1\n\trec.y = if rec.y == maxi: 1\n\t\t\t\t\telif rec.y != 0: 0\n\t\t\t\t\telse: -1\n\n\tif rec.x != 0 or rec.y != 0: board.expand(rec.x, rec.y)\n\tresult = true\n\n\nproc play() =\n\trandomize()\n\tvar board = initBoard()\n\tvar waitKey = true\n\tlet win {.used.} = initscr()\n\tnoecho()\n\tcbreak()\n\n\tvar move = 0\n\twhile true:\n\t\tmvprintw(0, 0, \"Move %d\", move)\n\t\tinc move\n\t\tboard.show()\n\t\tif not board.nextMove():\n\t\t\tboard.nextMove()\n\t\t\tboard.show()\n\t\t\tbreak\n\t\tif not waitKey: sleep(100)\n\t\tlet ch = getch()\n\t\tif ch == ord(' '):\n\t\t\twaitKey = not waitKey\n\t\t\tif waitKey: timeout(-1)\n\t\t\telse: timeout(0)\n\t\telif ch == ord('q'):\n\t\t\tbreak\n\n\ttimeout(-1)\n\tgetch()\n\tnocbreak()\n\tonecho()\n\tendwin()\n\nplay()\n" + }, + { + "id": 882, + "length": 4574, + "source": "Rosetta Code", + "text": "import math, strutils\n\ntype Matrix[height, width: static Positive; T: SomeNumber] = array[height, array[width, T]]\n\n\nproc `$`(m: Matrix): string =\n\tfor i, row in m:\n\t\tvar line = \"[\"\n\t\tfor j, val in row:\n\t\t\tline.addSep(\" \", 1)\n\t\t\tline.add($val)\n\t\tline.add(\"]\\n\")\n\t\tresult.add(line)\n\n# Templates.\n\ntemplate elementWise(m1, m2: Matrix; op: proc(v1, v2: m1.T): auto): untyped =\n\tvar result: Matrix[m1.height, m1.width, m1.T]\n\tfor i in 0.. aux2:\n\t\t\tinc a, c\n\t\t\tinc b, d\n\t\telse:\n\t\t\tinc c, a\n\t\t\tinc d, b\n\tvar gcd = gcd(a + c, b + d)\n\tif flagNeg:\n\t\tRational(numerator: -(a + c) div gcd, denominator: (b + d) div gcd)\n\telse:\n\t\tRational(numerator: (a + c) div gcd, denominator: (b + d) div gcd)\n\necho rationalize(0.9054054054)\necho rationalize(0.9054054054, 0.0001)\necho rationalize(0.5185185185)\necho rationalize(0.5185185185, 0.0001)\necho rationalize(0.75)\necho rationalize(0.1428571428, 0.001)\necho rationalize(35.000)\necho rationalize(35.001)\necho rationalize(0.9)\necho rationalize(0.99)\necho rationalize(0.909)\necho rationalize(0.909, 0.001)\n" + }, + { + "id": 884, + "length": 2102, + "source": "Rosetta Code", + "text": "import math, strformat, strutils\nimport arraymancer\n\n# First part: QR decomposition.\n\nproc eye(n: Positive): Tensor[float] =\n\t## Return the (n, n) identity matrix.\n\tresult = newTensor[float](n.int, n.int)\n\tfor i in 0.. maxPeri: return\n\tinc(prim)\n\ttotal += maxPeri div p\n\n\tfor i in 0..2:\n\t\tnewTri([u[i][0] * ins[0] + u[i][1] * ins[1] + u[i][2] * ins[2],\n\t\t\t\t\t\tu[i][3] * ins[0] + u[i][4] * ins[1] + u[i][5] * ins[2],\n\t\t\t\t\t\tu[i][6] * ins[0] + u[i][7] * ins[1] + u[i][8] * ins[2]])\n\nwhile maxPeri <= 100_000_000:\n\ttotal = 0\n\tprim = 0\n\tnewTri([3, 4, 5])\n\techo \"Up to \", maxPeri, \": \", total, \" triples, \", prim, \" primitives\"\n\tmaxPeri *= 10\n" + }, + { + "id": 886, + "length": 1168, + "source": "Rosetta Code", + "text": "type HistoryVar[T] = object\n\thist: seq[T]\n\nffunc initHistoryVar[T](value: T = T.default): HistoryVar[T] =\n\t## Initialize a history variable with given value.\n\tresult.hist.add value\n\nfunc set(h: var HistoryVar; value: h.T) =\n\t## Set the history variable to given value.\n\th.hist.add value\n\nfunc get(h: HistoryVar): h.T =\n\t## Return the current value of history variable.\n\th.hist[^1]\n\nproc showHistory(h: HistoryVar) =\n\t## Show the history starting from oldest values.\n\tfor i, value in h.hist:\n\t\techo i, \": \", value\n\nfunc pop(h: var HistoryVar): h.T =\n\t## Pop the current value and return it.\n\tif h.hist.len > 1: h.hist.pop() else: h.hist[0]\n\n\nwhen isMainModule:\n\n\tvar h = initHistoryVar[int]() # Initialized to 0.\n\n\techo \"Assigning three values: 1, 2, 3\"\n\th.set(1) # 0, 1\n\th.set(2) # 0, 1, 2\n\th.set(3) # 0, 1, 2, 3\n\n\techo \"History (oldest values first):\"\n\th.showHistory()\n\n\techo \"Current value is \", h.get()\n\n\techo \"Recall the three values:\"\n\techo h.pop() # -> 3, last value removed.\n\techo h.pop() # -> 2, last value removed.\n\techo h.pop() # -> 1, last value removed.\n\n\techo \"History (note that initial value can never be removed):\"\n\th.showHistory()\n" + }, + { + "id": 887, + "length": 827, + "source": "Rosetta Code", + "text": "import strformat\n\nconst Jobs = 12\n\ntype Environment = object\n\tsequence: int\n\tcount: int\n\nvar\n\tenv: array[Jobs, Environment]\n\tsequence, count: ptr int\n\n\nproc hail() =\n\tstdout.write fmt\"{sequence[]: 4d}\"\n\tif sequence[] == 1: return\n\tinc count[]\n\tsequence[] = if (sequence[] and 1) != 0: 3 * sequence[] + 1\n\t\t\t\t\t\t\t else: sequence[] div 2\n\n\nproc switchTo(id: int) =\n\tsequence = addr(env[id].sequence)\n\tcount = addr(env[id].count)\n\n\ntemplate forAllJobs(statements: untyped): untyped =\n\tfor i in 0..`(a, b: Choice): bool =\n\t## By construction, only the successor is greater than the choice.\n\ta == Successor[b]\n\nproc choose(history: History): Choice =\n\t## Make a weighted random choice using the player counts\n\t## then select the choice likely to beat it.\n\tvar value = rand(1..history.total)\n\tfor choice, count in history.counts.pairs:\n\t\tif value <= count:\n\t\t\treturn Successor[choice]\n\t\tdec value, count\n\n\nrandomize()\n\n# Initialize history with one for each choice in order to avoid special case.\nvar history: History = (3, [Rock, Paper, Scissors].toCountTable)\n\necho \"To quit game, type 'q' when asked for your choice.\"\n\nvar myChoice, yourChoice: Choice\nvar myWins, yourWins = 0\n\nwhile true:\n\n\t# Get player choice.\n\ttry:\n\t\tstdout.write \"Rock(1), paper(2), scissors(3). Your choice? \"\n\t\tlet answer = stdin.readLine().strip()\n\t\tif answer == \"q\":\n\t\t\tquit \"Quitting game.\", QuitSuccess\n\t\tif answer notin [\"1\", \"2\", \"3\"]:\n\t\t\techo \"Invalid choice.\"\n\t\t\tcontinue\n\t\tyourChoice = Choice(ord(answer[0]) - ord('1'))\n\texcept EOFError:\n\t\tquit \"Quitting game.\", QuitFailure\n\n\t# Make my choice.\n\tmyChoice = history.choose()\n\techo \"I choosed \", myChoice, '.'\n\thistory.counts.inc yourChoice\n\tinc history.total\n\n\t# Display result of round.\n\tif myChoice == yourChoice:\n\t\techo \"It's a tie.\"\n\telif myChoice > yourChoice:\n\t\techo \"I win.\"\n\t\tinc myWins\n\telse:\n\t\techo \"You win.\"\n\t\tinc yourWins\n\techo \"Total wins. You: \", yourWins, \" Me: \", myWins\n" + }, + { + "id": 891, + "length": 730, + "source": "Rosetta Code", + "text": "proc binDigits(x: BiggestInt, r: int): int =\n\t## Calculates how many digits `x` has when each digit covers `r` bits.\n\tresult = 1\n\tvar y = x shr r\n\twhile y > 0:\n\t\ty = y shr r\n\t\tinc(result)\n\nproc toBin*(x: BiggestInt, len: Natural = 0): string =\n\t## converts `x` into its binary representation. The resulting string is\n\t## always `len` characters long. By default the length is determined\n\t## automatically. No leading ``0b`` prefix is generated.\n\tvar\n\t\tmask: BiggestInt = 1\n\t\tshift: BiggestInt = 0\n\t\tlen = if len == 0: binDigits(x, 1) else: len\n\tresult = newString(len)\n\tfor j in countdown(len-1, 0):\n\t\tresult[j] = chr(int((x and mask) shr shift) + ord('0'))\n\t\tshift = shift + 1\n\t\tmask = mask shl 1\n\nfor i in 0..15:\n\techo toBin(i)\n" + }, + { + "id": 892, + "length": 793, + "source": "Rosetta Code", + "text": "import terminal\n\necho \"Press the return key to go to next step.\"\necho \"Starting in the middle of last line.\"\n\ntemplate waitUser() =\n\twhile getch() != '\\r': discard\n\nlet (width, height) = terminalSize()\n# Start by positionning the cursor in the middle of the line.\nsetCursorXPos(width div 2)\nwaitUser()\n# Move one character backward.\ncursorBackward(1)\nwaitUser()\n# Move one character forward.\ncursorForward(1)\nwaitUser()\n# Move one character up.\ncursorUp(1)\nwaitUser()\n# Move one character down.\ncursorDown(1)\nwaitUser()\n# Move at beginning of line.\nsetCursorXPos(0)\nwaitUser()\n# Move at end of line.\nsetCursorXPos(width - 1)\nwaitUser()\n# Move cursor to the top left corner.\nsetCursorPos(0, 0)\nwaitUser()\n# Move cursor to the bottom right corner.\nsetCursorPos(width - 1, height - 1)\nwaitUser()\n" + }, + { + "id": 893, + "length": 1521, + "source": "Rosetta Code", + "text": "import endians, math, stats, strformat\n\nconst\n\tFreqs = [261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3]\n\tNotes = [\"Doh\", \"Ray\", \"Mee\", \"Fah\", \"Soh\", \"Lah\", \"Tee\", \"doh\"]\n\n\nfunc getNote(freq: float): string =\n\tvar index = Freqs.len\n\tfor i, f in Freqs:\n\t\tif freq <= f:\n\t\t\tindex = i\n\t\t\tbreak\n\tresult = if index == 0:\n\t\t\t\t\t\t \"Doh-\"\n\t\t\t\t\t elif index == Freqs.len:\n\t\t\t\t\t\t \"doh+\"\n\t\t\t\t\t elif Freqs[index] - freq <= freq - Freqs[index-1]:\n\t\t\t\t\t\t Notes[index] & '-'\n\t\t\t\t\t else:\n\t\t\t\t\t\t Notes[index-1] & '+'\n\n\nproc getUint32(buffer: openArray[byte]; pos: Natural): uint32 =\n\tlittleEndian32(result.addr, buffer[pos].unsafeAddr)\n\n\nlet file = open(\"notes.wav\")\nvar hdr: array[44, byte]\nlet n = file.readBytes(hdr, 0, hdr.len)\ndoAssert n == hdr.len\n\n# Check header parameters.\nlet sampleRate = hdr.getUint32(24)\necho \"Sample rate: \", sampleRate\nlet dataLength = hdr.getUint32(40)\nlet duration = dataLength div sampleRate\necho \"Duration: \", duration\n\nvar sum = 0.0\nlet sampleRateF = float(sampleRate)\nvar data = newSeq[byte](sampleRate)\nlet nbytes = 20\necho \"Bytes examined: \", nbytes, \" per sample\"\nfor j in 0..= lines.len:\n\t\traise newException(IOError, \"trying to delete lines after end of file.\")\n\n\t# Delete the lines and write the file.\n\tlines.delete(first, last)\n\tfilename.writeFile(lines.join())\n" + }, + { + "id": 895, + "length": 775, + "source": "Rosetta Code", + "text": "proc no_args() =\n\tdiscard\n# call\nno_args()\n\nproc fixed_args(x, y) =\n\techo x\n\techo y\n# calls\nfixed_args(1, 2) # x=1, y=2\nfixed_args 1, 2 # same call\n1.fixed_args(2) # same call\n\n\nproc opt_args(x=1.0) =\n\techo x\n# calls\nopt_args() # 1\nopt_args(3.141) # 3.141\n\nproc var_args(v: varargs[string, `$`]) =\n\tfor x in v: echo x\n# calls\nvar_args(1, 2, 3) # (1, 2, 3)\nvar_args(1, (2,3)) # (1, (2, 3))\nvar_args() # ()\n\n## Named arguments\nfixed_args(y=2, x=1) # x=1, y=2\n\n## As a statement\nif true:\n\tno_args()\n\nproc return_something(x): int =\n\tx + 1\n\nvar a = return_something(2)\n\n## First-class within an expression\nlet x = return_something(19) + 10\nlet y = 19.return_something() + 10\nlet z = 19.return_something + 10\n" + }, + { + "id": 896, + "length": 661, + "source": "Rosetta Code", + "text": "type\n\tNode[T] = ref TNode[T]\n\tTNode[T] = object\n\t\tdata: T\n\t\tleft, right: Node[T]\n\nproc newNode[T](data: T; left, right: Node[T] = nil): Node[T] =\n\tNode[T](data: data, left: left, right: right)\n\nproc preorder[T](n: Node[T]): seq[T] =\n\tif n == nil: @[]\n\telse: @[n.data] & preorder(n.left) & preorder(n.right)\n\nvar tree = 1.newNode(\n\t\t\t\t\t\t 2.newNode(\n\t\t\t\t\t\t\t 4.newNode(\n\t\t\t\t\t\t\t\t 7.newNode),\n\t\t\t\t\t\t\t 5.newNode),\n\t\t\t\t\t\t 3.newNode(\n\t\t\t\t\t\t\t 6.newNode(\n\t\t\t\t\t\t\t\t 8.newNode,\n\t\t\t\t\t\t\t\t 9.newNode)))\n\nvar tree2: Node[int]\ntree2.deepCopy tree\ntree2.data = 10\ntree2.left.data = 20\ntree2.right.left.data = 90\n\necho \"Tree2:\"\necho preorder tree2\n\necho \"Tree:\"\necho preorder tree\n" + }, + { + "id": 897, + "length": 1282, + "source": "Rosetta Code", + "text": "from sequtils import newSeqWith\nfrom random import rand, randomize\nfrom times import now\nimport libgd\n\nconst\n\timg_width = 400\n\timg_height = 300\n\tnSites = 20\n\nproc dot(x, y: int): int = x * x + y * y\n\nproc generateVoronoi(img: gdImagePtr) =\n\n\trandomize(cast[int64](now()))\n\n\t# random sites\n\tlet sx = newSeqWith(nSites, rand(img_width))\n\tlet sy = newSeqWith(nSites, rand(img_height))\n\n\t# generate a random color for each site\n\tlet sc = newSeqWith(nSites, img.setColor(rand(255), rand(255), rand(255)))\n\n\t# generate diagram by coloring each pixel with color of nearest site\n\tfor x in 0 ..< img_width:\n\t\tfor y in 0 ..< img_height:\n\t\t\tvar dMin = dot(img_width, img_height)\n\t\t\tvar sMin: int\n\t\t\tfor s in 0 ..< nSites:\n\t\t\t\tif (let d = dot(sx[s] - x, sy[s] - y); d) < dMin:\n\t\t\t\t\t(sMin, dMin) = (s, d)\n\n\t\t\timg.setPixel(point=[x, y], color=sc[sMin])\n\n\t# mark each site with a black box\n\tlet black = img.setColor(0x000000)\n\tfor s in 0 ..< nSites:\n\t\timg.drawRectangle(\n\t\t\tstartCorner=[sx[s] - 2, sy[s] - 2],\n\t\t\tendCorner=[sx[s] + 2, sy[s] + 2],\n\t\t\tcolor=black,\n\t\t\tfill=true)\n\nproc main() =\n\n\twithGd imageCreate(img_width, img_height, trueColor=true) as img:\n\t\timg.generateVoronoi()\n\n\t\tlet png_out = open(\"outputs/voronoi_diagram.png\", fmWrite)\n\t\timg.writePng(png_out)\n\t\tpng_out.close()\n\nmain()\n" + }, + { + "id": 898, + "length": 709, + "source": "Rosetta Code", + "text": "import os, strutils, terminal\n\nvar delay: int\nwhile true:\n\tstdout.write \"Enter delay in seconds: \"\n\tstdout.flushFile()\n\ttry:\n\t\tdelay = stdin.readLine.strip().parseInt()\n\t\tbreak\n\texcept ValueError:\n\t\techo \"Error: invalid value.\"\n\texcept EOFError:\n\t\techo()\n\t\tquit \"Quitting.\", QuitFailure\n\nvar filename: string\nwhile true:\n\tstdout.write \"Enter mp3 file name (without extension): \"\n\tstdout.flushFile()\n\ttry:\n\t\tfilename = stdin.readLine\n\t\tbreak\n\texcept EOFError:\n\t\techo ()\n\t\tquit \"Quitting.\", QuitFailure\n\nstdout.eraseScreen()\necho \"Alarm will sound in $# second(s)...\".format(delay)\nos.sleep delay * 1000\nstdout.eraseScreen()\nif execShellCmd(\"play $#.mp3\" % filename) != 0:\n\techo \"Error while playing mp3 file.\"\n" + }, + { + "id": 899, + "length": 949, + "source": "Rosetta Code", + "text": "import osproc, strutils\n\nproc getValue[T: int | float](msg: string; minval, maxval: T): T =\n\twhile true:\n\t\tstdout.write msg\n\t\tstdout.flushFile()\n\t\ttry:\n\t\t\tresult = when T is int: stdin.readLine.strip().parseInt()\n\t\t\t\t\t\t\t else: stdin.readLine.strip().parseFloat()\n\t\t\tif result notin minval..maxval:\n\t\t\t\techo \"Invalid value\"\n\t\t\telse:\n\t\t\t\treturn\n\t\texcept ValueError:\n\t\t\techo \"Error: invalid value.\"\n\t\texcept EOFError:\n\t\t\techo()\n\t\t\tquit \"Quitting.\", QuitFailure\n\nconst FileName = \"loop.wav\"\nlet reps = getValue(\"Enter number of repetitions (1 to 6): \", 1, 6)\nlet delay = getValue(\"Enter delay between repetitions in microseconds (50 to 500): \", 50, 500)\nlet decay = getValue(\"Enter decay between repetitions (0.2 to 0.9): \", 0.2, 0.9)\n\nvar args = @[FileName, \"echo\", \"0.8\", \"0.7\"]\nvar decay2 = 1.0\nfor i in 1..reps:\n\tdecay2 *= decay\n\targs.add $(i * delay)\n\targs.add $decay2\necho execProcess(\"play\", args = args, options = {poStdErrToStdOut, poUsePath})\n" + }, + { + "id": 900, + "length": 1348, + "source": "Rosetta Code", + "text": "import deques, sequtils\n\ntemplate shfl(idx): untyped = (K*(idx+1)) mod I\n\nfunc mutuallyprime(I, K: int16): bool {.compiletime.} =\n\t## compile time check shuffling works properly\n\tlet\n\t\tx = {1'i16..I}\n\t\ts = x.toSeq\n\tvar r: set[int16]\n\tfor n in 0.. m\n\t## because (i-j) is always less than m\n\ntemplate next(state): untyped =\n\tstate.addLast (state[^I]-state[^J]) % M\n\tdiscard state.popFirst()\n\nfunc seedGen[I, J, K, M: static int](seed: range[0..M-1]): Deque[int] =\n\tvar s = @[seed, 1]\n\tfor _ in 2.. 0, \"all params must be positive\"\n\t\tassert I > J, \"I must be > J\"\n\t\tassert mutuallyprime(I, K), \"I, K must be relatively prime\"\n\tvar r = seedGen[I, J, K, M](seed)\n\tresult = proc(): int =\n\t\tr.next\n\t\tr.peekLast\n\nlet subGen* = initSubGen[55, 24, 34, 1e9.int]\n\nwhen isMainModule:\n\tlet rand = subGen(292929)\n\tfor _ in 1..3:\n\t\techo rand()\n" + }, + { + "id": 901, + "length": 1109, + "source": "Rosetta Code", + "text": "type\n\tPriElem[T] = tuple\n\t\tdata: T\n\t\tpri: int\n\n\tPriQueue[T] = object\n\t\tbuf: seq[PriElem[T]]\n\t\tcount: int\n\n# first element not used to simplify indices\nproc initPriQueue[T](initialSize = 4): PriQueue[T] =\n\tresult.buf.newSeq(initialSize)\n\tresult.buf.setLen(1)\n\tresult.count = 0\n\nproc add[T](q: var PriQueue[T], data: T, pri: int) =\n\tvar n = q.buf.len\n\tvar m = n div 2\n\tq.buf.setLen(n + 1)\n\n\t# append at end, then up heap\n\twhile m > 0 and pri < q.buf[m].pri:\n\t\tq.buf[n] = q.buf[m]\n\t\tn = m\n\t\tm = m div 2\n\n\tq.buf[n] = (data, pri)\n\tq.count = q.buf.len - 1\n\nproc pop[T](q: var PriQueue[T]): PriElem[T] =\n\tassert q.buf.len > 1\n\tresult = q.buf[1]\n\n\tvar qn = q.buf.len - 1\n\tvar n = 1\n\tvar m = 2\n\twhile m < qn:\n\t\tif m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri:\n\t\t\tinc m\n\n\t\tif q.buf[qn].pri <= q.buf[m].pri:\n\t\t\tbreak\n\n\t\tq.buf[n] = q.buf[m]\n\t\tn = m\n\t\tm = m * 2\n\n\tq.buf[n] = q.buf[qn]\n\tq.buf.setLen(q.buf.len - 1)\n\tq.count = q.buf.len - 1\n\nvar p = initPriQueue[string]()\np.add(\"Clear drains\", 3)\np.add(\"Feed cat\", 4)\np.add(\"Make tea\", 5)\np.add(\"Solve RC tasks\", 1)\np.add(\"Tax return\", 2)\n\nwhile p.count > 0:\n\techo p.pop()\n" + }, + { + "id": 902, + "length": 725, + "source": "Rosetta Code", + "text": "import os\nimport parseopt\n\nproc main =\n\t# Directly accessing the app name and parameters\n\techo \"app name: \", getAppFilename().extractFilename()\n\techo \"# parameters: \", paramCount()\n\tfor ii in 1 .. paramCount(): # 1st param is at index 1\n\t\techo \"param \", ii, \": \", paramStr(ii)\n\n\techo \"\"\n\n\t# Using parseopt module to extract short and long options and arguments\n\tvar argCtr : int\n\n\tfor kind, key, value in getOpt():\n\t\tcase kind\n\t\tof cmdArgument:\n\t\t\techo \"Got arg \", argCtr, \": \\\"\", key, \"\\\"\"\n\t\t\targCtr.inc\n\n\t\tof cmdLongOption, cmdShortOption:\n\t\t\tcase key\n\t\t\tof \"v\", \"n\", \"z\", \"w\":\n\t\t\t\techo \"Got a \\\"\", key, \"\\\" option with value: \\\"\", value, \"\\\"\"\n\t\t\telse:\n\t\t\t\techo \"Unknown option: \", key\n\n\t\tof cmdEnd:\n\t\t\tdiscard\n\n\nmain()\n" + }, + { + "id": 903, + "length": 2936, + "source": "Rosetta Code", + "text": "import algorithm\nimport nimPNG\n\ntype\n\n\tChannel {.pure.} = enum R, G, B\n\n\tQItem = tuple\n\t\tcolor: array[Channel, byte] # Color of the pixel.\n\t\tindex: int # Position of pixel in the sequential sequence.\n\n\nproc quantize(bucket: openArray[QItem]; output: var seq[byte]) =\n\t## Apply the quantization to the pixels in the bucket.\n\n\t# Compute the mean value on each channel.\n\tvar means: array[Channel, int]\n\tfor qItem in bucket:\n\t\tfor channel in R..B:\n\t\t\tmeans[channel] += qItem.color[channel].int\n\tfor channel in R..B:\n\t\tmeans[channel] = (means[channel] / bucket.len).toInt\n\n\t# Store the new colors into the pixels.\n\tfor qItem in bucket:\n\t\tfor channel in R..B:\n\t\t\toutput[3 * qItem.index + ord(channel)] = means[channel].byte\n\n\nproc medianCut(bucket: openArray[QItem]; depth: Natural; output: var seq[byte]) =\n\t## Apply the algorithm on the bucket.\n\n\tif depth == 0:\n\t\t# Terminated for this bucket. Apply the quantization.\n\t\tquantize(bucket, output)\n\t\treturn\n\n\t# Compute the range of values for each channel.\n\tvar minVal: array[Channel, int] = [1000, 1000, 1000]\n\tvar maxVal: array[Channel, int] = [-1, -1, -1]\n\tfor qItem in bucket:\n\t\tfor channel in R..B:\n\t\t\tlet val = qItem.color[channel].int\n\t\t\tif val < minVal[channel]: minVal[channel] = val\n\t\t\tif val > maxVal[channel]: maxVal[channel] = val\n\tlet valRange: array[Channel, int] = [maxVal[R] - minVal[R],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t maxVal[G] - minVal[G],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t maxVal[B] - minVal[B]]\n\n\t# Find the channel with the greatest range.\n\tvar selchannel: Channel\n\tif valRange[R] >= valRange[G]:\n\t\tif valRange[R] >= valRange[B]:\n\t\t\tselchannel = R\n\t\telse:\n\t\t\tselchannel = B\n\telif valrange[G] >= valrange[B]:\n\t\tselchannel = G\n\telse:\n\t\tselchannel = B\n\n\t# Sort the quantization items according to the selected channel.\n\tlet sortedBucket = case selchannel\n\t\t\t\t\t\t\t\t\t\t of R: sortedByIt(bucket, it.color[R])\n\t\t\t\t\t\t\t\t\t\t of G: sortedByIt(bucket, it.color[G])\n\t\t\t\t\t\t\t\t\t\t of B: sortedByIt(bucket, it.color[B])\n\n\t# Split the bucket into two buckets.\n\tlet medianIndex = bucket.high div 2\n\tmedianCut(sortedBucket.toOpenArray(0, medianIndex), depth - 1, output)\n\tmedianCut(sortedBucket.toOpenArray(medianIndex, bucket.high), depth - 1, output)\n\n\nconst Input = \"Quantum_frog.png\"\nconst Output = \"Quantum_frog_16.png\"\n\nlet pngImage = loadPNG24(seq[byte], Input).get()\n\n# Build the first bucket.\nvar bucket = newSeq[QItem](pngImage.data.len div 3)\nvar idx: Natural = 0\nfor item in bucket.mitems:\n\titem = (color: [pngImage.data[idx], pngImage.data[idx + 1], pngImage.data[idx + 2]],\n\t\t\t\t\tindex: idx div 3)\n\tinc idx, 3\n\n# Create the storage for the quantized image.\nvar data = newSeq[byte](pngImage.data.len)\n\n# Launch the quantization.\nmedianCut(bucket, 4, data)\n\n# Save the result into a PNG file.\nlet status = savePNG24(Output, data, pngImage.width, pngImage.height)\nif status.isOk:\n\techo \"File \", Input, \" processed. Result is available in file \", Output\nelse:\n\techo \"Error: \", status.error\n" + }, + { + "id": 904, + "length": 602, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\n\t# Define int constants instead of an enum to use only ints and strings.\n\tShorter = -1\n\tSameLength = 0\n\tLonger = 1\n\ntype LengthComparison = range[Shorter..Longer]\n\nfunc cmpLength(a, b: string): LengthComparison =\n\tlet a = repeat(' ', a.len)\n\tlet b = repeat(' ', b.len)\n\tresult = if a in b: (if b in a: SameLength else: Shorter) else: Longer\n\nvar longest = \"\"\nvar result = \"\"\nfor line in \"longest_string_challenge.txt\".lines:\n\tcase cmpLength(line, longest)\n\tof Shorter:\n\t\tdiscard\n\tof SameLength:\n\t\tresult.add '\\n' & line\n\tof Longer:\n\t\tlongest = line\n\t\tresult = line\n\necho result\n" + }, + { + "id": 905, + "length": 1276, + "source": "Rosetta Code", + "text": "const S = 10\n\ntype\n\n\tNodeKind = enum nodeFree, nodeA, nodeB\n\n\tNode = object\n\t\tv: float\n\t\tfixed: NodeKind\n\n\tMesh[H, W: static int] = array[H, array[W, Node]]\n\n\nfunc setBoundary(m: var Mesh) =\n\tm[1][1].v = 1.0\n\tm[1][1].fixed = nodeA\n\tm[6][7].v = -1.0\n\tm[6][7].fixed = nodeB\n\n\nfunc calcDiff[H, W: static int](m,: Mesh[H, W]; d: var Mesh[H, W]): float =\n\tfor i in 0.. 0:\n\t\t\t\tv += m[i - 1][j].v\n\t\t\t\tinc n\n\t\t\tif j > 0:\n\t\t\t\tv += m[i][j - 1].v\n\t\t\t\tinc n\n\t\t\tif i + 1 < m.H:\n\t\t\t\tv += m[i + 1][j].v\n\t\t\t\tinc n\n\t\t\tif j + 1 < m.W:\n\t\t\t\tv += m[i][j + 1].v\n\t\t\t\tinc n\n\t\t\tv = m[i][j].v - v / n.toFloat\n\t\t\td[i][j].v = v\n\t\t\tif m[i][j].fixed == nodeFree:\n\t\t\t\tresult += v * v\n\n\nfunc iter[H, W: static int](m: var Mesh[H, W]): float =\n\tvar\n\t\td: Mesh[H, W]\n\t\tcur: array[NodeKind, float]\n\t\tdiff = 1e10\n\n\twhile diff > 1e-24:\n\t\tm.setBoundary()\n\t\tdiff = calcDiff(m, d)\n\t\tfor i in 0.. number of iterations.\n\n\niterator sequence(seed: string): string =\n\t## Yield the successive strings of a sequence.\n\n\tvar history: HashSet[string]\n\thistory.incl seed\n\tvar current = seed\n\tyield current\n\n\twhile true:\n\t\tvar counts = current.toCountTable()\n\t\tvar next: string\n\t\tfor ch in sorted(toSeq(counts.keys), Descending):\n\t\t\tnext.add $counts[ch] & ch\n\t\tif next in history: break\n\t\tcurrent = move(next)\n\t\thistory.incl current\n\t\tyield current\n\n\nproc seqLength(seed: string): int =\n\t## Return the number of iterations for the given seed.\n\tlet key = sorted(seed, Descending)\n\tif key in cache: return cache[key]\n\tresult = toSeq(sequence(seed)).len\n\tcache[key] = result\n\n\nvar seeds: seq[int]\nvar itermax = 0\nfor seed in 0..<1_000_000:\n\tlet itercount = seqLength($seed)\n\tif itercount > itermax:\n\t\titermax = itercount\n\t\tseeds = @[seed]\n\telif itercount == itermax:\n\t\tseeds.add seed\n\necho \"Maximum iterations: \", itermax\necho \"Seed values: \", seeds.join(\", \")\necho \"Sequence for $#:\".format(seeds[0])\nfor s in sequence($seeds[0]): echo s\n" + }, + { + "id": 907, + "length": 1254, + "source": "Rosetta Code", + "text": "type Trit* = enum ttrue, tmaybe, tfalse\n\nproc `$`*(a: Trit): string =\n\tcase a\n\tof ttrue: \"T\"\n\tof tmaybe: \"?\"\n\tof tfalse: \"F\"\n\nproc `not`*(a: Trit): Trit =\n\tcase a\n\tof ttrue: tfalse\n\tof tmaybe: tmaybe\n\tof tfalse: ttrue\n\nproc `and`*(a, b: Trit): Trit =\n\tconst t: array[Trit, array[Trit, Trit]] =\n\t\t[ [ttrue, tmaybe, tfalse]\n\t\t, [tmaybe, tmaybe, tfalse]\n\t\t, [tfalse, tfalse, tfalse] ]\n\tt[a][b]\n\nproc `or`*(a, b: Trit): Trit =\n\tconst t: array[Trit, array[Trit, Trit]] =\n\t\t[ [ttrue, ttrue, ttrue]\n\t\t, [ttrue, tmaybe, tmaybe]\n\t\t, [ttrue, tmaybe, tfalse] ]\n\tt[a][b]\n\nproc then*(a, b: Trit): Trit =\n\tconst t: array[Trit, array[Trit, Trit]] =\n\t\t[ [ttrue, tmaybe, tfalse]\n\t\t, [ttrue, tmaybe, tmaybe]\n\t\t, [ttrue, ttrue, ttrue] ]\n\tt[a][b]\n\nproc equiv*(a, b: Trit): Trit =\n\tconst t: array[Trit, array[Trit, Trit]] =\n\t\t[ [ttrue, tmaybe, tfalse]\n\t\t, [tmaybe, tmaybe, tmaybe]\n\t\t, [tfalse, tmaybe, ttrue] ]\n\tt[a][b]\n\n\nwhen isMainModule:\n\n\timport strutils\n\n\tfor t in Trit:\n\t\techo \"Not \", t , \": \", not t\n\n\tfor op1 in Trit:\n\t\tfor op2 in Trit:\n\t\t\techo \"$# and $#: $#\".format(op1, op2, op1 and op2)\n\t\t\techo \"$# or $#: $#\".format(op1, op2, op1 or op2)\n\t\t\techo \"$# then $#: $#\".format(op1, op2, op1.then op2)\n\t\t\techo \"$# equiv $#: $#\".format(op1, op2, op1.equiv op2)\n" + }, + { + "id": 908, + "length": 6371, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\nconst\n\tN = 32\n\tNMax = 40_000\n\ntype Save = tuple[p: ptr int; v: int]\n\nvar\n\tu: array[N, int] # Upper bounds.\n\tl: array[N, int] # Lower bounds.\nu[0] = 1; u[1] = 2\nl[0] = 1; l[1] = 2\n\nvar outp, sum, tail: array[N, int]\n\nvar cache: array[NMax + 1, int]\ncache[2] = 1\n\nvar\n\tknown = 2\n\tstack = 0\n\tundo: array[N * N, Save]\n\n\nproc replace(x: var openArray[int]; i, n: int) =\n\tundo[stack] = (x[i].addr, x[i])\n\tx[i] = n\n\tinc stack\n\n\nproc restore(n: int) =\n\twhile stack > n:\n\t\tdec stack\n\t\tundo[stack].p[] = undo[stack].v\n\n\nproc bounds(n: int): tuple[lower, upper: int] =\n\t# Return lower and upper bounds.\n\tif n <= 2 or n <= NMax and cache[n] != 0:\n\t\treturn (cache[n], cache[n])\n\tvar\n\t\ti = -1\n\t\to = 0\n\t\tn = n\n\twhile n != 0:\n\t\tif (n and 1) != 0: inc o\n\t\tn = n shr 1\n\t\tinc i\n\tdec i\n\tresult.upper = o + i\n\twhile true:\n\t\tinc i\n\t\to = o shr 1\n\t\tif o == 0: break\n\to = 2\n\twhile o * o < n:\n\t\tif n mod o == 0:\n\t\t\tlet q = cache[o] + cache[n div o]\n\t\t\tif q < result.upper:\n\t\t\t\tresult.upper = q\n\t\t\t\tif q == i: break\n\t\tinc o\n\tif n > 2:\n\t\tif result.upper > cache[n - 2] + 1:\n\t\t\tresult.upper = cache[n - 1] + 1\n\t\tif result.upper > cache[n - 2] + 1:\n\t\t\tresult.upper = cache[n - 2] + 1\n\tresult.lower = i\n\n\nproc insert(x, pos: int): bool =\n\tlet save = stack\n\n\tif l[pos] > x or u[pos] < x:\n\t\treturn false\n\n\tif l[pos] != x:\n\t\tl.replace(pos, x)\n\t\tvar i = pos - 1\n\t\twhile u[i] * 2 < u[i+1]:\n\t\t\tlet t = l[i+1] + 1\n\t\t\tif t * 2 > u[i]:\n\t\t\t\trestore(save)\n\t\t\t\treturn false\n\t\t\tl.replace(i, t)\n\t\t\tdec i\n\t\ti = pos + 1\n\t\twhile l[i] <= l[i-1]:\n\t\t\tlet t = l[i-1] + 1\n\t\t\tif t > u[i]:\n\t\t\t\trestore(save)\n\t\t\t\treturn false\n\t\t\tl.replace(i, t)\n\t\t\tinc i\n\n\tif u[pos] == x:\n\t\treturn true\n\n\tu.replace(pos, x)\n\tvar i = pos - 1\n\twhile u[i] >= u[i+1]:\n\t\tlet t = u[i+1] - 1\n\t\tif t < l[i]:\n\t\t\trestore(save)\n\t\t\treturn false\n\t\tu.replace(i, t)\n\t\tdec i\n\ti = pos + 1\n\twhile u[i] > u[i-1] * 2:\n\t\tlet t = u[i-1] * 2\n\t\tif t < l[i]:\n\t\t\trestore(save)\n\t\t\treturn false\n\t\tu.replace(i, t)\n\t\tinc i\n\n\tresult = true\n\n\n# Forward reference.\nproc seqRecur(le: int): bool\n\n\nproc `try`(p, q, le: int): bool =\n\n\tvar pl = cache[p]\n\tif pl >= le: return false\n\tvar ql = cache[q]\n\tif ql >= le: return false\n\n\twhile pl < le and u[pl] < p: inc pl\n\tvar pu = pl - 1\n\twhile pu < le - 1 and u[pu+1] >= p: inc pu\n\n\twhile ql < le and u[ql] < q: inc ql\n\tvar qu = ql - 1\n\twhile qu < le - 1 and u[qu+1] >= q: inc qu\n\n\tif p != q and pl <= ql: pl = ql + 1\n\tif pl > pu or ql > qu or ql > pu: return false\n\n\tif outp[le] == 0:\n\t\tpu = le - 1\n\t\tpl = pu\n\n\tlet ps = stack\n\twhile pu >= pl:\n\t\tif insert(p, pu):\n\t\t\tinc outp[pu]\n\t\t\tinc sum[pu], le\n\t\t\tif p != q:\n\t\t\t\tlet qs= stack\n\t\t\t\tvar j = qu\n\t\t\t\tif j >= pu: j = pu - 1\n\t\t\t\twhile j >= ql:\n\t\t\t\t\tif insert(q, j):\n\t\t\t\t\t\tinc outp[j]\n\t\t\t\t\t\tinc sum[j], le\n\t\t\t\t\t\ttail[le] = q\n\t\t\t\t\t\tif seqRecur(le - 1): return true\n\t\t\t\t\t\trestore(qs)\n\t\t\t\t\t\tdec outp[j]\n\t\t\t\t\t\tdec sum[j], le\n\t\t\t\t\tdec j\n\t\t\telse:\n\t\t\t\tinc outp[pu]\n\t\t\t\tinc sum[pu], le\n\t\t\t\ttail[le] = p\n\t\t\t\tif seqRecur(le - 1): return true\n\t\t\t\tdec outp[pu]\n\t\t\t\tdec sum[pu], le\n\t\t\tdec outp[pu]\n\t\t\tdec sum[pu], le\n\t\t\trestore(ps)\n\t\tdec pu\n\n\nproc seqRecur(le: int): bool =\n\tlet n = l[le]\n\tif le < 2: return true\n\tvar limit = n - 1\n\tif outp[le] == 1: limit = n - tail[sum[le]]\n\tif limit > u[le-1]: limit = u[le-1]\n\t# Try to break n into p + q, and see if we can insert p, q into\n\t# list while satisfying bounds.\n\tvar p = limit\n\tvar q = n - p\n\twhile q <= p:\n\t\tif `try`(p, q, le): return true\n\t\tdec p\n\t\tinc q\n\n\n# Forward reference.\nproc sequence(n, le: int): int\n\n\nproc seqLen(n: int): int =\n\n\tif n <= known: return cache[n]\n\n\t# Need all lower n to compute sequence.\n\twhile known + 1 < n:\n\t\tdiscard seqLen(known + 1)\n\n\tvar (lb, ub) = bounds(n)\n\twhile lb < ub and sequence(n, lb) == 0: inc lb\n\n\tknown = n\n\tif (n and 1023) == 0: echo \"Cached: \", known\n\tcache[n] = lb\n\tresult = lb\n\n\nproc sequence(n, le: int): int =\n\tlet le = if le != 0: le else: seqLen(n)\n\tstack = 0\n\tl[le] = n\n\tu[le] = n\n\tfor i in 0..le:\n\t\toutp[i] = 0\n\t\tsum[i] = 0\n\tfor i in 2..= u[i+1]:\n\t\t\tu[i] = u[i+1] - 1\n\n\tif not seqRecur(le): return 0\n\tresult = le\n\n\nproc sequence(n, le: int; buf: var openArray[int]): int =\n\tlet le = sequence(n, le)\n\tfor i in 0..le: buf[i] = u[i]\n\tresult = le\n\n\nproc binLen(n: int): int =\n\tvar r, o = -1\n\tvar n = n\n\twhile n != 0:\n\t\tif (n and 1) != 0: inc o\n\t\tn = n shr 1\n\t\tinc r\n\tresult = r + o\n\n\ntype\n\tVector = seq[float]\n\tMatrix = seq[Vector]\n\n\nfunc `*`(m1, m2: Matrix): Matrix =\n\tlet\n\t\trows1 = m1.len\n\t\tcols1 = m1[0].len\n\t\trows2 = m2.len\n\t\tcols2 = m2[0].len\n\tif cols1 != rows2:\n\t\traise newException(ValueError, \"Matrices cannot be multiplied.\")\n\n\tresult = newSeqWith(rows1, newSeq[float](cols2))\n\tfor i in 0.. e[i]: continue\n\t\t\t\t\tv[i] = v[j] * v[k]\n\t\t\t\t\tbreak loop2\n\tresult = v[le]\n\n\nfunc `$`(m: Matrix): string =\n\tfor v in m:\n\t\tresult.add '['\n\t\tlet start = result.len\n\t\tfor x in v:\n\t\t\tresult.addSep(\" \", start)\n\t\t\tresult.add x.formatFloat(ffDecimal, precision = 6).align(9)\n\t\tresult.add \"]\\n\"\n\n\nvar m = 27182\nvar n = 31415\necho \"Precompute chain lengths:\"\ndiscard seqlen(n)\nlet rh = sqrt(0.5)\nlet mx: Matrix = @[@[ rh, 0.0, rh, 0.0, 0.0, 0.0],\n\t\t\t\t\t\t\t\t\t @[0.0, rh, 0.0, rh, 0.0, 0.0],\n\t\t\t\t\t\t\t\t\t @[0.0, rh, 0.0, -rh, 0.0, 0.0],\n\t\t\t\t\t\t\t\t\t @[-rh, 0.0, rh, 0.0, 0.0, 0.0],\n\t\t\t\t\t\t\t\t\t @[0.0, 0.0, 0.0, 0.0, 0.0, 1.0],\n\t\t\t\t\t\t\t\t\t @[0.0, 0.0, 0.0, 0.0, 1.0, 0.0]]\n\necho \"\\nThe first 100 terms of A003313 are:\"\nfor i in 1..100:\n\tstdout.write seqLen(i), ' '\n\tif i mod 10 == 0: echo()\n\nlet exs = [m, n]\nvar mxs: array[2, Matrix]\nfor i, ex in exs:\n\techo()\n\techo \"Exponent: \", ex\n\tmxs[i] = mx.pow(ex, true)\n\techo \"A ^ $#:\\n\".format(ex)\n\techo mxs[i]\n\techo \"Number of A/C multiplies: \", seqLen(ex)\n\techo \" c.f. Binary multiplies: \", binLen(ex)\necho()\necho \"Exponent: $1 x $2 = $3\".format(m, n, m * n)\necho \"A ^ $1 = (A ^ $2) ^ $3:\\n\".format(m * n, m, n)\necho mxs[0].pow(n, false)\n" + }, + { + "id": 909, + "length": 2271, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat, strutils, tables\n\n\nconst\n\tStates = @[\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n\t\t\t\t\t\t \"California\", \"Colorado\", \"Connecticut\", \"Delaware\",\n\t\t\t\t\t\t \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\",\n\t\t\t\t\t\t \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\",\n\t\t\t\t\t\t \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n\t\t\t\t\t\t \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n\t\t\t\t\t\t \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n\t\t\t\t\t\t \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n\t\t\t\t\t\t \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\", \"Rhode Island\",\n\t\t\t\t\t\t \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n\t\t\t\t\t\t \"Utah\", \"Vermont\", \"Virginia\",\n\t\t\t\t\t\t \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"]\n\n\tFictitious = @[\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"]\n\ntype MatchingPairs = ((string, string), (string, string))\n\n\nproc matchingPairs(states: openArray[string]): seq[MatchingPairs] =\n\t## Build the list of matching pairs of states.\n\n\tlet states = sorted(states).deduplicate()\n\n\t# Build a mapping from ordered sequence of chars to sequence of (state, state).\n\tvar mapping: Table[seq[char], seq[(string, string)]]\n\tfor i in 0.. 1:\n\t\t\t# These pairs are candidates.\n\t\t\tfor i in 0..\", importc: \"printf\", varargs.}\n\n# Declaration of a deprecated procedure. If not used, no warning will be emitted.\nproc notUsed(x: int) {.used, deprecated.} = echo x\n\n# Declaration of a type with an alignment constraint.\ntype SseType = object\n\tsseData {.align(16).}: array[4, float32]\n\n# Declaration of a procedure containing a variable to store in register, if possible, and a variable to store as global.\nproc p() =\n\tvar x {.register.}: int\n\tvar y {.global.} = \"abcdef\"\n\n{.push checks: on.}\n# From here, checks are activated.\n...\n{.pop.}\n# From here, checks are deactivated again.\n" + }, + { + "id": 915, + "length": 3362, + "source": "Rosetta Code", + "text": "import strutils\n\nconst Input = \"\"\"\n((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))\n\"\"\"\n\ntype\n\tTokenKind = enum\n\t\ttokInt, tokFloat, tokString, tokIdent\n\t\ttokLPar, tokRPar\n\t\ttokEnd\n\tToken = object\n\t\tcase kind: TokenKind\n\t\tof tokString: stringVal: string\n\t\tof tokInt: intVal: int\n\t\tof tokFloat: floatVal: float\n\t\tof tokIdent: ident: string\n\t\telse: discard\n\nproc lex(input: string): seq[Token] =\n\tvar pos = 0\n\n\ttemplate current: char =\n\t\tif pos < input.len: input[pos]\n\t\telse: '\\x00'\n\n\twhile pos < input.len:\n\t\tcase current\n\t\tof ';':\n\t\t\tinc(pos)\n\t\t\twhile current notin {'\\r', '\\n'}:\n\t\t\t\tinc(pos)\n\t\t\tif current == '\\r': inc(pos)\n\t\t\tif current == '\\n': inc(pos)\n\t\tof '(': inc(pos); result.add(Token(kind: tokLPar))\n\t\tof ')': inc(pos); result.add(Token(kind: tokRPar))\n\t\tof '0'..'9':\n\t\t\tvar\n\t\t\t\tnum = \"\"\n\t\t\t\tisFloat = false\n\t\t\twhile current in Digits:\n\t\t\t\tnum.add(current)\n\t\t\t\tinc(pos)\n\t\t\tif current == '.':\n\t\t\t\tnum.add(current)\n\t\t\t\tisFloat = true\n\t\t\t\tinc(pos)\n\t\t\t\twhile current in Digits:\n\t\t\t\t\tnum.add(current)\n\t\t\t\t\tinc(pos)\n\t\t\tresult.add(if isFloat: Token(kind: tokFloat, floatVal: parseFloat(num))\n\t\t\t\t\t\t\t\t else: Token(kind: tokInt, intVal: parseInt(num)))\n\t\tof ' ', '\\t', '\\n', '\\r': inc(pos)\n\t\tof '\"':\n\t\t\tvar str = \"\"\n\t\t\tinc(pos)\n\t\t\twhile current != '\"':\n\t\t\t\tstr.add(current)\n\t\t\t\tinc(pos)\n\t\t\tinc(pos)\n\t\t\tresult.add(Token(kind: tokString, stringVal: str))\n\t\telse:\n\t\t\tconst BannedChars = {' ', '\\t', '\"', '(', ')', ';'}\n\t\t\tvar ident = \"\"\n\t\t\twhile current notin BannedChars:\n\t\t\t\tident.add(current)\n\t\t\t\tinc(pos)\n\t\t\tresult.add(Token(kind: tokIdent, ident: ident))\n\tresult.add(Token(kind: tokEnd))\n\ntype\n\tSExprKind = enum\n\t\tseInt, seFloat, seString, seIdent, seList\n\tSExpr = ref object\n\t\tcase kind: SExprKind\n\t\tof seInt: intVal: int\n\t\tof seFloat: floatVal: float\n\t\tof seString: stringVal: string\n\t\tof seIdent: ident: string\n\t\tof seList: children: seq[SExpr]\n\tParseError = object of CatchableError\n\nproc `$`*(se: SExpr): string =\n\tcase se.kind\n\tof seInt: result = $se.intVal\n\tof seFloat: result = $se.floatVal\n\tof seString: result = '\"' & se.stringVal & '\"'\n\tof seIdent: result = se.ident\n\tof seList:\n\t\tresult = \"(\"\n\t\tfor i, ex in se.children:\n\t\t\tif ex.kind == seList and ex.children.len > 1:\n\t\t\t\tresult.add(\"\\n\")\n\t\t\t\tresult.add(indent($ex, 2))\n\t\t\telse:\n\t\t\t\tif i > 0:\n\t\t\t\t\tresult.add(\" \")\n\t\t\t\tresult.add($ex)\n\t\tresult.add(\")\")\n\nvar\n\ttokens = lex(Input)\n\tpos = 0\n\ntemplate current: Token =\n\tif pos < tokens.len: tokens[pos]\n\telse: Token(kind: tokEnd)\n\nproc parseInt(token: Token): SExpr =\n\tresult = SExpr(kind: seInt, intVal: token.intVal)\n\nproc parseFloat(token: Token): SExpr =\n\tresult = SExpr(kind: seFloat, floatVal: token.floatVal)\n\nproc parseString(token: Token): SExpr =\n\tresult = SExpr(kind: seString, stringVal: token.stringVal)\n\nproc parseIdent(token: Token): SExpr =\n\tresult = SExpr(kind: seIdent, ident: token.ident)\n\nproc parse(): SExpr\n\nproc parseList(): SExpr =\n\tresult = SExpr(kind: seList)\n\twhile current.kind notin {tokRPar, tokEnd}:\n\t\tresult.children.add(parse())\n\tif current.kind == tokEnd:\n\t\traise newException(ParseError, \"Missing right paren ')'\")\n\telse:\n\t\tinc(pos)\n\nproc parse(): SExpr =\n\tvar token = current\n\tinc(pos)\n\tresult =\n\t\tcase token.kind\n\t\tof tokInt: parseInt(token)\n\t\tof tokFloat: parseFloat(token)\n\t\tof tokString: parseString(token)\n\t\tof tokIdent: parseIdent(token)\n\t\tof tokLPar: parseList()\n\t\telse: nil\n\necho parse()\n" + }, + { + "id": 916, + "length": 570, + "source": "Rosetta Code", + "text": "import random\n\nfunc sOfNCreator[T](n: Positive): proc(item: T): seq[T] =\n\tvar sample = newSeqOfCap[T](n)\n\tvar i = 0\n\n\tresult = proc(item: T): seq[T] =\n\t\t\t\t\t\t inc i\n\t\t\t\t\t\t if i <= n:\n\t\t\t\t\t\t\t sample.add(item)\n\t\t\t\t\t\t elif rand(1..i) <= n:\n\t\t\t\t\t\t\t sample[rand(n - 1)] = item\n\t\t\t\t\t\t sample\n\nwhen isMainModule:\n\n\trandomize()\n\n\techo \"Digits counts for 100_000 runs:\"\n\tvar hist: array[10, Natural]\n\tfor _ in 1..100_000:\n\t\tlet sOfN = sOfNCreator[Natural](3)\n\t\tfor i in 0..8:\n\t\t\tdiscard sOfN(i)\n\t\tfor val in sOfN(9):\n\t\t\tinc hist[val]\n\n\tfor n, count in hist:\n\t\techo n, \": \", count\n" + }, + { + "id": 917, + "length": 617, + "source": "Rosetta Code", + "text": "var cr = @[1]\nvar cs = @[2]\n\nproc extendRS =\n\tlet x = cr[cr.high] + cs[cr.high]\n\tcr.add x\n\tfor y in cs[cs.high] + 1 ..< x: cs.add y\n\tcs.add x + 1\n\nproc ffr(n: int): int =\n\tassert n > 0\n\twhile n > cr.len: extendRS()\n\tcr[n - 1]\n\nproc ffs(n: int): int =\n\tassert n > 0\n\twhile n > cs.len: extendRS()\n\tcs[n - 1]\n\nfor i in 1..10: stdout.write ffr i,\" \"\necho \"\"\n\nvar bin: array[1..1000, int]\nfor i in 1..40: inc bin[ffr i]\nfor i in 1..960: inc bin[ffs i]\nvar all = true\nfor x in bin:\n\tif x != 1:\n\t\tall = false\n\t\tbreak\n\nif all: echo \"All Integers 1..1000 found OK\"\nelse: echo \"All Integers 1..1000 NOT found only once: ERROR\"\n" + }, + { + "id": 918, + "length": 806, + "source": "Rosetta Code", + "text": "import imageman\n\nconst\n\tWidth = 1920\n\tHeight = 1080\n\tMaxDepth = 10\n\tColor = ColorRGBU([byte 0, 255, 0])\n\n\nproc drawTree(img: var Image; x1, y1, x2, y2: int; depth: Natural) =\n\n\tif depth == 0: return\n\n\tlet\n\t\tdx = x2 - x1\n\t\tdy = y1 - y2\n\t\tx3 = x2 - dy\n\t\ty3 = y2 - dx\n\t\tx4 = x1 - dy\n\t\ty4 = y1 - dx\n\t\tx5 = x4 + (dx - dy) div 2\n\t\ty5 = y4 - (dx + dy) div 2\n\n\t# Draw square.\n\timg.drawPolyline(true, Color, (x1, y1), (x2, y2), (x3, y3), (x4, y4))\n\n\t# Draw triangle.\n\timg.drawPolyline(true, Color, (x3, y3), (x4, y4), (x5, y5))\n\n\t# Next level.\n\timg.drawTree(x4, y4, x5, y5, depth - 1)\n\timg.drawTree(x5, y5, x3, y3, depth - 1)\n\n\nvar image = initImage[ColorRGBU](Width, Height)\nimage.drawTree(int(Width / 2.3), Height - 1, int(Width / 1.8), Height - 1, MaxDepth)\nimage.savePNG(\"pythagoras_tree.png\", compression = 9)\n" + }, + { + "id": 919, + "length": 638, + "source": "Rosetta Code", + "text": "import strutils, sequtils\n\ntype\n\tDirection = enum up, right, down, left\n\tColor = enum white, black\n\nconst\n\twidth = 75\n\theight = 52\n\tmaxSteps = 12_000\n\nvar\n\tm: array[height, array[width, Color]]\n\tdir = up\n\tx = width div 2\n\ty = height div 2\n\nvar i = 0\nwhile i < maxSteps and x in 0 ..< width and y in 0 ..< height:\n\tlet turn = m[y][x] == black\n\tm[y][x] = if m[y][x] == black: white else: black\n\n\tdir = Direction((4 + int(dir) + (if turn: 1 else: -1)) mod 4)\n\tcase dir\n\tof up: dec y\n\tof right: dec x\n\tof down: inc y\n\tof left: inc x\n\n\tinc i\n\nfor row in m:\n\techo map(row, proc(x: Color): string =\n\t\tif x == white: \".\" else: \"#\").join(\"\")\n" + }, + { + "id": 920, + "length": 2668, + "source": "Rosetta Code", + "text": "import sequtils, strutils, sugar\n\n# List of possible variables names.\nconst VarChars = {'A'..'E', 'G'..'S', 'U'..'Z'}\n\ntype\n\n\tExpression = object\n\t\tnames: seq[char] # List of variables names.\n\t\tvalues: seq[bool] # Associated values.\n\t\tformula: string # Formula as a string.\n\n\nproc initExpression(str: string): Expression =\n\t## Build an expression from a string.\n\tfor ch in str:\n\t\tif ch in VarChars and ch notin result.names:\n\t\t\tresult.names.add ch\n\tresult.values.setLen(result.names.len)\n\tresult.formula = str\n\n\ntemplate apply(stack: seq[bool]; op: (bool, bool) -> bool): bool =\n\t## Apply an operator on the last two operands of an evaluation stack.\n\t## Needed to make sure that pops are done (avoiding short-circuit optimization).\n\tlet op2 = stack.pop()\n\tlet op1 = stack.pop()\n\top(op1, op2)\n\n\nproc evaluate(expr: Expression): bool =\n\t## Evaluate the current expression.\n\n\tvar stack: seq[bool] # Evaluation stack.\n\n\tfor e in expr.formula:\n\t\tstack.add case e\n\t\t\t\t\t\t\tof 'T': true\n\t\t\t\t\t\t\tof 'F': false\n\t\t\t\t\t\t\tof '!': not stack.pop()\n\t\t\t\t\t\t\tof '&': stack.apply(`and`)\n\t\t\t\t\t\t\tof '|': stack.apply(`or`)\n\t\t\t\t\t\t\tof '^': stack.apply(`xor`)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif e in VarChars: expr.values[expr.names.find(e)]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\traise newException(\n\t\t\t\t\t\t\t\t\t\tValueError, \"Non-conformant character in expression: '$#'.\".format(e))\n\n\tif stack.len != 1:\n\t\traise newException(ValueError, \"Ill-formed expression.\")\n\tresult = stack[0]\n\n\nproc setVariables(expr: var Expression; pos: Natural) =\n\t## Recursively set the variables.\n\t## When all the variables are set, launch the evaluation of the expression\n\t## and print the result.\n\n\tassert pos <= expr.values.len\n\n\tif pos == expr.values.len:\n\t\t# Evaluate and display.\n\t\tlet vs = expr.values.mapIt(if it: 'T' else: 'F').join(\" \")\n\t\tlet es = if expr.evaluate(): 'T' else: 'F'\n\t\techo vs, \" \", es\n\n\telse:\n\t\t# Set values.\n\t\texpr.values[pos] = false\n\t\texpr.setVariables(pos + 1)\n\t\texpr.values[pos] = true\n\t\texpr.setVariables(pos + 1)\n\n\necho \"Accepts single-character variables (except for 'T' and 'F',\"\necho \"which specify explicit true or false values), postfix, with\"\necho \"&|!^ for and, or, not, xor, respectively; optionally\"\necho \"seperated by spaces or tabs. Just enter nothing to quit.\"\n\nwhile true:\n\t# Read formula and create expression.\n\tstdout.write \"\\nBoolean expression: \"\n\tlet line = stdin.readLine.toUpperAscii.multiReplace((\" \", \"\"), (\"\\t\", \"\"))\n\tif line.len == 0: break\n\tvar expr = initExpression(line)\n\tif expr.names.len == 0: break\n\n\t# Display the result.\n\tlet vs = expr.names.join(\" \")\n\techo '\\n', vs, \" \", expr.formula\n\tlet h = vs.len + expr.formula.len + 2\n\techo repeat('=', h)\n\texpr.setVariables(0)\n" + }, + { + "id": 921, + "length": 2160, + "source": "Rosetta Code", + "text": "import algorithm, json, os, strformat, strutils, times\n\nconst FileName = \"simdb.json\"\n\ntype\n\n\tItem = object\n\t\tname: string\n\t\tdate: string\n\t\tcategory: string\n\n\tDatabase = seq[Item]\n\n\tDbError = object of CatchableError\n\n\nproc load(): Database =\n\tif fileExists(FileName):\n\t\tlet node = try: FileName.parseFile()\n\t\t\t\t\t\t\t except JsonParsingError:\n\t\t\t\t\t\t\t\t raise newException(DbError, getCurrentExceptionMsg())\n\t\tresult = node.to(DataBase)\n\n\nproc store(db: Database) =\n\ttry:\n\t\tFileName.writeFile $(%* db)\n\texcept IOError:\n\t\tquit \"Unable to save database.\", QuitFailure\n\n\nproc addItem(args: seq[string]) =\n\tvar db = try: load()\n\t\t\t\t\t except DbError: quit getCurrentExceptionMsg(), QuitFailure\n\n\tlet date = now().format(\"yyyy-MM-dd HH:mm:ss\")\n\tlet cat = if args.len == 2: args[1] else: \"none\"\n\tdb.add Item(name: args[0], date: date, category: cat)\n\tdb.store()\n\n\nproc printLatest(args: seq[string]) =\n\tlet db = try: load()\n\t\t\t\t\t except DbError: quit getCurrentExceptionMsg(), QuitFailure\n\tif db.len == 0:\n\t\techo \"No entries in database.\"\n\t\treturn\n\n\t# No need to sort db as items are added chronologically.\n\tif args.len == 1:\n\t\tvar found = false\n\t\tfor item in reversed(db):\n\t\t\tif item.category == args[0]:\n\t\t\t\techo item\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\tif not found:\n\t\t\techo \"There are no items for category '{args[0]}'\"\n\telse:\n\t\techo db[^1]\n\n\nproc printAll() =\n\tlet db = try: load()\n\t\t\t\t\t except DbError: quit getCurrentExceptionMsg(), QuitFailure\n\tif db.len == 0:\n\t\techo \"No entries in database.\"\n\t\treturn\n\tfor item in db:\n\t\techo item\n\n\nproc printUsage() =\n\techo \"\"\"\nUsage:\n\t{getAppFilename().splitPath().tail} cmd [categoryName]\n\n\tadd add item, followed by optional category\n\tlatest print last added item(s), followed by optional category\n\tall print all\n\n\tFor instance: add \"some item name\" \"some category name\"\n\t\"\"\"\n\tquit QuitFailure\n\n\nif paramCount() notin 1..3: printUsage()\n\nvar params = commandLineParams()\nlet command = params[0].toLowerAscii\nparams.delete(0)\ncase command\nof \"add\":\n\tif params.len == 0: printUsage()\n\taddItem(params)\nof \"latest\":\n\tif params.len > 1: printUsage()\n\tprintLatest(params)\nof \"all\":\n\tif params.len != 0: printUsage()\n\tprintAll()\n" + }, + { + "id": 922, + "length": 722, + "source": "Rosetta Code", + "text": "import rdstdin, strutils, tables\n\nvar history: seq[string]\n\nproc hello =\n\techo \"Hello World!\"\n\thistory.add \"hello\"\n\nproc hist =\n\tif history.len == 0:\n\t\techo \"no history\"\n\telse:\n\t\tfor cmd in history:\n\t\t\techo \" -\", cmd\n\thistory.add \"hist\"\n\nproc help =\n\techo \"Available commands:\"\n\techo \" hello\"\n\techo \" hist\"\n\techo \" exit\"\n\techo \" help\"\n\thistory.add \"help\"\n\nconst Vfs = {\"help\": help, \"hist\": hist, \"hello\": hello}.toTable\n\necho \"Enter a command, type help for a listing.\"\nwhile true:\n\tlet line = try:\n\t\t\t\t\t\t\t readLineFromStdin(\">\").strip()\n\t\t\t\t\t\t except IOError:\n\t\t\t\t\t\t\t echo \"EOF encountered. Bye.\"\n\t\t\t\t\t\t\t break\n\tif line == \"exit\": break\n\tif line notin Vfs:\n\t\techo \"Unknown command, try again.\"\n\telse:\n\t\tVfs[line]()\n" + }, + { + "id": 923, + "length": 1353, + "source": "Rosetta Code", + "text": "# naive function calling counter\n# TODO consider a more sophisticated condition on counting function callings\n# without parenthesis which are common in nim lang. Be aware that the AST of\n# object accessor and procedure calling without parenthesis are same.\n\nimport macros, tables, strformat, os\nproc visitCall(node: NimNode, table: CountTableRef) =\n\tif node.kind == nnkCall:\n\t\tif node[0].kind == nnkDotExpr:\n\t\t\ttable.inc($node[0][1])\n\t\t\tvisitCall(node[0][0], table)\n\t\telse:\n\t\t\tif node[0].kind == nnkBracketExpr:\n\t\t\t\tif node[0][0].kind == nnkDotExpr:\n\t\t\t\t\ttable.inc($node[0][0][1])\n\t\t\t\t\tvisitCall(node[0][0][0], table)\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\ttable.inc($node[0][0])\n\t\t\t\t\tif len(node[0]) > 1:\n\t\t\t\t\t\tfor child in node[0][1..^1]:\n\t\t\t\t\t\t\tvisitCall(child, table)\n\t\t\telif node[0].kind == nnkPar:\n\t\t\t\tvisitCall(node[0], table)\n\t\t\telse:\n\t\t\t\ttable.inc($node[0])\n\t\t\tif len(node) > 1:\n\t\t\t\tfor child in node[1..^1]:\n\t\t\t\t\tvisitCall(child, table)\n\telse:\n\t\tfor child in node.children():\n\t\t\tvisitCall(child, table)\n\nstatic:\n\tconst code = staticRead(expandTilde(\"~/.choosenim/toolchains/nim-{NimVersion}/lib/system.nim\"))\n\tvar\n\t\tast = parseStmt(code)\n\t\tcallCounts = newCountTable[string]()\n\tast.visitCall(callCounts)\n\tsort(callCounts)\n\tvar total = 10\n\tfor ident, times in callCounts.pairs():\n\t\techo(\"{ident} called {times} times\")\n\t\ttotal-=1\n\t\tif total == 0:\n\t\t\tbreak\n" + }, + { + "id": 924, + "length": 614, + "source": "Rosetta Code", + "text": "import rdstdin, re, algorithm, sequtils, strutils\n\n#let templ = readLineFromStdin \"Enter your story: \"\nconst templ = \"\"\" went for a walk in the park. \nfound a . decided to take it home.\"\"\"\n\necho \"The story template is:\\n\", templ\nvar fields = templ.findAll re\"<[^>]+>\"\nfields.sort(cmp)\nfields = deduplicate fields\nlet values = readLineFromStdin(\"\\nInput a comma-separated list of words to replace the following items\\n \" & fields.join(\",\") & \": \").split(\",\")\n\nvar story = templ\nfor f,v in zip(fields, values).items:\n\tstory = story.replace(f, v)\necho \"\\nThe story becomes:\\n\\n\", story\n" + }, + { + "id": 925, + "length": 1291, + "source": "Rosetta Code", + "text": "import os, strutils\n\nconst\n\tSuffix = \".backup\"\n\tDir = \"working_dir\"\n\tSubDir = \"dir\"\n\tf1 = \"f1.txt\"\n\tf2 = \"f2.txt\"\n\tf3 = SubDir / \"file.txt\"\n\nproc newBackup(path: string): string =\n\t## Create a backup file. Return the path to this file.\n\tif not path.fileExists():\n\t\traise newException(IOError, \"file doesn't exist.\")\n\tlet path = path.expandFilename() # This follows symlinks.\n\tresult = path & Suffix\n\tmoveFile(path, result)\n\tresult = result.relativePath(getCurrentDir())\n\n# Prepare test files.\nlet oldDir = getCurrentDir()\ncreateDir(Dir)\nsetCurrentDir(Dir)\ncreateDir(SubDir)\nf1.writeFile(\"This is version 1 of file $#\" % f1)\nf3.writeFile(\"This is version 1 of file $#\" % f3)\ncreateSymlink(f3, f2)\n\n# Display initial state.\necho \"Before backup:\"\necho f1, \": \", f1.readFile\necho f2, \" -> \", f3, \": \", f2.readFile()\n\n# Create backups.\necho \"\\nBackup of regular file:\"\nlet f1Backup = newBackup(f1)\nf1.writeFile(\"This is version 2 of file $#\" % f1)\necho f1, \": \", f1.readFile()\necho f1Backup, \": \", f1Backup.readFile()\n\necho \"\\nBackup of symbolic link to file:\"\nlet f2Backup = newBackup(f2)\nf2.writeFile(\"This is version 2 of file $#\" % f3)\necho f2, \" -> \", f3, \": \", f2.readFile()\necho f2Backup, \": \", f2Backup.readFile()\n\n# Cleanup.\nsetCurrentDir(oldDir)\nremoveDir(Dir)\n" + }, + { + "id": 926, + "length": 920, + "source": "Rosetta Code", + "text": "import bigints\n\nconst\n\tnMax: int32 = 250\n\tnBranches = 4\n\nvar rooted, unrooted: array[nMax + 1, BigInt]\nrooted[0..1] = [1.initBigInt, 1.initBigInt]\nunrooted[0..1] = [1.initBigInt, 1.initBigInt]\nfor i in 2 .. nMax:\n\trooted[i] = 0.initBigInt\n\tunrooted[i] = 0.initBigInt\n\nproc choose(m: BigInt; k: int32): BigInt =\n\tresult = m\n\tif k == 1: return\n\tfor i in 1 ..< k:\n\t\tresult = result * (m + i) div (i + 1)\n\nproc tree(br, n, l, sum: int32; cnt: BigInt) =\n\tvar s: int32 = 0\n\tfor b in br + 1 .. nBranches:\n\t\ts = sum + (b - br) * n\n\t\tif s > nMax: return\n\n\t\tlet c = choose(rooted[n], b - br) * cnt\n\n\t\tif l * 2 < s: unrooted[s] += c\n\t\tif b == nBranches: return\n\t\trooted[s] += c\n\t\tfor m in countdown(n-1, 1):\n\t\t\ttree b, m, l, s, c\n\nproc bicenter(s: int32) =\n\tif (s and 1) == 0:\n\t\tunrooted[s] += rooted[s div 2] * (rooted[s div 2] + 1) div 2\n\nfor n in 1 .. nMax:\n\ttree 0, n, n, 1, 1.initBigInt\n\tn.bicenter\n\techo n, \": \", unrooted[n]\n" + }, + { + "id": 927, + "length": 2814, + "source": "Rosetta Code", + "text": "import algorithm, strformat, sequtils\n\ntype\n\n\tColor {.pure.} = enum Blue, Green, Red, White, Yellow\n\tPerson {.pure.} = enum Dane, English, German, Norwegian, Swede\n\tPet {.pure.} = enum Birds, Cats, Dog, Horse, Zebra\n\tDrink {.pure.} = enum Beer, Coffee, Milk, Tea, Water\n\tCigarettes {.pure.} = enum Blend, BlueMaster = \"Blue Master\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Dunhill, PallMall = \"Pall Mall\", Prince\n\n\tHouse = tuple\n\t\tcolor: Color\n\t\tperson: Person\n\t\tpet: Pet\n\t\tdrink: Drink\n\t\tcigarettes: Cigarettes\n\n\tHouses = array[5, House]\n\n\niterator permutations[T](): array[5, T] =\n\t## Yield the successive permutations of values of type T.\n\tvar term = [T(0), T(1), T(2), T(3), T(4)]\n\tyield term\n\twhile term.nextPermutation():\n\t\tyield term\n\n\nproc findSolutions(): seq[Houses] =\n\t## Return all the solutions.\n\n\tfor colors in permutations[Color]():\n\t\tif colors.find(White) != colors.find(Green) + 1: continue # 5\n\t\tfor persons in permutations[Person]():\n\t\t\tif persons[0] != Norwegian: continue # 10\n\t\t\tif colors.find(Red) != persons.find(English): continue # 2\n\t\t\tif abs(persons.find(Norwegian) - colors.find(Blue)) != 1: continue # 15\n\t\t\tfor pets in permutations[Pet]():\n\t\t\t\tif persons.find(Swede) != pets.find(Dog): continue # 3\n\t\t\t\tfor drinks in permutations[Drink]():\n\t\t\t\t\tif drinks[2] != Milk: continue # 9\n\t\t\t\t\tif persons.find(Dane) != drinks.find(Tea): continue # 4\n\t\t\t\t\tif colors.find(Green) != drinks.find(Coffee): continue # 6\n\t\t\t\t\tfor cigarettes in permutations[Cigarettes]():\n\t\t\t\t\t\tif cigarettes.find(PallMall) != pets.find(Birds): continue # 7\n\t\t\t\t\t\tif cigarettes.find(Dunhill) != colors.find(Yellow): continue # 8\n\t\t\t\t\t\tif cigarettes.find(BlueMaster) != drinks.find(Beer): continue # 13\n\t\t\t\t\t\tif cigarettes.find(Prince) != persons.find(German): continue # 14\n\t\t\t\t\t\tif abs(cigarettes.find(Blend) - pets.find(Cats)) != 1: continue # 11\n\t\t\t\t\t\tif abs(cigarettes.find(Dunhill) - pets.find(Horse)) != 1: continue # 12\n\t\t\t\t\t\tif abs(cigarettes.find(Blend) - drinks.find(Water)) != 1: continue # 16\n\t\t\t\t\t\tvar houses: Houses\n\t\t\t\t\t\tfor i in 0..4:\n\t\t\t\t\t\t\thouses[i] = (colors[i], persons[i], pets[i], drinks[i], cigarettes[i])\n\t\t\t\t\t\tresult.add houses\n\nlet solutions = findSolutions()\necho \"Number of solutions: \", solutions.len\nlet sol = solutions[0]\necho()\n\necho \"Number Color Person Pet Drink Cigarettes\"\necho \"------ ------ --------- ----- ------ -----------\"\nfor i in 0..4:\n\techo \"{i + 1:3} {sol[i].color:6} {sol[i].person:9} \",\n\t\t\t \"{sol[i].pet:5} {sol[i].drink:6} {sol[i].cigarettes: 11}\"\n\nlet owner = sol.filterIt(it.pet == Zebra)[0].person\necho \"\\nThe {owner} owns the zebra.\"\n" + }, + { + "id": 928, + "length": 1165, + "source": "Rosetta Code", + "text": "import tables, strutils, strformat\n\ntype operator = tuple[prec:int, rassoc:bool]\n\nlet ops = newTable[string, operator](\n\t[ (\"^\", (4, true )),\n\t\t(\"*\", (3, false)),\n\t\t(\"/\", (3, false)),\n\t\t(\"+\", (2, false)),\n\t\t(\"-\", (2, false)) ])\n\nproc shuntRPN(tokens:seq[string]): string =\n\tvar stack: seq[string]\n\tvar op:string\n\n\tfor token in tokens:\n\t\tcase token\n\t\tof \"(\": stack.add token\n\t\tof \")\":\n\t\t\twhile stack.len > 0:\n\t\t\t\top = stack.pop()\n\t\t\t\tif op == \"(\": break\n\t\t\t\tresult &= op & \" \"\n\t\telse:\n\t\t\tif token in ops:\n\t\t\t\twhile stack.len > 0:\n\t\t\t\t\top = stack[^1] # peek stack top\n\t\t\t\t\tif not (op in ops): break\n\t\t\t\t\tif ops[token].prec > ops[op].prec or (ops[token].rassoc and (ops[token].prec == ops[op].prec)):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdiscard stack.pop()\n\t\t\t\t\tresult &= op & \" \"\n\t\t\t\tstack.add token\n\t\t\telse:\n\t\t\t\tresult &= token & \" \"\n\t\techo fmt\"\"\"{token:5} {join(stack,\" \"):18} {result:25} \"\"\"\n\n\twhile stack.len > 0:\n\t\tresult &= stack.pop() & \" \"\n\t\techo fmt\"\"\" {join(stack,\" \"):18} {result:25} \"\"\"\n\nlet input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\necho \"for infix expression: '{input}' \\n\", \"\\nTOKEN OP STACK RPN OUTPUT\"\necho \"postfix: \", shuntRPN(input.strip.split)\n" + }, + { + "id": 929, + "length": 1406, + "source": "Rosetta Code", + "text": "import math, rdstdin, strutils, tables\n\ntype Stack = seq[float]\n\nproc opPow(s: var Stack) =\n\tlet b = s.pop\n\tlet a = s.pop\n\ts.add a.pow b\n\nproc opMul(s: var Stack) =\n\tlet b = s.pop\n\tlet a = s.pop\n\ts.add a * b\n\nproc opDiv(s: var Stack) =\n\tlet b = s.pop\n\tlet a = s.pop\n\ts.add a / b\n\nproc opAdd(s: var Stack) =\n\tlet b = s.pop\n\tlet a = s.pop\n\ts.add a + b\n\nproc opSub(s: var Stack) =\n\tlet b = s.pop\n\tlet a = s.pop\n\ts.add a - b\n\nproc opNum(s: var Stack; num: float) =\n\ts.add num\n\nlet ops = toTable({\"^\": opPow,\n\t\t\t\t\t\t\t\t\t \"*\": opMul,\n\t\t\t\t\t\t\t\t\t \"/\": opDiv,\n\t\t\t\t\t\t\t\t\t \"+\": opAdd,\n\t\t\t\t\t\t\t\t\t \"-\": opSub})\n\nproc getInput(inp = \"\"): seq[string] =\n\tvar inp = inp\n\tif inp.len == 0:\n\t\tinp = readLineFromStdin \"Expression: \"\n\tresult = inp.strip.split\n\nproc rpnCalc(tokens: seq[string]): seq[seq[string]] =\n\tvar s: Stack\n\tresult = @[@[\"TOKEN\",\"ACTION\",\"STACK\"]]\n\tfor token in tokens:\n\t\tvar action = \"\"\n\t\tif ops.hasKey token:\n\t\t\taction = \"Apply op to top of stack\"\n\t\t\tops[token](s)\n\t\telse:\n\t\t\taction = \"Push num onto top of stack\"\n\t\t\ts.opNum token.parseFloat\n\t\tresult.add(@[token, action, s.join(\" \")])\n\nlet rpn = \"3 4 2 * 1 5 - 2 3 ^ ^ / +\"\necho \"For RPN expression: \", rpn\nlet rp = rpnCalc rpn.getInput\n\nvar maxColWidths = newSeq[int](rp[0].len)\nfor i in 0 .. rp[0].high:\n\tfor x in rp:\n\t\tmaxColWidths[i] = max(maxColWidths[i], x[i].len + 3)\n\nfor x in rp:\n\tfor i, y in x:\n\t\tstdout.write y.alignLeft(maxColWidths[i])\n\techo \"\"\n" + }, + { + "id": 930, + "length": 963, + "source": "Rosetta Code", + "text": "import tables, strutils\n\nconst nPrec = 9\n\nlet ops: Table[string, tuple[prec: int, rAssoc: bool]] =\n\t{ \"^\": (4, true)\n\t, \"*\": (3, false)\n\t, \"/\": (3, false)\n\t, \"+\": (2, false)\n\t, \"-\": (2, false)\n\t}.toTable\n\nproc parseRPN(e: string) =\n\techo \"postfix: \", e\n\tvar stack = newSeq[tuple[prec: int, expr: string]]()\n\n\tfor tok in e.split:\n\t\techo \"Token: \", tok\n\t\tif ops.hasKey tok:\n\t\t\tlet op = ops[tok]\n\t\t\tlet rhs = stack.pop\n\t\t\tvar lhs = stack.pop\n\n\t\t\tif lhs.prec < op.prec or (lhs.prec == op.prec and op.rAssoc):\n\t\t\t\tlhs.expr = \"(\" & lhs.expr & \")\"\n\n\t\t\tlhs.expr.add \" \" & tok & \" \"\n\n\t\t\tif rhs.prec < op.prec or (rhs.prec == op.prec and not op.rAssoc):\n\t\t\t\tlhs.expr.add \"(\" & rhs.expr & \")\"\n\t\t\telse:\n\t\t\t\tlhs.expr.add rhs.expr\n\n\t\t\tlhs.prec = op.prec\n\t\t\tstack.add lhs\n\t\telse:\n\t\t\tstack.add((nPrec, tok))\n\n\t\tfor f in stack:\n\t\t\techo \" \", f.prec, \" \", f.expr\n\n\techo \"infix: \", stack[0].expr\n\nfor test in [\"3 4 2 * 1 5 - 2 3 ^ ^ / +\", \"1 2 + 3 4 + ^ 5 6 + ^\"]:\n\ttest.parseRPN\n" + }, + { + "id": 931, + "length": 2123, + "source": "Rosetta Code", + "text": "# Dijkstra algorithm.\n\nfrom algorithm import reverse\nimport sets\nimport strformat\nimport tables\n\ntype\n\tEdge = tuple[src, dst: string; cost: int]\n\tGraph = object\n\t\tvertices: HashSet[string]\n\t\tneighbours: Table[string, seq[tuple[dst: string, cost: float]]]\n\n\nproc initGraph(edges: openArray[Edge]): Graph =\n\t## Initialize a graph from an edge list.\n\t## Use floats for costs in order to compare to Inf value.\n\n\tfor (src, dst, cost) in edges:\n\t\tresult.vertices.incl(src)\n\t\tresult.vertices.incl(dst)\n\t\tresult.neighbours.mgetOrPut(src, @[]).add((dst, cost.toFloat))\n\n\nproc dijkstraPath(graph: Graph; first, last: string): seq[string] =\n\t## Find the path from \"first\" to \"last\" which minimizes the cost.\n\n\tvar dist = initTable[string, float]()\n\tvar previous = initTable[string, string]()\n\tvar notSeen = graph.vertices\n\tfor vertex in graph.vertices:\n\t\tdist[vertex] = Inf\n\tdist[first] = 0\n\n\twhile notSeen.card > 0:\n\t\t# Search vertex with minimal distance.\n\t\tvar vertex1: string\n\t\tvar mindist = Inf\n\t\tfor vertex in notSeen:\n\t\t\tif dist[vertex] < mindist:\n\t\t\t\tvertex1 = vertex\n\t\t\t\tmindist = dist[vertex]\n\t\tif vertex1 == last:\n\t\t\tbreak\n\t\tnotSeen.excl(vertex1)\n\t\t# Find shortest paths to neighbours.\n\t\tfor (vertex2, cost) in graph.neighbours.getOrDefault(vertex1):\n\t\t\tif vertex2 in notSeen:\n\t\t\t\tlet altdist = dist[vertex1] + cost\n\t\t\t\tif altdist < dist[vertex2]:\n\t\t\t\t\t# Found a shorter path to go to vertex2.\n\t\t\t\t\tdist[vertex2] = altdist\n\t\t\t\t\tprevious[vertex2] = vertex1 # To go to vertex2, go through vertex1.\n\n\t# Build the path.\n\tvar vertex = last\n\twhile vertex.len > 0:\n\t\tresult.add(vertex)\n\t\tvertex = previous.getOrDefault(vertex)\n\tresult.reverse()\n\n\nproc printPath(path: seq[string]) =\n\t## Print a path.\n\tstdout.write(fmt\"Shortest path from '{path[0]}' to '{path[^1]}': {path[0]}\")\n\tfor i in 1..path.high:\n\t\tstdout.write(fmt\" -> {path[i]}\")\n\tstdout.write('\\n')\n\n\nlet graph = initGraph([(\"a\", \"b\", 7), (\"a\", \"c\", 9), (\"a\", \"f\", 14),\n\t\t\t\t\t\t\t\t\t\t\t (\"b\", \"c\", 10), (\"b\", \"d\", 15), (\"c\", \"d\", 11),\n\t\t\t\t\t\t\t\t\t\t\t (\"c\", \"f\", 2), (\"d\", \"e\", 6), (\"e\", \"f\", 9)])\nprintPath(graph.dijkstraPath(\"a\", \"e\"))\nprintPath(graph.dijkstraPath(\"a\", \"f\"))\n" + }, + { + "id": 932, + "length": 1943, + "source": "Rosetta Code", + "text": "import bignum\n\n# Missing functions in \"bignum\".\n\ntemplate isOdd(val: Int): bool =\n\t## Needed as bignum \"odd\" function crashes.\n\t(val and 1) != 0\n\nfunc exp(x, y, m: Int): Int =\n\t## Missing \"exp\" function in \"bignum\".\n\tif m == 1: return newInt(0)\n\tresult = newInt(1)\n\tvar x = x mod m\n\tvar y = y\n\twhile y > 0:\n\t\tif y.isOdd:\n\t\t\tresult = (result * x) mod m\n\t\ty = y shr 1\n\t\tx = (x * x) mod m\n\n\ntype Montgomery = object\n\tm: Int # Modulus; must be odd.\n\tn: int # m.bitLen().\n\trrm: Int # (1<<2n) mod m.\n\nconst Base = 2\n\n\nfunc initMontgomery(m: Int): Montgomery =\n\t## Initialize a Mongtgomery object.\n\tdoAssert m > 0 and m.isOdd, \"argument must be positive and odd.\"\n\tresult.m = m\n\tresult.n = m.bitLen\n\tresult.rrm = newInt(1) shl culong(result.n * 2) mod m\n\n\nfunc reduce(mont: Montgomery; t: Int): Int =\n\t## Montgomery reduction algorithm.\n\tresult = t\n\tfor i in 0..= mont.m: dec result, mont.m\n\n\nwhen isMainModule:\n\n\tlet\n\t\tm = newInt(\"750791094644726559640638407699\")\n\t\tx1 = newInt(\"540019781128412936473322405310\")\n\t\tx2 = newInt(\"515692107665463680305819378593\")\n\n\t\tmont = initMontgomery(m)\n\t\tt1 = x1 * mont.rrm\n\t\tt2 = x2 * mont.rrm\n\n\t\tr1 = mont.reduce(t1)\n\t\tr2 = mont.reduce(t2)\n\t\tr = newInt(1) shl culong(mont.n)\n\n\techo \"b: \", Base\n\techo \"n: \", mont.n\n\techo \"r: \", r\n\techo \"m: \", mont.m\n\techo \"t1: \", t1\n\techo \"t2: \", t2\n\techo \"r1: \", r1\n\techo \"r2: \", r2\n\techo()\n\techo \"Original x1: \", x1\n\techo \"Recovered from r1: \", mont.reduce(r1)\n\techo \"Original x2: \", x2\n\techo \"Recovered from r2: \", mont.reduce(r2)\n\n\techo \"\\nMontgomery computation of x1^x2 mod m:\"\n\tvar\n\t\tprod = mont.reduce(mont.rrm)\n\t\tbase = mont.reduce(x1 * mont.rrm)\n\t\te = x2\n\twhile e > 0:\n\t\tif e.isOdd: prod = mont.reduce(prod * base)\n\t\te = e shr 1\n\t\tbase = mont.reduce(base * base)\n\techo mont.reduce(prod)\n\techo \"\\nAlternate computation of x1^x2 mod m:\"\n\techo x1.exp(x2, m)\n" + }, + { + "id": 933, + "length": 1230, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils\nimport itertools\n\nconst Words = {\"alliance\": -624,\n\t\t\t\t\t\t\t \"archbishop\": -915,\n\t\t\t\t\t\t\t \"balm\": 397,\n\t\t\t\t\t\t\t \"bonnet\": 452,\n\t\t\t\t\t\t\t \"brute\": 870,\n\t\t\t\t\t\t\t \"centipede\": -658,\n\t\t\t\t\t\t\t \"cobol\": 362,\n\t\t\t\t\t\t\t \"covariate\": 590,\n\t\t\t\t\t\t\t \"departure\": 952,\n\t\t\t\t\t\t\t \"deploy\": 44,\n\t\t\t\t\t\t\t \"diophantine\": 645,\n\t\t\t\t\t\t\t \"efferent\": 54,\n\t\t\t\t\t\t\t \"elysee\": -326,\n\t\t\t\t\t\t\t \"eradicate\": 376,\n\t\t\t\t\t\t\t \"escritoire\": 856,\n\t\t\t\t\t\t\t \"exorcism\": -983,\n\t\t\t\t\t\t\t \"fiat\": 170,\n\t\t\t\t\t\t\t \"filmy\": -874,\n\t\t\t\t\t\t\t \"flatworm\": 503,\n\t\t\t\t\t\t\t \"gestapo\": 915,\n\t\t\t\t\t\t\t \"infra\": -847,\n\t\t\t\t\t\t\t \"isis\": -982,\n\t\t\t\t\t\t\t \"lindholm\": 999,\n\t\t\t\t\t\t\t \"markham\": 475,\n\t\t\t\t\t\t\t \"mincemeat\": -880,\n\t\t\t\t\t\t\t \"moresby\": 756,\n\t\t\t\t\t\t\t \"mycenae\": 183,\n\t\t\t\t\t\t\t \"plugging\": -266,\n\t\t\t\t\t\t\t \"smokescreen\": 423,\n\t\t\t\t\t\t\t \"speakeasy\": -745,\n\t\t\t\t\t\t\t \"vein\": 813}\n\nvar words: seq[string]\nvar values: seq[int]\nfor (word, value) in Words:\n\twords.add word\n\tvalues.add value\n\nfor lg in 1..words.len:\n\tblock checkCombs:\n\t\tfor comb in combinations(words.len, lg):\n\t\t\tvar sum = 0\n\t\t\tfor idx in comb: sum += values[idx]\n\t\t\tif sum == 0:\n\t\t\t\techo \"For length {lg}, found for example: \", comb.mapIt(words[it]).join(\" \")\n\t\t\t\tbreak checkCombs\n\t\techo \"For length {lg}, no set found.\"\n" + }, + { + "id": 934, + "length": 1532, + "source": "Rosetta Code", + "text": "import re, strutils, xmltree\n\nconst Text = \"\"\" Sample Text\n\nThis is an example of converting plain text to HTML which demonstrates extracting a title and escaping certain characters within bulleted and numbered lists.\n\n* This is a bulleted list with a less than sign (<)\n\n* And this is its second line with a greater than sign (>)\n\nA 'normal' paragraph between the lists.\n\n1. This is a numbered list with an ampersand (&)\n\n2. \"Second line\" in double quotes\n\n3. 'Third line' in single quotes\n\nThat's all folks.\"\"\"\n\n\nlet p = re\"\\n\\s*(\\n\\s*)+\"\nlet ul = re\"^\\*\"\nlet ol = re\"^\\d\\.\"\nlet text = xmltree.escape(Text)\nlet paras = text.split(p)\n\n# Assume if first character of first paragraph is white-space\n# then it's probably a document title.\nlet firstChar = paras[0][0]\nvar titleString = \"untitled\"\nvar start = 0\nif firstChar.isSpaceAscii:\n\ttitleString = paras[0].strip()\n\tstart = 1\necho \"\"\necho \"\", titleString, \"\"\necho \"\"\n\nvar blist, nlist = false\nfor ipara in start..paras.high:\n\tvar para = paras[ipara].strip()\n\n\tif para.find(ul) >= 0:\n\t\tif not blist:\n\t\t\tblist = true\n\t\t\techo \"
    \"\n\t\techo \"
  • \", para[1..^1].strip(), \"
  • \"\n\t\tcontinue\n\telif blist:\n\t\tblist = false\n\t\techo \"
\"\n\n\tif para.find(ol) >= 0:\n\t\tif not nlist:\n\t\t\tnlist = true\n\t\t\techo \"
    \"\n\t\techo \"
  1. \", para[2..^1].strip(), \"
  2. \"\n\t\tcontinue\n\telif nlist:\n\t\tnlist = false\n\t\techo \"
\"\n\n\tif not (blist or nlist):\n\t\techo \"

\", para, \"

\"\n\nif blist: echo \"\"\nif nlist: echo \"\"\n\necho \"\"\necho \"\"\n" + }, + { + "id": 935, + "length": 917, + "source": "Rosetta Code", + "text": "var a: array[17, array[17, int]]\nvar idx: array[4, int]\n\n\nproc findGroup(kind, minN, maxN, depth: int): bool =\n\n\tif depth == 4:\n\t\techo \"\\nTotally \", if kind != 0: \"\" else: \"un\", \"connected group:\"\n\t\tfor i in 0..3:\n\t\t\tstdout.write idx[i], if i == 3: '\\n' else: ' '\n\t\treturn true\n\n\tfor i in minN.. hidato.given[^1]:\n\t\treturn true\n\tif hidato.board[r][c] < 0:\n\t\treturn false\n\tif hidato.board[r][c] > 0 and hidato.board[r][c] != n:\n\t\treturn false\n\tif hidato.board[r][c] == 0 and hidato.given[next] == n:\n\t\treturn false\n\n\tlet back = hidato.board[r][c]\n\thidato.board[r][c] = n\n\tfor i in -1 .. 1:\n\t\tfor j in -1 .. 1:\n\t\t\tif back == n:\n\t\t\t\tif hidato.solve(r + i, c + j, n + 1, next + 1): return true\n\t\t\telse:\n\t\t\t\tif hidato.solve(r + i, c + j, n + 1, next): return true\n\thidato.board[r][c] = back\n\tresult = false\n\n\nproc print(hidato: Hidato) =\n\tfor row in hidato.board:\n\t\tfor val in row:\n\t\t\tstdout.write if val == -1: \" . \" elif val == 0: \"__ \" else: \"{val:2} \"\n\t\twriteLine(stdout, \"\")\n\n\nconst Hi = \"\"\"\n__ 33 35 __ __ . . .\n__ __ 24 22 __ . . .\n__ __ __ 21 __ __ . .\n__ 26 __ 13 40 11 . .\n27 __ __ __ 9 __ 1 .\n . . __ __ 18 __ __ .\n . . . . __ 7 __ __\n . . . . . . 5 __\"\"\"\n\nvar hidato = initHidato(Hi)\nhidato.print()\necho(\"\")\necho(\"Found:\")\ndiscard hidato.solve(hidato.start[0], hidato.start[1], 1)\nhidato.print()\n" + }, + { + "id": 937, + "length": 3404, + "source": "Rosetta Code", + "text": "import complex, strformat\n\ntype Matrix[M, N: static Positive] = array[M, array[N, Complex[float]]]\n\nconst Eps = 1e-10 # Tolerance used for float comparisons.\n\n\n# Templates.\n\ntemplate `[]`(m: Matrix; i, j: Natural): Complex[float] =\n\t## Allow to get value of an element using m[i, j] syntax.\n\tm[i][j]\n\ntemplate `[]=`(m: var Matrix; i, j: Natural; val: Complex[float]) =\n\t## Allow to set value of an element using m[i, j] syntax.\n\tm[i][j] = val\n\n\n# General operations.\n\nfunc `$`(m: Matrix): string =\n\t## Return the string representation of a matrix using one line per row.\n\n\tfor i, row in m:\n\t\tresult.add(if i == 0: '[' else: ' ')\n\t\tfor j, val in row:\n\t\t\tif j != 0: result.add(' ')\n\t\t\tresult.add(\"({val.re:7.4f}, {val.im:7.4f})\")\n\t\tresult.add(if i == m.high: ']' else: '\\n')\n\n\nfunc conjugateTransposed[M, N: static int](m: Matrix[M, N]): Matrix[N, M] =\n\t## Return the conjugate transpose of a matrix.\n\n\tfor i in 0.. Eps:\n\t\t\t\t\t\treturn false\n\t\t\t\telse:\n\t\t\t\t\tif abs(m[i, j]) > Eps:\n\t\t\t\t\t\treturn false\n\t\tresult = true\n\n\nfunc isUnitary(m: Matrix): bool =\n\t## Check if a matrix is unitary.\n\n\twhen m.M != m.N:\n\t\t{.error: \"unitary test only allowed for square matrices\".}\n\telse:\n\t\tlet h = m.conjugateTransposed\n\t\tresult = (m * h).isIdentity and (h * m).isIdentity\n\n\nwhen isMainModule:\n\n\timport math\n\n\tproc test(m: Matrix) =\n\t\techo \"\\n\"\n\t\techo \"Matrix\"\n\t\techo \"------\"\n\t\techo m\n\t\techo \"\"\n\t\techo \"Conjugate transposed\"\n\t\techo \"--------------------\"\n\t\techo m.conjugateTransposed\n\n\t\twhen m.M == m.N:\n\t\t\t# Only for squares matrices.\n\t\t\techo \"\"\n\t\t\techo \"Hermitian: \", m.isHermitian\n\t\t\techo \"Normal: \", m.isNormal\n\t\t\techo \"Unitary: \", m.isUnitary\n\n\t# Non square matrix.\n\tconst M1: Matrix[2, 3] = [[1.0 + im 2.0, 3.0 + im 0.0, 2.0 + im 5.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[3.0 - im 1.0, 2.0 + im 0.0, 0.0 + im 3.0]]\n\n\t\t# Square matrices.\n\tconst M2: Matrix[2, 2] = [[3.0 + im 0.0, 2.0 + im 1.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[2.0 - im 1.0, 1.0 + im 0.0]]\n\n\tconst M3: Matrix[3, 3] = [[1.0 + im 0.0, 1.0 + im 0.0, 0.0 + im 0.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[0.0 + im 0.0, 1.0 + im 0.0, 1.0 + im 0.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[1.0 + im 0.0, 0.0 + im 0.0, 1.0 + im 0.0]]\n\n\tconst SR2 = 1 / sqrt(2.0)\n\tconst M4: Matrix[3, 3] = [[SR2 + im 0.0, SR2 + im 0.0, 0.0 + im 0.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[0.0 + im SR2, 0.0 - im SR2, 0.0 + im 0.0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t[0.0 + im 0.0, 0.0 + im 0.0, 0.0 + im 1.0]]\n\n\ttest(M1)\n\ttest(M2)\n\ttest(M3)\n\ttest(M4)\n" + }, + { + "id": 938, + "length": 1791, + "source": "Rosetta Code", + "text": "const Eps = 1e-14 # Tolerance required.\n\ntype\n\n\tVector[N: static Positive] = array[N, float]\n\tMatrix[M, N: static Positive] = array[M, Vector[N]]\n\tSquareMatrix[N: static Positive] = Matrix[N, N]\n\nfunc gaussPartialScaled(a: SquareMatrix; b: Vector): Vector =\n\n\tdoAssert a.N == b.N, \"matrix and vector have incompatible dimensions\"\n\tconst N = a.N\n\n\tvar m: Matrix[N, N + 1]\n\tfor i, row in a:\n\t\tm[i][0.. s: s = e\n\t\t\t# Scale the abs used to pick the pivot.\n\t\t\tlet val = abs(m[i][k]) / s\n\t\t\tif val > vmax:\n\t\t\t\timax = i\n\t\t\t\tvmax = val\n\n\t\tif m[imax][k] == 0:\n\t\t\traise newException(ValueError, \"matrix is singular\")\n\n\t\tswap m[imax], m[k]\n\n\t\tfor i in (k + 1).. Eps:\n\t\techo \"Out of tolerance.\"\n\t\techo \"Expected values are \", refx\n\t\tbreak\n" + }, + { + "id": 939, + "length": 589, + "source": "Rosetta Code", + "text": "proc calc(f: proc(n: int): tuple[a, b: float], n: int): float =\n\tvar a, b, temp = 0.0\n\tfor i in countdown(n, 1):\n\t\t(a, b) = f(i)\n\t\ttemp = b / (a + temp)\n\t(a, b) = f(0)\n\ta + temp\n\nproc sqrt2(n: int): tuple[a, b: float] =\n\tif n > 0:\n\t\t(2.0, 1.0)\n\telse:\n\t\t(1.0, 1.0)\n\nproc napier(n: int): tuple[a, b: float] =\n\tlet a = if n > 0: float(n) else: 2.0\n\tlet b = if n > 1: float(n - 1) else: 1.0\n\t(a, b)\n\nproc pi(n: int): tuple[a, b: float] =\n\tlet a = if n > 0: 6.0 else: 3.0\n\tlet b = (2 * float(n) - 1) * (2 * float(n) - 1)\n\t(a, b)\n\necho calc(sqrt2, 20)\necho calc(napier, 15)\necho calc(pi, 10000)\n" + }, + { + "id": 940, + "length": 3919, + "source": "Rosetta Code", + "text": "type\n\n\tPoint[Dim: static Natural; T: SomeNumber] = array[Dim, T]\n\n\tKdNode[Dim: static Natural; T: SomeNumber] = ref object\n\t\tx: Point[Dim, T]\n\t\tleft, right: KdNode[Dim, T]\n\n\nfunc toKdNodes[N, Dim: static Natural; T](a: array[N, array[Dim, T]]): array[N, KdNode[Dim, T]] =\n\t## Create an array of KdNodes from an array of list of numerical values.\n\tfor i in 0.. md:\n\t\t\tlast = store\n\t\telse:\n\t\t\tfirst = store\n\n\nfunc makeTree(nodes: openArray[KdNode]; slice: Slice; idx: Natural = 0): KdNode =\n\t## Build a tree from a list of nodes. Return the root of the tree.\n\n\tif slice.b < slice.a: return nil\n\n\tlet n = nodes.findMedian(slice, idx)\n\tif n < 0: return nil\n\n\tlet idx = (idx + 1) mod result.Dim\n\tnodes[n].left = nodes.makeTree(slice.a.. 0: root.left else: root.right, point, idx, best, bestDist, nVisited)\n\tif dx * dx >= bestDist: return\n\tnearest(if dx > 0: root.right else: root.left, point, idx, best, bestDist, nVisited)\n\n\nwhen isMainModule:\n\timport math, random, strformat\n\n\tproc displayResult(title: string; thisPt: Point;\n\t\t\t\t\t\t\t\t\t\t found: KdNode; bestDist: thisPt.T; nVisited: int) =\n\t\techo title & ':'\n\t\techo \" Searching for {thisPt}\"\n\t\techo \" Found {found.x}, dist = {sqrt(float(bestDist)):.5f}\"\n\t\techo \" Seen {nVisited} nodes.\"\n\t\techo \"\"\n\n\n\tproc initRandom(point: var Point) =\n\t\tfor item in point.mitems:\n\t\t\titem = rand(1.0)\n\n\n\tproc runSmallTest() =\n\n\t\tlet\n\t\t\twp = [[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]].toKdNodes()\n\t\t\t#thisPt = newPoint([9, 2])\n\t\t\tthisPt = Point([9, 2])\n\t\t\troot = wp.makeTree(0..wp.high)\n\n\t\tvar\n\t\t\tfound: KdNode[root.Dim, root.T]\n\t\t\tbestDist = root.T(0)\n\t\t\tnVisited = 0\n\n\t\troot.nearest(thisPt, 0, found, bestDist, nVisited)\n\t\tdisplayResult(\"WP tree\", thisPt, found, bestDist, nVisited)\n\n\n\tproc runBigTest() =\n\n\t\tconst N = 1_000_000\n\t\tconst TestRuns = 100_000\n\n\t\trandomize()\n\n\t\tvar bigTree: array[N, KdNode[3, float]]\n\t\tfor node in bigTree.mitems:\n\t\t\tnew(node)\n\t\t\tnode.x.initRandom()\n\n\t\tlet root = bigTree.makeTree(0..bigTree.high)\n\t\tvar thisPt: Point[3, float]\n\t\tthisPt.initRandom()\n\n\t\tvar\n\t\t\tfound: KdNode[3, float]\n\t\t\tbestDist = 0.0\n\t\t\tnVisited = 0\n\n\t\troot.nearest(thisPt, 0, found, bestDist, nVisited)\n\t\tdisplayResult(\"Big Tree\", thisPt, found, bestDist, nVisited)\n\n\t\tvar sum = 0\n\t\tfor _ in 0.. \", toSeq(0..14).mapIt($fibber(it)).join(\" \"), \" ...\"\n" + }, + { + "id": 943, + "length": 841, + "source": "Rosetta Code", + "text": "import sequtils, permutationsswap\n\ntype Matrix[M,N: static[int]] = array[M, array[N, float]]\n\nproc det[M,N](a: Matrix[M,N]): float =\n\tlet n = toSeq 0..a.high\n\tfor sigma, sign in n.permutations:\n\t\tvar x = sign.float\n\t\tfor i in n: x *= a[i][sigma[i]]\n\t\tresult += x\n\nproc perm[M,N](a: Matrix[M,N]): float =\n\tlet n = toSeq 0..a.high\n\tfor sigma, sign in n.permutations:\n\t\tvar x = 1.0\n\t\tfor i in n: x *= a[i][sigma[i]]\n\t\tresult += x\n\nconst\n\ta = [ [1.0, 2.0]\n\t\t\t, [3.0, 4.0]\n\t\t\t]\n\tb = [ [ 1.0, 2, 3, 4]\n\t\t\t, [ 4.0, 5, 6, 7]\n\t\t\t, [ 7.0, 8, 9, 10]\n\t\t\t, [10.0, 11, 12, 13]\n\t\t\t]\n\tc = [ [ 0.0, 1, 2, 3, 4]\n\t\t\t, [ 5.0, 6, 7, 8, 9]\n\t\t\t, [10.0, 11, 12, 13, 14]\n\t\t\t, [15.0, 16, 17, 18, 19]\n\t\t\t, [20.0, 21, 22, 23, 24]\n\t\t\t]\n\necho \"perm: \", a.perm, \" det: \", a.det\necho \"perm: \", b.perm, \" det: \", b.det\necho \"perm: \", c.perm, \" det: \", c.det\n" + }, + { + "id": 944, + "length": 1231, + "source": "Rosetta Code", + "text": "import os, random, strutils\n\ntype Color {.pure.} = enum Red = \"R\", White = \"W\", Blue = \"B\"\n\n\nproc isSorted(a: openArray[Color]): bool =\n\t# Check if an array of colors is in the order of the dutch national flag.\n\tvar prevColor = Red\n\tfor color in a:\n\t\tif color < prevColor:\n\t\t\treturn false\n\t\tprevColor = color\n\treturn true\n\n\nproc threeWayPartition(a: var openArray[Color]; mid: Color) =\n\t## Dijkstra way to sort the colors.\n\tvar i, j = 0\n\tvar k = a.high\n\twhile j <= k:\n\t\tif a[j] < mid:\n\t\t\tswap a[i], a[j]\n\t\t\tinc i\n\t\t\tinc j\n\t\telif a[j] > mid:\n\t\t\tswap a[j], a[k]\n\t\t\tdec k\n\t\telse:\n\t\t\tinc j\n\n\nvar n: Positive = 10\n\n# Get the number of colors.\nif paramCount() > 0:\n\ttry:\n\t\tn = paramStr(1).parseInt()\n\t\tif n <= 1:\n\t\t\traise newException(ValueError, \"\")\n\texcept ValueError:\n\t\techo \"Wrong number of colors\"\n\t\tquit(QuitFailure)\n\n# Create the colors.\nrandomize()\nvar colors = newSeqOfCap[Color](n)\n\nwhile true:\n\tfor i in 0.. 1:\n\t\t\t\tdec d\n\t\t\t\tc[d] = 0\n\t\t\twhile c[d] >= d:\n\t\t\t\tinc d\n\t\t\t\tif d >= ys.len: break outter\n\n\t\t\tlet i = if (d and 1) == 1: c[d] else: 0\n\t\t\tswap xs[i], xs[d]\n\t\t\tsign *= -1\n\t\t\tyield (xs, sign)\n\t\t\tinc c[d]\n\nwhen isMainModule:\n\tfor i in permutations([0,1,2]):\n\t\techo i\n\n\techo \"\"\n\n\tfor i in permutations([0,1,2,3]):\n\t\techo i\n" + }, + { + "id": 948, + "length": 2345, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\n\ntype Node = ref object\n\tvalue: int\n\tleft, right: Node\n\n\nproc add(tree: var Node; value: int) =\n\t## Add a node to a tree (or subtree), insuring values are in increasing order.\n\tif tree.isNil:\n\t\ttree = Node(value: value)\n\telif value <= tree.value:\n\t\ttree.left.add value\n\telse:\n\t\ttree.right.add value\n\n\nproc newTree(list: varargs[int]): Node =\n\t## Create a new tree with the given nodes.\n\tfor value in list:\n\t\tresult.add value\n\n\nproc `$`(tree: Node): string =\n\t# Display a tree.\n\tif tree.isNil: return\n\tresult = '(' & $tree.left & $tree.value & $tree.right & ')'\n\n\niterator nodes(tree: Node): Node =\n\t## Yield the successive leaves of a tree.\n\t## Iterators cannot be recursive, so we have to manage a stack.\n\t## Note: with Nim 1.4 a bug prevents to use a closure iterator,\n\t## so we use an inline iterator which is not optimal here.\n\n\ttype\n\t\tDirection {.pure.} = enum Up, Down\n\t\tItem = (Node, Direction)\n\n\tvar stack: seq[Item]\n\tstack.add (nil, Down) # Sentinel to avoid checking for empty stack.\n\n\tvar node = tree\n\tvar dir = Down\n\n\twhile not node.isNil:\n\t\tif dir == Down and not node.left.isNil:\n\t\t\t# Process left subtree.\n\t\t\tstack.add (node, Up)\n\t\t\tnode = node.left\n\t\telse:\n\t\t\tyield node\n\t\t\t# Process right subtree of pop an element form stack.\n\t\t\t(node, dir) = if node.right.isNil: stack.pop() else: (node.right, Down)\n\n\nproc haveSameFringe(tree1, tree2: Node): bool =\n\t## Return true if the trees have the same fringe.\n\t## Check is done node by node and terminates as soon as\n\t## a difference is encountered.\n\tlet iter1 = iterator: Node = (for node in tree1.nodes: yield node)\n\tlet iter2 = iterator: Node = (for node in tree2.nodes: yield node)\n\twhile true:\n\t\tlet node1 = iter1()\n\t\tlet node2 = iter2()\n\t\tif iter1.finished and iter2.finished: return true # Both terminates at same round.\n\t\tif iter1.finished or iter2.finished: return false # One terminates before the other.\n\t\tif node1.value != node2.value: return false\n\n\nwhen isMainModule:\n\trandomize()\n\tvar values = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\tvalues.shuffle()\n\tlet tree1 = newTree(values)\n\techo \"First tree: \", tree1\n\n\tvalues.shuffle()\n\tlet tree2 = newTree(values)\n\techo \"Second tree: \", tree2\n\n\tlet s = if haveSameFringe(tree1, tree2): \"have \" else: \"don't have \"\n\techo \"The trees \", s, \"same fringe: \", toSeq(tree1.nodes()).mapIt(it.value).join(\", \")\n" + }, + { + "id": 949, + "length": 1733, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nconst\n\tK1 = [byte 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3]\n\tK2 = [byte 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9]\n\tK3 = [byte 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11]\n\tK4 = [byte 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3]\n\tK5 = [byte 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2]\n\tK6 = [byte 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14]\n\tK7 = [byte 13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12]\n\tK8 = [byte 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]\n\n\nproc kboxInit: tuple[k87, k65, k43, k21: array[256, byte]] {.compileTime.} =\n\tfor i in 0 .. 255:\n\t\tresult.k87[i] = K8[i shr 4] shl 4 or K7[i and 15]\n\t\tresult.k65[i] = K6[i shr 4] shl 4 or K5[i and 15]\n\t\tresult.k43[i] = K4[i shr 4] shl 4 or K3[i and 15]\n\t\tresult.k21[i] = K2[i shr 4] shl 4 or K1[i and 15]\n\nconst (K87, K65, K43, K21) = kboxInit()\n\ntemplate rol(x: uint32; n: typed): uint32 =\n\tx shl n or x shr (32 - n)\n\nproc f(x: uint32): uint32 =\n\tlet x = K87[x shr 24 and 255].uint32 shl 24 or K65[x shr 16 and 255].uint32 shl 16 or\n\t\t\t\t\tK43[x shr 8 and 255].uint32 shl 8 or K21[x and 255].uint32\n\tresult = x.rol(11)\n\nproc mainStep(input: array[8, byte]; key: array[4, byte]): array[8, byte] =\n\tlet input32 = cast[array[2, uint32]](input)\n\tlet key = cast[uint32](key)\n\tlet val = f(key + input32[0]) xor input32[1]\n\tresult[0..3] = cast[array[4, byte]](val)\n\tresult[4..7] = input[0..3]\n\nwhen isMainModule:\n\tconst\n\t\tInput = [byte 0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04]\n\t\tKey = [byte 0xF9, 0x04, 0xC1, 0xE2]\n\n\tlet output = mainStep(Input, Key)\n\techo mapIt(output, it.toHex).join(\" \")\n" + }, + { + "id": 950, + "length": 1233, + "source": "Rosetta Code", + "text": "import random, strformat, strutils\n\nrandomize()\n\nstdout.write \"Player 1 - Enter your name : \"\nlet name1 = block:\n\t\t\t\t\t\t\tlet n = stdin.readLine().strip()\n\t\t\t\t\t\t\tif n.len == 0: \"PLAYER 1\" else: n.toUpper\nstdout.write \"Player 2 - Enter your name : \"\nlet name2 = block:\n\t\t\t\t\t\t\tlet n = stdin.readLine().strip()\n\t\t\t\t\t\t\tif n.len == 0: \"PLAYER 2\" else: n.toUpper\n\nlet names = [name1, name2]\nvar totals: array[2, Natural]\nvar player = 0\n\nwhile true:\n\techo \"\\n{names[player]}\"\n\techo \" Your total score is currently {totals[player]}\"\n\tvar score = 0\n\n\twhile true:\n\t\tstdout.write \" Roll or Hold r/h : \"\n\t\tlet rh = stdin.readLine().toLowerAscii()\n\t\tcase rh\n\n\t\tof \"h\":\n\t\t\tinc totals[player], score\n\t\t\techo \" Your total score is now {totals[player]}\"\n\t\t\tif totals[player] >= 100:\n\t\t\t\techo \" So, {names[player]}, YOU'VE WON!\"\n\t\t\t\tquit QuitSuccess\n\t\t\tplayer = 1 - player\n\t\t\tbreak\n\n\t\tof \"r\":\n\t\t\tlet dice = rand(1..6)\n\t\t\techo \" You have thrown a {dice}\"\n\t\t\tif dice == 1:\n\t\t\t\techo \" Sorry, your score for this round is now 0\"\n\t\t\t\techo \" Your total score remains at {totals[player]}\"\n\t\t\t\tplayer = 1 - player\n\t\t\t\tbreak\n\t\t\tinc score, dice\n\t\t\techo \" Your score for the round is now {score}\"\n\n\t\telse:\n\t\t\techo \" Must be 'r' or 'h', try again\"\n" + }, + { + "id": 951, + "length": 2518, + "source": "Rosetta Code", + "text": "import random, strformat\n\nconst MaxPoints = 100\n\ntype\n\n\tMove {.pure.} = enum Roll, Hold\n\tStrategy {.pure.} = enum Rand, Q2Win, AL20, AL20T\n\n\t# Player description.\n\tPlayer = ref object\n\t\tnum: Natural\n\t\tcurrentScore: Natural\n\t\troundScore: Natural\n\t\tstrategy: Strategy\n\t\tnext: Player\n\n\t# Player list managed as a singly linked ring.\n\tPlayerList = object\n\t\tcount: Natural\n\t\thead, tail: Player\n\n\nproc addPlayer(playerList: var PlayerList; strategy: Strategy) =\n\t## Add a player with given strategy.\n\tinc playerList.count\n\tlet newPlayer = Player(num: playerList.count, strategy: strategy)\n\tif playerList.head.isNil:\n\t\tplayerList.head = newPlayer\n\telse:\n\t\tplayerList.tail.next = newPlayer\n\tplayerList.tail = newPlayer\n\tnewPlayer.next = playerList.head\n\n\niterator items(playerList: PlayerList): Player =\n\t## Yield the successive players of a player list.\n\tvar player = playerList.head\n\tyield player\n\twhile player != playerList.tail:\n\t\tplayer = player.next\n\t\tyield player\n\n\nproc getMove(player: Player): Move =\n\t## Get the move for the given player.\n\n\tif player.roundScore + player.currentScore >= MaxPoints: return Hold\n\n\tcase player.strategy\n\n\tof Strategy.Rand:\n\t\tresult = if rand(1) == 0: Roll\n\t\t\t\t\t\t elif player.roundScore > 0: Hold\n\t\t\t\t\t\t else: Roll\n\n\tof Strategy.Q2Win:\n\t\tlet q = MaxPoints - player.currentScore\n\t\tresult = if q < 6 or player.roundScore < q div 4: Roll\n\t\t\t\t\t\t else: Hold\n\n\tof Strategy.AL20:\n\t\tresult = if player.roundScore < 20: Roll\n\t\t\t\t\t\t else: Hold\n\n\tof Strategy.AL20T:\n\t\tlet d = 5 * player.roundScore\n\t\tresult = if player.roundScore < 20 and d < rand(99): Roll\n\t\t\t\t\t\t else: Hold\n\n\nrandomize()\n\n# Create player list.\nvar playerList = PlayerList()\nfor strategy in Strategy.low..Strategy.high:\n\tplayerList.addPlayer(strategy)\n\nvar endGame = false\nvar player = playerList.head\n\nwhile not endGame:\n\tcase player.getMove()\n\n\tof Roll:\n\t\tlet die = rand(1..6)\n\t\tif die == 1:\n\t\t\techo \"Player {player.num} rolled {die} Current score: {player.currentScore:3}\\n\"\n\t\t\tplayer.roundScore = 0\n\t\t\tplayer = player.next\n\t\t\tcontinue\n\t\tinc player.roundScore, die\n\t\techo \"Player {player.num} rolled {die} Round score: {player.roundScore:3}\"\n\n\tof Hold:\n\t\tinc player.currentScore, player.roundScore\n\t\techo \"Player {player.num} holds Current score: {player.currentScore:3}\\n\"\n\t\tif player.currentScore >= MaxPoints:\n\t\t\tendGame = true\n\t\telse:\n\t\t\tplayer.roundScore = 0\n\t\t\tplayer = player.next\n\nfor player in playerList:\n\tlet stratStr = \"({player.strategy}):\"\n\techo \"Player {player.num} {stratStr:8} {player.currentScore:3}\"\n" + }, + { + "id": 952, + "length": 1319, + "source": "Rosetta Code", + "text": "import bignum, strformat\n\nconst\n\n\tPrimes = [2, 3, 5, 7, 11, 13, 17]\n\tDigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\n\nfunc isProbablyPrime(n: Int): bool =\n\t## Return true if \"n\" is not definitively composite.\n\tprobablyPrime(n, 25) != 0\n\n\nfunc maxLeftTruncablePrime(base: int): Int =\n\t## Return the maximum left truncable prime for given base.\n\n\tlet base = base.int32\n\tvar primes: seq[Int]\n\n\t# Initialize primes with one digit in given base.\n\tfor p in Primes:\n\t\tif p < base:\n\t\t\tprimes.add(newInt(p))\n\t\telse:\n\t\t\tbreak\n\n\t# Build prime list with one more digit per generation.\n\tvar next: seq[Int]\n\twhile true:\n\n\t\t# Build the next generation (with one more digit).\n\t\tfor p in primes:\n\t\t\tvar pstr = ' ' & `$`(p, base) # ' ' as a placeholder for next digit.\n\t\t\tfor i in 1..3} {m}\", if base > 10: \" (\" & `$`(m, base.int32) & ')' else: \"\"\n" + }, + { + "id": 953, + "length": 1856, + "source": "Rosetta Code", + "text": "import sequtils\n\ntype Circle = tuple[x, y, r: float]\n\nconst circles: seq[Circle] = @[\n\t( 1.6417233788, 1.6121789534, 0.0848270516),\n\t(-1.4944608174, 1.2077959613, 1.1039549836),\n\t( 0.6110294452, -0.6907087527, 0.9089162485),\n\t( 0.3844862411, 0.2923344616, 0.2375743054),\n\t(-0.2495892950, -0.3832854473, 1.0845181219),\n\t( 1.7813504266, 1.6178237031, 0.8162655711),\n\t(-0.1985249206, -0.8343333301, 0.0538864941),\n\t(-1.7011985145, -0.1263820964, 0.4776976918),\n\t(-0.4319462812, 1.4104420482, 0.7886291537),\n\t( 0.2178372997, -0.9499557344, 0.0357871187),\n\t(-0.6294854565, -1.3078893852, 0.7653357688),\n\t( 1.7952608455, 0.6281269104, 0.2727652452),\n\t( 1.4168575317, 1.0683357171, 1.1016025378),\n\t( 1.4637371396, 0.9463877418, 1.1846214562),\n\t(-0.5263668798, 1.7315156631, 1.4428514068),\n\t(-1.2197352481, 0.9144146579, 1.0727263474),\n\t(-0.1389358881, 0.1092805780, 0.7350208828),\n\t( 1.5293954595, 0.0030278255, 1.2472867347),\n\t(-0.5258728625, 1.3782633069, 1.3495508831),\n\t(-0.1403562064, 0.2437382535, 1.3804956588),\n\t( 0.8055826339, -0.0482092025, 0.3327165165),\n\t(-0.6311979224, 0.7184578971, 0.2491045282),\n\t( 1.4685857879, -0.8347049536, 1.3670667538),\n\t(-0.6855727502, 1.6465021616, 1.0593087096),\n\t( 0.0152957411, 0.0638919221, 0.9771215985)]\n\ntemplate sqr(x: SomeNumber): SomeNumber = x * x\n\nlet xMin = min circles.mapIt(it.x - it.r)\nlet xMax = max circles.mapIt(it.x + it.r)\nlet yMin = min circles.mapIt(it.y - it.r)\nlet yMax = max circles.mapIt(it.y + it.r)\n\nconst boxSide = 500\n\nlet dx = (xMax - xMin) / boxSide\nlet dy = (yMax - yMin) / boxSide\n\nvar count = 0\n\nfor r in 0 ..< boxSide:\n\tlet y = yMin + float(r) * dy\n\tfor c in 0 ..< boxSide:\n\t\tlet x = xMin + float(c) * dx\n\t\tfor circle in circles:\n\t\t\tif sqr(x - circle.x) + sqr(y - circle.y) <= sqr(circle.r):\n\t\t\t\tinc count\n\t\t\t\tbreak\n\necho \"Approximated area: \", float(count) * dx * dy\n" + }, + { + "id": 954, + "length": 1409, + "source": "Rosetta Code", + "text": "import bitops, sequtils, strformat, strutils, sugar\n\ntype Bools = array[1..12, bool]\n\nconst Predicates = [1: (b: Bools) => b.len == 12,\n\t\t\t\t\t\t\t\t\t\t2: (b: Bools) => b[7..12].count(true) == 3,\n\t\t\t\t\t\t\t\t\t\t3: (b: Bools) => toSeq(countup(2, 12, 2)).mapIt(b[it]).count(true) == 2,\n\t\t\t\t\t\t\t\t\t\t4: (b: Bools) => not b[5] or b[6] and b[7],\n\t\t\t\t\t\t\t\t\t\t5: (b: Bools) => not b[2] and not b[3] and not b[4],\n\t\t\t\t\t\t\t\t\t\t6: (b: Bools) => toSeq(countup(1, 12, 2)).mapIt(b[it]).count(true) == 4,\n\t\t\t\t\t\t\t\t\t\t7: (b: Bools) => b[2] xor b[3],\n\t\t\t\t\t\t\t\t\t\t8: (b: Bools) => not b[7] or b[5] and b[6],\n\t\t\t\t\t\t\t\t\t\t9: (b: Bools) => b[1..6].count(true) == 3,\n\t\t\t\t\t\t\t\t\t\t10: (b: Bools) => b[11] and b[12],\n\t\t\t\t\t\t\t\t\t\t11: (b: Bools) => b[7..9].count(true) == 1,\n\t\t\t\t\t\t\t\t\t\t12: (b: Bools) => b[1..11].count(true) == 4]\n\n\nproc `$`(b: Bools): string =\n\ttoSeq(1..12).filterIt(b[it]).join(\" \")\n\n\necho \"Exacts hits:\"\nvar bools: Bools\nfor n in 0..4095:\n\tblock check:\n\t\tfor i in 1..12: bools[i] = n.testBit(12 - i)\n\t\tfor i, predicate in Predicates:\n\t\t\tif predicate(bools) != bools[i]:\n\t\t\t\tbreak check\n\t\techo \" \", bools\n\necho \"\\nNear misses:\"\nfor n in 0..4095:\n\tfor i in 1..12: bools[i] = n.testBit(12 - i)\n\tvar count = 0\n\tfor i, predicate in Predicates:\n\t\tif predicate(bools) == bools[i]: inc count\n\tif count == 11:\n\t\tfor i, predicate in Predicates:\n\t\t\tif predicate(bools) != bools[i]:\n\t\t\t\techo \" (Fails at statement {i:2}) {bools}\"\n\t\t\t\tbreak\n" + }, + { + "id": 955, + "length": 662, + "source": "Rosetta Code", + "text": "import re, strutils\n\nconst\n\tWords = [\"She\", \"she\", \"Her\", \"her\", \"hers\", \"He\", \"he\", \"His\", \"his\", \"him\"]\n\tRepls = [\"He_\", \"he_\", \"His_\", \"his_\" ,\"his_\", \"She_\", \"she_\", \"Her_\", \"her_\", \"her_\"]\n\nfunc reverseGender(s: string): string =\n\tresult = s\n\tfor i, word in Words:\n\t\tlet r = re(r\"\\b\" & word & r\"\\b\")\n\t\tresult = result.replace(r, Repls[i])\n\tresult = result.replace(\"_\", \"\")\n\necho reverseGender(\"She was a soul stripper. She took his heart!\")\necho reverseGender(\"He was a soul stripper. He took her heart!\")\necho reverseGender(\"She wants what's hers, he wants her and she wants him!\")\necho reverseGender(\"Her dog belongs to him but his dog is hers!\")\n" + }, + { + "id": 956, + "length": 1099, + "source": "Rosetta Code", + "text": "func mrUnrank1(vec: var openArray[int]; rank, n: int) =\n\tif n < 1: return\n\tlet q = rank div n\n\tlet r = rank mod n\n\tswap vec[r], vec[n - 1]\n\tvec.mrUnrank1(q, n - 1)\n\nfunc mrRank1(vec, inv: var openArray[int]; n: int): int =\n\tif n < 2: return 0\n\tlet s = vec[n - 1]\n\tswap vec[n - 1], vec[inv[n - 1]]\n\tswap inv[s], inv[n - 1]\n\tresult = s + n * vec.mrRank1(inv, n - 1)\n\nfunc getPermutation(vec: var openArray[int]; rank: int) =\n\tfor i in 0..vec.high: vec[i] = i\n\tvec.mrUnrank1(rank, vec.len)\n\nfunc getRank(vec: openArray[int]): int =\n\tvar v, inv = newSeq[int](vec.len)\n\tfor i, val in vec:\n\t\tv[i] = val\n\t\tinv[val] = i\n\tresult = v.mrRank1(inv, vec.len)\n\n\nwhen isMainModule:\n\n\timport math, random, sequtils, strformat\n\n\trandomize()\n\n\tvar tv3: array[3, int]\n\tfor r in 0..5:\n\t\ttv3.getPermutation(r)\n\t\techo \"{r:>2} -> {tv3} -> {tv3.getRank()}\"\n\n\techo \"\"\n\tvar tv4: array[4, int]\n\tfor r in 0..23:\n\t\ttv4.getPermutation(r)\n\t\techo \"{r:>2} -> {tv4} -> {tv4.getRank()}\"\n\n\techo \"\"\n\tvar tv12: array[12, int]\n\tfor r in newSeqWith(4, rand(fac(12))):\n\t\ttv12.getPermutation(r)\n\t\techo \"{r:>9} -> {tv12} -> {tv12.getRank()}\"\n" + }, + { + "id": 957, + "length": 2576, + "source": "Rosetta Code", + "text": "type Zeckendorf = object\n\tdVal: Natural\n\tdLen: Natural\n\nconst\n\tDig = [\"00\", \"01\", \"10\"]\n\tDig1 = [\"\", \"1\", \"10\"]\n\n# Forward references.\nfunc b(z: var Zeckendorf; pos: Natural)\nfunc inc(z: var Zeckendorf)\n\n\nfunc a(z: var Zeckendorf; n: Natural) =\n\tvar i = n\n\twhile true:\n\n\t\tif z.dLen < i: z.dLen = i\n\t\tlet j = z.dVal shr (i * 2) and 3\n\n\t\tcase j\n\t\tof 0, 1:\n\t\t\treturn\n\t\tof 2:\n\t\t\tif (z.dVal shr ((i + 1) * 2) and 1) != 1: return\n\t\t\tz.dVal += 1 shl (i * 2 + 1)\n\t\t\treturn\n\t\tof 3:\n\t\t\tz.dVal = z.dVal and not (3 shl (i * 2))\n\t\t\tz.b((i + 1) * 2)\n\t\telse:\n\t\t\t\tassert(false)\n\n\t\tinc i\n\n\nfunc b(z: var Zeckendorf; pos: Natural) =\n\tif pos == 0:\n\t\tinc z\n\t\treturn\n\n\tif (z.dVal shr pos and 1) == 0:\n\t\tz.dVal += 1 shl pos\n\t\tz.a(pos div 2)\n\t\tif pos > 1: z.a(pos div 2 - 1)\n\telse:\n\t\tz.dVal = z.dVal and not(1 shl pos)\n\t\tz.b(pos + 1)\n\t\tz.b(pos - (if pos > 1: 2 else: 1))\n\n\nfunc c(z: var Zeckendorf; pos: Natural) =\n\tif (z.dVal shr pos and 1) == 1:\n\t\tz.dVal = z.dVal and not(1 shl pos)\n\t\treturn\n\n\tz.c(pos + 1)\n\tif pos > 0:\n\t\tz.b(pos - 1)\n\telse:\n\t\tinc z\n\n\nfunc initZeckendorf(s = \"0\"): Zeckendorf =\n\tvar q = 1\n\tvar i = s.high\n\tresult.dLen = i div 2\n\twhile i >= 0:\n\t\tresult.dVal += (ord(s[i]) - ord('0')) * q\n\t\tq *= 2\n\t\tdec i\n\n\nfunc inc(z: var Zeckendorf) =\n\tinc z.dVal\n\tz.a(0)\n\n\nfunc `+=`(z1: var Zeckendorf; z2: Zeckendorf) =\n\tfor gn in 0 .. (2 * z2.dLen + 1):\n\t\tif (z2.dVal shr gn and 1) == 1:\n\t\t\tz1.b(gn)\n\n\nfunc `-=`(z1: var Zeckendorf; z2: Zeckendorf) =\n\tfor gn in 0 .. (2 * z2.dLen + 1):\n\t\tif (z2.dVal shr gn and 1) == 1:\n\t\t\tz1.c(gn)\n\n\twhile z1.dLen > 0 and (z1.dVal shr (z1.dLen * 2) and 3) == 0:\n\t\tdec z1.dLen\n\n\nfunc `*=`(z1: var Zeckendorf; z2: Zeckendorf) =\n\tvar na, nb = z2\n\tvar nr: Zeckendorf\n\tfor i in 0 .. (z1.dLen + 1) * 2:\n\t\tif (z1.dVal shr i and 1) > 0: nr += nb\n\t\tlet nt = nb\n\t\tnb += na\n\t\tna = nt\n\tz1 = nr\n\nfunc`$`(z: var Zeckendorf): string =\n\tif z.dVal == 0: return \"0\"\n\tresult.add Dig1[z.dVal shr (z.dLen * 2) and 3]\n\tfor i in countdown(z.dLen - 1, 0):\n\t\tresult.add Dig[z.dVal shr (i * 2) and 3]\n\nwhen isMainModule:\n\n\tvar g: Zeckendorf\n\n\techo \"Addition:\"\n\tg = initZeckendorf(\"10\")\n\tg += initZeckendorf(\"10\")\n\techo g\n\tg += initZeckendorf(\"10\")\n\techo g\n\tg += initZeckendorf(\"1001\")\n\techo g\n\tg += initZeckendorf(\"1000\")\n\techo g\n\tg += initZeckendorf(\"10101\")\n\techo g\n\n\n\techo \"\\nSubtraction:\"\n\tg = initZeckendorf(\"1000\")\n\tg -= initZeckendorf(\"101\")\n\techo g\n\tg = initZeckendorf(\"10101010\")\n\tg -= initZeckendorf(\"1010101\")\n\techo g\n\n\techo \"\\nMultiplication:\"\n\tg = initZeckendorf(\"1001\")\n\tg *= initZeckendorf(\"101\")\n\techo g\n\tg = initZeckendorf(\"101010\")\n\tg += initZeckendorf(\"101\")\n\techo g\n" + }, + { + "id": 958, + "length": 6203, + "source": "Rosetta Code", + "text": "import bignum\n\ntype\n\n\t# Description of a term.\n\tTerm = object\n\t\tfactor: int # Multiplier (may be negative).\n\t\tfract: Rat # Argument of arc tangent.\n\n\tExpression = seq[Term]\n\n# Rational 1.\nlet One = newRat(1)\n\n\n# Formula parser.\n\ntype\n\n\t# Possible tokens for parsing.\n\tToken = enum tkPi, tkArctan, tkNumber, tkEqual, tkAdd, tkSub,\n\t\t\t\t\t\t\t tkMul, tkDiv, tkLPar, tkRPar, tkError, tkEnd\n\n\t# Lexer description.\n\tLexer = object\n\t\tline: string # The line to parse.\n\t\tpos: Natural # Current position of lexer.\n\t\ttoken: Token # Current token.\n\t\tvalue: Natural # Associated value (for numbers).\n\n\t# Exception raised if an error is found.\n\tSyntaxError = object of CatchableError\n\n\nproc initLexer(line: string): Lexer =\n\t## Create and initialize a lexer.\n\tresult.line = line\n\tresult.pos = 0\n\n\nproc parseName(lexer: var Lexer; pos: Natural) =\n\t## Parse a name.\n\n\t# Build the name.\n\tvar pos = pos\n\tvar name = \"\"\n\twhile pos < lexer.line.len and (let c = lexer.line[pos]; c) in 'a'..'z':\n\t\tname.add(c)\n\t\tinc pos\n\n\t# Update lexer state.\n\tlexer.token = if name == \"arctan\": tkArctan\n\t\t\t\t\t\t\t\telif name == \"pi\": tkPi\n\t\t\t\t\t\t\t\telse: tkError\n\tlexer.pos = pos\n\n\nproc parseNumber(lexer: var Lexer; pos: Natural) =\n\t## Parse a number.\n\n\t# Build the number.\n\tvar pos = pos\n\tvar value = 0\n\twhile pos < lexer.line.len and (let c = lexer.line[pos]; c) in '0'..'9':\n\t\tvalue = 10 * value + ord(c) - ord('0')\n\t\tinc pos\n\n\t# Update lexer state.\n\tlexer.token = tkNumber\n\tlexer.value = value\n\tlexer.pos = pos\n\n\nproc getNextToken(lexer: var Lexer) =\n\t## Find next token.\n\n\tvar pos = lexer.pos\n\tvar token: Token\n\twhile pos < lexer.line.len and lexer.line[pos] == ' ': inc pos\n\tif pos == lexer.line.len:\n\t\t# Reached end of string.\n\t\tlexer.pos = pos\n\t\tlexer.token = tkEnd\n\t\treturn\n\n\t# Find token.\n\tcase lexer.line[pos]\n\tof '=': token = tkEqual\n\tof '+': token = tkAdd\n\tof '-': token = tkSub\n\tof '*': token = tkMul\n\tof '/': token = tkDiv\n\tof '(': token = tkLPar\n\tof ')': token = tkRPar\n\tof 'a'..'z':\n\t\tlexer.parseName(pos)\n\t\treturn\n\tof '0'..'9':\n\t\tlexer.parseNumber(pos)\n\t\treturn\n\telse: token = tkError\n\n\t# Update lexer state.\n\tlexer.pos = pos + 1\n\tlexer.token = token\n\n\ntemplate syntaxError(message: string) =\n\t## Raise a syntax error exception.\n\traise newException(SyntaxError, message)\n\n\nproc parseFraction(lexer: var Lexer): Rat =\n\t## Parse a fraction: number / number.\n\n\tlexer.getNextToken()\n\tif lexer.token != tkNumber:\n\t\tsyntaxError(\"number expected.\")\n\tlet num = lexer.value\n\tlexer.getNextToken()\n\tif lexer.token != tkDiv:\n\t\tsyntaxError(\"/ expected.\")\n\tlexer.getNextToken()\n\tif lexer.token != tkNumber:\n\t\tsyntaxError(\"number expected\")\n\tif lexer.value == 0:\n\t\traise newException(ValueError, \"null denominator.\")\n\tlet den = lexer.value\n\tresult = newRat(num, den)\n\n\nproc parseTerm(lexer: var Lexer): Term =\n\t## Parse a term: factor * arctan(fraction) or arctan(fraction).\n\n\tlexer.getNextToken()\n\n\t# Parse factor.\n\tif lexer.token == tkNumber:\n\t\tresult.factor = lexer.value\n\t\tlexer.getNextToken\n\t\tif lexer.token != tkMul:\n\t\t\tsyntaxError(\"* expected.\")\n\t\tlexer.getNextToken()\n\telse:\n\t\tresult.factor = 1\n\n\t# Parse arctan.\n\tif lexer.token != tkArctan:\n\t\tsyntaxError(\"arctan expected.\")\n\tlexer.getNextToken()\n\tif lexer.token != tkLPar:\n\t\tsyntaxError(\"( expected.\")\n\tresult.fract = lexer.parseFraction()\n\tlexer.getNextToken()\n\tif lexer.token != tkRPar:\n\t\tsyntaxError(\") expected.\")\n\n\nproc parse(line: string): Expression =\n\t## Parse a formula.\n\n\tvar lexer = initLexer(line)\n\tlexer.getNextToken()\n\n\tif lexer.token != tkPi:\n\t\tsyntaxError(\"pi symbol expected.\")\n\tlexer.getNextToken()\n\n\tif lexer.token != tkDiv:\n\t\tsyntaxError(\"'/' expected.\")\n\tlexer.getNextToken()\n\n\tif lexer.token != tkNumber:\n\t\tsyntaxError(\"number expected.\")\n\tif lexer.value != 4:\n\t\traise newException(ValueError, \"value 4 expected.\")\n\tlexer.getNextToken()\n\n\tif lexer.token != tkEqual:\n\t\tsyntaxError(\"= expected.\")\n\tresult.add(lexer.parseTerm())\n\tlexer.getNextToken()\n\n\t# Parse the next terms.\n\twhile (let token = lexer.token; token) in {tkAdd, tkSub}:\n\t\tvar term = lexer.parseTerm()\n\t\tif token == tkSub:\n\t\t\tterm.factor = -term.factor\n\t\tresult.add(term)\n\t\tlexer.getNextToken()\n\n\tif lexer.token != tkEnd:\n\t\tsyntaxError(\"invalid characters at end of formula.\")\n\n\n# Evaluator.\n\nproc tangent(factor: int; fract: Rat): Rat =\n\t## Compute the tangent of \"factor * arctan(fract)\".\n\n\tif factor == 1:\n\t\treturn fract\n\tif factor < 0:\n\t\treturn -tangent(-factor, fract)\n\n\t# Split in two parts.\n\tlet n = factor div 2\n\tlet a = tangent(n, fract)\n\tlet b = tangent(factor - n, fract)\n\tresult = (a + b) / (One - a * b)\n\n\nproc tangent(expr: Expression): Rat =\n\t## Compute the tangent of a sum of terms.\n\n\tif expr.len == 1:\n\t\tresult = tangent(expr[0].factor, expr[0].fract)\n\telse:\n\t\t# Split in two parts.\n\t\tlet a = tangent(expr[0..<(expr.len div 2)])\n\t\tlet b = tangent(expr[(expr.len div 2)..^1])\n\t\tresult = (a + b) / (One - a * b)\n\n\nwhen isMainModule:\n\n\tconst Formulas = [\n\t\t\"pi/4 = arctan(1/2) + arctan(1/3)\",\n\t\t\"pi/4 = 2*arctan(1/3) + arctan(1/7)\",\n\t\t\"pi/4 = 4*arctan(1/5) - arctan(1/239)\",\n\t\t\"pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\",\n\t\t\"pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\",\n\t\t\"pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)\",\n\t\t\"pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)\",\n\t\t\"pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\",\n\t\t\"pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\",\n\t\t\"pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\",\n\t\t\"pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\",\n\t\t\"pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\",\n\t\t\"pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\",\n\t\t\"pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\",\n\t\t\"pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\",\n\t\t\"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\",\n\t\t\"pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\"]\n\nfor formula in Formulas:\n\tlet expr = formula.parse()\n\tlet value = tangent(expr)\n\tif value == 1:\n\t\techo \"True: \", formula\n\telse:\n\t\techo \"False: \", formula\n\t\techo \"Tangent of the right expression is about \", value.toFloat\n" + }, + { + "id": 959, + "length": 737, + "source": "Rosetta Code", + "text": "import strformat\n\nconst maxBest = 32\nvar best: array[maxBest, int]\n\nproc trySwaps(deck: seq[int], f, d, n: int) =\n\tif d > best[n]:\n\t\tbest[n] = d\n\n\tfor i in countdown(n - 1, 0):\n\t\tif deck[i] == -1 or deck[i] == i:\n\t\t\tbreak\n\t\tif d + best[i] <= best[n]:\n\t\t\treturn\n\n\tvar deck2 = deck\n\tfor i in 1.. 0 and n < maxBest)\n\tbest[n] = 0\n\tvar deck0 = newSeq[int](n + 1)\n\tfor i in 1.. 1e20 or pt.x < -1e20\n\n\nfunc `-`(pt: Point): Point {.inline.} =\n\t(pt.x, -pt.y)\n\n\nfunc double(pt: Point): Point =\n\n\tif pt.isZero: return pt\n\n\tlet t = (3 * pt.x * pt.x) / (2 * pt.y)\n\tresult.x = t * t - 2 * pt.x\n\tresult.y = t * (pt.x - result.x) - pt.y\n\n\nfunc `+`(pt1, pt2: Point): Point =\n\n\tif pt1.x == pt2.x and pt1.y == pt2.y: return double(pt1)\n\tif pt1.isZero: return pt2\n\tif pt2.isZero: return pt1\n\n\tlet t = (pt2.y - pt1.y) / (pt2.x - pt1.x)\n\tresult.x = t * t - pt1.x - pt2.x\n\tresult.y = t * (pt1.x - result.x) - pt1.y\n\n\nfunc `*`(pt: Point; n: int): Point =\n\n\tresult = zero()\n\tvar pt = pt\n\tvar i = 1\n\n\twhile i <= n:\n\t\tif (i and n) != 0:\n\t\t\tresult = result + pt\n\t\tpt = double(pt)\n\t\ti = i shl 1\n\n\nfunc `$`(pt: Point): string =\n\tif pt.isZero: \"Zero\" else: fmt\"({pt.x:.3f}, {pt.y:.3f})\"\n\n\nfunc fromY(y: float): Point {.inline.} =\n\t(cbrt(y * y - B), y)\n\n\nwhen isMainModule:\n\tlet a = fromY(1)\n\tlet b = fromY(2)\n\n\techo \"a = \", a\n\techo \"b = \", b\n\tlet c = a + b\n\techo \"c = a + b = \", c\n\tlet d = -c\n\techo \"d = -c = \", d\n\techo \"c + d = \", c + d\n\techo \"a + b + d = \", a + b + d\n\techo \"a * 12345 = \", a * 12345\n" + }, + { + "id": 962, + "length": 985, + "source": "Rosetta Code", + "text": "import httpclient, strutils, strformat\n\nconst\n\tRule1 = \"\\\"I before E when not preceded by C\\\"\"\n\tRule2 = \"\\\"E before I when preceded by C\\\"\"\n\tPhrase = \"\\\"I before E except after C\\\"\"\n\tPlausibilityText: array[bool, string] = [\"not plausible\", \"plausible\"]\n\n\nproc plausibility(rule: string; count1, count2: int): bool =\n\t## Compute, display and return plausibility.\n\tresult = count1 > 2 * count2\n\tstdout.write \"The rule {rule} is {PlausibilityText[result]}: \"\n\techo \"there were {count1} examples and {count2} counter-examples.\"\n\n\nlet client = newHttpClient()\n\nvar nie, cie, nei, cei = 0\nfor word in client.getContent(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\").split():\n\tif word.contains(\"ie\"):\n\t\tif word.contains(\"cie\"):\n\t\t\tinc cie\n\t\telse:\n\t\t\tinc nie\n\tif word.contains(\"ei\"):\n\t\tif word.contains(\"cei\"):\n\t\t\tinc cei\n\t\telse:\n\t\t\tinc nei\n\nlet p1 = plausibility(Rule1, nie, nei)\nlet p2 = plausibility(Rule2, cei, cie)\necho \"So the phrase {Phrase} is {PlausibilityText[p1 and p2]}.\"\n" + }, + { + "id": 963, + "length": 709, + "source": "Rosetta Code", + "text": "import random, math, strformat\nrandomize()\n\nconst\n\tmaxN = 20\n\ttimes = 1_000_000\n\nproc factorial(n: int): float =\n\tresult = 1\n\tfor i in 1 .. n:\n\t\tresult *= i.float\n\nproc expected(n: int): float =\n\tfor i in 1 .. n:\n\t\tresult += factorial(n) / pow(n.float, i.float) / factorial(n - i)\n\nproc test(n, times: int): int =\n\tfor i in 1 .. times:\n\t\tvar\n\t\t\tx = 1\n\t\t\tbits = 0\n\t\twhile (bits and x) == 0:\n\t\t\tinc result\n\t\t\tbits = bits or x\n\t\t\tx = 1 shl rand(n - 1)\n\necho \" n\\tavg\\texp.\\tdiff\"\necho \"-------------------------------\"\nfor n in 1 .. maxN:\n\tlet cnt = test(n, times)\n\tlet avg = cnt.float / times\n\tlet theory = expected(n)\n\tlet diff = (avg / theory - 1) * 100\n\techo fmt\"{n:2} {avg:8.4f} {theory:8.4f} {diff:6.3f}%\"\n" + }, + { + "id": 964, + "length": 936, + "source": "Rosetta Code", + "text": "import os, strutils, sequtils, tables\n\nconst Unit2Mult = {\"arshin\": 0.7112, \"centimeter\": 0.01, \"diuym\": 0.0254,\n\t\t\t\t\t\t\t\t\t \"fut\": 0.3048, \"kilometer\": 1000.0, \"liniya\": 0.00254,\n\t\t\t\t\t\t\t\t\t \"meter\": 1.0, \"milia\": 7467.6, \"piad\": 0.1778,\n\t\t\t\t\t\t\t\t\t \"sazhen\": 2.1336, \"tochka\": 0.000254, \"vershok\": 0.04445,\n\t\t\t\t\t\t\t\t\t \"versta\": 1066.8}.toOrderedTable\n\nif paramCount() != 2:\n\traise newException(ValueError, \"need two arguments: number then units.\")\n\nlet value = try: parseFloat(paramStr(1))\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\traise newException(ValueError, \"first argument must be a (float) number.\")\n\nlet unit = paramStr(2)\nif unit notin Unit2Mult:\n\traise newException(ValueError,\n\t\t\t\t\t\t\t\t\t\t \"only know the following units: \" & toSeq(Unit2Mult.keys).join(\" \"))\n\necho value, ' ', unit, \" to:\"\nfor (key, mult) in Unit2Mult.pairs:\n\techo key.align(10), \": \", formatFloat(value * Unit2Mult[unit] / mult, ffDecimal, 5)\n" + }, + { + "id": 965, + "length": 2104, + "source": "Rosetta Code", + "text": "import strutils, tables\n\nproc runUTM(state, halt, blank: string, tape: seq[string] = @[],\n\t\t\t\t\t\trules: seq[seq[string]]) =\n\tvar\n\t\tst = state\n\t\tpos = 0\n\t\ttape = tape\n\t\trulesTable: Table[tuple[s0, v0: string], tuple[v1, dr, s1: string]]\n\n\tif tape.len == 0: tape = @[blank]\n\tif pos < 0: pos += tape.len\n\tassert pos in 0..tape.high\n\n\tfor r in rules:\n\t\tassert r.len == 5\n\t\trulesTable[(r[0], r[1])] = (r[2], r[3], r[4])\n\n\twhile true:\n\t\tstdout.write st, '\\t'\n\t\tfor i, v in tape:\n\t\t\tstdout.write if i == pos: '[' & v & ']' else: ' ' & v & ' '\n\t\techo()\n\n\t\tif st == halt: break\n\t\tif not rulesTable.hasKey((st, tape[pos])): break\n\n\t\tlet (v1, dr, s1) = rulesTable[(st, tape[pos])]\n\t\ttape[pos] = v1\n\t\tif dr == \"left\":\n\t\t\tif pos > 0: dec pos\n\t\t\telse: tape.insert blank\n\t\tif dr == \"right\":\n\t\t\tinc pos\n\t\t\tif pos >= tape.len: tape.add blank\n\t\tst = s1\n\necho \"incr machine\\n\"\nrunUTM(halt = \"qf\",\n\t\t\t state = \"q0\",\n\t\t\t tape = \"1 1 1\".split,\n\t\t\t blank = \"B\",\n\t\t\t rules = @[\"q0 1 1 right q0\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"q0 B 1 stay qf\".splitWhitespace])\n\necho \"\\nbusy beaver\\n\"\nrunUTM(halt = \"halt\",\n\t\t\t state = \"a\",\n\t\t\t blank = \"0\",\n\t\t\t rules = @[\"a 0 1 right b\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"a 1 1 left c\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"b 0 1 left a\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"b 1 1 right b\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"c 0 1 left b\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"c 1 1 stay halt\".splitWhitespace])\n\necho \"\\nsorting test\\n\"\nrunUTM(halt = \"STOP\",\n\t\t\t state = \"A\",\n\t\t\t blank = \"0\",\n\t\t\t tape = \"2 2 2 1 2 2 1 2 1 2 1 2 1 2\".split,\n\t\t\t rules = @[\"A 1 1 right A\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"A 2 3 right B\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"A 0 0 left E\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"B 1 1 right B\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"B 2 2 right B\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"B 0 0 left C\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"C 1 2 left D\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"C 2 2 left C\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"C 3 2 left E\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"D 1 1 left D\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"D 2 2 left D\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"D 3 1 right A\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"E 1 1 left E\".splitWhitespace,\n\t\t\t\t\t\t\t\t \"E 0 0 right STOP\".splitWhitespace])\n" + }, + { + "id": 966, + "length": 661, + "source": "Rosetta Code", + "text": "iterator r2cf*(n1, n2: int): int =\n\tvar (n1, n2) = (n1, n2)\n\twhile n2 != 0:\n\t\tyield n1 div n2\n\t\tn1 = n1 mod n2\n\t\tswap n1, n2\n\n\nwhen isMainModule:\n\n\tfrom sequtils import toSeq\n\n\tfor pair in [(1, 2), (3, 1), (23, 8), (13, 11), (22, 7), (-151, 77)]:\n\t\techo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n\n\techo \"\"\n\tfor pair in [(14142, 10000), (141421, 100000), (1414214, 1000000), (14142136, 10000000)]:\n\t\techo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n\n\techo \"\"\n\tfor pair in [(31,10), (314,100), (3142,1000), (31428,10000), (314285,100000),\n\t\t\t\t\t\t\t(3142857,1000000), (31428571,10000000), (314285714,100000000)]:\n\t\techo pair, \" -> \", toSeq(r2cf(pair[0], pair[1]))\n" + }, + { + "id": 967, + "length": 2185, + "source": "Rosetta Code", + "text": "import math, rationals, strformat\n\ntype\n\tRat = Rational[int]\n\tNg = tuple[a1, a, b1, b: int]\n\nconst NS = 1 // 1 # Non significant value.\n\n\niterator r2cf(rat: Rat): int {.closure.} =\n\tvar\n\t\tnum = rat.num\n\t\tden = rat.den\n\tfor count in 1..20:\n\t\tlet d = num div den\n\t\tnum = num mod den\n\t\tswap num, den\n\t\tyield d\n\t\tif den == 0: break\n\n\niterator d2cf(f: float): int {.closure.} =\n\tvar f = f\n\tfor count in 1..20:\n\t\tlet d = floor(f)\n\t\tlet r = f - d\n\t\tyield int(d)\n\t\tif r == 0: break\n\t\tf = 1 / r\n\n\niterator root2(dummy: Rat): int {.closure.} =\n\tyield 1\n\tfor count in 1..20: yield 2\n\n\niterator recipRoot2(rat: Rat): int {.closure.} =\n\tyield 0\n\tyield 1\n\tfor count in 1..20: yield 2\n\n\nfunc ingress(ng: var Ng; n: int) =\n\tng.a += ng.a1 * n\n\tswap ng.a, ng.a1\n\tng.b += ng.b1 * n\n\tswap ng.b, ng.b1\n\n\nfunc egress(ng: var Ng): int =\n\tlet n = ng.a div ng.b\n\tng.a -= ng.b * n\n\tswap ng.a, ng.b\n\tng.a1 -= ng.b1 * n\n\tswap ng.a1, ng.b1\n\tresult = n\n\n\nfunc needTerm(ng: Ng): bool = ng.b == 0 or ng.b1 == 0 or (ng.a // ng.b != ng.a1 // ng.b1)\n\n\nfunc egressDone(ng: var Ng): int =\n\tif ng.needTerm:\n\t\tng.a = ng.a1\n\t\tng.b = ng.b1\n\tresult = ng.egress()\n\n\nfunc done(ng: Ng): bool = ng.b == 0 or ng.b1 == 0\n\n\nwhen isMainModule:\n\n\tlet data = [(\"[1;5,2] + 1/2 \", (2, 1, 0, 2), 13 // 11, r2cf),\n\t\t\t\t\t\t\t(\"[3;7] + 1/2 \", (2, 1, 0, 2), 22 // 7, r2cf),\n\t\t\t\t\t\t\t(\"[3;7] divided by 4 \", (1, 0, 0, 4), 22 // 7, r2cf),\n\t\t\t\t\t\t\t(\"sqrt(2) \", (0, 1, 1, 0), NS, recipRoot2),\n\t\t\t\t\t\t\t(\"1 / sqrt(2) \", (0, 1, 1, 0), NS, root2),\n\t\t\t\t\t\t\t(\"(1 + sqrt(2)) / 2 \", (1, 1, 0, 2), NS, root2),\n\t\t\t\t\t\t\t(\"(1 + 1 / sqrt(2)) / 2\", (1, 1, 0, 2), NS, recipRoot2)]\n\n\techo \"Produced by NG object:\"\n\tfor (str, ng, r, gen) in data:\n\t\tstdout.write \"{str} -> \"\n\t\tvar op = ng\n\t\tfor n in gen(r):\n\t\t\tif not op.needTerm: stdout.write \" {op.egress()} \"\n\t\t\top.ingress(n)\n\t\twhile true:\n\t\t\tstdout.write \" {op.egressDone} \"\n\t\t\tif op.done: break\n\t\techo()\n\n\techo \"\\nProduced by direct calculation:\"\n\tlet data2 = [(\"(1 + sqrt(2)) / 2 \", (1 + sqrt(2.0)) / 2),\n\t\t\t\t\t\t\t (\"(1 + 1 / sqrt(2)) / 2\", (1 + 1 / sqrt(2.0)) / 2)]\n\tfor (str, d) in data2:\n\t\tstdout.write \"{str} ->\"\n\t\tfor n in d2cf(d): stdout.write \" \", n\n\t\techo()\n" + }, + { + "id": 968, + "length": 2232, + "source": "Rosetta Code", + "text": "import algorithm, math, random, sequtils, strformat, strutils\n\ntype\n\n\t# Card features.\n\tNumber {.pure.} = enum One, Two, Three\n\tColor {.pure.} = enum Red, Green, Purple\n\tSymbol {.pure.} = enum Oval, Squiggle, Diamond\n\tShading {.pure.} = enum Solid, Open, Striped\n\n\t# Cards and list of cards.\n\tCard = tuple[number: Number; color: Color; symbol: Symbol; shading: Shading]\n\tTriplet = array[3, Card]\n\tDeck = array[81, Card]\n\n\t# Game level.\n\tLevel {.pure.} = enum Basic = \"basic\", Advanced = \"advanced\"\n\n\nproc `$`(card: Card): string =\n\t## Return the string representation of a card.\n\ttoLowerAscii(\"{card.number:<5} {card.color:<6} {card.symbol:<8} {card.shading:<7}\")\n\n\nproc initDeck(): Deck =\n\t## Create a new deck.\n\tvar i = 0\n\tfor num in Number.low..Number.high:\n\t\tfor col in Color.low..Color.high:\n\t\t\tfor sym in Symbol.low..Symbol.high:\n\t\t\t\tfor sh in Shading.low..Shading.high:\n\t\t\t\t\tresult[i] = (number: num, color: col, symbol: sym, shading: sh)\n\t\t\t\t\tinc i\n\n\nproc isSet(triplet: Triplet): bool =\n\t## Check if a triplets of cards is a set.\n\tsum(triplet.mapIt(ord(it.number))) mod 3 == 0 and\n\tsum(triplet.mapIt(ord(it.color))) mod 3 == 0 and\n\tsum(triplet.mapIt(ord(it.symbol))) mod 3 == 0 and\n\tsum(triplet.mapIt(ord(it.shading))) mod 3 == 0\n\n\nproc playGame(level: Level) =\n\t## Play the game at given level.\n\n\tvar deck = initDeck()\n\tlet (nCards, nSets) = if level == Basic: (9, 4) else: (12, 6)\n\tvar sets: seq[Triplet]\n\tvar hand: seq[Card]\n\techo \"Playing {level} game: {nCards} cards, {nSets} sets.\"\n\n\tblock searchHand:\n\t\twhile true:\n\t\t\tsets.setLen(0)\n\t\t\tdeck.shuffle()\n\t\t\thand = deck[0.. nSets:\n\t\t\t\t\t\t\t\t\tbreak countSets # Too much sets. Try with a new hand.\n\t\t\t\tif sets.len == nSets:\n\t\t\t\t\tbreak searchHand # Found: terminate search.\n\n\t# Display the hand and the sets.\n\techo \"\\nCards:\"\n\tfor card in sorted(hand): echo \" \", card\n\techo \"\\nSets:\"\n\tfor s in sets:\n\t\tfor card in sorted(s): echo \" \", card\n\t\techo()\n\n\nrandomize()\nplayGame(Basic)\necho()\nplayGame(Advanced)\n" + }, + { + "id": 969, + "length": 4987, + "source": "Rosetta Code", + "text": "import strformat\n\n\ntype MatrixNG = ref object of RootObj\n\tcfn: int\n\tthisTerm: int\n\thaveTerm: bool\n\nmethod consumeTerm(m: MatrixNG) {.base.} =\n\traise newException(CatchableError, \"Method without implementation override\")\n\nmethod consumeTerm(m: MatrixNG; n: int) {.base.} =\n\traise newException(CatchableError, \"Method without implementation override\")\n\nmethod needTerm(m: MatrixNG): bool {.base.} =\n\traise newException(CatchableError, \"Method without implementation override\")\n\n\n\ntype NG4 = ref object of MatrixNG\n\ta1, a, b1, b: int\n\nproc newNG4(a1, a, b1, b: int): NG4 =\n\tNG4(a1: a1, a: a, b1: b1, b: b)\n\nmethod needTerm(ng: NG4): bool =\n\tif ng.b1 == 0 and ng.b == 0: return false\n\tif ng.b1 == 0 or ng.b == 0: return true\n\tng.thisTerm = ng.a div ng.b\n\tif ng.thisTerm == ng.a1 div ng.b1:\n\t\tng.a -= ng.b * ng.thisTerm; swap ng.a, ng.b\n\t\tng.a1 -= ng.b1 * ng.thisTerm; swap ng.a1, ng.b1\n\t\tng.haveTerm = true\n\t\treturn false\n\treturn true\n\nmethod consumeTerm(ng: NG4) =\n\tng.a = ng.a1\n\tng.b = ng.b1\n\nmethod consumeTerm(ng: NG4; n: int) =\n\tng.a += ng.a1 * n; swap ng.a, ng.a1\n\tng.b += ng.b1 * n; swap ng.b, ng.b1\n\n\n\ntype NG8 = ref object of MatrixNG\n\ta12, a1, a2, a: int\n\tb12, b1, b2, b: int\n\nproc newNG8(a12, a1, a2, a, b12, b1, b2, b: int): NG8 =\n\tNG8(a12: a12, a1: a1, a2: a2, a: a, b12: b12, b1: b1, b2: b2, b: b)\n\n\nmethod needTerm(ng: NG8): bool =\n\tif ng.b1 == 0 and ng.b == 0 and ng.b2 == 0 and ng.b12 == 0: return false\n\tif ng.b == 0:\n\t\tng.cfn = ord(ng.b2 != 0)\n\t\treturn true\n\tif ng.b2 == 0:\n\t\tng. cfn = 1\n\t\treturn true\n\tif ng.b1 == 0:\n\t\tng.cfn = 0\n\t\treturn true\n\n\tlet\n\t\tab = ng.a / ng.b\n\t\ta1b1 = ng.a1 / ng.b1\n\t\ta2b2 = ng.a2 / ng.b2\n\tif ng.b12 == 0:\n\t\tng.cfn = ord(abs(a1b1 - ab) <= abs(a2b2 - ab))\n\t\treturn true\n\n\tng.thisTerm = int(ab)\n\tif ng.thisTerm == int(a1b1) and ng.thisTerm == int(a2b2) and ng.thisTerm == ng.a12 div ng.b12:\n\t\tng.a -= ng.b * ng.thisTerm; swap ng.a, ng.b\n\t\tng.a1 -= ng.b1 * ng.thisTerm; swap ng.a1, ng.b1\n\t\tng.a2 -= ng.b2 * ng.thisTerm; swap ng.a2, ng.b2\n\t\tng.a12 -= ng.b12 * ng.thisTerm; swap ng.a12, ng.b12\n\t\tng.haveTerm = true\n\t\treturn false\n\n\tng.cfn = ord(abs(a1b1 - ab) <= abs(a2b2 - ab))\n\tresult = true\n\n\nmethod consumeTerm(ng: NG8) =\n\tif ng.cfn == 0:\n\t\tng.a = ng.a1\n\t\tng.a2 = ng.a12\n\t\tng.b = ng.b1\n\t\tng.b2 = ng.b12\n\telse:\n\t\tng.a = ng.a2\n\t\tng.a1 = ng.a12\n\t\tng.b = ng.b2\n\t\tng.b1 = ng.b12\n\nmethod consumeTerm(ng: NG8; n: int) =\n\tif ng.cfn == 0:\n\t\tng.a += ng.a1 * n; swap ng.a, ng.a1\n\t\tng.a2 += ng.a12 * n; swap ng.a2, ng.a12\n\t\tng.b += ng.b1 * n; swap ng.b, ng.b1\n\t\tng.b2 += ng.b12 * n; swap ng.b2, ng.b12\n\telse:\n\t\tng.a += ng.a2 * n; swap ng.a, ng.a2\n\t\tng.a1 += ng.a12 * n; swap ng.a1, ng.a12\n\t\tng.b += ng.b2 * n; swap ng.b, ng.b2\n\t\tng.b1 += ng.b12 * n; swap ng.b1, ng.b12\n\n\n\ntype ContinuedFraction = ref object of RootObj\n\nmethod nextTerm(cf: ContinuedFraction): int {.base.} =\n\traise newException(CatchableError, \"Method without implementation override\")\n\nmethod moreTerms(cf: ContinuedFraction): bool {.base.} =\n\traise newException(CatchableError, \"Method without implementation override\")\n\n\n\ntype R2Cf = ref object of ContinuedFraction\n\tn1, n2: int\n\nproc newR2Cf(n1, n2: int): R2Cf =\n\tR2Cf(n1: n1, n2: n2)\n\nmethod nextTerm(x: R2Cf): int =\n\tresult = x.n1 div x.n2\n\tx.n1 -= result * x.n2\n\tswap x.n1, x.n2\n\nmethod moreTerms(x: R2Cf): bool =\n\tabs(x.n2) > 0\n\n\n\ntype NG = ref object of ContinuedFraction\n\tng: MatrixNG\n\tn: seq[ContinuedFraction]\n\nproc newNG(ng: NG4; n1: ContinuedFraction): NG =\n\tNG(ng: ng, n: @[n1])\n\nproc newNG(ng: NG8; n1, n2: ContinuedFraction): NG =\n\tNG(ng: ng, n: @[n1, n2])\n\nmethod nextTerm(x: NG): int =\n\tx.ng.haveTerm = false\n\tresult = x.ng.thisTerm\n\nmethod moreTerms(x: NG): bool =\n\twhile x.ng.needTerm():\n\t\tif x.n[x.ng.cfn].moreTerms():\n\t\t\tx.ng.consumeTerm(x.n[x.ng.cfn].nextTerm())\n\t\telse:\n\t\t\tx.ng.consumeTerm()\n\tresult = x.ng.haveTerm\n\n\n\nwhen isMainModule:\n\n\tproc test(desc: string; cfs: varargs[ContinuedFraction]) =\n\t\techo \"TESTING -> {desc}\"\n\t\tfor cf in cfs:\n\t\t\twhile cf.moreTerms(): stdout.write \"{cf.nextTerm()} \"\n\t\t\techo()\n\t\techo()\n\n\tlet\n\t\ta = newNG8(0, 1, 1, 0, 0, 0, 0, 1)\n\t\tn2 = newR2Cf(22, 7)\n\t\tn1 = newR2Cf(1, 2)\n\t\ta3 = newNG4(2, 1, 0, 2)\n\t\tn3 = newR2cf(22, 7)\n\ttest(\"[3;7] + [0;2]\", newNG(a, n1, n2), newNG(a3, n3))\n\n\tlet\n\t\tb = newNG8(1, 0, 0, 0, 0, 0, 0, 1)\n\t\tb1 = newR2cf(13, 11)\n\t\tb2 = newR2cf(22, 7)\n\ttest(\"[1;5,2] * [3;7]\", newNG(b, b1, b2), newR2cf(286, 77))\n\n\tlet\n\t\tc = newNG8(0, 1, -1, 0, 0, 0, 0, 1)\n\t\tc1 = newR2cf(13, 11)\n\t\tc2 = newR2cf(22, 7)\n\ttest(\"[1;5,2] - [3;7]\", newNG(c, c1, c2), newR2cf(-151, 77))\n\n\tlet\n\t\td = newNG8(0, 1, 0, 0, 0, 0, 1, 0)\n\t\td1 = newR2cf(22 * 22, 7 * 7)\n\t\td2 = newR2cf(22,7)\n\ttest(\"Divide [] by [3;7]\", newNG(d, d1, d2))\n\n\tlet\n\t\tna = newNG8(0, 1, 1, 0, 0, 0, 0, 1)\n\t\ta1 = newR2cf(2, 7)\n\t\ta2 = newR2cf(13, 11)\n\t\taa = newNG(na, a1, a2)\n\t\tnb = newNG8(0, 1, -1, 0, 0, 0, 0, 1)\n\t\tb3 = newR2cf(2, 7)\n\t\tb4 = newR2cf(13, 11)\n\t\tbb = newNG(nb, b3, b4)\n\t\tnc = newNG8(1, 0, 0, 0, 0, 0, 0, 1)\n\t\tdesc = \"([0;3,2] + [1;5,2]) * ([0;3,2] - [1;5,2])\"\n\ttest(desc, newNG(nc, aa, bb), newR2cf(-7797, 5929))\n" + }, + { + "id": 970, + "length": 1003, + "source": "Rosetta Code", + "text": "import os, strformat, times\n\nconst\n\tWatches = [\"First\", \"Middle\", \"Morning\", \"Forenoon\", \"Afternoon\", \"First dog\", \"Last dog\", \"First\"]\n\tWatchEnds = [(0, 0), (4, 0), (8, 0), (12, 0), (16, 0), (18, 0), (20, 0), (23, 59)]\n\tBells = array[1..8, string]([\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\"])\n\tDing = \"ding!\"\n\n\nproc nb(h, m: Natural) =\n\tvar bell = (h * 60 + m) div 30 mod 8\n\tif bell == 0: bell = 8\n\tlet hm = (h, m)\n\tvar watch = 0\n\twhile hm > WatchEnds[watch]: inc watch\n\tlet plural = if bell == 1: ' ' else: 's'\n\tvar dings = Ding\n\tfor i in 2..bell:\n\t\tif i mod 2 != 0: dings.add ' '\n\t\tdings.add Ding\n\techo \"{h:02d}:{m:02d} {Watches[watch]:>9} watch {Bells[bell]:>5} bell{plural} {dings}\"\n\n\nproc simulateOneDay() =\n\tfor h in 0..23:\n\t\tfor m in [0, 30]:\n\t\t\tnb(h, m)\n\tnb(0, 0)\n\n\nwhen isMainModule:\n\n\tsimulateOneDay()\n\n\twhile true:\n\t\tlet d = getTime().utc()\n\t\tvar m = d.second + (d.minute mod 30) * 60\n\t\tif m == 0:\n\t\t\tnb(d.hour, d.minute)\n\t\tsleep((1800 - m) * 1000) # In milliseconds.\n" + }, + { + "id": 971, + "length": 645, + "source": "Rosetta Code", + "text": "proc lcs(x, y: string): string =\n\tif x.len == 0 or y.len == 0: return\n\tlet x1 = x[0..^2]\n\tlet y1 = y[0..^2]\n\tif x[^1] == y[^1]: return lcs(x1, y1) & x[^1]\n\tlet x2 = lcs(x, y1)\n\tlet y2 = lcs(x1, y)\n\tresult = if x2.len > y2.len: x2 else: y2\n\nproc scs(u, v: string): string =\n\tlet lcs = lcs(u, v)\n\tvar ui, vi = 0\n\tfor ch in lcs:\n\t\twhile ui < u.len and u[ui] != ch:\n\t\t\tresult.add u[ui]\n\t\t\tinc ui\n\t\twhile vi < v.len and v[vi] != ch:\n\t\t\tresult.add v[vi]\n\t\t\tinc vi\n\t\tresult.add ch\n\t\tinc ui\n\t\tinc vi\n\tif ui < u.len: result.add u.substr(ui)\n\tif vi < v.len: result.add v.substr(vi)\n\nwhen isMainModule:\n\tlet u = \"abcbdab\"\n\tlet v = \"bdcaba\"\n\techo scs(u, v)\n" + }, + { + "id": 972, + "length": 934, + "source": "Rosetta Code", + "text": "import osproc, strutils\n\ntype Waveform {.pure.} = enum\n\tSine = (1, \"sine\")\n\tSquare = (2, \"square\")\n\tSawtooth = (3, \"sawtooth\")\n\nproc getIntValue(msg: string; minval, maxval: int): int =\n\twhile true:\n\t\tstdout.write msg\n\t\tstdout.flushFile()\n\t\ttry:\n\t\t\tresult = stdin.readLine.strip().parseInt()\n\t\t\tif result notin minval..maxval:\n\t\t\t\techo \"Invalid value\"\n\t\t\telse:\n\t\t\t\treturn\n\t\texcept ValueError:\n\t\t\techo \"Error: invalid value.\"\n\t\texcept EOFError:\n\t\t\techo()\n\t\t\tquit \"Quitting.\", QuitFailure\n\nlet freq = getIntValue(\"Enter frequency in Hz (40 to 10000): \", 40, 10_000)\nlet vol = getIntValue(\"Enter volume in dB (1 to 50): \", 1, 50)\nlet dur = getIntValue(\"Enter duration in seconds (2 to 10): \", 2, 10)\nlet kind = Waveform getIntValue(\"Enter kind (1 = sine, 2 = square, 3 = sawtooth): \", 1, 3)\n\nlet args = [\"-n\", \"synth\", $dur, $kind, $freq, \"vol\", $vol, \"dB\"]\necho execProcess(\"play\", args = args, options = {poStdErrToStdOut, poUsePath})\n" + }, + { + "id": 973, + "length": 1497, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils, sugar\n\nstdout.write \"Enter the number of resources: \"\nlet r = stdin.readLine().parseInt()\n\nstdout.write \"Enter the number of processes: \"\nstdout.flushFile()\nlet p = stdin.readLine().parseInt()\n\nstdout.write \"Enter Claim Vector: \"\nlet maxRes = stdin.readLine().splitWhitespace().map(parseInt)\n\necho \"Enter Allocated Resource Table:\"\nvar curr = newSeqWith(p, newSeq[int](r))\nfor i in 0.. 0:\n\tvar safe = false\n\tfor i in 0.. avl[j]:\n\t\t\t\t\texec = false\n\t\t\t\t\tbreak\n\t\t\tif exec:\n\t\t\t\techo \"\\nProcess {i + 1} is executing.\"\n\t\t\t\trunning[i] = false\n\t\t\t\tdec count\n\t\t\t\tsafe = true\n\t\t\t\tfor j in 0.. 1:\n\t\tlet last = fields[^1]\n\t\tif last.isRoman: word.setLen(word.len - last.len)\n\tword = word.multiReplace((\" \", \"\"), (\",\", \"\"), (\"'\", \"\"), (\"-\", \"\"))\n\tfor eStr in EStrs:\n\t\tif word.endsWith(eStr): word.setLen(word.len - eStr.len)\n\tfor fStr in FStrs:\n\t\tif word.startsWith(fStr[0]): word[0..fStr[0].high] = fStr[1]\n\tfor lStr in LStrs:\n\t\tif word.endsWith(lStr[0]): word[^2..^1] = lStr[1]\n\n\tresult.add word[0]\n\tword.delete(0, 0)\n\tfor mStr in MStrs:\n\t\tword = word.replace(mStr[0], mStr[1])\n\tvar s = result[0] & word\n\tvar len = s.len\n\tfor i in 1.. 1 and s[len-2..len-1] == \"AY\":\n\t\ts.delete(len-2, len-2)\n\t\tdec len\n\tif len > 0 and s[len-1] == 'A':\n\t\ts.setLen(len-1)\n\t\tdec len\n\n\tvar prev = result[0]\n\tfor i in 1.. 6:\n\t\tname2 = \"$1($2)\".format(name2[0..5], name2[6..^1])\n\techo name1.alignLeft(16), \": \", name2\n" + }, + { + "id": 975, + "length": 1339, + "source": "Rosetta Code", + "text": "import endians, math\n\nconst\n\tSampleRate = 44100\n\tDuration = 8\n\tDataLength = SampleRate * Duration\n\tHdrSize = 44\n\tFileLen = DataLength + HdrSize - 8\n\tBps = 8\n\tChannels = 1\n\nproc writeUint16(f: File; x: uint16) =\n\tvar x = x\n\tvar y: array[2, byte]\n\tlittleEndian16(y.addr, x.addr)\n\tlet n = f.writeBytes(y, 0, 2)\n\tdoAssert n == 2\n\nproc writeUint32(f: File; x: uint32) =\n\tvar x = x\n\tvar y: array[4, byte]\n\tlittleEndian32(y.addr, x.addr)\n\tlet n = f.writeBytes(y, 0, 4)\n\tdoAssert n == 4\n\n\nlet file = open(\"notes.wav\", fmWrite)\n\n# Wav header.\nfile.write \"RIFF\"\nfile.writeUint32(FileLen)\nfile.write \"WAVE\"\nfile.write \"fmt \"\nfile.writeUint32(16) # length of format data.\nfile.writeUint16(1) # type of format(PCM).\nfile.writeUint16(Channels)\nfile.writeUint32(SampleRate)\nfile.writeUint32(SampleRate * Bps * Channels div 8)\nfile.writeUint16(Bps * Channels div 8)\nfile.writeUint16(Bps)\nfile.write \"data\"\nfile.writeUint32(DataLength) # size of data section.\n\n# Compute and write actual data.\nconst Freqs = [261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3]\nfor freq in Freqs:\n\tlet omega = 2 * Pi * freq\n\tfor i in 0..<(DataLength div Duration):\n\t\tlet y = (32 * sin(omega * i.toFloat / SampleRate.toFloat)).toInt\n\t\tfile.write chr(y.byte) # Signed int to byte then to char as it's easier this way.\n\nfile.close()\n" + }, + { + "id": 976, + "length": 1391, + "source": "Rosetta Code", + "text": "import tables, strutils, re, bigints\n\nlet countryLen = toTable({\n\t\"AL\": 28, \"AD\": 24, \"AT\": 20, \"AZ\": 28, \"BE\": 16, \"BH\": 22, \"BA\": 20, \"BR\": 29,\n\t\"BG\": 22, \"CR\": 21, \"HR\": 21, \"CY\": 28, \"CZ\": 24, \"DK\": 18, \"DO\": 28, \"EE\": 20,\n\t\"FO\": 18, \"FI\": 18, \"FR\": 27, \"GE\": 22, \"DE\": 22, \"GI\": 23, \"GR\": 27, \"GL\": 18,\n\t\"GT\": 28, \"HU\": 28, \"IS\": 26, \"IE\": 22, \"IL\": 23, \"IT\": 27, \"KZ\": 20, \"KW\": 30,\n\t\"LV\": 21, \"LB\": 28, \"LI\": 21, \"LT\": 20, \"LU\": 20, \"MK\": 19, \"MT\": 31, \"MR\": 27,\n\t\"MU\": 30, \"MC\": 27, \"MD\": 24, \"ME\": 22, \"NL\": 18, \"NO\": 15, \"PK\": 24, \"PS\": 29,\n\t\"PL\": 28, \"PT\": 25, \"RO\": 24, \"SM\": 27, \"SA\": 24, \"RS\": 22, \"SK\": 24, \"SI\": 19,\n\t\"ES\": 24, \"SE\": 24, \"CH\": 21, \"TN\": 24, \"TR\": 26, \"AE\": 23, \"GB\": 22, \"VG\": 24})\n\nproc validIban(iban: string): bool =\n\t# Ensure upper alphanumeric input\n\tvar iban = iban.replace(\" \",\"\").replace(\"\\t\",\"\")\n\tif not iban.match(re\"^[\\dA-Z]+$\"):\n\t\treturn false\n\n\t# Validate country code against expected length\n\tif iban.len != countryLen[iban[0..1]]:\n\t\treturn false\n\n\t# Shift and convert\n\tiban = iban[4..iban.high] & iban[0..3]\n\tvar digits = \"\"\n\tfor ch in iban:\n\t\tcase ch\n\t\t\tof '0'..'9': digits.add($(ch.ord - '0'.ord))\n\t\t\tof 'A'..'Z': digits.add($(ch.ord - 'A'.ord + 10))\n\t\t\telse: discard\n\tresult = initBigInt(digits) mod 97 == 1\n\nfor account in [\"GB82 WEST 1234 5698 7654 32\", \"GB82 TEST 1234 5698 7654 32\"]:\n\techo account, \" validation is: \", validIban account\n" + }, + { + "id": 977, + "length": 3085, + "source": "Rosetta Code", + "text": "import algorithm\nimport os\nimport strformat\nimport strutils\nimport tables\nimport std/sha1\nimport times\n\ntype\n\n\t# Mapping \"size\" -> \"list of paths\".\n\tPathsFromSizes = Table[BiggestInt, seq[string]]\n\n\t# Mapping \"hash\" -> \"list fo paths\".\n\tPathsFromHashes = Table[string, seq[string]]\n\n\t# Information data.\n\tInfo = tuple[size: BiggestInt; paths: seq[string]]\n\n\n\nproc processCmdLine(): tuple[dirpath: string; minsize: Natural] =\n\t## Process the command line. Extra parameters are ignored.\n\n\tif paramCount() == 0:\n\t\tquit fmt\"Usage: {getAppFileName().splitPath()[1]} folder minsize\"\n\n\tresult.dirpath = paramStr(1)\n\tif not result.dirpath.dirExists():\n\t\tquit fmt\"Wrong directory path: {result.dirpath}\"\n\n\tif paramCount() >= 2:\n\t\ttry:\n\t\t\tresult.minsize = parseInt(paramStr(2))\n\t\texcept ValueError:\n\t\t\tquit fmt\"Wrong minimum size: {paramStr(2)}\"\n\n\nproc initPathsFromSize(dirpath: string; minsize: Natural): PathsFromSizes =\n\t## Retrieve the files in directory \"dirpath\" with minimal size \"minsize\"\n\t## and build the mapping from size to paths.\n\n\tfor path in dirpath.walkDirRec():\n\t\tif not path.fileExists():\n\t\t\tcontinue # Not a regular file.\n\t\tlet size = path.getFileSize()\n\t\tif size >= minSize:\n\t\t\t# Store path in \"size to paths\" table.\n\t\t\tresult.mgetOrPut(size, @[]).add(path)\n\n\nproc initPathsFromHashes(pathsFromSizes: PathsFromSizes): PathsFromHashes =\n\t## Compute hashes for files whose size is not unique and build the mapping\n\t## from hash to paths.\n\n\tfor size, paths in pathsFromSizes.pairs:\n\t\tif paths.len > 1:\n\t\t\tfor path in paths:\n\t\t\t\t# Store path in \"digest to paths\" table.\n\t\t\t\tresult.mgetOrPut($path.secureHashFile(), @[]).add(path)\n\n\nproc cmp(x, y: Info): int =\n\t## Compare two information tuples. Used to sort the list of duplicates files.\n\n\tresult = cmp(x.size, y.size)\n\tif result == 0:\n\t\t# Same size. Compare the first paths (we are sure that they are different).\n\t\tresult = cmp(x.paths[0], y.paths[0])\n\n\nproc displayDuplicates(dirpath: string; pathsFromHashes: PathsFromHashes) =\n\t## Display duplicates files in directory \"dirpath\".\n\n\techo \"Files with same size and same SHA1 hash value in directory: \", dirpath\n\techo \"\"\n\n\t# Build list of duplicates.\n\tvar duplicates: seq[Info]\n\tfor paths in pathsFromHashes.values:\n\t\tif paths.len > 1:\n\t\t\tduplicates.add((paths[0].getFileSize(), sorted(paths)))\n\tif duplicates.len == 0:\n\t\techo \"No files\"\n\t\treturn\n\tduplicates.sort(cmp, Descending)\n\n\t# Display duplicates.\n\techo fmt\"\"\"{\"Size\":>10} {\"Last date modified\":^19} {\"Inode\":>8} HL File name\"\"\"\n\techo repeat('=', 80)\n\tfor (size, paths) in duplicates:\n\t\techo \"\"\n\t\tfor path in paths:\n\t\t\tlet mtime = path.getLastModificationTime().format(\"YYYY-MM-dd HH:mm:ss\")\n\t\t\tlet info = path.getFileInfo()\n\t\t\tlet inode = info.id.file\n\t\t\tlet hardlink = if info.linkCount == 1: \" \" else: \"*\"\n\t\t\techo fmt\"{size:>10} {mtime:>23} {inode:>12} {hardlink:<5} {path.relativePath(dirpath)}\"\n\n\n\nlet (dirpath, minsize) = processCmdLine()\nlet pathsFromSizes = initPathsFromSize(dirpath, minsize)\nlet pathsFromHashes = initPathsFromHashes(pathsFromSizes)\ndirpath.displayDuplicates(pathsFromHashes)\n" + }, + { + "id": 978, + "length": 1376, + "source": "Rosetta Code", + "text": "import math\n\ntype\n\tPoint = tuple[x, y: float]\n\tCircle = tuple[x, y, r: float]\n\nproc circles(p1, p2: Point, r: float): tuple[c1, c2: Circle] =\n\tif r == 0: raise newException(ValueError,\n\t\t\"radius of zero\")\n\tif p1 == p2: raise newException(ValueError,\n\t\t\"coincident points gives infinite number of Circles\")\n\n\t# delta x, delta y between points\n\tlet (dx, dy) = (p2.x - p1.x, p2.y - p1.y)\n\t# dist between points\n\tlet q = sqrt(dx*dx + dy*dy)\n\tif q > 2.0*r: raise newException(ValueError,\n\t\t\"separation of points > diameter\")\n\n\t# halfway point\n\tlet p3: Point = ((p1.x+p2.x)/2, (p1.y+p2.y)/2)\n\t# distance along the mirror line\n\tlet d = sqrt(r*r - (q/2)*(q/2))\n\t# One answer\n\tresult.c1 = (p3.x - d*dy/q, p3.y + d*dx/q, abs(r))\n\t# The other answer\n\tresult.c2 = (p3.x + d*dy/q, p3.y - d*dx/q, abs(r))\n\nconst tries: seq[tuple[p1, p2: Point, r: float]] =\n\t@[((0.1234, 0.9876), (0.8765, 0.2345), 2.0),\n\t\t((0.0000, 2.0000), (0.0000, 0.0000), 1.0),\n\t\t((0.1234, 0.9876), (0.1234, 0.9876), 2.0),\n\t\t((0.1234, 0.9876), (0.8765, 0.2345), 0.5),\n\t\t((0.1234, 0.9876), (0.1234, 0.9876), 0.0)]\n\nfor p1, p2, r in tries.items:\n\techo \"Through points:\"\n\techo \" \", p1\n\techo \" \", p2\n\techo \" and radius \", r\n\techo \"You can construct the following circles:\"\n\ttry:\n\t\tlet (c1, c2) = circles(p1, p2, r)\n\t\techo \" \", c1\n\t\techo \" \", c2\n\texcept ValueError:\n\t\techo \" ERROR: \", getCurrentExceptionMsg()\n\techo \"\"\n" + }, + { + "id": 979, + "length": 1739, + "source": "Rosetta Code", + "text": "const A = 1 # \"1\" is considered as as int, so this is the type of \"x\".\nconst B: float = 1 # Implicit conversion from int to float done by the compiler.\n\nvar x: uint = 1 # Implicit conversion from int to uint done by the compiler.\nvar y = 1f32 # \"y\" is a float32.\nvar z: float64 = y # The compiler generates code to convert from float32 to float64.\n\n# Tuple conversions.\n# Note that these conversions doesn't change the memory representation of the data.\n\nvar t1: tuple[a, b: int] # Named tuple.\nvar t2: tuple[c, d: int] # Named tuple, incompatible with the previous one.\nvar t3: (int, int) # Unnamed tuple.\n\nt3 = (1, 2) # No conversion here.\nt1 = t3 # Implicit conversion from unnamed to named.\nt2 = (int, int)(t1) # Explicit conversion followed by an implicit conversion.\nt3 = t2 # Implicit conversion from named to unnamed.\n\n# Simplifying operations with \"lenientops\".\nvar f1, f2, f3: float\nvar i1, i2, i3: int\n\nf1 = f2 + i1.toFloat * (f3 * i2.toFloat) + i3.toFloat\n\nimport lenientops\n\nf1 = f2 + i1 * (f3 * i2) + i3 # Looks like implicit conversions for the user.\n\n# Another example: / operator.\n# This operator is defined for float32 and float64 operands. But is also defined\n# for integer operands in \"system\" module. Actually, it simply converts the operands\n# to float and apply the float division. This is another example of overloading\n# hiding the conversions.\necho 1 / 2 # Displays 0.5.\n\n# Converter examples.\n# The following ones are absolutely not recommended as Nim is not C or Python.\nconverter toInt(b: bool): int = ord(b)\nconverter toBool(i: int): bool = i != 0\n\necho 1 + true # Displays 2.\nif 2: echo \"ok\" # Displays \"ok\".\n" + }, + { + "id": 980, + "length": 685, + "source": "Rosetta Code", + "text": "import strutils\n\n\nfunc decide(pc: openArray[char]): bool =\n\t## Terminate when first two characters of the\n\t## permutation are 'B' and 'C' respectively.\n\tpc[0] == 'B' and pc[1] == 'C'\n\n\nproc permute(values: openArray[char]; n: Positive) =\n\n\tlet k = values.len\n\tvar\n\t\tpn = newSeq[int](n)\n\t\tp = newSeq[char](n)\n\n\twhile true:\n\t\t# Generate permutation\n\t\tfor i, x in pn: p[i] = values[x]\n\t\t# Show progress.\n\t\techo p.join(\" \")\n\t\t# Pass to deciding function.\n\t\tif decide(p): return # Terminate early.\n\t\t# Increment permutation number.\n\t\tvar i = 0\n\t\twhile true:\n\t\t\tinc pn[i]\n\t\t\tif pn[i] < k: break\n\t\t\tpn[i] = 0\n\t\t\tinc i\n\t\t\tif i == n: return # All permutations generated.\n\n\npermute(\"ABCD\", 3)\n" + }, + { + "id": 981, + "length": 1180, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils\n\nproc levenshteinAlign(a, b: string): tuple[a, b: string] =\n\tlet a = a.toLower()\n\tlet b = b.toLower()\n\tvar costs = newSeqWith(a.len + 1, newSeq[int](b.len + 1))\n\tfor j in 0..b.len: costs[0][j] = j\n\tfor i in 1..a.len:\n\t\tcosts[i][0] = i\n\t\tfor j in 1..b.len:\n\t\t\tlet tmp = costs[i - 1][j - 1] + ord(a[i - 1] != b[j - 1])\n\t\t\tcosts[i][j] = min(1 + min(costs[i - 1][j], costs[i][j - 1]), tmp)\n\n\t# Walk back through matrix to figure out path.\n\tvar aPathRev, bPathRev: string\n\tvar i = a.len\n\tvar j = b.len\n\twhile i != 0 and j != 0:\n\t\tlet tmp = costs[i - 1][j - 1] + ord(a[i - 1] != b[j - 1])\n\t\tif costs[i][j] == tmp:\n\t\t\tdec i\n\t\t\tdec j\n\t\t\taPathRev.add a[i]\n\t\t\tbPathRev.add b[j]\n\t\telif costs[i][j] == 1 + costs[i-1][j]:\n\t\t\tdec i\n\t\t\taPathRev.add a[i]\n\t\t\tbPathRev.add '-'\n\t\telif costs[i][j] == 1 + costs[i][j-1]:\n\t\t\tdec j\n\t\t\taPathRev.add '-'\n\t\t\tbPathRev.add b[j]\n\t\telse:\n\t\t\tquit \"Internal error\"\n\n\tresult = (reversed(aPathRev).join(), reversed(bPathRev).join())\n\nwhen isMainModule:\n\n\tvar result = levenshteinAlign(\"place\", \"palace\")\n\techo result.a\n\techo result.b\n\techo \"\"\n\n\tresult = levenshteinAlign(\"arthur\",\"raisethysword\")\n\techo result.a\n\techo result.b\n" + }, + { + "id": 982, + "length": 4290, + "source": "Rosetta Code", + "text": "#[ AVL tree adapted from Julienne Walker's presentation at\n\t http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.\n\n\t Uses bounded recursive versions for insertion and deletion.\n]#\n\ntype\n\n\t# Objects strored in the tree must be comparable.\n\tComparable = concept x, y\n\t\t(x == y) is bool\n\t\t(x < y) is bool\n\n\t# Direction used to select a child.\n\tDirection = enum Left, Right\n\n\t# Description of the tree node.\n\tNode[T: Comparable] = ref object\n\t\tdata: T # Payload.\n\t\tbalance: range[-2..2] # Balance factor (bounded).\n\t\tlinks: array[Direction, Node[T]] # Children.\n\n\t# Description of a tree.\n\tAvlTree[T: Comparable] = object\n\t\troot: Node[T]\n\n\n\nfunc opp(dir: Direction): Direction {.inline.} =\n\t## Return the opposite of a direction.\n\tDirection(1 - ord(dir))\n\n\nfunc single(root: Node; dir: Direction): Node =\n\t## Single rotation.\n\n\tresult = root.links[opp(dir)]\n\troot.links[opp(dir)] = result.links[dir]\n\tresult.links[dir] = root\n\n\nfunc double(root: Node; dir: Direction): Node =\n\t## Double rotation.\n\n\tlet save = root.links[opp(dir)].links[dir]\n\n\troot.links[opp(dir)].links[dir] = save.links[opp(dir)]\n\tsave.links[opp(dir)] = root.links[opp(dir)]\n\troot.links[opp(dir)] = save\n\n\tresult = root.links[opp(dir)]\n\troot.links[opp(dir)] = result.links[dir]\n\tresult.links[dir] = root\n\n\nfunc adjustBalance(root: Node; dir: Direction; balance: int) =\n\t## Adjust balance factors after double rotation.\n\n\tlet node1 = root.links[dir]\n\tlet node2 = node1.links[opp(dir)]\n\n\tif node2.balance == 0:\n\t\troot.balance = 0\n\t\tnode1.balance = 0\n\n\telif node2.balance == balance:\n\t\troot.balance = -balance\n\t\tnode1.balance = 0\n\n\telse:\n\t\troot.balance = 0\n\t\tnode1.balance = balance\n\n\tnode2.balance = 0\n\n\nfunc insertBalance(root: Node; dir: Direction): Node =\n\t## Rebalancing after an insertion.\n\n\tlet node = root.links[dir]\n\tlet balance = 2 * ord(dir) - 1\n\n\tif node.balance == balance:\n\t\troot.balance = 0\n\t\tnode.balance = 0\n\t\tresult = root.single(opp(dir))\n\n\telse:\n\t\troot.adjustBalance(dir, balance)\n\t\tresult = root.double(opp(dir))\n\n\nfunc insertR(root: Node; data: root.T): tuple[node: Node, done: bool] =\n\t## Insert data (recursive way).\n\n\tif root.isNil:\n\t\treturn (Node(data: data), false)\n\n\tlet dir = if root.data < data: Right else: Left\n\tvar done: bool\n\t(root.links[dir], done) = root.links[dir].insertR(data)\n\tif done:\n\t\treturn (root, true)\n\n\tinc root.balance, 2 * ord(dir) - 1\n\tresult = case root.balance\n\t\t\t\t\t of 0: (root, true)\n\t\t\t\t\t of -1, 1: (root, false)\n\t\t\t\t\t else: (root.insertBalance(dir), true)\n\n\nfunc removeBalance(root: Node; dir: Direction): tuple[node: Node, done: bool] =\n\t## Rebalancing after a deletion.\n\n\tlet node = root.links[opp(dir)]\n\tlet balance = 2 * ord(dir) - 1\n\tif node.balance == -balance:\n\t\troot.balance = 0\n\t\tnode.balance = 0\n\t\tresult = (root.single(dir), false)\n\telif node.balance == balance:\n\t\troot.adjustBalance(opp(dir), -balance)\n\t\tresult = (root.double(dir), false)\n\telse:\n\t\troot.balance = -balance\n\t\tnode.balance = balance\n\t\tresult = (root.single(dir), true)\n\n\nfunc removeR(root: Node; data: root.T): tuple[node: Node, done: bool] =\n\t## Remove data (recursive way).\n\n\tif root.isNil:\n\t\treturn (nil, false)\n\n\tvar data = data\n\tif root.data == data:\n\t\tif root.links[Left].isNil:\n\t\t\treturn (root.links[Right], false)\n\t\tif root.links[Right].isNil:\n\t\t\treturn (root.links[Left], false)\n\t\tvar heir = root.links[Left]\n\t\twhile not heir.links[Right].isNil:\n\t\t\their = heir.links[Right]\n\t\troot.data = heir.data\n\t\tdata = heir.data\n\n\tlet dir = if root.data < data: Right else: Left\n\tvar done: bool\n\t(root.links[dir], done) = root.links[dir].removeR(data)\n\tif done:\n\t\treturn (root, true)\n\tdec root.balance, 2 * ord(dir) - 1\n\tresult = case root.balance\n\t\t\t\t\t of -1, 1: (root, true)\n\t\t\t\t\t of 0: (root, false)\n\t\t\t\t\t else: root.removeBalance(dir)\n\n\nfunc insert(tree: var AvlTree; data: tree.T) =\n\t## Insert data in an AVL tree.\n\ttree.root = tree.root.insertR(data).node\n\n\nfunc remove(tree: var AvlTree; data: tree.T) =\n\t## Remove data from an AVL tree.\n\ttree.root = tree.root.removeR(data).node\n\n\nimport json\n\nvar tree: AvlTree[int]\necho pretty(%tree)\n\necho \"Insert test:\"\ntree.insert(3)\ntree.insert(1)\ntree.insert(4)\ntree.insert(1)\ntree.insert(5)\necho pretty(%tree)\n\necho \"\"\necho \"Remove test:\"\ntree.remove(3)\ntree.remove(1)\necho pretty(%tree)\n" + }, + { + "id": 983, + "length": 1476, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\ntype\n\n\t# Non zero digit range.\n\tDigit = range[1..9]\n\n\t# Count array used to compute a distribution.\n\tCount = array[Digit, Natural]\n\n\t# Array to store frequencies.\n\tDistribution = array[Digit, float]\n\n\n# Fibonacci numbers generation.\n\nimport bignum\n\nproc fib(count: int): seq[Int] =\n\t## Build a sequence of \"count auccessive Finonacci numbers.\n\tresult.setLen(count)\n\tresult[0..1] = @[newInt(1), newInt(1)]\n\tfor i in 2..= 1000:\n\t\t\tif lastNum >= 100:\n\t\t\t\temitError(\"'{name}' is not a well formed numeric string\")\n\t\t\tmultiplier = num\n\t\t\tif i == 0: sum += multiplier\n\t\telif num >= 100:\n\t\t\tmultiplier *= 100\n\t\t\tif i == 0: sum += multiplier\n\t\telif num >= 20:\n\t\t\tif lastNum in 10u64..90u64:\n\t\t\t\temitError(\"'{name}' is not a well formed numeric string\")\n\t\t\tsum += num * multiplier\n\t\telse:\n\t\t\tif lastNum in 1u64..90u64:\n\t\t\t\temitError(\"'{name}' is not a well formed numeric string\")\n\t\t\tsum += num * multiplier\n\t\tlastNum = num\n\n\tif isNegative and sum == uint64(int64.high) + 1:\n\t\treturn int64.low\n\tif sum > uint64(int64.high):\n\t\temitError(\"'$name' is outside the range of a 64 bits integer\")\n\n\tresult = if isNegative: -int64(sum) else: int64(sum)\n\n\nwhen isMainModule:\n\tlet names = [\n\t\t\"none\",\n\t\t\"one\",\n\t\t\"twenty-five\",\n\t\t\"minus one hundred and seventeen\",\n\t\t\"hundred and fifty-six\",\n\t\t\"minus two thousand two\",\n\t\t\"nine thousand, seven hundred, one\",\n\t\t\"minus six hundred and twenty six thousand, eight hundred and fourteen\",\n\t\t\"four million, seven hundred thousand, three hundred and eighty-six\",\n\t\t\"fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four\",\n\t\t\"two hundred and one billion, twenty-one million, two thousand and one\",\n\t\t\"minus three hundred trillion, nine million, four hundred and one thousand and thirty-one\",\n\t\t\"seventeen quadrillion, one hundred thirty-seven\",\n\t\t\"a quintillion, eight trillion and five\",\n\t\t\"minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight\"]\n\nfor name in names:\n\techo ($nametoNum(name)).align(20), \" = \", name\n" + }, + { + "id": 986, + "length": 5359, + "source": "Rosetta Code", + "text": "import fenv, lists, math, sequtils, strformat, strutils\n\ntype\n\n\tShipment = object\n\t\tquantity: float\n\t\tcostPerUnit: float\n\t\tr, c: int\n\n\tTransport = object\n\t\tfilename: string\n\t\tsupply: seq[int]\n\t\tdemand: seq[int]\n\t\tcosts: seq[seq[float]]\n\t\tmatrix: seq[seq[Shipment]]\n\n\tShipmentList = DoublyLinkedList[Shipment]\n\nconst ShipZero = Shipment()\n\n\ntemplate emitError(msg: string) =\n\traise newException(ValueError, msg)\n\n\nproc initTransport(filename: string): Transport =\n\tlet infile = filename.open()\n\tlet fields = infile.readLine().splitWhitespace().map(parseInt)\n\tlet numSources = fields[0]\n\tlet numDests = fields[1]\n\tif numSources < 1 or numDests < 1:\n\t\temitError \"wrong number of sources or destinations.\"\n\tvar src = infile.readLine().splitWhitespace().map(parseInt)\n\tif src.len != numSources:\n\t\temitError \"wrong number of sources; got $1, expected $2.\".format(src.len, numSources)\n\tvar dst = infile.readLine().splitWhitespace().map(parseInt)\n\tif dst.len != numDests:\n\t\temitError \"wrong number of destinations; got $1, expected $2.\".format(dst.len, numDests)\n\n\t# Fix imbalance.\n\tlet totalSrc = sum(src)\n\tlet totalDst = sum(dst)\n\tlet diff = totalSrc - totalDst\n\tif diff > 0: dst.add diff\n\telif diff < 0: src.add -diff\n\n\tvar costs = newSeqWith(src.len, newSeq[float](dst.len))\n\tvar matrix = newSeqWith(src.len, newSeq[Shipment](dst.len))\n\n\tfor i in 0.. dst.len:\n\t\t\temitError \"wrong number of costs; got $1, expected $2.\".format(fields.len, numDests)\n\t\tfor j in 0.. 0:\n\t\t\t\ttr.matrix[r][c] = Shipment(quantity: quantity.toFloat, costPerUnit: tr.costs[r][c], r: r, c: c)\n\t\t\t\tdec tr.supply[r], quantity\n\t\t\t\tdec tr.demand[c], quantity\n\t\t\t\tif tr.supply[r] == 0:\n\t\t\t\t\tnorthWest = c\n\t\t\t\t\tbreak\n\n\nfunc getNeighbors(tr: Transport; s: Shipment; list: ShipmentList): array[2, Shipment] =\n\tfor o in list:\n\t\tif o != s:\n\t\t\tif o.r == s.r and result[0] == ShipZero:\n\t\t\t\tresult[0] = o\n\t\t\telif o.c == s.c and result[1] == ShipZero:\n\t\t\t\tresult[1] = o\n\t\t\tif result[0] != ShipZero and result[1] != ShipZero:\n\t\t\t\tbreak\n\n\nfunc matrixToList(tr: Transport): ShipmentList =\n\tfor m in tr.matrix:\n\t\tfor s in m:\n\t\t\tif s != ShipZero:\n\t\t\t\tresult.append(s)\n\n\nfunc getClosedPath(tr: Transport; s: Shipment): seq[Shipment] =\n\tvar path = tr.matrixToList\n\tpath.prepend(s)\n\n\t# Remove (and keep removing) elements that do not have a\n\t# vertical and horizontal neighbor.\n\twhile true:\n\t\tvar removals = 0\n\t\tfor e in path.nodes:\n\t\t\tlet nbrs = tr.getNeighbors(e.value, path)\n\t\t\tif nbrs[0] == ShipZero or nbrs[1] == ShipZero:\n\t\t\t\tpath.remove(e)\n\t\t\t\tinc removals\n\t\tif removals == 0:\n\t\t\tbreak\n\n\t# Place the remaining elements in the correct plus-minus order.\n\tvar prev = s\n\tvar i = 0\n\tfor _ in path:\n\t\tresult.add prev\n\t\tprev = tr.getNeighbors(prev, path)[i]\n\t\ti = 1 - i\n\n\nfunc fixDegenerateCase(tr: var Transport) =\n\tconst Eps = minimumPositiveValue(float)\n\tif tr.supply.len + tr.demand.len - 1 != tr.matrix.len * tr.matrix[0].len:\n\t\tfor r in 0..tr.supply.high:\n\t\t\tfor c in 0..tr.demand.high:\n\t\t\t\tif tr.matrix[r][c] == ShipZero:\n\t\t\t\t\tlet dummy = Shipment(quantity: Eps, costPerUnit: tr.costs[r][c], r: r, c: c)\n\t\t\t\t\tif tr.getClosedPath(dummy).len == 0:\n\t\t\t\t\t\ttr.matrix[r][c] = dummy\n\t\t\t\t\t\treturn\n\n\nfunc steppingStone(tr: var Transport) =\n\tvar maxReduction = 0.0\n\tvar move: seq[Shipment]\n\tvar leaving = ShipZero\n\ttr.fixDegenerateCase()\n\n\tfor r in 0..tr.supply.high:\n\t\tfor c in 0..tr.demand.high:\n\t\t\tif tr.matrix[r][c] != ShipZero:\n\t\t\t\tcontinue\n\t\t\tlet trial = Shipment(quantity: 0, costPerUnit: tr.costs[r][c], r: r, c: c)\n\t\t\tvar path = tr.getClosedPath(trial)\n\t\t\tvar reduction = 0.0\n\t\t\tvar lowestQuantity = float(int32.high)\n\t\t\tvar leavingCandidate = ShipZero\n\t\t\tvar plus = true\n\t\t\tfor s in path:\n\t\t\t\tif plus:\n\t\t\t\t\treduction += s.costPerUnit\n\t\t\t\telse:\n\t\t\t\t\treduction -= s.costPerUnit\n\t\t\t\t\tif s.quantity < lowestQuantity:\n\t\t\t\t\t\tleavingCandidate = s\n\t\t\t\t\t\tlowestQuantity = s.quantity\n\t\t\t\tplus = not plus\n\t\t\tif reduction < maxReduction:\n\t\t\t\tmove = move(path)\n\t\t\t\tleaving = leavingCandidate\n\t\t\t\tmaxReduction = reduction\n\n\tif move.len != 0:\n\t\tlet q = leaving.quantity\n\t\tvar plus = true\n\t\tfor s in move.mitems:\n\t\t\tif plus: s.quantity += q\n\t\t\telse: s.quantity -= q\n\t\t\ttr.matrix[s.r][s.c] = if s.quantity == 0: ShipZero else: s\n\t\t\tplus = not plus\n\t\ttr.steppingStone()\n\n\nproc printResult(tr: Transport) =\n\techo tr.filename, '\\n'\n\tstdout.write tr.filename.readFile()\n\techo \"\\nOptimal solution for \", tr.filename, '\\n'\n\tvar totalCosts = 0.0\n\tfor r in 0..tr.supply.high:\n\t\tfor c in 0..tr.demand.high:\n\t\t\tlet s = tr.matrix[r][c]\n\t\t\tif s != ShipZero and s.r == r and s.c == c:\n\t\t\t\tstdout.write \" {int(s.quantity):3} \"\n\t\t\t\ttotalCosts += s.quantity * s.costPerUnit\n\t\t\telse:\n\t\t\t\tstdout.write \" - \"\n\t\techo()\n\techo \"\\nTotal costs: {totalCosts:g}\\n\"\n\n\nwhen isMainModule:\n\n\tconst Filenames = [\"input1.txt\", \"input2.txt\", \"input3.txt\"]\n\tfor filename in Filenames:\n\t\tvar tr = initTransport(filename)\n\t\ttr.northWestCornerRule()\n\t\ttr.steppingStone()\n\t\ttr.printResult()\n" + }, + { + "id": 987, + "length": 970, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat\n\nproc equalBirthdays(nSharers, groupSize, nRepetitions: int): float =\n\trandomize(1)\n\tvar eq = 0\n\tfor _ in 1..nRepetitions:\n\t\tvar group: array[1..365, int]\n\t\tfor _ in 1..groupSize:\n\t\t\tinc group[rand(1..group.len)]\n\t\teq += ord(group.anyIt(it >= nSharers))\n\tresult = eq * 100 / nRepetitions\n\nproc main() =\n\n\tvar groupEst = 2\n\tfor sharers in 2..5:\n\n\t\t# Coarse.\n\t\tvar groupSize = groupEst + 1\n\t\twhile equalBirthdays(sharers, groupSize, 100) < 50:\n\t\t\tinc groupSize\n\n\t\t# Finer.\n\t\tlet inf = (groupSize.toFloat - (groupSize - groupEst) / 4).toInt()\n\t\tfor gs in inf..(groupSize+998):\n\t\t\tlet eq = equalBirthdays(sharers, groupSize, 250)\n\t\t\tif eq > 50:\n\t\t\t\tgroupSize = gs\n\t\t\t\tbreak\n\n\t\t# Finest.\n\t\tfor gs in (groupSize-1)..(groupSize+998):\n\t\t\tlet eq = equalBirthdays(sharers, gs, 50_000)\n\t\t\tif eq > 50:\n\t\t\t\tgroupEst = gs\n\t\t\t\techo \"{sharers} independent people in a group of {gs:3} \",\n\t\t\t\t\t\t \"share a common birthday ({eq:4.1f}%)\"\n\t\t\t\tbreak\n\nmain()\n" + }, + { + "id": 988, + "length": 2486, + "source": "Rosetta Code", + "text": "import stats, strformat\n\ntype Rule = proc(x, y: float): float\n\nconst Dxs = [-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n\t\t\t\t\t\t\t1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n\t\t\t\t\t\t -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n\t\t\t\t\t\t\t0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n\t\t\t\t\t\t -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n\t\t\t\t\t\t -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n\t\t\t\t\t\t\t0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n\t\t\t\t\t\t -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n\t\t\t\t\t\t\t0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n\t\t\t\t\t\t -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n\t\t\t\t\t\t\t0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n\t\t\t\t\t\t\t0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n\t\t\t\t\t\t\t0.443, -0.521, -0.799, 0.087]\n\nconst Dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n\t\t\t\t\t\t\t0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n\t\t\t\t\t\t\t0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n\t\t\t\t\t\t\t0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n\t\t\t\t\t\t -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n\t\t\t\t\t\t\t0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n\t\t\t\t\t\t\t0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n\t\t\t\t\t\t\t1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n\t\t\t\t\t\t -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n\t\t\t\t\t\t\t0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n\t\t\t\t\t\t -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n\t\t\t\t\t\t\t1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n\t\t\t\t\t\t -0.947, -1.424, -0.542, -1.032]\n\nfunc funnel(a: openArray[float]; rule: Rule): seq[float] =\n\tvar x = 0.0\n\tresult.setlen(a.len)\n\tfor i, val in a:\n\t\tresult[i] = x + val\n\t\tx = rule(x, val)\n\nproc experiment(label: string; r: Rule) =\n\tlet rxs = funnel(Dxs, r)\n\tlet rys = funnel(Dys, r)\n\techo label\n\techo fmt\"Mean x, y : {rxs.mean:7.4f} {rys.mean:7.4f}\"\n\techo fmt\"Std dev x, y : {rxs.standardDeviation:7.4f} {rys.standardDeviation:7.4f}\"\n\techo \"\"\n\nexperiment(\"Rule 1\", proc(z, dz: float): float = 0.0)\n\nexperiment(\"Rule 2\", proc(z, dz: float): float = -dz)\n\nexperiment(\"Rule 3\", proc(z, dz: float): float = -(z + dz))\n\nexperiment(\"Rule 4\", proc(z, dz: float): float = z + dz)\n" + }, + { + "id": 989, + "length": 1258, + "source": "Rosetta Code", + "text": "import imageman\n\nfunc lerp(s, e, t: float): float =\n\ts + (e - s) * t\n\nfunc blerp(c00, c10, c01, c11, tx, ty: float): float =\n\tlerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty)\n\nfunc scale(img: Image; scaleX, scaleY: float): Image =\n\tlet newWidth = (img.width.toFloat * scaleX).toInt\n\tlet newHeight = (img.height.toFloat * scaleY).toInt\n\tresult = initImage[ColorRGBU](newWidth, newHeight)\n\tfor x in 0.. 0: input[0].toLowerAscii else: '0'\n\t\tif ch notin \"123abc\":\n\t\t\techo \"Must be 1, 2, 3, a, b or c\"\n\t\t\tcontinue\n\t\tif ch in '1'..'3':\n\t\t\tn = ord(ch) - ord('1')\n\t\telse:\n\t\t\tisRow = false\n\t\t\tn = ord(ch) - ord('a')\n\n\t# Update board.\n\tinc flips\n\tif isRow: board.flipRow(n) else: board.flipCol(n)\n\ttarget.print(\"\\nTARGET\")\n\tlet plural = if flips == 1: \"\" else: \"S\"\n\tboard.print(\"BOARD AFTER {flips} FLIP{plural}\")\n\nlet plural = if flips == 1: \"\" else: \"s\"\necho \"You've succeeded in {flips} flip{plural}\"\n" + }, + { + "id": 992, + "length": 703, + "source": "Rosetta Code", + "text": "import math, strformat, strutils\n\n\nfunc entropy(str: string): float =\n\t## return the entropy of a fibword string.\n\tif str.len <= 1: return 0.0\n\tlet strlen = str.len.toFloat\n\tlet count0 = str.count('0').toFloat\n\tlet count1 = strlen - count0\n\tresult = -(count0 / strlen * log2(count0 / strlen) + count1 / strlen * log2(count1 / strlen))\n\n\niterator fibword(): string =\n\t## Yield the successive fibwords.\n\tvar a = \"1\"\n\tvar b = \"0\"\n\tyield a\n\tyield b\n\twhile true:\n\t\ta = b & a\n\t\tswap a, b\n\t\tyield b\n\n\nwhen isMainModule:\n\techo \" n length entropy\"\n\techo \"--------------------------------\"\n\tvar n = 0\n\tfor str in fibword():\n\t\tinc n\n\t\techo fmt\"{n:2} {str.len:8} {entropy(str):.16f}\"\n\t\tif n == 37: break\n" + }, + { + "id": 993, + "length": 794, + "source": "Rosetta Code", + "text": "import imageman\n\nconst\n\tWidth = 1000\n\tHeight = 1000\n\tLineColor = ColorRGBU [byte 64, 192, 96]\n\tOutput = \"fibword.png\"\n\n\nproc fibword(n: int): string =\n\t## Return the nth fibword.\n\tvar a = \"1\"\n\tresult = \"0\"\n\tfor _ in 1..n:\n\t\ta = result & a\n\t\tswap a, result\n\n\nproc drawFractal(image: var Image; fw: string) =\n\t# Draw the fractal.\n\tvar\n\t\tx = 0\n\t\ty = image.h - 1\n\t\tdx = 1\n\t\tdy = 0\n\n\tfor i, ch in fw:\n\t\tlet (nextx, nexty) = (x + dx, y + dy)\n\t\timage.drawLine((x, y), (nextx, nexty), LineColor)\n\t\t(x, y) = (nextx, nexty)\n\t\tif ch == '0':\n\t\t\tif (i and 1) == 0:\n\t\t\t\t(dx, dy) = (dy, -dx)\n\t\t\telse:\n\t\t\t\t(dx, dy) = (-dy, dx)\n\n\n\nvar image = initImage[ColorRGBU](Width, Height)\nimage.fill(ColorRGBU [byte 0, 0, 0])\nimage.drawFractal(fibword(23))\n\n# Save into a PNG file.\nimage.savePNG(Output, compression = 9)\n" + }, + { + "id": 994, + "length": 663, + "source": "Rosetta Code", + "text": "# A slice just contains the first and last value\nlet alpha: Slice[char] = 'a'..'z'\necho alpha # (a: a, b: z)\n\n# but can be used to check if a character is in it:\necho 'f' in alpha # true\necho 'G' in alpha # false\n\n# A set contains all elements as a bitvector:\nlet alphaSet: set[char] = {'a'..'z'}\necho alphaSet # {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z}\necho 'f' in alphaSet # true\nvar someChars = {'a','f','g'}\necho someChars <= alphaSet # true\n\nimport sequtils\n# A sequence:\nlet alphaSeq = toSeq 'a'..'z'\necho alphaSeq # @[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]\necho alphaSeq[10] # k\n" + }, + { + "id": 995, + "length": 1595, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat\n\nconst\n\tN = 15\n\tT = 5\n\tP = 0.5\n\tNotClustered = 1\n\tCell2Char = \" #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tNRange = [4, 64, 256, 1024, 4096]\n\ntype Grid = seq[seq[int]]\n\n\nproc newGrid(n: Positive; p: float): Grid =\n\tresult = newSeqWith(n, newSeq[int](n))\n\tfor row in result.mitems:\n\t\tfor cell in row.mitems:\n\t\t\tif rand(1.0) < p: cell = 1\n\n\nfunc walkMaze(grid: var Grid; m, n, idx: int) =\n\tgrid[n][m] = idx\n\tif n < grid.high and grid[n + 1][m] == NotClustered:\n\t\tgrid.walkMaze(m, n + 1, idx)\n\tif m < grid[0].high and grid[n][m + 1] == NotClustered:\n\t\tgrid.walkMaze(m + 1, n, idx)\n\tif m > 0 and grid[n][m - 1] == NotClustered:\n\t\tgrid.walkMaze(m - 1, n, idx)\n\tif n > 0 and grid[n - 1][m] == NotClustered:\n\t\tgrid.walkMaze(m, n - 1, idx)\n\n\nfunc clusterCount(grid: var Grid): int =\n\tvar walkIndex = 1\n\tfor n in 0..grid.high:\n\t\tfor m in 0..grid[0].high:\n\t\t\tif grid[n][m] == NotClustered:\n\t\t\t\tinc walkIndex\n\t\t\t\tgrid.walkMaze(m, n, walkIndex)\n\tresult = walkIndex - 1\n\n\nproc clusterDensity(n: int; p: float): float =\n\tvar grid = newGrid(n, p)\n\tresult = grid.clusterCount() / (n * n)\n\n\nproc print(grid: Grid) =\n\tfor n, row in grid:\n\t\tstdout.write n mod 10, \") \"\n\t\tfor cell in row:\n\t\t\tstdout.write ' ', Cell2Char[cell]\n\t\tstdout.write '\\n'\n\n\nwhen isMainModule:\n\n\trandomize()\n\n\tvar grid = newGrid(N, 0.5)\n\techo \"Found {grid.clusterCount()} clusters in this {N} by {N} grid\\n\"\n\tgrid.print()\n\techo \"\"\n\n\tfor n in NRange:\n\t\tvar sum = 0.0\n\t\tfor _ in 1..T:\n\t\t\tsum += clusterDensity(n, P)\n\t\tlet sim = sum / T\n\t\techo \"t = {T} p = {P:4.2f} n = {n:4} sim = {sim:7.5f}\"\n" + }, + { + "id": 996, + "length": 898, + "source": "Rosetta Code", + "text": "import std/decls\n\nfunc patienceSort[T](a: var openArray[T]) =\n\n\tif a.len < 2: return\n\n\tvar piles: seq[seq[T]]\n\n\tfor elem in a:\n\t\tblock processElem:\n\t\t\tfor pile in piles.mitems:\n\t\t\t\tif pile[^1] > elem:\n\t\t\t\t\tpile.add(elem)\n\t\t\t\t\tbreak processElem\n\t\t\tpiles.add(@[elem])\n\n\tfor i in 0..a.high:\n\t\tvar min = piles[0][^1]\n\t\tvar minPileIndex = 0\n\t\tfor j in 1..piles.high:\n\t\t\tif piles[j][^1] < min:\n\t\t\t\tmin = piles[j][^1]\n\t\t\t\tminPileIndex = j\n\n\t\ta[i] = min\n\t\tvar minPile {.byAddr.} = piles[minPileIndex]\n\t\tminPile.setLen(minpile.len - 1)\n\t\tif minPile.len == 0: piles.delete(minPileIndex)\n\n\nwhen isMainModule:\n\n\tvar iArray = [4, 65, 2, -31, 0, 99, 83, 782, 1]\n\tiArray.patienceSort()\n\techo iArray\n\tvar cArray = ['n', 'o', 'n', 'z', 'e', 'r', 'o', 's', 'u','m']\n\tcArray.patienceSort()\n\techo cArray\n\tvar sArray = [\"dog\", \"cow\", \"cat\", \"ape\", \"ant\", \"man\", \"pig\", \"ass\", \"gnu\"]\n\tsArray.patienceSort()\n\techo sArray\n" + }, + { + "id": 997, + "length": 1974, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\nvar\n\tsupply = [50, 60, 50, 50]\n\tdemand = [30, 20, 70, 30, 60]\n\nlet\n\tcosts = [[16, 16, 13, 22, 17],\n\t\t\t\t\t [14, 14, 13, 19, 15],\n\t\t\t\t\t [19, 19, 20, 23, 50],\n\t\t\t\t\t [50, 12, 50, 15, 11]]\n\n\tnRows = supply.len\n\tnCols = demand.len\n\nvar\n\trowDone = newSeq[bool](nRows)\n\tcolDone = newSeq[bool](nCols)\n\tresults = newSeqWith(nRows, newSeq[int](nCols))\n\n\nproc diff(j, len: int; isRow: bool): array[3, int] =\n\tvar min1, min2 = int.high\n\tvar minP = -1\n\tfor i in 0.. md:\n\t\t\tmd = res[0] # max diff\n\t\t\tpm = i # pos of max diff\n\t\t\tmc = res[1] # min cost\n\t\t\tpc = res[2] # pos of min cost\n\tresult = if isRow: [pm, pc, mc, md] else: [pc, pm, mc, md]\n\n\nproc nextCell(): array[4, int] =\n\tlet res1 = maxPenalty(nRows, nCols, true)\n\tlet res2 = maxPenalty(nCols, nRows, false)\n\tif res1[3] == res2[3]:\n\t\treturn if res1[2] < res2[2]: res1 else: res2\n\tresult = if res1[3] > res2[3]: res2 else: res1\n\n\nwhen isMainModule:\n\n\tvar supplyLeft = sum(supply)\n\tvar totalCost = 0\n\n\twhile supplyLeft > 0:\n\t\tlet cell = nextCell()\n\t\tlet r = cell[0]\n\t\tlet c = cell[1]\n\t\tlet q = min(demand[c], supply[r])\n\t\tdec demand[c], q\n\t\tif demand[c] == 0: colDone[c] = true\n\t\tdec supply[r], q\n\t\tif supply[r] == 0: rowDone[r] = true\n\t\tresults[r][c] = q\n\t\tdec supplyLeft, q\n\t\tinc totalCost, q * costs[r][c]\n\n\techo \" A B C D E\"\n\tfor i, result in results:\n\t\tstdout.write chr(i + ord('W'))\n\t\tfor item in result:\n\t\t\tstdout.write \" \", ($item).align(2)\n\t\techo()\n\techo \"\\nTotal cost = \", totalCost\n" + }, + { + "id": 998, + "length": 2693, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\ntype\n\tBit = 0..1\n\tBitMatrix = seq[seq[Bit]] # Two-dimensional array of 0/1.\n\tNeighbors = array[2..9, Bit] # Neighbor values.\n\nconst Symbols = [Bit(0): '.', Bit(1): '#']\n\n\nfunc toBitMatrix(s: openArray[string]): BitMatrix =\n\t## Convert an array of 01 strings into a BitMatrix.\n\tfor row in s:\n\t\tassert row.allCharsInSet({'0', '1'})\n\t\tresult.add row.mapIt(Bit(ord(it) - ord('0')))\n\n\nproc `$`(m: BitMatrix): string =\n\t## Return the string representation of a BitMatrix.\n\tfor row in m:\n\t\techo row.mapIt(Symbols[it]).join()\n\n# Templates to allow using double indexing.\ntemplate `[]`(m: BitMatrix; i, j: Natural): Bit = m[i][j]\ntemplate `[]=`(m: var BitMatrix; i, j: Natural; val: Bit) = m[i][j] = val\n\n\nfunc neighbors(m: BitMatrix; i, j: int): Neighbors =\n\t## Return the array of neighbors.\n\t[m[i-1, j], m[i-1, j+1], m[i, j+1], m[i+1, j+1],\n\t m[i+1, j], m[i+1, j-1], m[i, j-1], m[i-1, j-1]]\n\nfunc transitions(p: Neighbors): int =\n\t## Return the numbers of transitions from P2 to P9.\n\tfor (i, j) in [(2, 3), (3, 4), (4, 5), (5, 6),\n\t\t\t\t\t\t\t\t (6, 7), (7, 8), (8, 9), (9, 2)]:\n\t\tresult += ord(p[i] == 0 and p[j] == 1)\n\nfunc thinned(m: BitMatrix): BitMatrix =\n\t## Return a thinned version of \"m\".\n\tconst Pair1 = [2, 8]\n\tconst Pair2 = [4, 6]\n\tlet rowMax = m.high\n\tlet colMax = m[0].high\n\tresult = m\n\n\twhile true:\n\t\tvar changed = false\n\n\t\tfor step in 1..2:\n\t\t\tlet (p1, p2) = if step == 1: (Pair1, Pair2) else: (Pair2, Pair1)\n\t\t\tvar m = result\n\t\t\tfor i in 1..= 0), \"Expected non negative values.\"\n\tlet posList = valList.distribute(valList.len div 4)\n\tresult = posList.mapIt((ff: it[0], lf: it[1], tab: it[2], sp: it[3]))\n\n\nproc decode(filename: string; uiList: seq[Position]): string =\n\n\tfunc decode(text: string; ui: Position): Option[char] =\n\t\tvar f, l, t, s = 0\n\t\tlet (ff, lf, tab, sp) = ui\n\t\tfor c in text:\n\t\t\tif f == ff and l == lf and t == tab and s == sp:\n\t\t\t\treturn if c == '!': none(char) else: some(c)\n\t\t\tcase c\n\t\t\tof '\\f': inc f; l = 0; t = 0; s = 0\n\t\t\tof '\\l': inc l; t = 0; s = 0\n\t\t\tof '\\t': inc t; s = 0\n\t\t\telse: inc s\n\n\tlet text = filename.readFile()\n\tfor ui in uiList:\n\t\tlet c = text.decode(ui)\n\t\tif c.isNone: break\n\t\tresult.add c.get()\n\nconst UiList = buildUserInput(\"0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 \" &\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 \" &\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 \" &\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"33 0 50 0 46 0 54 0 76 0 47 0 84 2 28\")\n\necho \"theRaven.txt\".decode(UiList)\n" + }, + { + "id": 1002, + "length": 735, + "source": "Rosetta Code", + "text": "import strutils, algorithm\n\nconst\n\tGifts = [\"A partridge in a pear tree.\",\n\t\t\t\t\t \"Two turtle doves\",\n\t\t\t\t\t \"Three french hens\",\n\t\t\t\t\t \"Four calling birds\",\n\t\t\t\t\t \"Five golden rings\",\n\t\t\t\t\t \"Six geese a-laying\",\n\t\t\t\t\t \"Seven swans a-swimming\",\n\t\t\t\t\t \"Eight maids a-milking\",\n\t\t\t\t\t \"Nine ladies dancing\",\n\t\t\t\t\t \"Ten lords a-leaping\",\n\t\t\t\t\t \"Eleven pipers piping\",\n\t\t\t\t\t \"Twelve drummers drumming\"]\n\n\tDays = [\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\",\n\t\t\t\t\t\"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\"]\n\nfor n, day in Days:\n\tvar g = reversed(Gifts[0..n])\n\techo \"\\nOn the \", day, \" day of Christmas\\nMy true love gave to me:\\n\",\n\t\t\t g[0..^2].join(\"\\n\"), if n > 0: \" and\\n\" & g[^1] else: capitalizeAscii(g[^1])\n" + }, + { + "id": 1003, + "length": 592, + "source": "Rosetta Code", + "text": "import posix\n\nlet MAP_ANONYMOUS {.importc: \"MAP_ANONYMOUS\", header: \"\".}: cint\n\nproc test(a, b: cint): cint =\n\t# mov EAX, [ESP+4]\n\t# add EAX, [ESP+8]\n\t# ret\n\tvar code = [0x8B'u8, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]\n\n\t# create an executable buffer\n\tvar buf = mmap(nil, sizeof(code), PROT_READ or PROT_WRITE or PROT_EXEC,\n\t\tMAP_PRIVATE or MAP_ANONYMOUS, -1, 0)\n\n\t# copy code to the buffer\n\tcopyMem(buf, addr code[0], sizeof(code))\n\t# run code\n\tresult = cast[proc(a, b: cint): cint {.nimcall.}](buf)(a, b)\n\t# free buffer\n\tdiscard munmap(buf, sizeof(code))\n\necho test(7, 12)\n" + }, + { + "id": 1004, + "length": 673, + "source": "Rosetta Code", + "text": "import strformat\nimport bignum\n\nlet ln2 = newInt(\"693147180559945309417232121458\") / newInt(\"1000000000000000000000000000000\")\n\niterator hickerson(): tuple[n: int; val: Rat] =\n\t## Yield the hickerson series values as rational numbers.\n\tvar\n\t\tn = 1\n\t\tnum = 1\n\t\tdenom = 2 * ln2 * ln2\n\twhile true:\n\t\tyield (n, num / denom)\n\t\tinc n\n\t\tnum *= n\n\t\tdenom *= ln2\n\nfunc fract(r: Rat): float =\n\t## Return the fractional part of rational \"r\".\n\t((r.num mod r.denom) / r.denom).toFloat\n\nfor i, val in hickerson():\n\tlet f = val.fract\n\tlet s = if int(10 * f) in {0, 9}: \"\" else: \"not \"\n\techo \"Fractional part of h({i}) is {f:.5f}..., so h({i}) is {s}nearly an integer.\"\n\tif i == 17: break\n" + }, + { + "id": 1005, + "length": 2529, + "source": "Rosetta Code", + "text": "import strutils\nimport bignum\n\ntype Currency = Int\n\n\nfunc currency(units, subunits: int): Currency =\n\t## Build a currency from units and subunits.\n\t## Units may be negative. Subunits must be in range 0..99.\n\tif subunits notin 0..99:\n\t\traise newException(ValueError, \"wrong value for subunits\")\n\tresult = if units >= 0: newInt(units * 100 + subunits)\n\t\t\t\t\t else: newInt(subunits * 100 - subunits)\n\n\nfunc currency(value: string): Currency =\n\t## Build a currency from a string.\n\t## Negative values are allowed. At most two digits are allowed for subunits.\n\n\tconst StartingChars = Digits + {'-'}\n\tif value.len == 0 or value[0] notin StartingChars:\n\t\traise newException(ValueError, \"wrong currency string\")\n\n\t# process sign and units.\n\tvar units = newInt(0)\n\tvar subunits = 0\n\tlet sign = if value[0] == '-': -1 else: 1\n\tvar idx = if sign == 1: 0 else: 1\n\twhile idx < value.len:\n\t\tif value[idx] notin Digits: break\n\t\tunits = 10 * units + ord(value[idx]) - ord('0')\n\t\tinc idx\n\n\t# Process separator.\n\tif idx <= value.high:\n\t\tif value[idx] != '.':\n\t\t\traise newException(ValueError, \"expected a separator\")\n\t\tinc idx\n\n\t# Process subunits.\n\tfor _ in 0..1:\n\t\tlet c = if idx >= value.len: '0' else: value[idx]\n\t\tif c notin Digits:\n\t\t\traise newException(ValueError, \"wrong value for subunits\")\n\t\tsubunits = 10 * subunits + ord(c) - ord('0')\n\t\tinc idx\n\n\tif idx <= value.high:\n\t\traise newException(ValueError, \"extra characters after subunits digits\")\n\n\tresult = sign * (units * 100 + subunits)\n\n\nfunc `//`(a, b: int): Rat =\n\t## Create a rational value.\n\tnewRat(a, b)\n\n\nfunc percentage(a: Currency; p: Rat): Currency =\n\t## Compute a percentage on currency value \"a\".\n\t## Returned value is rounded to nearest integer.\n\n\t(a * p.num * 10 div p.denom + 5) div 10\n\n\nfunc `$`(a: Currency): string =\n\t## Build a string representation of a currency value.\n\n\tresult = bignum.`$`(a div 100) & '.' & ($(a mod 100).toInt).align(2, '0')\n\n\nlet hamburgers = currency(5, 50) * int 4_000_000_000_000_000\nlet milkshakes = currency(\"2.86\") * 2\nlet rate = 765 // 10_000\nlet beforeTax = hamburgers + milkshakes\nlet tax = beforeTax.percentage(rate)\nlet total = beforeTax + tax\n\n# Find the maximum length of numerical value representations.\nlet beforeTaxStr = $beforeTax\nlet taxStr = $tax\nlet totalStr = $total\nlet length = max([beforeTaxStr.len, taxStr.len, totalStr.len])\n\n# Display the results.\necho \"Total price before tax: \", beforeTaxStr.align(length)\necho \"Tax: \", taxStr.align(length)\necho \"Total with tax: \", totalStr.align(length)\n" + }, + { + "id": 1006, + "length": 830, + "source": "Rosetta Code", + "text": "import std / strutils\n\nfunc canMakeWord(blocks: seq[string]; word: string): bool =\n\t\tif blocks.len < word.len: return false\n\t\tif word.len == 0: return true\n\n\t\tlet ch = word[0].toUpperAscii\n\t\tfor i, pair in blocks:\n\t\t\t\tif ch in pair and\n\t\t\t\t\t (blocks[0.. 0:\n\t\t\t\tresult.add('.')\n\t\t\tresult.add($val)\n\t\t\tif exp > 1:\n\t\t\t\tresult.add('^')\n\t\t\t\tresult.add($exp)\n\nproc run(fractString: string; init: int; maxSteps = 0) =\n\t## Run a Fractran program.\n\n\tvar prog = newProg(fractString, init)\n\n\tvar stepCount = 0\n\twhile stepCount < maxSteps:\n\t\tif not prog.doOneStep():\n\t\t\techo \"*** No more possible fraction. Program stopped.\"\n\t\t\treturn\n\t\tinc stepCount\n\t\techo stepCount, \": \", prog\n\nproc findPrimes(maxCount: int) =\n\t## Search and print primes.\n\n\tvar prog = newProg(PrimeProg, 2)\n\tlet oddPrimes = prog.primes[1..^1]\n\tvar primeCount = 0\n\twhile primeCount < maxCount:\n\t\tdiscard prog.doOneStep()\n\t\tblock powerOf2:\n\t\t\tif prog.exponents[2] > 0:\n\t\t\t\tfor p in oddPrimes:\n\t\t\t\t\tif prog.exponents[p] != 0:\n\t\t\t\t\t\t# Not a power of 2.\n\t\t\t\t\t\tbreak powerOf2\n\t\t\t\tinc primeCount\n\t\t\t\techo primeCount, \": \", prog.exponents[2]\n\necho \"First ten steps for program to find primes:\"\nrun(PrimeProg, 2, 10)\necho \"\\nFirst twenty prime numbers:\"\nfindPrimes(20)\n" + }, + { + "id": 1009, + "length": 1120, + "source": "Rosetta Code", + "text": "proc expandBraces(str: string) =\n\n\tvar\n\t\tescaped = false\n\t\tdepth = 0\n\t\tbracePoints: seq[int]\n\t\tbracesToParse: seq[int]\n\n\tfor idx, ch in str:\n\t\tcase ch\n\t\tof '\\\\':\n\t\t\tescaped = not escaped\n\t\tof '{':\n\t\t\tinc depth\n\t\t\tif not escaped and depth == 1:\n\t\t\t\tbracePoints = @[idx]\n\t\tof ',':\n\t\t\tif not escaped and depth == 1:\n\t\t\t\tbracePoints &= idx\n\t\tof '}':\n\t\t\tif not escaped and depth == 1 and bracePoints.len >= 2:\n\t\t\t\tbracesToParse = bracePoints & idx\n\t\t\tdec depth\n\t\telse:\n\t\t\tdiscard\n\t\tif ch != '\\\\':\n\t\t\tescaped = false\n\n\tif bracesToParse.len > 0:\n\t\tlet prefix = str[0.. 0.0:\n\t\tlet r = d * 2\n\t\tif r >= 1:\n\t\t\tresult.add '1'\n\t\t\td = r - 1\n\t\telse:\n\t\t\tresult.add '0'\n\t\t\td = r\n\nfunc binToDec(s: string): float =\n\tlet num = fromBin[int](s.replace(\".\", \"\"))\n\tlet den = fromBin[int]('1' & s.split('.')[1].replace('1', '0'))\n\tresult = num / den\n\nwhen isMainModule:\n\n\tlet d = 23.34375\n\techo d, \" -> \", decToBin(d)\n\tlet s = \"1011.11101\"\n\techo s, \" -> \", binToDec(s)\n" + }, + { + "id": 1011, + "length": 939, + "source": "Rosetta Code", + "text": "import sequtils, strutils, sugar\n\nproc solve(tri: seq[seq[int]]): int =\n\tvar tri = tri\n\twhile tri.len > 1:\n\t\tlet t0 = tri.pop\n\t\tfor i, t in tri[tri.high]: tri[tri.high][i] = max(t0[i], t0[i+1]) + t\n\ttri[0][0]\n\nconst data = \"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t55\n\t\t\t\t\t\t\t\t\t\t\t\t94 48\n\t\t\t\t\t\t\t\t\t\t\t 95 30 96\n\t\t\t\t\t\t\t\t\t\t 77 71 26 67\n\t\t\t\t\t\t\t\t\t\t97 13 76 38 45\n\t\t\t\t\t\t\t\t\t07 36 79 16 37 68\n\t\t\t\t\t\t\t\t 48 07 09 18 70 26 06\n\t\t\t\t\t\t\t 18 72 79 46 59 79 29 90\n\t\t\t\t\t\t\t20 76 87 11 32 07 07 49 18\n\t\t\t\t\t\t27 83 58 35 71 11 25 57 29 85\n\t\t\t\t\t 14 64 36 96 27 11 58 56 92 18 55\n\t\t\t\t 02 90 03 60 48 49 41 46 33 36 47 23\n\t\t\t\t92 50 48 02 36 59 42 79 72 20 82 77 42\n\t\t\t56 78 38 80 39 75 02 71 66 66 01 03 55 72\n\t\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\t06 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\necho solve data.splitLines.map((x: string) => x.strip.split.map parseInt)\n" + }, + { + "id": 1012, + "length": 1154, + "source": "Rosetta Code", + "text": "import bitops\n\nconst\n\tSize = 32\n\tLastBit = Size - 1\n\tLines = Size div 2\n\tRule = 90\n\ntype State = int # State is represented as an int and will be used as a bit string.\n\n\ntemplate bitVal(state: State; n: typed): int =\n\t## Return the value of a bit as an int rather than a bool.\n\tord(state.testBit(n))\n\n\nproc ruleTest(x: int): bool =\n\t## Return true if a bit must be set.\n\t(Rule and 1 shl (7 and x)) != 0\n\n\nproc evolve(state: var State) =\n\t## Compute next state.\n\n\tvar newState: State # All bits cleared by default.\n\tif ruleTest(state.bitVal(0) shl 2 or state.bitVal(LastBit) shl 1 or state.bitVal(LastBit-1)):\n\t\tnewState.setBit(LastBit)\n\tif ruleTest(state.bitVal(1) shl 2 or state.bitVal(0) shl 1 or state.bitVal(LastBit)):\n\t\tnewState.setBit(0)\n\tfor i in 1.. k: break\n\t\tif val > j:\n\t\t\tlist.addSep(\", \", start)\n\t\t\tlist.add $val\n\techo list\n\n\n# Command line parsing.\n\nproc parseCommandLine(): tuple[j, k: int; kind: LuckyKind] =\n\t## Parse the command line.\n\n\t# Internal exception to catch invalid argument value.\n\ttype InvalidArgumentError = object of ValueError\n\n\ttemplate raiseError(message, value = \"\") =\n\t\t## Raise an InvalidArgumentError.\n\t\traise newException(InvalidArgumentError, message & value & '.')\n\n\n\tresult = (Novalue, Novalue, Lucky)\n\n\ttry:\n\n\t\tif paramCount() notin 1..3: raiseError \"Wrong number of arguments\"\n\n\t\t# First argument: \"j\" value.\n\t\tlet p1 = paramStr(1)\n\t\ttry:\n\t\t\tresult.j = parseInt(p1)\n\t\t\tif result.j <= 0: raiseError \"Expected a positive number, got: \", p1\n\t\texcept ValueError:\n\t\t\traiseError \"Expected an integer, got: \", p1\n\n\t\t# Second argument: \"k\" value or a comma.\n\t\tif paramCount() > 1:\n\t\t\tlet p2 = paramStr(2)\n\t\t\tif p2 == \",\":\n\t\t\t\t# Must be followed by the kind of lucky number.\n\t\t\t\tif paramCount() != 3: raiseError \"Missing kind argument\"\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tresult.k = parseInt(p2)\n\t\t\t\t\tif result.k == 0: raiseError \"Expected a non null number, got: \", p2\n\t\t\t\texcept ValueError:\n\t\t\t\t\traiseError \"Expected an integer, got: \", p2\n\n\t\t# Third argument: number kind.\n\t\tif paramCount() == 3:\n\t\t\tlet p3 = paramStr(3)\n\t\t\ttry:\n\t\t\t\tresult.kind = parseEnum[LuckyKind](p3.toLowerAscii())\n\t\t\texcept ValueError:\n\t\t\t\traiseError \"Wrong kind: \", p3\n\n\texcept InvalidArgumentError:\n\t\tquit getCurrentExceptionMsg()\n\n\n# Main program.\n\nlet (j, k, kind) = parseCommandLine()\n\nif k == NoValue:\n\t# Print jth value.\n\tprintSingle(j, kind)\n\nelif k > 0:\n\t# Print jth to kth values.\n\tprintRange(j, k, kind)\n\nelse:\n\t# Print values in range j..(-k).\n\tprintInRange(j, -k, kind)\n" + }, + { + "id": 1015, + "length": 985, + "source": "Rosetta Code", + "text": "import heapqueue, strformat\n\ntype\n\n\tCubeSum = tuple[x, y, value: int]\n\n# Comparison function needed for the heap queues.\nproc `<`(c1, c2: CubeSum): bool = c1.value < c2.value\n\ntemplate cube(n: int): int = n * n * n\n\n\niterator cubesum(): CubeSum =\n\tvar queue: HeapQueue[CubeSum]\n\tvar n = 1\n\twhile true:\n\t\twhile queue.len == 0 or queue[0].value > cube(n):\n\t\t\tqueue.push (n, 1, cube(n) + 1)\n\t\t\tinc n\n\t\tvar s = queue.pop()\n\t\tyield s\n\t\tinc s.y\n\t\tif s.y < s.x: queue.push (s.x, s.y, cube(s.x) + cube(s.y))\n\n\niterator taxis(): seq[CubeSum] =\n\tvar result: seq[CubeSum] = @[(0, 0, 0)]\n\tfor s in cubesum():\n\t\tif s.value == result[^1].value:\n\t\t\tresult.add s\n\t\telse:\n\t\t\tif result.len > 1: yield result\n\t\t\tresult.setLen(0)\n\t\t\tresult.add s # These two statements are faster than the single result = @[s].\n\n\nvar n = 0\nfor t in taxis():\n\tinc n\n\tif n > 2006: break\n\tif n <= 25 or n >= 2000:\n\t\tstdout.write \"{n:4}: {t[0].value:10}\"\n\t\tfor s in t:\n\t\t\tstdout.write \" = {s.x:4}^3 + {s.y:4}^3\"\n\t\techo()\n" + }, + { + "id": 1016, + "length": 1394, + "source": "Rosetta Code", + "text": "import strutils\n\ntype LudicArray[N: static int] = array[1..N, int]\n\nfunc initLudicArray[N: static int](): LudicArray[N] =\n\t## Initialize an array of ludic numbers.\n\tresult[1] = 1\n\tfor i in 2..N:\n\t\tvar k = 0\n\t\tfor j in countdown(i - 1, 2):\n\t\t\tk = k * result[j] div (result[j] - 1) + 1\n\t\tresult[i] = k + 2\n\n\nproc print(text: string; list: openArray[int]) =\n\t## Print a text followed by a list of ludic numbers.\n\tvar line = text\n\tlet start = line.len\n\tfor val in list:\n\t\tline.addSep(\", \", start)\n\t\tline.add $val\n\techo line\n\n\nfunc isLudic(ludicArray: LudicArray; n, start: Positive): bool =\n\t## Check if a number \"n\" is ludic, starting search from index \"start\".\n\tfor idx in start..ludicArray.N:\n\t\tlet val = ludicArray[idx]\n\t\tif n == val: return true\n\t\tif n < val: break\n\n\nwhen isMainModule:\n\n\tlet ludicArray = initLudicArray[2005]()\n\n\tprint \"The 25 first ludic numbers are: \", ludicArray[1..25]\n\n\tvar count = 0\n\tfor n in ludicArray:\n\t\tif n > 1000: break\n\t\tinc count\n\techo \"\\nThere are \", count, \" ludic numbers less or equal to 1000.\"\n\n\tprint \"\\nThe 2000th to 2005th ludic numbers are: \", ludicArray[2000..2005]\n\n\techo \"\\nThe triplets of ludic numbers less than 250 are:\"\n\tvar line = \"\"\n\tfor i, n in ludicArray:\n\t\tif n >= 244:\n\t\t\techo line\n\t\t\tbreak\n\t\tif ludicArray.isLudic(n + 2, i + 1) and ludicArray.isLudic(n + 6, i + 2):\n\t\t\tline.addSep(\", \")\n\t\t\tline.add \"($1, $2, $3)\".format(n, n + 2, n + 6)\n" + }, + { + "id": 1017, + "length": 695, + "source": "Rosetta Code", + "text": "import strutils\n\n\nfunc step(cells: string; rule: int): string =\n\tfor i in 0..(cells.len - 3):\n\t\tvar bin = 0\n\t\tvar b = 2\n\t\tfor n in i..(i + 2):\n\t\t\tinc bin, ord(cells[n] == '*') shl b\n\t\t\tb = b shr 1\n\t\tlet a = if (rule and 1 shl bin) != 0: '*' else: '.'\n\t\tresult.add(a)\n\n\nfunc addNoCells(cells: var string) =\n\tlet left = if cells[0] == '*': \".\" else: \"*\"\n\tlet right = if cells[^1] == '*': \".\" else: \"*\"\n\tcells.insert(left)\n\tcells.add(right)\n\tcells.insert(left)\n\tcells.add(right)\n\n\nproc evolve(limit, rule: int) =\n\techo \"Rule #\", rule\n\tvar cells = \"*\"\n\tfor _ in 0.. 8000:\n\t\techo \"\"\n\t\tbreak\n\nstdout.write \"The 10000th emirp: \"\ncount = 0\nfor n in emirps():\n\tinc count\n\tif count == 10000:\n\t\techo n\n\t\tbreak\n" + }, + { + "id": 1019, + "length": 1097, + "source": "Rosetta Code", + "text": "import math\n\nconst N = 1_000_000\n\n# Sieve of Erathostenes.\nvar isPrime: array[2..N, bool]\nfor item in isPrime.mitems: item = true\n\n# Initialize the sieve.\nfor n in 2..int(sqrt(N.toFloat)):\n\tif isPrime[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tisPrime[k] = false\n\n\nfunc reversed(n: int): int =\n\t## Return the reversed number in base 10 representation.\n\tvar n = n\n\twhile true:\n\t\tresult = 10 * result + n mod 10\n\t\tn = n div 10\n\t\tif n == 0:\n\t\t\tbreak\n\n\niterator emirps(): int =\n\t## Yield the emirps.\n\tfor n, prime in isPrime:\n\t\tif prime:\n\t\t\tlet r = reversed(n)\n\t\t\tif r > N:\n\t\t\t\tbreak # Unable to continue.\n\t\t\tif r != n and isPrime[r]:\n\t\t\t\tyield n\n\n\nstdout.write \"First 20 emirps:\"\nvar count = 0\nfor n in emirps():\n\tstdout.write ' ', n\n\tinc count\n\tif count == 20:\n\t\techo \"\"\n\t\tbreak\n\nstdout.write \"Emirps between 7700 and 8000:\"\nfor n in emirps():\n\tif n in 7700..8000:\n\t\tstdout.write ' ', n\n\telif n > 8000:\n\t\techo \"\"\n\t\tbreak\n\nstdout.write \"The 10000th emirp: \"\ncount = 0\nfor n in emirps():\n\tinc count\n\tif count == 10000:\n\t\techo n\n\t\tbreak\nif count < 10000:\n\techo \"Not enough primes. Increase value of N.\"\n" + }, + { + "id": 1020, + "length": 1449, + "source": "Rosetta Code", + "text": "import bitops, strformat, times\n\n\nfunc isPal2(k: uint64; digitCount: Natural): bool =\n\t## Return true if the \"digitCount\" + 1 bits of \"k\" form a palindromic number.\n\n\tfor i in 0..digitCount:\n\t\tif k.testBit(i) != k.testBit(digitCount - i):\n\t\t\treturn false\n\tresult = true\n\n\nfunc reverseNumber(k: uint64): uint64 =\n\t## Return the reverse number of \"n\".\n\n\tvar p = k\n\twhile p > 0:\n\t\tresult += 2 * result + p mod 3\n\t\tp = p div 3\n\n\nfunc toBase2(n: uint64): string =\n\t## Return the string representation of \"n\" in base 2.\n\n\tvar n = n\n\twhile true:\n\t\tresult.add(chr(ord('0') + (n and 1)))\n\t\tn = n shr 1\n\t\tif n == 0: break\n\n\nfunc toBase3(n: uint64): string =\n\t## Return the string representation of \"n\" in base 3.\n\n\tvar n = n\n\twhile true:\n\t\tresult.add(chr(ord('0') + n mod 3))\n\t\tn = n div 3\n\t\tif n == 0: break\n\n\nproc print(n: uint64) =\n\t## Print the value in bases 10, 2 and 3.\n\n\techo \"{n:>18} {n.toBase2():^59} {n.toBase3():^41}\"\n\n\nproc findPal23() =\n\t## Find the seven first palindromic numbers in binary and ternary bases.\n\n\tvar p3 = 1u64\n\tvar countPal = 1\n\n\tprint(0)\n\tfor p in 0..31:\n\t\twhile (3 * p3 + 1) * p3 < 1u64 shl (2 * p):\n\t\t\tp3 *= 3\n\t\tlet bound = 1u64 shl (2 * p) div (3 * p3)\n\t\tfor k in max(p3 div 3, bound) .. min(2 * bound, p3 - 1):\n\t\t\tlet n = (3 * k + 1) * p3 + reverseNumber(k)\n\t\t\tif isPal2(n, 2 * p):\n\t\t\t\tprint(n)\n\t\t\t\tinc countPal\n\t\t\t\tif countPal == 7:\n\t\t\t\t\treturn\n\n\nlet t0 = cpuTime()\nfindPal23()\necho fmt\"\\nTime: {cpuTime() - t0:.2f}s\"\n" + }, + { + "id": 1021, + "length": 1533, + "source": "Rosetta Code", + "text": "import tables\n\ntype PrimeType = int\n\nproc primesHashTable(): iterator(): PrimeType {.closure.} =\n\titerator output(): PrimeType {.closure.} =\n\t\t# some initial values to avoid race and reduce initializations...\n\t\tyield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType\n\t\tvar h = initTable[PrimeType,PrimeType]()\n\t\tvar n = 9.PrimeType\n\t\tlet bps = primesHashTable()\n\t\tvar bp = bps() # advance past 2\n\t\tbp = bps(); var q = bp * bp # to initialize with 3\n\t\twhile true:\n\t\t\tif n >= q:\n\t\t\t\tlet inc = bp + bp\n\t\t\t\th[n + inc] = inc\n\t\t\t\tbp = bps(); q = bp * bp\n\t\t\telif h.hasKey(n):\n\t\t\t\tvar inc: PrimeType\n\t\t\t\tdiscard h.take(n, inc)\n\t\t\t\tvar nxt = n + inc\n\t\t\t\twhile h.hasKey(nxt): nxt += inc # ensure no duplicates\n\t\t\t\th[nxt] = inc\n\t\t\telse: yield n\n\t\t\tn += 2.PrimeType\n\toutput\n\nvar num = 0\nstdout.write \"The first 20 primes are: \"\nvar iter = primesHashTable()\nfor p in iter():\n\tif num >= 20: break else: stdout.write(p, \" \"); num += 1\necho \"\"\nstdout.write \"The primes between 100 and 150 are: \"\niter = primesHashTable()\nfor p in iter():\n\tif p >= 150: break\n\tif p >= 100: stdout.write(p, \" \")\necho \"\"\nnum = 0\niter = primesHashTable()\nfor p in iter():\n\tif p > 8000: break\n\tif p >= 7700: num += 1\necho \"The number of primes between 7700 and 8000 is: \", num\nnum = 1\niter = primesHashTable()\nfor p in iter():\n\tif num >= 10000:\n\t\techo \"The 10,000th prime is: \", p\n\t\tbreak\n\tnum += 1\nvar sum = 0\niter = primesHashTable()\nfor p in iter():\n\tif p >= 2_000_000:\n\t\techo \"The sum of the primes to two million is: \", sum\n\t\tbreak\n\tsum += p\n" + }, + { + "id": 1022, + "length": 592, + "source": "Rosetta Code", + "text": "import strutils\n\nlet text = \"\"\"---------- 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\nproc reversed*[T](a: openArray[T], first, last: int): seq[T] =\n\tresult = newSeq[T](last - first + 1)\n\tvar x = first\n\tvar y = last\n\twhile x <= last:\n\t\tresult[x] = a[y]\n\t\tdec(y)\n\t\tinc(x)\n\nproc reversed*[T](a: openArray[T]): seq[T] =\n\treversed(a, 0, a.high)\n\nfor line in text.splitLines():\n\techo line.split(' ').reversed().join(\" \")\n" + }, + { + "id": 1023, + "length": 1177, + "source": "Rosetta Code", + "text": "import lists, random\n\n\nfunc treeInsert[T](tree: var DoublyLinkedNode[T]; node: DoublyLinkedNode[T]) =\n\tif tree.isNil: tree = node\n\telif node.value < tree.value: tree.prev.treeInsert(node)\n\telse: tree.next.treeInsert(node)\n\n\nfunc listFromTree[T](list: var DoublyLinkedList[T]; node: DoublyLinkedNode[T]) =\n\tif node.isNil: return\n\tlet prev = node.prev\n\tlet next = node.next\n\tlist.listFromTree(prev)\n\tlist.append(node)\n\tlist.listFromTree(next)\n\n\nfunc treeSort[T](list: DoublyLinkedList[T]): DoublyLinkedList[T] =\n\tvar list = list\n\tif list.head == list.tail: return list\n\tvar n = list.head\n\tvar root: DoublyLinkedNode[T] = nil\n\twhile not n.isNil:\n\t\tvar next = n.next\n\t\tn.next = nil\n\t\tn.prev = nil\n\t\troot.treeInsert(n)\n\t\tn = next\n\tresult = initDoublyLinkedList[T]()\n\tresult.listFromTree(root)\n\n\nrandomize()\nvar list1 = initDoublyLinkedList[int]()\nfor i in 0..15: list1.append(rand(10..99))\necho \"Before sort: \", list1\necho \"After sort: \", list1.treeSort()\necho()\n\nvar list2 = initDoublyLinkedList[string]()\nfor s in [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"]:\n\tlist2.append(s)\necho \"Before sort: \", list2\necho \"After sort: \", list2.treeSort()\n" + }, + { + "id": 1024, + "length": 953, + "source": "Rosetta Code", + "text": "import strformat\n\nproc farey(n: int) =\n\tvar f1 = (d: 0, n: 1)\n\tvar f2 = (d: 1, n: n)\n\twrite(stdout, fmt\"0/1 1/{n}\")\n\twhile f2.n > 1:\n\t\tlet k = (n + f1.n) div f2.n\n\t\tlet aux = f1\n\t\tf1 = f2\n\t\tf2 = (f2.d * k - aux.d, f2.n * k - aux.n)\n\t\twrite(stdout, fmt\" {f2.d}/{f2.n}\")\n\twrite(stdout, \"\\n\")\n\nproc fareyLength(n: int, cache: var seq[int]): int =\n\tif n >= cache.len:\n\t\tvar newLen = cache.len\n\t\tif newLen == 0:\n\t\t\tnewLen = 16\n\t\twhile newLen <= n:\n\t\t\tnewLen *= 2\n\t\tcache.setLen(newLen)\n\telif cache[n] != 0:\n\t\treturn cache[n]\n\n\tvar length = n * (n + 3) div 2\n\tvar p = 2\n\tvar q = 0\n\twhile p <= n:\n\t\tq = n div (n div p) + 1\n\t\tdec length, fareyLength(n div p, cache) * (q - p)\n\t\tp = q\n\tcache[n] = length\n\treturn length\n\nfor n in 1..11:\n\twrite(stdout, fmt\"{n:>8}: \")\n\tfarey(n)\n\nvar cache: seq[int] = @[]\nfor n in countup(100, 1000, step=100):\n\techo fmt\"{n:>8}: {fareyLength(n, cache):14} items\"\n\nlet n = 10_000_000\necho fmt\"{n}: {fareyLength(n, cache):14} items\"\n" + }, + { + "id": 1025, + "length": 2304, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\nlet\n\tZero = newInt(0)\n\tOne = newInt(1)\n\n\nproc toEgyptianrecursive(rat: Rat; fracs: seq[Rat]): seq[Rat] =\n\n\tif rat.isZero: return fracs\n\n\tlet iquo = cdiv(rat.denom, rat.num)\n\tlet rquo = newRat(1, iquo)\n\tresult = fracs & rquo\n\tlet num2 = cmod(-rat.denom, rat.num)\n\tif num2 < Zero:\n\t\tnum2 += rat.num\n\tlet denom2 = rat.denom * iquo\n\tlet f = newRat(num2, denom2)\n\tif f.num == One:\n\t\tresult.add(f)\n\telse:\n\t\tresult = f.toEgyptianrecursive(result)\n\n\nproc toEgyptian(rat: Rat): seq[Rat] =\n\n\tif rat.num.isZero: return @[rat]\n\n\tif abs(rat.num) >= rat.denom:\n\t\tlet iquo = rat.num div rat.denom\n\t\tlet rquo = newRat(iquo, 1)\n\t\tlet rrem = rat - rquo\n\t\tresult = rrem.toEgyptianrecursive(@[rquo])\n\telse:\n\t\tresult = rat.toEgyptianrecursive(@[])\n\n\nfor frac in [newRat(43, 48), newRat(5, 121), newRat(2014, 59)]:\n\tlet list = frac.toEgyptian()\n\tif list[0].denom == One:\n\t\tlet first = fmt\"[{list[0].num}]\"\n\t\tlet rest = list[1..^1].join(\" + \")\n\t\techo fmt\"{frac} -> {first} + {rest}\"\n\telse:\n\t\tlet all = list.join(\" + \")\n\t\techo fmt\"{frac} -> {all}\"\n\nfor r in [98, 998]:\n\tif r == 98:\n\t\techo \"\\nFor proper fractions with 1 or 2 digits:\"\n\telse:\n\t\techo \"\\nFor proper fractions with 1, 2 or 3 digits:\"\n\n\tvar maxSize = 0\n\tvar maxSizeFracs: seq[Rat]\n\tvar maxDen = Zero\n\tvar maxDenFracs: seq[Rat]\n\tvar sieve = newSeq[seq[bool]](r + 1) # To eliminate duplicates.\n\n\tfor item in sieve.mitems: item.setLen(r + 2)\n\tfor i in 1..r:\n\t\tfor j in (i + 1)..(r + 1):\n\t\t\tif sieve[i][j]: continue\n\n\t\t\tlet f = newRat(i, j)\n\t\t\tlet list = f.toEgyptian()\n\t\t\tlet listSize = list.len\n\t\t\tif listSize > maxSize:\n\t\t\t\tmaxSize = listSize\n\t\t\t\tmaxSizeFracs.setLen(0)\n\t\t\t\tmaxSizeFracs.add(f)\n\t\t\telif listSize == maxSize:\n\t\t\t\tmaxSizeFracs.add(f)\n\n\t\t\tlet listDen = list[^1].denom()\n\t\t\tif listDen > maxDen:\n\t\t\t\tmaxDen = listDen\n\t\t\t\tmaxDenFracs.setLen(0)\n\t\t\t\tmaxDenFracs.add(f)\n\t\t\telif listDen == maxDen:\n\t\t\t\tmaxDenFracs.add(f)\n\n\t\t\tif i < r div 2:\n\t\t\t\tvar k = 2\n\t\t\t\twhile j * k <= r + 1:\n\t\t\t\t\tsieve[i * k][j * k] = true\n\t\t\t\t\tinc k\n\n\techo fmt\" largest number of items = {maxSize}\"\n\techo fmt\" fraction(s) with this number : {maxSizeFracs.join(\"\", \"\")}\"\n\tlet md = $maxDen\n\techo fmt\" largest denominator = {md.len} digits, {md[0..19]}...{md[^20..^1]}\"\n\techo fmt\" fraction(s) with this denominator : {maxDenFracs.join(\"\", \"\")}\"\n" + }, + { + "id": 1026, + "length": 813, + "source": "Rosetta Code", + "text": "import math, sequtils, strformat, strutils\n\n\nproc genSequence(ones: seq[string]; numZeroes: Natural): seq[string] =\n\tif ones.len == 0: return @[repeat('0', numZeroes)]\n\tfor x in 1..(numZeroes - ones.len + 1):\n\t\tlet skipOne = ones[1..^1]\n\t\tfor tail in genSequence(skipOne, numZeroes - x):\n\t\t\tresult.add repeat('0', x) & ones[0] & tail\n\n\nproc printBlock(data: string; length: Positive) =\n\n\tlet a = mapIt(data, ord(it) - ord('0'))\n\tlet sumBytes = sum(a)\n\n\techo \"\\nblocks {($a)[1..^1]} cells {length}\"\n\tif length - sumBytes <= 0:\n\t\techo \"No solution\"\n\t\treturn\n\n\tvar prep: seq[string]\n\tfor b in a: prep.add repeat('1', b)\n\n\tfor r in genSequence(prep, length - sumBytes + 1):\n\t\techo r[1..^1]\n\n\nwhen isMainModule:\n\tprintBlock(\"21\", 5)\n\tprintBlock(\"\", 5)\n\tprintBlock(\"8\", 10)\n\tprintBlock(\"2323\", 15)\n\tprintBlock(\"23\", 5)\n" + }, + { + "id": 1027, + "length": 3099, + "source": "Rosetta Code", + "text": "import math, os, strformat, strscans, strutils\n\ntype Vector = tuple[x, y, z: float]\n\nfunc`+`(v1, v2: Vector): Vector = (v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)\n\nfunc `+=`(v1: var Vector; v2: Vector) =\n\tv1.x += v2.x\n\tv1.y += v2.y\n\tv1.z += v2.z\n\nfunc`-`(v1, v2: Vector): Vector = (v1.x - v2.x, v1.y - v2.y, v1.z - v2.z)\n\nfunc `*`(v: Vector; m: float): Vector = (v.x * m, v.y * m, v.z * m)\n\nfunc abs(v: Vector): float = sqrt(v.x * v.x + v.y * v.y + v.z * v.z)\n\n\ntype Simulation = object\n\tbodies: int\n\ttimeSteps: int\n\tmasses: seq[float]\n\tgc: float\n\tpositions: seq[Vector]\n\tvelocities: seq[Vector]\n\taccelerations: seq[Vector]\n\nproc emitError(linenum: Positive) =\n\traise newException(ValueError, \"wrong data at line $#.\".format(linenum))\n\nproc initSimulation(fileName: string): Simulation =\n\tlet infile = fileName.open()\n\tvar line = infile.readLine()\n\tif not line.scanf(\"$f $i $i\", result.gc, result.bodies, result.timeSteps):\n\t\temitError(1)\n\tresult.masses.setlen(result.bodies)\n\tresult.positions.setLen(result.bodies)\n\tresult.velocities.setLen(result.bodies)\n\tresult.accelerations.setLen(result.bodies)\n\tvar linenum = 1\n\tfor i in 0..\" % getAppFilename().lastPathPart\nelse:\n\tvar sim = initSimulation(paramStr(1))\n\techo \"Body x y z | vx vy vz\"\n\tfor step in 1..sim.timeSteps:\n\t\techo \"\\nCycle \", step\n\t\tsim.step()\n\t\tsim.printResults()\n" + }, + { + "id": 1028, + "length": 811, + "source": "Rosetta Code", + "text": "import algorithm, strutils\n\n\nproc orderDisjoint(m, n: string): string =\n\n\t# Build the list of items.\n\tvar m = m.splitWhitespace()\n\tlet n = n.splitWhitespace()\n\n\t# Find the indexes of items to replace.\n\tvar indexes: seq[int]\n\tfor item in n:\n\t\tlet idx = m.find(item)\n\t\tif idx >= 0:\n\t\t\tindexes.add idx\n\t\t\tm[idx] = \"\" # Set to empty string for next searches.\n\tindexes.sort()\n\n\t# Do the replacements.\n\tfor i, idx in indexes:\n\t\tm[idx] = n[i]\n\n\tresult = m.join(\" \")\n\n\nwhen isMainModule:\n\n\ttemplate process(a, b: string) =\n\t\techo a, \" | \", b, \" -> \", orderDisjoint(a, b)\n\n\tprocess(\"the cat sat on the mat\", \"mat cat\")\n\tprocess(\"the cat sat on the mat\", \"cat mat\")\n\tprocess(\"A B C A B C A B C\", \"C A C A\")\n\tprocess(\"A B C A B D A B E\", \"E A D A\")\n\tprocess(\"A B\", \"B\")\n\tprocess(\"A B\", \"B A\")\n\tprocess(\"A B B A\", \"B A\")\n" + }, + { + "id": 1029, + "length": 625, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\nfunc rank(list: openArray[uint]): Int =\n\tresult = newInt(0)\n\tfor n in list:\n\t\tresult = result shl (n + 1)\n\t\tresult = result.setBit(n)\n\nfunc unrank(n: Int): seq[uint] =\n\tvar m = n.clone\n\tvar a = if m.isZero: 0u else: m.bitLen.uint\n\twhile a > 0:\n\t\tm = m.clearBit(a - 1)\n\t\tlet b = if m.isZero: 0u else: m.bitLen.uint\n\t\tresult.add(a - b - 1)\n\t\ta = b\n\nwhen isMainModule:\n\n\tvar b: Int\n\tfor i in 0..10:\n\t\tb = newInt(i)\n\t\tlet u = b.unrank()\n\t\tlet r = u.rank()\n\t\techo \"{i:2d} {u:>9s} {r:>2s}\"\n\n\tb = newInt(\"12345678901234567890\")\n\tlet u = b.unrank()\n\tlet r = u.rank()\n\techo \"\\n{b}\\n{u}\\n{r}\"\n" + }, + { + "id": 1030, + "length": 717, + "source": "Rosetta Code", + "text": "proc example =\n\techo \"Example\"\n\n# Ordinary procedure\nproc repeatProc(fn: proc, n: int) =\n\tfor x in 0.. 0:\n\t\t\t\tlist.add val\n\t\t\t\tif val == 1:\n\t\t\t\t\tresult.startRow = r + 1\n\t\t\t\t\tresult.startCol = c + 1\n\n\tlist.sort()\n\tresult.clues = list\n\n\nproc solve(numbrix: var Numbrix; row, col, count: Natural; nextClue: int): bool =\n\n\tif count > numbrix.totalToFill:\n\t\treturn true\n\n\tlet back = numbrix.grid[row][col]\n\tif back notin [0, count]:\n\t\treturn false\n\tif back == 0 and nextClue < numbrix.clues.len and numbrix.clues[nextClue] == count:\n\t\treturn false\n\n\tvar nextClue = nextClue\n\tif back == count: inc nextClue\n\n\tnumbrix.grid[row][col] = count\n\tfor move in Moves:\n\t\tif numbrix.solve(row + move[1], col + move[0], count + 1, nextClue):\n\t\t\treturn true\n\tnumbrix.grid[row][col] = back\n\n\nproc print(numbrix: Numbrix) =\n\tfor row in numbrix.grid:\n\t\tfor val in row:\n\t\t\tif val != -1:\n\t\t\t\tstdout.write \"{val:2} \"\n\t\techo()\n\n\nwhen isMainModule:\n\n\tconst\n\n\t\tExample1 = [\"00,00,00,00,00,00,00,00,00\",\n\t\t\t\t\t\t\t\t\"00,00,46,45,00,55,74,00,00\",\n\t\t\t\t\t\t\t\t\"00,38,00,00,43,00,00,78,00\",\n\t\t\t\t\t\t\t\t\"00,35,00,00,00,00,00,71,00\",\n\t\t\t\t\t\t\t\t\"00,00,33,00,00,00,59,00,00\",\n\t\t\t\t\t\t\t\t\"00,17,00,00,00,00,00,67,00\",\n\t\t\t\t\t\t\t\t\"00,18,00,00,11,00,00,64,00\",\n\t\t\t\t\t\t\t\t\"00,00,24,21,00,01,02,00,00\",\n\t\t\t\t\t\t\t\t\"00,00,00,00,00,00,00,00,00\"]\n\n\t\tExample2 = [\"00,00,00,00,00,00,00,00,00\",\n\t\t\t\t\t\t\t\t\"00,11,12,15,18,21,62,61,00\",\n\t\t\t\t\t\t\t\t\"00,06,00,00,00,00,00,60,00\",\n\t\t\t\t\t\t\t\t\"00,33,00,00,00,00,00,57,00\",\n\t\t\t\t\t\t\t\t\"00,32,00,00,00,00,00,56,00\",\n\t\t\t\t\t\t\t\t\"00,37,00,01,00,00,00,73,00\",\n\t\t\t\t\t\t\t\t\"00,38,00,00,00,00,00,72,00\",\n\t\t\t\t\t\t\t\t\"00,43,44,47,48,51,76,77,00\",\n\t\t\t\t\t\t\t\t\"00,00,00,00,00,00,00,00,00\"]\n\n\tfor i, board in [1: Example1, 2: Example2]:\n\t\tvar numbrix = initNumbrix(board)\n\t\tif numbrix.solve(numbrix.startRow, numbrix.startCol, 1, 0):\n\t\t\techo \"Solution for example {i}:\"\n\t\t\tnumbrix.print()\n\t\telse:\n\t\t\techo \"No solution.\"\n" + }, + { + "id": 1033, + "length": 2106, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat\n\nconst Moves = [(-3, 0), (0, 3), ( 3, 0), ( 0, -3),\n\t\t\t\t\t\t\t ( 2, 2), (2, -2), (-2, 2), (-2, -2)]\n\ntype\n\n\tHopido = object\n\t\tgrid: seq[seq[int]]\n\t\tnRows, nCols: int\n\t\ttotalToFill : Natural\n\n\tNeighbor = (int, int, int)\n\n\nproc initHopido(board: openArray[string]): Hopido =\n\tresult.nRows = board.len + 6\n\tresult.nCols = board[0].len + 6\n\tresult.grid = newSeqWith(result.nRows, repeat(-1, result.nCols))\n\n\tfor row in 0..board.high:\n\t\tfor col in 0..board[0].high:\n\t\t\tif board[row][col] == '0':\n\t\t\t\tresult.grid[row + 3][col + 3] = 0\n\t\t\t\tinc result.totalToFill\n\n\nproc countNeighbors(hopido: Hopido; row, col: Natural): int =\n\tfor (x, y) in Moves:\n\t\tif hopido.grid[row + y][col + x] == 0:\n\t\t\tinc result\n\n\nproc neighbors(hopido: Hopido; row, col: Natural): seq[Neighbor] =\n\tfor (x, y) in Moves:\n\t\tif hopido.grid[row + y][col + x] == 0:\n\t\t\tlet num = hopido.countNeighbors(row + y, col + x) - 1\n\t\t\tresult.add (row + y, col + x, num)\n\n\nproc solve(hopido: var Hopido; row, col, count: Natural): bool =\n\n\tif count > hopido.totalTofill: return true\n\n\tvar nbrs = hopido.neighbors(row, col)\n\tif nbrs.len == 0 and count != hopido.totalToFill:\n\t\treturn false\n\n\tnbrs.sort(proc(a, b: Neighbor): int = cmp(a[2], b[2]))\n\n\tfor (row, col, _) in nbrs:\n\t\thopido.grid[row][col] = count\n\t\tif hopido.solve(row, col, count + 1):\n\t\t\treturn true\n\t\thopido.grid[row][col] = 0\n\n\nproc findSolution(hopido: var Hopido) =\n\tvar pos = -1\n\tvar row, col: Natural\n\n\twhile true:\n\t\twhile true:\n\t\t\tinc pos\n\t\t\trow = pos div hopido.nCols\n\t\t\tcol = pos mod hopido.nCols\n\t\t\tif hopido.grid[row][col] != -1:\n\t\t\t\tbreak\n\t\thopido.grid[row][col] = 1\n\t\tif hopido.solve(row, col, 2):\n\t\t\tbreak\n\t\thopido.grid[row][col] = 0\n\t\tif pos >= hopido.nRows * hopido.nCols:\n\t\t\tbreak\n\n\nproc print(hopido: Hopido) =\n\tfor row in hopido.grid:\n\t\tfor val in row:\n\t\t\tstdout.write if val == -1: \" \" else: \"{val:2} \"\n\t\techo()\n\n\nwhen isMainModule:\n\n\tconst Board = [\".00.00.\",\n\t\t\t\t\t\t\t\t \"0000000\",\n\t\t\t\t\t\t\t\t \"0000000\",\n\t\t\t\t\t\t\t\t \".00000.\",\n\t\t\t\t\t\t\t\t \"..000..\",\n\t\t\t\t\t\t\t\t \"...0...\"]\n\n\tvar hopido = initHopido(Board)\n\thopido.findSolution()\n\thopido.print()\n" + }, + { + "id": 1034, + "length": 1501, + "source": "Rosetta Code", + "text": "import sequtils, strformat\n\nconst Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]]\n\nproc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool =\n\n\tif idx > count: return true\n\n\tvar x, y: int\n\tfor move in Moves:\n\t\tx = sx + move[0]\n\t\ty = sy + move[1]\n\t\tif x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0:\n\t\t\tpz[x][y] = idx\n\t\t\tif pz.solve(x, y, idx + 1, count): return true\n\t\t\tpz[x][y] = 0\n\n\nproc findSolution(board: openArray[string]) =\n\tlet sz = board.len\n\tvar pz = newSeqWith(sz, repeat(-1, sz))\n\n\tvar count = 0\n\tvar x, y: int\n\tfor i in 0.. 255: break\n\n\tif flag:\n\t\t# Do a second pass to make all of the seed affect all of \"mm\".\n\t\ti = 0\n\t\twhile true:\n\t\t\tfor n in 0u32..7: a[n] += s.mm[n + i]\n\t\t\ta.mix()\n\t\t\tfor n in 0u32..7: s.mm[n + i] = a[n]\n\t\t\tinc i, 8\n\t\t\tif i > 255: break\n\n\ts.isaac() # Fill in the first set of results.\n\ts.randcnt = 0 # Prepare to use the first set of results.\n\n\nproc iSeed(s: var State; seed: string; flag: bool) =\n\t## Seed ISAAC with a given string.\n\t## The string can be any size. The first 256 values will be used.\n\ts.mm.reset()\n\tlet m = seed.high\n\tfor i in 0..255:\n\t\ts.randrsl[i] = if i > m: 0 else: ord(seed[i])\n\t# Initialize ISAAC with seed.\n\ts.iRandInit(flag)\n\n\nproc iRandom(s: var State): uint32 =\n\t## Get a random 32-bit value 0..int32.high.\n\tresult = s.randrsl[s.randcnt]\n\tinc s.randcnt\n\tif s.randcnt > 255:\n\t\ts.isaac()\n\t\ts.randcnt = 0\n\n\nproc iRandA(s: var State): byte =\n\t## Get a random character in printable ASCII range.\n\tresult = byte(s.iRandom() mod 95 + 32)\n\n\nproc vernam(s: var State; msg: string): string =\n\t## XOR encrypt on random stream. Output: ASCII string.\n\tresult.setLen(msg.len)\n\tfor i, c in msg:\n\t\tresult[i] = chr(s.irandA() xor byte(c))\n\n\ntemplate letterNum(letter, start: char): int =\n\tord(letter) - ord(start)\n\n\nproc caesar(m: IMode; ch: char; shift, modulo: int; start: char): char =\n\tlet shift = if m == iEncrypt: shift else: -shift\n\tvar n = letterNum(ch, start) + shift\n\tn = n mod modulo\n\tif n < 0: inc n, modulo\n\tresult = chr(ord(start) + n)\n\n\nproc vigenere(s: var State; msg: string; m: IMode): string =\n\t## Vigenere MOD 95 encryption & decryption. Output: ASCII string.\n\tresult.setLen(msg.len)\n\tfor i, c in msg:\n\t\tresult[i] = caesar(m, c, s.iRanda().int, 95, ' ')\n\n\nlet\n\tmsg = \"a Top Secret secret\"\n\tkey = \"this is my secret key\"\n\nvar state: State\n\n# 1) seed ISAAC with the key\nstate.iSeed(key, true)\n# 2) Encryption\n# a) XOR (Vernam)\nlet xctx = state.vernam(msg) # XOR ciphertext.\n# b) MOD (Vigenere)\nlet mctx = state.vigenere(msg, iEncrypt) # MOD ciphertext.\n# 3) Decryption\nstate.iSeed(key, true)\n# a) XOR (Vernam)\nlet xptx = state.vernam(xctx) # XOR decryption (plaintext).\n# b) MOD (Vigenere)\nlet mptx = state.vigenere(mctx, iDecrypt) # MOD decryption (plaintext).\n# Program output\necho \"Message: \", msg\necho \" Key: \", key\necho \" XOR: \", xctx.tohex\necho \" MOD: \", mctx.toHex\necho \"XOR dcr: \", xptx\necho \"MOD dcr: \", mptx\n" + }, + { + "id": 1041, + "length": 2207, + "source": "Rosetta Code", + "text": "echo \"For 32 bits signed integers with overflow check suppressed:\"\n{.push overflowChecks: off.}\nvar a: int32\na = -(-2147483647i32 - 1'i32)\necho \" -(-2147483647-1) gives \", a # -2147483648.\na = 2000000000i32 + 2000000000i32\necho \" 2000000000 + 2000000000 gives \", a # -294967296.\na = -2147483647i32 - 2147483647i32\necho \" -2147483647 - 2147483647 gives \", a # 2.\na = 46341i32 * 46341i32\necho \" 46341 * 46341 gives \", a # -2147479015.\na = (-2147483647i32 - 1i32) div -1i32\necho \" (-2147483647-1) / -1 gives \", a # -2147483648.\n{.pop.}\necho \"\"\n\necho \"For 64 bits signed integers with overflow check suppressed:\"\n{.push overflowChecks: off.}\nvar b: int64\nb = -(-9223372036854775807i64 - 1i64)\necho \" -(-9223372036854775807-1) gives \", b # -9223372036854775808.\nb = 5000000000000000000i64 + 5000000000000000000i64\necho \" 5000000000000000000 + 5000000000000000000 gives \", b # -8446744073709551616.\nb = -9223372036854775807i64 - 9223372036854775807i64\necho \" -9223372036854775807 - 9223372036854775807 gives \", b # 2.\nb = 3037000500i64 * 3037000500i64\necho \" 3037000500 * 3037000500 gives \", b # -9223372036709301616.\nb = (-9223372036854775807i64 - 1i64) div -1i64\necho \" (-9223372036854775807-1) / -1 gives \", b # -9223372036854775808.\n{.pop.}\necho \"\"\n\necho \"For 32 bits unsigned integers:\"\nvar c: uint32\necho \" -4294967295 doesn't compile.\"\nc = 3000000000u32 + 3000000000u32\necho \" 3000000000 + 3000000000 gives \", c # 1705032704.\nc = 2147483647u32 - 4294967295u32\necho \" 2147483647 - 4294967295 gives \", c # 2147483648.\nc = 65537u32 * 65537u32\necho \" 65537 * 65537 gives \", c # 131073.\necho \"\"\n\necho \"For 64 bits unsigned integers:\"\nvar d: uint64\necho \" -18446744073709551615 doesn't compile.\"\nd = 10000000000000000000u64 + 10000000000000000000u64\necho \" 10000000000000000000 + 10000000000000000000 gives \", d # 1553255926290448384.\nd = 9223372036854775807u64 - 18446744073709551615u64\necho \" 9223372036854775807 - 18446744073709551615 gives \", d # 9223372036854775808.\nd = 4294967296u64 * 4294967296u64\necho \" 4294967296 * 4294967296 gives \", d # 0.\n" + }, + { + "id": 1042, + "length": 1054, + "source": "Rosetta Code", + "text": "import tables\n\niterator digits(n: int): int =\n\t## Yield the digits starting from the unit.\n\tvar n = n\n\twhile true:\n\t\tyield n mod 10\n\t\tn = n div 10\n\t\tif n == 0:\n\t\t\tbreak\n\n\nfunc gen(n: int): int =\n\t## Compute the chain.\n\tresult = n\n\twhile result notin [1, 89]:\n\t\tvar s = 0\n\t\tfor d in digits(result):\n\t\t\tinc s, d * d\n\t\tresult = s\n\n\nfunc chainsEndingWith89(ndigits: Natural): Natural =\n\t## Compute the number of chains ending with 89.\n\n\t# Initialize the count table with values for one digit numbers.\n\tvar prevCount, currcount: CountTable[int]\n\tfor i in 0..9: prevcount[i * i] = 1\n\n\t# Add next digits.\n\tfor _ in 2..ndigits:\n\t\t# Create the next generation count array.\n\t\tcurrcount.clear()\n\t\tfor val, count in prevcount:\n\t\t\tfor newdigit in 0..9:\n\t\t\t\t# As 0 is included, \"currcount\" includes \"prevcount\".\n\t\t\t\tcurrcount.inc(newdigit * newdigit + val, count)\n\t\tprevcount = currcount\n\n\tfor val, count in currcount:\n\t\tif val != 0 and gen(val) == 89:\n\t\t\tinc result, count\n\necho \"For 8 digits: \", chainsEndingWith89(8)\necho \"For 50 digits: \", chainsEndingWith89(15)\n" + }, + { + "id": 1043, + "length": 718, + "source": "Rosetta Code", + "text": "import math, strformat\n\nfunc endsWithOne(n: Natural): bool =\n\tvar n = n\n\twhile true:\n\t\tvar sum = 0\n\t\twhile n > 0:\n\t\t\tlet digit = n mod 10\n\t\t\tsum += digit * digit\n\t\t\tn = n div 10\n\t\tif sum == 1: return true\n\t\tif sum == 89: return false\n\t\tn = sum\n\nconst Ks = [7, 8, 11, 14, 17]\n\nfor k in Ks:\n\tvar sums = newSeq[int64](k * 81 + 1) # Initialized to 0s.\n\tsums[0] = 1\n\tfor n in 1..k:\n\t\tfor i in countdown(n * 81, 1):\n\t\t\tfor j in 1..9:\n\t\t\t\tlet s = j * j\n\t\t\t\tif s > i: break\n\t\t\t\tsums[i] += sums[i - s]\n\n\tvar count1 = 0i64\n\tfor i in 1..k*81:\n\t\tif i.endsWithOne(): count1 += sums[i]\n\tlet limit = 10^k - 1\n\techo \"For k = {k} in the range 1 to {limit}\"\n\techo \"{count1} numbers produce 1 and {limit - count1} numbers produce 89\\n\"\n" + }, + { + "id": 1044, + "length": 2944, + "source": "Rosetta Code", + "text": "import endians, math, sequtils, std/sha1, times\n\ntype\n\n\tHashFunc = proc(msg: openArray[char]): seq[char]\n\n\tOneTimePassword = object\n\t\tdigit: int # Length of code generated.\n\t\ttimeStep: Duration # Length of each time step for TOTP.\n\t\tbaseTime: Time # The start time for TOTP step calculation.\n\t\thash: HashFunc # Hash algorithm used with HMAC.\n\n\nfunc sha1Hash(msg: openArray[char]): seq[char] =\n\tmapIt(@(Sha1Digest(secureHash(msg))), char(it))\n\n\nfunc `xor`(s: seq[char]; val: byte): seq[char] =\n\t## Apply a XOR to the chars of a sequence.\n\ts.mapIt(char(it.byte xor val))\n\n\nfunc hmac(key, msg: openArray[char]; hashFunc: HashFunc; blockSize = 64): seq[char] =\n\t## Compute a HMAC for gien key, message, hash function and block size.\n\tvar key = @key\n\tlet paddingNeeded = blockSize - key.len\n\tif paddingNeeded > 0: key.setLen(blockSize)\n\tresult = hashFunc((key xor 0x5c) & hashFunc((key xor 0x36) & @msg))\n\n\nfunc simple(digit: int): OneTimePassword =\n\t## Return a new OneTimePassword with the specified HTOP code length,\n\t## SHA-1 as the HMAC hash algorithm, the Unix epoch as the base time, and\n\t## 30 seconds as the step length.\n\tdoAssert digit in 6..9, \"HTOP code length must be in 6..9.\"\n\tlet step = initDuration(seconds = 30)\n\tresult = OneTimePassword(digit: digit, timeStep: step, baseTime: fromUnix(0), hash: sha1Hash)\n\n\nfunc hmacSum(otp: OneTimePassword; secret: openArray[char]; count: uint64): seq[char] =\n\tvar count = count\n\tvar beCount: uint64\n\tbigEndian64(beCount.addr, count.addr)\n\tlet msg = cast[array[8, char]](beCount)\n\tresult = hmac(secret, msg, otp.hash)\n\n\nfunc dt(hs: seq[char]): seq[char] =\n\tlet offset = hs[^1].byte and 0xf\n\tresult = hs[offset..offset+3]\n\tresult[0] = char(result[0].byte and 0x7f)\n\n\nfunc truncate(otp: OneTimePassword; hs: seq[char]): uint64 =\n\tlet sbits = dt(hs)\n\tlet snum = sbits[3].uint64 or sbits[2].uint64 shl 8 or\n\t\t\t\t\t\t sbits[1].uint64 shl 16 or sbits[0].uint64 shl 24\n\tresult = snum mod 10u^otp.digit\n\n\nfunc hotp(otp: OneTimePassword; secret: openArray[char]; count: uint64): uint64 =\n\tlet hs = otp.hmacSum(secret, count)\n\tresult = otp.truncate(hs)\n\n\nfunc steps(otp: OneTimePassword; t: Time): uint64 =\n\tlet elapsed = t - otp.baseTime\n\tresult = uint64(elapsed.inSeconds div otp.timeStep.inSeconds)\n\n\nproc totp(otp: OneTimePassword; secret: openArray[char]): uint64 =\n\t## Return a TOTP code calculated with the current time and the given secret.\n\totp.hotp(secret, otp.steps(getTime()))\n\n\nwhen isMainModule:\n\n\tproc exampleSimple =\n\t\t## Simple 6-digit HOTP code.\n\t\tconst secret = \"SOME_SECRET\"\n\t\tvar counter: uint64 = 123456\n\t\tlet otp = simple(6)\n\t\tlet code = otp.hotp(secret, counter)\n\t\techo code\n\t\t# Output:\n\t\t# 260040\n\n\tproc exampleAuthenticator =\n\t\t## Google authenticator style 8-digit TOTP code.\n\t\tconst secret = \"SOME_SECRET\"\n\t\tlet otp = simple(8)\n\t\tlet code = otp.totp(secret)\n\t\techo code\n\n\techo \"Simple:\"\n\texampleSimple()\n\n\techo \"Google authenticator:\"\n\texampleAuthenticator()\n" + }, + { + "id": 1045, + "length": 935, + "source": "Rosetta Code", + "text": "import os, random, sequtils, strutils\n\nrandomize()\n\nlet first = sample([false, true])\n\nvar you, me = \"\"\nif first:\n\tme = newSeqWith(3, sample(\"HT\")).join()\n\techo \"I choose first and will win on first seeing $# in the list of tosses.\" % me\n\twhile you.len != 3 or not allCharsInSet(you, {'H', 'T'}) or you == me:\n\t\tstdout.write \"What sequence of three Heads/Tails will you win with? \"\n\t\tyou = stdin.readLine()\nelse:\n\twhile you.len != 3 or not allCharsInSet(you, {'H', 'T'}):\n\t\techo \"After you: what sequence of three Heads/Tails will you win with? \"\n\t\tyou = stdin.readLine()\n\tme = (if you[1] == 'T': 'H' else: 'T') & you[0..1]\n\techo \"I win on first seeing $# in the list of tosses\" % me\n\nvar rolled = \"\"\nstdout.write \"Rolling:\\n \"\nwhile true:\n\trolled.add sample(\"HT\")\n\tstdout.write rolled[^1]\n\tstdout.flushFile()\n\tif rolled.endsWith(you):\n\t\techo \"\\n You win!\"\n\t\tbreak\n\telif rolled.endsWith(me):\n\t\techo \"\\n I win!\"\n\t\tbreak\n\tsleep(1000)\n" + }, + { + "id": 1046, + "length": 1092, + "source": "Rosetta Code", + "text": "import strformat\n\nconst Connections = [(1, 3), (1, 4), (1, 5), # A to C, D, E\n\t\t\t\t\t\t\t\t\t\t (2, 4), (2, 5), (2, 6), # B to D, E, F\n\t\t\t\t\t\t\t\t\t\t (7, 3), (7, 4), (7, 5), # G to C, D, E\n\t\t\t\t\t\t\t\t\t\t (8, 4), (8, 5), (8, 6), # H to D, E, F\n\t\t\t\t\t\t\t\t\t\t (3, 4), (4, 5), (5, 6)] # C-D, D-E, E-F\n\ntype\n\tPeg = 1..8\n\tPegs = array[1..8, Peg]\n\n\nfunc valid(pegs: Pegs): bool =\n\tfor (src, dst) in Connections:\n\t\tif abs(pegs[src] - pegs[dst]) == 1:\n\t\t\treturn false\n\tresult = true\n\n\nproc print(pegs: Pegs; num: Positive) =\n\techo \"----- {num} -----\"\n\techo \" {pegs[1]} {pegs[2]}\"\n\techo \"{pegs[3]} {pegs[4]} {pegs[5]} {pegs[6]}\"\n\techo \" {pegs[7]} {pegs[8]}\"\n\techo()\n\n\nproc findSolution(pegs: var Pegs; left, right: Natural; solCount = 0): Natural =\n\tvar solCount = solCount\n\tif left == right:\n\t\tif pegs.valid():\n\t\t\tinc solCount\n\t\t\tpegs.print(solCount)\n\telse:\n\t\tfor i in left..right:\n\t\t\tswap pegs[left], pegs[i]\n\t\t\tsolCount = pegs.findSolution(left + 1, right, solCount)\n\t\t\tswap pegs[left], pegs[i]\n\tresult = solCount\n\n\nwhen isMainModule:\n\n\tvar pegs = [Peg 1, 2, 3, 4, 5, 6, 7, 8]\n\tdiscard pegs.findSolution(1, 8)\n" + }, + { + "id": 1047, + "length": 2043, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\ntype\n\tSolution = tuple[peg, over, land: int]\n\tBoard = array[16, bool]\n\n\nconst\n\tEmptyStart = 1\n\tJumpMoves = [@[],\n\t\t\t\t\t\t\t @[(2, 4), (3, 6)],\n\t\t\t\t\t\t\t @[(4, 7), (5, 9)],\n\t\t\t\t\t\t\t @[(5, 8), (6, 10)],\n\t\t\t\t\t\t\t @[(2, 1), (5, 6), (7, 11), (8, 13)],\n\t\t\t\t\t\t\t @[(8, 12), (9, 14)],\n\t\t\t\t\t\t\t @[(3, 1), (5, 4), (9, 13), (10, 15)],\n\t\t\t\t\t\t\t @[(4, 2), (8, 9)],\n\t\t\t\t\t\t\t @[(5, 3), (9, 10)],\n\t\t\t\t\t\t\t @[(5, 2), (8, 7)],\n\t\t\t\t\t\t\t @[(9, 8)],\n\t\t\t\t\t\t\t @[(12, 13)],\n\t\t\t\t\t\t\t @[(8, 5), (13, 14)],\n\t\t\t\t\t\t\t @[(8, 4), (9, 6), (12, 11), (14, 15)],\n\t\t\t\t\t\t\t @[(9, 5), (13, 12)],\n\t\t\t\t\t\t\t @[(10, 6), (14, 13)]]\n\n\nfunc initBoard(): Board =\n\tfor i in 1..15: result[i] = true\n\tresult[EmptyStart] = false\n\n\nproc draw(board: Board) =\n\tvar pegs: array[16, char]\n\tfor peg in pegs.mitems: peg = '-'\n\tfor i in 1..15:\n\t\tif board[i]:\n\t\t\tpegs[i] = i.toHex(1)[0]\n\techo \" $#\".format(pegs[1])\n\techo \" $# $#\".format(pegs[2], pegs[3])\n\techo \" $# $# $#\".format(pegs[4], pegs[5], pegs[6])\n\techo \" $# $# $# $#\".format(pegs[7], pegs[8], pegs[9], pegs[10])\n\techo \" $# $# $# $# $#\".format(pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])\n\n\nfunc solved(board: Board): bool = board.count(true) == 1\n\n\nproc solve(board: var Board; solutions: var seq[Solution]) =\n\tif board.solved: return\n\tfor peg in 1..15:\n\t\tif board[peg]:\n\t\t\tfor (over, land) in JumpMoves[peg]:\n\t\t\t\tif board[over] and not board[land]:\n\t\t\t\t\tlet saveBoard = board\n\t\t\t\t\tboard[peg] = false\n\t\t\t\t\tboard[over] = false\n\t\t\t\t\tboard[land] = true\n\t\t\t\t\tsolutions.add (peg, over, land)\n\t\t\t\t\tboard.solve(solutions)\n\t\t\t\t\tif board.solved: return # otherwise back-track.\n\t\t\t\t\tboard = saveBoard\n\t\t\t\t\tdiscard solutions.pop()\n\nvar board = initBoard()\nvar solutions: seq[Solution]\nboard.solve(solutions)\nboard = initBoard()\nboard.draw()\necho \"Starting with peg $# removed\\n\".format(EmptyStart.toHex(1))\nfor (peg, over, land) in solutions:\n\tboard[peg] = false\n\tboard[over] = false\n\tboard[land] = true\n\tboard.draw()\n\techo \"Peg $1 jumped over $2 to land on $3\\n\".format(peg.toHex(1), over.toHex(1), land.toHex(1))\n" + }, + { + "id": 1048, + "length": 2145, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils, sugar\n\ntype Point = tuple[x, y: int]\n\nfunc rotate90(p: Point): Point = (p.y, -p.x)\nfunc rotate180(p: Point): Point = (-p.x, -p.y)\nfunc rotate270(p: Point): Point = (-p.y, p.x)\nfunc reflect(p: Point): Point = (-p.x, p.y)\n\nfunc `$`(p: Point): string = \"($1, $2)\".format(p.x, p.y)\n\n\ntype Polyomino = seq[Point]\n\nfunc minima(poly: Polyomino): (int, int) =\n\t## Finds the min x and y coordinates of a polyomino.\n\t(min(poly.mapIt(it.x)), min(poly.mapIt(it.y)))\n\nfunc translateToOrigin(poly: Polyomino): Polyomino =\n\tlet (minX, minY) = poly.minima\n\tresult = sorted(poly.mapIt((it.x - minX, it.y - minY)))\n\nfunc rotationsAndReflections(poly: Polyomino): seq[Polyomino] =\n\t@[poly,\n\t\tpoly.mapIt(it.rotate90),\n\t\tpoly.mapIt(it.rotate180),\n\t\tpoly.mapIt(it.rotate270),\n\t\tpoly.mapIt(it.reflect),\n\t\tpoly.mapIt(it.rotate90.reflect),\n\t\tpoly.mapIt(it.rotate180.reflect),\n\t\tpoly.mapIt(it.rotate270.reflect)]\n\nfunc canonical(poly: Polyomino): Polyomino =\n\tsortedByIt(poly.rotationsAndReflections.map(translateToOrigin), $it)[0]\n\nfunc contiguous(p: Point): array[4, Point] =\n\t# Return all four points in Von Neumann neighborhood.\n\t[(p.x - 1, p.y), (p.x + 1, p.y), (p.x, p.y - 1), (p.x, p.y + 1)]\n\nfunc newPoints(poly: Polyomino): seq[Point] =\n\t## Return all distinct points that can be added to a Polyomino.\n\tresult = collect(newSeq):\n\t\t\t\t\t\t for point in poly:\n\t\t\t\t\t\t\t for pt in point.contiguous():\n\t\t\t\t\t\t\t\t if pt notin poly: pt\n\tresult = result.deduplicate()\n\nfunc newPolys(poly: Polyomino): seq[Polyomino] =\n\tcollect(newSeq, for pt in poly.newPoints: canonical(poly & pt))\n\nconst Monominoes = @[@[(x: 0, y: 0)]]\n\nfunc rank(n: Natural): seq[Polyomino] =\n\tif n == 0: return newSeq[Polyomino]()\n\tif n == 1: return Monominoes\n\tresult = collect(newSeq):\n\t\t\t\t\t\t for poly in rank(n - 1):\n\t\t\t\t\t\t\t for p in poly.newPolys(): p\n\tresult = sortedByIt(result, $it).deduplicate(true)\n\nwhen isMainModule:\n\n\tlet n = 5\n\techo \"All free polyominoes of rank $#:\\n\".format(n)\n\tfor poly in rank(n): echo poly.join(\" \")\n\n\tlet k = 10\n\techo \"\\nNumber of free polyominoes of ranks 1 to $#:\".format(k)\n\tfor i in 1..k: stdout.write rank(i).len, ' '\n\techo()\n" + }, + { + "id": 1049, + "length": 1648, + "source": "Rosetta Code", + "text": "import os, strformat\n\nconst LibXml = \"libxml2.so\"\n\ntype\n\tXmlSchemaParserCtxtPtr = pointer\n\tXmlSchemaPtr = pointer\n\tXmlSchemaValidCtxtPtr = pointer\n\n\n# Declaration of needed \"libxml2\" procedures.\n\nproc xmlSchemaNewParserCtxt(url: cstring): XmlSchemaParserCtxtPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaNewParserCtxt\".}\n\nproc xmlSchemaParse(ctxt: XmlSchemaParserCtxtPtr): XmlSchemaPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaParse\".}\n\nproc xmlSchemaFreeParserCtxt(ctxt: XmlSchemaParserCtxtPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaFreeParserCtxt\".}\n\nproc xmlSchemaNewValidCtxt(schema: XmlSchemaPtr): XmlSchemaValidCtxtPtr\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaNewValidCtxt\".}\n\nproc xmlSchemaValidateFile(ctxt: XmlSchemaValidCtxtPtr; filename: cstring; options: cint): cint\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaValidateFile\".}\n\nproc xmlSchemaFreeValidCtxt(ctxt: XmlSchemaValidCtxtPtr)\n\t{.cdecl, dynlib: LibXml, importc: \"xmlSchemaFreeValidCtxt\".}\n\n\nif paramCount() != 2:\n\tquit \"Usage: {getAppFilename().lastPathPart} 1000: break\nif index <= 1000:\n\techo \"Found two successive terms at index: \", index\nelse:\n\techo \"All consecutive terms up to the 1000th member have a GCD equal to one.\"\n" + }, + { + "id": 1054, + "length": 609, + "source": "Rosetta Code", + "text": "import std/sums\n\nfunc kahanSum[T](input: openArray[T]): T =\n\tvar c = T(0)\n\tfor val in input:\n\t\tlet y = val - c\n\t\tlet t = result + y\n\t\tc = (t - result) - y\n\t\tresult = t\n\ntemplate isOne[T](n: T): string =\n\tif n == 1: \"yes\" else: \"no\"\n\nvar epsilon = 1.0\nwhile 1 + epsilon != 1:\n\t\tepsilon = epsilon / 2\n\nlet a = 1.0\nlet b = epsilon\nlet c = -epsilon\n\necho \"Computing sum of 1.0, epsilon and -epsilon for epsilon = \", epsilon, '.'\necho \"Is result equal to 1.0?\"\necho \"- simple addition: \", (a + b + c).isOne\necho \"- using Kahan sum: \", kahanSum([a, b, c]).isOne\necho \"- using stdlib: \", sumKbn([a, b, c]).isOne\n" + }, + { + "id": 1055, + "length": 679, + "source": "Rosetta Code", + "text": "import strformat\n\nproc properDivisors(n: int) =\n\tvar count = 0\n\tfor i in 1.. 2:\n\t\tprod *= 2\n\tprod - 1\n\nfor i in 1..10:\n\twrite(stdout, fmt\"{i:2}: \")\n\tproperDivisors(i)\n\nvar max = 0\nvar maxI = 1\n\nfor i in 1..20000:\n\tvar v = countProperDivisors(i)\n\tif v >= max:\n\t\tmax = v\n\t\tmaxI = i\n\necho fmt\"{maxI} with {max} divisors\"\n" + }, + { + "id": 1056, + "length": 2146, + "source": "Rosetta Code", + "text": "import math\nimport strformat\nfrom strutils import addSep\nimport times\n\ntype\n\n\t# Classification categories.\n\tCategory = enum\n\t\tUnknown\n\t\tTerminating = \"terminating\"\n\t\tPerfect = \"perfect\"\n\t\tAmicable = \"amicable\"\n\t\tSociable = \"sociable\"\n\t\tAspiring = \"aspiring\"\n\t\tCyclic = \"cyclic\"\n\t\tNonTerminating = \"non-terminating\"\n\n\t# Aliquot sequence.\n\tAliquotSeq = seq[int]\n\nconst Limit = 2^47 # Limit beyond which the category is considered to be \"NonTerminating\".\n\n\nproc sumProperDivisors(n: int): int =\n\t## Compute the sum of proper divisors.*\n\n\tif n == 1: return 0\n\tresult = 1\n\tfor d in 2..sqrt(n.toFloat).int:\n\t\tif n mod d == 0:\n\t\t\tinc result, d\n\t\t\tif n div d != d:\n\t\t\t\tinc result, n div d\n\n\niterator aliquotSeq(n: int): int =\n\t## Yield the elements of the aliquot sequence of \"n\".\n\t## Stopped if the current value is null or equal to \"n\".\n\n\tvar k = n\n\twhile true:\n\t\tk = sumProperDivisors(k)\n\t\tyield k\n\n\nproc `$`(a: AliquotSeq): string =\n\t## Return the representation of an allquot sequence.\n\n\tfor n in a:\n\t\tresult.addSep(\", \", 0)\n\t\tresult.addInt(n)\n\n\nproc classification(n: int): tuple[cat: Category, values: AliquotSeq] =\n\t## Return the category of the aliquot sequence of a number \"n\" and the sequence itself.\n\n\tvar count = 0 # Number of elements currently generated.\n\tvar prev = n # Previous element in the sequence.\n\tresult.cat = Unknown\n\tfor k in aliquotSeq(n):\n\t\tinc count\n\t\tif k == 0:\n\t\t\tresult.cat = Terminating\n\t\telif k == n:\n\t\t\tresult.cat = case count\n\t\t\t\t\t\t\t\t\t of 1: Perfect\n\t\t\t\t\t\t\t\t\t of 2: Amicable\n\t\t\t\t\t\t\t\t\t else: Sociable\n\t\telif k > Limit or count > 16:\n\t\t\tresult.cat = NonTerminating\n\t\telif k == prev:\n\t\t\tresult.cat = Aspiring\n\t\telif k in result.values:\n\t\t\tresult.cat = Cyclic\n\t\tprev = k\n\t\tresult.values.add(k)\n\t\tif result.cat != Unknown:\n\t\t\tbreak\n\n\nlet t0 = getTime()\n\nfor n in 1..10:\n\tlet (cat, aseq) = classification(n)\n\techo fmt\"{n:14}: {cat:<20} {aseq}\"\n\necho \"\"\nfor n in [11, 12, 28, 496, 220, 1184, 12496, 1264460,\n\t\t\t\t\t790, 909, 562, 1064, 1488, 15355717786080.int]:\n\tlet (cat, aseq) = classification(n)\n\techo fmt\"{n:14}: {cat:<20} {aseq}\"\n\necho \"\"\necho fmt\"Processed in {(getTime() - t0).inMilliseconds} ms.\"\n" + }, + { + "id": 1057, + "length": 1533, + "source": "Rosetta Code", + "text": "import math, algorithm, lenientops, strformat, sequtils\n\ntype HeronianTriangle = tuple[a, b, c: int; p: int; area: int]\n\nfunc `$` (t: HeronianTriangle): string =\n\tfmt\"{t.a:3d}, {t.b:3d}, {t.c:3d} {t.p:7d} {t.area:8d}\"\n\nfunc hero(a, b, c: int): float =\n\tlet s = (a + b + c) / 2\n\tresult = sqrt(s * (s - a) * (s - b) * (s - c))\n\nfunc isHeronianTriangle(x: float): bool = x > 0 and ceil(x) == x\n\nfunc gcd(x, y: int): int =\n\tvar\n\t\t(dividend, divisor) = if x > y: (x, y) else: (y, x)\n\t\tremainder = dividend mod divisor\n\n\twhile remainder != 0:\n\t\tdividend = divisor\n\t\tdivisor = remainder\n\t\tremainder = dividend mod divisor\n\tresult = divisor\n\nfunc max(a, b, c: int): int = max(a, max(b, c))\nfunc gcd(a, b, c: int): int = gcd(a, gcd(b, c))\n\nconst Header = \" Sides Perimeter Area\\n------------- --------- ----\"\n\nvar list: seq[HeronianTriangle]\nconst Max = 200\n\nfor c in 1..Max:\n\tfor b in 1..c:\n\t\tfor a in 1..b:\n\t\t\tlet area = hero(a, b, c)\n\t\t\tif isHeronianTriangle(area) and gcd(a, b, c) == 1:\n\t\t\t\tlet t: HeronianTriangle = (a, b, c, a + b + c, area.toInt)\n\t\t\t\tlist.add(t)\n\necho \"Number of Heronian triangles: \", list.len\n\nlist.sort do (x, y: HeronianTriangle) -> int:\n\tresult = cmp(x.area, y.area)\n\tif result == 0:\n\t\tresult = cmp(x.p, y.p)\n\t\tif result == 0:\n\t\t\tresult = cmp(max(x.a, x.b, x.c), max(y.a, y.b, y.c))\n\necho \"\\nOrdered list of first ten Heronian triangles:\"\necho Header\nfor t in list[0 ..< 10]: echo t\n\necho \"\\nOrdered list of Heronian triangles with area 210:\"\necho Header\nfor t in list.filterIt(it.area == 210): echo t\n" + }, + { + "id": 1058, + "length": 995, + "source": "Rosetta Code", + "text": "proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int =\n\tvar localSwaps: int = swaps\n\tvar localHi: int = hi\n\tvar localLo: int = lo\n\tif localLo == localHi:\n\t\treturn swaps\n\n\tvar `high` = localHi\n\tvar `low` = localLo\n\tvar mid = (localHi - localLo) div 2\n\n\twhile localLo < localHi:\n\t\tif a[localLo] > a[localHi]:\n\t\t\tswap a[localLo], a[localHi]\n\t\t\tinc localSwaps\n\t\tinc localLo\n\t\tdec localHi\n\tif localLo == localHi:\n\t\tif a[localLo] > a[localHi + 1]:\n\t\t\tswap a[localLo], a[localHi + 1]\n\t\t\tinc localSwaps\n\n\tlocalswaps = a.innerCircleSort(`low`, `low` + mid, localSwaps)\n\tlocalSwaps = a.innerCircleSort(`low` + mid + 1, `high`, localSwaps)\n\tresult = localSwaps\n\nproc circleSort[T](a: var openArray[T]) =\n\twhile a.innerCircleSort(0, a.high, 0) != 0:\n\t\tdiscard\n\nvar arr = @[@[6, 7, 8, 9, 2, 5, 3, 4, 1],\n\t\t\t\t\t\t@[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]]\n\nfor i in 0..arr.high:\n\techo \"Original: \", $arr[i]\n\tarr[i].circleSort()\n\techo \"Sorted: \", $arr[i], if i != arr.high: \"\\n\" else: \"\"\n" + }, + { + "id": 1059, + "length": 1043, + "source": "Rosetta Code", + "text": "import arraymancer\n\nlet c = [\n\t\t\t\t\t[\n\t\t\t\t\t\t[1,2,3],\n\t\t\t\t\t\t[4,5,6]\n\t\t\t\t\t],\n\t\t\t\t\t[\n\t\t\t\t\t\t[11,22,33],\n\t\t\t\t\t\t[44,55,66]\n\t\t\t\t\t],\n\t\t\t\t\t[\n\t\t\t\t\t\t[111,222,333],\n\t\t\t\t\t\t[444,555,666]\n\t\t\t\t\t],\n\t\t\t\t\t[\n\t\t\t\t\t\t[1111,2222,3333],\n\t\t\t\t\t\t[4444,5555,6666]\n\t\t\t\t\t]\n\t\t\t\t].toTensor()\n\necho c\n# Tensor of shape 4x2x3 of type \"int\" on backend \"Cpu\"\n# | 1 2 3 | 11 22 33 | 111 222 333 | 1111 2222 3333|\n# | 4 5 6 | 44 55 66 | 444 555 666 | 4444 5555 6666|\n\nlet e = newTensor[bool]([2, 3])\n\necho e\n# Tensor of shape 2x3 of type \"bool\" on backend \"Cpu\"\n# |false false false|\n# |false false false|\n\nlet f = zeros[float]([4, 3])\n\necho f\n# Tensor of shape 4x3 of type \"float\" on backend \"Cpu\"\n# |0.0 0.0 0.0|\n# |0.0 0.0 0.0|\n# |0.0 0.0 0.0|\n# |0.0 0.0 0.0|\n\nlet g = ones[float]([4, 3])\n\necho g\n# Tensor of shape 4x3 of type \"float\" on backend \"Cpu\"\n# |1.0 1.0 1.0|\n# |1.0 1.0 1.0|\n# |1.0 1.0 1.0|\n# |1.0 1.0 1.0|\n" + }, + { + "id": 1060, + "length": 1625, + "source": "Rosetta Code", + "text": "import imageman\n\nconst\n\tN = 501 # Grid width and height.\n\tFG = ColorRGBU [byte 255, 255, 255]\n\tBG = ColorRGBU [byte 0, 0, 0]\n\ntype\n\tVec2 = tuple[x, y: int]\n\tGrid = array[N, array[N, int32]]\n\nconst Deltas: array[4, Vec2] = [(0, 1), (-1, 0), (0, -1), (1, 0)]\n\n\nproc `+`(v1, v2: Vec2): Vec2 =\n\t## Vector addition.\n\t(v1.x + v2.x, v1.y + v2.y)\n\n\nproc isPrime(n: Positive): bool =\n\t## Check if a number is prime.\n\tif n == 1: return false\n\tif (n and 1) == 0: return n == 2\n\tif (n mod 3) == 0: return n == 3\n\tvar delta = 2\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, delta\n\t\tdelta = 6 - delta\n\treturn true\n\n\nproc fill(grid: var Grid; start: Positive = 1) =\n\t## Fill the grid using Ulam algorithm.\n\n\ttemplate isEmpty(pos: Vec2): bool = grid[pos.x][pos.y] == 0\n\n\tlet start = start.int32\n\n\t# Fill the grid with successive numbers (as strings).\n\tvar pos: Vec2 = (N div 2, N div 2)\n\tgrid[pos.x][pos.y] = start\n\tvar currIdx = 3\n\tfor n in (start + 1)..<(start + N * N):\n\t\tlet nextIdx = (currIdx + 1) and 3\n\t\tvar nextPos = pos + Deltas[nextIdx]\n\t\tif nextPos.isEmpty():\n\t\t\t# Direction change is OK.\n\t\t\tcurrIdx = nextIdx\n\t\telse:\n\t\t\t# Continue in same direction.\n\t\t\tnextPos = pos + Deltas[currIdx]\n\t\tpos = move(nextPos)\n\t\tgrid[pos.x][pos.y] = n\n\nproc apply(img: var Image; grid: Grid) =\n\t## Fill the image with foreground pixel (for primes) or nothing (for composites).\n\tfor row in 0.. 1)\n\techo \"There are {countValid} words in '{Url}' \",\n\t\t\t \"which can be represented by the digit key mapping.\"\n\techo \"They require {mapping.len} digit combinations to represent them.\"\n\techo \"{textonyms.len} digit combinations represent Textonyms.\\n\"\n\n\tlet longest = textonyms.sortedByIt(-it[0].len)\n\tlet ambiguous = longest.sortedByIt(-it[1].len)\n\techo \"Top 8 in ambiguity:\\n\"\n\techo \"Count Textonym Words\"\n\techo \"====== ======== =====\"\n\tfor a in ambiguous[0..7]:\n\t\techo \"\"\"{a[1].len:4} {a[0]:>8} {a[1].join(\", \")}\"\"\"\n\n\techo \"\\nTop 6 in length:\\n\"\n\techo \"Length Textonym Words\"\n\techo \"====== ============== =====\"\n\tfor l in longest[0..5]:\n\t\techo \"\"\"{l[0].len:4} {l[0]:>14} {l[1].join(\", \")}\"\"\"\n\nprocessList(WordList)\n" + }, + { + "id": 1063, + "length": 1028, + "source": "Rosetta Code", + "text": "import algorithm, strformat, strutils, sugar\n\nconst MaxSum = 99\n\nfunc getPrimes(max: Positive): seq[int] =\n\tif max < 2: return\n\tresult.add 2\n\tfor n in countup(3, max, 2):\n\t\tblock check:\n\t\t\tfor p in result:\n\t\t\t\tif n mod p == 0:\n\t\t\t\t\tbreak check\n\t\t\tresult.add n\n\nlet primes = getPrimes(MaxSum)\n\nvar descendants, ancestors = newSeq[seq[int]](MaxSum + 1)\n\nfor p in primes:\n\tdescendants[p].add p\n\tfor s in 1..(descendants.high - p):\n\t\tdescendants[s + p].add collect(newSeq, for pr in descendants[s]: p * pr)\n\nfor p in primes & 4:\n\tdiscard descendants[p].pop()\n\nvar total = 0\nfor s in 1..MaxSum:\n\tdescendants[s].sort()\n\tfor d in descendants[s]:\n\t\tif d > MaxSum: break\n\t\tancestors[d] = ancestors[s] & s\n\tlet dlength = descendants[s].len\n\techo \"[{s}] Level: {ancestors[s].len}\"\n\techo \"Ancestors: \", if ancestors[s].len != 0: ancestors[s].join(\" \") else: \"None\"\n\techo \"Descendants: \", if dlength != 0: $dlength else: \"None\"\n\tif dlength != 0: echo descendants[s].join(\", \")\n\techo \"\"\n\tinc total, dlength\n\necho \"Total descendants: \", total\n" + }, + { + "id": 1064, + "length": 1205, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\tDigitRange = '0'..'9'\n\tUpperCaseRange = 'A'..'Z'\n\ntype ISINError = object of ValueError\n\n\nproc luhn(s: string): bool =\n\tconst m = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n\tvar sum = 0\n\tvar odd = true\n\tfor i in countdown(s.high, 0):\n\t\tlet digit = ord(s[i]) - ord('0')\n\t\tsum += (if odd: digit else: m[digit])\n\t\todd = not odd\n\tresult = sum mod 10 == 0\n\n\nproc validateISIN(s: string) =\n\tif s.len != 12:\n\t\traise newException(ISINError, \"wrong length\")\n\tif s[0] notin UpperCaseRange or s[1] notin UpperCaseRange:\n\t\traise newException(ISINError, \"wrong country code\")\n\tif s[11] notin DigitRange:\n\t\traise newException(ISINError, \"wrong checksum character\")\n\tvar t: string\n\tfor ch in s:\n\t\tcase ch\n\t\tof '0'..'9': t.add ch\n\t\tof 'A'..'Z': t.addInt ord(ch) - ord('A') + 10\n\t\telse: raise newException(ISINError, \"invalid characters in code\")\n\tif not t.luhn():\n\t\traise newException(ISINError, \"checksum error\")\n\n\nwhen isMainModule:\n\n\tfor isin in [\"US0378331005\", \"US0373831005\", \"U50378331005\",\n\t\t\t\t\t\t\t \"US03378331005\", \"AU0000XVGZA3\", \"AU0000VXGZA3\", \"FR0000988040\"]:\n\t\ttry:\n\t\t\tisin.validateISIN()\n\t\t\techo \"{isin} is valid.\"\n\t\texcept ISINError:\n\t\t\techo \"{isin} is not valid: {getCurrentExceptionMsg()}.\"\n" + }, + { + "id": 1065, + "length": 929, + "source": "Rosetta Code", + "text": "import parseutils, strutils, algorithm\n\ntype FactorAndWord = tuple[factor:int, word: string]\n\nvar number: int\nvar factorAndWords: array[3, FactorAndWord]\n\n#custom comparison proc for the FactorAndWord type\nproc customCmp(x,y: FactorAndWord): int =\n\tif x.factor < y.factor:\n\t\t-1\n\telif x.factor > y.factor:\n\t\t1\n\telse:\n\t\t0\n\necho \"Enter max number:\"\nvar input = readLine(stdin)\ndiscard parseInt(input, number)\n\nfor i in 0..2:\n\n\techo \"Enter a number and word separated by space:\"\n\tvar input = readLine(stdin)\n\n\tvar tokens = input.split\n\tdiscard parseInt(tokens[0], factorAndWords[i].factor)\n\tfactorAndWords[i].word = tokens[1]\n\n#sort factors in ascending order\nsort(factorAndWords, customCmp)\n\n#implement fiz buz\nfor i in 1..number:\n\tvar written = false;\n\tfor item in items(factorAndWords):\n\t\tif i mod item.factor == 0 :\n\t\t\twrite(stdout, item.word)\n\t\t\twritten = true\n\tif written :\n\t\twrite(stdout, \"\\n\")\n\telse :\n\t\twriteLine(stdout, i)\n" + }, + { + "id": 1066, + "length": 604, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils\n\nfunc lcp(list: varargs[string]): string =\n\tif list.len == 0: return\n\tresult = list[0]\n\tfor i in 1..list.high:\n\t\tvar newLength = 0\n\t\tfor j in 0..result.high:\n\t\t\tif j >= list[i].len or list[i][j] != result[j]:\n\t\t\t\tbreak\n\t\t\tinc newLength\n\t\tresult.setLen(newLength)\n\nproc test(list: varargs[string]) =\n\tlet lst = list.mapIt('\"' & it & '\"').join(\", \")\n\techo \"lcp({lst}) = \\\"{lcp(list)}\\\"\"\n\n\ntest(\"interspecies\", \"interstellar\", \"interstate\")\ntest(\"throne\", \"throne\")\ntest(\"throne\", \"dungeon\")\ntest(\"cheese\")\ntest(\"\")\ntest()\ntest(\"prefix\", \"suffix\")\ntest(\"foo\", \"foobar\")\n" + }, + { + "id": 1067, + "length": 906, + "source": "Rosetta Code", + "text": "import strformat\n\ntype Vec2[T: SomeNumber] = tuple[x, y: T]\n\nproc initVec2[T](x, y: T): Vec2[T] = (x, y)\n\nfunc`+`[T](a, b: Vec2[T]): Vec2[T] = (a.x + b.x, a.y + b.y)\n\nfunc `-`[T](a, b: Vec2[T]): Vec2[T] = (a.x - b.x, a.y - b.y)\n\nfunc `*`[T](a: Vec2[T]; m: T): Vec2[T] = (a.x * m, a.y * m)\n\nfunc `/`[T](a: Vec2[T]; d: T): Vec2[T] =\n\tif d == 0:\n\t\traise newException(DivByZeroDefect, \"division of vector by 0\")\n\twhen T is SomeInteger:\n\t\t(a.x div d, a.y div d)\n\telse:\n\t\t(a.x / d, a.y / d)\n\nfunc `$`[T](a: Vec2[T]): string =\n\t\"({a.x}, {a.y})\"\n\n# Three ways to initialize a vector.\nlet v1 = initVec2(2, 3)\nlet v2: Vec2[int] = (-1, 2)\nlet v3 = (x: 4, y: -2)\n\necho \"{v1} + {v2} = {v1 + v2}\"\necho \"{v3} - {v2} = {v3 - v2}\"\n\n# Float vectors.\nlet v4 = initVec2(2.0, 3.0)\nlet v5 = (x: 3.0, y: 2.0)\n\necho \"{v4} * 2 = {v4 * 2}\"\necho \"{v3} / 2 = {v3 / 2}\" # Int division.\necho \"{v5} / 2 = {v5 / 2}\" # Float division.\n" + }, + { + "id": 1068, + "length": 952, + "source": "Rosetta Code", + "text": "# Brute force approach\n\nimport times\n\n# assumes an array of non-decreasing positive integers\nproc binarySearch(a : openArray[int], target : int) : int =\n\tvar left, right, mid : int\n\tleft = 0\n\tright = len(a) - 1\n\twhile true :\n\t\tif left > right : return 0 # no match found\n\t\tmid = (left + right) div 2\n\t\tif a[mid] < target :\n\t\t\tleft = mid + 1\n\t\telif a[mid] > target :\n\t\t\tright = mid - 1\n\t\telse :\n\t\t\treturn mid # match found\n\nvar\n\tp5 : array[250, int]\n\tsum = 0\n\ty, t1 : int\n\nlet t0 = cpuTime()\n\nfor i in 1 .. 249 :\n\tp5[i] = i * i * i * i * i\n\nfor x0 in 1 .. 249 :\n\tfor x1 in 1 .. x0 - 1 :\n\t\tfor x2 in 1 .. x1 - 1 :\n\t\t\tfor x3 in 1 .. x2 - 1 :\n\t\t\t\tsum = p5[x0] + p5[x1] + p5[x2] + p5[x3]\n\t\t\t\ty = binarySearch(p5, sum)\n\t\t\t\tif y > 0 :\n\t\t\t\t\tt1 = int((cputime() - t0) * 1000.0)\n\t\t\t\t\techo \"Time : \", t1, \" milliseconds\"\n\t\t\t\t\techo $x0 & \"^5 + \" & $x1 & \"^5 + \" & $x2 & \"^5 + \" & $x3 & \"^5 = \" & $y & \"^5\"\n\t\t\t\t\tquit()\n\nif y == 0 :\n\techo \"No solution was found\"\n" + }, + { + "id": 1069, + "length": 1085, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\ntype SquareMatrix = seq[seq[Natural]]\n\nfunc newSquareMatrix(n: Positive): SquareMatrix =\n\t## Create a square matrix.\n\tnewSeqWith(n, newSeq[Natural](n))\n\nfunc pascalUpperTriangular(n: Positive): SquareMatrix =\n\t## Create an upper Pascal matrix.\n\tresult = newSquareMatrix(n)\n\tfor i in 0.. list of factors.\n\n# Build the factor mapping.\nfor i in 0.. For every decomposition of S, there is no product with a single decomposition.\nfor s in toSeq(sums):\n\tfor (x, y) in s.terms():\n\t\tlet p = x * y\n\t\tif factors[p].len == 1:\n\t\t\tsums.excl s\n\t\t\tbreak\n\n# P says \"Now I know X and Y.\"\n# => P has only one decomposition with sum in \"sums\".\nfor p in toSeq(factors.keys):\n\tvar sums = collect(initHashSet):\n\t\t\t\t\t\t\t for (x, y) in factors[p]:\n\t\t\t\t\t\t\t\t if x + y in sums: {x + y}\n\tif card(sums) > 1: factors.del p\n\n# S says \"Now I also know X and Y.\"\n# => S has only one decomposition with product in \"factors\".\nfor s in toSeq(sums):\n\tvar prods = collect(initHashSet):\n\t\t\t\t\t\t\t\tfor (x, y) in s.terms():\n\t\t\t\t\t\t\t\t\tif x * y in factors: {x * y}\n\tif card(prods) > 1: sums.excl s\n\n# Now, combine the sums and the products.\nfor s in sums:\n\tfor (x, y) in s.terms:\n\t\tif x * y in factors: echo (x, y)\n" + }, + { + "id": 1073, + "length": 1623, + "source": "Rosetta Code", + "text": "import algorithm, deques, random, sequtils, strutils\n\nproc riffle(deck: seq[int]; iterations: Positive): seq[int] =\n\tresult = deck\n\n\tfor _ in 1..iterations:\n\t\tlet mid = deck.len div 2\n\t\tlet tenPc = mid div 10\n\t\t# Choose a random number within 10% of midpoint.\n\t\tlet cut = mid - tenPc + rand(2 * tenPc)\n\t\t# Split deck into two at cut point.\n\t\tvar deck1 = result[0.. 0 and deck2.len > 0:\n\t\t\tif fromTop:\n\t\t\t\tresult.add deck1.popFirst\n\t\t\t\tresult.add deck2.popFirst\n\t\t\telse:\n\t\t\t\tresult.add deck1.popLast\n\t\t\t\tresult.add deck2.popLast\n\t\t# Add any remaining cards to the pile and reverse it.\n\t\tif deck1.len > 0: result.add deck1.toSeq\n\t\telif deck2.len > 0: result.add deck2.toSeq\n\t\tresult.reverse()\n\nproc overhand(deck: seq[int]; iterations: Positive): seq[int] =\n\tresult = deck\n\tvar pile: seq[int]\n\tlet twentyPc = deck.len div 5\n\tfor _ in 1..iterations:\n\t\twhile result.len > 0:\n\t\t\tlet cards = min(result.len, rand(1..twentyPc))\n\t\t\tpile.insert result[0..= 0:\n\t\tlet A = i.mem[i.ip]\n\t\tlet B = i.mem[i.ip+1]\n\t\tlet C = i.mem[i.ip+2]\n\t\ti.ip += 3\n\t\tif A == -1:\n\t\t\ti.mem[B] = ord(i.input.readChar)\n\t\telif B == -1:\n\t\t\ti.output.write(chr(i.mem[A]))\n\t\telse:\n\t\t\ti.mem[B] -= i.mem[A]\n\t\t\tif i.mem[B] <= 0:\n\t\t\t\ti.ip = C\n\nlet test = @[15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1,\n\t\t\t\t\t\t 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0]\nvar intr = load(test, newFileStream(stdin), newFileStream(stdout))\n\ntry:\n\tintr.run()\nexcept IndexDefect:\n\techo \"ip: \", intr.ip\n\techo \"mem: \", intr.mem\n" + }, + { + "id": 1075, + "length": 712, + "source": "Rosetta Code", + "text": "import strformat\n\nvar coconuts = 11\n\nfor ns in 2..9:\n\tvar hidden = newSeq[int](ns)\n\tcoconuts = (coconuts div ns) * ns + 1\n\tblock Search:\n\t\twhile true:\n\t\t\tvar nc = coconuts\n\t\t\tfor sailor in 1..ns:\n\t\t\t\tif nc mod ns == 1:\n\t\t\t\t\thidden[sailor-1] = nc div ns\n\t\t\t\t\tdec nc, hidden[sailor-1] + 1\n\t\t\t\t\tif sailor == ns and nc mod ns == 0:\n\t\t\t\t\t\techo \"{ns} sailors require a minimum of {coconuts} coconuts.\"\n\t\t\t\t\t\tfor t in 1..ns:\n\t\t\t\t\t\t\techo \"\\tSailor {t} hides {hidden[t-1]}.\"\n\t\t\t\t\t\techo \"\\tThe monkey gets {ns}.\"\n\t\t\t\t\t\techo \"\\tFinally, each sailor takes {nc div ns}.\\n\"\n\t\t\t\t\t\tbreak Search # Done. Continue with more sailors or exit.\n\t\t\t\telse:\n\t\t\t\t\tbreak # Failed. Continue search with more coconuts.\n\t\t\tinc coconuts, ns\n" + }, + { + "id": 1076, + "length": 567, + "source": "Rosetta Code", + "text": "import os, strutils\n\nfunc extractFileExt(path: string): string =\n\tvar s: seq[char]\n\tfor i in countdown(path.high, 0):\n\t\tcase path[i]\n\t\tof Letters, Digits:\n\t\t\ts.add path[i]\n\t\tof '.':\n\t\t\ts.add '.'\n\t\t\twhile s.len > 0: result.add s.pop()\n\t\t\treturn\n\t\telse:\n\t\t\tbreak\n\tresult = \"\"\n\nfor input in [\"http://example.com/download.tar.gz\", \"CharacterModel.3DS\",\n\t\t\t\t\t\t\t\".desktop\", \"document\", \"document.txt_backup\", \"/etc/pam.d/login\"]:\n\techo \"Input: \", input\n\techo \"Extracted extension: \", input.extractFileExt()\n\techo \"Using standard library: \", input.splitFile()[2]\n\techo()\n" + }, + { + "id": 1077, + "length": 1941, + "source": "Rosetta Code", + "text": "import math\nimport sdl2\n\nconst\n\tWidth = 500\n\tHeight = 500\n\tOffset = 500 / 2\n\nvar nodes = [(x: -100.0, y: -100.0, z: -100.0),\n\t\t\t\t\t\t (x: -100.0, y: -100.0, z: 100.0),\n\t\t\t\t\t\t (x: -100.0, y: 100.0, z: -100.0),\n\t\t\t\t\t\t (x: -100.0, y: 100.0, z: 100.0),\n\t\t\t\t\t\t (x: 100.0, y: -100.0, z: -100.0),\n\t\t\t\t\t\t (x: 100.0, y: -100.0, z: 100.0),\n\t\t\t\t\t\t (x: 100.0, y: 100.0, z: -100.0),\n\t\t\t\t\t\t (x: 100.0, y: 100.0, z: 100.0)]\n\nconst Edges = [(a: 0, b: 1), (a: 1, b: 3), (a: 3, b: 2), (a: 2, b: 0),\n\t\t\t\t\t\t\t (a: 4, b: 5), (a: 5, b: 7), (a: 7, b: 6), (a: 6, b: 4),\n\t\t\t\t\t\t\t (a: 0, b: 4), (a: 1, b: 5), (a: 2, b: 6), (a: 3, b: 7)]\n\nvar\n\twindow: WindowPtr\n\trenderer: RendererPtr\n\tevent: Event\n\tendSimulation = false\n\n\nproc rotateCube(angleX, angleY: float) =\n\tlet\n\t\tsinX = sin(angleX)\n\t\tcosX = cos(angleX)\n\t\tsinY = sin(angleY)\n\t\tcosY = cos(angleY)\n\n\tfor node in nodes.mitems:\n\t\tvar (x, y, z) = node\n\t\tnode.x = x * cosX - z * sinX\n\t\tnode.z = z * cosX + x * sinX\n\t\tz = node.z\n\t\tnode.y = y * cosY - z * sinY\n\t\tnode.z = z * cosY + y * sinY\n\n\nproc pollQuit(): bool =\n\twhile pollEvent(event):\n\t\tif event.kind == QuitEvent:\n\t\t\treturn true\n\n\nproc drawCube(): bool =\n\tvar rect: Rect = (cint(0), cint(0), cint(Width), cint(Height))\n\trotateCube(PI / 4, arctan(sqrt(2.0)))\n\tfor frame in 0..359:\n\t\trenderer.setDrawColor((0u8, 0u8, 0u8, 255u8))\n\t\trenderer.fillRect(addr(rect))\n\t\trenderer.setDrawColor((0u8, 220u8, 0u8, 255u8))\n\t\tfor edge in Edges:\n\t\t\tlet xy1 = nodes[edge.a]\n\t\t\tlet xy2 = nodes[edge.b]\n\t\t\trenderer.drawLine(cint(xy1.x + Offset), cint(xy1.y + Offset),\n\t\t\t\t\t\t\t\t\t\t\t\tcint(xy2.x + Offset), cint(xy2.y + Offset))\n\t\trotateCube(PI / 180, 0)\n\t\trenderer.present()\n\t\tif pollQuit(): return true\n\t\tdelay 10\n\n\nif sdl2.init(INIT_EVERYTHING) == SdlError:\n\tquit(QuitFailure)\n\nwindow = createWindow(\"Rotating cube\", 10, 10, 500, 500, 0)\nrenderer = createRenderer(window, -1, Renderer_Accelerated)\n\nwhile not endSimulation:\n\tendSimulation = drawCube()\nwindow.destroy()\n" + }, + { + "id": 1078, + "length": 1967, + "source": "Rosetta Code", + "text": "import os, strformat, strutils\n\ntype\n\tTree = int\n\tTrees = object\n\t\tlist: seq[Tree]\n\t\toffsets: array[32, int]\n\n\nfunc isOdd(n: int): bool = (n and 1) != 0\n\n\nfunc append(trees: var Trees; tree: Tree) =\n\ttrees.list.add(1 or tree shl 1)\n\n\nproc show(tree: Tree; n: int) =\n\tvar tree = tree\n\tvar n = n\n\twhile n > 0:\n\t\tdec n\n\t\tstdout.write if tree.isOdd: '(' else: ')'\n\t\ttree = tree shr 1\n\tstdout.write '\\n'\n\n\nproc print(trees: Trees; n: int) =\n\tfor i in trees.offsets[n].. rem:\n\t\ts = rem\n\t\tp = trees.offsets[s]\n\telif p >= trees.offsets[s + 1]:\n\t\t# Used up sl-trees, try smaller ones.\n\t\tdec s\n\t\tif s == 0: return\n\t\tp = trees.offsets[s]\n\n\ttrees.assemble(n, t shl ( 2 * s) or trees.list[p], s, p, rem - s)\n\ttrees.assemble(n, t, s, p + 1, rem)\n\n\nfunc make(trees: var Trees; n: int) =\n\tif trees.offsets[n + 1] != 0: return\n\tif n > 0: trees.make(n - 1)\n\ttrees.assemble(n, 0, n - 1, trees.offsets[n - 1], n - 1)\n\ttrees.offsets[n + 1] = trees.list.len\n\n\nwhen isMainModule:\n\n\tif paramCount() != 1:\n\t\traise newException(ValueError, \"there must be exactly one command line argument\")\n\tlet n = try:\n\t\t\t\t\t\tparamStr(1).parseInt()\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\traise newException(ValueError, \"argument is not a valid number\")\n\t# Insure \"n\" is limited to 12 to avoid overflowing default stack.\n\tif n notin 1..12:\n\t\traise newException(ValueError, \"argument must be between 1 and 12\")\n\n\t# Init 1-tree.\n\tvar trees: Trees\n\ttrees.offsets[1] = 1\n\ttrees.append(0)\n\n\ttrees.make(n)\n\techo \"Number of {n}-trees: {trees.offsets[n + 1] - trees.offsets[n]}\"\n\ttrees.print(n)\n" + }, + { + "id": 1079, + "length": 3441, + "source": "Rosetta Code", + "text": "import random, strformat, strutils\n\ntype Adjacent = array[3, int]\n\nconst Cave: array[1..20, Adjacent] =\n\t\t[ 1: [2, 3, 4], 2: [1, 5, 6], 3: [1, 7, 8], 4: [1, 9, 10],\n\t\t\t5: [2, 9, 11], 6: [2, 7, 12], 7: [3, 6, 13], 8: [3, 10, 14],\n\t\t\t9: [4, 5, 15], 10: [4, 8, 16], 11: [5, 12, 17], 12: [6, 11, 18],\n\t\t 13: [7, 14, 18], 14: [8, 13, 19], 15: [9, 16, 17], 16: [10, 15, 19],\n\t\t 17: [11, 20, 15], 18: [12, 13, 20], 19: [14, 16, 20], 20: [17, 18, 19]]\n\ntype Game = object\n\tplayer: int\n\twumpus: int\n\tbat1: int\n\tbat2: int\n\tpit1: int\n\tpit2: int\n\tarrows: int\n\n\nproc initGame(): Game =\n\tresult.player = 1\n\tresult.wumpus = rand(2..20)\n\tresult.bat1 = rand(2..20)\n\twhile true:\n\t\tresult.bat2 = rand(2..20)\n\t\tif result.bat2 != result.bat1: break\n\twhile true:\n\t\tresult.pit1 = rand(2..20)\n\t\tif result.pit1 notin [result.bat1, result.bat2]: break\n\twhile true:\n\t\tresult.pit2 = rand(2..20)\n\t\tif result.pit2 notin [result.bat1, result.bat2, result.pit1]: break\n\tresult.arrows = 5\n\n\nfunc isEmpty(game: Game; room: int): bool =\n\troom notin [game.player, game.wumpus, game.bat1, game.bat2, game.pit1, game.pit2]\n\n\n\nproc sense(game: Game; adj: Adjacent) =\n\tvar bat, pit = false\n\tfor ar in adj:\n\t\tif ar == game.wumpus:\n\t\t\techo \"You smell something terrible nearby.\"\n\t\tif ar in [game.bat1, game.bat2]:\n\t\t\tif not bat:\n\t\t\t\techo \"You hear a rustling.\"\n\t\t\t\tbat = true\n\t\telif ar in [game.pit1, game.pit2]:\n\t\t\tif not pit:\n\t\t\t\techo \"You feel a cold wind blowing from a nearby cavern.\"\n\t\t\t\tpit = true\n\techo()\n\n\nfunc plural(n: int): string =\n\tif n > 1: \"s\" else: \"\"\n\n\nproc play(game: var Game) =\n\n\twhile true:\n\n\t\techo \"\\nYou are in room {game.player} with {game.arrows} arrow{plural(game.arrows)} left\"\n\t\tlet adj = Cave[game.player]\n\t\techo \"The adjacent rooms are \", adj.join(\", \")\n\t\tgame.sense(adj)\n\n\t\tvar room: int\n\t\twhile true:\n\t\t\tstdout.write \"Choose an adjacent room: \"\n\t\t\tstdout.flushFile()\n\t\t\ttry:\n\t\t\t\troom = stdin.readLine().parseInt()\n\t\t\t\tif room notin adj:\n\t\t\t\t\traise newException(ValueError, \"\")\n\t\t\t\tbreak\n\t\t\texcept ValueError:\n\t\t\t\techo \"Invalid response, try again\"\n\t\t\texcept EOFError:\n\t\t\t\tquit \"\\nEnd of file encountered; quitting.\", QuitFailure\n\n\t\tvar action: char\n\t\twhile true:\n\t\t\tstdout.write \"Walk or shoot (w/s): \"\n\t\t\tstdout.flushFile()\n\t\t\ttry:\n\t\t\t\tlet reply = stdin.readLine()\n\t\t\t\tif reply.len != 1 or reply[0] notin ['w', 's']:\n\t\t\t\t\techo \"Invalid response, try again\"\n\t\t\t\taction = reply[0]\n\t\t\t\tbreak\n\t\t\texcept EOFError:\n\t\t\t\tquit \"\\nEnd of file encountered; quitting.\", QuitFailure\n\n\t\tif action == 'w':\n\t\t\tgame.player = room\n\t\t\tif game.player == game.wumpus:\n\t\t\t\techo \"You have been eaten by the Wumpus and lost the game!\"\n\t\t\t\treturn\n\t\t\tif game.player in [game.pit1, game.pit2]:\n\t\t\t\techo \"You have fallen down a bottomless pit and lost the game!\"\n\t\t\t\treturn\n\t\t\tif game.player in [game.bat1, game.bat2]:\n\t\t\t\twhile true:\n\t\t\t\t\troom = rand(2..20)\n\t\t\t\t\tif game.isEmpty(room):\n\t\t\t\t\t\techo \"A bat has transported you to a random empty room\"\n\t\t\t\t\t\tgame.player = room\n\t\t\t\t\t\tbreak\n\n\t\telse:\n\t\t\tif room == game.wumpus:\n\t\t\t\techo \"You have killed the Wumpus and won the game!!\"\n\t\t\t\treturn\n\t\t\tlet chance = rand(3)\n\t\t\tif chance > 0:\n\t\t\t\tgame.wumpus = Cave[game.wumpus].sample()\n\t\t\t\tif game.player == game.wumpus:\n\t\t\t\t\techo \"You have been eaten by the Wumpus and lost the game!\"\n\t\t\t\t\treturn\n\t\t\tdec game.arrows\n\t\t\tif game.arrows == 0:\n\t\t\t\techo \"You have run out of arrows and lost the game!\"\n\t\t\t\treturn\n\n\nrandomize()\nvar game = initGame()\ngame.play()\n" + }, + { + "id": 1080, + "length": 1554, + "source": "Rosetta Code", + "text": "type\n\tPoint = object\n\t\tx: float\n\t\ty: float\n\n# Calculate orientation for 3 points\n# 0 -> Straight line\n# 1 -> Clockwise\n# 2 -> Counterclockwise\nproc orientation(p, q, r: Point): int =\n\tlet val = (q.y - p.y) * (r.x - q.x) -\n\t\t(q.x - p.x) * (r.y - q.y)\n\n\tif val == 0: 0\n\telif val > 0: 1\n\telse: 2\n\nproc calculateConvexHull(points: openArray[Point]): seq[Point] =\n\tresult = newSeq[Point]()\n\n\t# There must be at least 3 points\n\tif len(points) < 3:\n\t\tfor i in points: result.add(i)\n\n\t# Find the leftmost point\n\tvar indexMinX = 0\n\tfor i, _ in points:\n\t\tif points[i].x < points[indexMinX].x:\n\t\t\tindexMinX = i\n\n\tvar p = indexMinX\n\tvar q = 0\n\n\twhile true:\n\t\t# The leftmost point must be part of the hull.\n\t\tresult.add(points[p])\n\n\t\tq = (p + 1) mod len(points)\n\n\t\tfor i in 0.. parent node id.\n\t\tlastLevel: seq[Id] # List of node ids in current last level.\n\n\nfunc initTree(): Tree =\n\t## Return an initialized tree.\n\tconst Root = Id(1)\n\tTree(parents: {Root: Id(0)}.toTable, lastLevel: @[Root])\n\n\nfunc path(tree: var Tree; id: Id): seq[Id] =\n\t## Return the path to node with given id.\n\n\tif id == 0: return\n\n\twhile id notin tree.parents:\n\t\t# Node \"id\" not yet present in the tree: build a new level.\n\t\tvar newLevel: seq[Id]\n\t\tfor x in tree.lastLevel:\n\t\t\tfor y in tree.path(x):\n\t\t\t\tlet newId = x + y\n\t\t\t\tif newId in tree.parents: break # Node already created.\n\t\t\t\t# Create a new node.\n\t\t\t\ttree.parents[newId] = x\n\t\t\t\tnewLevel.add newId\n\t\ttree.lastLevel = move(newLevel)\n\n\t# Node path is the concatenation of parent node path and node id.\n\tresult = tree.path(tree.parents[id]) & id\n\n\nfunc treePow[T: SomeNumber | Int](tree: var Tree; x: T; n: Natural): T =\n\t## Compute x^n using the power tree.\n\tlet one = when T is Int: newInt(1) else: T(1)\n\tvar results = {0: one, 1: x}.toTable # Intermediate and last results.\n\tvar k = 0\n\tfor i in tree.path(n):\n\t\tresults[i] = results[i - k] * results[k]\n\t\tk = i\n\treturn results[n]\n\n\nproc showPow[T: SomeNumber | Int](tree: var Tree; x: T; n: Natural) =\n\techo n, \" -> \", ($tree.path(n))[1..^1]\n\tlet result = tree.treePow(x, n)\n\techo x, \"^\", n, \" = \", result\n\n\nwhen isMainModule:\n\n\tvar tree = initTree()\n\tfor n in 0..17: tree.showPow(2, n)\n\techo \"\"\n\ttree.showPow(1.1, 81)\n\techo \"\"\n\ttree.showPow(newInt(3), 191)\n" + }, + { + "id": 1082, + "length": 854, + "source": "Rosetta Code", + "text": "import strformat\n\ntype Polynomial = seq[int]\n\nfunc `$`(p: Polynomial): string = system.`$`(p)[1..^1]\n\nfunc extendedSyntheticDivision(dividend, divisor: Polynomial): tuple[q, r: Polynomial] =\n\t\tvar res = dividend\n\t\tlet normalizer = divisor[0]\n\t\tlet separator = dividend.len - divisor.len\n\t\tfor i in 0..separator:\n\t\t\tres[i] = res[i] div normalizer\n\t\t\tlet coef = res[i]\n\t\t\tif coef != 0:\n\t\t\t\tfor j in 1..divisor.high:\n\t\t\t\t\tres[i + j] += -divisor[j] * coef\n\t\tresult = (res[0..separator], res[(separator+1)..^1])\n\nwhen isMainModule:\n\techo \"Polynomial synthetic division\"\n\tlet n1 = @[1, -12, 0, -42]\n\tlet d1 = @[1, -3]\n\tlet (q1, r1) = extendedSyntheticDivision(n1, d1)\n\techo \"{n1} / {d1} = {q1}, remainder {r1}\"\n\tlet n2 = @[1, 0, 0, 0, -2]\n\tlet d2 = @[1, 1, 1, 1]\n\tlet (q2, r2) = extendedSyntheticDivision(n2, d2)\n\techo \"{n2} / {d2} = {q2}, remainder {r2}\"\n" + }, + { + "id": 1083, + "length": 1053, + "source": "Rosetta Code", + "text": "import times\n\nlet t0 = cpuTime()\n\n# Build list of primes.\n\nconst\n\tNPrimes = 1_000_000\n\tN = 16 * NPrimes\n\nvar sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.\n\nfor i, composite in sieve:\n\tif not composite:\n\t\tlet n = 2 * i + 3\n\t\tfor k in countup(n * n, N, 2 * n):\n\t\t\tsieve[(k - 3) div 2] = true\n\nvar primes = @[2]\nfor i, composite in sieve:\n\tif not composite:\n\t\tprimes.add 2 * i + 3\n\nif primes.len < NPrimes:\n\tquit \"Not enough primes. Please, increase value of N.\"\n\n\n# Compute primorial.\n\nimport strformat\nimport bignum\n\nconst LastToPrint = NPrimes\n\niterator primorials(): Int =\n\t## Yield successive primorial numbers.\n\tvar prim = newInt(1)\n\tyield prim\n\tfor p in primes:\n\t\tprim *= p\n\t\tyield prim\n\nvar n = 0\nfor prim in primorials():\n\techo \"primorial({n}) = {prim}\"\n\tinc n\n\tif n == 10: break\n\nn = 0\nvar nextToPrint = 10\nfor prim in primorials():\n\tif n == nextToPrint:\n\t\techo \"primorial({n}) has {($prim).len} digits\"\n\t\tif nextToPrint == LastToPrint: break\n\t\tnextToPrint *= 10\n\tinc n\n\necho \"\"\necho \"Total time: {cpuTime() - t0:.2f} s\"\n" + }, + { + "id": 1084, + "length": 1326, + "source": "Rosetta Code", + "text": "import std/monotimes\n\nlet t0 = getMonoTime()\n\n# Build list of primes.\n\nconst\n\tNPrimes = 1_000_000\n\tN = 16 * NPrimes\n\nvar sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.\n\nfor i, composite in sieve:\n\tif not composite:\n\t\tlet n = 2 * i + 3\n\t\tfor k in countup(n * n, N, 2 * n):\n\t\t\tsieve[(k - 3) div 2] = true\n\nvar primes = @[2]\nfor i, composite in sieve:\n\tif not composite:\n\t\tprimes.add 2 * i + 3\n\nif primes.len < NPrimes:\n\tquit \"Not enough primes. Please, increase value of N.\"\n\n\n# Compute primorial.\n\nimport strformat, threadpool\nimport bignum\n\nconst NWorkers = 8\n\n\nproc computeProduct(a: openArray[int]): Int =\n\tresult = newInt(1)\n\tfor n in a: result *= n\n\n\nproc primorial(n: int): Int =\n\tif n == 0: return newInt(1)\n\n\t# Prepare sublists.\n\tvar input: array[NWorkers, seq[int]]\n\tfor i in 0.. float\n\n\tParameters = tuple[omega, phip, phig: float]\n\n\tState = object\n\t\titer: int\n\t\tgbpos: seq[float]\n\t\tgbval: float\n\t\tmin, max: seq[float]\n\t\tparameters: Parameters\n\t\tpos, vel, bpos: seq[seq[float]]\n\t\tbval: seq[float]\n\t\tnParticles, nDims: int\n\n\nfunc initState(min, max: seq[float]; parameters: Parameters; nParticles: int): State =\n\tlet nDims = min.len\n\tState(iter: 0,\n\t\t\t\tgbpos: repeat(Inf, nDims),\n\t\t\t\tgbval: Inf,\n\t\t\t\tmin: min,\n\t\t\t\tmax: max,\n\t\t\t\tparameters: parameters,\n\t\t\t\tpos: repeat(min, nParticles),\n\t\t\t\tvel: newSeqWith(nParticles,\n\t\t\t\tnewSeq[float](nDims)),\n\t\t\t\tbpos: repeat(min, nParticles),\n\t\t\t\tbval: repeat(Inf, nParticles),\n\t\t\t\tnParticles: nParticles,\n\t\t\t\tnDims: nDims)\n\n\nproc report(state: State; testFunc: string) =\n\techo \"Test Function: \", testfunc\n\techo \"Iterations: \", state.iter\n\techo \"Global Best Position: \", state.gbpos\n\techo \"Global Best Value: \", state.gbval\n\n\nproc pso(fn: Func; y: State): State =\n\tlet p = y.parameters\n\tvar v = newSeq[float](y.nParticles)\n\tvar bpos = repeat(y.min, y.nParticles)\n\tvar bval = newSeq[float](y.nParticles)\n\tvar gbpos = newSeq[float](y.nDims)\n\tvar gbval = Inf\n\n\tfor j in 0.. pos[j][k]\n\t\tif not ok:\n\t\t\tfor k in 0.. float): Cheb =\n\n\tresult = Cheb(c: newSeq[float](nCoeff), min: min, max: max)\n\tvar f, p = newSeq[float](nNodes)\n\tlet z = 0.5 * (max + min)\n\tlet r = 0.5 * (max - min)\n\tfor k in 0.. float = cos\n\tlet cheb = initCheb(0, 1, 10, 10, fn)\n\techo \"Coefficients:\"\n\tfor c in cheb.c:\n\t\techo \"{c: .15f}\"\n\n\techo \"\\n x computed approximated computed-approx\"\n\tconst N = 10\n\tfor i in 0..N:\n\t\tlet x = (cheb.min * (N - i) + cheb.max * i) / N\n\t\tlet computed = fn(x)\n\t\tlet approx = cheb.eval(x)\n\t\techo \"{x:.1f} {computed:12.8f} {approx:12.8f} {computed-approx: .3e}\"\n" + }, + { + "id": 1089, + "length": 3508, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\ntype\n\n\tFCNode = ref object\n\t\tname: string\n\t\tweight: int\n\t\tcoverage: float\n\t\tchildren: seq[FCNode]\n\t\tparent: FCNode\n\nfunc newFCNode(name: string; weight: int; coverage: float): FCNode =\n\tFCNode(name: name, weight: weight, coverage: coverage)\n\n# Forward reference.\nfunc updateCoverage(n: FCNode)\n\nfunc addChildren(n: FCNode; nodes: openArray[FCNode]) =\n\tfor node in nodes:\n\t\tnode.parent = n\n\tn.children = @nodes\n\tn.updateCoverage()\n\nfunc setCoverage(n: FCNode; value: float) =\n\tif n.coverage != value:\n\t\tn.coverage = value\n\t\t# Update any parent's coverage.\n\t\tif not n.parent.isNil:\n\t\t\tn.parent.updateCoverage()\n\nfunc updateCoverage(n: FCNode) =\n\tvar v1 = 0.0\n\tvar v2 = 0\n\tfor node in n.children:\n\t\tv1 += node.weight.toFloat * node.coverage\n\t\tv2 += node.weight\n\tn.setCoverage(v1 / v2.toFloat)\n\nproc show(n: FCNode; level: int) =\n\tlet indent = level * 4\n\tlet nl = n.name.len + indent\n\tconst Sep = \"|\"\n\techo \"{n.name.align(nl)}{Sep.align(32-nl)} {n.weight:>3d} | {n.coverage:8.6f} |\"\n\tfor child in n.children:\n\t\tchild.show(level + 1)\n\n\nlet houses = [newFCNode(\"house1\", 40, 0), newFCNode(\"house2\", 60, 0)]\n\nlet house1 = [\n\t\tnewFCNode(\"bedrooms\", 1, 0.25),\n\t\tnewFCNode(\"bathrooms\", 1, 0),\n\t\tnewFCNode(\"attic\", 1, 0.75),\n\t\tnewFCNode(\"kitchen\", 1, 0.1),\n\t\tnewFCNode(\"living_rooms\", 1, 0),\n\t\tnewFCNode(\"basement\", 1, 0),\n\t\tnewFCNode(\"garage\", 1, 0),\n\t\tnewFCNode(\"garden\", 1, 0.8)]\n\nlet house2 = [\n\t\tnewFCNode(\"upstairs\", 1, 0),\n\t\tnewFCNode(\"groundfloor\", 1, 0),\n\t\tnewFCNode(\"basement\", 1, 0)]\n\nlet h1Bathrooms = [\n\t\tnewFCNode(\"bathroom1\", 1, 0.5),\n\t\tnewFCNode(\"bathroom2\", 1, 0),\n\t\tnewFCNode(\"outside_lavatory\", 1, 1)]\n\nlet h1LivingRooms = [\n\t\tnewFCNode(\"lounge\", 1, 0),\n\t\tnewFCNode(\"dining_room\", 1, 0),\n\t\tnewFCNode(\"conservatory\", 1, 0),\n\t\tnewFCNode(\"playroom\", 1, 1)]\n\nlet h2Upstairs = [\n\t\tnewFCNode(\"bedrooms\", 1, 0),\n\t\tnewFCNode(\"bathroom\", 1, 0),\n\t\tnewFCNode(\"toilet\", 1, 0),\n\t\tnewFCNode(\"attics\", 1, 0.6)]\n\nlet h2Groundfloor = [\n\t\tnewFCNode(\"kitchen\", 1, 0),\n\t\tnewFCNode(\"living_rooms\", 1, 0),\n\t\tnewFCNode(\"wet_room_&_toilet\", 1, 0),\n\t\tnewFCNode(\"garage\", 1, 0),\n\t\tnewFCNode(\"garden\", 1, 0.9),\n\t\tnewFCNode(\"hot_tub_suite\", 1, 1)]\n\nlet h2Basement = [\n\t\tnewFCNode(\"cellars\", 1, 1),\n\t\tnewFCNode(\"wine_cellar\", 1, 1),\n\t\tnewFCNode(\"cinema\", 1, 0.75)]\n\nlet h2UpstairsBedrooms = [\n\t\tnewFCNode(\"suite_1\", 1, 0),\n\t\tnewFCNode(\"suite_2\", 1, 0),\n\t\tnewFCNode(\"bedroom_3\", 1, 0),\n\t\tnewFCNode(\"bedroom_4\", 1, 0)]\n\nlet h2GroundfloorLivingRooms = [\n\t\tnewFCNode(\"lounge\", 1, 0),\n\t\tnewFCNode(\"dining_room\", 1, 0),\n\t\tnewFCNode(\"conservatory\", 1, 0),\n\t\tnewFCNode(\"playroom\", 1, 0)]\n\nlet cleaning = newFCNode(\"cleaning\", 1, 0)\n\nhouse1[1].addChildren(h1Bathrooms)\nhouse1[4].addChildren(h1LivingRooms)\nhouses[0].addChildren(house1)\n\nh2Upstairs[0].addChildren(h2UpstairsBedrooms)\nhouse2[0].addChildren(h2Upstairs)\nh2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)\nhouse2[1].addChildren(h2Groundfloor)\nhouse2[2].addChildren(h2Basement)\nhouses[1].addChildren(house2)\n\ncleaning.addChildren(houses)\nlet topCoverage = cleaning.coverage\necho \"TOP COVERAGE = {topCoverage:8.6f}\\n\"\necho \"NAME HIERARCHY | WEIGHT | COVERAGE |\"\ncleaning.show(0)\n\nh2Basement[2].setCoverage(1) # Change Cinema node coverage to 1.\nlet diff = cleaning.coverage - topCoverage\necho \"\\nIf the coverage of the Cinema node were increased from 0.75 to 1\"\necho \"the top level coverage would increase by {diff:8.6f} to {topCoverage + diff:8.6f}\"\nh2Basement[2].setCoverage(0.75) # Restore to original value if required.\n" + }, + { + "id": 1090, + "length": 3696, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat, strutils, tables\n\ntype\n\n\tDigit = range[0..9]\n\tNumber = seq[Digit] # Number as a sequence of digits (unit at index 0).\n\n\t# Structure used to find the candidates for Lychrel numbers.\n\tCandidates = object\n\t\tseeds: seq[Number] # List of possible seeds.\n\t\tlinked: Table[Number, Number] # Maps a number to a smallest number in a sequence.\n\n\n# Conversions.\n\nfunc toInt(n: Number): Natural =\n\t## Convert a Number to an int. No check is done for overflow.\n\tfor i in countdown(n.high, 0):\n\t\tresult = 10 * result + n[i]\n\nfunc `$`(n: Number): string =\n\t## Return the string representation of a Number.\n\treversed(n).join()\n\nfunc `$`(s: seq[Number]): string =\n\t## Return the string representation of a sequence of Numbers.\n\ts.mapIt($it).join(\" \")\n\n\n# Operations on Numbers.\n\nfunc addReverse(n: var Number) =\n\t## Add a Number to its reverse.\n\tvar carry = 0\n\tvar high = n.high\n\tvar r = reversed(n)\n\tfor i in 0..high:\n\t\tvar sum = n[i] + r[i] + carry\n\t\tif sum >= 10:\n\t\t\tn[i] = sum - 10\n\t\t\tcarry = 1\n\t\telse:\n\t\t\tn[i] = sum\n\t\t\tcarry = 0\n\tif carry != 0: n.add carry\n\nfunc inc(a: var Number) =\n\t## Increment a Number by one.\n\tfor item in a.mitems:\n\t\tlet sum = item + 1\n\t\tif sum >= 10:\n\t\t\titem = sum - 10\n\t\telse:\n\t\t\titem = sum\n\t\t\treturn # No carry: stop adding.\n\ta.add 1 # Add last carry.\n\n\n# Operations related to Lychrel numbers.\n\nfunc isPalindromic(n: Number): bool =\n\t## Check if a Number is palindromic.\n\tfor i in 0..(n.high div 2):\n\t\tif n[i] != n[n.high - i]: return false\n\tresult = true\n\n\nfunc isRelatedLychrel(candidates: Candidates; n: Number): bool =\n\t## Check if a Number is a Lychrel related number.\n\n\tvar val = candidates.linked[n]\n\t# Search for the first value in a list of linked values.\n\twhile val in candidates.linked: val = candidates.linked[val]\n\t# If the first value is a seed, \"n\" is related to it.\n\tresult = val in candidates.seeds\n\n\nfunc relatedCount(candidates: Candidates; maxlen: Positive): int =\n\t## Return the number of related Lychrel numbers with length <= maxlen.\n\n\t# Loop on values which are linked to a smallest value.\n\tfor n in candidates.linked.keys:\n\t\tif n.len <= maxlen and candidates.isRelatedLychrel(n): inc result\n\n\nfunc palindromicLychrel(candidates: Candidates; maxlen: Positive): seq[int] =\n\t## Return the list of palindromic Lychrel numbers with length <= maxlen.\n\n\t# Search among seed Lychrel numbers.\n\tfor n in candidates.seeds:\n\t\tif n.len <= maxlen and n.isPalindromic:\n\t\t\tresult.add n.toInt\n\t# Search among related Lychrel numbers.\n\tfor n in candidates.linked.keys:\n\t\tif n.len <= maxlen and n.isPalindromic and candidates.isRelatedLychrel(n):\n\t\t\tresult.add n.toInt\n\t# Sort the whole list.\n\tresult.sort()\n\n\nproc check(candidates: var Candidates; num: Number) =\n\t## Check if a Number is a possible Lychrel number.\n\n\tif num in candidates.linked: return # Already encountered: nothing to do.\n\tvar val = num\n\tfor _ in 1..500:\n\t\tval.addReverse()\n\t\tif val in candidates.linked:\n\t\t\t# Set the linked value of \"num\" to that of \"val\".\n\t\t\tcandidates.linked[num] = candidates.linked[val]\n\t\t\treturn\n\t\tif val.isPalindromic(): return # Don't store palindromic values as they may be seeds.\n\t\tcandidates.linked[val] = num\n\tcandidates.seeds.add num\n\n\n\nvar cand: Candidates\n\nvar num: Number = @[Digit(0)] # The Number to test.\nfor n in 1..10_000:\n\tinc num\n\tcand.check(num)\n\necho \"Found {cand.seeds.len} candidate seed Lychrel numbers between 1 and 10000.\"\necho \"These candidate seed Lychrel numbers are: \", cand.seeds\necho \"Found {cand.relatedCount(4)} candidate related Lychrel numbers between 1 and 10000.\"\necho \"Palindromic candidate Lychrel numbers between 1 and 10000 are: \", cand.palindromicLychrel(4)\n" + }, + { + "id": 1091, + "length": 1878, + "source": "Rosetta Code", + "text": "import strutils, sugar, tables\n\nconst Codes = {'a': \"AAAAA\", 'b': \"AAAAB\", 'c': \"AAABA\", 'd': \"AAABB\", 'e': \"AABAA\",\n\t\t\t\t\t\t\t 'f': \"AABAB\", 'g': \"AABBA\", 'h': \"AABBB\", 'i': \"ABAAA\", 'j': \"ABAAB\",\n\t\t\t\t\t\t\t 'k': \"ABABA\", 'l': \"ABABB\", 'm': \"ABBAA\", 'n': \"ABBAB\", 'o': \"ABBBA\",\n\t\t\t\t\t\t\t 'p': \"ABBBB\", 'q': \"BAAAA\", 'r': \"BAAAB\", 's': \"BAABA\", 't': \"BAABB\",\n\t\t\t\t\t\t\t 'u': \"BABAA\", 'v': \"BABAB\", 'w': \"BABBA\", 'x': \"BABBB\", 'y': \"BBAAA\",\n\t\t\t\t\t\t\t 'z': \"BBAAB\", ' ': \"BBBAA\"}.toTable\n\nlet RevCodes = collect(newTable, for k, v in Codes.pairs: {v: k})\n\nproc encode(plaintext, message: string): string =\n\tvar et: string\n\tfor c in plaintext.toLowerAscii:\n\t\tet.add if c in 'a'..'z': Codes[c] else: Codes[' ']\n\tvar count = 0\n\tfor c in message.toLowerAscii:\n\t\tif c in 'a'..'z':\n\t\t\tresult.add if et[count] == 'A': c else: c.toUpperAscii\n\t\t\tinc count\n\t\t\tif count == et.len: break\n\t\telse:\n\t\t\tresult.add c\n\n\nproc decode(message: string): string =\n\tvar et: string\n\tfor c in message:\n\t\tif c.isAlphaAscii:\n\t\t\tet.add if c.isLowerAscii: 'A' else: 'B'\n\tfor i in countup(0, et.high - 4, 5):\n\t\tresult.add RevCodes[et[i..(i+4)]]\n\n\nwhen isMainModule:\n\tconst\n\t\tPlainText = \"the quick brown fox jumps over the lazy dog\"\n\t\tMessage = \"bacon's cipher is a method of steganography created by francis bacon.\" &\n\t\t\t\t\t\t\t\"this task is to implement a program for encryption and decryption of \" &\n\t\t\t\t\t\t\t\"plaintext using the simple alphabet of the baconian cipher or some \" &\n\t\t\t\t\t\t\t\"other kind of representation of this alphabet (make anything signify anything). \" &\n\t\t\t\t\t\t\t\"the baconian alphabet may optionally be extended to encode all lower \" &\n\t\t\t\t\t\t\t\"case characters individually and/or adding a few punctuation characters \" &\n\t\t\t\t\t\t\t\"such as the space.\"\n\tlet cipherText = PlainText.encode(Message)\n\techo \"Cipher text ->\\n\", cipherText\n\tlet decodedText = cipherText.decode()\n\techo \"\\nHidden text ->\\n\", decodedText\n" + }, + { + "id": 1092, + "length": 1220, + "source": "Rosetta Code", + "text": "template findIt(data, pred: untyped): int =\n\t## Return the index of the first element in \"data\" satisfying\n\t## the predicate \"pred\" or -1 if no such element is found.\n\tvar result = -1\n\tfor i, it {.inject.} in data.pairs:\n\t\tif pred:\n\t\t\tresult = i\n\t\t\tbreak\n\tresult\n\n\nwhen isMainModule:\n\n\timport strutils\n\n\ttype City = tuple[name: string; population: float]\n\n\tconst Cities: seq[City] = @[(\"Lagos\", 21.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Cairo\", 15.2),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Kinshasa-Brazzaville\", 11.3),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Greater Johannesburg\", 7.55),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Mogadishu\", 5.85),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Khartoum-Omdurman\", 4.98),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Dar Es Salaam\", 4.7),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Alexandria\", 4.58),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Abidjan\", 4.4),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\"Casablanca\", 3.98)]\n\n\techo \"Index of the first city whose name is Dar Es Salaam: \",\n\t\t\tCities.findIt(it.name == \"Dar Es Salaam\")\n\n\tlet idx1 = Cities.findIt(it.population < 5)\n\techo \"Name of the first city whose population is less than 5 million: \",\n\t\t\tif idx1 == -1: \"\" else: Cities[idx1].name\n\n\tlet idx2 = Cities.findIt(it.name.startsWith(\"A\"))\n\techo \"Population of the first city whose name starts with the letter A: \",\n\t\t\tif idx2 == -1: \"\" else: $Cities[idx2].population\n" + }, + { + "id": 1093, + "length": 1168, + "source": "Rosetta Code", + "text": "import sequtils, strformat\n\ntype\n\tWeight = tuple[src, dest, value: int]\n\tWeights = seq[Weight]\n\n\n\nproc printResult(dist: seq[seq[float]]; next: seq[seq[int]]) =\n\n\techo \"pair dist path\"\n\tfor i in 0..next.high:\n\t\tfor j in 0..next.high:\n\t\t\tif i != j:\n\t\t\t\tvar u = i + 1\n\t\t\t\tlet v = j + 1\n\t\t\t\tvar path = fmt\"{u} -> {v} {dist[i][j].toInt:2d} {u}\"\n\t\t\t\twhile true:\n\t\t\t\t\tu = next[u-1][v-1]\n\t\t\t\t\tpath &= fmt\" -> {u}\"\n\t\t\t\t\tif u == v: break\n\t\t\t\techo path\n\n\n\nproc floydWarshall(weights: Weights; numVertices: Positive) =\n\n\tvar dist = repeat(repeat(Inf, numVertices), numVertices)\n\tfor w in weights:\n\t\tdist[w.src - 1][w.dest - 1] = w.value.toFloat\n\n\tvar next = repeat(newSeq[int](numVertices), numVertices)\n\tfor i in 0.. dist[i][k] + dist[k][j]:\n\t\t\t\t\tdist[i][j] = dist[i][k] + dist[k][j]\n\t\t\t\t\tnext[i][j] = next[i][k]\n\n\tprintResult(dist, next)\n\n\n\nlet weights: Weights = @[(1, 3, -2), (2, 1, 4), (2, 3, 3), (3, 4, 2), (4, 2, -1)]\nlet numVertices = 4\n\nfloydWarshall(weights, numVertices)\n" + }, + { + "id": 1094, + "length": 653, + "source": "Rosetta Code", + "text": "import strformat\n\nproc linearCombo(c: openArray[int]): string =\n\n\tfor i, n in c:\n\t\tif n == 0: continue\n\t\tlet op = if n < 0:\n\t\t\t\t\t\t\t if result.len == 0: \"-\" else: \" - \"\n\t\t\t\t\t\t else:\n\t\t\t\t\t\t\t if n > 0 and result.len == 0: \"\" else: \" + \"\n\t\tlet av = abs(n)\n\t\tlet coeff = if av == 1: \"\" else: $av & '*'\n\t\tresult &= fmt\"{op}{coeff}e({i + 1})\"\n\tif result.len == 0:\n\t\tresult = \"0\"\n\nconst Combos = [@[1, 2, 3],\n\t\t\t\t\t\t\t\t@[0, 1, 2, 3],\n\t\t\t\t\t\t\t\t@[1, 0, 3, 4],\n\t\t\t\t\t\t\t\t@[1, 2, 0],\n\t\t\t\t\t\t\t\t@[0, 0, 0],\n\t\t\t\t\t\t\t\t@[0],\n\t\t\t\t\t\t\t\t@[1, 1, 1],\n\t\t\t\t\t\t\t\t@[-1, -1, -1],\n\t\t\t\t\t\t\t\t@[-1, -2, 0, -3],\n\t\t\t\t\t\t\t\t@[-1]]\n\nfor c in Combos:\n\techo fmt\"{($c)[1..^1]:15} -> {linearCombo(c)}\"\n" + }, + { + "id": 1095, + "length": 748, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nproc encrypt(key: seq[char]; msg: string): string =\n\tresult.setLen(msg.len)\n\tfor i, c in msg:\n\t\tresult[i] = key[ord(c) - 32]\n\nproc decrypt(key: seq[char]; msg: string): string =\n\tresult.setLen(msg.len)\n\tfor i, c in msg:\n\t\tresult[i] = chr(key.find(c) + 32)\n\nwhen isMainModule:\n\n\timport random\n\trandomize()\n\n\t# Build a random key.\n\tvar key = toSeq(32..126).mapIt(chr(it)) # All printable characters.\n\tkey.shuffle()\n\n\tconst Message = \"The quick brown fox jumps over the lazy dog, who barks VERY loudly!\"\n\tlet encrypted = key.encrypt(Message)\n\tlet decrypted = key.decrypt(encrypted)\n\n\techo \"Key = $#\" % key.join()\n\techo \"Message = $#\" % Message\n\techo \"Encrypted = $#\" % encrypted\n\techo \"Decrypted = $#\" % decrypted\n" + }, + { + "id": 1096, + "length": 1270, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\nconst\n\tRed = ColorRGBU [byte 255, 0, 0]\n\tGreen = ColorRGBU [byte 0, 255, 0]\n\tBlue = ColorRGBU [byte 0, 0, 255]\n\tMagenta = ColorRGBU [byte 255, 0, 255]\n\tCyan = ColorRGBU [byte 0, 255, 255]\n\tBlack = ColorRGBU [byte 0, 0, 0]\n\n\t(W, H) = (640, 640)\n\tDeg72 = degToRad(72.0)\n\tScaleFactor = 1 / ( 2 + cos(Deg72) * 2)\n\tPalette = [Red, Green, Blue, Magenta, Cyan]\n\n\nproc drawPentagon(img: var Image; x, y, side: float; depth: int) =\n\tvar (x, y) = (x, y)\n\tvar colorIndex {.global.} = 0\n\tvar angle = 3 * Deg72\n\tif depth == 0:\n\t\tfor _ in 0..4:\n\t\t\tlet (prevx, prevy) = (x, y)\n\t\t\tx += cos(angle) * side\n\t\t\ty -= sin(angle) * side\n\t\t\timg.drawLine(prevx.toInt, prevy.toInt, x.toInt, y.toInt, Palette[colorIndex])\n\t\t\tangle += Deg72\n\t\tcolorIndex = (colorIndex + 1) mod 5\n\telse:\n\t\tlet side = side * ScaleFactor\n\t\tlet dist = side * (1 + cos(Deg72) * 2)\n\t\tfor _ in 0..4:\n\t\t\tx += cos(angle) * dist\n\t\t\ty -= sin(angle) * dist\n\t\t\timg.drawPentagon(x, y, side, depth - 1)\n\t\t\tangle += Deg72\n\nvar image = initImage[ColorRGBU](W, H)\nimage.fill(Black)\nvar order = 5\nlet hw = W / 2\nlet margin = 20.0\nlet radius = hw - 2 * margin\nlet side = radius * sin(PI / 5) * 2\nimage.drawPentagon(hw, 3 * margin, side, order - 1)\nimage.savePNG(\"Sierpinski_pentagon.png\", compression = 9)\n" + }, + { + "id": 1097, + "length": 928, + "source": "Rosetta Code", + "text": "import math\nimport imageman\n\nconst\n\tSize = 600\n\tX0 = Size div 2\n\tY0 = Size div 2\n\tBackground = ColorRGBU [byte 0, 0, 0]\n\tForeground = ColorRGBU [byte 255, 255, 255]\n\n\nproc drawSuperEllipse(img: var Image; n: float; a, b: int) =\n\n\tvar yList = newSeq[int](a + 1)\n\tfor x in 0..a:\n\t\tlet an = pow(a.toFloat, n)\n\t\tlet bn = pow(b.toFloat, n)\n\t\tlet xn = pow(x.toFloat, n)\n\t\tlet t = max(bn - xn * bn / an, 0.0) # Avoid negative values due to rounding errors.\n\t\tyList[x] = pow(t, 1/n).toInt\n\n\tvar pos: seq[Point]\n\tfor x in countdown(a, 0):\n\t\tpos.add (X0 + x, Y0 - yList[x])\n\tfor x in 0..a:\n\t\tpos.add (X0 - x, Y0 - yList[x])\n\tfor x in countdown(a, 0):\n\t\tpos.add (X0 - x, Y0 + yList[x])\n\tfor x in 0..a:\n\t\tpos.add (X0 + x, Y0 + yList[x])\n\timg.drawPolyline(true, Foreground, pos)\n\n\nvar image = initImage[ColorRGBU](Size, Size)\nimage.fill(Background)\nimage.drawSuperEllipse(2.5, 200, 200)\nimage.savePNG(\"super_ellipse.png\", compression = 9)\n" + }, + { + "id": 1098, + "length": 633, + "source": "Rosetta Code", + "text": "import opengl, opengl/glut\n\nvar\n\trot = 0.0\n\tmatCol = [GLfloat 1, 0, 0, 0]\n\nproc onIdle() {.cdecl.} =\n\trot += 0.01\n\tglutPostRedisplay()\n\nproc display() {.cdecl.} =\n\tglClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)\n\tglPushMatrix()\n\tglRotatef(30, 1, 1, 0)\n\tglRotatef(rot, 0, 1, 1)\n\tglMaterialfv(GL_FRONT, GL_DIFFUSE, addr(matCol[0]))\n\tglutWireTeapot(0.5)\n\tglPopMatrix()\n\tglFlush()\n\nvar argc: cint = 0\nglutInit(addr(argc), nil)\nglutInitDisplayMode(GLUT_SINGLE or GLUT_RGB or GLUT_DEPTH)\nglutInitWindowSize(900, 700)\ndiscard glutCreateWindow(\"Utah Teapot\")\nglutIdleFunc(onIdle)\nglutDisplayFunc(display)\nloadExtensions()\nglutMainLoop()\n" + }, + { + "id": 1099, + "length": 3571, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat, strutils, sugar, tables\n\ntype\n\n\tDirection {.pure.} = enum Left = (-1, \"L\"), Straight = (0, \"S\"), Right = (1, \"R\")\n\n\tPermutationsGen = object\n\t\tindices: seq[int]\n\t\tchoices: seq[Direction]\n\t\tcarry: int\n\n\nfunc initPermutationsGen(numPositions: int; choices: seq[Direction]): PermutationsGen =\n\tresult.indices.setLen(numPositions)\n\tresult.choices = choices\n\n\nfunc next(pg: var PermutationsGen): seq[Direction] =\n\tpg.carry = 1\n\t# The generator skips the first index, so the result will always start\n\t# with a right turn (0) and we avoid clockwise/counter-clockwise\n\t# duplicate solutions.\n\tvar i = 1\n\twhile i < pg.indices.len and pg.carry > 0:\n\t\tpg.indices[i] += pg.carry\n\t\tpg.carry = 0\n\t\tif pg.indices[i] == pg.choices.len:\n\t\t\tpg.carry = 1\n\t\t\tpg.indices[i] = 0\n\t\tinc i\n\tresult.setLen(pg.indices.len)\n\tfor i, idx in pg.indices:\n\t\tresult[i] = pg.choices[idx]\n\n\ntemplate hasNext(pg: PermutationsGen): bool = pg.carry != 1\n\n\nfunc normalize(tracks: seq[Direction]): string =\n\tlet length = tracks.len\n\tvar a = collect(newSeq, for val in tracks: $val).join()\n\n\t# Rotate the array and find the lexicographically lowest order\n\t# to allow the hashmap to weed out duplicate solutions.\n\tresult = a\n\tfor _ in 2..length:\n\t\ta.rotateLeft(1)\n\t\tif a < result: result = a\n\n\nfunc fullCircleStraight(tracks: seq[Direction]; nStraight: int): bool =\n\tif nStraight == 0: return true\n\n\t# Do we have the requested number of straight tracks?\n\tif tracks.count(Straight) != nStraight: return false\n\n\t# Check symmetry of straight tracks: i and i + 6, i and i + 4.\n\tvar straight: array[12, int]\n\tvar i, idx = 0\n\twhile i < tracks.len and idx >= 0:\n\t\tif tracks[i] == Straight: inc straight[idx mod 12]\n\t\tidx += ord(tracks[i])\n\t\tinc i\n\tresult = true\n\tfor i in 0..5:\n\t\tif straight[i] != straight[i + 6]:\n\t\t\tresult = false\n\t\t\tbreak\n\tif result: return\n\tresult = true\n\tfor i in 0..7:\n\t\tif straight[i] != straight[i + 4]: return false\n\n\nfunc fullCircleRight(tracks: seq[Direction]): bool =\n\t# All tracks need to add up to a multiple of 360.\n\tvar s = 0\n\tfor dir in tracks: s += ord(dir) * 30\n\tif s mod 360 != 0: return false\n\n\t# Check symmetry of right turns: i and i + 6, i and i + 4.\n\tvar rTurns: array[12, int]\n\tvar i, idx = 0\n\twhile i < tracks.len and idx >= 0:\n\t\tif tracks[i] == Right: inc rTurns[idx mod 12]\n\t\tidx += ord(tracks[i])\n\t\tinc i\n\tresult = true\n\tfor i in 0..5:\n\t\tif rTurns[i] != rTurns[i + 6]:\n\t\t\tresult = false\n\t\t\tbreak\n\tif result: return\n\tresult = true\n\tfor i in 0..7:\n\t\tif rTurns[i] != rTurns[i + 4]: return false\n\n\nfunc getPermutationsGen(nCurved, nStraight: int): PermutationsGen =\n\tdoAssert (nCurved + nStraight - 12) mod 4 == 0, \"input must be 12 + k * 4\"\n\tlet trackTypes =\n\t\tif nStraight == 0: @[Right, Left]\n\t\telif nCurved == 12: @[Right, Straight]\n\t\telse: @[Right, Left, Straight]\n\tresult = initPermutationsGen(nCurved + nStraight, trackTypes)\n\n\nproc report(sol: Table[string, seq[Direction]]; nCurved, nStraight: int) =\n\tlet length = sol.len\n\tlet plural = if length > 1: \"s\" else: \"\"\n\techo \"\\n{length} solution{plural} for C{nCurved},{nStraight}\"\n\tif nCurved <= 20:\n\t\tfor track in sol.values:\n\t\t\techo track.join(\" \")\n\nproc circuits(nCurved, nStraight: Natural) =\n\tvar solutions: Table[string, seq[Direction]]\n\tvar gen = getPermutationsGen(nCurved, nStraight)\n\twhile gen.hasNext():\n\t\tlet tracks = gen.next()\n\t\tif not fullCircleStraight(tracks, nStraight): continue\n\t\tif not fullCircleRight(tracks): continue\n\t\tsolutions[tracks.normalize()] = tracks\n\treport(solutions, nCurved, nStraight)\n\nfor n in countup(12, 36, 4):\n\tcircuits(n, 0)\ncircuits(12, 4)\n" + }, + { + "id": 1100, + "length": 1941, + "source": "Rosetta Code", + "text": "import strformat, sugar, tables\nimport bignum\n\ntype Freq = CountTable[char]\n\n\nproc cumulativeFreq(freq: Freq): Freq =\n\tvar total = 0\n\tfor c in '\\0'..'\\255':\n\t\tresult.inc c, total\n\t\tinc total, freq[c]\n\n\nfunc arithmeticCoding(str: string; radix: int): (Int, int, Freq) =\n\n\tlet freq = str.toCountTable() # The frequency characters.\n\tlet cf = cumulativeFreq(freq) # The cumulative frequency.\n\tlet base = newInt(str.len) # Base.\n\tvar lower = newInt(0) # Lower bound.\n\tvar pf = newInt(1) # Product of all frequencies.\n\n\t# Each term is multiplied by the product of the\n\t# frequencies of all previously occurring symbols.\n\tfor c in str:\n\t\tlower = lower * base + cf[c] * pf\n\t\tpf *= freq[c]\n\n\tlet upper = lower + pf # Upper bound.\n\tvar powr = 0\n\n\twhile true:\n\t\tpf = pf div radix\n\t\tif pf.isZero: break\n\t\tinc powr\n\n\tlet diff = (upper - 1) div radix.pow(powr.culong)\n\tresult = (diff, powr, freq)\n\n\nfunc arithmeticDecoding(num: Int; radix, pwr: int; freq: Freq): string =\n\tvar enc = num * radix.pow(pwr.culong)\n\tvar base = 0\n\tfor v in freq.values: base += v\n\n\t# Create the cumulative frequency table.\n\tlet cf = cumulativeFreq(freq)\n\n\t# Create the dictionary.\n\tlet dict = collect(newTable, for k in '\\0'..'\\255': {cf[k]: k})\n\n\t# Fill the gaps in the dictionary.\n\tvar lchar = -1\n\tfor i in 0..= 0:\n\t\t\tdict[i] = chr(lchar)\n\n\t# Decode the input number.\n\tfor i in countdown(base - 1, 0):\n\t\tlet p = base.pow(i.culong)\n\t\tlet d = enc div p\n\t\tlet c = dict[d.toInt]\n\t\tlet diff = enc - p * cf[c]\n\t\tenc = diff div freq[c]\n\t\tresult.add c\n\n\nconst Radix = 10\nconst Strings = [\"DABDDB\", \"DABDDBBDDBA\", \"ABRACADABRA\", \"TOBEORNOTTOBEORTOBEORNOT\"]\nfor str in Strings:\n\tlet (enc, pow, freq) = arithmeticCoding(str, Radix)\n\tlet dec = arithmeticDecoding(enc, Radix, pow, freq)\n\techo \"{str:<25}-> {enc:>19} * {Radix}^{pow}\"\n\tdoAssert str == dec, \"\\tHowever that is incorrect!\"\n" + }, + { + "id": 1101, + "length": 1551, + "source": "Rosetta Code", + "text": "type\n\tSquareMatrix[N: static Positive] = array[N, array[N, float]]\n\tVector[N: static Positive] = array[N, float]\n\n\n# Templates.\n\ntemplate `[]`(m: SquareMatrix; i, j: Natural): float =\n\t## Allow to get value of an element using m[i, j] syntax.\n\tm[i][j]\n\ntemplate `[]=`(m: var SquareMatrix; i, j: Natural; val: float) =\n\t## Allow to set value of an element using m[i, j] syntax.\n\tm[i][j] = val\n\n\nfunc det(m: SquareMatrix): float =\n\t## Return the determinant of matrix \"m\".\n\n\tvar m = m\n\tresult = 1\n\n\tfor j in 0..m.high:\n\t\tvar imax = j\n\t\tfor i in (j + 1)..m.high:\n\t\t\tif m[i, j] > m[imax, j]:\n\t\t\t\timax = i\n\n\t\tif imax != j:\n\t\t\tswap m[iMax], m[j]\n\t\t\tresult = -result\n\n\t\tif abs(m[j, j]) < 1e-12:\n\t\t\treturn NaN\n\n\t\tfor i in (j + 1)..m.high:\n\t\t\tlet mult = -m[i, j] / m[j, j]\n\t\t\tfor k in 0..m.high:\n\t\t\t\tm[i, k] += mult * m[j, k]\n\n\tfor i in 0..m.high:\n\t\tresult *= m[i, i]\n\n\nfunc cramerSolve(a: SquareMatrix; detA: float; b: Vector; col: Natural): float =\n\t## Apply Cramer rule on matrix \"a\", using vector \"b\" to replace column \"col\".\n\n\twhen a.N != b.N:\n\t\t{.error: \"incompatible matrix and vector sizes\".}\n\n\telse:\n\t\tvar a = a\n\t\tfor i in 0..a.high:\n\t\t\ta[i, col] = b[i]\n\t\tresult = det(a) / detA\n\n\nimport strformat\n\nconst\n\n\tA: SquareMatrix[4] = [[2.0, -1.0, 5.0, 1.0],\n\t\t\t\t\t\t\t\t\t\t\t\t[3.0, 2.0, 2.0, -6.0],\n\t\t\t\t\t\t\t\t\t\t\t\t[1.0, 3.0, 3.0, -1.0],\n\t\t\t\t\t\t\t\t\t\t\t\t[5.0, -2.0, -3.0, 3.0]]\n\n\tB: Vector[4] = [-3.0, -32.0, -47.0, 49.0]\n\nlet detA = det(A)\nif detA == NaN:\n\techo \"Singular matrix!\"\n\tquit(QuitFailure)\n\nfor i in 0..A.high:\n\techo \"{cramerSolve(A, detA, B, i):7.3f}\"\n" + }, + { + "id": 1102, + "length": 2041, + "source": "Rosetta Code", + "text": "import times, strutils\n\nconst\n\tMaxLen = 13\n\tMaxNonBrauer = 382\n\nfunc isBrauer(a: seq[int]): bool =\n\tfor i in 2..a.high:\n\t\tblock loop:\n\t\t\tfor j in countdown(i - 1, 0):\n\t\t\t\tif a[i-1] + a[j] == a[i]:\n\t\t\t\t\tbreak loop\n\t\t\treturn false\n\tresult = true\n\nvar\n\tbrauerCount, nonBrauerCount: int\n\tbrauerExample, nonBrauerExample: seq[int]\n\n\nproc additionChains(target, length: int; chosen: seq[int]): int =\n\tvar length = length\n\tvar le = chosen.len\n\tvar last = chosen[^1]\n\n\tif last == target:\n\t\tif le < length:\n\t\t\tbrauerCount = 0\n\t\t\tnonBrauerCount = 0\n\t\tif chosen.isBrauer:\n\t\t\tinc brauerCount\n\t\t\tbrauerExample = chosen\n\t\telse:\n\t\t\tinc nonBrauerCount\n\t\t\tnonBrauerExample = chosen\n\t\treturn le\n\n\tif le == length: return length\n\n\tif target > MaxNonBrauer:\n\t\tvar nextChosen = chosen & 0\n\t\tfor i in countdown(le - 1, 0):\n\t\t\tlet next = last + chosen[i]\n\t\t\tif next <= target and next > chosen[^1] and i < length:\n\t\t\t\tnextChosen[^1] = next\n\t\t\t\tlength = additionChains(target, length, nextChosen)\n\telse:\n\t\tvar ndone = newSeqOfCap[int](le)\n\t\tvar nextChosen = chosen & 0\n\t\twhile true:\n\t\t\tfor i in countdown(le - 1, 0):\n\t\t\t\tlet next = last + chosen[i]\n\t\t\t\tif next <= target and next > chosen[^1] and i < length and next notin ndone:\n\t\t\t\t\tndone.add next\n\t\t\t\t\tnextChosen[^1] = next\n\t\t\t\t\tlength = additionChains(target, length, nextChosen)\n\t\t\tdec le\n\t\t\tif le == 0: break\n\t\t\tlast = chosen[le-1]\n\tresult = length\n\n\nconst Nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]\n\nlet start = now()\necho \"Searching for Brauer chains up to a minimum length of \", MaxLen - 1\nfor num in Nums:\n\tbrauerCount = 0\n\tnonBrauerCount = 0\n\tlet le = additionChains(num, MaxLen, @[1])\n\techo \"\\nN = \", num\n\techo \"Minimum length of chains : L($1) = $2\".format(num, le - 1)\n\techo \"Number of minimum length Brauer chains: \", brauerCount\n\tif brauerCount > 0:\n\t\techo \"Brauer example: \", brauerExample.join(\", \")\n\techo \"Number of minimum length non-Brauer chains: \", nonBrauerCount\n\tif nonBrauerCount > 0:\n\t\techo \"Non-Brauer example: \", nonBrauerExample.join(\", \")\necho \"\\nTook \", now() - start\n" + }, + { + "id": 1103, + "length": 629, + "source": "Rosetta Code", + "text": "import options,math,sugar,strformat\ntemplate checkAndWrap(x:float,body:typed): untyped =\n\tif x.classify in {fcNormal,fcZero,fcNegZero}:\n\t\tsome(body)\n\telse:\n\t\tnone(typeof(body))\nfunc reciprocal(x:float):Option[float] =\n\tlet res = 1 / x\n\tres.checkAndWrap(res)\nfunc log(x:float):Option[float] =\n\tlet res = ln(x)\n\tres.checkAndWrap(res)\nfunc format(x:float):Option[string] =\n\tx.checkAndWrap(\"{x:.2f}\")\n\n#our bind function:\nfunc `-->`[T,U](input:Option[T], f: T->Option[U]):Option[U] =\n\tif input.isSome:\n\t\tf(input.get)\n\telse:\n\t\tnone(U)\n\nwhen isMainModule:\n\tfor i in [0.9,0.0,-0.9,3.0]:\n\t\techo some(i) --> reciprocal --> log --> format\n" + }, + { + "id": 1104, + "length": 885, + "source": "Rosetta Code", + "text": "import lenientops\n\nfunc jaro(s1, s2: string): float =\n\n\tif s1.len == 0 and s2.len == 0: return 1\n\tif s1.len == 0 or s2.len == 0: return 0\n\n\tlet matchDistance = max(s1.len, s2.len) div 2 - 1\n\tvar s1Matches = newSeq[bool](s1.len)\n\tvar s2Matches = newSeq[bool](s2.len)\n\tvar matches = 0\n\tfor i in 0..s1.high:\n\t\tfor j in max(0, i - matchDistance)..min(i + matchDistance, s2.high):\n\t\t\tif not s2Matches[j] and s1[i] == s2[j]:\n\t\t\t\ts1Matches[i] = true\n\t\t\t\ts2Matches[j] = true\n\t\t\t\tinc matches\n\t\t\t\tbreak\n\tif matches == 0: return 0\n\n\tvar transpositions = 0.0\n\tvar k = 0\n\tfor i in ..s1.high:\n\t\tif not s1Matches[i]: continue\n\t\twhile not s2Matches[k]: inc k\n\t\tif s1[i] != s2[k]: transpositions += 0.5\n\t\tinc k\n\n\tresult = (matches / s1.len + matches / s2.len + (matches - transpositions) / matches) / 3\n\necho jaro(\"MARTHA\", \"MARHTA\")\necho jaro(\"DIXON\", \"DICKSONX\")\necho jaro(\"JELLYFISH\", \"SMELLYFISH\")\n" + }, + { + "id": 1105, + "length": 3166, + "source": "Rosetta Code", + "text": "import math, strutils, strformat\nimport decimal\nimport bignum\n\n# Utilities.\n\nproc format[T: DecimalType|Rat](val: T; intLen, fractLen: Positive): string =\n\t## Format a decimal or a rational with \"intLen\" integer digits and \"fractLen\"\n\t## fractional digits.\n\tlet s = when T is DecimalType: ($val).split('.')\n\t\t\t\t\telse: ($val.toFloat).split('.')\n\n\tresult = s[0].align(intLen) & '.'\n\tif s[1].len < fractLen:\n\t\tresult.add s[1].alignLeft(fractLen, '0')\n\telse:\n\t\tresult.add s[1][0..3} {vfloat[n]:>20.16f} {vdecimal[n].format(3, 16)} {vrational[n].format(3, 16)}\"\n\n\n# Task 2.\n\nproc balance[T: float|DecimalType|Rat](): T =\n\t## Return the balance after 25 years.\n\tresult = when T is float: E - 1\n\t\t\t\t\t elif T is DecimalType: exp(newDecimal(1)) - 1\n\t\t\t\t\t else: newInt(\"17182818284590452353602874713526624977572470\") /\n\t\t\t\t\t\t\t\t newInt(\"10000000000000000000000000000000000000000000\")\n\n\tvar n = when T is float: 1.0 else: 1\n\twhile n <= 25:\n\t\tresult = result * n - 1\n\t\tn += 1\n\necho \"\\nTask 2.\"\necho \"Balance after 25 years (float): \", (\"{balance[float]():.16f}\")[0..17]\necho \"Balance after 25 years (decimal): \", balance[DecimalType]().format(1, 16)\necho \"Balance after 25 years: (rational): \", balance[Rat]().format(1, 16)\n\n\n# Task 3.\n\nconst\n\tA = 77617\n\tB = 33096\n\nproc rump[T: float|DecimalType|Rat](a, b: T): T =\n\t## Return the value of the Rump's function.\n\tlet C1 = when T is float: 333.75\n\t\t\t\t\t elif T is Rat: newRat(333.75)\n\t\t\t\t\t else: newDecimal(\"333.75\")\n\tlet C2 = when T is float: 5.5\n\t\t\t\t\t elif T is Rat: newRat(5.5)\n\t\t\t\t\t else: newDecimal(\"5.5\")\n\tresult = C1 * b^6 + a^2 * (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) + C2 * b^8 + a / (2 * b)\n\necho \"\\nTask 3\"\n\nlet rumpFloat = rump(A.toFloat, B.toFloat)\nlet rumpDecimal = rump(newDecimal(A), newDecimal(B))\nlet rumpRational = rump(newRat(A), newRat(B))\n\necho \"f({A}, {B}) float = \", rumpFloat\necho \"f({A}, {B}) decimal = \", rumpDecimal.format(1, 16)\necho \"f({A}, {B}) rational = \", rumpRational.format(1, 16)\n" + }, + { + "id": 1106, + "length": 835, + "source": "Rosetta Code", + "text": "import random\n\nimport rapid/gfx\n\nvar\n\twindow = initRWindow()\n\t\t.title(\"Chaos Game\")\n\t\t.open()\n\tsurface = window.openGfx()\n\tsierpinski = window.newRCanvas()\n\tpoints: array[3, Vec2[float]]\n\nfor i in 0..<3:\n\tpoints[i] = vec2(cos(PI * 2 / 3 * i.float), sin(PI * 2 / 3 * i.float)) * 300\n\nvar point = vec2(rand(0.0..surface.width), rand(0.0..surface.height))\n\nsurface.vsync = false\nsurface.loop:\n\tdraw ctx, step:\n\t\tlet vertex = sample(points)\n\t\tpoint = (point + vertex) / 2\n\t\tctx.renderTo(sierpinski):\n\t\t\tctx.transform():\n\t\t\t\tctx.translate(surface.width / 2, surface.height / 2)\n\t\t\t\tctx.rotate(-PI / 2)\n\t\t\t\tctx.begin()\n\t\t\t\tctx.point((point.x, point.y))\n\t\t\t\tctx.draw(prPoints)\n\t\tctx.clear(gray(0))\n\t\tctx.begin()\n\t\tctx.texture = sierpinski\n\t\tctx.rect(0, 0, surface.width, surface.height)\n\t\tctx.draw()\n\t\tctx.noTexture()\n\tupdate step:\n\t\tdiscard\n" + }, + { + "id": 1107, + "length": 1019, + "source": "Rosetta Code", + "text": "import sdl2, std/random\n\nlet\n\tmax_it = 50000\n\tsize = [800, 600]\n\tv = [\n\t\t[0, 0],\n\t\t[size[0] - 1, 0],\n\t\t[size[0] div 2, size[1] - 1]\n\t\t]\n\ndiscard sdl2.init(INIT_EVERYTHING)\n\nvar\n\twindow: WindowPtr\n\trender: RendererPtr\n\nwindow = createWindow(\"chaos\", 100, 100, cint(size[0]), cint(size[1]), SDL_WINDOW_SHOWN)\nrender = createRenderer(window, -1, Renderer_Accelerated or\n\t\tRenderer_PresentVsync or Renderer_TargetTexture)\n\nvar\n\tevt = sdl2.defaultEvent\n\trunGame = true\n\tit = 0\n\tr: Point\n\nr.x = cint(rand(size[0] - 1))\nr.y = cint(rand(size[1] - 1))\nrender.setDrawColor(0, 0, 0)\nrender.clear\n\nwhile it < max_it:\n\tlet vn = rand(2)\n\tr.x = cint((r.x + v[vn][0]) div 2)\n\tr.y = cint((r.y + v[vn][1]) div 2)\n\tif vn == 0:\n\t\trender.setDrawColor(255, 0, 0)\n\telif vn == 1:\n\t\trender.setDrawColor(0, 255, 0)\n\telse:\n\t\trender.setDrawColor(0, 0, 255)\n\trender.drawPoint(r.x, r.y)\n\tinc it\n\nwhile runGame:\n\trender.present\n\tdelay(100)\n\twhile pollEvent(evt):\n\t\tif evt.kind == QuitEvent:\n\t\t\trunGame = false\n\t\t\tbreak\n\ndestroy render\ndestroy window\n" + }, + { + "id": 1108, + "length": 1655, + "source": "Rosetta Code", + "text": "import math\nimport random\n\nimport imageman\n\nconst\n\tWidth = 400\n\tHeight = 400\n\tMargin = 20\n\ntype Coords = tuple[x, y: float]\n\n# The triangle.\nconst T = [Coords (0.0, 0.0), (1.0, 0.0), (0.5, 0.5 * tan(PI / 3))]\n\n\nfunc toPoint(v: Coords): Point =\n\t## Convert [0..1] coordinates to image coordinates.\n\t## We have to change scale, then to change position of y-axis.\n\tresult = ((Margin + v.x * (Width - 2 * Margin)).toInt,\n\t\t\t\t\t\t((Height - Margin) - v.y * (Height - 2 * Margin)).toInt)\n\n\nfunc side(p, p1, p2: Coords): float =\n\t## Auxiliary function to check if a point is in a triangle.\n\t(p2.y - p1.y) * (p.x - p1.x) + (p1.x - p2.x) * (p.y - p1.y)\n\n\nproc firstPoint(): Coords =\n\t## Choose the first point.\n\n\twhile true:\n\t\tresult = (x: rand(1.0), y: rand(1.0))\n\t\tlet b1 = side(result, T[0], T[1]) >= 0\n\t\tlet b2 = side(result, T[1], T[2]) >= 0\n\t\tlet b3 = side(result, T[2], T[0]) >= 0\n\t\tif b1 == b2 and b2 == b3:\n\t\t\t# The point is in the triangle. Keep it.\n\t\t\treturn\n\n\nconst\n\tIterations = 50_000\n\tBlack = ColorRGBU [byte 0, 0, 0]\n\tWhite = ColorRGBU [byte 255, 255, 255]\n\tPointColor = ColorRGBU [byte 255, 255, 0] # Color for points.\n\n# Points in image coordinates.\nconst\n\tA = T[0].toPoint\n\tB = T[1].toPoint\n\tC = T[2].toPoint\n\n\nrandomize()\nvar image = initImage[ColorRGBU](Width, Height)\nimage.fill(Black)\n\n# Draw the triangle.\nimage.drawLine(A, B, White)\nimage.drawLine(B, C, White)\nimage.drawLine(C, A, White)\n\nvar p = firstPoint()\n\nfor _ in 1..Iterations:\n\tlet pt = p.toPoint\n\timage[pt.x, pt.y] = PointColor\n\t# Find position of next point.\n\tlet idx = rand(2)\n\tp = ((p.x + T[idx].x) / 2, (p.y + T[idx].y) / 2)\n\nimage.savePNG(\"chaos_game.png\", compression = 9)\n" + }, + { + "id": 1109, + "length": 1323, + "source": "Rosetta Code", + "text": "import nimPNG, random\n\nrandomize()\n\nconst\n\twidth = 640\n\theight = 640\n\tminX = -2.1815\n\tmaxX = 2.6556\n\tminY = 0.0\n\tmaxY = 9.9982\n\titerations = 1_000_000\n\nvar img: array[width * height * 3, char]\n\nproc floatToPixel(x,y:float): tuple[a:int,b:int] =\n\tvar px = abs(x - minX) / abs(maxX - minX)\n\tvar py = abs(y - minY) / abs(maxY - minY)\n\n\tvar a:int = (int)(width * px)\n\tvar b:int = (int)(height * py)\n\n\ta = a.clamp(0, width-1)\n\tb = b.clamp(0, height-1)\n\t# flip the y axis\n\t(a:a,b:height-b-1)\n\nproc pixelToOffset(a,b: int): int =\n\tb * width * 3 + a * 3\n\nproc toString(a: openArray[char]): string =\n\tresult = newStringOfCap(a.len)\n\n\tfor ch in items(a):\n\t\tresult.add(ch)\n\nproc drawPixel(x,y:float) =\n\tvar (a,b) = floatToPixel(x,y)\n\tvar offset = pixelToOffset(a,b)\n\n\t#img[offset] = 0 # red channel\n\timg[offset+1] = char(250) # green channel\n\t#img[offset+2] = 0 # blue channel\n\n# main\nvar x, y: float = 0.0\n\nfor i in 1..iterations:\n\tvar r = random(101)\n\tvar nx, ny: float\n\tif r <= 85:\n\t\tnx = 0.85 * x + 0.04 * y\n\t\tny = -0.04 * x + 0.85 * y + 1.6\n\telif r <= 85 + 7:\n\t\tnx = 0.2 * x - 0.26 * y\n\t\tny = 0.23 * x + 0.22 * y + 1.6\n\telif r <= 85 + 7 + 7:\n\t\tnx = -0.15 * x + 0.28 * y\n\t\tny = 0.26 * x + 0.24 * y + 0.44\n\telse:\n\t\tnx = 0\n\t\tny = 0.16 * y\n\n\tx = nx\n\ty = ny\n\n\tdrawPixel(x,y)\n\ndiscard savePNG24(\"fern.png\",img.toString, width, height)\n" + }, + { + "id": 1110, + "length": 1523, + "source": "Rosetta Code", + "text": "import math\n\nimport gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\n\tWidth = 601\n\tHeight = 601\n\n\tLimit = 12 * math.PI\n\n\tOrigin = (x: float(Width div 2), y: float(Height div 2))\n\tB = floor((Width div 2) / Limit)\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the spiral.\n\n\tvar theta = 0.0\n\tvar delta = 0.01\n\tvar (prevx, prevy) = Origin\n\n\t# Clear the region.\n\tcontext.moveTo(0, 0)\n\tcontext.setSource(0.0, 0.0, 0.0)\n\tcontext.paint()\n\n\t# Draw the spiral.\n\tcontext.setSource(1.0, 1.0, 0.0)\n\tcontext.moveTo(Origin.x, Origin.y)\n\twhile theta < Limit:\n\t\tlet r = B * theta\n\t\tlet x = Origin.x + r * cos(theta) # X-coordinate on drawing area.\n\t\tlet y = Origin.y + r * sin(theta) # Y-coordinate on drawing area.\n\t\tcontext.lineTo(x, y)\n\t\tcontext.stroke()\n\t\t# Set data for next round.\n\t\tcontext.moveTo(x, y)\n\t\tprevx = x\n\t\tprevy = y\n\t\ttheta += delta\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Archimedean spiral\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the spiral.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Spiral\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 1111, + "length": 680, + "source": "Rosetta Code", + "text": "import lenientops\nimport imageman\n\nconst\n\tW = 800\n\tH = 600\n\tZoom = 1\n\tMaxIter = 255\n\tMoveX = 0\n\tMoveY = 0\n\tCx = -0.7\n\tCy = 0.27015\n\nvar colors: array[256, ColorRGBU]\nfor n in byte.low..byte.high:\n\tcolors[n] = ColorRGBU [n shr 5 * 36, (n shr 3 and 7) * 36, (n and 3) * 85]\n\nvar image = initImage[ColorRGBU](W, H)\n\nfor x in 0.. 1:\n\t\t\t(zy, zx) = (2.0 * zx * zy + Cy, zx * zx - zy * zy + Cx)\n\t\t\tdec i\n\t\timage[x, y] = colors[i]\n\n# Save into a PNG file.\nimage.savePNG(\"julia.png\", compression = 9)\n" + }, + { + "id": 1112, + "length": 932, + "source": "Rosetta Code", + "text": "import bitops, sequtils, strutils\n\ntype Square = seq[seq[int]]\n\nfunc magicSquareDoublyEven(n: int): Square =\n\t## Build a magic square of doubly even order.\n\n\tassert n >= 4 and (n and 3) == 0, \"base must be a positive multiple of 4.\"\n\tresult = newSeqWith(n, newSeq[int](n))\n\n\tconst bits = 0b1001_0110_0110_1001 # Pattern of count-up vs count-down zones.\n\tlet size = n * n\n\tlet mult = n div 4 # How many multiples of 4.\n\n\tvar i = 0\n\tfor r in 0..= 3 and (n and 1) != 0, \"base must be odd and greater than 2.\"\n\tresult = newSeqWith(n, newSeq[int](n))\n\n\tvar\n\t\tr = 0\n\t\tc = n div 2\n\t\tvalue = 0\n\n\twhile value < n * n:\n\t\tinc value\n\t\tresult[r][c] = value\n\t\tif r == 0:\n\t\t\tif c == n - 1:\n\t\t\t\tinc r\n\t\t\telse:\n\t\t\t\tr = n - 1\n\t\t\t\tinc c\n\t\telif c == n - 1:\n\t\t\tdec r\n\t\t\tc = 0\n\t\telif result[r - 1][c + 1] == 0:\n\t\t\tdec r\n\t\t\tinc c\n\t\telse:\n\t\t\tinc r\n\n\nfunc magicSquareSinglyEven(n: int): Square =\n\t## Build a magic square of singly even order.\n\n\tassert n >= 6 and ((n - 2) and 3) == 0, \"base must be a positive multiple of 4 plus 2.\"\n\tresult = newSeqWith(n, newSeq[int](n))\n\n\tlet\n\t\thalfN = n div 2\n\t\tsubSquareSize = n * n div 4\n\t\tsubSquare = magicSquareOdd(halfN)\n\n\tconst QuadrantFactors = [0, 2, 3, 1]\n\n\tfor r in 0..= n - nColsRight or (c == nColsLeft and r == nColsLeft):\n\t\t\t\tif c != 0 or r != nColsLeft:\n\t\t\t\t\tswap result[r][c], result[r + halfN][c]\n\n\nfunc `$`(square: Square): string =\n\t## Return the string representation of a magic square.\n\tlet length = len($(square.len * square.len))\n\tfor row in square:\n\t\tresult.add row.mapIt(($it).align(length)).join(\" \") & '\\n'\n\n\nwhen isMainModule:\n\tlet n = 6\n\techo magicSquareSinglyEven(n)\n\techo \"Magic constant = \", n * (n * n + 1) div 2\n" + }, + { + "id": 1114, + "length": 1748, + "source": "Rosetta Code", + "text": "# Prime conspiracy.\n\nfrom algorithm import sorted\nfrom math import sqrt\nfrom sequtils import toSeq\nfrom strformat import fmt\nimport tables\n\nconst N = 1_020_000_000.int # Size of sieve of Eratosthenes.\n\nproc newSieve(): seq[bool] =\n\t## Create a sieve with only odd values.\n\t## Index \"i\" in sieve represents value \"n = 2 * i + 3\".\n\tresult.setLen(N)\n\tfor item in result.mitems: item = true\n\t# Apply sieve.\n\tvar i = 0\n\tconst Limit = sqrt(2 * N.toFloat + 3).int\n\twhile true:\n\t\tlet n = 2 * i + 3\n\t\tif n > Limit:\n\t\t\tbreak\n\t\tif result[i]:\n\t\t\t# Found prime, so eliminate multiples.\n\t\t\tfor k in countup((n * n - 3) div 2, N - 1, n):\n\t\t\t\tresult[k] = false\n\t\tinc i\n\nvar isPrime = newSieve()\n\nproc countTransitions(isPrime: seq[bool]; nprimes: int) =\n\t## Build the transition count table and print it.\n\n\tvar counts = [(2, 3)].toCountTable() # Count of transitions.\n\tvar d1 = 3 # Last digit of first prime in transition.\n\tvar count = 2 # Count of primes (starting with 2 and 3).\n\tfor i in 1..isPrime.high:\n\t\tif isPrime[i]:\n\t\t\tinc count\n\t\t\tlet d2 = (2 * i + 3) mod 10 # Last digit of second prime in transition.\n\t\t\tcounts.inc((d1, d2))\n\t\t\tif count == nprimes: break\n\t\t\td1 = d2\n\n\t# Check if sieve was big enough.\n\tif count < nprimes:\n\t\techo fmt\"Found only {count} primes; expected {nprimes} primes. Increase value of N.\"\n\t\tquit(QuitFailure)\n\n\t# Print result.\n\techo fmt\"{nprimes} first primes. Transitions prime % 10 -> next-prime % 10.\"\n\tfor key in sorted(toSeq(counts.keys)):\n\t\tlet count = counts[key]\n\t\tlet freq = count.toFloat * 100 / nprimes.toFloat\n\t\techo fmt\"{key[0]} -> {key[1]}: count: {count:7d} frequency: {freq:4.2f}%\"\n\techo \"\"\n\nisPrime.countTransitions(10_000)\nisPrime.countTransitions(1_000_000)\nisPrime.countTransitions(100_000_000)\n" + }, + { + "id": 1115, + "length": 2042, + "source": "Rosetta Code", + "text": "import math, random, sequtils, strformat\n\nconst\n\tkT = 1\n\tkMax = 1_000_000\n\nproc randomNeighbor(x: int): int =\n\tcase x\n\tof 0:\n\t\tsample([1, 10, 11])\n\tof 9:\n\t\tsample([8, 18, 19])\n\tof 90:\n\t\tsample([80, 81, 91])\n\tof 99:\n\t\tsample([88, 89, 98])\n\telif x > 0 and x < 9: # top ceiling\n\t\tsample [x-1, x+1, x+9, x+10, x+11]\n\telif x > 90 and x < 99: # bottom floor\n\t\tsample [x-11, x-10, x-9, x-1, x+1]\n\telif x mod 10 == 0: # left wall\n\t\tsample([x-10, x-9, x+1, x+10, x+11])\n\telif (x+1) mod 10 == 0: # right wall\n\t\tsample([x-11, x-10, x-1, x+9, x+10])\n\telse: # center\n\t\tsample([x-11, x-10, x-9, x-1, x+1, x+9, x+10, x+11])\n\nproc neighbor(s: seq[int]): seq[int] =\n\tresult = s\n\tvar city = sample(s)\n\tvar cityNeighbor = city.randomNeighbor\n\twhile cityNeighbor == 0 or city == 0:\n\t\tcity = sample(s)\n\t\tcityNeighbor = city.randomNeighbor\n\tresult[s.find city].swap result[s.find cityNeighbor]\n\nfunc distNeighbor(a, b: int): float =\n\ttemplate divmod(a: int): (int, int) = (a div 10, a mod 10)\n\tlet\n\t\t(diva, moda) = a.divmod\n\t\t(divb, modb) = b.divmod\n\thypot((diva-divb).float, (moda-modb).float)\n\nfunc temperature(k, kmax: float): float =\n\tkT * (1 - (k / kmax))\n\nfunc pdelta(eDelta, temp: float): float =\n\tif eDelta < 0: 1.0\n\telse: exp(-eDelta / temp)\n\nfunc energy(path: seq[int]): float =\n\tvar sum = 0.distNeighbor path[0]\n\tfor i in 1 ..< path.len:\n\t\tsum += path[i-1].distNeighbor(path[i])\n\tsum + path[^1].distNeighbor 0\n\nproc main =\n\trandomize()\n\tvar\n\t\ts = block:\n\t\t\tvar x = toSeq(0..99)\n\t\t\ttemplate shuffler: int = rand(1 .. x.high)\n\t\t\tfor i in 1 .. x.high:\n\t\t\t\tx[i].swap x[shuffler()]\n\t\t\tx\n\techo fmt\"E(s0): {energy s:6.4f}\"\n\tfor k in 0 .. kMax:\n\t\tvar\n\t\t\ttemp = temperature(float k, float kMax)\n\t\t\tlastenergy = energy s\n\t\t\tnewneighbor = s.neighbor\n\t\t\tnewenergy = newneighbor.energy\n\t\tif k mod (kMax div 10) == 0:\n\t\t\techo fmt\"k: {k:7} T: {temp:6.2f} Es: {lastenergy:6.4f}\"\n\t\tvar deltaEnergy = newenergy - lastenergy\n\t\tif pDelta(deltaEnergy, temp) >= rand(1.0):\n\t\t\ts = newneighbor\n\n\ts.add 0\n\techo fmt\"E(sFinal): {energy s:6.4f}\"\n\techo fmt\"path: {s}\"\n\nmain()\n" + }, + { + "id": 1116, + "length": 1759, + "source": "Rosetta Code", + "text": "import options\nimport bignum\n\nlet\n\tZero = newInt(0)\n\tOne = newInt(1)\n\tBigBig = newInt(10)^50 + 15\n\ntype\n\tPoint = tuple[x, y: Int]\n\tSolutions = (Int, Int)\n\n\nproc exp(x, y, m: Int): Int =\n\t## Missing function in \"bignum\" module.\n\tif m == 1: return Zero\n\tresult = newInt(1)\n\tvar x = x mod m\n\tvar y = y.clone\n\twhile not y.isZero:\n\t\tif y mod 2 == 1:\n\t\t\tresult = result * x mod m\n\t\ty = y shr 1\n\t\tx = x * x mod m\n\n\nproc c(ns, ps: string): Option[Solutions] =\n\tlet n = newInt(ns)\n\tlet p = if ps.len != 0: newInt(ps) else: BigBig\n\n\t# Legendre symbol: returns 1, 0 or p - 1.\n\tproc ls(a: Int): Int = a.exp((p - 1) div 2, p)\n\n\t# Step 0, validate arguments.\n\tif ls(n) != One: return none(Solutions)\n\n\t# Step 1, find a, omega2.\n\tvar a = newInt(0)\n\tvar omega2: Int\n\twhile true:\n\t\tomega2 = (a * a + p - n) mod p\n\t\tif ls(omega2) == p - 1: break\n\t\ta += 1\n\n\t# Multiplication in Fp2.\n\tproc `*`(a, b: Point): Point =\n\t\t((a.x * b.x + a.y * b.y * omega2) mod p,\n\t\t (a.x * b.y + b.x * a.y) mod p)\n\n\t# Step 2, compute power.\n\tvar\n\t\tr: Point = (One, Zero)\n\t\ts: Point = (a, One)\n\t\tnn = ((p + 1) shr 1) mod p\n\twhile not nn.isZero:\n\t\tif (nn and One) == One: r = r * s\n\t\ts = s * s\n\t\tnn = nn shr 1\n\n\t# Step 3, check x in Fp.\n\tif not r.y.isZero: return none(Solutions)\n\n\t # Step 5, check x * x = n.\n\tif r.x * r.x mod p != n: return none(Solutions)\n\n\t # Step 4, solutions.\n\tresult = some((r.x, p - r.x))\n\n\nwhen isMainModule:\n\n\tconst Values = [(\"10\", \"13\"), (\"56\", \"101\"), (\"8218\", \"10007\"),\n\t\t\t\t\t\t\t\t\t(\"8219\", \"10007\"), (\"331575\", \"1000003\"),\n\t\t\t\t\t\t\t\t\t(\"665165880\", \"1000000007\"), (\"881398088036\", \"1000000000039\"),\n\t\t\t\t\t\t\t\t\t(\"34035243914635549601583369544560650254325084643201\", \"\")]\n\n\tfor (n, p) in Values:\n\t\tlet sols = c(n, p)\n\t\tif sols.isSome: echo sols.get()\n\t\telse: echo \"No solutions.\"\n" + }, + { + "id": 1117, + "length": 3179, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, strutils\n\nconst\n\n\tDirs = [[1, 0], [ 0, 1], [ 1, 1],\n\t\t\t\t\t[1, -1], [-1, 0],\n\t\t\t\t\t[0, -1], [-1, -1], [-1, 1]]\n\n\tNRows = 10\n\tNCols = 10\n\tGridSize = NRows * NCols\n\tMinWords = 25\n\ntype Grid = ref object\n\tnumAttempts: Natural\n\tcells: array[NRows, array[NCols, char]]\n\tsolutions: seq[string]\n\nproc readWords(filename: string): seq[string] =\n\n\tconst MaxLen = max(NRows, NCols)\n\n\tfor word in filename.lines():\n\t\tif word.len in 3..MaxLen:\n\t\t\tif word.allCharsInSet(Letters):\n\t\t\t\tresult.add word.toLowerAscii\n\n\nproc placeMessage(grid: var Grid; msg: string): int =\n\tlet msg = msg.map(toUpperAscii).filter(isUpperAscii).join()\n\tif msg.len in 1.. NCols) or\n\t\t (Dirs[dir][0] == -1 and (length - 1) > col) or\n\t\t (Dirs[dir][1] == 1 and (length + row) > NRows) or\n\t\t (Dirs[dir][1] == -1 and (length - 1) > row):\n\t\treturn 0\n\n\t# Check cells.\n\tvar r = row\n\tvar c = col\n\tfor ch in word:\n\t\tif grid.cells[r][c] != '\\0' and grid.cells[r][c] != ch: return 0\n\t\tc += Dirs[dir][0]\n\t\tr += Dirs[dir][1]\n\n\t# Place.\n\tr = row\n\tc = col\n\tvar overlaps = 0\n\tfor i, ch in word:\n\t\tif grid.cells[r][c] == ch: inc overlaps\n\t\telse: grid.cells[r][c] = ch\n\t\tif i < word.high:\n\t\t\tc += Dirs[dir][0]\n\t\t\tr += Dirs[dir][1]\n\n\tlet lettersPlaced = length - overlaps\n\tif lettersPlaced > 0:\n\t\tgrid.solutions.add \"{word:<10} ({col}, {row}) ({c}, {r})\"\n\n\tresult = lettersPlaced\n\n\nproc tryPlaceWord(grid: var Grid; word: string): int =\n\tlet randDir = rand(Dirs.high)\n\tlet randPos = rand(GridSize - 1)\n\n\tfor dir in 0..Dirs.high:\n\t\tlet dir = (dir + randDir) mod Dirs.len\n\t\tfor pos in 0.. 0:\n\t\t\t\treturn lettersPlaced\n\n\nproc initGrid(words: seq[string]): Grid =\n\tvar words = words\n\tfor numAttempts in 1..100:\n\t\twords.shuffle()\n\t\tnew(result)\n\t\tlet messageLen = result.placeMessage(\"Hello world!\")\n\t\tlet target = GridSize - messageLen\n\n\t\tvar cellsFilled = 0\n\t\tfor word in words:\n\t\t\tcellsFilled += result.tryPlaceWord(word)\n\t\t\tif cellsFilled == target:\n\t\t\t\tif result.solutions.len >= MinWords:\n\t\t\t\t\tresult.numAttempts = numAttempts\n\t\t\t\t\treturn\n\t\t\t\t# Grid is full but we didn't pack enough words: start over.\n\t\t\t\tbreak\n\nproc printResult(grid: Grid) =\n\tif grid.isNil or grid.numAttempts == 0:\n\t\techo \"No grid to display.\"\n\t\treturn\n\n\tlet size = grid.solutions.len\n\techo \"Attempts: \", grid.numAttempts\n\techo \"Number of words: \", size\n\n\techo \"\\n 0 1 2 3 4 5 6 7 8 9\\n\"\n\tfor r in 0.. 0:\n\t\tif (e and 1) == 1:\n\t\t\tresult = result * t mod p\n\t\tt = t * t mod p\n\t\te = e shr 1\n\nproc legendre*[T: SomeInteger](a, p: T): T = pow(a, (p-1) shr 1, p)\n\nproc tonelliShanks*[T: SomeInteger](n, p: T): T =\n\t# Check that n is indeed a square.\n\tif legendre(n, p) != 1:\n\t\traise newException(ValueError, \"Not a square\")\n\n\t# Factor out power of 2 from p-1.\n\tvar q = p - 1\n\tvar s = 0\n\twhile (q and 1) == 0:\n\t\ts += 1\n\t\tq = q shr 1\n\n\tif s == 1:\n\t\treturn pow(n, (p+1) shr 2, p)\n\n\t# Select a non-square z such as (z | p) = -1.\n\tvar z = 2\n\twhile legendre(z, p) != p - 1:\n\t\tz += 1\n\n\tvar\n\t\tc = pow(z, q, p)\n\t\tt = pow(n, q, p)\n\t\tm = s\n\tresult = pow(n, (q+1) shr 1, p)\n\twhile t != 1:\n\t\tvar\n\t\t\ti = 1\n\t\t\tz = t * t mod p\n\t\twhile z != 1 and i < m-1:\n\t\t\ti += 1\n\t\t\tz = z * z mod p\n\n\t\tvar b = pow(c, 1 shl (m-i-1), p)\n\t\tc = b * b mod p\n\t\tt = t * c mod p\n\t\tm = i\n\t\tresult = result * b mod p\n\nwhen isMainModule:\n\tproc run(n, p: SomeInteger) =\n\t\ttry:\n\t\t\tlet r = tonelliShanks(n, p)\n\t\t\techo r, \" \", p-r\n\t\texcept ValueError:\n\t\t\techo getCurrentExceptionMsg()\n\n\trun(10, 13)\n\trun(56, 101)\n\trun(1030, 10009)\n\trun(1032, 10009)\n\trun(44402, 100049)\n\trun(665820697, 1000000009)\n" + }, + { + "id": 1120, + "length": 2336, + "source": "Rosetta Code", + "text": "import macros, os, random\nimport ncurses\n\nwhen defined(Linux):\n\tproc positional_putch(x, y: int; ch: char) = mvaddch(x.cint, y.cint, ch.chtype)\n\tproc updateScreen = refresh()\n\tproc nonBlockingGetch(): char =\n\t\tlet c = getch()\n\t\tresult = if c in 0..255: char(c) else: '\\0'\n\tproc closeScreen = endwin()\n\nelse:\n\terror \"Not implemented\"\n\nconst\n\n\tW = 80\n\tH = 40\n\tSpace = 0\n\tFood = 1\n\tBorder = 2\n\tSymbol = [' ', '@', '.']\n\ntype\n\n\tDir {.pure.} = enum North, East, South, West\n\tGame = object\n\t\tboard: array[W * H, int]\n\t\thead: int\n\t\tdir: Dir\n\t\tquit: bool\n\n\nproc age(game: var Game) =\n\t## Reduce a time-to-live, effectively erasing the tail.\n\tfor i in 0.. 0:\n\t\tinc sum, n mod 10\n\t\tn = n div 10\n\tsum\n\nvar cnt = 0\nfor n in 1..10_000:\n\tvar factors = primeFactors(n)\n\tif factors.len > 1:\n\t\tvar sum = sumDigits(n)\n\t\tfor f in factors:\n\t\t\tdec sum, sumDigits(f)\n\t\tif sum == 0:\n\t\t\tstdout.write(\"{n:4} \")\n\t\t\tinc cnt\n\t\tif cnt == 10:\n\t\t\tcnt = 0\n\t\t\tstdout.write(\"\\n\")\necho()\n" + }, + { + "id": 1122, + "length": 3498, + "source": "Rosetta Code", + "text": "import random, strutils\nimport gintro/[gobject, glib, gtk, gio]\n\nconst Rows = 22\nconst Cols = 79\n\ntype\n\n\tBoard = array[Rows, array[Cols, int]]\n\n\n\tBState = object\n\t\tboard: Board\n\t\tscore: Natural\n\t\trow, col: int\n\n\n\tGame = ref object\n\t\twindow: Window\n\t\tscore: Natural\n\t\twon: string\n\t\tboard: Board\n\t\tbuttons: array[Rows, array[Cols, Button]]\n\t\tmyRow, myCol: Natural\n\t\tpastBoardStates: seq[BState]\n\n\nproc update(game: Game) =\n\t## Update game state.\n\tvar won = true\n\tfor i in 0.. 0: $val else: \"\")\n\n\t\tgame.buttons[game.myRow][game.myCol].setLabel(\"@\")\n\t\tgame.won = if won: \"WINNING \" else: \"\"\n\t\tgame.window.setTitle(game.won & \"Greed game (score: $#)\".format(game.score))\n\n\nproc eraseFromTile(game: Game; moveRow, moveCol: Natural) =\n\t## Erase tile values from the given tile.\n\tlet xdir = moveRow - game.myRow\n\tlet ydir = moveCol - game.myCol\n\tif abs(xdir) > 1 or abs(ydir) > 1 or xdir == 0 and ydir == 0 or game.board[moveRow][moveCol] == 0:\n\t\treturn\n\tgame.pastBoardStates.add BState(board: game.board, score: game.score,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trow: game.myRow, col: game.myCol)\n\tlet count = game.board[moveRow][moveCol]\n\tvar x: int = game.myRow\n\tvar y: int = game.myCol\n\tfor i in 1..count:\n\t\tinc x, xdir\n\t\tinc y, ydir\n\t\tif x in 0.. 0:\n\t\tlet bst = game.pastBoardStates.pop()\n\t\tgame.board = bst.board\n\t\tgame.score = bst.score\n\t\tgame.myRow = bst.row\n\t\tgame.myCol = bst.col\n\t\tgame.update()\n\n\nproc initialize(game: Game) =\n\t## Initialize the game.\n\tconst PossibleVals = {1..9}\n\tgame.score = 0\n\tgame.won = \"\"\n\tfor i in 0..\\n\"\n\t\t(x, y) = (nx, ny)\n\tof '+':\n\t\ttheta += PI / 5\n\tof '-':\n\t\ttheta -= PI / 5\n\tof '[':\n\t\tstack.add (x, y, theta)\n\tof ']':\n\t\t(x, y, theta) = stack.pop()\n\telse:\n\t\tdiscard\n\nlet svgFile = \"penrose_tiling.svg\".open(fmWrite)\nsvgFile.write \"\"\"\n\n\n\"\"\"\nsvgFile.write svg, \"\"\nsvgFile.close()\n" + }, + { + "id": 1124, + "length": 2418, + "source": "Rosetta Code", + "text": "import os, parseopt, random, sequtils, strformat, strutils\n\nconst Symbols = toSeq(\"!\\\"#$%&'()*+,-./:;<=>?@[]^_{|}~\")\n\n\nproc passGen(passLength = 10,\n\t\t\t\t\t\t count = 1,\n\t\t\t\t\t\t seed = 0,\n\t\t\t\t\t\t excludeSimilars = false): seq[string] =\n\t## Generate a sequence of passwords.\n\n\t# Initialize the random number generator.\n\tif seed == 0: randomize()\n\telse: randomize(seed)\n\n\t# Prepare list of chars per category.\n\tvar\n\t\tlowerLetters = toSeq('a'..'z')\n\t\tupperLetters = toSeq('A'..'Z')\n\t\tdigits = toSeq('0'..'9')\n\n\tif excludeSimilars:\n\t\tlowerLetters.delete(lowerLetters.find('l'))\n\t\tfor c in \"IOSZ\": upperLetters.delete(upperLetters.find(c))\n\t\tfor c in \"012\": digits.delete(digits.find(c))\n\n\tlet all = lowerLetters & upperLetters & digits & Symbols\n\n\t# Generate the passwords.\n\tfor _ in 1..count:\n\t\tvar password = newString(passLength)\n\t\tpassword[0] = lowerLetters.sample\n\t\tpassword[1] = upperLetters.sample\n\t\tpassword[2] = digits.sample\n\t\tpassword[3] = Symbols.sample\n\t\tfor i in 4.. 0: 1 else: -1\n\nproc showOutput(ws: FloatArray) =\n\tvar inputs: IntArray\n\tinputs[2] = 1 # bias.\n\tfor y in countdown(10, -9):\n\t\tinputs[1] = y\n\t\tfor x in countup(-9, 10):\n\t\t\tinputs[0] = x\n\t\t\tstdout.write if feedForward(inputs, ws) == 1: '#' else: 'O'\n\t\techo()\n\techo()\n\nproc train(ws: var FloatArray; runs: int) =\n\tvar inputs: IntArray\n\tinputs[2] = 1 # bias.\n\tfor _ in 1..runs:\n\t\tfor y in countdown(10, -9):\n\t\t\tinputs[1] = y\n\t\t\tfor x in countup(-9, 10):\n\t\t\t\tinputs[0] = x\n\t\t\t\tlet error = targetOutput(x, y) - feedForward(inputs, ws)\n\t\t\t\tfor i in 0..2:\n\t\t\t\t\tws[i] += float(error * inputs[i]) * 0.01 # 0.01 is the learning constant.\n\nwhen isMainModule:\n\tvar weights: FloatArray\n\techo \"Target output for the function f(x) = 2x + 1:\"\n\tshowTargetOutput()\n\trandomWeights(weights)\n\techo \"Output from untrained perceptron:\"\n\tshowOutput(weights)\n\ttrain(weights, 1)\n\techo \"Output from perceptron after 1 training run:\"\n\tshowOutput(weights)\n\ttrain(weights, 4)\n\techo \"Output from perceptron after 5 training runs:\"\n\tshowOutput(weights)\n" + }, + { + "id": 1126, + "length": 1345, + "source": "Rosetta Code", + "text": "import heapqueue, os, sequtils, streams\n\ntype\n\t\tSource = tuple[stream: Stream; line: string]\n\t\tSourceHeap = HeapQueue[Source]\n\n\n# Comparison of sources. Needed for the heap to sort the sources by line contents.\nproc `<`(a, b: Source): bool = a.line < b.line\n\n\nproc add(heap: var SourceHeap; stream: Stream) =\n\t## Add a stream to the heap.\n\tif stream.atEnd:\n\t\tstream.close()\n\telse:\n\t\theap.push((stream, stream.readLine()))\n\n\nproc merge(inStreams: seq[Stream]; outStream: Stream) =\n\t## Merge the input streams into an output stream.\n\n\t# Initialize the heap.\n\tvar heap: SourceHeap\n\tfor stream in inStreams:\n\t\theap.add(stream)\n\n\t# Merging loop.\n\twhile heap.len > 0:\n\t\tlet (stream, line) = heap.pop()\n\t\toutStream.writeLine line\n\t\theap.add(stream)\n\n\nwhen isMainModule:\n\n\tconst\n\t\tData = [\"Line 001\\nLine 008\\nLine 017\\n\",\n\t\t\t\t\t\t\"Line 019\\nLine 033\\nLine 044\\nLine 055\\n\",\n\t\t\t\t\t\t\"Line 019\\nLine 029\\nLine 039\\n\",\n\t\t\t\t\t\t\"Line 023\\nLine 030\\n\"]\n\t\tFilenames = [\"file1.txt\", \"file2.txt\", \"file3.txt\", \"file4.txt\"]\n\n\t# Create files.\n\tfor i, name in Filenames:\n\t\twriteFile(name, Data[i])\n\n\t# Create input and output streams.\n\tlet inStreams = Filenames.mapIt(Stream(newFileStream(it)))\n\tlet outStream = Stream(newFileStream(stdout))\n\n\t# Merge the streams.\n\tmerge(inStreams, outStream)\n\n\t# Clean-up: delete the files.\n\tfor name in Filenames:\n\t\tremoveFile(name)\n" + }, + { + "id": 1127, + "length": 1151, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils, tables\n\nproc markov(filePath: string; keySize, outputSize: Positive): string =\n\n\tlet words = filePath.readFile().strip(false, true).splitWhitespace()\n\tdoAssert outputSize in keySize..words.len, \"Output size is out of range\"\n\n\tvar dict: Table[string, seq[string]]\n\n\tfor i in 0..(words.len - keySize):\n\t\tlet prefix = words[i..<(i+keySize)].join(\" \")\n\t\tlet suffix = if i + keySize < words.len: words[i + keySize] else: \"\"\n\t\tdict.mgetOrPut(prefix, @[]).add suffix\n\n\tvar output: seq[string]\n\tvar prefix = toSeq(dict.keys).sample()\n\toutput.add prefix.split(' ')\n\n\tfor n in 1..words.len:\n\t\tlet nextWord = dict[prefix].sample()\n\t\tif nextWord.len == 0: break\n\t\toutput.add nextWord\n\t\tif output.len >= outputSize: break\n\t\tprefix = output[n..<(n + keySize)].join(\" \")\n\n\tresult = output[0..= 2 and text[0] == '/' and text[1] == '*':\n\t\t\tstripComment(text, lineNo, colNo)\n\t\telse: return\n\nproc lookAhead(ch1, ch2: char, tk1, tk2: TokenKind): (TokenKind, int) =\n\tif ch1 == ch2: (tk1, 2)\n\telse: (tk2, 1)\n\nproc consumeToken(text: var string; tkl: var int): Token =\n\t## Return token removing it from the `text` and write its length to\n\t## `tkl`. If the token can not be defined, return `tkUnknown` as a\n\t## token, shrink text by 1 and write 1 to its length.\n\n\tvar\n\t\tmatches: array[1, string]\n\t\ttKind: TokenKind\n\t\tval: string\n\n\tif text.len == 0:\n\t\t(tKind, tkl) = (tkEof, 0)\n\n\t# Simple characters\n\telif text[0] in symbols: (tKind, tkl) = (tkSymbols.findTokenKind(text[0]), 1)\n\telif text[0] == '<': (tKind, tkl) = lookAhead(text[1], '=', tkLte, tkLt)\n\telif text[0] == '>': (tKind, tkl) = lookAhead(text[1], '=', tkGte, tkGt)\n\telif text[0] == '=': (tKind, tkl) = lookAhead(text[1], '=', tkEq, tkAsgn)\n\telif text[0] == '!': (tKind, tkl) = lookAhead(text[1], '=', tkNeq, tkNot)\n\telif text[0] == '&': (tKind, tkl) = lookAhead(text[1], '&', tkAnd, tkUnknown)\n\telif text[0] == '|': (tKind, tkl) = lookAhead(text[1], '|', tkOr, tkUnknown)\n\n\t# Keywords\n\telif match(text, re\"\\Aif\\b\"): (tKind, tkl) = (tkIf, 2)\n\telif match(text, re\"\\Aelse\\b\"): (tKind, tkl) = (tkElse, 4)\n\telif match(text, re\"\\Awhile\\b\"): (tKind, tkl) = (tkWhile, 5)\n\telif match(text, re\"\\Aprint\\b\"): (tKind, tkl) = (tkPrint, 5)\n\telif match(text, re\"\\Aputc\\b\"): (tKind, tkl) = (tkPutc, 4)\n\n\t# Literals and identifiers\n\telif match(text, re\"\\A([0-9]+)\", matches):\n\t\t(tKind, tkl) = (tkInt, matches[0].len)\n\t\tval = matches[0]\n\telif match(text, re\"\\A([_a-zA-Z][_a-zA-Z0-9]*)\", matches):\n\t\t(tKind, tkl) = (tkId, matches[0].len)\n\t\tval = matches[0]\n\telif match(text, re\"\\A('(?:[^'\\n]|\\\\\\\\|\\\\n)')\", matches):\n\t\t(tKind, tkl) = (tkChar, matches[0].len)\n\t\tval = case matches[0]\n\t\t\t\t\tof r\"' '\": $ord(' ')\n\t\t\t\t\tof r\"'\\n'\": $ord('\\n')\n\t\t\t\t\tof r\"'\\\\'\": $ord('\\\\')\n\t\t\t\t\telse: $ord(matches[0][1]) # \"'a'\"[1] == 'a'\n\telif match(text, re\"\\A(\"\"[^\"\"\\n]*\"\")\", matches):\n\t\t(tKind, tkl) = (tkStr, matches[0].len)\n\t\tval = matches[0]\n\telse: (tKind, tkl) = (tkUnknown, 1)\n\n\ttext = text[tkl..^1]\n\tToken(kind: tKind, value: val)\n\nproc tokenize*(text: string): seq[TokenAnn] =\n\tresult = newSeq[TokenAnn]()\n\tvar\n\t\tlineNo, colNo: int = 1\n\t\ttext = text\n\t\ttoken: Token\n\t\ttokenLength: int\n\n\twhile text.len > 0:\n\t\tstripUnimportant(text, lineNo, colNo)\n\t\ttoken = consumeToken(text, tokenLength)\n\t\tresult.add TokenAnn(token: token, line: lineNo, column: colNo)\n\t\tinc colNo, tokenLength\n\nproc output*(s: seq[TokenAnn]): string =\n\tvar\n\t\ttokenKind: TokenKind\n\t\tvalue: string\n\t\tline, column: int\n\n\tfor tokenAnn in items(s):\n\t\tline = tokenAnn.line\n\t\tcolumn = tokenAnn.column\n\t\ttokenKind = tokenAnn.token.kind\n\t\tvalue = tokenAnn.token.value\n\t\tresult.add(\n\t\t\tfmt\"{line:>5}{column:>7} {tokenKind:<15}{value}\"\n\t\t\t\t.strip(leading = false) & \"\\n\")\n\nwhen isMainModule:\n\timport os\n\n\tlet input = if paramCount() > 0: readFile paramStr(1)\n\t\t\t\t\t\t\telse: readAll stdin\n\n\techo input.tokenize.output\n" + }, + { + "id": 1133, + "length": 7066, + "source": "Rosetta Code", + "text": "import lexbase, streams\nfrom strutils import Whitespace\n\ntype\n\tTokenKind = enum\n\t\ttkInvalid = \"Invalid\",\n\t\ttkOpMultiply = \"Op_multiply\",\n\t\ttkOpDivide = \"Op_divide\",\n\t\ttkOpMod = \"Op_mod\",\n\t\ttkOpAdd = \"Op_add\",\n\t\ttkOpSubtract = \"Op_subtract\",\n\t\ttkOpLess = \"Op_less\",\n\t\ttkOpLessEqual = \"Op_lessequal\",\n\t\ttkOpGreater = \"Op_greater\",\n\t\ttkOpGreaterEqual = \"Op_greaterequal\",\n\t\ttkOpEqual = \"Op_equal\",\n\t\ttkOpNotEqual = \"Op_notequal\",\n\t\ttkOpNot = \"Op_not\",\n\t\ttkOpAssign = \"Op_assign\",\n\t\ttkOpAnd = \"Op_and\",\n\t\ttkOpOr = \"Op_or\",\n\t\ttkLeftParen = \"LeftParen\",\n\t\ttkRightParen = \"RightParen\",\n\t\ttkLeftBrace = \"LeftBrace\",\n\t\ttkRightBrace = \"RightBrace\",\n\t\ttkSemicolon = \"Semicolon\",\n\t\ttkComma = \"Comma\",\n\t\ttkKeywordIf = \"Keyword_if\",\n\t\ttkKeywordElse = \"Keyword_else\",\n\t\ttkKeywordWhile = \"Keyword_while\",\n\t\ttkKeywordPrint = \"Keyword_print\",\n\t\ttkKeywordPutc = \"Keyword_putc\",\n\t\ttkIdentifier = \"Identifier\",\n\t\ttkInteger = \"Integer\",\n\t\ttkString = \"String\",\n\t\ttkEndOfInput = \"End_of_input\"\n\n\tLexer = object of BaseLexer\n\t\tkind: TokenKind\n\t\ttoken, error: string\n\t\tstartPos: int\n\ntemplate setError(l: var Lexer; err: string): untyped =\n\tl.kind = tkInvalid\n\tif l.error.len == 0:\n\t\tl.error = err\n\nproc hasError(l: Lexer): bool {.inline.} =\n\tl.error.len > 0\n\nproc open(l: var Lexer; input: Stream) {.inline.} =\n\tlexbase.open(l, input)\n\tl.startPos = 0\n\tl.kind = tkInvalid\n\tl.token = \"\"\n\tl.error = \"\"\n\nproc handleNewLine(l: var Lexer) =\n\tcase l.buf[l.bufpos]\n\tof '\\c': l.bufpos = l.handleCR l.bufpos\n\tof '\\n': l.bufpos = l.handleLF l.bufpos\n\telse: discard\n\nproc skip(l: var Lexer) =\n\twhile true:\n\t\tcase l.buf[l.bufpos]\n\t\tof Whitespace:\n\t\t\tif l.buf[l.bufpos] notin NewLines:\n\t\t\t\tinc l.bufpos\n\t\t\telse:\n\t\t\t\thandleNewLine l\n\t\tof '/':\n\t\t\tif l.buf[l.bufpos + 1] == '*':\n\t\t\t\tinc l.bufpos, 2\n\t\t\t\twhile true:\n\t\t\t\t\tcase l.buf[l.bufpos]\n\t\t\t\t\tof '*':\n\t\t\t\t\t\tif l.buf[l.bufpos + 1] == '/':\n\t\t\t\t\t\t\tinc l.bufpos, 2\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse: inc l.bufpos\n\t\t\t\t\tof NewLines:\n\t\t\t\t\t\thandleNewLine l\n\t\t\t\t\tof EndOfFile:\n\t\t\t\t\t\tsetError l, \"EOF reached in comment\"\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tinc l.bufpos\n\t\t\telse: break\n\t\telse: break\n\nproc handleSpecial(l: var Lexer): char =\n\tassert l.buf[l.bufpos] == '\\\\'\n\tinc l.bufpos\n\tcase l.buf[l.bufpos]\n\tof 'n':\n\t\tl.token.add \"\\\\n\"\n\t\tresult = '\\n'\n\t\tinc l.bufpos\n\tof '\\\\':\n\t\tl.token.add \"\\\\\\\\\"\n\t\tresult = '\\\\'\n\t\tinc l.bufpos\n\telse:\n\t\tsetError l, \"Unknown escape sequence: '\\\\\" & l.buf[l.bufpos] & \"'\"\n\t\tresult = '\\0'\n\nproc handleChar(l: var Lexer) =\n\tassert l.buf[l.bufpos] == '\\''\n\tl.startPos = l.getColNumber l.bufpos\n\tl.kind = tkInvalid\n\tinc l.bufpos\n\tif l.buf[l.bufpos] == '\\\\':\n\t\tl.token = $ord(handleSpecial l)\n\t\tif hasError l: return\n\telif l.buf[l.bufpos] == '\\'':\n\t\tsetError l, \"Empty character constant\"\n\t\treturn\n\telse:\n\t\tl.token = $ord(l.buf[l.bufpos])\n\t\tinc l.bufpos\n\tif l.buf[l.bufpos] == '\\'':\n\t\tl.kind = tkInteger\n\t\tinc l.bufpos\n\telse:\n\t\tsetError l, \"Multi-character constant\"\n\nproc handleString(l: var Lexer) =\n\tassert l.buf[l.bufpos] == '\"'\n\tl.startPos = l.getColNumber l.bufpos\n\tl.token = \"\\\"\"\n\tinc l.bufpos\n\twhile true:\n\t\tcase l.buf[l.bufpos]\n\t\tof '\\\\':\n\t\t\tdiscard handleSpecial l\n\t\t\tif hasError l: return\n\t\tof '\"':\n\t\t\tl.kind = tkString\n\t\t\tadd l.token, '\"'\n\t\t\tinc l.bufpos\n\t\t\tbreak\n\t\tof NewLines:\n\t\t\tsetError l, \"EOL reached before end-of-string\"\n\t\t\treturn\n\t\tof EndOfFile:\n\t\t\tsetError l, \"EOF reached before end-of-string\"\n\t\t\treturn\n\t\telse:\n\t\t\tadd l.token, l.buf[l.bufpos]\n\t\t\tinc l.bufpos\n\nproc handleNumber(l: var Lexer) =\n\tassert l.buf[l.bufpos] in {'0'..'9'}\n\tl.startPos = l.getColNumber l.bufpos\n\tl.token = \"0\"\n\twhile l.buf[l.bufpos] == '0': inc l.bufpos\n\twhile true:\n\t\tcase l.buf[l.bufpos]\n\t\tof '0'..'9':\n\t\t\tif l.token == \"0\":\n\t\t\t\tsetLen l.token, 0\n\t\t\tadd l.token, l.buf[l.bufpos]\n\t\t\tinc l.bufpos\n\t\tof 'a'..'z', 'A'..'Z', '_':\n\t\t\tsetError l, \"Invalid number\"\n\t\t\treturn\n\t\telse:\n\t\t\tl.kind = tkInteger\n\t\t\tbreak\n\nproc handleIdent(l: var Lexer) =\n\tassert l.buf[l.bufpos] in {'a'..'z'}\n\tl.startPos = l.getColNumber l.bufpos\n\tsetLen l.token, 0\n\twhile true:\n\t\tif l.buf[l.bufpos] in {'a'..'z', 'A'..'Z', '0'..'9', '_'}:\n\t\t\tadd l.token, l.buf[l.bufpos]\n\t\t\tinc l.bufpos\n\t\telse:\n\t\t\tbreak\n\tl.kind = case l.token\n\t\t\t\t\t of \"if\": tkKeywordIf\n\t\t\t\t\t of \"else\": tkKeywordElse\n\t\t\t\t\t of \"while\": tkKeywordWhile\n\t\t\t\t\t of \"print\": tkKeywordPrint\n\t\t\t\t\t of \"putc\": tkKeywordPutc\n\t\t\t\t\t else: tkIdentifier\n\nproc getToken(l: var Lexer): TokenKind =\n\tl.kind = tkInvalid\n\tsetLen l.token, 0\n\tskip l\n\n\tcase l.buf[l.bufpos]\n\tof '*':\n\t\tl.kind = tkOpMultiply\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '/':\n\t\tl.kind = tkOpDivide\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '%':\n\t\tl.kind = tkOpMod\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '+':\n\t\tl.kind = tkOpAdd\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '-':\n\t\tl.kind = tkOpSubtract\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '<':\n\t\tl.kind = tkOpLess\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\t\tif l.buf[l.bufpos] == '=':\n\t\t\tl.kind = tkOpLessEqual\n\t\t\tinc l.bufpos\n\tof '>':\n\t\tl.kind = tkOpGreater\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\t\tif l.buf[l.bufpos] == '=':\n\t\t\tl.kind = tkOpGreaterEqual\n\t\t\tinc l.bufpos\n\tof '=':\n\t\tl.kind = tkOpAssign\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\t\tif l.buf[l.bufpos] == '=':\n\t\t\tl.kind = tkOpEqual\n\t\t\tinc l.bufpos\n\tof '!':\n\t\tl.kind = tkOpNot\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\t\tif l.buf[l.bufpos] == '=':\n\t\t\tl.kind = tkOpNotEqual\n\t\t\tinc l.bufpos\n\tof '&':\n\t\tif l.buf[l.bufpos + 1] == '&':\n\t\t\tl.kind = tkOpAnd\n\t\t\tl.startPos = l.getColNumber l.bufpos\n\t\t\tinc l.bufpos, 2\n\t\telse:\n\t\t\tsetError l, \"Unrecognized character\"\n\tof '|':\n\t\tif l.buf[l.bufpos + 1] == '|':\n\t\t\tl.kind = tkOpOr\n\t\t\tl.startPos = l.getColNumber l.bufpos\n\t\t\tinc l.bufpos, 2\n\t\telse:\n\t\t\tsetError l, \"Unrecognized character\"\n\tof '(':\n\t\tl.kind = tkLeftParen\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof ')':\n\t\tl.kind = tkRightParen\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '{':\n\t\tl.kind = tkLeftBrace\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '}':\n\t\tl.kind = tkRightBrace\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof ';':\n\t\tl.kind = tkSemicolon\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof ',':\n\t\tl.kind = tkComma\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tinc l.bufpos\n\tof '\\'': handleChar l\n\tof '\"': handleString l\n\tof '0'..'9': handleNumber l\n\tof 'a'..'z', 'A'..'Z': handleIdent l\n\tof EndOfFile:\n\t\tl.startPos = l.getColNumber l.bufpos\n\t\tl.kind = tkEndOfInput\n\telse:\n\t\tsetError l, \"Unrecognized character\"\n\tresult = l.kind\n\nwhen isMainModule:\n\timport os, strformat\n\tproc main() =\n\t\tvar l: Lexer\n\t\tif paramCount() < 1:\n\t\t\topen l, newFileStream stdin\n\t\telse:\n\t\t\topen l, newFileStream paramStr(1)\n\t\twhile l.getToken notin {tkInvalid}:\n\t\t\tstdout.write \"{l.lineNumber:5} {l.startPos + 1:5} {l.kind:<14}\"\n\t\t\tif l.kind in {tkIdentifier, tkInteger, tkString}:\n\t\t\t\tstdout.write \" {l.token}\"\n\t\t\tstdout.write '\\n'\n\t\t\tif l.kind == tkEndOfInput:\n\t\t\t\tbreak\n\t\tif hasError l:\n\t\t\techo \"({l.lineNumber},{l.getColNumber l.bufpos + 1}) {l.error}\"\n\tmain()\n" + }, + { + "id": 1134, + "length": 5727, + "source": "Rosetta Code", + "text": "import strutils\n\ntype\n\n\tTokenKind* = enum\n\t\ttokMult = \"Op_multiply\", tokDiv = \"Op_divide\", tokMod = \"Op_mod\",\n\t\ttokAdd = \"Op_add\", tokSub = \"Op_subtract\", tokLess = \"Op_less\",\n\t\ttokLessEq = \"Op_lessequal\", tokGreater = \"Op_greater\",\n\t\ttokGreaterEq = \"Op_greaterequal\", tokEq = \"Op_equal\",\n\t\ttokNotEq = \"Op_notequal\", tokNot = \"Op_not\", tokAssign = \"Op_assign\",\n\t\ttokAnd = \"Op_and\", tokOr = \"Op_or\"\n\t\ttokLPar = \"LeftParen\", tokRPar = \"RightParen\"\n\t\ttokLBrace = \"LeftBrace\", tokRBrace = \"RightBrace\"\n\t\ttokSemi = \"Semicolon\", tokComma = \"Comma\"\n\t\ttokIf = \"Keyword_if\", tokElse = \"Keyword_else\", tokWhile = \"Keyword_while\",\n\t\ttokPrint = \"Keyword_print\", tokPutc = \"Keyword_putc\"\n\t\ttokIdent = \"Identifier\", tokInt = \"Integer\", tokChar = \"Integer\",\n\t\ttokString = \"String\"\n\t\ttokEnd = \"End_of_input\"\n\n\tToken* = object\n\t\tln*, col*: int\n\t\tcase kind*: TokenKind\n\t\tof tokIdent: ident*: string\n\t\tof tokInt: intVal*: int\n\t\tof tokChar: charVal*: char\n\t\tof tokString: stringVal*: string\n\t\telse: discard\n\n\tLexer* = object\n\t\tinput: string\n\t\tpos: int\n\t\tln, col: int\n\n\tLexicalError* = object of CatchableError\n\t\tln*, col*: int\n\nproc error(lexer: var Lexer, message: string) =\n\tvar err = newException(LexicalError, message)\n\terr.ln = lexer.ln\n\terr.col = lexer.col\n\ntemplate current: char =\n\tif lexer.pos < lexer.input.len: lexer.input[lexer.pos]\n\telse: '\\x00'\ntemplate get(n: int): string =\n\tif lexer.pos < lexer.input.len:\n\t\tlexer.input[min(lexer.pos, lexer.input.len)..\n\t\t\t\t\t\t\t\tmin(lexer.pos + n - 1, lexer.input.len)]\n\telse: \"\"\n\ntemplate next() =\n\tinc(lexer.pos); inc(lexer.col)\n\tif current() == '\\n':\n\t\tinc(lexer.ln)\n\t\tlexer.col = 0\n\telif current() == '\\r':\n\t\tlexer.col = 0\n\nproc skip(lexer: var Lexer) =\n\twhile true:\n\t\tif current() in Whitespace:\n\t\t\twhile current() in Whitespace:\n\t\t\t\tnext()\n\t\t\tcontinue\n\t\telif get(2) == \"/*\":\n\t\t\tnext(); next()\n\t\t\twhile get(2) != \"*/\":\n\t\t\t\tif current() == '\\x00':\n\t\t\t\t\tlexer.error(\"Unterminated comment\")\n\t\t\t\tnext()\n\t\t\tnext(); next()\n\t\t\tcontinue\n\t\telse: discard\n\t\tbreak\n\nproc charOrEscape(lexer: var Lexer): char =\n\tif current() != '\\\\':\n\t\tresult = current()\n\t\tnext()\n\telse:\n\t\tnext()\n\t\tcase current()\n\t\tof 'n': result = '\\n'\n\t\tof '\\\\': result = '\\\\'\n\t\telse: lexer.error(\"Unknown escape sequence '\\\\\" & current() & \"'\")\n\t\tnext()\n\nproc next*(lexer: var Lexer): Token =\n\tlet\n\t\tln = lexer.ln\n\t\tcol = lexer.col\n\n\tcase current()\n\tof '*': result = Token(kind: tokMult); next()\n\tof '/': result = Token(kind: tokDiv); next()\n\tof '%': result = Token(kind: tokMod); next()\n\tof '+': result = Token(kind: tokAdd); next()\n\tof '-': result = Token(kind: tokSub); next()\n\tof '<':\n\t\tnext()\n\t\tif current() == '=': result = Token(kind: tokLessEq)\n\t\telse: result = Token(kind: tokLess)\n\tof '>':\n\t\tnext()\n\t\tif current() == '=':\n\t\t\tresult = Token(kind: tokGreaterEq)\n\t\t\tnext()\n\t\telse:\n\t\t\tresult = Token(kind: tokGreater)\n\tof '=':\n\t\tnext()\n\t\tif current() == '=':\n\t\t\tresult = Token(kind: tokEq)\n\t\t\tnext()\n\t\telse:\n\t\t\tresult = Token(kind: tokAssign)\n\tof '!':\n\t\tnext()\n\t\tif current() == '=':\n\t\t\tresult = Token(kind: tokNotEq)\n\t\t\tnext()\n\t\telse:\n\t\t\tresult = Token(kind: tokNot)\n\tof '&':\n\t\tnext()\n\t\tif current() == '&':\n\t\t\tresult = Token(kind: tokAnd)\n\t\t\tnext()\n\t\telse:\n\t\t\tlexer.error(\"'&&' expected\")\n\tof '|':\n\t\tnext()\n\t\tif current() == '|':\n\t\t\tresult = Token(kind: tokOr)\n\t\t\tnext()\n\t\telse:\n\t\t\tlexer.error(\"'||' expected\")\n\tof '(': result = Token(kind: tokLPar); next()\n\tof ')': result = Token(kind: tokRPar); next()\n\tof '{': result = Token(kind: tokLBrace); next()\n\tof '}': result = Token(kind: tokRBrace); next()\n\tof ';': result = Token(kind: tokSemi); next()\n\tof ',': result = Token(kind: tokComma); next()\n\tof '\\'':\n\t\tnext()\n\t\tif current() == '\\'': lexer.error(\"Empty character literal\")\n\t\tlet ch = lexer.charOrEscape()\n\t\tif current() != '\\'':\n\t\t\tlexer.error(\"Character literal must contain a single character or \" &\n\t\t\t\t\t\t\t\t\t\"escape sequence\")\n\t\tresult = Token(kind: tokChar, charVal: ch)\n\t\tnext()\n\tof '0'..'9':\n\t\tvar number = \"\"\n\t\twhile current() in Digits:\n\t\t\tnumber.add(current())\n\t\t\tnext()\n\t\tif current() in IdentStartChars:\n\t\t\tlexer.error(\"Integer literal ends in non-digit characters\")\n\t\tresult = Token(kind: tokInt, intVal: parseInt(number))\n\tof '\"':\n\t\tnext()\n\t\tvar str = \"\"\n\t\twhile current() notin {'\"', '\\x00', '\\n'}:\n\t\t\tstr.add(lexer.charOrEscape())\n\t\tif current() == '\\x00':\n\t\t\tlexer.error(\"Unterminated string literal\")\n\t\telif current() == '\\n':\n\t\t\tlexer.error(\"Line feed in string literal\")\n\t\telse:\n\t\t\tnext()\n\t\t\tresult = Token(kind: tokString, stringVal: str)\n\tof IdentStartChars:\n\t\tvar ident = $current()\n\t\tnext()\n\t\twhile current() in IdentChars:\n\t\t\tident.add(current())\n\t\t\tnext()\n\t\tcase ident\n\t\tof \"if\": result = Token(kind: tokIf)\n\t\tof \"else\": result = Token(kind: tokElse)\n\t\tof \"while\": result = Token(kind: tokWhile)\n\t\tof \"print\": result = Token(kind: tokPrint)\n\t\tof \"putc\": result = Token(kind: tokPutc)\n\t\telse: result = Token(kind: tokIdent, ident: ident)\n\tof '\\x00':\n\t\tresult = Token(kind: tokEnd)\n\telse:\n\t\tlexer.error(\"Unexpected character: '\" & current() & \"'\")\n\n\tresult.ln = ln\n\tresult.col = col\n\tlexer.skip()\n\nproc peek*(lexer: var Lexer): Token =\n\tdiscard\n\nproc initLexer*(input: string): Lexer =\n\tresult = Lexer(input: input, pos: 0, ln: 1, col: 1)\n\tresult.skip()\n\nwhen isMainModule:\n\tlet code = readAll(stdin)\n\tvar\n\t\tlexer = initLexer(code)\n\t\ttoken: Token\n\twhile true:\n\t\ttoken = lexer.next()\n\t\tstdout.write(token.ln, ' ', token.col, ' ', token.kind)\n\t\tcase token.kind\n\t\tof tokInt: stdout.write(' ', token.intVal)\n\t\tof tokChar: stdout.write(' ', token.charVal.ord)\n\t\tof tokString: stdout.write(\" \\\"\", token.stringVal\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\\\\", \"\\\\\\\\\")\n\t\t\t\t\t\t\t\t\t\t.replace(\"\\n\", \"\\\\n\"), '\"')\n\t\tof tokIdent: stdout.write(' ', token.ident)\n\t\telse: discard\n\t\tstdout.write('\\n')\n\t\tif token.kind == tokEnd:\n\t\t\tbreak\n" + }, + { + "id": 1135, + "length": 1169, + "source": "Rosetta Code", + "text": "import math\n\nimport imageman\n\n\nfunc hsvToRgb(h, s, v: float): ColorRGBU =\n\t## Convert HSV values to RGB values.\n\n\tlet hp = h / 60\n\tlet c = s * v\n\tlet x = c * (1 - abs(hp mod 2 - 1))\n\tlet m = v - c\n\tvar r, g, b = 0.0\n\tif hp <= 1:\n\t\tr = c\n\t\tg = x\n\telif hp <= 2:\n\t\tr = x\n\t\tg = c\n\telif hp <= 3:\n\t\tg = c\n\t\tb = x\n\telif hp <= 4:\n\t\tg = x\n\t\tb= c\n\telif hp <= 5:\n\t\tr = x\n\t\tb = c\n\telse:\n\t\tr = c\n\t\tb = x\n\tr += m\n\tg += m\n\tb += m\n\tresult = ColorRGBU [byte(r * 255), byte(g * 255), byte(b * 255)]\n\n\nfunc buildColorWheel(image: var Image) =\n\t## Build a color wheel into the image.\n\n\tconst Margin = 10\n\tlet diameter = min(image.w, image.h) - 2 * Margin\n\tlet xOffset = (image.w - diameter) div 2\n\tlet yOffset = (image.h - diameter) div 2\n\tlet radius = diameter / 2\n\n\tfor x in 0..diameter:\n\t\tlet rx = x.toFloat - radius\n\t\tfor y in 0..diameter:\n\t\t\tlet ry = y.toFloat - radius\n\t\t\tlet r = hypot(rx, ry) / radius\n\t\t\tif r > 1: continue\n\t\t\tlet a = 180 + arctan2(ry, -rx).radToDeg()\n\t\t\timage[x + xOffset, y + yOffset] = hsvToRgb(a, r, 1)\n\n\nconst\n\tSide = 400\n\tOutput = \"color_wheel.png\"\n\nvar image = initImage[ColorRGBU](Side, Side)\nimage.buildColorWheel()\n\nimage.savePNG(Output, compression = 9)\n" + }, + { + "id": 1136, + "length": 1182, + "source": "Rosetta Code", + "text": "import math, os, strformat\n\nconst\n\tMaxPower = 10\n\tPowers = [1, 10, 100]\n\nfunc powerWithUnit(idx: int): string =\n\t## Return a string representing value 10^idx with a unit.\n\tif idx < 0:\n\t\t\"0B\"\n\telif idx < 3:\n\t\tfmt\"{Powers[idx]}B\"\n\telif idx < 6:\n\t\tfmt\"{Powers[idx - 3]}kB\"\n\telif idx < 9:\n\t\tfmt\"{Powers[idx - 6]}MB\"\n\telse:\n\t\tfmt\"{Powers[idx - 9]}GB\"\n\n\n# Retrieve the directory path.\nvar dirpath: string\nif paramCount() == 0:\n\tdirpath = getCurrentDir()\nelse:\n\tdirpath = paramStr(1)\n\tif not dirExists(dirpath):\n\t\traise newException(ValueError, \"wrong directory path: \" & dirpath)\n\n# Distribute sizes.\nvar counts: array[-1..MaxPower, Natural]\nfor path in dirpath.walkDirRec():\n\tif not path.fileExists():\n\t\tcontinue # Not a regular file.\n\tlet size = getFileSize(path)\n\tlet index = if size == 0: -1 else: log10(size.float).toInt\n\tinc counts[index]\n\n# Display distribution.\nlet total = sum(counts)\necho \"File size distribution for directory: \", dirpath\necho \"\"\nfor idx, count in counts:\n\tlet rangeString = fmt\"[{powerWithUnit(idx)}..{powerWithUnit(idx + 1)}[:\"\n\techo fmt\"Size in {rangeString: 14} {count:>7} {100 * count / total:5.2f}%\"\necho \"\"\necho \"Total number of files: \", sum(counts)\n" + }, + { + "id": 1137, + "length": 6369, + "source": "Rosetta Code", + "text": "import ast_lexer\n\ntype NodeKind* = enum\n\t\t\t\t\t\t\t\t\t\tnIdentifier = \"Identifier\"\n\t\t\t\t\t\t\t\t\t\tnString = \"String\"\n\t\t\t\t\t\t\t\t\t\tnInteger = \"Integer\"\n\t\t\t\t\t\t\t\t\t\tnSequence = \"Sequence\"\n\t\t\t\t\t\t\t\t\t\tnIf = \"If\"\n\t\t\t\t\t\t\t\t\t\tnPrtc = \"Prtc\"\n\t\t\t\t\t\t\t\t\t\tnPrts = \"Prts\"\n\t\t\t\t\t\t\t\t\t\tnPrti = \"Prti\"\n\t\t\t\t\t\t\t\t\t\tnWhile = \"While\"\n\t\t\t\t\t\t\t\t\t\tnAssign = \"Assign\"\n\t\t\t\t\t\t\t\t\t\tnNegate = \"Negate\"\n\t\t\t\t\t\t\t\t\t\tnNot = \"Not\"\n\t\t\t\t\t\t\t\t\t\tnMultiply = \"Multiply\"\n\t\t\t\t\t\t\t\t\t\tnDivide = \"Divide\"\n\t\t\t\t\t\t\t\t\t\tnMod = \"Mod\"\n\t\t\t\t\t\t\t\t\t\tnAdd = \"Add\"\n\t\t\t\t\t\t\t\t\t\tnSubtract = \"Subtract\"\n\t\t\t\t\t\t\t\t\t\tnLess = \"Less\"\n\t\t\t\t\t\t\t\t\t\tnLessEqual = \"LessEqual\"\n\t\t\t\t\t\t\t\t\t\tnGreater = \"Greater\"\n\t\t\t\t\t\t\t\t\t\tnGreaterEqual = \"GreaterEqual\"\n\t\t\t\t\t\t\t\t\t\tnEqual = \"Equal\"\n\t\t\t\t\t\t\t\t\t\tnNotEqual = \"NotEqual\"\n\t\t\t\t\t\t\t\t\t\tnAnd = \"And\"\n\t\t\t\t\t\t\t\t\t\tnOr = \"Or\"\n\ntype Node* = ref object\n\tleft*: Node\n\tright*: Node\n\tcase kind*: NodeKind\n\tof nString: stringVal*: string\n\tof nInteger: intVal*: int\n\tof nIdentifier: name*: string\n\telse: nil\n\ntype Operator = range[tokMult..tokOr]\n\nconst\n\n\tPrecedences: array[Operator, int] = [13, # tokMult\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 13, # tokDiv\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 13, # tokMod\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 12, # tokAdd\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 12, # tokSub\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 10, # tokLess\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 10, # tokLessEq\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 10, # tokGreater\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 10, # tokGreaterEq\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t9, # tokEq\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t9, # tokNeq\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 14, # tokNot\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t -1, # tokAssign\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t5, # tokAnd\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t4] # tokOr\n\tUnaryPrecedence = 14\n\tBinaryOperators = {tokMult, tokDiv, tokMod, tokAdd, tokSub, tokLess, tokLessEq,\n\t\t\t\t\t\t\t\t\t\ttokGreater, tokGreaterEq, tokEq, tokNotEq, tokAnd, tokOr}\n\n\t# Mapping of operators from TokenKind to NodeKind.\n\tNodeKinds: array[Operator, NodeKind] = [nMultiply, nDivide, nMod, nAdd, nSubtract,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnLess, nLessEqual, nGreater, nGreaterEqual,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnEqual, nNotEqual, nNot, nAssign, nAnd, nOr]\n\ntype SyntaxError* = object of CatchableError\n\n\n\ntemplate expect(token: Token; expected: TokenKind; errmsg: string) =\n\t## Check if a token is of the expected kind.\n\t## Raise a SyntaxError if this is not the case.\n\tif token.kind != expected:\n\t\traise newException(SyntaxError, \"line \" & $token.ln & \": \" & errmsg)\n\ttoken = lexer.next()\n\n\nproc newNode*(kind: NodeKind; left: Node; right: Node = nil): Node =\n\t## Create a new node with given left and right children.\n\tresult = Node(kind: kind, left: left, right: right)\n\n\n# Forward reference.\nproc parExpr(lexer: var Lexer; token: var Token): Node\n\n\nproc expr(lexer: var Lexer; token: var Token; p: int): Node =\n\t## Parse an expression.\n\n\tcase token.kind\n\n\tof tokLPar:\n\t\tresult = parExpr(lexer, token)\n\n\tof tokAdd, tokSub, tokNot:\n\t\t# Unary operators.\n\t\tlet savedToken = token\n\t\ttoken = lexer.next()\n\t\tlet e = expr(lexer, token, UnaryPrecedence)\n\t\tif savedToken.kind == tokAdd:\n\t\t\tresult = e\n\t\telse:\n\t\t\tresult = newNode(if savedToken.kind == tokSub: nNegate else: nNot, e)\n\n\tof tokIdent:\n\t\tresult = Node(kind: nIdentifier, name: token.ident)\n\t\ttoken = lexer.next()\n\n\tof tokInt:\n\t\tresult = Node(kind:nInteger, intVal: token.intVal)\n\t\ttoken = lexer.next()\n\n\tof tokChar:\n\t\tresult = Node(kind:nInteger, intVal: ord(token.charVal))\n\t\ttoken = lexer.next()\n\n\telse:\n\t\traise newException(SyntaxError, \"Unexpected symbol at line \" & $token.ln)\n\n\t# Process the binary operators in the expression.\n\twhile token.kind in BinaryOperators and Precedences[token.kind] >= p:\n\t\tlet savedToken = token\n\t\ttoken = lexer.next()\n\t\tlet q = Precedences[savedToken.kind] + 1 # No operator is right associative.\n\t\tresult = newNode(NodeKinds[savedToken.kind], result, expr(lexer, token, q))\n\n\nproc parExpr(lexer: var Lexer; token: var Token): Node =\n\t## Parse a parenthetized expression.\n\ttoken.expect(tokLPar, \"'(' expected\")\n\tresult = expr(lexer, token, 0)\n\ttoken.expect(tokRPar, \"')' expected\")\n\n\nproc stmt(lexer: var Lexer; token: var Token): Node =\n\t## Parse a statement.\n\n\tcase token.kind:\n\n\tof tokIf:\n\t\ttoken = lexer.next()\n\t\tlet e = parExpr(lexer, token)\n\t\tlet thenNode = stmt(lexer, token)\n\t\tvar elseNode: Node = nil\n\t\tif token.kind == tokElse:\n\t\t\ttoken = lexer.next()\n\t\t\telseNode = stmt(lexer, token)\n\t\tresult = newNode(nIf, e, newNode(nIf, thenNode, elseNode))\n\n\tof tokPutc:\n\t\ttoken = lexer.next()\n\t\tresult = newNode(nPrtc, parExpr(lexer, token))\n\t\ttoken.expect(tokSemi, \"';' expected\")\n\n\tof tokPrint:\n\t\ttoken = lexer.next()\n\t\ttoken.expect(tokLPar, \"'(' expected\")\n\t\twhile true:\n\t\t\tvar e: Node\n\t\t\tif token.kind == tokString:\n\t\t\t\te = newNode(nPrts, Node(kind: nString, stringVal: token.stringVal))\n\t\t\t\ttoken = lexer.next()\n\t\t\telse:\n\t\t\t\te = newNode(nPrti, expr(lexer, token, 0))\n\t\t\tresult = newNode(nSequence, result, e)\n\t\t\tif token.kind == tokComma:\n\t\t\t\ttoken = lexer.next()\n\t\t\telse:\n\t\t\t\tbreak\n\t\ttoken.expect(tokRPar, \"')' expected\")\n\t\ttoken.expect(tokSemi, \"';' expected\")\n\n\tof tokSemi:\n\t\ttoken = lexer.next()\n\n\tof tokIdent:\n\t\tlet v = Node(kind: nIdentifier, name: token.ident)\n\t\ttoken = lexer.next()\n\t\ttoken.expect(tokAssign, \"'=' expected\")\n\t\tresult = newNode(nAssign, v, expr(lexer, token, 0))\n\t\ttoken.expect(tokSemi, \"';' expected\")\n\n\tof tokWhile:\n\t\ttoken = lexer.next()\n\t\tlet e = parExpr(lexer, token)\n\t\tresult = newNode(nWhile, e, stmt(lexer, token))\n\n\tof tokLBrace:\n\t\ttoken = lexer.next()\n\t\twhile token.kind notin {tokRBrace, tokEnd}:\n\t\t\tresult = newNode(nSequence, result, stmt(lexer, token))\n\t\ttoken.expect(tokRBrace, \"'}' expected\")\n\n\tof tokEnd:\n\t\tdiscard\n\n\telse:\n\t\traise newException(SyntaxError, \"Unexpected symbol at line \" & $token.ln)\n\n\nproc parse*(code: string): Node =\n\t## Parse the code provided.\n\n\tvar lexer = initLexer(code)\n\tvar token = lexer.next()\n\twhile true:\n\t\tresult = newNode(nSequence, result, stmt(lexer, token))\n\t\tif token.kind == tokEnd:\n\t\t\tbreak\n\n\nwhen isMainModule:\n\n\timport os, strformat, strutils\n\n\tproc printAst(node: Node) =\n\t\t## Print tha AST in linear form.\n\n\t\tif node.isNil:\n\t\t\techo ';'\n\n\t\telse:\n\t\t\tstdout.write \"{$node.kind:<14}\"\n\t\t\tcase node.kind\n\t\t\tof nIdentifier:\n\t\t\t\techo node.name\n\t\t\tof nInteger:\n\t\t\t\techo node.intVal\n\t\t\tof nString:\n\t\t\t\t# Need to escape and to replace hexadecimal \\x0A by \\n.\n\t\t\t\techo escape(node.stringVal).replace(\"\\\\x0A\", \"\\\\n\")\n\t\t\telse:\n\t\t\t\techo \"\"\n\t\t\t\tnode.left.printAst()\n\t\t\t\tnode.right.printAst()\n\n\n\tlet code = if paramCount() < 1: stdin.readAll() else: paramStr(1).readFile()\n\tlet tree = parse(code)\n\ttree.printAst()\n" + }, + { + "id": 1138, + "length": 635, + "source": "Rosetta Code", + "text": "proc twoSum(src: openarray[int], target: int): array[2, int] =\n\tif src.len < 2:\n\t\treturn\n\n\tfor base in 0 .. (src.len - 2):\n\t\tfor ext in (base + 1) ..< src.len:\n\t\t\tif src[base] + src[ext] == target:\n\t\t\t\tresult[0] = base\n\t\t\t\tresult[1] = ext\n\n\nproc main =\n\tvar data0 = [0, 2, 11, 19, 90]\n\tvar res = twoSum(data0, 21)\n\tassert(res == [1, 3])\n\n\tvar data1 = [0, 2, 11, 19, 90]\n\tres = twoSum(data1, 22)\n\tassert(res == [0, 0])\n\n\tvar data2 = [1]\n\tres = twoSum(data2, 22)\n\tassert(res == [0, 0])\n\n\tvar data3 = [1, 99]\n\tres = twoSum(data3, 100)\n\tassert(res == [0, 1])\n\n\tvar data4 = [1, 99]\n\tres = twoSum(data4, 101)\n\tassert(res == [0, 0])\n\n\nmain()\n" + }, + { + "id": 1139, + "length": 1442, + "source": "Rosetta Code", + "text": "import algorithm, heapqueue, os, random, sequtils, strformat, strutils\n\n\nproc sortFiles(filenames: seq[string]) =\n\tfor filename in filenames:\n\t\tvar lines = filename.readFile()\n\t\tlines.stripLineEnd() # Ignore last line feed, if any.\n\t\tvar sortedLines = sorted(lines.splitLines())\n\t\techo \"\"\"{filename} => {sortedLines.join(\", \")}\"\"\"\n\t\tfilename.writeFile(sortedLines.join(\"\\n\"))\n\n\nproc mergeFiles(outfile: File; filenames: seq[string]) =\n\tvar queue: HeapQueue[(string, File)]\n\tfor filename in filenames:\n\t\tlet f = open(fileName)\n\t\tqueue.push (f.readLine(), f)\n\twhile queue.len > 0:\n\t\tlet (s, infile) = queue.pop()\n\t\toutfile.write s & '\\n'\n\t\tif infile.endOfFile:\n\t\t\tinfile.close()\n\t\telse:\n\t\t\tqueue.push((infile.readLine(), infile))\n\n\nwhen isMainModule:\n\tconst WriteToFile = false # Compile time switch.\n\n\trandomize()\n\tlet nf = rand(2..4) # Number of files.\n\tlet lp = 3 # Lines per file.\n\tvar filenames: seq[string]\n\tvar lines = toSeq(1..nf*lp)\n\tlines.shuffle()\n\n\tfor i in 1..nf:\n\t\tlet filename = \"file{i}.txt\"\n\t\tfilenames.add filename\n\t\tlet f = open(filename, fmWrite)\n\t\tfor l in 1..lp:\n\t\t\tf.write \"Line {lines[^l]:2}\\n\"\n\t\tlines.setLen(lines.len - lp)\n\t\tf.close()\n\n\techo \"sorting {nf * lp} lines split over {nf} files\"\n\tsortFiles(filenames)\n\n\twhen WriteToFile:\n\t\tlet f = open(\"results.txt\", fmWrite)\n\t\tmergeFiles(f, filenames)\n\t\tf.close()\n\telse:\n\t\tmergeFiles(stdout, filenames)\n\n\tfor filename in filenames:\n\t\tremoveFile(filename)\n" + }, + { + "id": 1140, + "length": 3734, + "source": "Rosetta Code", + "text": "import os, strutils, streams, tables\n\nimport ast_parser\n\ntype\n\n\tValueKind = enum valNil, valInt, valString\n\n\t# Representation of a value.\n\tValue = object\n\t\tcase kind: ValueKind\n\t\tof valNil: nil\n\t\tof valInt: intVal: int\n\t\tof valString: stringVal: string\n\n\t# Range of binary operators.\n\tBinaryOperator = range[nMultiply..nOr]\n\n# Table of variables.\nvar variables: Table[string, Value]\n\ntype RunTimeError = object of CatchableError\n\n\ntemplate newInt(val: typed): Value =\n\t## Create an integer value.\n\tValue(kind: valInt, intVal: val)\n\n\nproc interp(node: Node): Value =\n\t## Interpret code starting at \"node\".\n\n\tif node.isNil:\n\t\treturn Value(kind: valNil)\n\n\tcase node.kind\n\n\tof nInteger:\n\t\tresult = Value(kind: valInt, intVal: node.intVal)\n\n\tof nIdentifier:\n\t\tif node.name notin variables:\n\t\t\traise newException(RunTimeError, \"Variable {node.name} is not initialized.\")\n\t\tresult = variables[node.name]\n\n\tof nString:\n\t\tresult = Value(kind: valString, stringVal: node.stringVal)\n\n\tof nAssign:\n\t\tvariables[node.left.name] = interp(node.right)\n\n\tof nNegate:\n\t\tresult = newInt(-interp(node.left).intVal)\n\n\tof nNot:\n\t\tresult = newInt(not interp(node.left).intVal)\n\n\tof BinaryOperator.low..BinaryOperator.high:\n\n\t\tlet left = interp(node.left)\n\t\tlet right = interp(node.right)\n\n\t\tcase BinaryOperator(node.kind)\n\t\tof nMultiply:\n\t\t\tresult = newInt(left.intVal * right.intVal)\n\t\tof nDivide:\n\t\t\tresult = newInt(left.intVal div right.intVal)\n\t\tof nMod:\n\t\t\tresult = newInt(left.intVal mod right.intVal)\n\t\tof nAdd:\n\t\t\tresult = newInt(left.intVal + right.intVal)\n\t\tof nSubtract:\n\t\t\tresult = newInt(left.intVal - right.intVal)\n\t\tof nLess:\n\t\t\tresult = newInt(ord(left.intVal < right.intVal))\n\t\tof nLessEqual:\n\t\t\tresult = newInt(ord(left.intVal <= right.intVal))\n\t\tof nGreater:\n\t\t\tresult = newInt(ord(left.intVal > right.intVal))\n\t\tof nGreaterEqual:\n\t\t\tresult = newInt(ord(left.intVal >= right.intVal))\n\t\tof nEqual:\n\t\t\tresult = newInt(ord(left.intVal == right.intVal))\n\t\tof nNotEqual:\n\t\t\tresult = newInt(ord(left.intVal != right.intVal))\n\t\tof nAnd:\n\t\t\tresult = newInt(left.intVal and right.intVal)\n\t\tof nOr:\n\t\t\tresult = newInt(left.intVal or right.intVal)\n\n\tof nIf:\n\t\tif interp(node.left).intVal != 0:\n\t\t\tdiscard interp(node.right.left)\n\t\telse:\n\t\t\tdiscard interp(node.right.right)\n\n\tof nWhile:\n\t\twhile interp(node.left).intVal != 0:\n\t\t\tdiscard interp(node.right)\n\n\tof nPrtc:\n\t\tstdout.write(chr(interp(node.left).intVal))\n\n\tof nPrti:\n\t\tstdout.write(interp(node.left).intVal)\n\n\tof nPrts:\n\t\tstdout.write(interp(node.left).stringVal)\n\n\tof nSequence:\n\t\tdiscard interp(node.left)\n\t\tdiscard interp(node.right)\n\n\nimport re\n\nproc loadAst(stream: Stream): Node =\n\t## Load a linear AST and build a binary tree.\n\n\tlet line = stream.readLine().strip()\n\tif line.startsWith(';'):\n\t\treturn nil\n\n\tvar fields = line.split(' ', 1)\n\tlet kind = parseEnum[NodeKind](fields[0])\n\tif kind in {nIdentifier, nString, nInteger}:\n\t\tif fields.len < 2:\n\t\t\traise newException(ValueError, \"Missing value field for \" & fields[0])\n\t\telse:\n\t\t\tfields[1] = fields[1].strip()\n\tcase kind\n\tof nIdentifier:\n\t\treturn Node(kind: nIdentifier, name: fields[1])\n\tof nString:\n\t\tstr = fields[1].replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n\t\treturn Node(kind: nString, stringVal: str)\n\tof nInteger:\n\t\treturn Node(kind: nInteger, intVal: parseInt(fields[1]))\n\telse:\n\t\tif fields.len > 1:\n\t\t\traise newException(ValueError, \"Extra field for \" & fields[0])\n\n\tlet left = stream.loadAst()\n\tlet right = stream.loadAst()\n\tresult = newNode(kind, left, right)\n\n\nvar stream: Stream\nvar toClose = false\n\nif paramCount() < 1:\n\tstream = newFileStream(stdin)\nelse:\n\tstream = newFileStream(paramStr(1))\n\ttoClose = true\n\nlet ast = loadAst(stream)\nif toClose: stream.close()\n\ndiscard ast.interp()\n" + }, + { + "id": 1141, + "length": 7613, + "source": "Rosetta Code", + "text": "import os, re, streams, strformat, strutils, tables, std/decls\n\ntype\n\n\t# AST node types.\n\tNodeKind = enum\n\t\t\t\t\t\t nIdentifier = \"Identifier\"\n\t\t\t\t\t\t nString = \"String\"\n\t\t\t\t\t\t nInteger = \"Integer\"\n\t\t\t\t\t\t nSequence = \"Sequence\"\n\t\t\t\t\t\t nIf = \"If\"\n\t\t\t\t\t\t nPrtc = \"Prtc\"\n\t\t\t\t\t\t nPrts = \"Prts\"\n\t\t\t\t\t\t nPrti = \"Prti\"\n\t\t\t\t\t\t nWhile = \"While\"\n\t\t\t\t\t\t nAssign = \"Assign\"\n\t\t\t\t\t\t nNegate = \"Negate\"\n\t\t\t\t\t\t nNot = \"Not\"\n\t\t\t\t\t\t nMultiply = \"Multiply\"\n\t\t\t\t\t\t nDivide = \"Divide\"\n\t\t\t\t\t\t nMod = \"Mod\"\n\t\t\t\t\t\t nAdd = \"Add\"\n\t\t\t\t\t\t nSubtract = \"Subtract\"\n\t\t\t\t\t\t nLess = \"Less\"\n\t\t\t\t\t\t nLessEqual = \"LessEqual\"\n\t\t\t\t\t\t nGreater = \"Greater\"\n\t\t\t\t\t\t nGreaterEqual = \"GreaterEqual\"\n\t\t\t\t\t\t nEqual = \"Equal\"\n\t\t\t\t\t\t nNotEqual = \"NotEqual\"\n\t\t\t\t\t\t nAnd = \"And\"\n\t\t\t\t\t\t nOr = \"Or\"\n\n\t# Ast node description.\n\tNode = ref object\n\t\tleft: Node\n\t\tright: Node\n\t\tcase kind: NodeKind\n\t\tof nString: stringVal: string\n\t\tof nInteger: intVal: int\n\t\tof nIdentifier: name: string\n\t\telse: nil\n\n\t# Virtual machine opcodes.\n\tOpCode = enum\n\t\t\t\t\t opFetch = \"fetch\"\n\t\t\t\t\t opStore = \"store\"\n\t\t\t\t\t opPush = \"push\"\n\t\t\t\t\t opJmp = \"jmp\"\n\t\t\t\t\t opJz = \"jz\"\n\t\t\t\t\t opAdd = \"add\"\n\t\t\t\t\t opSub = \"sub\"\n\t\t\t\t\t opMul = \"mul\"\n\t\t\t\t\t opDiv = \"div\"\n\t\t\t\t\t opMod = \"mod\"\n\t\t\t\t\t opLt = \"lt\"\n\t\t\t\t\t opgt = \"gt\"\n\t\t\t\t\t opLe = \"le\"\n\t\t\t\t\t opGe = \"ge\"\n\t\t\t\t\t opEq = \"eq\"\n\t\t\t\t\t opNe = \"ne\"\n\t\t\t\t\t opAnd = \"and\"\n\t\t\t\t\t opOr = \"or\"\n\t\t\t\t\t opNeg = \"neg\"\n\t\t\t\t\t opNot = \"not\"\n\t\t\t\t\t opPrtc = \"prtc\"\n\t\t\t\t\t opPrti = \"prti\"\n\t\t\t\t\t opPrts = \"prts\"\n\t\t\t\t\t opHalt = \"halt\"\n\t\t\t\t\t opInvalid = \"invalid\"\n\n\t# Code generator context.\n\tCodeGen = object\n\t\taddress: int # Current address in code part.\n\t\tinstr: seq[string] # List of instructions.\n\t\tvars: Table[string, int] # Mapping variable name -> variable index.\n\t\tstrings: seq[string] # List of strings.\n\n\t# Node ranges.\n\tUnaryOpNode = range[nNegate..nNot]\n\tBinaryOpNode = range[nMultiply..nOr]\n\tPrintNode = range[nPrtc..nPrti]\n\n\nconst\n\n\t# Mapping unary operator Node -> OpCode.\n\tUnOp: array[UnaryOpNode, OpCode] = [opNeg, opNot]\n\n\t# Mapping binary operator Node -> OpCode.\n\tBinOp: array[BinaryOpNode, OpCode] = [opMul, opDiv, opMod, opAdd, opSub, opLt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\topLe, opGt, opGe, opEq, opNe, opAnd, opOr]\n\n\t# Mapping print Node -> OpCode.\n\tPrintOp: array[PrintNode, OpCode] = [opPrtc, opPrts, opPrti]\n\n\n# Code generator.\n\nproc genSimpleInst(gen: var CodeGen; opcode: OpCode) =\n\t## Build a simple instruction (no operand).\n\tgen.instr.add \"{gen.address:>5} {opcode}\"\n\n\nproc genMemInst(gen: var CodeGen; opcode: OpCode; memIndex: int) =\n\t## Build a memory access instruction (opFetch, opStore).\n\tgen.instr.add \"{gen.address:>5} {opcode:<5} [{memIndex}]\"\n\n\nproc genJumpInst(gen: var CodeGen; opcode: OpCode): int =\n\t## Build a jump instruction. We use the letters X and Y as placeholders\n\t## for the offset and the target address.\n\tresult = gen.instr.len\n\tgen.instr.add \"{gen.address:>5} {opcode:<5} (X) Y\"\n\n\nproc genPush(gen: var CodeGen; value: int) =\n\t## Build a push instruction.\n\tgen.instr.add \"{gen.address:>5} {opPush:<5} {value}\"\n\n\nproc updateJumpInst(gen: var CodeGen; index: int; jumpAddress, targetAddress: int) =\n\t## Update the offset and the target address of a jump instruction.\n\n\tvar instr {.byAddr.} = gen.instr[index]\n\tlet offset = targetAddress - jumpAddress - 1\n\tfor idx in countdown(instr.high, 0):\n\t\tcase instr[idx]\n\t\tof 'Y':\n\t\t\tinstr[idx..idx] = $targetAddress\n\t\tof 'X':\n\t\t\tinstr[idx..idx] = $offset\n\t\t\tbreak\n\t\telse:\n\t\t\tdiscard\n\n\nproc process(gen: var CodeGen; node: Node) =\n\t## Generate code for a node.\n\n\tif node.isNil: return\n\n\tcase node.kind:\n\n\tof nInteger:\n\t\tgen.genPush(node.intVal)\n\t\tinc gen.address, 5\n\n\tof nIdentifier:\n\t\tif node.name notin gen.vars:\n\t\t\tgen.vars[node.name] = gen.vars.len\n\t\tgen.genMemInst(opFetch, gen.vars[node.name])\n\t\tinc gen.address, 5\n\n\tof nString:\n\t\tvar index = gen.strings.find(node.stringVal)\n\t\tif index < 0:\n\t\t\tindex = gen.strings.len\n\t\t\tgen.strings.add(node.stringVal)\n\t\tgen.genPush(index)\n\t\tinc gen.address, 5\n\n\tof nAssign:\n\t\tgen.process(node.right)\n\t\tif node.left.name notin gen.vars:\n\t\t\tgen.vars[node.left.name] = gen.vars.len\n\t\tgen.genMemInst(opStore, gen.vars[node.left.name])\n\t\tinc gen.address, 5\n\n\tof UnaryOpNode.low..UnaryOpNode.high:\n\t\tgen.process(node.left)\n\t\tgen.genSimpleInst(UnOp[node.kind])\n\t\tinc gen.address\n\n\tof BinaryOpNode.low..BinaryOpNode.high:\n\t\tgen.process(node.left)\n\t\tgen.process(node.right)\n\t\tgen.genSimpleInst(BinOp[node.kind])\n\t\tinc gen.address\n\n\tof PrintNode.low..PrintNode.high:\n\t\tgen.process(node.left)\n\t\tgen.genSimpleInst(PrintOp[node.kind])\n\t\tinc gen.address\n\n\tof nIf:\n\t\t# Generate condition expression.\n\t\tgen.process(node.left)\n\t\t# Generate jump if zero.\n\t\tlet jzAddr = gen.address\n\t\tlet jzInst = gen.genJumpInst(opJz)\n\t\tinc gen.address, 5\n\t\t# Generate then branch expression.\n\t\tgen.process(node.right.left)\n\t\t# If there is an \"else\" clause, generate unconditional jump\n\t\tvar jmpAddr, jmpInst: int\n\t\tlet hasElseClause = not node.right.right.isNil\n\t\tif hasElseClause:\n\t\t\tjmpAddr = gen.address\n\t\t\tjmpInst = gen.genJumpInst(opJmp)\n\t\t\tinc gen.address, 5\n\t\t# Update JZ offset.\n\t\tgen.updateJumpInst(jzInst, jzAddr, gen.address)\n\t\t# Generate else expression.\n\t\tif hasElseClause:\n\t\t\tgen.process(node.right.right)\n\t\t\t# Update JMP offset.\n\t\t\tgen.updateJumpInst(jmpInst, jmpAddr, gen.address)\n\n\tof nWhile:\n\t\tlet condAddr = gen.address\n\t\t# Generate condition expression.\n\t\tgen.process(node.left)\n\t\t# Generate jump if zero.\n\t\tlet jzAddr = gen.address\n\t\tlet jzInst = gen.genJumpInst(opJz)\n\t\tinc gen.address, 5\n\t\t# Generate loop code.\n\t\tgen.process(node.right)\n\t\t# Generate unconditional jump.\n\t\tlet jmpAddr = gen.address\n\t\tlet jmpInst = gen.genJumpInst(opJmp)\n\t\tinc gen.address, 5\n\t\t# Update JMP offset.\n\t\tgen.updateJumpInst(jmpInst, jmpAddr, condAddr)\n\t\t# Update JZ offset.\n\t\tgen.updateJumpInst(jzInst, jzAddr, gen.address)\n\n\tof nSequence:\n\t\tgen.process(node.left)\n\t\tgen.process(node.right)\n\n\nproc run(gen: var CodeGen; ast: Node) =\n\t## Run the code generator on the AST.\n\n\t# Process recursively the nodes.\n\tgen.process(ast)\n\tgen.genSimpleInst(opHalt) # Add a Halt operator at the end.\n\n\t# Output header.\n\techo \"Datasize: {gen.vars.len} Strings: {gen.strings.len}\"\n\t# Output strings.\n\tfor s in gen.strings:\n\t\techo s.escape().replace(\"\\\\x0A\", \"\\\\n\")\n\t# Output code.\n\tfor inst in gen.instr:\n\t\techo inst\n\n# AST loader.\n\nproc newNode(kind: NodeKind; left: Node; right: Node = nil): Node =\n\t## Create a new node with given left and right children.\n\tresult = Node(kind: kind, left: left, right: right)\n\n\nproc loadAst(stream: Stream): Node =\n\t## Load a linear AST and build a binary tree.\n\n\tlet line = stream.readLine().strip()\n\tif line.startsWith(';'):\n\t\treturn nil\n\n\tvar fields = line.split(' ', 1)\n\tlet kind = parseEnum[NodeKind](fields[0])\n\tif kind in {nIdentifier, nString, nInteger}:\n\t\tif fields.len < 2:\n\t\t\traise newException(ValueError, \"Missing value field for \" & fields[0])\n\t\telse:\n\t\t\tfields[1] = fields[1].strip()\n\tcase kind\n\tof nIdentifier:\n\t\treturn Node(kind: nIdentifier, name: fields[1])\n\tof nString:\n\t\tlet str = fields[1].replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n\t\treturn Node(kind: nString, stringVal: str)\n\tof nInteger:\n\t\treturn Node(kind: nInteger, intVal: parseInt(fields[1]))\n\telse:\n\t\tif fields.len > 1:\n\t\t\traise newException(ValueError, \"Extra field for \" & fields[0])\n\n\tlet left = stream.loadAst()\n\tlet right = stream.loadAst()\n\tresult = newNode(kind, left, right)\n\n\n\nvar stream: Stream\nvar toClose = false\nvar codegen: CodeGen\n\nif paramCount() < 1:\n\tstream = newFileStream(stdin)\nelse:\n\tstream = newFileStream(paramStr(1))\n\ttoClose = true\n\nlet ast = loadAst(stream)\nif toClose: stream.close()\n\ncodegen.run(ast)\n" + }, + { + "id": 1142, + "length": 7629, + "source": "Rosetta Code", + "text": "import os, parseutils, strutils, strscans, strformat\n\ntype\n\n\tValue = int32\n\tBytesValue = array[4, byte]\n\tAddress = int32\n\n\tOpCode = enum\n\t\t\t\t\t opFetch = \"fetch\"\n\t\t\t\t\t opStore = \"store\"\n\t\t\t\t\t opPush = \"push\"\n\t\t\t\t\t opJmp = \"jmp\"\n\t\t\t\t\t opJz = \"jz\"\n\t\t\t\t\t opAdd = \"add\"\n\t\t\t\t\t opSub = \"sub\"\n\t\t\t\t\t opMul = \"mul\"\n\t\t\t\t\t opDiv = \"div\"\n\t\t\t\t\t opMod = \"mod\"\n\t\t\t\t\t opLt = \"lt\"\n\t\t\t\t\t opgt = \"gt\"\n\t\t\t\t\t opLe = \"le\"\n\t\t\t\t\t opGe = \"ge\"\n\t\t\t\t\t opEq = \"eq\"\n\t\t\t\t\t opNe = \"ne\"\n\t\t\t\t\t opAnd = \"and\"\n\t\t\t\t\t opOr = \"or\"\n\t\t\t\t\t opNeg = \"neg\"\n\t\t\t\t\t opNot = \"not\"\n\t\t\t\t\t opPrtc = \"prtc\"\n\t\t\t\t\t opPrti = \"prti\"\n\t\t\t\t\t opPrts = \"prts\"\n\t\t\t\t\t opHalt = \"halt\"\n\t\t\t\t\t opInvalid = \"invalid\"\n\n\t# Virtual machine description.\n\tVM = object\n\t\tstack: seq[Value] # Evaluation stack.\n\t\tmemory: seq[byte] # Memory to store program.\n\t\tdata: seq[Value] # Data storage.\n\t\tstrings: seq[string] # String storage.\n\t\tpc: Address # Program counter.\n\n\t# Exceptions.\n\tLoadingError = object of CatchableError\n\tRuntimeError = object of CatchableError\n\n\n# Running program.\n\nproc checkStackLength(vm: VM; minLength: int) {.inline.} =\n\t## Check that evaluation stack contains at least \"minLength\" elements.\n\tif vm.stack.len < minLength:\n\t\traise newException(RuntimeError, \"not enough operands on the stack (pc = {vm.pc}).\")\n\n\nproc getOperand(vm: var VM): Value =\n\t## Get a 32 bits operand.\n\n\ttype Union {.union.} = object\n\t\tvalue: Value\n\t\tbytes: BytesValue\n\n\tif vm.pc + 4 >= vm.memory.len:\n\t\traise newException(RuntimeError, \"out of memory (pc = {vm.pc}).\")\n\n\tvar aux: Union\n\tlet address = vm.pc + 1\n\tfor idx in 0..3:\n\t\taux.bytes[idx] = vm.memory[address + idx]\n\tresult = aux.value\n\n\nproc run(vm: var VM) =\n\t## Run a program loaded in VM memory.\n\n\tvm.pc = 0\n\n\twhile true:\n\n\t\tif vm.pc notin 0..vm.memory.high:\n\t\t\traise newException(RuntimeError, \"out of memory (pc = {vm.pc}).\")\n\n\t\tlet opcode = OpCode(vm.memory[vm.pc])\n\t\tcase opcode\n\n\t\tof opFetch, opStore:\n\t\t\tlet index = vm.getOperand()\n\t\t\tif index notin 0..vm.data.high:\n\t\t\t\traise newException(RuntimeError, \"wrong memory index (pc = {vm.pc}).\")\n\t\t\tif opcode == opFetch:\n\t\t\t\tvm.stack.add(vm.data[index])\n\t\t\telse:\n\t\t\t\tvm.checkStackLength(1)\n\t\t\t\tvm.data[index] = vm.stack.pop()\n\t\t\tinc vm.pc, 4\n\n\t\tof opPush:\n\t\t\tlet value = vm.getOperand()\n\t\t\tvm.stack.add(value)\n\t\t\tinc vm.pc, 4\n\n\t\tof opJmp:\n\t\t\tlet offset = vm.getOperand()\n\t\t\tinc vm.pc, offset\n\n\t\tof opJz:\n\t\t\tlet offset = vm.getOperand()\n\t\t\tvm.checkStackLength(1)\n\t\t\tlet value = vm.stack.pop()\n\t\t\tinc vm.pc, if value == 0: offset else: 4\n\n\t\tof opAdd..opOr:\n\t\t\t# Two operands instructions.\n\t\t\tvm.checkStackLength(2)\n\t\t\tlet op2 = vm.stack.pop()\n\t\t\tlet op1 = vm.stack.pop()\n\t\t\tcase range[opAdd..opOr](opcode)\n\t\t\tof opAdd:\n\t\t\t\tvm.stack.add(op1 + op2)\n\t\t\tof opSub:\n\t\t\t\tvm.stack.add(op1 - op2)\n\t\t\tof opMul:\n\t\t\t\tvm.stack.add(op1 * op2)\n\t\t\tof opDiv:\n\t\t\t\tvm.stack.add(op1 div op2)\n\t\t\tof opMod:\n\t\t\t\tvm.stack.add(op1 mod op2)\n\t\t\tof opLt:\n\t\t\t\tvm.stack.add(Value(op1 < op2))\n\t\t\tof opgt:\n\t\t\t\tvm.stack.add(Value(op1 > op2))\n\t\t\tof opLe:\n\t\t\t\tvm.stack.add(Value(op1 <= op2))\n\t\t\tof opGe:\n\t\t\t\tvm.stack.add(Value(op1 >= op2))\n\t\t\tof opEq:\n\t\t\t\tvm.stack.add(Value(op1 == op2))\n\t\t\tof opNe:\n\t\t\t\tvm.stack.add(Value(op1 != op2))\n\t\t\tof opAnd:\n\t\t\t\tvm.stack.add(op1 and op2)\n\t\t\tof opOr:\n\t\t\t\tvm.stack.add(op1 or op2)\n\n\t\tof opNeg..opPrts:\n\t\t\t# One operand instructions.\n\t\t\tvm.checkStackLength(1)\n\t\t\tlet op = vm.stack.pop()\n\t\t\tcase range[opNeg..opPrts](opcode)\n\t\t\tof opNeg:\n\t\t\t\tvm.stack.add(-op)\n\t\t\tof opNot:\n\t\t\t\tvm.stack.add(not op)\n\t\t\tof opPrtc:\n\t\t\t\tstdout.write(chr(op))\n\t\t\tof opPrti:\n\t\t\t\tstdout.write(op)\n\t\t\tof opPrts:\n\t\t\t\tif op notin 0..vm.strings.high:\n\t\t\t\t\traise newException(RuntimeError, \"wrong string index (pc = {vm.pc}).\")\n\t\t\t\tstdout.write(vm.strings[op])\n\n\t\tof opHalt:\n\t\t\tbreak\n\n\t\tof opInvalid:\n\t\t\tdiscard # Not possible.\n\n\t\tinc vm.pc\n\n\n# Loading assembly file.\n\nproc parseHeader(line: string): tuple[dataSize, stringCount: int] =\n\t## Parse the header.\n\n\tif not line.scanf(\"Datasize: $s$i $sStrings: $i\", result.dataSize, result.stringCount):\n\t\traise newException(LoadingError, \"Wrong header in code.\")\n\n\nimport re\n\nproc parseString(line: string; linenum: int): string =\n\t## Parse a string.\n\n\tif not line.startsWith('\"'):\n\t\traise newException(LoadingError, \"Line $1: incorrect string.\".format(linenum))\n\t# Can't use \"unescape\" as it is confused by \"\\\\n\" and \"\\n\".\n\tresult = line.replacef(re\"([^\\\\])(\\\\n)\", \"$1\\n\").replace(r\"\\\\\", r\"\\\").replace(\"\\\"\", \"\")\n\n\nproc parseValue(line: string; linenum: int; pos: var int; msg: string): int32 =\n\t## Parse an int32 value.\n\n\tvar value: int\n\n\tpos += line.skipWhitespace(pos)\n\tlet parsed = line.parseInt(value, pos)\n\tif parsed == 0:\n\t\traise newException(LoadingError, \"Line $1: \".format(linenum) & msg)\n\tpos += parsed\n\tresult = int32(value)\n\n\nproc parseOpcode(line: string; linenum: int; pos: var int): OpCode =\n\t## Parse an opcode.\n\n\tvar opstring: string\n\n\tpos += line.skipWhitespace(pos)\n\tlet parsed = line.parseIdent(opstring, pos)\n\tif parsed == 0:\n\t\traise newException(LoadingError, \"Line $1: opcode expected\".format(linenum))\n\tpos += parsed\n\n\tresult = parseEnum[OpCode](opstring, opInvalid)\n\tif result == opInvalid:\n\t\traise newException(LoadingError, \"Line $1: invalid opcode encountered\".format(linenum))\n\n\nproc parseMemoryIndex(line: string; linenum: int; pos: var int): int32 =\n\t## Parse a memory index (int32 value between brackets).\n\n\tvar memIndex: int\n\n\tpos += line.skipWhitespace(pos)\n\tlet str = line.captureBetween('[', ']', pos)\n\tif str.parseInt(memIndex) == 0 or memIndex < 0:\n\t\traise newException(LoadingError, \"Line $1: invalid memory index\".format(lineNum))\n\tpos += str.len + 2\n\tresult = int32(memIndex)\n\n\nproc parseOffset(line: string; linenum: int; pos: var int): int32 =\n\t## Parse an offset (int32 value between parentheses).\n\n\tvar offset: int\n\n\tpos += line.skipWhitespace(pos)\n\tlet str = line.captureBetween('(', ')', pos)\n\tif str.parseInt(offset) == 0:\n\t\traise newException(LoadingError, \"Line $1: invalid offset\".format(linenum))\n\tpos += str.len + 2\n\tresult = int32(offset)\n\n\nproc load(vm: var VM; code: string) =\n\t## Load an assembly code into VM memory.\n\n\t# Analyze header.\n\tlet lines = code.splitlines()\n\tlet (dataSize, stringCount) = parseHeader(lines[0])\n\tvm.data.setLen(dataSize)\n\tvm.strings.setLen(stringCount)\n\n\t# Load strings.\n\tfor idx in 1..stringCount:\n\t\tvm.strings[idx - 1] = lines[idx].parseString(idx + 1)\n\n\t# Load code.\n\tvar pc: Address = 0\n\tfor idx in (stringCount + 1)..lines.high:\n\t\tvar pos = 0\n\t\tlet line = lines[idx]\n\t\tif line.len == 0: continue\n\n\t\t# Process address.\n\t\tlet address = line.parseValue(idx + 1, pos, \"address expected\")\n\t\tif address != pc:\n\t\t\traise newException(LoadingError, \"Line $1: wrong address\".format(idx + 1))\n\n\t\t# Process opcode.\n\t\tlet opcode = line.parseOpcode(idx + 1, pos)\n\t\tvm.memory.add(byte(opcode))\n\n\t\t# Process operand.\n\t\tcase opcode\n\n\t\tof opFetch, opStore:\n\t\t\t# Find memory index.\n\t\t\tlet memIndex = line.parseMemoryIndex(idx + 1, pos)\n\t\t\tvm.memory.add(cast[BytesValue](Value(memIndex)))\n\t\t\tinc pc, 5\n\n\t\tof opJmp, opJz:\n\t\t\t# Find offset.\n\t\t\tlet offset = line.parseOffset(idx + 1, pos)\n\t\t\tvm.memory.add(cast[BytesValue](Value(offset)))\n\t\t\t# Find and check branch address.\n\t\t\tlet branchAddress = line.parseValue(idx + 1, pos, \"branch address expected\")\n\t\t\tif branchAddress != pc + offset + 1:\n\t\t\t\traise newException(LoadingError, \"Line $1: wrong branch address\".format(idx + 1))\n\t\t\tinc pc, 5\n\n\t\tof opPush:\n\t\t\t# Find value.\n\t\t\tlet value = line.parseValue(idx + 1, pos, \"value expected\")\n\t\t\tvm.memory.add(cast[BytesValue](Value(value)))\n\t\t\tinc pc, 5\n\n\t\telse:\n\t\t\tinc pc\n\n\nlet code = if paramCount() == 0: stdin.readAll() else: paramStr(1).readFile()\nvar vm: VM\n\nvm.load(code)\nvm.run()\n" + }, + { + "id": 1143, + "length": 1685, + "source": "Rosetta Code", + "text": "import strutils\n\ntype\n\n\tNode[T] = ref object\n\t\tnext: Node[T]\n\t\tdata: T\n\n\tSinglyLinkedList[T] = object\n\t\thead, tail: Node[T]\n\nproc newNode[T](data: T): Node[T] =\n\tNode[T](data: data)\n\nproc append[T](list: var SinglyLinkedList[T]; node: Node[T]) =\n\tif list.head.isNil:\n\t\tlist.head = node\n\t\tlist.tail = node\n\telse:\n\t\tlist.tail.next = node\n\t\tlist.tail = node\n\nproc append[T](list: var SinglyLinkedList[T]; data: T) =\n\tlist.append newNode(data)\n\nproc prepend[T](list: var SinglyLinkedList[T]; node: Node[T]) =\n\tif list.head.isNil:\n\t\tlist.head = node\n\t\tlist.tail = node\n\telse:\n\t\tnode.next = list.head\n\t\tlist.head = node\n\nproc prepend[T](list: var SinglyLinkedList[T]; data: T) =\n\tlist.prepend newNode(data)\n\nproc remove[T](list: var SinglyLinkedList[T]; node: Node[T]) =\n\tif node.isNil:\n\t\traise newException(ValueError, \"trying to remove nil reference.\")\n\tif node == list.head:\n\t\tlist.head = list.head.next\n\t\tif list.head.isNil: list.tail = nil\n\telse:\n\t\tvar n = list.head\n\t\twhile not n.isNil and n.next != node:\n\t\t\tn = n.next\n\t\tif n.isNil: return # Not found: ignore.\n\t\tn.next = node.next\n\t\tif n.next.isNil: list.tail = n\n\nproc find[T](list: SinglyLinkedList[T]; data: T): Node[T] =\n\tresult = list.head\n\twhile not result.isNil and result.data != data:\n\t\tresult = result.next\n\nproc `$`[T](list: SinglyLinkedList[T]): string =\n\tvar s: seq[T]\n\tvar n = list.head\n\twhile not n.isNil:\n\t\ts.add n.data\n\t\tn = n.next\n\tresult = s.join(\" -> \")\n\nvar list: SinglyLinkedList[int]\n\nfor i in 1..5: list.append(i)\necho \"List: \", list\nlist.remove(list.find(3))\necho \"After removing 3: \", list\nlist.remove(list.find(1))\necho \"After removing 1: \", list\nlist.remove(list.find(5))\necho \"After removing 5: \", list\n" + }, + { + "id": 1144, + "length": 1617, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, strutils\n\nproc encode(correct, guess: string): string =\n\tresult.setlen(correct.len)\n\tfor i in 0..correct.high:\n\t\tresult[i] = if correct[i] == guess[i]: 'X' else: (if guess[i] in correct: 'O' else: '-')\n\tresult.join(\" \")\n\nproc safeIntInput(prompt: string; minVal, maxVal: Positive): int =\n\twhile true:\n\t\tstdout.write prompt\n\t\tlet userInput = stdin.readLine()\n\t\tresult = try: parseInt(userInput)\n\t\t\t\t\t\t except ValueError: continue\n\t\tif result in minVal..maxVal:\n\t\t\treturn\n\n\nproc playGame() =\n\n\techo \"You will need to guess a random code.\"\n\techo \"For each guess, you will receive a hint.\"\n\techo \"In this hint, X denotes a correct letter, \" &\n\t\t\t \"and O a letter in the original string but in a different position.\"\n\techo \"\"\n\n\tlet numLetters = safeIntInput(\"Select a number of possible letters for the code (2-20): \", 2, 20)\n\tlet codeLength = safeIntInput(\"Select a length for the code (4-10): \", 4, 10)\n\tlet letters = \"ABCDEFGHIJKLMNOPQRST\"[0.. {encode(code, guess)}\"\n\t\tfor guess in guesses:\n\t\t\techo \"------------------------------------\"\n\t\t\techo guess\n\t\techo \"------------------------------------\"\n\n\nrandomize()\nplayGame()\n" + }, + { + "id": 1145, + "length": 1218, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, tables\n\nconst Snl = {4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34,\n\t\t\t\t\t\t 62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78}.toTable\n\nconst SixThrowsAgain = true\n\n\nproc turn(player, square: Positive): int =\n\tvar square = square\n\twhile true:\n\t\tlet roll = rand(1..6)\n\t\tstdout.write \"Player {player}, on square {square}, rolls a {roll}\"\n\t\tif square + roll > 100:\n\t\t\techo \" but cannot move.\"\n\t\telse:\n\t\t\tinc square, roll\n\t\t\techo \" and moves to square {square}.\"\n\t\t\tif square == 100: return 100\n\t\t\tlet next = Snl.getOrDefault(square, square)\n\t\t\tif square < next:\n\t\t\t\techo \"Yay! Landed on a ladder. Climb up to {next}.\"\n\t\t\t\tif next == 100: return 100\n\t\t\t\tsquare = next\n\t\t\telif square > next:\n\t\t\t\techo \"Oops! Landed on a snake. Slither down to {next}.\"\n\t\t\t\tsquare = next\n\t\tif roll < 6 or not SixThrowsAgain: return square\n\t\techo \"Rolled a 6 so roll again.\"\n\n\nproc playGame(n: Positive) =\n\n\t\t# \"n\" players starting on square one.\n\t\tvar players = repeat(1, n)\n\t\twhile true:\n\t\t\tfor i, s in players:\n\t\t\t\tlet ns = turn(i + 1, s)\n\t\t\t\tif ns == 100:\n\t\t\t\t\techo \"Player {i+1} wins!\"\n\t\t\t\t\treturn\n\t\t\t\tplayers[i] = ns\n\t\t\t\techo()\n\nrandomize()\n\nwhen isMainModule:\n\tplayGame(3)\n" + }, + { + "id": 1146, + "length": 790, + "source": "Rosetta Code", + "text": "import strutils, math, stats\n\nfunc meanSquareDiff(refValue: float; estimates: seq[float]): float =\n\t## Compute the mean of the squares of the differences\n\t## between estimated values and a reference value.\n\tfor estimate in estimates:\n\t\tresult += (estimate - refValue)^2\n\tresult /= estimates.len.toFloat\n\n\nconst Samples = [(trueValue: 49.0, estimates: @[48.0, 47.0, 51.0]),\n\t\t\t\t\t\t\t\t (trueValue: 49.0, estimates: @[48.0, 47.0, 51.0, 42.0])]\n\nfor (trueValue, estimates, ) in Samples:\n\tlet m = mean(estimates)\n\techo \"True value: \", trueValue\n\techo \"Estimates: \", estimates.join(\", \")\n\techo \"Average error: \", meanSquareDiff(trueValue, estimates)\n\techo \"Crowd error: \", (m - trueValue)^2\n\techo \"Prediction diversity: \", meanSquareDiff(m, estimates)\n\techo \"\"\n" + }, + { + "id": 1147, + "length": 722, + "source": "Rosetta Code", + "text": "import math, sequtils, sugar\n\nproc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =\n\tif len(barChart) <= 2:\n\t\treturn\n\tif isLeftPeak and isRightPeak:\n\t\treturn sum(barChart[1..^2].map(x=>min(barChart[0], barChart[^1])-x))\n\tvar i: int\n\tif isLeftPeak:\n\t\ti = maxIndex(barChart[1..^1])+1\n\telse:\n\t\ti = maxIndex(barChart[0..^2])\n\treturn water(barChart[0..i], isLeftPeak, true)+water(barChart[i..^1], true, isRightPeak)\n\nconst barCharts = [\n\t\t@[1, 5, 3, 7, 2],\n\t\t@[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n\t\t@[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n\t\t@[5, 5, 5, 5],\n\t\t@[5, 6, 7, 8],\n\t\t@[8, 7, 7, 6],\n\t\t@[6, 7, 10, 7, 6]]\nconst waterUnits = barCharts.map(chart=>water(chart, false, false))\necho(waterUnits)\n" + }, + { + "id": 1148, + "length": 3553, + "source": "Rosetta Code", + "text": "import algorithm, strformat, strutils, tables\n\ntype\n\n\tNode = ref object\n\t\tedges: Table[char, Node] # Edges (forward links).\n\t\tlink: Node # Suffix link (backward link).\n\t\tlen: int # Length of the node.\n\n\tEertree = object\n\t\tnodes: seq[Node]\n\t\trto: Node # Odd length root node or node -1.\n\t\trte: Node # Even length root node or node 0.Node\n\t\tstr: string # Accumulated input string.\n\t\tmaxSuf: Node # Maximum suffix.\n\n\nfunc initEertree(): Eertree =\n\t## Create and initialize an eertree.\n\tresult = Eertree(rto: Node(len: - 1), rte: Node(len: 0))\n\tresult.rto.link = result.rto\n\tresult.rte.link = result.rto\n\tresult.str = \"0\"\n\tresult.maxSuf = result.rte\n\n\nfunc getMaxSuffixPal(tree: Eertree; startNode: Node; ch: char): Node =\n\t## We traverse the suffix-palindromes of \"tree\" in the order of decreasing length.\n\t## For each palindrome we read its length \"k\" and compare \"tree[i-k]\" against \"ch\"\n\t## until we get an equality or arrive at the -1 node.\n\n\tresult = startNode\n\tlet i = tree.str.high\n\twhile result != tree.rto and tree.str[i - result.len] != ch:\n\t\tdoAssert(result != result.link, \"circular reference above odd root\")\n\t\tresult = result.link\n\n\nfunc add(tree: var Eertree; ch: char): bool =\n\t## We need to find the maximum suffix-palindrome P of Ta.\n\t## Start by finding maximum suffix-palindrome Q of T.\n\t## To do this, we traverse the suffix-palindromes of T\n\t## in the order of decreasing length, starting with maxSuf(T).\n\n\tlet q = tree.getMaxSuffixPal(tree.maxSuf, ch)\n\n\t# We check \"q\" to see whether it has an outgoing edge labeled by \"ch\".\n\tresult = ch notin q.edges\n\n\tif result:\n\t\t# We create the node \"p\" of length \"q.len + 2\"\n\t\tlet p = Node()\n\t\ttree.nodes.add(p)\n\t\tp.len = q.len + 2\n\t\tif p.len == 1:\n\t\t\t# If p = ch, create the suffix link (p, 0).\n\t\t\tp.link = tree.rte\n\t\telse:\n\t\t\t# It remains to create the suffix link from \"p\" if \"|p|>1\". Just continue\n\t\t\t# traversing suffix-palindromes of T starting with the suffix link of \"q\".\n\t\t\tp.link = tree.getMaxSuffixPal(q.link, ch).edges[ch]\n\t\t# Create the edge \"(q, p)\".\n\t\tq.edges[ch] = p\n\n\t# \"p\" becomes the new maxSuf.\n\ttree.maxSuf = q.edges[ch]\n\n\t# Store accumulated input string.\n\ttree.str.add(ch)\n\n\nfunc getSubPalindromes(tree: Eertree; node: Node;\n\t\t\t\t\t\t\t\t\t\t\t nodesToHere: seq[Node]; charsToHere: string;\n\t\t\t\t\t\t\t\t\t\t\t result: var seq[string]) =\n\t## Each node represents a palindrome, which can be reconstructed\n\t## by the path from the root node to each non-root node.\n\n\t# Traverse all edges, since they represent other palindromes.\n\tfor linkName, node2 in node.edges.pairs:\n\t\ttree.getSubPalindromes(node2, nodesToHere & node2, charsToHere & linkName, result)\n\n\t# Reconstruct based on charsToHere characters.\n\tif node notin [tree.rto, tree.rte]:\n\t\t# Don't print for root nodes.\n\t\tlet assembled = reversed(charsTohere).join() &\n\t\t\t\t\t\t\t\t\t\t(if nodesToHere[0] == tree.rte: charsToHere\n\t\t\t\t\t\t\t\t\t\t else: charsToHere[1..^1])\n\t\tresult.add(assembled)\n\n\nfunc getSubPalindromes(tree: Eertree): seq[string] =\n\t## Traverse tree to find sub-palindromes.\n\n\t# Odd length words\n\ttree.getSubPalindromes(tree.rto, @[tree.rto], \"\", result)\n\t# Even length words\n\ttree.getSubPalindromes(tree.rte, @[tree.rte], \"\", result)\n\n\nwhen isMainModule:\n\tconst Str = \"eertree\"\n\techo fmt\"Processing string: '{Str}'\"\n\tvar eertree = initEertree()\n\tfor ch in Str:\n\t\tdiscard eertree.add(ch)\n\techo fmt\"Number of sub-palindromes: {eertree.nodes.len}\"\n\tlet result = eertree.getSubPalindromes()\n\techo fmt\"Sub-palindromes: {result.join(\"\", \"\")}\"\n" + }, + { + "id": 1149, + "length": 1301, + "source": "Rosetta Code", + "text": "import algorithm, sugar, tables\n\nconst\n\tDigits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\tValues = collect(initTable):\n\t\t\t\t\t\t for i, c in Digits: {c: i} # Maps the digits to their values in base 10.\n\ntype Number = object\n\t## Representation of a number in any base.\n\tbase: int\n\tvalue: string\n\nfunc toBase(n, base: int): Number =\n\t## Convert an integer into a number in base 'base'.\n\tassert base notin -1..1, \"wrong value for base: \" & $base\n\tif n == 0: return Number(base: base, value: \"0\")\n\tresult.base = base\n\tvar n = n\n\twhile n != 0:\n\t\tvar m = n mod base\n\t\tn = n div base\n\t\tif m < 0:\n\t\t\tinc m, abs(base)\n\t\t\tinc n\n\t\tresult.value.add Digits[m]\n\tresult.value.reverse()\n\nfunc `$`(n: Number): string =\n\t## String representation of a number.\n\t$n.value\n\nfunc toInt(n: Number): int =\n\t## Convert a number in some base into an integer in base 10.\n\tfor d in n.value:\n\t\tresult = n.base * result + Values[d]\n\n\nwhen isMainModule:\n\n\tproc process(n, base: int) =\n\t\tlet s = n.toBase(base)\n\t\techo \"The value \", n, \" is encoded in base \", base, \" as: \", s\n\t\techo \"and is decoded back in base 10 as: \", s.toInt\n\t\techo \"\"\n\nprocess(10, -2)\nprocess(146, -3)\nprocess(15, -10)\n\nconst Nim = Number(base: -62, value: \"Nim\")\necho \"The string Nim is decoded from base -62 to base 10 as: \", Nim.toInt\n" + }, + { + "id": 1150, + "length": 1056, + "source": "Rosetta Code", + "text": "type Vector = tuple[x, y, z: float]\n\n\nfunc `+`(v1, v2: Vector): Vector =\n\t## Add two vectors.\n\t(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)\n\nfunc `-`(v1, v2: Vector): Vector =\n\t## Subtract a vector to another one.\n\t(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z)\n\nfunc `*`(v1, v2: Vector): float =\n\t## Compute the dot product of two vectors.\n\tv1.x * v2.x + v1.y * v2.y + v1.z * v2.z\n\nfunc `*`(v: Vector; k: float): Vector =\n\t## Multiply a vector by a scalar.\n\t(v.x * k, v.y * k, v.z * k)\n\n\nfunc intersection(lineVector, linePoint, planeVector, planePoint: Vector): Vector =\n\t## Return the coordinates of the intersection of two vectors.\n\n\tlet tnum = planeVector * (planePoint - linePoint)\n\tlet tdenom = planeVector * lineVector\n\tif tdenom == 0: return (Inf, Inf, Inf) # No intersection.\n\tlet t = tnum / tdenom\n\tresult = lineVector * t + linePoint\n\nlet coords = intersection(lineVector = (0.0, -1.0, -1.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\tlinePoint = (0.0, 0.0, 10.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\tplaneVector = (0.0, 0.0, 1.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\tplanePoint = (0.0, 0.0, 5.0))\necho \"Intersection at \", coords\n" + }, + { + "id": 1151, + "length": 669, + "source": "Rosetta Code", + "text": "type\n\tLine = tuple\n\t\tslope: float\n\t\tyInt: float\n\tPoint = tuple\n\t\tx: float\n\t\ty: float\n\nfunc createLine(a, b: Point): Line =\n\tresult.slope = (b.y - a.y) / (b.x - a.x)\n\tresult.yInt = a.y - result.slope * a.x\n\nfunc evalX(line: Line, x: float): float =\n\tline.slope * x + line.yInt\n\nfunc intersection(line1, line2: Line): Point =\n\tlet x = (line2.yInt - line1.yInt) / (line1.slope - line2.slope)\n\tlet y = evalX(line1, x)\n\t(x, y)\n\nvar line1 = createLine((4.0, 0.0), (6.0, 10.0))\nvar line2 = createLine((0.0, 3.0), (10.0, 7.0))\necho intersection(line1, line2)\nline1 = createLine((0.0, 0.0), (1.0, 1.0))\nline2 = createLine((1.0, 2.0), (4.0, 5.0))\necho intersection(line1, line2)\n" + }, + { + "id": 1152, + "length": 3649, + "source": "Rosetta Code", + "text": "import strformat\n\ntype Point = tuple[x, y: float]\n\ntype Triangle = array[3, Point]\n\nfunc `$`(p: Point): string =\n\tfmt\"({p.x:.1f}, {p.y:.1f})\"\n\nfunc `$`(t: Triangle): string =\n\tfmt\"Triangle {t[0]}, {t[1]}, {t[2]}\"\n\nfunc det2D(t: Triangle): float =\n\tt[0].x * (t[1].y - t[2].y) +\n\tt[1].x * (t[2].y - t[0].y) +\n\tt[2].x * (t[0].y - t[1].y)\n\nfunc checkTriWinding(t: var Triangle; allowReversed: bool) =\n\tlet det = t.det2D()\n\tif det < 0:\n\t\tif allowReversed:\n\t\t\tswap t[1], t[2]\n\t\telse:\n\t\t\traise newException(ValueError, \"Triangle has wrong winding direction.\")\n\nfunc boundaryCollideChk(t: Triangle; eps: float): bool =\n\tt.det2D() < eps\n\nfunc boundaryDoesntCollideChk(t: Triangle; eps: float): bool =\n\tt.det2D() <= eps\n\nfunc triTri2D(t1, t2: var Triangle; eps = 0.0;\n\t\t\t\t\t\t\tallowReversed = false; onBoundary = true): bool =\n\n\t# Triangles must be expressed anti-clockwise.\n\tt1.checkTriWinding(allowReversed)\n\tt2.checkTriWinding(allowReversed)\n\n\t# \"onBoundary\" determines whether points on boundary are considered as colliding or not.\n\tlet chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk\n\n\t# For each edge E of t1.\n\tfor i in 0..2:\n\t\tlet j = (i + 1) mod 3\n\t\t# Check that all points of t2 lay on the external side of edge E.\n\t\t# If they do, the triangles do not overlap.\n\t\tif chkEdge([t1[i], t1[j], t2[0]], eps) and\n\t\t\t chkEdge([t1[i], t1[j], t2[1]], eps) and\n\t\t\t chkEdge([t1[i], t1[j], t2[2]], eps):\n\t\t\t\t return false\n\n\t# For each edge E of t2.\n\tfor i in 0..2:\n\t\tlet j = (i + 1) mod 3\n\t\t# Check that all points of t1 lay on the external side of edge E.\n\t\t# If they do, the triangles do not overlap.\n\t\tif chkEdge([t2[i], t2[j], t1[0]], eps) and\n\t\t\t chkEdge([t2[i], t2[j], t1[1]], eps) and\n\t\t\t chkEdge([t2[i], t2[j], t1[2]], eps):\n\t\t\t\t return false\n\n\t# The triangles overlap.\n\tresult = true\n\n\nwhen isMainModule:\n\n\tvar t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]\n\tvar t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)]\n\techo t1, \" and\\n\", t2\n\tvar overlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\t# Need to allow reversed for this pair to avoid exception.\n\tt1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)]\n\tt2 = t1\n\techo t1, \" and\\n\", t2\n\toverlapping = triTri2D(t1, t2, 0, true, true)\n\techo if overlapping: \"overlap (reversed)\\n\" else: \"do not overlap\\n\"\n\n\tt1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)]\n\tt2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)]\n\techo t1, \" and\\n\", t2\n\toverlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\tt1[2] = (2.5, 5.0)\n\tt2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)]\n\techo t1, \" and\\n\", t2\n\toverlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\tt1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)]\n\tt2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)]\n\techo t1, \" and\\n\", t2\n\toverlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\tt2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)]\n\techo t1, \" and\\n\", t2\n\toverlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\tt1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)]\n\tt2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)]\n\techo t1, \" and\\n\", t2\n\techo \"which have only a single corner in contact, if boundary points collide\"\n\toverlapping = triTri2D(t1, t2, 0, false, true)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n\n\techo t1, \" and\\n\", t2\n\techo \"which have only a single corner in contact, if boundary points do not collide\"\n\toverlapping = triTri2D(t1, t2, 0, false, false)\n\techo if overlapping: \"overlap\\n\" else: \"do not overlap\\n\"\n" + }, + { + "id": 1153, + "length": 758, + "source": "Rosetta Code", + "text": "import math\nimport strutils\n\n\nproc delta(b1, b2: float) : float =\n\tresult = (b2 - b1) mod 360.0\n\n\tif result < -180.0:\n\t\tresult += 360.0\n\telif result >= 180.0:\n\t\tresult -= 360.0\n\n\nlet testVectors : seq[tuple[b1, b2: float]] = @[\n\t\t\t(20.00, 45.00 ),\n\t\t (-45.00, 45.00 ),\n\t\t (-85.00, 90.00 ),\n\t\t (-95.00, 90.00 ),\n\t\t (-45.00, 125.00 ),\n\t\t (-45.00, 145.00 ),\n\t\t ( 29.48, -88.64 ),\n\t\t (-78.33, -159.04 ),\n\t(-70099.74, 29840.67 ),\n (-165313.67, 33693.99 ),\n\t\t(1174.84, -154146.66 ),\n\t (60175.77, 42213.07 ) ]\n\nfor vector in testVectors:\n\techo vector.b1.formatFloat(ffDecimal, 2).align(13) &\n\t\t\t vector.b2.formatFloat(ffDecimal, 2).align(13) &\n\t\t\t delta(vector.b1, vector.b2).formatFloat(ffDecimal, 2).align(13)\n" + }, + { + "id": 1154, + "length": 942, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc filter(a, b, signal: openArray[float]): seq[float] =\n\n\tresult.setLen(signal.len)\n\n\tfor i in 0..signal.high:\n\t\tvar tmp = 0.0\n\t\tfor j in 0..min(i, b.high):\n\t\t\ttmp += b[j] * signal[i - j]\n\t\tfor j in 1..min(i, a.high):\n\t\t\ttmp -= a[j] * result[i - j]\n\t\ttmp /= a[0]\n\t\tresult[i] = tmp\n\n\nlet a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]\nlet b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nlet signal = [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n\t\t\t\t\t\t\t-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n\t\t\t\t\t\t\t 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n\t\t\t\t\t\t\t 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n\t\t\t\t\t\t\t 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\nlet result = filter(a, b, signal)\nfor i in 0..result.high:\n\tstdout.write fmt\"{result[i]: .8f}\"\n\tstdout.write if (i + 1) mod 5 != 0: \", \" else: \"\\n\"\n" + }, + { + "id": 1155, + "length": 1116, + "source": "Rosetta Code", + "text": "func isUnique(a, b, c, d, e, f, g: uint8): bool =\n\ta != b and a != c and a != d and a != e and a != f and a != g and\n\t\tb != c and b != d and b != e and b != f and b != g and\n\t\tc != d and c != e and c != f and c != g and\n\t\td != e and d != f and d != f and\n\t\te != f and e != g and\n\t\tf != g\n\nfunc isSolution(a, b, c, d, e, f, g: uint8): bool =\n\tlet sum = a + b\n\tsum == b + c + d and sum == d + e + f and sum == f + g\n\nfunc fourSquares(l, h: uint8, unique: bool): seq[array[7, uint8]] =\n\tfor a in l..h:\n\t\tfor b in l..h:\n\t\t\tfor c in l..h:\n\t\t\t\tfor d in l..h:\n\t\t\t\t\tfor e in l..h:\n\t\t\t\t\t\tfor f in l..h:\n\t\t\t\t\t\t\tfor g in l..h:\n\t\t\t\t\t\t\t\tif (not unique or isUnique(a, b, c, d, e, f, g)) and\n\t\t\t\t\t\t\t\t\t isSolution(a, b, c, d, e, f, g):\n\t\t\t\t\t\t\t\t\tresult &= [a, b, c, d, e, f, g]\n\nproc printFourSquares(l, h: uint8, unique = true) =\n\tlet solutions = fourSquares(l, h, unique)\n\n\tif unique:\n\t\tfor s in solutions:\n\t\t\techo s\n\n\techo solutions.len, (if unique: \" \" else: \" non-\"), \"unique solutions in \",\n\t\t l, \" to \", h, \" range\\n\"\n\nwhen isMainModule:\n\tprintFourSquares(1, 7)\n\tprintFourSquares(3, 9)\n\tprintFourSquares(0, 9, unique = false)\n" + }, + { + "id": 1156, + "length": 1091, + "source": "Rosetta Code", + "text": "import algorithm, parseutils, sequtils, strutils, tables\n\ntype Expression = string\n\nproc buildExprs(start: Natural = 0): seq[Expression] =\n\tlet item = if start == 0: \"\" else: $start\n\tif start == 9: return @[item]\n\tfor expr in buildExprs(start + 1):\n\t\tresult.add item & expr\n\t\tresult.add item & '-' & expr\n\t\tif start != 0: result.add item & '+' & expr\n\nproc evaluate(expr: Expression): int =\n\tvar idx = 0\n\tvar val: int\n\twhile idx < expr.len:\n\t\tlet n = expr.parseInt(val, idx)\n\t\tinc idx, n\n\t\tresult += val\n\nlet exprs = buildExprs()\nvar counts: CountTable[int]\n\necho \"The solutions for 100 are:\"\nfor expr in exprs:\n\tlet sum = evaluate(expr)\n\tif sum == 100: echo expr\n\tif sum > 0: counts.inc(sum)\n\nlet (n, count) = counts.largest()\necho \"\\nThe maximum count of positive solutions is $1 for number $2.\".format(count, n)\n\nvar s = 1\nwhile true:\n\tif s notin counts:\n\t\techo \"\\nThe smallest number than cannot be expressed is: $1.\".format(s)\n\t\tbreak\n\tinc s\n\necho \"\\nThe ten highest numbers than can be expressed are:\"\nlet numbers = sorted(toSeq(counts.keys), Descending)\necho numbers[0..9].join(\", \")\n" + }, + { + "id": 1157, + "length": 6156, + "source": "Rosetta Code", + "text": "#[\n**********************************************************************\n*\n* A cube 'state' is a sequence of ints with 40 entries, the first\n* 20 are a permutation of {0,...,19} and describe which cubie is\n* at a certain position (regarding the input ordering). The first\n* twelve are for edges, the last eight for corners.\n*\n* The last 20 entries are for the orientations, each describing\n* how often the cubie at a certain position has been turned\n* counterclockwise away from the correct orientation. Again the\n* first twelve are edges, the last eight are corners. The values\n* are 0 or 1 for edges and 0, 1 or 2 for corners.\n*\n**********************************************************************\n]#\n\nimport deques, os, strformat, strutils, tables, times\n\nconst\n\n\tApplicableMoves = [0, 262143, 259263, 74943, 74898]\n\n\tAffectedCubies = [[0, 1, 2, 3, 0, 1, 2, 3], # U\n\t\t\t\t\t\t\t\t\t\t[4, 7, 6, 5, 4, 5, 6, 7], # D\n\t\t\t\t\t\t\t\t\t\t[0, 9, 4, 8, 0, 3, 5, 4], # F\n\t\t\t\t\t\t\t\t\t\t[2, 10, 6, 11, 2, 1, 7, 6], # B\n\t\t\t\t\t\t\t\t\t\t[3, 11, 7, 9, 3, 2, 6, 5], # L\n\t\t\t\t\t\t\t\t\t\t[1, 8, 5, 10, 1, 0, 4, 7]] # R\n\ntype State = seq[int]\n\nfunc initState(n: Natural = 0): State = newSeq[int](n)\n\n\nvar phase: Natural\n\n\nproc slicetoState(s: openArray[int]): State =\n\tresult.setLen(40)\n\tfor i, val in s: result[i] = val\n\tfor i in s.len..39: result[i] = -1\n\n\nproc id(state: State): State =\n\n\tcase phase\n\tof 1: # Phase 1: Edge orientations.\n\t\tresult = sliceToState(state[20..31])\n\n\tof 2: # Phase 2: Corner orientations, E slice edges.\n\t\tvar res = state[31..39]\n\t\tfor e in 0..11:\n\t\t\tres[0] = res[0] or state[e] shr 3 shl e\n\t\tresult = sliceToState(res)\n\n\tof 3: # Phase 3: Edge slices M and S, corner tetrads, overall parity.\n\t\tvar res = @[0, 0, 0]\n\t\tfor e in 0..11:\n\t\t\tlet temp = if state[e] > 7: 2 else: (state[e] and 1) shl (2 * e)\n\t\t\tres[0] = res[0] or temp\n\t\tfor c in 0..7:\n\t\t\tres[1] = res[1] or ((state[c + 12] - 12) and 5) shl (3 * c)\n\t\tfor i in 12..18:\n\t\t\tfor j in (i + 1)..19:\n\t\t\t\tres[2] = res[2] xor ord(state[i] > state[j])\n\t\tresult = sliceToState(res)\n\n\telse: # Phase 4: The rest.\n\t\tresult = state\n\n\nproc applyMove(move: int; state: State): State =\n\tresult = state\n\tvar turns = move mod 3 + 1\n\tlet face = move div 3\n\twhile turns != 0:\n\t\tdec turns\n\t\tvar oldState = result\n\t\tfor i in 0..7:\n\t\t\tlet isCorner = ord(i > 3)\n\t\t\tlet target = AffectedCubies[face][i] + isCorner * 12\n\t\t\tlet temp = if (i and 3) == 3: i - 3 else: i + 1\n\t\t\tlet killer = AffectedCubies[face][temp] + isCorner * 12\n\t\t\tlet orientationDelta =\n\t\t\t\tif i < 4: ord(face in 2..3)\n\t\t\t\telif face < 2: 0\n\t\t\t\telse: 2 - (i and 1)\n\t\t\tresult[target] = oldState[killer]\n\t\t\tresult[target + 20] = oldState[killer + 20] + orientationDelta\n\t\t\tif turns == 0:\n\t\t\t\t\tresult[target + 20] = result[target + 20] mod (2 + isCorner)\n\n\nfunc inverse(move: int): int = move + 2 - 2 * (move mod 3)\n\n\nlet startTime = cpuTime()\nvar aggregateMoves = 0\n\n# Define the goal.\nconst Goal = [\"UF\", \"UR\", \"UB\", \"UL\", \"DF\", \"DR\", \"DB\", \"DL\", \"FR\", \"FL\", \"BR\", \"BL\",\n\t\t\t\t\t\t\t\"UFR\", \"URB\", \"UBL\", \"ULF\", \"DRF\", \"DFL\", \"DLB\", \"DBR\"]\n\n# Load dataset (file name should be passed as a command line argument).\nif paramCount() == 0: quit \"Missing file name\", QuitFailure\nvar lineCount = 0\nfor line in paramStr(1).lines():\n\tlet inputs = line.splitWhitespace()\n\tinc lineCount\n\tvar totalMoves = 0\n\n\t# Prepare current (start) and goal state.\n\tvar currentState, goalState = initState(40)\n\tfor i in 0..19:\n\t\t# Goal state.\n\t\tgoalState[i] = i\n\t\t# Current (start) state.\n\t\tvar cubie = inputs[i]\n\t\twhile true:\n\t\t\tlet idx = Goal.find(cubie)\n\t\t\tcurrentState[i] = if idx >= 0: idx else: 20\n\t\t\tif currentState[i] != 20: break\n\t\t\tcubie = cubie[1..^1] & cubie[0]\n\t\t\tinc currentState[i + 20]\n\n\t# Dance the funky Thistlethwaite...\n\tphase = 1\n\twhile phase < 5:\n\t\tblock doPhase:\n\n\t\t\t# Compute ids for current and goal state, skip phase if equal.\n\t\t\tlet currentId = id(currentState)\n\t\t\tlet goalId = id(goalState)\n\t\t\tif currentId == goalId: break doPhase\n\n\t\t\t# Initialize the BFS queue.\n\t\t\tvar q = [currentState, goalState].toDeque\n\n\t\t\t# Initialize the BFS tables.\n\t\t\tvar predecessor: Table[State, State]\n\t\t\tvar direction, lastMove: Table[State, int]\n\t\t\tdirection[currentId] = 1\n\t\t\tdirection[goalId] = 2\n\n\t\t\t# Dance the funky bidirectional BFS.\n\t\t\twhile true:\n\t\t\t\t# Get state from queue, compute its ID and get its direction.\n\t\t\t\tlet oldState = q.popFirst()\n\t\t\t\tvar oldId = id(oldState)\n\t\t\t\tlet oldDir = direction[oldId]\n\n\t\t\t\t# Apply all applicable moves to it and handle the new state.\n\t\t\t\tvar move = 0\n\t\t\t\twhile move < 18:\n\t\t\t\t\tif (ApplicableMoves[phase] and (1 shl move)) != 0:\n\t\t\t\t\t\t# Apply the move.\n\t\t\t\t\t\tlet newState = applyMove(move, oldState)\n\t\t\t\t\t\tvar newId = id(newState)\n\t\t\t\t\t\tlet newDir = direction.getOrDefault(newId, 0)\n\n\t\t\t\t\t\t# Have we seen this state (id) from the other direction already?\n\t\t\t\t\t\t# I.e. have we found a connection?\n\t\t\t\t\t\tif newDir != 0 and newDir != oldDir:\n\t\t\t\t\t\t\t# Make oldId represent the forwards and newId the backwards search state.\n\t\t\t\t\t\t\tif oldDir > 1:\n\t\t\t\t\t\t\t\tswap newId, oldId\n\t\t\t\t\t\t\t\tmove = inverse(move)\n\n\t\t\t\t\t\t\t# Reconstruct the connecting algorithm.\n\t\t\t\t\t\t\tvar algorithm: State = @[move]\n\t\t\t\t\t\t\twhile oldId != currentId:\n\t\t\t\t\t\t\t\talgorithm.insert(lastMove.mgetOrPut(oldId, 0), 0)\n\t\t\t\t\t\t\t\toldId = predecessor.mgetOrPut(oldId, initState())\n\t\t\t\t\t\t\twhile newId != goalId:\n\t\t\t\t\t\t\t\talgorithm.add inverse(lastMove.mgetOrPut(newId, 0))\n\t\t\t\t\t\t\t\tnewId = predecessor.mgetOrPut(newId, initState())\n\n\t\t\t\t\t\t\t# Print and apply the algorithm.\n\t\t\t\t\t\t\tfor step in algorithm:\n\t\t\t\t\t\t\t\tstdout.write \"UDFBLR\"[step div 3], step mod 3 + 1, ' '\n\t\t\t\t\t\t\t\tinc totalMoves\n\t\t\t\t\t\t\t\tcurrentState = applyMove(step, currentState)\n\n\t\t\t\t\t\t\t# Jump to the next phase.\n\t\t\t\t\t\t\tbreak doPhase\n\n\t\t\t\t\t\t# If we've never seen this state (id) before, visit it.\n\t\t\t\t\t\tif newdir == 0:\n\t\t\t\t\t\t\tq.addLast(newState)\n\t\t\t\t\t\t\tdirection[newId] = oldDir\n\t\t\t\t\t\t\tlastMove[newId] = move\n\t\t\t\t\t\t\tpredecessor[newId] = oldId\n\n\t\t\t\t\tinc move\n\n\t\tinc phase\n\n\techo \" (moves {totalMoves})\"\n\tinc aggregateMoves, totalMoves\n\nlet elapsedTime = cpuTime() - startTime\necho \"\\nAverage number of moves = {aggregateMoves / lineCount}\"\necho \"\\nAverage time = {elapsedTime * 1000 / lineCount.toFloat:.2f} milliseconds\"\n" + }, + { + "id": 1158, + "length": 1082, + "source": "Rosetta Code", + "text": "import strutils, threadpool\nimport nimcrypto\n\nconst\n\n\t# List of hexadecimal representation of target hashes.\n\tHexHashes = [\"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad\",\n\t\t\t\t\t\t\t \"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b\",\n\t\t\t\t\t\t\t \"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f\"]\n\n\t# List of target hashes.\n\tHashes = [MDigest[256].fromHex(HexHashes[0]),\n\t\t\t\t\t\tMDigest[256].fromHex(HexHashes[1]),\n\t\t\t\t\t\tMDigest[256].fromHex(HexHashes[2])]\n\n\tLetters = 'a'..'z'\n\n\nproc findHashes(a: char) =\n\t## Build the arrays of five characters starting with the value\n\t## of \"a\" and check if their hash matches one of the targets.\n\t## Print the string and the hash value if a match is found.\n\tfor b in Letters:\n\t\tfor c in Letters:\n\t\t\tfor d in Letters:\n\t\t\t\tfor e in Letters:\n\t\t\t\t\tlet s = [a, b, c, d, e]\n\t\t\t\t\tlet h = sha256.digest(s)\n\t\t\t\t\tfor i, target in Hashes:\n\t\t\t\t\t\tif h == target: # Match.\n\t\t\t\t\t\t\techo s.join(), \" -> \", HexHashes[i]\n\n\n# Launch a thread for each starting character.\nfor a in Letters:\n\tspawn findHashes(a)\n\nsync()\n" + }, + { + "id": 1159, + "length": 1592, + "source": "Rosetta Code", + "text": "import sequtils, strutils, tables\n\ntype\n\n\tNode = ref object\n\t\tval: int\n\t\tindex: int\n\t\tlowLink: int\n\t\tonStack: bool\n\n\tNodes = seq[Node]\n\n\tDirectedGraph = object\n\t\tnodes: seq[Node]\n\t\tedges: Table[int, Nodes]\n\n\nfunc initNode(n: int): Node =\n\tNode(val: n, index: -1, lowLink: -1, onStack: false)\n\n\nfunc `$`(node: Node): string = $node.val\n\n\nfunc tarjan(g: DirectedGraph): seq[Nodes] =\n\tvar index = 0\n\tvar s: seq[Node]\n\tvar sccs: seq[Nodes]\n\n\n\tfunc strongConnect(v: Node) =\n\n\t\t# Set the depth index for \"v\" to the smallest unused index.\n\t\tv.index = index\n\t\tv.lowLink = index\n\t\tinc index\n\t\ts.add v\n\t\tv.onStack = true\n\n\t\t# Consider successors of \"v\".\n\t\tfor w in g.edges[v.val]:\n\t\t\tif w.index < 0:\n\t\t\t\t# Successor \"w\" has not yet been visited; recurse on it.\n\t\t\t\tw.strongConnect()\n\t\t\t\tv.lowLink = min(v.lowLink, w.lowLink)\n\t\t\telif w.onStack:\n\t\t\t\t# Successor \"w\" is in stack \"s\" and hence in the current SCC.\n\t\t\t\tv.lowLink = min(v.lowLink, w.index)\n\n\t\t# If \"v\" is a root node, pop the stack and generate an SCC.\n\t\tif v.lowLink == v.index:\n\t\t\tvar scc: Nodes\n\t\t\twhile true:\n\t\t\t\tlet w = s.pop()\n\t\t\t\tw.onStack = false\n\t\t\t\tscc.add w\n\t\t\t\tif w == v: break\n\t\t\tsccs.add scc\n\n\n\tfor v in g.nodes:\n\t\tif v.index < 0:\n\t\t\tv.strongConnect()\n\tresult = move(sccs)\n\n\nwhen isMainModule:\n\n\tlet vs = toSeq(0..7).map(initNode)\n\tlet es = {0: @[vs[1]],\n\t\t\t\t\t\t1: @[vs[2]],\n\t\t\t\t\t\t2: @[vs[0]],\n\t\t\t\t\t\t3: @[vs[1], vs[2], vs[4]],\n\t\t\t\t\t\t4: @[vs[5], vs[3]],\n\t\t\t\t\t\t5: @[vs[2], vs[6]],\n\t\t\t\t\t\t6: @[vs[5]],\n\t\t\t\t\t\t7: @[vs[4], vs[7], vs[6]]}.toTable\n\tvar g = DirectedGraph(nodes: vs, edges: es)\n\tlet sccs = g.tarjan()\n\techo sccs.join(\"\\n\")\n" + }, + { + "id": 1160, + "length": 1127, + "source": "Rosetta Code", + "text": "type\n\tVertex = int\n\tGraph = seq[seq[Vertex]]\n\tScc = seq[Vertex]\n\nfunc korasaju(g: Graph): seq[Scc] =\n\n\tvar\n\t\tsize = g.len\n\t\tvisited = newSeq[bool](size) # All false by default.\n\t\tl = newSeq[Vertex](size) # All zero by default.\n\t\tx = size # Index for filling \"l\" in reverse order.\n\t\tt = newSeq[seq[Vertex]](size) # Transposed graph.\n\t\tc = newSeq[Vertex](size) # Used for component assignment.\n\n\tfunc visit(u: Vertex) =\n\t\tif not visited[u]:\n\t\t\tvisited[u] = true\n\t\t\tfor v in g[u]:\n\t\t\t\tvisit(v)\n\t\t\t\tt[v].add(u) # Construct transposed graph.\n\t\t\tdec x\n\t\t\tl[x] = u\n\n\tfunc assign(u, root: Vertex) =\n\t\tif visited[u]:\n\t\t\t# Repurpose visited to mean 'unassigned'.\n\t\t\tvisited[u] = false\n\t\t\tc[u] = root\n\t\t\tfor v in t[u]: v.assign(root)\n\n\tfor u in 0..g.high: u.visit()\n\tfor u in l: u.assign(u)\n\n\t# Build list of strongly connected components.\n\tvar prev = -1\n\tfor v1, v2 in c:\n\t\tif v2 != prev:\n\t\t\tprev = v2\n\t\t\tresult.add @[]\n\t\tresult[^1].add v1\n\n\nwhen isMainModule:\n\tlet g = @[@[1], @[2], @[0], @[1, 2, 4], @[3, 5], @[2, 6], @[5], @[4, 6, 7]]\n\tfor scc in korasaju(g): echo $scc\n" + }, + { + "id": 1161, + "length": 3413, + "source": "Rosetta Code", + "text": "import algorithm, complex, math, strformat, strutils\n\nconst\n\tTwoI = complex(0.0, 2.0)\n\tInvTwoI = inv(TwoI)\n\ntype QuaterImaginery = object\n\tb2i: string\n\n# Conversions between digit character and digit value.\ntemplate digitChar(n: range[0..9]): range['0'..'9'] = chr(n + ord('0'))\ntemplate digitValue(c: range['0'..'9']): range[0..9] = ord(c) - ord('0')\n\n\n# Quater imaginary functions.\n\nfunc initQuaterImaginary(s: string): QuaterImaginery =\n\t## Create a Quater imaginary number.\n\tif s.len == 0 or not s.allCharsInSet({'0'..'3', '.'}) or s.count('.') > 1:\n\t\traise newException(ValueError, \"invalid base 2i number.\")\n\tresult = QuaterImaginery(b2i: s)\n\n\nfunc toComplex(q: QuaterImaginery): Complex[float] =\n\t## Convert a Quater imaginary number to a complex.\n\n\tlet pointPos = q.b2i.find('.')\n\tlet posLen = if pointPos != -1: pointPos else: q.b2i.len\n\tvar prod = complex(1.0)\n\n\tfor j in 0.. 0: result += prod * k\n\t\tprod *= TwoI\n\n\tif pointPos != -1:\n\t\tprod = InvTwoI\n\t\tfor j in (posLen + 1)..q.b2i.high:\n\t\t\tlet k = float(q.b2i[j].digitValue)\n\t\t\tif k > 0: result += prod * k\n\t\t\tprod *= InvTwoI\n\n\nfunc `$`(q: QuaterImaginery): string =\n\t## Convert a Quater imaginary number to a string.\n\tq.b2i\n\n\n# Supplementary functions for complex numbers.\n\nfunc toQuaterImaginary(c: Complex): QuaterImaginery =\n\t## Convert a complex number to a Quater imaginary number.\n\n\tif c.re == 0 and c.im == 0: return initQuaterImaginary(\"0\")\n\n\tvar re = c.re.toInt\n\tvar im = c.im.toInt\n\tvar fi = -1\n\n\twhile re != 0:\n\t\tvar rem = re mod -4\n\t\tre = re div -4\n\t\tif rem < 0:\n\t\t\tinc rem, 4\n\t\t\tinc re\n\t\tresult.b2i.add rem.digitChar\n\t\tresult.b2i.add '0'\n\n\tif im != 0:\n\t\tvar f = (complex(0.0, c.im) / TwoI).re\n\t\tim = f.ceil.toInt\n\t\tf = -4 * (f - im.toFloat)\n\t\tvar index = 1\n\t\twhile im != 0:\n\t\t\tvar rem = im mod -4\n\t\t\tim = im div -4\n\t\t\tif rem < 0:\n\t\t\t\tinc rem, 4\n\t\t\t\tinc im\n\t\t\tif index < result.b2i.len:\n\t\t\t\tresult.b2i[index] = rem.digitChar\n\t\t\telse:\n\t\t\t\tresult.b2i.add '0'\n\t\t\t\tresult.b2i.add rem.digitChar\n\t\t\tinc index, 2\n\t\tfi = f.toInt\n\n\tresult.b2i.reverse()\n\tif fi != -1: result.b2i.add \".\" & $fi\n\tresult.b2i = result.b2i.strip(leading = true, trailing = false, {'0'})\n\tif result.b2i.startsWith('.'): result.b2i = '0' & result.b2i\n\n\nfunc toString(c: Complex[float]): string =\n\t## Convert a complex number to a string.\n\t## This function is used in place of `$`.\n\n\tlet real = if c.re.classify == fcNegZero: 0.0 else: c.re\n\tlet imag = if c.im.classify == fcNegZero: 0.0 else: c.im\n\tresult = if imag >= 0: fmt\"{real} + {imag}i\" else: fmt\"{real} - {-imag}i\"\n\tresult = result.replace(\".0 \", \" \").replace(\".0i\", \"i\").replace(\" + 0i\", \"\")\n\tif result.startsWith(\"0 + \"): result = result[4..^1]\n\tif result.startsWith(\"0 - \"): result = '-' & result[4..^1]\n\n\n\nwhen isMainModule:\n\n\tfor i in 1..16:\n\t\tvar c1 = complex(i.toFloat)\n\t\tvar qi = c1.toQuaterImaginary\n\t\tvar c2 = qi.toComplex\n\t\tstdout.write fmt\"{c1.toString:>4s} -> {qi:>8s} -> {c2.toString:>4s} \"\n\t\tc1 = -c1\n\t\tqi = c1.toQuaterImaginary\n\t\tc2 = qi.toComplex\n\t\techo fmt\"{c1.toString:>4s} -> {qi:>8s} -> {c2.toString:>4s}\"\n\n\techo \"\"\n\n\tfor i in 1..16:\n\t\tvar c1 = complex(0.0, i.toFloat)\n\t\tvar qi = c1.toQuaterImaginary\n\t\tvar c2 = qi.toComplex\n\t\tstdout.write fmt\"{c1.toString:>4s} -> {qi:>8s} -> {c2.toString:>4s} \"\n\t\tc1 = -c1\n\t\tqi = c1.toQuaterImaginary\n\t\tc2 = qi.toComplex\n\t\techo fmt\"{c1.toString:>4s} -> {qi:>8s} -> {c2.toString:>4s}\"\n" + }, + { + "id": 1162, + "length": 1201, + "source": "Rosetta Code", + "text": "import math, sugar\n\nconst N = 100_000\n\n# Fill a sieve of Erathostenes.\nvar isPrime {.noInit.}: array[2..N, bool]\nfor item in isPrime.mitems: item = true\nfor n in 2..int(sqrt(N.toFloat)):\n\tif isPrime[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tisPrime[k] = false\n\n# Build list of primes.\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t for n in 2..N:\n\t\t\t\t\t\t\t\t if isPrime[n]: n\n\n\nproc partition(n, k: int; start = 0): seq[int] =\n\t## Partition \"n\" in \"k\" primes starting at position \"start\" in \"primes\".\n\t## Return the list of primes or an empty list if partitionning is impossible.\n\n\tif k == 1:\n\t\treturn if isPrime[n] and n >= primes[start]: @[n] else: @[]\n\n\tfor i in start..primes.high:\n\t\tlet a = primes[i]\n\t\tif n - a <= 1: break\n\t\tresult = partition(n - a, k - 1, i + 1)\n\t\tif result.len != 0:\n\t\t\treturn a & result\n\n\nwhen isMainModule:\n\n\timport strutils\n\n\tfunc plural(k: int): string =\n\t\tif k <= 1: \"\" else: \"s\"\n\n\tfor (n, k) in [(99809, 1), (18, 2), (19, 3), (20, 4),\n\t\t\t\t\t\t\t\t(2017, 24), (22699, 1), (22699, 2),\n\t\t\t\t\t\t\t\t(22699, 3), (22699, 4), (40355, 3)]:\n\t\tlet part = partition(n, k)\n\t\tif part.len == 0:\n\t\t\techo n, \" cannot be partitionned into \", k, \" prime\", plural(k)\n\t\telse:\n\t\t\techo n, \" = \", part.join(\" + \")\n" + }, + { + "id": 1163, + "length": 2045, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils\n\nconst\n\n\t# First byte of a 2-byte encoding starts 110 and carries 5 bits of data.\n\tB2Lead = 0xC0 # 1100 0000\n\tB2Mask = 0x1F # 0001 1111\n\n\t# First byte of a 3-byte encoding starts 1110 and carries 4 bits of data.\n\tB3Lead = 0xE0 # 1110 0000\n\tB3Mask = 0x0F # 0000 1111\n\n\t# First byte of a 4-byte encoding starts 11110 and carries 3 bits of data.\n\tB4Lead = 0xF0 # 1111 0000\n\tB4Mask = 0x07 # 0000 0111\n\n\t# Non-first bytes start 10 and carry 6 bits of data.\n\tMbLead = 0x80 # 1000 0000\n\tMbMask = 0x3F # 0011 1111\n\n\ntype CodePoint = distinct int32\n\n\nproc toUtf8(c: CodePoint): seq[byte] =\n\tlet i = int32(c)\n\tresult = if i <= 1 shl 7 - 1:\n\t\t\t\t\t\t @[byte(i)]\n\t\t\t\t\t elif i <= 1 shl 11 - 1:\n\t\t\t\t\t\t @[B2Lead or byte(i shr 6),\n\t\t\t\t\t\t\t MbLead or byte(i) and MbMask]\n\t\t\t\t\t elif i <= 1 shl 16 - 1:\n\t\t\t\t\t\t @[B3Lead or byte(i shr 12),\n\t\t\t\t\t\t\t MbLead or byte(i shr 6) and MbMask,\n\t\t\t\t\t\t\t MbLead or byte(i) and MbMask]\n\t\t\t\t\t else:\n\t\t\t\t\t\t @[B4Lead or byte(i shr 18),\n\t\t\t\t\t\t\t MbLead or byte(i shr 12) and MbMask,\n\t\t\t\t\t\t\t MbLead or byte(i shr 6) and MbMask,\n\t\t\t\t\t\t\t MbLead or byte(i) and MbMask]\n\n\nproc toCodePoint(b: seq[byte]): CodePoint =\n\tlet b0 = b[0].int32\n\tresult = CodePoint(\n\t\tif b0 < 0x80: b0\n\t\telif b0 < 0xE0: (b0 and B2Mask) shl 6 or b[1].int32 and MbMask\n\t\telif b0 < 0xF0: (b0 and B3Mask) shl 12 or\n\t\t\t\t\t\t\t\t\t\t(b[1].int32 and MbMask) shl 6 or b[2].int32 and MbMask\n\t\telse: (b0 and B4Mask) shl 18 or (b[1].int32 and MbMask) shl 12 or\n\t\t\t\t\t(b[2].int32 and MbMask) shl 6 or b[3].int32 and MbMask)\n\n\nproc toString(s: seq[byte]): string =\n\ts.mapIt(chr(it)).join()\n\n\nconst UChars = [CodePoint(0x00041),\n\t\t\t\t\t\t\t\tCodePoint(0x000F6),\n\t\t\t\t\t\t\t\tCodePoint(0x00416),\n\t\t\t\t\t\t\t\tCodePoint(0x020AC),\n\t\t\t\t\t\t\t\tCodePoint(0x1D11E)]\n\necho \"Character Unicode UTF-8 encoding (hex)\"\n\nfor uchar in UChars:\n\t# Convert the code point to a sequence of bytes.\n\tlet s = uchar.toUtf8\n\t# Convert back the sequence of bytes to a code point.\n\tlet c = s.toCodePoint\n\t# Display.\n\techo \"\"\"{s.toString:>5} U+{c.int.toHex(5)} {s.map(toHex).join(\" \")}\"\"\"\n" + }, + { + "id": 1164, + "length": 996, + "source": "Rosetta Code", + "text": "import strutils\n\ntype Matrix[M, N: static Positive; T: SomeNumber] = array[M, array[N, T]]\n\nfunc kroneckerProduct[M, N, P, Q: static int; T: SomeNumber](\n\ta: Matrix[M, N, T], b: Matrix[P, Q, T]): Matrix[M * P, N * Q, T] =\n\tfor i in 0..URL Not Found\"):\n\t\tresult = \"\"\n\tclient.close()\n\nlet today = now()\nconst Back = 10\nif paramCount() != 1:\n\tquit \"Wrong number of parameters\", QuitFailure\nlet needle = paramStr(1)\nfor i in -Back..1:\n\tlet day = today + initTimeInterval(days = i)\n\tlet url = day.format(Template)\n\tlet haystack = url.get()\n\tif haystack.len != 0:\n\t\tlet mentions = collect(newSeq):\n\t\t\t\t\t\t\t\t\t\t for line in haystack.splitLines(keepEol = true):\n\t\t\t\t\t\t\t\t\t\t\t if needle in line:\n\t\t\t\t\t\t\t\t\t\t\t\t line\n\t\tif mentions.len > 0:\n\t\t\techo \"{url}\\n------\\n{mentions.join()}------\\n\"\n" + }, + { + "id": 1167, + "length": 1443, + "source": "Rosetta Code", + "text": "import sequtils, sets, strutils\n\ntype\n\tDict = HashSet[string]\n\tWordSeq = seq[string]\n\nproc initDict(words: openArray[string]): Dict =\n\t## Initialize a dictionary from a list of words.\n\twords.toHashSet\n\nproc initDict(fileName: string; minlength = 0): Dict =\n\t## Initialize a dictionary with words from a file.\n\t## Only words with minimal length are retained.\n\tfor word in filename.lines:\n\t\tif word.len >= minLength:\n\t\t\tresult.incl word\n\nfunc wordBreaks(dict: Dict; word: string): seq[WordSeq] =\n\t## Build recursively the list of breaks for a word, using the given dictionary.\n\tfor last in 0..\"\n\telse:\n\t\tfor wordSeq in wordSeqs:\n\t\t\techo \" \", wordSeq.join(\" \")\n\nwhen isMainModule:\n\n\tconst EDict = [\"a\", \"bc\", \"abc\", \"cd\", \"b\"]\n\techo \"Using explicit dictionary: \", EDict\n\tvar dict = initDict(EDict)\n\tfor s in [\"abcd\", \"abbc\", \"abcbcd\", \"acdbc\", \"abcdd\"]:\n\t\tdict.breakWord(s)\n\n\techo(\"\\nUsing unixdict.txt dictionary without single letter words.\")\n\tdict = initDict(\"unixdict.txt\", 2)\n\tdict.breakWord(\"because\")\n\tdict.breakWord(\"software\")\n" + }, + { + "id": 1168, + "length": 939, + "source": "Rosetta Code", + "text": "iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] =\n\t# Yield the element of the cartesian product of \"a\" and \"b\".\n\t# Yield tuples rather than arrays as it allows T1 and T2 to be different.\n\n\tfor x in a:\n\t\tfor y in b:\n\t\t\tyield (x, y)\n\n\nwhen isMainModule:\n\n\tfrom seqUtils import toSeq\n\timport strformat\n\tfrom strutils import addSep\n\n\tproc `$`[T1, T2](t: tuple[a: T1, b: T2]): string =\n\t\t## Overloading of `$` to display a tuple without the field names.\n\t\t\"({t.a}, {t.b})\"\n\n\tproc `$$`[T](s: seq[T]): string =\n\t\t## New operator to display a sequence using mathematical set notation.\n\t\tresult = \"{\"\n\t\tfor item in s:\n\t\t\tresult.addSep(\", \", 1)\n\t\t\tresult.add($item)\n\t\tresult.add('}')\n\n\tconst Empty = newSeq[int]() # Empty list of \"int\".\n\n\tfor (a, b) in [(@[1, 2], @[3, 4]),\n\t\t\t\t\t\t\t\t (@[3, 4], @[1, 2]),\n\t\t\t\t\t\t\t\t (@[1, 2], Empty ),\n\t\t\t\t\t\t\t\t ( Empty, @[1, 2])]:\n\n\t\techo \"{$$a} x {$$b} = {$$toSeq(product(a, b))}\"\n" + }, + { + "id": 1169, + "length": 1982, + "source": "Rosetta Code", + "text": "import macros\n\nmacro product(args: varargs[typed]): untyped =\n\t## Macro to generate the code to build the product of several sequences.\n\n\tlet t = args[0].getType()\n\tif t.kind != nnkBracketExpr or t[0].kind != nnkSym or $t[0] != \"seq\":\n\t\terror(\"Arguments must be sequences\", args)\n\n\t# Build the result type i.e. a tuple with \"args.len\" elements.\n\t# Fields are named \"f0\", \"f1\", etc.\n\tlet tupleTyNode = newNimNode(nnkTupleTy)\n\tfor idx, arg in args:\n\t\tlet identDefsNode = newIdentDefs(ident('f' & $idx), arg.getType()[1])\n\t\ttupleTyNode.add(identDefsNode)\n\n\t# Build the nested for loops with counter \"i0\", \"i1\", etc.\n\tvar stmtListNode = newStmtList()\n\tlet loopsNode = nnkForStmt.newTree(ident(\"i0\"), ident($args[0]), stmtListNode)\n\tvar idx = 0\n\tfor arg in args[1..^1]:\n\t\tinc idx\n\t\tlet loopNode = nnkForStmt.newTree(ident('i' & $idx), ident($arg))\n\t\tstmtListNode.add(loopNode)\n\t\tstmtListNode = newStmtList()\n\t\tloopNode.add(stmtListNode)\n\n\t# Build the instruction \"result.add(i1, i2,...)\".\n\tlet parNode = newPar()\n\tlet addNode = newCall(newDotExpr(ident(\"result\"), ident(\"add\")), parNode)\n\tfor i, arg in args:\n\t\tparNode.add(ident('i' & $i))\n\tstmtListNode.add(addNode)\n\n\t# Build the tree.\n\tresult = nnkStmtListExpr.newTree(\n\t\t\t\t\t\t nnkVarSection.newTree(\n\t\t\t\t\t\t\t newIdentDefs(\n\t\t\t\t\t\t\t\t ident(\"result\"),\n\t\t\t\t\t\t\t\t nnkBracketExpr.newTree(ident(\"seq\"), tupleTyNode))),\n\t\t\t\t\t\t\t loopsNode,\n\t\t\t\t\t\t ident(\"result\"))\n\n\nwhen isMainModule:\n\n\timport strformat\n\timport strutils\n\n\tproc `$`[T: tuple](t: T): string =\n\t\t## Overloading of `$` to display a tuple without the field names.\n\t\tresult = \"(\"\n\t\tfor f in t.fields:\n\t\t\tresult.addSep(\", \", 1)\n\t\t\tresult.add($f)\n\t\tresult.add(']')\n\n\tproc `$$`[T](s: seq[T]): string =\n\t\t## New operator to display a sequence using mathematical set notation.\n\t\tresult = \"{\"\n\t\tfor item in s:\n\t\t\tresult.addSep(\", \", 1)\n\t\t\tresult.add($item)\n\t\tresult.add('}')\n\n\tvar a = @[1, 2]\n\tvar b = @['a', 'b']\n\tvar c = @[false, true]\n\techo \"{$$a} x {$$b} x {$$c} = {$$product(a, b, c)}\"\n" + }, + { + "id": 1170, + "length": 1241, + "source": "Rosetta Code", + "text": "from algorithm import reverse\n\nconst Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n\t\t\t\t\t\t\t [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n\t\t\t\t\t\t\t [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n\t\t\t\t\t\t\t [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n\t\t\t\t\t\t\t [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n\t\t\t\t\t\t\t [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n\t\t\t\t\t\t\t [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n\t\t\t\t\t\t\t [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n\t\t\t\t\t\t\t [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n\t\t\t\t\t\t\t [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]]\n\ntype Digit = range[0..9]\n\nfunc isValid(digits: openArray[Digit]): bool =\n\t## Apply Damm algorithm to check validity of a digit sequence.\n\tvar interim = 0\n\tfor d in digits:\n\t\tinterim = Table[interim][d]\n\tresult = interim == 0\n\nproc toDigits(n: int): seq[Digit] =\n\t## Return the digits of a number.\n\tvar n = n\n\twhile true:\n\t\tresult.add(n mod 10)\n\t\tn = n div 10\n\t\tif n == 0:\n\t\t\tbreak\n\tresult.reverse()\n\nproc checkData(digits: openArray[Digit]) =\n\t## Check if a digit sequence if valid.\n\tif isValid(digits):\n\t\techo \"Sequence \", digits, \" is valid.\"\n\telse:\n\t\techo \"Sequence \", digits, \" is invalid.\"\n\ncheckData(5724.toDigits)\ncheckData(5727.toDigits)\ncheckData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 1])\ncheckData([Digit 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6, 7, 8, 9, 0, 8])\n" + }, + { + "id": 1171, + "length": 1082, + "source": "Rosetta Code", + "text": "import algorithm, math, strutils\nimport bignum\n\ntype FaulhaberSequence = seq[Rat]\n\n\nfunc bernoulli(n: Natural): Rat =\n\t## Return nth Bernoulli coefficient.\n\n\tvar a = newSeq[Rat](n + 1)\n\tfor m in 0..n:\n\t\ta[m] = newRat(1, m + 1)\n\t\tfor k in countdown(m, 1):\n\t\t\ta[k - 1] = (a[k - 1] - a[k]) * k\n\tresult = if n != 1: a[0] else: -a[0]\n\n\nfunc faulhaber(n: Natural): FaulhaberSequence =\n\t## Return nth Faulhaber sequence (high degree first).\n\n\tvar a = newRat(1, n + 1)\n\tvar sign = -1\n\tfor k in 0..n:\n\t\tsign = -sign\n\t\tresult.add(a * sign * binom(n + 1, k) * bernoulli(k))\n\n\nproc display(fs: FaulhaberSequence) =\n\t## Return the string representing a Faulhaber sequence.\n\n\tvar str = \"\"\n\tfor i, coeff in reversed(fs):\n\t\tstr.addSep(\" \", 0)\n\t\tstr.add(($coeff).align(6))\n\techo str\n\n\nfunc evaluate(fs: FaulhaberSequence; n: int): Rat =\n\t## Evaluate the polynomial associated to a sequence for value \"n\".\n\n\tresult = newRat(0)\n\tfor coeff in fs:\n\t\tresult = result * n + coeff\n\tresult *= n\n\n\nfor n in 0..9:\n\tdisplay(faulhaber(n))\n\necho \"\"\nlet fs18 = faulhaber(17) # 18th row.\necho fs18.evaluate(1000)\n" + }, + { + "id": 1172, + "length": 897, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc egyptianDivision(dividend, divisor: int): tuple[quotient, remainder: int] =\n\tif dividend < 0 or divisor <= 0:\n\t\traise newException(IOError, \"Invalid argument(s)\")\n\tif dividend < divisor:\n\t\treturn (0, dividend)\n\n\tvar powersOfTwo: array[sizeof(int) * 8, int]\n\tvar doublings: array[sizeof(int) * 8, int]\n\n\tfor i, _ in powersOfTwo:\n\t\tpowersOfTwo[i] = 1 shl i\n\t\tdoublings[i] = divisor shl i\n\t\tif doublings[i] > dividend:\n\t\t\tbreak\n\n\tvar answer = 0\n\tvar accumulator = 0\n\tfor i in countdown(len(doublings) - 1, 0):\n\t\tif accumulator + doublings[i] <= dividend:\n\t\t\tinc accumulator, doublings[i]\n\t\t\tinc answer, powersOfTwo[i]\n\t\t\tif accumulator == dividend:\n\t\t\t\tbreak\n\t(answer, dividend - accumulator)\n\nlet dividend = 580\nlet divisor = 34\nvar (quotient, remainder) = egyptianDivision(dividend, divisor)\necho fmt\"{dividend} divided by {divisor} is {quotient} with remainder {remainder}\"\n" + }, + { + "id": 1173, + "length": 1073, + "source": "Rosetta Code", + "text": "import strutils\n\ntype State {.pure.} = enum Ready, Waiting, Exit, Dispense, Refunding\n\n\nproc getAnswer(message: string; answers: set[char]): char =\n\twhile true:\n\t\tstdout.write message, ' '\n\t\tstdout.flushFile\n\t\tresult = (stdin.readLine().toLowerAscii & ' ')[0]\n\t\tif result in answers: return\n\n\nproc fsm =\n\n\techo \"Please enter your option when prompted\"\n\techo \"(any characters after the first will be ignored)\"\n\tvar state = State.Ready\n\n\twhile true:\n\t\tcase state\n\n\t\tof State.Ready:\n\t\t\tlet trans = getAnswer(\"\\n(D)ispense or (Q)uit :\", {'d', 'q'})\n\t\t\tstate = if trans == 'd': State.Waiting else: State.Exit\n\n\t\tof State.Waiting:\n\t\t\techo \"OK, put your money in the slot\"\n\t\t\tlet trans = getAnswer(\"(S)elect product or choose a (R)efund :\", {'s', 'r'})\n\t\t\tstate = if trans == 's': State.Dispense else: State.Refunding\n\n\t\tof State.Dispense:\n\t\t\tdiscard getAnswer(\"(R)emove product :\", {'r'})\n\t\t\tstate = State.Ready\n\n\t\tof State.Refunding:\n\t\t\t# No transitions defined.\n\t\t\techo \"OK, refunding your money\"\n\t\t\tstate = State.Ready\n\n\t\tof State.Exit:\n\t\t\techo \"OK, quitting\"\n\t\t\tbreak\n\nfsm()\n" + }, + { + "id": 1174, + "length": 2724, + "source": "Rosetta Code", + "text": "import strutils, algorithm, tables\n\nconst irregularOrdinals = {\"one\": \"first\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"two\": \"second\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"three\": \"third\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"five\": \"fifth\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"eight\": \"eighth\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"nine\": \"ninth\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"twelve\": \"twelfth\"}.toTable\n\nconst\n\ttens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\",\n\t\t\t\t\t\"eighty\", \"ninety\"]\n\tsmall = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\",\n\t\t\t\t\t \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\t\t\t\t \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\thuge = [\"\", \"\", \"million\", \"billion\", \"trillion\", \"quadrillion\",\n\t\t\t\t\t\"quintillion\", \"sextillion\", \"septillion\", \"octillion\", \"nonillion\",\n\t\t\t\t\t\"decillion\"]\n\n# Forward reference.\nproc spellInteger(n: int64): string\n\nproc nonzero(c: string; n: int64; connect = \"\"): string =\n\tif n == 0: \"\" else: connect & c & spellInteger(n)\n\nproc lastAnd(num: string): string =\n\tif ',' in num:\n\t\tlet pos = num.rfind(',')\n\t\tvar (pre, last) = if pos >= 0: (num[0 ..< pos], num[pos+1 .. num.high])\n\t\t\t\t\t\t\t\t\t\t\telse: (\"\", num)\n\t\tif \" and \" notin last: last = \" and\" & last\n\t\tresult = [pre, \",\", last].join()\n\telse:\n\t\tresult = num\n\nproc big(e, n: int64): string =\n\tif e == 0:\n\t\tspellInteger(n)\n\telif e == 1:\n\t\tspellInteger(n) & \" thousand\"\n\telse:\n\t\tspellInteger(n) & \" \" & huge[e]\n\niterator base1000Rev(n: int64): int64 =\n\tvar n = n\n\twhile n != 0:\n\t\tlet r = n mod 1000\n\t\tn = n div 1000\n\t\tyield r\n\nproc spellInteger(n: int64): string =\n\tif n < 0:\n\t\t\"minus \" & spellInteger(-n)\n\telif n < 20:\n\t\tsmall[int(n)]\n\telif n < 100:\n\t\tlet a = n div 10\n\t\tlet b = n mod 10\n\t\ttens[int(a)] & nonzero(\"-\", b)\n\telif n < 1000:\n\t\tlet a = n div 100\n\t\tlet b = n mod 100\n\t\tsmall[int(a)] & \" hundred\" & nonzero(\" \", b, \" and\")\n\telse:\n\t\tvar sq = newSeq[string]()\n\t\tvar e = 0\n\t\tfor x in base1000Rev(n):\n\t\t\tif x > 0: sq.add big(e, x)\n\t\t\tinc e\n\t\treverse sq\n\t\tlastAnd(sq.join(\", \"))\n\nproc num2ordinal(n: SomeInteger|SomeFloat): string =\n\n\tlet n = n.int64\n\n\tvar num = spellInteger(n)\n\tlet hyphen = num.rsplit('-', 1)\n\tvar number = num.rsplit(' ', 1)\n\tvar delim = ' '\n\tif number[^1].len > hyphen[^1].len:\n\t\tnumber = hyphen\n\t\tdelim = '-'\n\n\tif number[^1] in irregularOrdinals:\n\t\tnumber[^1] = delim & irregularOrdinals[number[^1]]\n\telif number[^1].endswith('y'):\n\t\tnumber[^1] = delim & number[^1][0..^2] & \"ieth\"\n\telse:\n\t\tnumber[^1] = delim & number[^1] & \"th\"\n\n\tresult = number.join()\n\n\nwhen isMainModule:\n\n\tconst\n\t\ttests1 = [int64 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123]\n\t\ttests2 = [0123.0, 1.23e2]\n\n\tfor num in tests1:\n\t\techo \"$1 => $2\".format(num, num2ordinal(num))\n\tfor num in tests2:\n\t\techo \"$1 => $2\".format(num, num2ordinal(num))\n" + }, + { + "id": 1175, + "length": 3889, + "source": "Rosetta Code", + "text": "import strutils, strformat, tables\n\n# Cardinal and ordinal strings.\n\nconst\n\n\tSmall = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n\t\t\t\t\t \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n\t\t\t\t\t \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\t\t\t\t \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\n\tTens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n\n\tIllions = [\"\", \" thousand\", \" million\", \" billion\", \" trillion\", \" quadrillion\", \" quintillion\"]\n\n\tIrregularOrdinals = {\"one\": \"first\", \"two\": \"second\", \"three\": \"third\", \"five\": \"fifth\",\n\t\t\t\t\t\t\t\t\t\t\t \"eight\": \"eighth\", \"nine\": \"ninth\", \"twelve\": \"twelfth\"}.toTable()\n\n\nfunc spellCardinal(n: int64): string =\n\t## Spell an integer as a cardinal.\n\n\tvar n = n\n\n\tif n < 0:\n\t\tresult = \"negative \"\n\t\tn = -n\n\n\tif n < 20:\n\t\tresult &= Small[n]\n\n\telif n < 100:\n\t\tresult &= Tens[n div 10]\n\t\tlet m = n mod 10\n\t\tif m != 0: result &= '-' & Small[m]\n\n\telif n < 1000:\n\t\tresult &= Small[n div 100] & \" hundred\"\n\t\tlet m = n mod 100\n\t\tif m != 0: result &= ' ' & m.spellCardinal()\n\n\telse:\n\t\t# Work from right to left.\n\t\tvar sx = \"\"\n\t\tvar i = 0\n\t\twhile n > 0:\n\t\t\tlet m = n mod 1000\n\t\t\tn = n div 1000\n\t\t\tif m != 0:\n\t\t\t\tvar ix = m.spellCardinal() & Illions[i]\n\t\t\t\tif sx.len > 0: ix &= \" \" & sx\n\t\t\t\tsx = ix\n\t\t\tinc i\n\t\tresult &= sx\n\n\nfunc spellOrdinal(n: int64): string =\n\t## Spell an integer as an ordinal.\n\n\tresult = n.spellCardinal()\n\tvar parts = result.rsplit({' ', '-'}, maxsplit = 1)\n\tlet tail = parts[^1]\n\tif tail in IrregularOrdinals:\n\t\tresult[^tail.len..^1] = IrregularOrdinals[tail]\n\telif tail.endsWith('y'):\n\t\tresult[^1..^1]= \"ieth\"\n\telse:\n\t\tresult &= \"th\"\n\n\n# Sentence building.\n\ntype Sentence = seq[string]\n\n\niterator words(sentence: var Sentence): tuple[idx: int; word: string] =\n\t## Yield the successive words of the sentence with their index.\n\n\tyield (0, \"Four\")\n\tvar idx = 1\n\tvar last = 0\n\twhile true:\n\t\tyield (idx, sentence[idx])\n\t\tinc idx\n\t\tif idx == sentence.len:\n\t\t\tinc last\n\t\t\tsentence.add([sentence[last].count(Letters).spellCardinal(), \"in\", \"the\"])\n\t\t\t# For the position, we need to split the ordinal as it may contain spaces.\n\t\t\tsentence.add(((last + 1).spellOrdinal() & ',').splitWhitespace())\n\n\niterator letterCounts(sentence: var Sentence): tuple[idx: int; word: string; count: int] =\n\t## Secondary iterator used to yield the number of letters in addition to the index and the word.\n\n\tfor i, word in sentence.words():\n\t\tyield (i, word, word.count(Letters))\n\n\n# Drivers.\n\n# Constant to initialize the sentence.\nconst Init = \"Four is the number of letters in the first word of this sentence,\".splitWhitespace()\n\n\nproc displayLetterCounts(pos: Positive) =\n\t## Display the number of letters of the word at position \"pos\".\n\n\tvar sentence = Init\n\techo fmt\"Number of letters in first {pos} words in the sequence:\"\n\tvar valcount = 0 # Number of values displayed in the current line.\n\tvar length = 0\n\n\tfor i, word, letterCount in sentence.letterCounts():\n\t\tif i == pos:\n\t\t\t# Terminated.\n\t\t\tdec length # Adjust space count.\n\t\t\techo \"\"\n\t\t\tbreak\n\n\t\tif valcount == 0: stdout.write fmt\"{i+1:>3}:\"\n\t\tstdout.write fmt\"{letterCount:>3}\"\n\t\tinc valcount\n\t\tinc length, word.len + 1 # +1 for space.\n\n\t\tif valcount == 12:\n\t\t\t# Terminate line.\n\t\t\techo \"\"\n\t\t\tvalcount = 0\n\n\techo fmt\"Length of sentence: {length}\"\n\n\nproc displayWord(pos: Positive) =\n\t## Display the word at position \"pos\".\n\n\tvar sentence = Init\n\tlet idx = pos - 1\n\tvar length = 0\n\tfor i, word in sentence.words():\n\t\tlength += word.len + 1\n\t\tif i == idx:\n\t\t\tdec length # Adjust space count.\n\t\t\tlet w = word.strip(leading = false, chars = {','}) # Remove trailing ',' if needed.\n\t\t\techo fmt\"Word {pos} is \"\"{w}\"\" with {w.count(Letters)} letters.\"\n\t\t\techo fmt\"Length of sentence: {length}\"\n\t\t\tbreak\n\n\ndisplayLetterCounts(201)\nfor n in [1_000, 10_000, 100_000, 1_000_000, 10_000_000]:\n\techo \"\"\n\tdisplayWord(n)\n" + }, + { + "id": 1176, + "length": 2463, + "source": "Rosetta Code", + "text": "import parseutils\nimport strutils\nimport tables\n\nconst Commands =\n\t\"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \" &\n\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \" &\n\t\"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" &\n\t\"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \" &\n\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \" &\n\t\"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \" &\n\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" &\n\t\"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\"\n\n\nproc abbrevationLengths(commands: string): Table[string, int] =\n\t## Find the minimal abbreviation length for each word.\n\t## A word that does not have minimum abbreviation length specified\n\t## gets it's full length as the minimum.\n\n\tvar word = \"\"\n\tfor item in commands.splitWhitespace():\n\t\tvar n: int\n\t\tif item.parseInt(n) == 0:\n\t\t\t# Not a number.\n\t\t\tif word.len != 0:\n\t\t\t\t# No minimal length specified for the word.\n\t\t\t\tresult[word] = word.len\n\t\t\tword = item\n\t\telse:\n\t\t\t# Got an integer.\n\t\t\tif word.len == 0:\n\t\t\t\traise newException(ValueError, \"Invalid position for number: \" & $n)\n\t\t\tresult[word] = n\n\t\t\tword = \"\"\n\n\nproc abbreviations(commandTable: Table[string, int]): Table[string, string] =\n\t## For each command insert all possible abbreviations.\n\tfor command, minlength in commandTable.pairs:\n\t\tfor length in minLength..command.len:\n\t\t\tlet abbr = command[0.. 0:\n\n\t\t# Extract the day names and store them in a sorted list of sequences of runes.\n\t\tvar days: seq[Runes]\n\t\tfor day in line.splitWhitespace():\n\t\t\tdays.add(day.toLower.toRunes)\n\t\tif days.len != 7:\n\t\t\techo \"Wrong number of days at line \", linenum\n\n\t\t# Build the abbreviations and store them in a set.\n\t\tvar index = 0\n\t\twhile true:\n\t\t\tvar abbrevs: HashSet[seq[Rune]]\n\t\t\tfor day in days:\n\t\t\t\tabbrevs.incl(day[0..min(index, day.high)])\n\t\t\tif abbrevs.card == 7:\n\t\t\t\t# All abbreviations are different: fine!\n\t\t\t\tbreak\n\t\t\tinc index\n\t\techo index + 1, \" \", line\n\n\telse:\n\t\techo line\n" + }, + { + "id": 1179, + "length": 872, + "source": "Rosetta Code", + "text": "import algorithm\nimport unicode\n\ntype Runes = seq[Rune]\n\nvar linenum = 0\nfor line in lines(\"days.txt\"):\n\tinc linenum\n\tif line.len > 0:\n\n\t\t# Extract the day names and store them in a sorted list of sequences of runes.\n\t\tvar days: seq[Runes]\n\t\tfor day in sorted(line.toLower.splitWhitespace()):\n\t\t\tdays.add(day.toRunes)\n\t\tif days.len != 7:\n\t\t\techo \"Wrong number of days at line \", linenum\n\n\t\t# Compare the first letters of successive day names, incrementing the upper index if necessary.\n\t\tvar index = 0 # Equal to abbreviation length - 1.\n\t\tvar prevday = days[0]\n\t\tfor idx in 1..days.high:\n\t\t\tlet currday = days[idx]\n\t\t\tif currday == prevday:\n\t\t\t\techo \"Double encountered at line \", linenum\n\t\t\twhile currday[0..min(index, currday.high)] == prevday[0..min(index, prevday.high)]:\n\t\t\t\tinc index\n\t\t\tprevday = currday\n\t\techo index + 1, \" \", line\n\n\telse:\n\t\techo line\n" + }, + { + "id": 1180, + "length": 1340, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\n\tSmall = [\"zero\", \"one\", \"two\", \"three\", \"four\",\n\t\t\t\t\t \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n\t\t\t\t\t \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n\t\t\t\t\t \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\n\tTens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n\n\tIllions = [\"\", \" thousand\", \" million\", \" billion\", \" trillion\", \" quadrillion\", \" quintillion\"]\n\n\nfunc say(n: int64): string =\n\n\tvar n = n\n\n\tif n < 0:\n\t\tresult = \"negative \"\n\t\tn = -n\n\n\tif n < 20:\n\t\tresult &= Small[n]\n\n\telif n < 100:\n\t\tresult &= Tens[n div 10]\n\t\tlet m = n mod 10\n\t\tif m != 0: result &= '-' & Small[m]\n\n\telif n < 1000:\n\t\tresult &= Small[n div 100] & \" hundred\"\n\t\tlet m = n mod 100\n\t\tif m != 0: result &= ' ' & m.say()\n\n\telse:\n\t\t# Work from right to left.\n\t\tvar sx = \"\"\n\t\tvar i = 0\n\t\twhile n > 0:\n\t\t\tlet m = n mod 1000\n\t\t\tn = n div 1000\n\t\t\tif m != 0:\n\t\t\t\tvar ix = m.say() & Illions[i]\n\t\t\t\tif sx.len > 0: ix &= \" \" & sx\n\t\t\t\tsx = ix\n\t\t\tinc i\n\t\tresult &= sx\n\n\nfunc fourIsMagic(n: int64): string =\n\tvar n = n\n\tvar s = n.say().capitalizeAscii()\n\tresult = s\n\twhile n != 4:\n\t\tn = s.len.int64\n\t\ts = n.say()\n\t\tresult &= \" is \" & s & \", \" & s\n\tresult &= \" is magic.\"\n\n\n\nfor n in [int64 0, 4, 6, 11, 13, 75, 100, 337, -164, int64.high]:\n\techo fourIsMagic(n)\n" + }, + { + "id": 1181, + "length": 4310, + "source": "Rosetta Code", + "text": "import algorithm, math, sequtils, strformat, strutils, sugar\n\ntype\n\n\tCorrectionType {.pure.} = enum\n\t\tBenjaminiHochberg = \"Benjamini-Hochberg\"\n\t\tBenjaminiYekutieli = \"Benjamini-Yekutieli\"\n\t\tBonferroni = \"Bonferroni\"\n\t\tHochberg = \"Hochberg\"\n\t\tHolm = \"Holm\"\n\t\tHommel = \"Hommel\"\n\t\tSidak = \"Sidak\"\n\n\tDirection {.pure.} = enum Up, Down\n\n\tPValues = seq[float]\n\n\ntemplate newPValues(length: Natural): PValues =\n\t## Create a PValues object of given length.\n\tnewSeq[float](length)\n\n\nfunc ratchet(p: var PValues; dir: Direction) =\n\tvar m = p[0]\n\tcase dir\n\tof Up:\n\t\tfor i in 1..p.high:\n\t\t\tif p[i] > m: p[i] = m\n\t\t\tm = p[i]\n\tof Down:\n\t\tfor i in 1..p.high:\n\t\t\tif p[i] < m: p[i] = m\n\t\t\tm = p[i]\n\tfor i in 0..p.high:\n\t\tif p[i] > 1: p[i] = 1\n\n\nfunc schwartzian(p, mult: PValues; dir: Direction): PValues =\n\n\tlet length = p.len\n\tlet sortOrder = if dir == Up: Descending else: Ascending\n\tlet order1 = toSeq(p.pairs).sorted((x, y) => cmp(x.val, y.val), sortOrder).mapIt(it.key)\n\n\tvar pa = newPValues(length)\n\tfor i in 0..pa.high:\n\t\tpa[i] = mult[i] * p[order1[i]]\n\n\tratchet(pa, dir)\n\n\tlet order2 = toSeq(order1.pairs).sortedByIt(it.val).mapIt(it.key)\n\tfor idx in order2:\n\t\tresult.add pa[idx]\n\n\nproc adjust(p: PValues; ctype: CorrectionType): PValues =\n\tlet length = p.len\n\tassert length > 0\n\tlet flength = length.toFloat\n\n\tcase ctype\n\n\tof BenjaminiHochberg:\n\t\tvar mult = newPValues(length)\n\t\tfor i in 0..mult.high:\n\t\t\tmult[i] = flength / (flength - i.toFloat)\n\t\treturn schwartzian(p, mult, Up)\n\n\tof BenjaminiYekutieli:\n\t\tvar q = 0.0\n\t\tfor i in 1..length: q += 1 / i\n\t\tvar mult = newPValues(length)\n\t\tfor i in 0..mult.high:\n\t\t\tmult[i] = (q * flength) / (flength - i.toFloat)\n\t\treturn schwartzian(p, mult, Up)\n\n\tof Bonferroni:\n\t\tresult = newPValues(length)\n\t\tfor i in 0..result.high:\n\t\t\tresult[i] = min(p[i] * flength, 1)\n\t\treturn\n\n\tof Hochberg:\n\t\tvar mult = newPValues(length)\n\t\tfor i in 0..mult.high:\n\t\t\tmult[i] = i.toFloat + 1\n\t\treturn schwartzian(p, mult, Up)\n\n\tof Holm:\n\t\tvar mult = newPValues(length)\n\t\tfor i in 0..mult.high:\n\t\t\tmult[i] = flength - i.toFloat\n\t\treturn schwartzian(p, mult, Down)\n\n\tof Hommel:\n\t\tlet order1 = toSeq(p.pairs).sortedByIt(it.val).mapIt(it.key)\n\t\tlet s = order1.mapIt(p[it])\n\t\tvar m = Inf\n\t\tfor i in 0..s.high:\n\t\t\tm = min(m, s[i] * flength / (i + 1).toFloat)\n\t\tvar q, pa = repeat(m, length)\n\n\t\tfor j in countdown(length - 1, 2):\n\t\t\tlet lower = toSeq(0..length - j)\n\t\t\tlet upper = toSeq((length - j + 1).. 0 and min(p) >= 0 and max(p) <= 1, \"p-values must be in range 0.0 to 1.0.\"\n\tresult = \"\\n{ctype}\\n{pformat(p.adjust(ctype))}\"\n\nwhen isMainModule:\n\n\tconst PVals = @[\n\t\t\t\t4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,\n\t\t\t\t8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,\n\t\t\t\t4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,\n\t\t\t\t8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,\n\t\t\t\t3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,\n\t\t\t\t1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,\n\t\t\t\t4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,\n\t\t\t\t3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,\n\t\t\t\t1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,\n\t\t\t\t2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03]\n\n\tfor ctype in CorrectionType:\n\t\techo adjusted(PVals, ctype)\n" + }, + { + "id": 1182, + "length": 1119, + "source": "Rosetta Code", + "text": "import algorithm\n\ntype FiveNum = array[5, float]\n\ntemplate isOdd(n: SomeInteger): bool = (n and 1) != 0\n\nfunc median(x: openArray[float]; startIndex, endIndex: Natural): float =\n\tlet size = endIndex - startIndex + 1\n\tassert(size > 0, \"array slice cannot be empty\")\n\tlet m = startIndex + size div 2\n\tresult = if size.isOdd: x[m] else: (x[m-1] + x[m]) / 2\n\nfunc fivenum(x: openArray[float]): FiveNum =\n\tlet x = sorted(x)\n\tlet m = x.len div 2\n\tlet lowerEnd = if x.len.isOdd: m else: m - 1\n\tresult[0] = x[0]\n\tresult[1] = median(x, 0, lowerEnd)\n\tresult[2] = median(x, 0, x.high)\n\tresult[3] = median(x, m, x.high)\n\tresult[4] = x[^1]\n\nconst Lists = [@[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0],\n\t\t\t\t\t\t\t @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0],\n\t\t\t\t\t\t\t @[0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n\t\t\t\t\t\t\t\t 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n\t\t\t\t\t\t\t\t 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n\t\t\t\t\t\t\t\t 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]]\n\nfor list in Lists:\n\techo \"\"\n\techo list\n\techo \" -> \", list.fivenum\n" + }, + { + "id": 1183, + "length": 2192, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nconst Eps = 1e-10\n\ntype\n\tMatrix[M, N: static Positive] = array[M, array[N, float]]\n\tSquareMatrix[N: static Positive] = Matrix[N, N]\n\n\nfunc toSquareMatrix[N: static Positive](a: array[N, array[N, int]]): SquareMatrix[N] =\n\t## Convert a square matrix of integers to a square matrix of floats.\n\n\tfor i in 0..= mat.N: return\n\n\t\tvar i = r\n\t\twhile mat[i][lead] == 0:\n\t\t\tinc i\n\t\t\tif i == mat.M:\n\t\t\t\ti = r\n\t\t\t\tinc lead\n\t\t\t\tif lead == mat.N: return\n\t\tswap mat[i], mat[r]\n\n\t\tlet d = mat[r][lead]\n\t\tif abs(d) > Eps: # Checking \"d != 0\" will give wrong results in some cases.\n\t\t\tfor item in mat[r].mitems:\n\t\t\t\titem /= d\n\n\t\tfor i in 0.. float\n\tFuncs = seq[Func]\n\tJacobian = seq[Funcs]\n\n\nfunc `*`(m1, m2: Matrix): Matrix =\n\tlet\n\t\trows1 = m1.len\n\t\tcols1 = m1[0].len\n\t\trows2 = m2.len\n\t\tcols2 = m2[0].len\n\tdoAssert cols1 == rows2\n\tresult = newSeqWith(rows1, newSeq[float](cols2))\n\tfor i in 0.. MaxIter: break\n\t\tvar exit = true\n\t\tfor idx, val in result:\n\t\t\tif abs(val - gu[idx]) > Tol:\n\t\t\t\texit = false\n\t\t\t\tbreak\n\t\tif exit: break\n\n\nwhen isMainModule:\n\n\t#[ Solve the two non-linear equations:\n\t\t y = -x^2 + x + 0.5\n\t\t y + 5xy = x^2\n\t\t given initial guesses of x = y = 1.2\n\n\t\t Example taken from:\n\t\t http://www.fixoncloud.com/Home/LoginValidate/OneProblemComplete_Detailed.php?problemid=286\n\n\t\t Expected results: x = 1.23332, y = 0.2122\n\t]#\n\n\tlet\n\t\tf1: Func = (x: Vector) => -x[0] * x[0] + x[0] + 0.5 - x[1]\n\t\tf2: Func = (x: Vector) => x[1] + 5 * x[0] * x[1] - x[0] * x[0]\n\t\tfuncs1: Funcs = @[f1, f2]\n\t\tjacobian1: Jacobian = @[@[Func((x: Vector) => - 2 * x[0] + 1),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => -1.0)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t@[Func((x: Vector) => 5 * x[1] - 2 * x[0]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => 1 + 5 * x[0])]]\n\n\t\tguesses1 = @[1.2, 1.2]\n\t\tsol1 = solve(funcs1, jacobian1, guesses1)\n\techo \"Approximate solutions are x = {sol1[0]:.7f}, y = {sol1[1]:.7f}\"\n\n\t#[ Solve the three non-linear equations:\n\t\t 9x^2 + 36y^2 + 4z^2 - 36 = 0\n\t\t x^2 - 2y^2 - 20z = 0\n\t\t x^2 - y^2 + z^2 = 0\n\t\t given initial guesses of x = y = 1.0 and z = 0.0\n\n\t\t Example taken from:\n\t\t http://mathfaculty.fullerton.edu/mathews/n2003/FixPointNewtonMod.html (exercise 5)\n\n\t\t Expected results: x = 0.893628, y = 0.894527, z = -0.0400893\n\t]#\n\n\techo()\n\tlet\n\t\tf3: Func = (x: Vector) => 9 * x[0] * x[0] + 36 * x[1] * x[1] + 4 * x[2] * x[2] - 36\n\t\tf4: Func = (x: Vector) => x[0] * x[0] - 2 * x[1] * x[1] - 20 * x[2]\n\t\tf5: Func = (x: Vector) => x[0] * x[0] - x[1] * x[1] + x[2] * x[2]\n\t\tfuncs2: Funcs = @[f3, f4, f5]\n\t\tjacobian2: Jacobian = @[@[Func((x: Vector) => 18 * x[0]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => 72 * x[1]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => 8 * x[2])],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t@[Func((x: Vector) => 2 * x[0]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => -4 * x[1]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => -20.0)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t@[Func((x: Vector) => 2 * x[0]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => -2 * x[1]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFunc((x: Vector) => 2 * x[2])]]\n\t\tguesses2 = @[1.0, 1.0, 0.0]\n\t\tsol2 = solve(funcs2, jacobian2, guesses2)\n\techo \"Approximate solutions are x = {sol2[0]:.7f}, y = {sol2[1]:.7f}, z = {sol2[2]:.7f}\"\n" + }, + { + "id": 1185, + "length": 835, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\tStdFmt = \"$1, $1, bo-b$2\\nBanana-fana fo-f$2\\nFee-fi-mo-m$2\\n$1!\"\n\tWovelFmt = \"$1, $1, bo-b$2\\nBanana-fana fo-f$2\\nFee-fi-mo-m$2\\n$1!\"\n\tBFmt = \"$1, $1, bo-$2\\nBanana-fana fo-f$2\\nFee-fi-mo-m$2\\n$1!\"\n\tFFmt = \"$1, $1, bo-b$2\\nBanana-fana fo-$2\\nFee-fi-mo-m$2\\n$1!\"\n\tMFmt = \"$1, $1, bo-b$2\\nBanana-fana fo-f$2\\nFee-fi-mo-$2\\n$1!\"\n\nproc lyrics(name: string): string =\n\tlet tail = name[1..^1]\n\tresult = case name[0].toUpperAscii\n\t\t\t\t\t of 'A', 'E', 'I', 'O', 'U', 'Y':\n\t\t\t\t\t\t WovelFmt.format(name, name.toLowerAscii)\n\t\t\t\t\t of 'B':\n\t\t\t\t\t\t BFmt.format(name, tail)\n\t\t\t\t\t of 'F':\n\t\t\t\t\t\t FFmt.format(name, tail)\n\t\t\t\t\t of 'M':\n\t\t\t\t\t\t MFmt.format(name, tail)\n\t\t\t\t\t else:\n\t\t\t\t\t\t StdFmt.format(name, tail)\n\tresult = result.capitalizeAscii()\n\nfor name in [\"Gary\", \"Earl\", \"Billy\", \"Felix\", \"Mary\"]:\n\techo name.lyrics()\n\techo()\n" + }, + { + "id": 1186, + "length": 1429, + "source": "Rosetta Code", + "text": "import sequtils\n\ntype Optimizer = object\n\tdims: seq[int]\n\tm: seq[seq[Natural]]\n\ts: seq[seq[Natural]]\n\n\nproc initOptimizer(dims: openArray[int]): Optimizer =\n\t## Create an optimizer for the given dimensions.\n\tOptimizer(dims: @dims)\n\nproc findMatrixChainOrder(opt: var Optimizer) =\n\t## Find the best order for matrix chain multiplication.\n\n\tlet n = opt.dims.high\n\topt.m = newSeqWith(n, newSeq[Natural](n))\n\topt.s = newSeqWith(n, newSeq[Natural](n))\n\n\tfor lg in 1.. 0:\n\t\timg.kochCurve(x1, y1, x3, y3, iter - 1)\n\t\timg.kochCurve(x3, y3, x5, y5, iter - 1)\n\t\timg.kochCurve(x5, y5, x4, y4, iter - 1)\n\t\timg.kochCurve(x4, y4, x2, y2, iter - 1)\n\telse:\n\t\timg.drawLine(startPoint=[x1.int, y1.int], endPoint=[x3.int, y3.int])\n\t\timg.drawLine(startPoint=[x3.int, y3.int], endPoint=[x5.int, y5.int])\n\t\timg.drawLine(startPoint=[x5.int, y5.int], endPoint=[x4.int, y4.int])\n\t\timg.drawLine(startPoint=[x4.int, y4.int], endPoint=[x2.int, y2.int])\n\nproc main() =\n\n\twithGd imageCreate(width, height) as img:\n\t\tlet white = img.backgroundColor(0xffffff)\n\t\tlet red = img.foregroundColor(0xff0000)\n\n\t\timg.kochCurve(100, 100, 400, 400, iterations)\n\n\t\tlet png_out = open(\"koch_curve.png\", fmWrite)\n\t\timg.writePng(png_out)\n\t\tpng_out.close()\n\nmain()\n" + }, + { + "id": 1188, + "length": 4819, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\nimport gintro/[glib, gobject, gtk, gio]\n\nconst\n\n\tBoardSize = 4\n\tGridSize = BoardSize + 2\n\tClock = \"\\u27f2\"\n\tAClock = \"\\u27f3\"\n\ntype\n\n\tValue = 1..16\n\tPuzzle = array[BoardSize, array[BoardSize, Value]]\n\n\tPuzzleApp = ref object of Application\n\t\tinOrder: Puzzle # Target grid.\n\t\tpuzzle: Puzzle # Current grid.\n\t\tbuttons: array[GridSize, array[GridSize, Button]] # Button grid.\n\t\twon: bool # True if game won.\n\t\tmoves: Natural # Count of moves.\n\n\nproc initPuzzle(puzzle: var Puzzle; data: openArray[Value]) =\n\t## Initialize the puzzle with a list of values.\n\tvar i = 0\n\tfor row in puzzle.mitems:\n\t\tfor cell in row.mitems:\n\t\t\tcell = data[i]\n\t\t\tinc i\n\n\nproc showMessage(app: PuzzleApp) =\n\t## As \"gintro\" doesn't provide \"MessageDialog\" yet, we will use a simple dialog.\n\tlet dialog = newDialog()\n\tdialog.setModal(true)\n\tlet label = newLabel(\"You won in $# move(s)\".format(app.moves))\n\tdialog.contentArea.add(label)\n\tdiscard dialog.addButton(\"Ok\", ord(ResponseType.ok))\n\tdialog.showAll()\n\tdiscard dialog.run()\n\tdialog.destroy()\n\n\nproc onQuit(button: ToolButton; window: ApplicationWindow) =\n\t## Procedure called when clicking quit button.\n\twindow.destroy()\n\n\nproc rotateRow(puzzle: var Puzzle; row: Natural; left: bool) =\n\t## Rotate a row left or right.\n\tif left:\n\t\tlet first = puzzle[row][0]\n\t\tfor i in 1..puzzle.high: puzzle[row][i-1] = puzzle[row][i]\n\t\tpuzzle[row][^1] = first\n\telse:\n\t\tlet last = puzzle[row][^1]\n\t\tfor i in countdown(puzzle.high, 1): puzzle[row][i] = puzzle[row][i-1]\n\t\tpuzzle[row][0] = last\n\n\nproc rotateCol(puzzle: var Puzzle; col: Natural; up: bool) =\n\t## Rotate a column up or down.\n\tif up:\n\t\tlet first = puzzle[0][col]\n\t\tfor i in 1..puzzle.high: puzzle[i-1][col] = puzzle[i][col]\n\t\tpuzzle[^1][col] = first\n\telse:\n\t\tlet last = puzzle[^1][col]\n\t\tfor i in countdown(puzzle[0].high, 1): puzzle[i][col] =puzzle[i-1][col]\n\t\tpuzzle[0][col] = last\n\n\nproc findRowCol(app: PuzzleApp; button: Button): (int, int) =\n\t## Find the row and column of a button.\n\tfor i in [0, BoardSize+1]:\n\t\tfor j in 1..Boardsize:\n\t\t\tif app.buttons[i][j] == button: return (i, j)\n\tfor j in [0, BoardSize+1]:\n\t\tfor i in 1..Boardsize:\n\t\t\tif app.buttons[i][j] == button: return (i, j)\n\n\nproc update(app: PuzzleApp) =\n\t## Update the grid.\n\tfor i in 0..BoardSize+1:\n\t\tfor j in 0..BoardSize+1:\n\t\t\tif j in 1..BoardSize:\n\t\t\t\tif i == 0:\n\t\t\t\t\tapp.buttons[i][j].setLabel(Clock)\n\t\t\t\telif i == BoardSize + 1:\n\t\t\t\t\tapp.buttons[i][j].setLabel(AClock)\n\t\t\t\telse:\n\t\t\t\t\tapp.buttons[i][j].setLabel($app.puzzle[i-1][j-1])\n\t\t\telif i in 1..BoardSize:\n\t\t\t\tif j == 0:\n\t\t\t\t\tapp.buttons[i][j].setLabel(Clock)\n\t\t\t\telif j == BoardSize + 1:\n\t\t\t\t\tapp.buttons[i][j].setLabel(AClock)\n\n\tif app.puzzle == app.inOrder:\n\t\tapp.won = true\n\t\tapp.showMessage()\n\n\nproc onClick(button: Button; app: PuzzleApp) =\n\t## Procedure called when the user cliked a grid button.\n\tif not app.won:\n\t\tinc app.moves\n\t\tlet (i, j) = app.findRowCol(button)\n\t\tif i == 0:\n\t\t\tapp.puzzle.rotateCol(j - 1, true)\n\t\telif i == BoardSize + 1:\n\t\t\tapp.puzzle.rotateCol(j - 1, false)\n\t\telif j == 0:\n\t\t\tapp.puzzle.rotateRow(i - 1, true)\n\t\telif j == BoardSize + 1:\n\t\t\tapp.puzzle.rotateRow(i - 1, false)\n\t\tapp.update()\n\n\nproc newGame(button: ToolButton; app: PuzzleApp) =\n\t## Prepare a new game.\n\tvar values = toSeq(Value.low..Value.high)\n\tvalues.shuffle()\n\tapp.puzzle.initPuzzle(values)\n\tapp.won = false\n\tapp.update()\n\n\nproc activate(app: PuzzleApp) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setTitle(\"16 puzzle game\")\n\twindow.setSizeRequest(300, 340)\n\n\tlet box = newBox(Orientation.vertical, 0)\n\twindow.add box\n\n\tlet toolbar = newToolbar()\n\tlet newGameButton = newToolButton(label = \"New game\")\n\ttoolbar.insert(newGameButton, 0)\n\tlet quitButton = newToolButton(label = \"Quit\")\n\ttoolbar.insert(quitButton, 1)\n\tbox.add toolbar\n\n\tlet grid = newGrid()\n\tbox.add grid\n\n\tfor i in 0..BoardSize+1:\n\t\tfor j in 0..BoardSize+1:\n\t\t\tlet button = newButton()\n\t\t\tbutton.setHexpand(true)\n\t\t\tbutton.setVexpand(true)\n\t\t\tapp.buttons[i][j] = button\n\t\t\tgrid.attach(button, j, i, 1, 1)\n\n\tvar values = toSeq(Value.low..Value.high)\n\tapp.inOrder.initPuzzle(values)\n\tvalues.shuffle()\n\tapp.puzzle.initPuzzle(values)\n\n\tfor i in [0, BoardSize + 1]:\n\t\tfor j in 1..BoardSize:\n\t\t\tapp.buttons[i][j].connect(\"clicked\", onClick, app)\n\tfor j in [0, BoardSize + 1]:\n\t\tfor i in 1..BoardSize:\n\t\t\tapp.buttons[i][j].connect(\"clicked\", onClick, app)\n\n\tnewGameButton.connect(\"clicked\", newGame, app)\n\tquitButton.connect(\"clicked\", onQuit, window)\n\n\tapp.won = false\n\tapp.update()\n\n\twindow.showAll()\n\n\nrandomize()\nlet app = newApplication(PuzzleApp, \"Puzzle16Game\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 1189, + "length": 2500, + "source": "Rosetta Code", + "text": "import math, random, sequtils, strformat, strutils, terminal\n\nconst Test = true\n\nproc getNumber(prompt: string; min, max: int; showMinMax: bool): int =\n\twhile true:\n\t\tstdout.write prompt\n\t\tstdout.write if showMinMax: \" from {min} to {max}: \" else: \": \"\n\t\tstdout.flushFile()\n\t\ttry:\n\t\t\tresult = stdin.readLine().parseInt()\n\t\texcept ValueError:\n\t\t\techo \"Wrong input\"\n\t\t\tcontinue\n\t\texcept EOFError:\n\t\t\tquit \"\\nEnd of file encountered. Quitting\", QuitFailure\n\t\tif result in min..max: break\n\t\techo \"Value out of range\"\n\techo()\n\n\nproc play() =\n\tlet\n\t\tplayers = getNumber(\"Number of players\", 2, 9, true)\n\t\tcoins = getNumber(\"Number of coins per player\", 3, 6, true)\n\tvar\n\t\tremaining = toSeq(1..players)\n\t\tfirst = rand(1..players)\n\t\tround = 1\n\n\techo \"The number of coins in your hand will be randomly determined for\"\n\techo \"each round and displayed to you. However, when you press ENTER\"\n\techo \"it will be erased so that the other players, who should look\"\n\techo \"away until it's their turn, won't see it. When asked to guess\"\n\techo \"the total, the computer won't allow a 'bum guess'.\"\n\n\twhile true:\n\t\techo \"\\nROUND {round:}\\n\"\n\t\tvar\n\t\t\tn = first\n\t\t\thands = newSeq[int](players + 1)\n\t\t\tguesses = repeat(- 1, players + 1)\n\t\twhile true:\n\t\t\techo \" PLAYER {n}:\"\n\t\t\techo \" Please come to the computer and press ENTER\"\n\t\t\thands[n] = rand(coins)\n\t\t\tlet plural = if hands[n] > 1: \"s\" else: \"\"\n\t\t\tstdout.write \" \"\n\t\t\tdiscard stdin.readLine()\n\t\t\tif not Test:\n\t\t\t\tcursorUp()\n\t\t\t\teraseLine()\n\t\t\t\tstdout.write '\\r'\n\t\t\telse:\n\t\t\t\techo()\n\t\t\twhile true:\n\t\t\t\tlet min = hands[n]\n\t\t\t\tlet max = remaining.high * coins + hands[n]\n\t\t\t\tlet guess = getNumber(\" Guess the total\", min, max, false)\n\t\t\t\tif guess notin guesses:\n\t\t\t\t\t\tguesses[n] = guess\n\t\t\t\t\t\tbreak\n\t\t\t\techo \" Already guessed by another player, try again\"\n\t\t\tlet index = remaining.find(n)\n\t\t\tn = remaining[(index + 1) mod remaining.len]\n\t\t\tif n == first: break\n\n\t\tlet total = sum(hands)\n\t\techo \" Total coins held = \", total\n\t\tvar eliminated = false\n\t\tfor i, n in remaining:\n\t\t\tif guesses[n] == total:\n\t\t\t\techo \" PLAYER {n} guessed correctly and is eliminated\"\n\t\t\t\tremaining.delete(i)\n\t\t\t\teliminated = true\n\t\t\t\tbreak\n\n\t\tif not eliminated:\n\t\t\techo \" No player guessed correctly in this round\"\n\t\telse:\n\t\t\tif remaining.len == 1:\n\t\t\t\techo \"\\nPLAYER {remaining[0]} buys the drinks!\"\n\t\t\t\treturn\n\n\t\tlet index = remaining.find(n)\n\t\tfirst = remaining[(index + 1) mod remaining.len]\n\t\tinc round\n\n\nrandomize()\nplay()\n" + }, + { + "id": 1190, + "length": 786, + "source": "Rosetta Code", + "text": "import random, strutils\n\nconst Answers = [\"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n\t\t\t\t\t\t\t\t \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n\t\t\t\t\t\t\t\t \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n\t\t\t\t\t\t\t\t \"Reply hazy, try again\", \"Ask again later\",\n\t\t\t\t\t\t\t\t \"Better not tell you now\", \"Cannot predict now\",\n\t\t\t\t\t\t\t\t \"Concentrate and ask again\", \"Don't bet on it\",\n\t\t\t\t\t\t\t\t \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n\t\t\t\t\t\t\t\t \"Very doubtful\"]\n\nproc exit() =\n\techo \"Bye.\"\n\tquit QuitSuccess\n\nrandomize()\n\ntry:\n\twhile true:\n\t\techo \"Type your question or an empty line to quit.\"\n\t\tstdout.write \"? \"\n\t\tlet question = stdin.readLine()\n\t\tif question.strip().len == 0: exit()\n\t\techo Answers[rand(19)], \".\\n\"\nexcept EOFError:\n\texit()\n" + }, + { + "id": 1191, + "length": 1593, + "source": "Rosetta Code", + "text": "import strformat\n\ntype\n\tMode = enum\n\t\tEncrypt\n\t\tDecrypt\n\nconst lAlphabet: string = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\nconst rAlphabet: string = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n\nproc chao(text: string, mode: Mode, verbose: bool = false): string =\n\tvar left = lAlphabet\n\tvar right = rAlphabet\n\tvar eText = newSeq[char](text.len)\n\tvar temp: array[26, char]\n\n\tfor i in 0.. 1:\n\t\t\tfor j in 1..(string,(string,string))\nproc intstr(n: NimNode): NimNode =\n\tif n.kind == nnkSym:\n\t\treturn ident(\"string\")\n\tresult = nnkPar.newNimNode()\n\tfor i in 1.. 2.\n\tvar p = 3\n\twhile true:\n\t\tlet p2 = p * p\n\t\tif p2 > limit: break\n\t\tfor i in countup(p2, limit, 2 * p):\n\t\t\tc[i] = true\n\t\twhile true:\n\t\t\tinc p, 2\n\t\t\tif not c[p]: break\n\tfor i in countup(3, limit, 2):\n\t\tif not c[i]: result.add i\n\n\nproc squareFree(fromVal, toVal: Natural): seq[int] =\n\tlet limit = int(sqrt(toVal.toFloat))\n\tlet primes = sieve(limit)\n\tfor i in fromVal..toVal:\n\t\tblock check:\n\t\t\tfor p in primes:\n\t\t\t\tlet p2 = p * p\n\t\t\t\tif p2 > i: break\n\t\t\t\tif i mod p2 == 0:\n\t\t\t\t\tbreak check # Not square free.\n\t\t\tresult.add i\n\n\nwhen isMainModule:\n\n\tconst Trillion = 1_000_000_000_000\n\n\techo \"Square-free integers from 1 to 145:\"\n\tvar sf = squareFree(1, 145)\n\tfor i, val in sf:\n\t\tif i > 0 and i mod 20 == 0:\n\t\t\techo()\n\t\tstdout.write ($val).align(4)\n\techo()\n\n\techo \"\\nSquare-free integers from $1 to $2:\\n\".format(Trillion, Trillion + 145)\n\tsf = squareFree(Trillion, Trillion + 145)\n\tfor i, val in sf:\n\t\tif i > 0 and i mod 5 == 0:\n\t\t\techo()\n\t\tstdout.write ($val).align(14)\n\techo()\n\n\techo \"\\nNumber of square-free integers:\\n\"\n\tfor n in [100, 1_000, 10_000, 100_000, 1_000_000]:\n\t\techo \" from $1 to $2 = $3\".format(1, n, squareFree(1, n).len)\n" + }, + { + "id": 1197, + "length": 1754, + "source": "Rosetta Code", + "text": "import sugar\n\nimport gintro/[gobject, gdk, gtk, gio, cairo]\nimport gintro/glib except Pi\n\nconst\n\tWidth = 640\n\tHeight = 480\n\tX0 = Width div 2 - 1\n\tY0 = Height div 2 - 1\n\tColors = [(0.0, 0.0, 0.0), (255.0, 0.0, 0.0), (0.0, 255.0, 0.0), (0.0, 0.0, 255.0),\n\t\t\t\t\t\t(255.0, 0.0, 255.0), (0.0, 255.0, 255.0), (255.0, 255.0, 0.0), (255.0, 255.0, 255.0)]\n\tSizes = collect(newSeq, for size in countdown(Width, 4, 16): float(size))\n\ntype\n\n\t# Description of the simulation.\n\tSimulation = ref object\n\t\tarea: DrawingArea # Drawing area.\n\t\tisize: Natural # Size index.\n\t\ticolor: Natural # Color index.\n\n\nproc newSimulation(area: DrawingArea): Simulation =\n\t## Allocate and initialize the simulation object.\n\n\tnew(result)\n\tresult.area = area\n\tresult.isize = 0\n\n\nproc draw(sim: Simulation; context: cairo.Context) =\n\t## Draw the rectangles.\n\n\tcontext.setSource(Colors[sim.icolor])\n\tlet width = Sizes[sim.isize]\n\tlet height = width * 3 / 4\n\tcontext.rectangle(X0 - width * 0.5, Y0 - height * 0.5, width, height)\n\tcontext.stroke()\n\n\nproc update(sim: Simulation): gboolean =\n\t## Update the simulation state.\n\n\tsim.isize = (sim.isize + 1) mod Sizes.len\n\tif sim.isize == 0:\n\t\t# Change color for next cycle.\n\t\tsim.icolor = (sim.icolor + 1) mod Colors.len\n\tsim.draw(sim.area.window.cairoCreate())\n\tresult = gboolean(1)\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Vibrating rectangles\")\n\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\tlet sim = newSimulation(area)\n\ttimeoutAdd(40, update, sim)\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Vibrating_Rectangles\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 1198, + "length": 1064, + "source": "Rosetta Code", + "text": "import imageman\n\nconst Width = 81\n\nproc peano(points: var seq[Point]; x, y, lg, i1, i2: int) =\n\n\tif lg == 1:\n\t\tpoints.add ((Width - x) * 10, (Width - y) * 10)\n\t\treturn\n\n\tlet lg = lg div 3\n\tpoints.peano(x + 2 * i1 * lg, y + 2 * i1 * lg, lg, i1, i2)\n\tpoints.peano(x + (i1 - i2 + 1) * lg, y + (i1 + i2) * lg, lg, i1, 1 - i2)\n\tpoints.peano(x + lg, y + lg, lg, i1, 1 - i2)\n\tpoints.peano(x + (i1 + i2) * lg, y + (i1 - i2 + 1) * lg, lg, 1 - i1, 1 - i2)\n\tpoints.peano(x + 2 * i2 * lg, y + 2 * (1-i2) * lg, lg, i1, i2)\n\tpoints.peano(x + (1 + i2 - i1) * lg, y + (2 - i1 - i2) * lg, lg, i1, i2)\n\tpoints.peano(x + 2 * (1 - i1) * lg, y + 2 * (1 - i1) * lg, lg, i1, i2)\n\tpoints.peano(x + (2 - i1 - i2) * lg, y + (1 + i2 - i1) * lg, lg, 1 - i1, i2)\n\tpoints.peano(x + 2 * (1 - i2) * lg, y + 2 * i2 * lg, lg, 1 - i1, i2)\n\n\nvar points: seq[Point]\npoints.peano(0, 0, Width, 0, 0)\nvar image = initImage[ColorRGBU](820, 820)\nlet color = ColorRGBU([byte 255, 255, 0])\nfor i in 1..points.high:\n\timage.drawLine(points[i - 1], points[i], color)\nimage.savePNG(\"peano.png\", compression = 9)\n" + }, + { + "id": 1199, + "length": 1053, + "source": "Rosetta Code", + "text": "# Import \"random\" to get random numbers and \"algorithm\" to get sorting functions for arrays.\nimport random, algorithm\n\nrandomize()\n\nproc diceFourRolls(): array[4, int] =\n\t## Generates 4 random values between 1 and 6.\n\tfor i in 0 .. 3:\n\t\tresult[i] = rand(1..6)\n\nproc sumRolls(rolls: array[4, int]): int =\n\t## Save the sum of the 3 highest values rolled.\n\tvar sorted = rolls\n\tsorted.sort()\n\t# By sorting first and then starting the iteration on 1 instead of 0, the lowest number is discarded even if it is repeated.\n\tfor i in 1 .. 3:\n\t\tresult += sorted[i]\n\nfunc twoFifteens(attr: var array[6, int]): bool =\n\tattr.sort()\n\t# Sorting implies than the second to last number is lesser than or equal to the last.\n\tif attr[4] < 15: false else: true\n\nvar sixAttr: array[6, int]\n\nwhile true:\n\tvar sumAttr = 0\n\tfor i in 0 .. 5:\n\t\tsixAttr[i] = sumRolls(diceFourRolls())\n\t\tsumAttr += sixAttr[i]\n\techo \"The roll sums are, in order: \", sixAttr, \", which adds to \", sumAttr\n\tif not twoFifteens(sixAttr) or sumAttr < 75: echo \"Not good enough. Rerolling...\"\n\telse: break\n" + }, + { + "id": 1200, + "length": 697, + "source": "Rosetta Code", + "text": "import sequtils, sets, strutils\n\niterator recaman(num: Positive = Natural.high): tuple[n, a: int; duplicate: bool] =\n\tvar a = 0\n\tyield (0, a, false)\n\tvar known = [0].toHashSet\n\tfor n in 1.. Numbers[index]:\n\t\ttotals[index] = count\n\t\tinc index\n\tinc count\ntotals[^1] = count\n\necho \"The long primes up to {Numbers[0]} are:\"\nfor i in 0..5} is {total}\"\n" + }, + { + "id": 1202, + "length": 957, + "source": "Rosetta Code", + "text": "import algorithm, math, sets, strformat, strutils\n\n\niterator ekg(n, limit: Positive): (int, int) =\n\tvar values: HashSet[int]\n\tdoAssert n >= 2\n\tyield (1, 1)\n\tyield (2, n)\n\tvalues.incl(n)\n\tvar i = 3\n\tvar prev = n\n\twhile i <= limit:\n\t\tvar val = 2\n\t\twhile true:\n\t\t\tif val notin values and gcd(val, prev) != 1:\n\t\t\t\tvalues.incl(val)\n\t\t\t\tyield (i, val)\n\t\t\t\tprev = val\n\t\t\t\tbreak\n\t\t\tinc val\n\t\tinc i\n\n\nfor n in [2, 5, 7, 9, 10]:\n\tvar result: array[1..10, int]\n\tfor i, val in ekg(n, 10): result[i] = val\n\tlet title = fmt\"EKG({n}):\"\n\techo fmt\"{title:8} {result.join(\"\", \"\")}\"\n\nvar ekg5, ekg7: array[1..100, int]\nfor i, val in ekg(5, 100): ekg5[i] = val\nfor i, val in ekg(7, 100): ekg7[i] = val\nvar convIndex = 0\nfor i in 2..100:\n\tif ekg5[i] == ekg7[i] and sorted(ekg5[1.. 0:\n\techo fmt\"EKG(5) and EKG(7) converge at index {convIndex}.\"\nelse:\n\techo \"No convergence found in the first {convIndex} terms.\"\n" + }, + { + "id": 1203, + "length": 2427, + "source": "Rosetta Code", + "text": "# 21 game.\n\nimport random\nimport strformat\nimport strutils\n\nconst\n\tTarget = 21\n\tPossibleChoices: array[18..20, seq[string]] = [@[\"1\", \"2\", \"3\"], @[\"1\", \"2\"], @[\"1\"]]\n\tTargets = [1, 5, 9, 13, 17, 21] # Totals that a player must obtain to win.\n\n\nproc printTotal(total: int) =\n\t## Print the running total.\n\techo fmt\"Running total is now {total}.\"\n\n\nproc computerPlays(total: var int) =\n\t## Make the computer play.\n\tvar choice: int\n\tif total in Targets:\n\t\t# No winning choice. Choose a random value.\n\t\tchoice = rand(1..3)\n\telse:\n\t\t# Find the running total to get.\n\t\tfor val in Targets:\n\t\t\tif val > total:\n\t\t\t\tchoice = val - total\n\t\t\t\tbreak\n\tinc total, choice\n\techo fmt\"I choose {choice}.\"\n\tprintTotal(total)\n\n\nproc prompt(message: string; answers: openArray[string]): int =\n\t## Prompt a message and get an answer checking its validity against possible answers.\n\n\twhile true:\n\t\tstdout.write(message & ' ')\n\t\ttry:\n\t\t\tresult = answers.find(stdin.readLine())\n\t\t\tif result >= 0:\n\t\t\t\tbreak\n\t\t\techo fmt\"Please answer one of: {answers.join(\"\", \"\")}.\"\n\t\texcept EOFError:\n\t\t\techo \"\"\n\t\t\treturn # Quit.\n\n\nrandomize()\n\necho \"21 is a two player game. The game is played by choosing a number (1, 2, 3) to\\n\" &\n\t\t \"be added to the running total. The game is won by the player whose chosen number\\n\" &\n\t\t \"causes the running total to reach exactly 21. The running total starts at zero.\\n\"\necho \"You can quit the game at any time by typing 'q'.\"\n\nblock mainLoop:\n\n\twhile true:\n\t\tvar total = 0\n\n\t\t# Choose the player who will play first.\n\t\tvar answer = prompt(\"Who will play first ('you', 'me')?\", [\"q\", \"you\", \"me\"])\n\t\tif answer == 0:\n\t\t\techo \"Quitting game.\"\n\t\t\tbreak\n\t\telif answer == 1:\n\t\t\tcomputerPlays(total)\n\n\t\t# Internal game loop.\n\t\twhile true:\n\n\t\t\t# Ask player its choice.\n\t\t\tlet choices = if total > 18: PossibleChoices[total] else: PossibleChoices[18]\n\t\t\tlet choice = prompt(fmt\"Your choice ({choices.join(\"\", \"\")})?\", \"q\" & choices)\n\t\t\tif choice == 0:\n\t\t\t\techo \"Quitting game.\"\n\t\t\t\tbreak mainLoop\n\n\t\t\t# Update running total and check if player win.\n\t\t\tinc total, choice\n\t\t\tprintTotal(total)\n\t\t\tif total == Target:\n\t\t\t\techo \"Congratulations, you win.\"\n\t\t\t\tbreak\n\n\t\t\t# Make computer play.\n\t\t\tcomputerPlays(total)\n\t\t\tif total == Target:\n\t\t\t\techo \"Sorry, I win.\"\n\t\t\t\tbreak\n\n\t\t# Ask player for another game.\n\t\tanswer = prompt(\"Do you want to play another game (y, n)\", [\"q\", \"y\", \"n\"])\n\t\tif answer != 1:\n\t\t\techo \"Quitting game.\"\n\t\t\tbreak\n" + }, + { + "id": 1204, + "length": 2746, + "source": "Rosetta Code", + "text": "import sugar\n\ntype # use a thunk closure as a data type...\n\tIn = () -> int # a lazy thunk producing an int\n\tFunc = In -> In\n\tChurch = Func -> Func\n\tMetaChurch = Church -> Church\n\tMetaMetaChurch = MetaChurch -> MetaChurch\n\tPredChurch = (Func -> In) -> (Func -> In)\n\tMetaPredChurch = PredChurch -> PredChurch\n\ntype # type Kind to/from conversions...\n\tPun {.union.} = object # does safer casting...\n\t\tnormal: Church\n\t\tupone: MetaChurch\n\t\tuptwo: MetaMetaChurch\n\t\tpreded: MetaPredChurch\nfunc lift1(ch: Church): MetaChurch = Pun(normal: ch).upone\nfunc lift2(ch: Church): MetaMetaChurch = Pun(normal: ch).uptwo\nfunc liftpred(ch: Church): MetaPredChurch = Pun(normal: ch).preded\n\nlet\n\tzeroChurch: Church = (_: Func) -> Func => ((x: In) => x)\n\toneChurch: Church = (f: Func) -> Func => f\n\tsuccChurch = (ch: Church) -> Church =>\n\t\t((f: Func) => ((x: In) => f(ch(f)x)))\n\taddChurch = (ach, bch: Church) -> Church =>\n\t\t((f: Func) => ((x: In) => ((ach f)(bch(f)x))))\n\tmultChurch = (ach, bch: Church) -> Church => ((f: Func) => ach(bch(f)))\n\texpChurch = (basech, expch: Church) -> Church => (expch.lift1() basech)\n\tisZeroChurch = (ch: Church) -> Church =>\n\t\t(ch.lift2()((_: Church) => zeroChurch) oneChurch)\n\tpredChurch = (ch: Church) -> Church =>\n\t\t(func(f: Func): Func =\n\t\t\tlet prd = (gf: Func -> In) => ((hf: In -> In) => (hf(gf(f))))\n\t\t\t# magic is here, reduces by one function level...\n\t\t\t((x: In) => (ch.liftpred())(prd)((_: Func) => x)((t:In) => t)))\n\tminusChurch = (ach, bch: Church) -> Church =>\n\t\t (bch.lift2()(predChurch)(ach))\n\t# recursively counts times divisor can be subtracted from dividend...\n\tdivChurch = proc(dvdndch, dvsrch: Church): Church =\n\t\tproc divr(n: Church): Church =\n\t\t\t(((vch: Church) =>\n\t\t\t\tvch.lift2()( # test for zero\n\t\t\t\t\t(_: Church) => (divr(vch).succChurch))( # not zero, loop\n\t\t\t\t\tzeroChurch)) # if zero, return zero\n\t\t\t)(n.minusChurch(dvsrch)) # subtract one more divisor per loop\n\t\tdivr(dvdndch.succChurch)\n\n# conversions to/from Church and int...\nproc toChurch(x: int): Church =\n\tresult = zeroChurch\n\tfor _ in 1 .. x: result = result.succChurch\nlet incr = (x: In) => (() => x() + 1)\nproc toInt(ch: Church): int = ch(incr)(() => 0)()\nproc `$`(ch: Church): string = $(ch.toInt)\n\nwhen isMainModule:\n\tlet threeChurch = 3.toChurch\n\tlet fourChurch = threeChurch.succChurch\n\tlet elevenChurch = 11.toChurch\n\tlet twelveChurch = elevenChurch.succChurch\n\techo [ threeChurch.addChurch(fourChurch)\n\t\t\t , threeChurch.multChurch(fourChurch)\n\t\t\t , threeChurch.expChurch(fourChurch)\n\t\t\t , fourChurch.expChurch(threeChurch)\n\t\t\t , zeroChurch.isZeroChurch, oneChurch.isZeroChurch\n\t\t\t , fourChurch.predChurch\n\t\t\t , elevenChurch.minusChurch(threeChurch)\n\t\t\t , elevenChurch.divChurch(threeChurch)\n\t\t\t , twelveChurch.divChurch(threeChurch)\n\t\t\t ]\n" + }, + { + "id": 1205, + "length": 3112, + "source": "Rosetta Code", + "text": "import sugar\n\ntype\n\tTag = enum tgChurch, tgArityZero\n\tChurch = ref object\n\t\tcase tag: Tag\n\t\tof tgChurch: church: Church -> Church\n\t\tof tgArityZero: value: int\nfunc makeCChurch(chf: Church -> Church): Church =\n\tChurch(tag: tgChurch, church: chf)\nproc applyChurch(ch, charg: Church): Church =\n\tcase ch.tag\n\tof tgChurch: ch.church(charg)\n\tof tgArityZero: charg # never happens!\nfunc composeChurch(chl, chr: Church): Church =\n\tcase chl.tag\n\tof tgChurch:\n\t\tcase chr.tag\n\t\tof tgChurch: makeCChurch((f: Church) => chl.church(chr.church(f)))\n\t\tof tgArityZero: chl # never happens!\n\tof tgArityZero: chl # never happens!\n\nlet churchZero = makeCChurch((f: Church) => makeCChurch((x) => x))\nlet churchOne = makeCChurch((x) => x)\nproc succChurch(ch: Church): Church =\n\tmakeCChurch((f) => composeChurch(f, applyChurch(ch, f)))\nproc addChurch(cha, chb: Church): Church =\n\tmakeCChurch((f) =>\n\t\tcomposeChurch(applyChurch(cha, f), applyChurch(chb, f)))\nproc multChurch(cha, chb: Church): Church = composeChurch(cha, chb)\nproc expChurch(chbs, chexp: Church): Church = applyChurch(chexp, chbs)\nproc isZeroChurch(ch: Church): Church =\n\tapplyChurch(applyChurch(ch, Church(tag: tgChurch,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t church: (_: Church) => churchZero)),\n\t\t\t\t\t\t\tchurchOne)\nproc predChurch(ch: Church): Church =\n\tproc ff(f: Church): Church =\n\t\tproc xf(x: Church): Church =\n\t\t\tlet prd = makeCChurch((g) => makeCChurch((h) =>\n\t\t\t\t\t\t\t\t\tapplyChurch(h, applyChurch(g, f))))\n\t\t\tlet frstch = makeCChurch((_) => x)\n\t\t\tlet idch = makeCChurch((a) => a)\n\t\t\tapplyChurch(applyChurch(applyChurch(ch, prd), frstch), idch)\n\t\tmakeCChurch(xf)\n\tmakeCChurch(ff)\nproc subChurch(cha, chb: Church): Church =\n\tapplyChurch(applyChurch(chb, makeCChurch(predChurch)), cha)\nproc divChurch(chdvdnd, chdvsr: Church): Church =\n\tproc divr(chn: Church): Church =\n\t\tproc tst(chv: Church): Church =\n\t\t\tlet loopr = makeCChurch((_) => succChurch(divr(chv)))\n\t\t\tapplyChurch(applyChurch(chv, loopr), churchZero)\n\t\ttst(subChurch(chn, chdvsr))\n\tdivr(succChurch(chdvdnd))\n\n# converters...\nconverter intToChurch(i: int): Church =\n\tfunc loop(n: int, rch: Church): Church = # recursive function call\n\t\tif n <= 0: rch else: loop(n - 1, succChurch(rch))\n\tloop(i, churchZero)\n# result = churchZero # imperative non recursive way...\n# for _ in 1 .. i: result = succChurch(result)\nconverter churchToInt(ch: Church): int =\n\tfunc succInt(chv: Church): Church =\n\t\tcase chv.tag\n\t\tof tgArityZero: Church(tag: tgArityZero, value: chv.value + 1)\n\t\tof tgChurch: chv\n\tlet rslt = applyChurch(applyChurch(ch, Church(tag: tgChurch, church: succInt)),\n\t\t\t\t\t\t\t\t\t\t\t\t Church(tag: tgArityZero, value: 0))\n\tcase rslt.tag\n\tof tgArityZero: rslt.value\n\tof tgChurch: -1\nproc `$`(ch: Church): string = $ch.int\n\n# test it...\nwhen isMainModule:\n\tlet c3: Church = 3\n\tlet c4 = succChurch c3\n\tlet c11: Church = 11\n\tlet c12 = succChurch c11\n\techo addChurch(c3, c4), \" \",\n\t\t\t multChurch(c3, c4), \" \",\n\t\t\t expChurch(c3, c4), \" \",\n\t\t\t expChurch(c4, c3), \" \",\n\t\t\t isZeroChurch(churchZero), \" \",\n\t\t\t isZeroChurch(c3), \" \",\n\t\t\t predChurch(c4), \" \",\n\t\t\t subChurch(c11, c3), \" \",\n\t\t\t divChurch(c11, c3), \" \",\n\t\t\t divChurch(c12, c3)\n" + }, + { + "id": 1206, + "length": 1673, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, strutils\n\ntype Color {.pure.} = enum Red = \"R\", Black = \"B\"\n\nproc `$`(s: seq[Color]): string = s.join(\" \")\n\n# Create pack, half red, half black and shuffle it.\nvar pack = newSeq[Color](52)\nfor i in 0..51: pack[i] = Color(i < 26)\npack.shuffle()\n\n# Deal from pack into 3 stacks.\nvar red, black, others: seq[Color]\nfor i in countup(0, 51, 2):\n\tcase pack[i]\n\t\tof Red: red.add pack[i + 1]\n\t\tof Black: black.add pack[i + 1]\n\tothers.add pack[i]\necho \"After dealing the cards the state of the stacks is:\"\necho \" Red: {red.len:>2} cards -> {red}\"\necho \" Black: {black.len:>2} cards -> {black}\"\necho \" Discard: {others.len:>2} cards -> {others}\"\n\n# Swap the same, random, number of cards between the red and black stacks.\nlet m = min(red.len, black.len)\nlet n = rand(1..m)\nvar rp = toSeq(0..red.high)\nrp.shuffle()\nrp.setLen(n)\nvar bp = toSeq(0..black.high)\nbp.shuffle()\nbp.setLen(n)\necho \"\\n{n} card(s) are to be swapped.\\n\"\necho \"The respective zero-based indices of the cards(s) to be swapped are:\"\necho \" Red : \", rp.join(\" \")\necho \" Black : \", bp.join(\" \")\nfor i in 0.. 0:\n\t\t\tfor i in countup(r.first, r.last, r.step):\n\t\t\t\tyield i\n\t\telif r.step < 0:\n\t\t\tfor i in countdown(r.first, r.last, -r.step):\n\t\t\t\tyield i\n\t\telse:\n\t\t\traise newException(ValueError, \"step cannot be zero\")\n\nfor j in loop(initRange(-three, 3^3, three),\n\t\t\t\t\t\t\tinitRange(-seven, seven, x),\n\t\t\t\t\t\t\tinitRange(555, 550 - y),\n\t\t\t\t\t\t\tinitRange(22, -28, three),\n\t\t\t\t\t\t\tinitRange(1927, 1939),\n\t\t\t\t\t\t\tinitRange(x, y, -z),\n\t\t\t\t\t\t\tinitRange(11^x, 11^x + one)):\n\tsum += abs(j)\n\tif abs(prod) < 2^27 and j != 0: prod *= j\n\nlet s = ($sum).insertSep(',')\nlet p = ($prod).insertSep(',')\nlet m = max(s.len, p.len)\necho \" sum = \", s.align(m)\necho \"prod = \", p.align(m)\n" + }, + { + "id": 1209, + "length": 1774, + "source": "Rosetta Code", + "text": "import strformat\nimport tables\n\n# Generate tables at compile time. This eliminates the initialization at\n# the expense of a bigger executable.\n\nconst square13 = block:\n\tvar tmp = newSeq[tuple[a, b: int]]()\n\tfor i in 1..13:\n\t\ttmp.add((i * i, i))\n\ttoTable(tmp)\n\nconst square10000 = block:\n\tvar tmp = newSeq[tuple[a, b: int]]()\n\tfor i in 1..10000:\n\t\ttmp.add((i * i, i))\n\ttoTable(tmp)\n\nproc solve(angle, maxLen: int, allowSame: bool): seq[tuple[a, b, c: int]] =\n\tresult = newSeq[tuple[a, b, c: int]]()\n\tfor a in 1..maxLen:\n\t\tfor b in a..maxLen:\n\t\t\tvar lhs = a * a + b * b\n\t\t\tif angle != 90:\n\t\t\t\tcase angle\n\t\t\t\tof 60:\n\t\t\t\t\tdec lhs, a * b\n\t\t\t\tof 120:\n\t\t\t\t\tinc lhs, a * b\n\t\t\t\telse:\n\t\t\t\t\traise newException(IOError, \"Angle must be 60, 90 or 120 degrees\")\n\t\t\tcase maxLen\n\t\t\tof 13:\n\t\t\t\tvar c = square13.getOrDefault(lhs)\n\t\t\t\tif (not allowSame and a == b and b == c) or c == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tresult.add((a, b, c))\n\t\t\tof 10000:\n\t\t\t\tvar c = square10000.getOrDefault(lhs)\n\t\t\t\tif (not allowSame and a == b and b == c) or c == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tresult.add((a, b, c))\n\t\t\telse:\n\t\t\t\traise newException(IOError, \"Maximum length must be either 13 or 10000\")\n\necho \"For sides in the range [1, 13] where they can all be the same length:\\n\"\nlet angles = [90, 60, 120]\nfor angle in angles:\n\tvar solutions = solve(angle, 13, true)\n\techo fmt\" For an angle of {angle} degrees there are {len(solutions)} solutions, to wit:\"\n\twrite(stdout, \" \")\n\tfor i in 0.. float\n\nfunc quadSimpsonsMem(f: Func; a, fa, b, fb: float): tuple[m, fm, val: float] =\n\t## Evaluates the Simpson's Rule, also returning m and f(m) to reuse\n\tresult.m = (a + b) / 2\n\tresult.fm = f(result.m)\n\tresult.val = abs(b - a) * (fa + 4 * result.fm + fb) / 6\n\nfunc quadAsr(f: Func; a, fa, b, fb, eps, whole, m, fm: float): float =\n\t## Efficient recursive implementation of adaptive Simpson's rule.\n\t## Function values at the start, middle, end of the intervals are retained.\n\tlet (lm, flm, left) = f.quadSimpsonsMem(a, fa, m, fm)\n\tlet (rm, frm, right) = f.quadSimpsonsMem(m, fm, b, fb)\n\tlet delta = left + right - whole\n\tresult = if abs(delta) <= 15 * eps:\n\t\t\t\t\t\t left + right + delta / 15\n\t\t\t\t\t else:\n\t\t\t\t\t\t f.quadAsr(a, fa, m, fm, eps / 2, left, lm, flm) +\n\t\t\t\t\t\t f.quadAsr(m, fm, b, fb, eps / 2, right, rm, frm)\n\nfunc quadAsr(f: Func; a, b, eps: float): float =\n\t## Integrate f from a to b using Adaptive Simpson's Rule with max error of eps.\n\tlet fa = f(a)\n\tlet fb = f(b)\n\tlet (m, fm, whole) = f.quadSimpsonsMem(a, fa, b, fb)\n\tresult = f.quadAsr(a, fa, b, fb, eps, whole, m, fm)\n\necho \"Simpson's integration of sine from 0 to 1 = \", sin.quadAsr(0, 1, 1e-9)\n" + }, + { + "id": 1212, + "length": 1981, + "source": "Rosetta Code", + "text": "import math, strformat, strutils\n\nconst Lim = 1_000_035\n\ntype Group {.pure.} = enum # \"ord\" gives the number of terms.\n\tUnsexy = (1, \"unsexy primes\")\n\tPairs = (2, \"sexy prime pairs\")\n\tTriplets = (3, \"sexy prime triplets\")\n\tQuadruplets = (4, \"sexy prime quadruplets\")\n\tQuintuplets = (5, \"sexy prime quintuplets\")\n\n\n# Sieve of Erathosthenes.\nvar composite: array[1..Lim, bool] # Default is false.\ncomposite[1] = true\nfor p in countup(3, sqrt(Lim.toFloat).int, 2): # Ignore even numbers.\n\tif not composite[p]:\n\t\tfor k in countup(p * p, Lim, 2 * p):\n\t\t\tcomposite[k] = true\n\ntemplate isPrime(n: int): bool = not composite[n]\n\n\nproc expandGroup(n: int; group: Group): string =\n\t## Given the first term of a group, return the full group\n\t## representation as a string.\n\tvar n = n\n\tfor _ in 1..ord(group):\n\t\tresult.addSep(\", \")\n\t\tresult.add $n\n\t\tinc n, 6\n\tif group != Unsexy: result = '(' & result & ')'\n\n\nproc printResult(group: Group; values: seq[int]; count: int) =\n\t## Print a result.\n\n\techo \"\\nNumber of {group} less than {Lim}: {values.len}\"\n\tlet last = min(values.len, count)\n\tlet verb = if last == 1: \"is\" else: \"are\"\n\techo \"The last {last} {verb}:\"\n\n\tvar line = \"\"\n\tfor i in countdown(last, 1):\n\t\tline.addSep(\", \")\n\t\tline.add expandGroup(values[^i], group)\n\techo \" \", line\n\n\nvar\n\tpairs, trips, quads, quints: seq[int] # Keep only the first prime of the group.\n\tunsexy = @[2, 3]\n\nfor n in countup(3, Lim, 2):\n\tif composite[n]: continue\n\n\tif n in 7..(Lim - 8) and composite[n - 6] and composite[n + 6]:\n\t\tunsexy.add n\n\t\tcontinue\n\n\tif n < Lim - 6 and isPrime(n + 6):\n\t\tpairs.add n\n\telse: continue\n\n\tif n < Lim - 12 and isPrime(n + 12):\n\t\ttrips.add n\n\telse: continue\n\n\tif n < Lim - 18 and isPrime(n + 18):\n\t\tquads.add n\n\telse: continue\n\n\tif n < Lim - 24 and isPrime(n + 24):\n\t\tquints.add n\n\nprintResult(Pairs, pairs, 5)\nprintResult(Triplets, trips, 5)\nprintResult(Quadruplets, quads, 5)\nprintResult(Quintuplets, quints, 5)\nprintResult(Unsexy, unsexy, 10)\n" + }, + { + "id": 1213, + "length": 1504, + "source": "Rosetta Code", + "text": "import strutils\n\nconst EmptyRecord = repeat(' ', 64)\n\n\nproc textToBlock(infile, outfile: string) =\n\t## Read lines of a text file and write them as 64 bytes records.\n\n\tlet input = infile.open(fmRead)\n\tdefer: input.close()\n\tlet output = outfile.open(fmWrite)\n\tdefer: output.close()\n\n\tvar count = 0\n\twhile not input.endOfFile:\n\t\tvar record = input.readLine()\n\t\tif record.len > 64:\n\t\t\trecord.setLen(64) # Truncate to 64 bytes.\n\t\telif record.len < 64:\n\t\t\trecord &= repeat(' ', 64 - record.len) # Pad to 64 bytes.\n\t\tif output.writeChars(record, 0, 64) != 64:\n\t\t\traise newException(IOError, \"error while writing block file\")\n\t\tinc count\n\n\t# Complete block with empty records.\n\tlet rem = count mod 16\n\tif rem != 0:\n\t\tfor _ in 1..(16 - rem):\n\t\t\tif output.writeChars(EmptyRecord, 0, 64) != 64:\n\t\t\t\traise newException(IOError, \"error while writing block file\")\n\n\nproc blockToText(infile, outfile: string) =\n\t## Read 64 bytes records and write them as lines trimming spaces.\n\n\tlet input = infile.open(fmRead)\n\tdefer: input.close()\n\tlet output = outfile.open(fmWrite)\n\tdefer: output.close()\n\n\tvar line: string\n\twhile not input.endOfFile:\n\t\tline.setLen(64) # Allocate space for the 64 bytes to read.\n\t\tif input.readChars(line, 0, 64) != 64:\n\t\t\traise newException(IOError, \"error while reading block file\")\n\t\tline = line.strip(leading = false, trailing = true) & '\\n'\n\t\toutput.write(line)\n\n\nwhen isMainModule:\n\ttextToBlock(\"block1.txt\", \"block.dat\")\n\tblockToText(\"block.dat\", \"block2.txt\")\n" + }, + { + "id": 1214, + "length": 5767, + "source": "Rosetta Code", + "text": "import math, random, strformat\n\nconst\n\tMaxN = 1073741789 # Maximum modulus.\n\tMaxR = MaxN + 65536 # Maximum order \"g\".\n\tInfinity = int64.high # Symbolic infinity.\n\ntype\n\n\tPoint = tuple[x, y: int64]\n\n\tCurve = object\n\t\ta, b: int64\n\t\tn: int64\n\t\tg: Point\n\t\tr: int64\n\n\tPair = tuple[a, b: int64]\n\n\tParameters = tuple[a, b, n, gx, gy, r: int]\n\nconst ZerO: Point = (Infinity, 0i64)\n\ntype\n\tInversionError = object of ValueError\n\tInvalidParamError = object of ValueError\n\n\ntemplate `%`(a, n: int64): int64 =\n\t## To simplify the writing.\n\tfloorMod(a, n)\n\n\nproc exgcd(v, u: int64): int64 =\n\t## Return 1/v mod u.\n\tvar u = u\n\tvar v = v\n\tif v < 0: v += u\n\n\tvar r = 0i64\n\tvar s = 1i64\n\twhile v != 0:\n\t\tlet q = u div v\n\t\tu = u mod v\n\t\tswap u, v\n\t\tr -= q * s\n\t\tswap r, s\n\n\tif u != 1:\n\t\traise newException(InversionError, \"impossible inverse mod N, gcd = \" & $u)\n\tresult = r\n\n\nfunc discr(e: Curve): int64 =\n\t## Return the discriminant of \"e\".\n\tlet c = e.a * e.a % e.n * e.a % e.n * 4\n\tresult = -16 * (e.b * e.b % e.n * 27 + c) % e.n\n\n\nfunc isO(p: Point): bool =\n\t## Return true if \"p\" is zero.\n\tp.x == Infinity and p.y == 0\n\n\nfunc isOn(e: Curve; p: Point): bool =\n\t## Return true if \"p\" is on curve \"e\".\n\tif p.isO: return true\n\tlet r = ((e.a + p.x * p.x) % e.n * p.x + e.b) % e.n\n\tlet s = p.y * p.y % e.n\n\tresult = r == s\n\n\nproc add(e: Curve; p, q: Point): Point =\n\t## Full Point addition.\n\n\tif p.isO: return q\n\tif q.isO: return p\n\n\tvar la: int64\n\tif p.x != q.x:\n\t\tla = (p.y - q.y) * exgcd(p.x - q.x, e.n) % e.n\n\telif p.y == q.y and p.y != 0:\n\t\tla = (p.x * p.x % e.n * 3 + e.a) % e.n * exgcd(2 * p.y, e.n) % e.n\n\telse:\n\t\treturn ZerO\n\n\tresult.x = (la * la - p.x - q.x) % e.n\n\tresult.y = (la * (p.x - result.x) - p.y) % e.n\n\n\nproc mul(e: Curve; p: Point; k: int64): Point =\n\t## Return \"kp\".\n\tvar q = p\n\tvar k = k\n\tresult = ZerO\n\n\twhile k != 0:\n\t\tif (k and 1) != 0:\n\t\t\tresult = e.add(result, q)\n\t\tq = e.add(q, q)\n\t\tk = k shr 1\n\n\nproc print(e: Curve; prefix: string; p: Point) =\n\t## Print a point with a prefix.\n\tvar y = p.y\n\tif p.isO:\n\t\techo prefix, \" (0)\"\n\telse:\n\t\tif y > e.n - y: y -= e.n\n\t\techo prefix, \" ({p.x}, {y})\"\n\n\nproc initCurve(params: Parameters): Curve =\n\t## Initialize the curve.\n\n\tresult.n = params.n\n\tif result.n notin 5..MaxN:\n\t\traise newException(ValueError, \"invalid value for N: \" & $result.n)\n\tresult.a = params.a.int64 % result.n\n\tresult.b = params.b.int64 % result.n\n\tresult.g.x = params.gx.int64 % result.n\n\tresult.g.y = params.gy.int64 % result.n\n\tresult.r = params.r\n\n\tif result.r notin 5..MaxR:\n\t\traise newException(ValueError, \"invalid value for r: \" & $result.r)\n\n\techo \"\\nE: y^2 = x^3 + {result.a}x + {result.b} (mod {result.n})\"\n\tresult.print(\"base point G\", result.g)\n\techo \"order(G, E) = {result.r}\"\n\n\nproc rnd(): float =\n\t## Return a pseudorandom number in range [0..1[.\n\twhile true:\n\t\tresult = rand(1.0)\n\t\tif result != 1: break\n\nproc signature(e: Curve; s, f: int64): Pair =\n\t## Compute the signature.\n\n\tvar\n\t\tc, d = 0i64\n\t\tu: int64\n\t\tv: Point\n\n\techo \"Signature computation\"\n\n\twhile true:\n\t\twhile true:\n\t\t\tu = 1 + int64(rnd() * float(e.r - 1))\n\t\t\tv = e.mul(e.g, u)\n\t\t\tc = v.x % e.r\n\t\t\tif c != 0: break\n\t\td = exgcd(u, e.r) * (f + s * c % e.r) % e.r\n\t\tif d != 0: break\n\n\techo \"one-time u = \", u\n\te.print(\"V = uG\", v)\n\n\tresult = (c, d)\n\n\nproc verify(e: Curve; w: Point; f: int64; sg: Pair): bool =\n\t## Verify a signature.\n\n\t# Domain check.\n\tif sg.a notin 1.. t: f = f shr 1\n\techo \"\\naligned hash {f:x}\"\n\n\tlet sg = e.signature(s, f)\n\techo \"signature c, d = {sg.a}, {sg.b}\"\n\n\tvar d = d\n\tif d > 0:\n\t\twhile d > t: d = d shr 1\n\t\tf = f xor d\n\t\techo \"\\ncorrupted hash {f:x}\"\n\n\techo if e.verify(w, f, sg): \"Valid\" else: \"Invalid\"\n\nwhen isMainModule:\n\n\trandomize()\n\n\t# Test vectors: elliptic curve domain parameters,\n\t# short Weierstrass model y^2 = x^3 + ax + b (mod N)\n\n\tconst Sets = [\n\t\t# a, b, modulus N, base point G, order(G, E), cofactor\n\t\t\t(355, 671, 1073741789, 13693, 10088, 1073807281),\n\t\t\t( 0, 7, 67096021, 6580, 779, 16769911),\n\t\t\t( -3, 1, 877073, 0, 1, 878159),\n\t\t\t( 0, 14, 22651, 63, 30, 151),\n\t\t\t( 3, 2, 5, 2, 1, 5),\n\n\t\t# ECDSA may fail if...\n\t\t# the base point is of composite order\n\t\t\t( 0, 7, 67096021, 2402, 6067, 33539822),\n\t\t# the given order is of composite order\n\t\t\t( 0, 7, 67096021, 6580, 779, 67079644),\n\t\t# the modulus is not prime (deceptive example)\n\t\t\t( 0, 7, 877069, 3, 97123, 877069),\n\t\t# fails if the modulus divides the discriminant\n\t\t\t( 39, 387, 22651, 95, 27, 22651)\n\t\t]\n\n\t# Digital signature on message hash f,\n\t# set d > 0 to simulate corrupted data.\n\tlet f = 0x789abcdei64\n\tlet d = 0\n\n\tfor s in Sets:\n\t\tlet e = initCurve(s)\n\t\ttry:\n\t\t\te.ecdsa(f, d)\n\t\texcept ValueError:\n\t\t\techo getCurrentExceptionMsg()\n\t\techo \"--------------\"\n" + }, + { + "id": 1215, + "length": 2611, + "source": "Rosetta Code", + "text": "import tables\nimport sets\nimport strformat\n\ntype Date = tuple[month: string, day: int]\n\nconst Dates = [Date (\"May\", 15), (\"May\", 16), (\"May\", 19), (\"June\", 17), (\"June\", 18),\n\t\t\t\t\t\t\t (\"July\", 14), (\"July\", 16), (\"August\", 14), (\"August\", 15), (\"August\", 17)]\n\nconst\n\n\tMonthTable: Table[int, HashSet[string]] =\n\t\t\t\t\t\t\t\tstatic:\n\t\t\t\t\t\t\t\t\tvar t: Table[int, HashSet[string]]\n\t\t\t\t\t\t\t\t\tfor date in Dates:\n\t\t\t\t\t\t\t\t\t\tt.mgetOrPut(date.day, initHashSet[string]()).incl(date.month)\n\t\t\t\t\t\t\t\t\tt\n\n\tDayTable: Table[string, HashSet[int]] =\n\t\t\t\t\t\t\tstatic:\n\t\t\t\t\t\t\t\tvar t: Table[string, HashSet[int]]\n\t\t\t\t\t\t\t\tfor date in Dates:\n\t\t\t\t\t\t\t\t\tt.mgetOrPut(date.month, initHashSet[int]()).incl(date.day)\n\t\t\t\t\t\t\t\tt\n\nvar possibleMonths: HashSet[string] # Set of possible months.\nvar possibleDays: HashSet[int] # Set of possible days.\n\n\n# Albert: I don't know when Cheryl's birthday is, ...\n# => eliminate months with a single possible day.\nfor month, days in DayTable.pairs:\n\tif days.len > 1:\n\t\tpossibleMonths.incl(month)\n\n# ... but I know that Bernard does not know too.\n# => eliminate months with one day present only in this month.\nfor month, days in DayTable.pairs:\n\tfor day in days:\n\t\tif MonthTable[day].len == 1:\n\t\t\tpossibleMonths.excl(month)\necho fmt\"After first Albert's sentence, possible months are {possibleMonths}.\"\n\n# Bernard: At first I don't know when Cheryl's birthday is, ...\n# => eliminate days with a single possible month.\nfor day, months in MonthTable.pairs:\n\tif months.len > 1:\n\t\tpossibleDays.incl(day)\n\n# ... but I know now.\n# => eliminate days which are compatible with several months in \"possibleMonths\".\nvar impossibleDays: HashSet[int] # Days which are eliminated by this sentence.\nfor day in possibleDays:\n\tif (MonthTable[day] * possibleMonths).len > 1:\n\t\timpossibleDays.incl(day)\npossibleDays.excl(impossibleDays)\necho fmt\"After Bernard's sentence, possible days are {possibleDays}.\"\n\n# Albert: Then I also know when Cheryl's birthday is.\n# => eliminate months which are compatible with several days in \"possibleDays\".\nvar impossibleMonths: HashSet[string] # Months which are eliminated by this sentence.\nfor month in possibleMonths:\n\tif (DayTable[month] * possibleDays).len > 1:\n\t\timpossibleMonths.incl(month)\npossibleMonths.excl(impossibleMonths)\n\ndoAssert possibleMonths.len == 1\nlet month = possibleMonths.pop()\necho fmt\"After second Albert's sentence, remaining month is {month}...\"\n\npossibleDays = possibleDays * DayTable[month]\ndoAssert possibleDays.len == 1\nlet day = possibleDays.pop()\necho fmt\"and thus remaining day is {day}.\"\n\necho \"\"\necho fmt\"So birthday date is {month} {day}.\"\n" + }, + { + "id": 1216, + "length": 2020, + "source": "Rosetta Code", + "text": "import re, strutils, parseutils, tables, math\nconst input = \"\"\"\n\t\t2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\t\t1,567 +1.567k 0.1567e-2m\n\t\t25.123kK 25.123m 2.5123e-00002G\n\t\t25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\t\t-.25123e-34Vikki 2e-77gooGols\n\t\t9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!\n\t\t\"\"\"\nlet\n\tabbrAlpha = re(r\"(PAIR)(s)?$|(SCO)(r|re|res)?$|(DOZ)(e|en|ens)?$|(GR)(o|os|oss)?$|(GREATGR)(o|os|oss)?$|(GOOGOL)(s)?$\",\n\t\t\tflags = {reIgnoreCase})\n\tmetricBinary = re(r\"[KMGTPEZYXWVU]i?\", flags = {reIgnoreCase})\n\tfactorial = re\"!+$\"\nconst\n\talphaValues = [2e0, 20e0, 12e0, 144e0, 1728e0, 1e100]\n\tmetricBinaryValueTab = {\"K\": 10.0^3, \"KI\": 2.0^10, \"M\": 10.0^6, \"MI\": 2.0^20,\n\t\t\t\"G\": 10.0^9, \"GI\": 2.0^30, \"T\": 10.0^12, \"TI\": 2.0^40, \"P\": 10.0^15,\n\t\t\t\"PI\": 2.0^50, \"E\": 10.0^18, \"EI\": 2.0^60, \"Z\": 10.0^21, \"ZI\": 2.0^70,\n\t\t\t\"Y\": 10.0^24, \"YI\": 2.0^80, \"X\": 10.0^27, \"XI\": 2.0^90, \"W\": 10.0^30,\n\t\t\t\"WI\": 2.0^100, \"V\": 10.0^33, \"VI\": 2.0^110, \"U\": 10.0^36,\n\t\t\t\"UI\": 2.0^120}.toTable\nvar\n\tmatches: array[12, string]\n\tres, fac: float\n\tsuffix: string\nproc sepFloat(f: float): string =\n\tvar\n\t\ts = $f\n\t\ti, num: int\n\tnum = parseInt(s, i)\n\tif num == 0:\n\t\treturn s\n\telse:\n\t\treturn insertSep($i, ',', 3)&s[num..^1]\nfor line in input.splitLines():\n\tif not isEmptyOrWhiteSpace(line):\n\t\techo(\"Input:\\n\", line, \"\\nOutput:\")\n\t\tvar output = \" \"\n\t\tfor raw_number in line.replace(\",\", \"\").splitWhiteSpace():\n\t\t\tsuffix = raw_number[parseutils.parseFloat(raw_number, res)..^1].toUpper()\n\t\t\tif suffix.match(abbrAlpha, matches):\n\t\t\t\tfor i, v in matches.mpairs():\n\t\t\t\t\tif i mod 2 == 0 and not v.isEmptyOrWhiteSpace():\n\t\t\t\t\t\tres*=alphaValues[i div 2]\n\t\t\t\t\t\tv = \"\"\n\t\t\t\t\t\tbreak\n\t\t\telif suffix.match(factorial):\n\t\t\t\tfac = abs(res)-toFloat(len(suffix))\n\t\t\t\twhile fac > 0:\n\t\t\t\t\tres*=fac\n\t\t\t\t\tfac-=toFloat(len(suffix))\n\t\t\telif suffix.match(metricBinary):\n\t\t\t\tfor m in suffix.findAll(metricBinary):\n\t\t\t\t\tres*=metricBinaryValueTab[m]\n\t\t\toutput &= sepFloat(res)\" \"\n\t\techo(output)\n" + }, + { + "id": 1217, + "length": 1014, + "source": "Rosetta Code", + "text": "import imageman\n\ntype\n\tFPoint = tuple[x, y: float]\n\tFPoints3 = array[3, FPoint]\n\nfunc lagrange(p: FPoints3; x: float): float =\n\t(x-p[1].x) * (x-p[2].x) / (p[0].x-p[1].x) / (p[0].x-p[2].x) * p[0].y +\n\t(x-p[0].x) * (x-p[2].x) / (p[1].x-p[0].x) / (p[1].x-p[2].x) * p[1].y +\n\t(x-p[0].x) * (x-p[1].x) / (p[2].x-p[0].x) / (p[2].x-p[1].x) * p[2].y\n\nfunc points(p: FPoints3; n: int): seq[Point] =\n\tresult.setLen(2 * n + 1)\n\tvar dx = (p[1].x - p[0].x) / float(n)\n\tfor i in 0..= 1e100:\n\t\tsuffixIndex = 13\n\t\tn /= 1e100\n\telif n > 1:\n\t\tlet magnitude = log(n, base.toFloat).int\n\t\tsuffixIndex = min(magnitude div exponentDist, 12)\n\t\tn /= float(base ^ (exponentDist * suffixIndex))\n\telse:\n\t\tsuffixIndex = 0\n\n\tlet numStr = if digits > 0:\n\t\t\t\t\t\t\t\t n.formatFloat(ffDecimal, precision = digits)\n\t\t\t\t\t\t\t elif digits == 0:\n\t\t\t\t\t\t\t\t # Can't use \"formatFloat\" with precision = 0 as it keeps the decimal point.\n\t\t\t\t\t\t\t\t # So convert to nearest int and format this value.\n\t\t\t\t\t\t\t\t $(n.toInt)\n\t\t\t\t\t\t\t else:\n\t\t\t\t\t\t\t\t n.formatFloat(ffDecimal, precision = 3).strip(chars = {'0'}).strip(chars = {'.'})\n\tresult = numSign & numStr & Suffixes[suffixIndex] & (if base == 2: \"i\" else: \"\")\n\n\nwhen isMainModule:\n\n\techo \"[87,654,321]: \",\n\t\t\t suffize(\"87,654,321\")\n\techo \"[-998,877,665,544,332,211,000 / digits = 3]: \",\n\t\t\t suffize(\"-998,877,665,544,332,211,000\", 3)\n\techo \"[+112,233 / digits = 0]: \",\n\t\t\t suffize(\"+112,233\", 0)\n\techo \"[16,777,216 / digits = 1]: \",\n\t\t\t suffize(\"16,777,216\", 1)\n\techo \"[456,789,100,000,000 / digits = 2]: \",\n\t\t\t suffize(\"456,789,100,000,000\", 2)\n\techo \"[456,789,100,000,000 / digits = 2 / base = 10]: \",\n\t\t\t suffize(\"456,789,100,000,000\", 2, 10)\n\techo \"[456,789,100,000,000 / digits = 5 / base = 2]: \",\n\t\t\t suffize(\"456,789,100,000,000\", digits = 5, base = 2)\n\techo \"[456,789,100,000.000e+000 / digits = 0 / base = 10]: \",\n\t\t\t suffize(\"456,789,100,000.000e+000\", digits = 0, base = 10)\n\techo \"[+16777216 / base = 2]: \",\n\t\t\t suffize(\"+16777216\", base = 2)\n\techo \"[1.2e101]: \",\n\t\t\t suffize(\"1.2e101\")\n" + }, + { + "id": 1219, + "length": 1383, + "source": "Rosetta Code", + "text": "import math, strutils\n\nconst\n\tM = 10_000_000\n\tN = M + 19 # Maximum value for sieve.\n\n# Fill sieve of Erathosthenes.\nvar comp: array[2..N, bool] # True means composite; default is prime.\nfor n in countup(3, sqrt(N.toFloat).int, 2):\n\tif not comp[n]:\n\t\tfor k in countup(n * n, N, 2 * n):\n\t\t\tcomp[k] = true\n\n# Build list of primes.\nvar primes = @[2]\nfor n in countup(3, N, 2):\n\tif not comp[n]:\n\t\tprimes.add n\nif primes[^1] < M: quit \"Not enough primes: please, increase value of N.\"\n\n# Build lists of strong and weak primes.\nvar strongPrimes, weakPrimes: seq[int]\nfor i in 1.. primes[i - 1] + primes[i + 1]:\n\t\tstrongPrimes.add p\n\telif p shl 1 < primes[i - 1] + primes[i + 1]:\n\t\tweakPrimes.add p\n\n\nwhen isMainModule:\n\n\tproc count(list: seq[int]; max: int): int =\n\t\t## Return the count of values less than \"max\".\n\t\tfor p in list:\n\t\t\tif p >= max: break\n\t\t\tinc result\n\n\techo \"First 36 strong primes:\"\n\techo \" \", strongPrimes[0..35].join(\" \")\n\techo \"Count of strong primes below 1_000_000: \", strongPrimes.count(1_000_000)\n\techo \"Count of strong primes below 10_000_000: \", strongPrimes.count(10_000_000)\n\techo()\n\n\techo \"First 37 weak primes:\"\n\techo \" \", weakPrimes[0..36].join(\" \")\n\techo \"Count of weak primes below 1_000_000: \", weakPrimes.count(1_000_000)\n\techo \"Count of weak primes below 10_000_000: \", weakPrimes.count(10_000_000)\n" + }, + { + "id": 1220, + "length": 1687, + "source": "Rosetta Code", + "text": "import os, random, sequtils\nimport ncurses\n\nconst RowDelay = 40 # In milliseconds.\n\nproc exit() {.noconv.} =\n\tendwin()\n\tquit QuitSuccess\n\nproc run() =\n\n\tconst\n\t\tChars = \"0123456789\" # Characters to randomly appear in the rain sequence.\n\n\tlet stdscr = initscr()\n\tnoEcho()\n\tcursSet(0)\n\tstartColor()\n\tinitPair(1, COLOR_GREEN, COLOR_BLACK)\n\tattron(COLOR_PAIR(1).cint)\n\n\tvar width, height: cint\n\tstdscr.getmaxyx(height, width)\n\tlet maxX = width - 1\n\tlet maxY = height - 1\n\n\t# Create arrays of columns based on screen width.\n\n\t# Array containing the current row of each column.\n\t# Set top row as current row for all columns.\n\tvar columnsRow = repeat(cint -1, width)\n\n\t# Array containing the active status of each column.\n\t# A column draws characters on a row when active.\n\tvar columnsActive = newSeq[bool](width)\n\n\n\tsetControlCHook(exit)\n\twhile true:\n\n\t\tfor i in 0..maxX:\n\t\t\tif columnsRow[i] == -1:\n\t\t\t\t# If a column is at the top row, pick a random starting row and active status.\n\t\t\t\tcolumnsRow[i] = cint(rand(maxY))\n\t\t\t\tcolumnsActive[i] = bool(rand(1))\n\n\t\t# Loop through columns and draw characters on rows.\n\t\tfor i in 0..maxX:\n\t\t\tif columnsActive[i]:\n\t\t\t\t# Draw a random character at this column's current row.\n\t\t\t\tlet charIndex = rand(Chars.high)\n\t\t\t\tmvprintw(columnsRow[i], i, \"%c\", Chars[charIndex])\n\t\t\telse:\n\t\t\t\t# Draw an empty character if the column is inactive.\n\t\t\t\tmvprintw(columnsRow[i], i, \" \")\n\n\t\t\tinc columnsRow[i]\n\t\t\t# When a column reaches the bottom row, reset to top.\n\t\t\tif columnsRow[i] > maxY: columnsRow[i] = -1\n\n\t\t\t# Randomly alternate the column's active status.\n\t\t\tif rand(999) == 0: columnsActive[i] = not columnsActive[i]\n\n\t\tsleep(RowDelay)\n\t\trefresh()\n\nrun()\n" + }, + { + "id": 1221, + "length": 1120, + "source": "Rosetta Code", + "text": "import strformat\nimport strutils\nimport math\n\nconst cutOff = 200\nconst bigUn = 100000\nconst chunks = 50\nconst little = bigUn div chunks\n\necho fmt\"The first {cutOff} cuban primes\"\nvar primes: seq[int] = @[3, 5]\nvar c, u = 0\nvar showEach: bool = true\nvar v = 1\nfor i in 1..high(BiggestInt):\n\tvar found: bool\n\tinc u, 6\n\tinc v, u\n\tvar mx = int(ceil(sqrt(float(v))))\n\tfor item in primes:\n\t\tif item > mx:\n\t\t\tbreak\n\t\tif v mod item == 0:\n\t\t\tfound = true\n\t\t\tbreak\n\tif not found:\n\t\tinc c\n\t\tif showEach:\n\t\t\tfor z in countup(primes[^1] + 2, v - 2, step=2):\n\t\t\t\tvar fnd: bool = false\n\t\t\t\tfor item in primes:\n\t\t\t\t\tif item > mx:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif z mod item == 0:\n\t\t\t\t\t\tfnd = true\n\t\t\t\t\t\tbreak\n\t\t\t\tif not fnd:\n\t\t\t\t\tprimes.add(z)\n\t\t\tprimes.add(v)\n\t\t\twrite(stdout, fmt\"{insertSep($v, ','):>11}\")\n\t\t\tif c mod 10 == 0:\n\t\t\t\twrite(stdout, \"\\n\")\n\t\t\tif c == cutOff:\n\t\t\t\tshowEach = false\n\t\t\t\twrite(stdout, fmt\"Progress to the {bigUn}th cuban prime: \")\n\t\t\t\tstdout.flushFile\n\t\tif c mod little == 0:\n\t\t\twrite(stdout, \".\")\n\t\t\tstdout.flushFile\n\t\t\tif c == bigUn:\n\t\t\t\tbreak\nwrite(stdout, \"\\n\")\necho fmt\"The {c}th cuban prime is {insertSep($v, ',')}\"\n" + }, + { + "id": 1222, + "length": 1521, + "source": "Rosetta Code", + "text": "import algorithm, strutils\n\n# Definition of a range of values of type T.\ntype Range[T] = array[2, T]\n\nproc `<`(a, b: Range): bool {.inline.} =\n\t## Check if range \"a\" is less than range \"b\". Needed for sorting.\n\tif a[0] == b[0]:\n\t\ta[1] < b[1]\n\telse:\n\t\ta[0] < b[0]\n\n\nproc consolidate[T](rangeList: varargs[Range[T]]): seq[Range[T]] =\n\t## Consolidate a list of ranges of type T.\n\n\t# Build a sorted list of normalized ranges.\n\tvar list: seq[Range[T]]\n\tfor item in rangeList:\n\t\tlist.add if item[0] <= item[1]: item else: [item[1], item[0]]\n\tlist.sort()\n\n\t# Build the consolidated list starting from \"smallest\" range.\n\tresult.add list[0]\n\tfor i in 1..list.high:\n\t\tlet rangeMin = result[^1]\n\t\tlet rangeMax = list[i]\n\t\tif rangeMax[0] <= rangeMin[1]:\n\t\t\tresult[^1] = [rangeMin[0], max(rangeMin[1], rangeMax[1])]\n\t\telse:\n\t\t\tresult.add rangeMax\n\n\nproc `$`[T](r: Range[T]): string {.inline.} =\n\t# Return the string representation of a range.\n\twhen T is SomeFloat:\n\t\t\"[$1, $2]\".format(r[0].formatFloat(ffDecimal, 1), r[1].formatFloat(ffDecimal, 1))\n\telse:\n\t\t\"[$1, $2]\".format(r[0], r[1])\n\nproc `$`[T](s: seq[Range[T]]): string {.inline.} =\n\t## Return the string representation of a sequence of ranges.\n\ts.join(\", \")\n\n\nwhen isMainModule:\n\n\tproc test[T](rangeList: varargs[Range[T]]) =\n\t\techo ($(@rangeList)).alignLeft(52), \"-> \", consolidate(rangeList)\n\n\ttest([1.1, 2.2])\n\ttest([6.1, 7.2], [7.2, 8.3])\n\ttest([4, 3], [2, 1])\n\ttest([4.0, 3.0], [2.0, 1.0], [-1.0, -2.0], [3.9, 10.0])\n\ttest([1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6])\n" + }, + { + "id": 1223, + "length": 1273, + "source": "Rosetta Code", + "text": "import strformat\n\nproc iseban(n: int): bool =\n\tif n == 0:\n\t\treturn false\n\tvar b = n div 1_000_000_000\n\tvar r = n mod 1_000_000_000\n\tvar m = r div 1_000_000\n\tr = r mod 1_000_000\n\tvar t = r div 1_000\n\tr = r mod 1_000\n\tm = if m in 30..66: m mod 10 else: m\n\tt = if t in 30..66: t mod 10 else: t\n\tr = if r in 30..66: r mod 10 else: r\n\treturn {b, m, t, r} <= {0, 2, 4, 6}\n\necho \"eban numbers up to and including 1000:\"\nfor i in 0..100:\n\tif iseban(i):\n\t\tstdout.write(\"{i} \")\n\necho \"\\n\\neban numbers between 1000 and 4000 (inclusive):\"\nfor i in 1_000..4_000:\n\tif iseban(i):\n\t\tstdout.write(\"{i} \")\n\nvar count = 0\nfor i in 0..10_000:\n\tif iseban(i):\n\t\tinc count\necho \"\\n\\nNumber of eban numbers up to and including {10000:8}: {count:4}\"\n\ncount = 0\nfor i in 0..100_000:\n\tif iseban(i):\n\t\tinc count\necho \"\\nNumber of eban numbers up to and including {100000:8}: {count:4}\"\n\ncount = 0\nfor i in 0..1_000_000:\n\tif iseban(i):\n\t\tinc count\necho \"\\nNumber of eban numbers up to and including {1000000:8}: {count:4}\"\n\ncount = 0\nfor i in 0..10_000_000:\n\tif iseban(i):\n\t\tinc count\necho \"\\nNumber of eban numbers up to and including {10000000:8}: {count:4}\"\n\ncount = 0\nfor i in 0..100_000_000:\n\tif iseban(i):\n\t\tinc count\necho \"\\nNumber of eban numbers up to and including {100000000:8}: {count:4}\"\n" + }, + { + "id": 1224, + "length": 929, + "source": "Rosetta Code", + "text": "import math, strutils, strformat\n\n\nfunc ebanCount(p10: Natural): Natural =\n\t## Return the count of eban numbers 1..10^p10.\n\tlet\n\t\tn = p10 - p10 div 3\n\t\tp5 = n div 2\n\t\tp4 = (n + 1) div 2\n\tresult = 5^p5 * 4^p4 - 1\n\n\nfunc eban(n: Natural): bool =\n\t## Return true if n is an eban number (only fully tested to 10e9).\n\tif n == 0: return false\n\tvar n = n\n\twhile n != 0:\n\t\tlet thou = n mod 1000\n\t\tif thou div 100 != 0: return false\n\t\tif thou div 10 notin {0, 3, 4, 5, 6}: return false\n\t\tif thou mod 10 notin {0, 2, 4, 6}: return false\n\t\tn = n div 1000\n\tresult = true\n\n\nvar s: seq[Natural]\nfor i in 0..1000:\n\tif eban(i): s.add(i)\necho fmt\"Eban to 1000: {s.join(\"\", \"\")} ({s.len} items)\"\n\ns.setLen(0)\nfor i in 1000..4000:\n\tif eban(i): s.add(i)\necho fmt\"Eban 1000..4000: {s.join(\"\", \"\")} ({s.len} items)\"\n\nimport times\nlet t0 = getTime()\nfor i in 0..21:\n\techo fmt\"ebanCount(10^{i}): {ebanCount(i)}\"\necho \"\"\necho fmt\"Time: {getTime() - t0}\"\n" + }, + { + "id": 1225, + "length": 694, + "source": "Rosetta Code", + "text": "import deques, strformat\n\n\niterator fusc(): int =\n\tvar q = [1].toDeque()\n\tyield 0\n\tyield 1\n\n\twhile true:\n\t\tvar val = q.popFirst()\n\t\tq.addLast(val)\n\t\tyield val\n\n\t\tval += q[0]\n\t\tq.addLast(val)\n\t\tyield val\n\n\niterator longestFusc(): tuple[idx, val: int] =\n\tvar sofar = 0\n\tvar i = -1\n\tfor f in fusc():\n\t\tinc i\n\t\tif f >= sofar:\n\t\t\tyield (i, f)\n\t\t\tsofar = if sofar == 0: 10 else: 10 * sofar\n\n\n\nconst\n\tMaxFusc = 61\n\tLongestCount = 7\n\necho \"First {MaxFusc}:\"\nvar i = -1\nfor f in fusc():\n\tinc i\n\tstdout.write f\n\tif i == MaxFusc:\n\t\techo \"\"\n\t\tbreak\n\tstdout.write ' '\n\necho \"\\nLength records:\"\nvar count = 0\nfor (i, f) in longestFusc():\n\tinc count\n\techo \"fusc({i}) = {f}\"\n\tif count == LongestCount:\n\t\tbreak\n" + }, + { + "id": 1226, + "length": 792, + "source": "Rosetta Code", + "text": "import strformat\nimport strutils\n\nfunc chowla(n: uint64): uint64 =\n\tvar sum = 0u64\n\tvar i = 2u64\n\tvar j: uint64\n\twhile i * i <= n:\n\t\tif n mod i == 0:\n\t\t\tj = n div i\n\t\t\tsum += i\n\t\t\tif i != j:\n\t\t\t\tsum += j\n\t\tinc i\n\tsum\n\nfor n in 1u64..37:\n\techo \"chowla({n}) = {chowla(n)}\"\n\nvar count = 0\nvar power = 100u64\nfor n in 2u64..10_000_000:\n\tif chowla(n) == 0:\n\t\tinc count\n\tif n mod power == 0:\n\t\techo \"There are {insertSep($count, ','):>7} primes < {insertSep($power, ','):>10}\"\n\t\tpower *= 10\n\ncount = 0\nconst limit = 350_000_000u64\nvar k = 2u64\nvar kk = 3u64\nvar p: uint64\nwhile true:\n\tp = k * kk\n\tif p > limit:\n\t\tbreak\n\tif chowla(p) == p - 1:\n\t\techo \"{insertSep($p, ','):>10} is a perfect number\"\n\t\tinc count\n\tk = kk + 1\n\tkk += k\necho \"There are {count} perfect numbers < {insertSep($limit, ',')}\"\n" + }, + { + "id": 1227, + "length": 845, + "source": "Rosetta Code", + "text": "import intsets, strutils, times\n\nproc mianchowla(n: Positive): seq[int] =\n\tresult = @[1]\n\tvar sums = [2].toIntSet()\n\tvar candidate = 1\n\n\twhile result.len < n:\n\t\t# Test successive candidates.\n\t\tvar fit = false\n\t\tresult.add 0 # Make room for next value.\n\t\twhile not fit:\n\t\t\tinc candidate\n\t\t\tfit = true\n\t\t\tresult[^1] = candidate\n\t\t\t# Check the sums.\n\t\t\tfor val in result:\n\t\t\t\tif val + candidate in sums:\n\t\t\t\t\t# Failed to satisfy criterium.\n\t\t\t\t\tfit = false\n\t\t\t\t\tbreak\n\t\t# Add the new sums to the set of sums.\n\t\tfor val in result:\n\t\t\tsums.incl val + candidate\n\nlet t0 = now()\nlet seq100 = mianchowla(100)\necho \"The first 30 terms of the Mian-Chowla sequence are:\"\necho seq100[0..29].join(\" \")\necho \"\"\necho \"Terms 91 to 100 of the sequence are:\"\necho seq100[90..99].join(\" \")\n\necho \"\"\necho \"Computation time: \", (now() - t0).inMilliseconds, \" ms\"\n" + }, + { + "id": 1228, + "length": 1485, + "source": "Rosetta Code", + "text": "import strutils, strformat\n\ntype\n\tNode = ref object\n\t\tkind: char # + = serial * = parallel r = resistor\n\t\tresistance: float\n\t\tvoltage: float\n\t\ta: Node\n\t\tb: Node\n\nproc res(node: Node): float =\n\tif node.kind == '+': return node.a.res + node.b.res\n\tif node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res)\n\tnode.resistance\n\nproc current(node: Node): float = node.voltage / node.res\nproc effect (node: Node): float = node.current * node.voltage\n\nproc report(node: Node, level: string = \"\") =\n\techo fmt\"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f} {level}{node.kind}\"\n\tif node.kind in \"+*\":\n\t\tnode.a.report level & \"| \"\n\t\tnode.b.report level & \"| \"\n\nproc setVoltage(node: Node, voltage: float) =\n\tnode.voltage = voltage\n\tif node.kind == '+':\n\t\tlet ra = node.a.res\n\t\tlet rb = node.b.res\n\t\tnode.a.setVoltage ra / (ra+rb) * voltage\n\t\tnode.b.setVoltage rb / (ra+rb) * voltage\n\tif node.kind == '*':\n\t\tnode.a.setVoltage voltage\n\t\tnode.b.setVoltage voltage\n\nproc build(tokens: seq[string]): Node =\n\tvar stack: seq[Node]\n\tfor token in tokens:\n\t\tstack.add if token == \"+\": Node(kind: '+', a: stack.pop, b: stack.pop)\n\t\t\t\t\t\t\telif token == \"*\": Node(kind: '*', a: stack.pop, b: stack.pop)\n\t\t\t\t\t\t\telse: Node(kind: 'r', resistance: parseFloat(token))\n\tstack.pop\n\nproc calculate(voltage: float, tokens: seq[string]): Node =\n\techo \"\"\n\techo \" Ohm Volt Ampere Watt Network tree\"\n\tlet node = build tokens\n\tnode.setVoltage voltage\n\tnode.report\n\tnode\n" + }, + { + "id": 1229, + "length": 1099, + "source": "Rosetta Code", + "text": "proc parse(s: string): seq[string] =\n\tvar tmp = \"\"\n\tfor ch in s:\n\t\tcase ch\n\t\tof ' ':\n\t\t\tif tmp != \"\": result.add tmp\n\t\t\ttmp = \"\"\n\t\t\tcontinue\n\t\tof '+', '*', '(', ')':\n\t\t\tif tmp != \"\": result.add tmp\n\t\t\ttmp = \"\"\n\t\t\tresult.add $ch\n\t\telse:\n\t\t\ttmp &= ch\n\tif tmp != \"\": result.add tmp\n\nproc shuntRPN(s: string): seq[string] =\n\tlet ops = \"+*\"\n\tvar tokens = parse s\n\tvar stack: seq[string]\n\tvar op: string\n\n\tfor token in tokens:\n\t\tcase token\n\t\tof \"(\":\n\t\t\tstack.add token\n\t\tof \")\":\n\t\t\twhile stack.len > 0:\n\t\t\t\top = stack.pop()\n\t\t\t\tif op == \"(\": break\n\t\t\t\tresult.add op\n\t\telse:\n\t\t\tif token in ops:\n\t\t\t\twhile stack.len > 0:\n\t\t\t\t\top = stack[^1]\n\t\t\t\t\tif op notin ops: break\n\t\t\t\t\tif ops.find(token) >= ops.find(op): break\n\t\t\t\t\tdiscard stack.pop()\n\t\t\t\t\tresult.add op\n\t\t\t\tstack.add token\n\t\t\telse: result.add token\n\n\twhile stack.len > 0: result.add stack.pop()\n\nproc infix(voltage:float, s:string): Node = calculate(voltage, shuntRPN s)\nnode = infix(18, \"((((10+2)*6+8)*6+4)*8+4)*8+6\")\nassert 10 == node.res\nassert 18 == node.voltage\nassert 1.8 == node.current()\nassert 32.4 == node.effect()\nassert '+' == node.kind\n" + }, + { + "id": 1230, + "length": 1081, + "source": "Rosetta Code", + "text": "import algorithm, math, strutils\n\nfunc divisors(n: int): seq[int] =\n\tvar smallDivs = @[1]\n\tfor i in 2..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tlet j = n div i\n\t\t\tsmallDivs.add i\n\t\t\tif i != j: result.add j\n\tresult.add reversed(smallDivs)\n\nfunc abundant(n: int; divs: seq[int]): bool {.inline.}=\n\tsum(divs) > n\n\nfunc semiperfect(n: int; divs: seq[int]): bool =\n\tif divs.len > 0:\n\t\tlet h = divs[0]\n\t\tlet t = divs[1..^1]\n\t\tresult = if n < h: semiperfect(n, t)\n\t\t\t\t\t\t else: n == h or semiperfect(n - h, t) or semiperfect(n, t)\n\nfunc sieve(limit: int): seq[bool] =\n\t# False denotes abundant and not semi-perfect.\n\t# Only interested in even numbers >= 2.\n\tresult.setLen(limit)\n\tfor i in countup(2, limit - 1, 2):\n\t\tif result[i]: continue\n\t\tlet divs = divisors(i)\n\t\tif not abundant(i, divs):\n\t\t\tresult[i] = true\n\t\telif semiperfect(i, divs):\n\t\t\tfor j in countup(i, limit - 1, i):\n\t\t\t\tresult[j] = true\n\n\nconst Max = 25\nlet w = sieve(17_000)\nvar list: seq[int]\n\necho \"The first 25 weird numbers are:\"\nvar n = 2\nwhile list.len != Max:\n\tif not w[n]: list.add n\n\tinc n, 2\necho list.join(\" \")\n" + }, + { + "id": 1231, + "length": 1633, + "source": "Rosetta Code", + "text": "import rationals, sequtils, strscans, strutils, sugar\n\ntype Fraction = Rational[int]\n\n\nfunc argmax(m: seq[seq[Fraction]]; i: int): int =\n\tvar max = -1 // 1\n\tfor x in i..m.high:\n\t\tlet val = abs(m[x][i])\n\t\tif val > max:\n\t\t\tmax = val\n\t\t\tresult = x\n\n\nfunc gauss(m: var seq[seq[Fraction]]): seq[Fraction] =\n\tlet n = m.len\n\tlet p = m[0].len\n\n\tfor i in 0.. 0: m[a][b] -= r\n\t\tif b > 0: m[b][a] -= r\n\tm[k0][k0] = 1 // 1\n\tm[k1][^1] = 1 // 1\n\tresult = gauss(m)[k1]\n\n\nassert 10 // 1 == network(7, 0, 1, \"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8\")\nassert 3 // 2 == network(3*3, 0, 3*3-1, \"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1\")\nassert 13 // 7 == network(4*4, 0, 4*4-1, \"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1\")\nassert 180 // 1 == network(4, 0, 3, \"0 1 150|0 2 50|1 3 300|2 3 250\")\n" + }, + { + "id": 1232, + "length": 876, + "source": "Rosetta Code", + "text": "import strformat\n\nconst MAX = 120\n\nproc isPrime(n: int): bool =\n\tvar d = 5\n\tif n < 2:\n\t\treturn false\n\tif n mod 2 == 0:\n\t\treturn n == 2\n\tif n mod 3 == 0:\n\t\treturn n == 3\n\twhile d * d <= n:\n\t\tif n mod d == 0:\n\t\t\treturn false\n\t\tinc d, 2\n\t\tif n mod d == 0:\n\t\t\treturn false\n\t\tinc d, 4\n\treturn true\n\nproc countPrimeFactors(n_in: int): int =\n\tvar count = 0\n\tvar f = 2\n\tvar n = n_in\n\tif n == 1:\n\t\treturn 0\n\tif isPrime(n):\n\t\treturn 1\n\twhile true:\n\t\tif n mod f == 0:\n\t\t\tinc count\n\t\t\tn = n div f\n\t\t\tif n == 1:\n\t\t\t\treturn count\n\t\t\tif isPrime(n):\n\t\t\t\tf = n\n\t\telif (f >= 3):\n\t\t\tinc f, 2\n\t\telse:\n\t\t\tf = 3\n\nproc main() =\n\tvar n, count: int = 0\n\techo fmt\"The attractive numbers up to and including {MAX} are:\"\n\tfor i in 1..MAX:\n\t\tn = countPrimeFactors(i)\n\t\tif isPrime(n):\n\t\t\twrite(stdout, fmt\"{i:4d}\")\n\t\t\tinc count\n\t\t\tif count mod 20 == 0:\n\t\t\t\twrite(stdout, \"\\n\")\n\twrite(stdout, \"\\n\")\n\nmain()\n" + }, + { + "id": 1233, + "length": 1706, + "source": "Rosetta Code", + "text": "import math, strformat\nimport bignum\n\ntype Record = tuple[num, count: Natural]\n\ntemplate isOdd(n: Natural): bool =\n\t(n and 1) != 0\n\nfunc isPrime(n: int): bool =\n\tlet bi = newInt(n)\n\tresult = bi.probablyPrime(25) != 0\n\nproc findPrimes(limit: Natural): seq[int] {.compileTime.} =\n\tresult = @[2]\n\tvar isComposite = newSeq[bool](limit + 1)\n\tvar p = 3\n\twhile true:\n\t\tlet p2 = p * p\n\t\tif p2 > limit: break\n\t\tfor i in countup(p2, limit, 2 * p):\n\t\t\tisComposite[i] = true\n\t\twhile true:\n\t\t\tinc p, 2\n\t\t\tif not isComposite[p]: break\n\tfor n in countup(3, limit, 2):\n\t\tif not isComposite[n]:\n\t\t\tresult.add n\n\nconst Primes = findPrimes(22_000)\n\nproc countDivisors(n: Natural): int =\n\tresult = 1\n\tvar n = n\n\tfor i, p in Primes:\n\t\tif p * p > n: break\n\t\tif n mod p != 0: continue\n\t\tn = n div p\n\t\tvar count = 1\n\t\twhile n mod p == 0:\n\t\t\tn = n div p\n\t\t\tinc count\n\t\tresult *= count + 1\n\t\tif n == 1: return\n\tif n != 1: result *= 2\n\nconst Max = 45\nvar records: array[0..Max, Record]\necho \"The first {Max} terms in the sequence are:\"\n\nfor n in 1..Max:\n\n\tif n.isPrime:\n\t\tvar z = newInt(Primes[n - 1])\n\t\tz = pow(z, culong(n - 1))\n\t\techo \"{n:2}: {z}\"\n\n\telse:\n\t\tvar count = records[n].count\n\t\tif count == n:\n\t\t\techo \"{n:2}: {records[n].num}\"\n\t\t\tcontinue\n\t\tlet odd = n.isOdd\n\t\tlet d = if odd or n == 2 or n == 10: 1 else: 2\n\t\tvar k = records[n].num\n\t\twhile true:\n\t\t\tinc k, d\n\t\t\tif odd:\n\t\t\t\tlet sq = sqrt(k.toFloat).int\n\t\t\t\tif sq * sq != k: continue\n\t\t\tlet cd = k.countDivisors()\n\t\t\tif cd == n:\n\t\t\t\tinc count\n\t\t\t\tif count == n:\n\t\t\t\t\techo \"{n:2}: {k}\"\n\t\t\t\t\tbreak\n\t\t\telif cd in (n + 1)..Max and records[cd].count < cd and\n\t\t\t\t\t k > records[cd].num and (d == 1 or d == 2 and not cd.isOdd):\n\t\t\t\trecords[cd].num = k\n\t\t\t\tinc records[cd].count\n" + }, + { + "id": 1234, + "length": 1383, + "source": "Rosetta Code", + "text": "import re, terminal\n\nconst Colors = [((15, 0, 0), fgRed),\n\t\t\t\t\t\t\t\t(( 0, 15, 0), fgGreen),\n\t\t\t\t\t\t\t\t((15, 15, 0), fgYellow),\n\t\t\t\t\t\t\t\t(( 0, 0, 15), fgBlue),\n\t\t\t\t\t\t\t\t((15, 0, 15), fgMagenta),\n\t\t\t\t\t\t\t\t(( 0, 15, 15), fgCyan)]\n\nlet Re = re\"^([A-Fa-f0-9]+)([ \\t]+.+)$\"\n\ntype RGB = tuple[r, g, b: int]\n\nfunc squareDist(c1, c2: RGB): int =\n\tlet xd = c1.r - c2.r\n\tlet yd = c1.g - c2.g\n\tlet zd = c1.b - c2.b\n\tresult = xd * xd + yd * yd + zd * zd\n\n\nfunc intValue(c: char): int =\n\tcase c\n\tof 'a'..'f': ord(c) - ord('a') + 10\n\tof 'A'..'F': ord(c) - ord('A') + 10\n\tof '0'..'9': ord(c) - ord('0')\n\telse: raise newException(ValueError, \"incorrect input\")\n\n\nproc printColor(s: string) =\n\tvar k = 0\n\tfor i in 0..<(s.len div 3):\n\t\tlet j = i * 3\n\t\tlet c1 = s[j]\n\t\tlet c2 = s[j+1]\n\t\tlet c3 = s[j+2]\n\t\tk = j + 3\n\t\tlet rgb: RGB = (c1.intValue(), c2.intValue(), c3.intValue())\n\t\tvar m = 676\n\t\tvar color = fgDefault\n\t\tfor cex in Colors:\n\t\t\tlet sqd = squareDist(cex[0], rgb)\n\t\t\tif sqd < m:\n\t\t\t\tcolor = cex[1]\n\t\t\t\tm = sqd\n\t\tstdout.setForegroundColor(color)\n\t\tstdout.write c1, c2, c3\n\n\tsetForegroundColor(fgDefault)\n\tfor j in k..s.high: stdout.write s[j]\n\n\nproc colorChecksum() =\n\tfor line in stdin.lines:\n\t\tvar s: array[2, string]\n\t\tif line.match(Re, s):\n\t\t\tprintColor(s[0])\n\t\t\techo s[1]\n\t\telse:\n\t\t\techo line\n\nproc cat() =\n\tfor line in stdin.lines: echo line\n\nif stdout.isatty: colorChecksum()\nelse: cat()\n" + }, + { + "id": 1235, + "length": 741, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport decimal\n\nsetPrec(75)\nlet pi = newDecimal(\"3.1415926535897932384626433832795028841971693993751058209749445923078164\")\n\nproc eval(n: int): DecimalType =\n\tresult = exp(pi * sqrt(newDecimal(n)))\n\nfunc format(n: DecimalType; d: Positive): string =\n\t## Return the representation of \"n\" with \"d\" digits of precision.\n\tlet parts = ($n).split('.')\n\tresult = parts[0] & '.' & parts[1][0.. 0: \"+ \" & $d else: \"- \" & $(-d)\n\techo \"{n:3}: {x}... = {k:>18} {s}...\"\n" + }, + { + "id": 1236, + "length": 1236, + "source": "Rosetta Code", + "text": "from math import sqrt\nimport strformat\n\n\nproc sumProperDivisors(n: int): int =\n\t## Compute the sum of proper divisors.\n\t## \"n\" is supposed to be odd.\n\tresult = 1\n\tfor d in countup(3, sqrt(n.toFloat).int, 2):\n\t\tif n mod d == 0:\n\t\t\tinc result, d\n\t\t\tif n div d != d:\n\t\t\t\tinc result, n div d\n\n\niterator oddAbundant(start: int): tuple[n, s: int] =\n\t## Yield the odd abundant numbers and the sum of their proper\n\t## divisors greater or equal to \"start\".\n\tvar n = start + (start and 1 xor 1) # Start with an odd number.\n\twhile true:\n\t\tlet s = n.sumProperDivisors()\n\t\tif s > n:\n\t\t\tyield (n, s)\n\t\tinc n, 2\n\n\necho \"List of 25 first odd abundant numbers.\"\necho \"Rank Number Proper divisors sum\"\necho \"---- ----- -------------------\"\nvar rank = 0\nfor (n, s) in oddAbundant(1):\n\tinc rank\n\techo fmt\"{rank:2}: {n:5} {s:5}\"\n\tif rank == 25:\n\t\tbreak\n\necho \"\"\nrank = 0\nfor (n, s) in oddAbundant(1):\n\tinc rank\n\tif rank == 1000:\n\t\techo fmt\"The 1000th odd abundant number is {n}.\"\n\t\techo fmt\"The sum of its proper divisors is {s}.\"\n\t\tbreak\n\necho \"\"\nfor (n, s) in oddAbundant(1_000_000_000):\n\tif n > 1_000_000_000:\n\t\techo fmt\"The first odd abundant number greater than 1000000000 is {n}.\"\n\t\techo fmt\"The sum of its proper divisors is {s}.\"\n\t\tbreak\n" + }, + { + "id": 1237, + "length": 977, + "source": "Rosetta Code", + "text": "import math, strformat, strutils\n\nconst N = 35_000\n\n# Sieve.\nvar composite: array[0..N, bool] # Default is false and means prime.\ncomposite[0] = true\ncomposite[1] = true\nfor n in 2..sqrt(N.toFloat).int:\n\tif not composite[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tcomposite[k] = true\n\n\nfunc digits(n: Positive): seq[0..9] =\n\tvar n = n.int\n\twhile n != 0:\n\t\tresult.add n mod 10\n\t\tn = n div 10\n\n\nproc isSPDS(n: int): bool =\n\tif composite[n]: return false\n\tresult = true\n\tfor d in n.digits:\n\t\tif composite[d]: return false\n\n\niterator spds(maxCount: Positive): int {.closure.} =\n\tyield 2\n\tvar count = 1\n\tvar n = 3\n\twhile count != maxCount and n <= N:\n\t\tif n.isSPDS:\n\t\t\tinc count\n\t\t\tyield n\n\t\tinc n, 2\n\tif count != maxCount:\n\t\tquit \"Too few values ({count}). Please, increase value of N.\", QuitFailure\n\n\nstdout.write \"The first 25 SPDS are:\"\nfor n in spds(25):\n\tstdout.write ' ', n\necho()\n\nvar count = 0\nfor n in spds(100):\n\tinc count\n\tif count == 100:\n\t\techo \"The 100th SPDS is: \", n\n" + }, + { + "id": 1238, + "length": 1958, + "source": "Rosetta Code", + "text": "import gintro/[gobject, glib, gdk, gtk, gio, cairo]\n\n\nconst Palette = [[166.0, 124.0, 0.0],\n\t\t\t\t\t\t\t\t [191.0, 155.0, 48.0],\n\t\t\t\t\t\t\t\t [255.0, 191.0, 0.0],\n\t\t\t\t\t\t\t\t [255.0, 207.0, 64.0],\n\t\t\t\t\t\t\t\t [255.0, 220.0, 115.0]]\n\ntype\n\n\t# Description of the simulation.\n\tSimulation = ref object\n\t\tarea: DrawingArea\n\t\thorizontal: bool\n\t\tpaletteIndex: Natural\n\t\tcount: int\n\n\tColor = array[3, float]\n\n\n\nproc newSimulation(area: DrawingArea): Simulation {.noInit.} =\n\t## Allocate and initialize the simulation object.\n\tSimulation(area: area, horizontal: true, paletteIndex: 0, count: 0)\n\n\nproc bar(ctx: cairo.Context; x1, y1, x2, y2: int; c: Color) =\n\t## Draw a bar.\n\tctx.setSource(c)\n\tctx.rectangle(x1.toFloat, y1.toFloat, (x2 - x1 + 1).toFloat, (y2 - y1 + 1).toFloat)\n\tctx.fill()\n\n\nproc draw(sim: Simulation; ctx: cairo.Context) =\n\t## Draw the bars.\n\n\tlet width = sim.area.window.width()\n\tlet height = sim.area.window.height()\n\n\tif sim.horizontal:\n\t\tfor i in countup(0, height - 4, 3):\n\t\t\tctx.bar(0, i, width - 1, i + 3, Palette[sim.paletteIndex])\n\t\t\tsim.paletteIndex = (sim.paletteIndex + 1) mod 5\n\n\telse:\n\t\tfor i in countup(0, width - 4, 3):\n\t\t\tctx.bar(i, 0, i + 3, height - 1, Palette[sim.paletteIndex])\n\t\t\tsim.paletteIndex = (sim.paletteIndex + 1) mod 5\n\n\nproc update(sim: Simulation): gboolean =\n\t## Update the simulation state.\n\n\tsim.draw(sim.area.window.cairoCreate())\n\tsim.area.showAll()\n\tsim.paletteIndex = (sim.paletteIndex + 2) mod 5\n\tinc sim.count\n\tif sim.count mod 30 == 29:\n\t\tsim.horizontal = not sim.horizontal\n\tresult = gboolean(1)\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(500, 500)\n\twindow.setTitle(\"Raster Bar Demo\")\n\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\tlet sim = newSimulation(area)\n\ttimeoutAdd(50, update, sim)\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Rasterbars\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 1239, + "length": 911, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\n\ntype LatinSquare = seq[seq[char]]\n\nproc get[T](s: set[T]): T =\n\t## Return the first element of a set.\n\tfor n in s:\n\t\treturn n\n\nproc letterAt(n: Natural): char {.inline.} = chr(ord('A') - 1 + n)\n\n\nproc latinSquare(n: Positive): LatinSquare =\n\tresult = newSeqWith(n, toSeq(letterAt(1)..letterAt(n)))\n\tresult[0].shuffle()\n\n\tfor row in 1..(n - 2):\n\t\tvar ok = false\n\t\twhile not ok:\n\t\t\tblock shuffling:\n\t\t\t\tresult[row].shuffle()\n\t\t\t\tfor prev in 0.. tolerance:\n\t\t# Calculate next value.\n\t\tfor i in 0.. g0: alpha *= 0.5\n\t\telse: g0 = g1\n\n\nwhen isMainModule:\n\n\tfunc g(x: openArray[float]): float =\n\t\t## Function for which minimum is to be found.\n\t\t(x[0]-1) * (x[0]-1) * exp(-x[1]*x[1]) + x[1] * (x[1]+2) * exp(-2*x[0]*x[0])\n\n\tfunc gradG(p: openArray[float]): seq[float] =\n\t\t## Provides a rough calculation of gradient g(p).\n\t\tresult = newSeq[float](p.len)\n\t\tlet x = p[0]\n\t\tlet y = p[1]\n\t\tresult[0] = 2 * (x-1) * exp(-y*y) - 4 * x * exp(-2*x*x) * y * (y+2)\n\t\tresult[1] = -2 * (x-1) * (x-1) * y * exp(-y*y) + 2 * (y+1) * exp(-2*x*x)\n\n\tconst\n\t\tTolerance = 0.0000006\n\t\tAlpha = 0.1\n\n\tvar x = [0.1, -1.0] # Initial guess of location of minimum.\n\n\tsteepDescent(g, gradG, x, Alpha, Tolerance)\n\techo \"Testing steepest descent method:\"\n\techo \"The minimum is at x = {x[0]:.12f}, y = {x[1]:.12f} for which f(x, y) = {g(x):.12f}\"\n" + }, + { + "id": 1241, + "length": 1106, + "source": "Rosetta Code", + "text": "iterator b(): int =\n\t## Iterator yielding the bell numbers.\n\tvar row = @[1]\n\tyield 1\n\tyield 1\n\twhile true:\n\t\tvar newRow = newSeq[int](row.len + 1)\n\t\tnewRow[0] = row[^1]\n\t\tfor i in 1..newRow.high:\n\t\t\tnewRow[i] = newRow[i - 1] + row[i - 1]\n\t\trow.shallowCopy(newRow)\n\t\tyield row[^1] # The last value of the row is one step ahead of the first one.\n\niterator bellTriangle(): seq[int] =\n\t## Iterator yielding the rows of the Bell triangle.\n\tvar row = @[1]\n\tyield row\n\twhile true:\n\t\tvar newRow = newSeq[int](row.len + 1)\n\t\tnewRow[0] = row[^1]\n\t\tfor i in 1..newRow.high:\n\t\t\tnewRow[i] = newRow[i - 1] + row[i - 1]\n\t\trow.shallowCopy(newRow)\n\t\tyield row\n\nwhen isMainModule:\n\n\timport strformat\n\timport strutils\n\n\tconst Limit = 25 # Maximum index beyond which an overflow occurs.\n\n\techo \"Bell numbers from B0 to B25:\"\n\tvar i = 0\n\tfor n in b():\n\t\techo fmt\"{i:2d}: {n:>20d}\"\n\t\tinc i\n\t\tif i > Limit:\n\t\t\tbreak\n\n\techo \"\\nFirst ten rows of Bell triangle:\"\n\ti = 0\n\tfor row in bellTriangle():\n\t\tinc i\n\t\tvar line = \"\"\n\t\tfor val in row:\n\t\t\tline.addSep(\" \", 0)\n\t\t\tline.add(fmt\"{val:6d}\")\n\t\techo line\n\t\tif i == 10:\n\t\t\tbreak\n" + }, + { + "id": 1242, + "length": 2768, + "source": "Rosetta Code", + "text": "import algorithm, math, sequtils, strformat\n\ntype\n\n\t# Row managed as a sequence of ints with base index 1.\n\tRow = object\n\t\tvalue: seq[int]\n\n\t# Matrix managed as a sequence of rows with base index 1.\n\tMatrix = object\n\t\tvalue: seq[Row]\n\nfunc newRow(n: Natural = 0): Row =\n\t## Create a new row of length \"n\".\n\tRow(value: newSeq[int](n))\n\n# Create a new matrix of length \"n\" containing rows of length \"p\".\nfunc newMatrix(n, p: Natural = 0): Matrix = Matrix(value: newSeqWith(n, newRow(p)))\n\n# Functions for rows.\nfunc `[]`(r: var Row; i: int): var int = r.value[i - 1]\nfunc `[]=`(r: var Row; i, n: int) = r.value[i - 1] = n\nfunc sort(r: var Row; low, high: Positive) =\n\tr.value.toOpenArray(low - 1, high - 1).sort()\nfunc `$`(r: Row): string = ($r.value)[1..^1]\n\n# Functions for matrices.\nfunc `[]`(m: Matrix; i: int): Row = m.value[i - 1]\nfunc `[]`(m: var Matrix; i: int): var Row = m.value[i - 1]\nfunc `[]=`(m: var Matrix; i: int; r: Row) = m.value[i - 1] = r\nfunc high(m: Matrix): Natural = m.value.len\nfunc add(m: var Matrix; r: Row) = m.value.add r\nfunc `$`(m: Matrix): string =\n\tfor row in m.value: result.add $row & '\\n'\n\n\nfunc dList(n, start: Positive): Matrix =\n\t## Generate derangements of first 'n' numbers, with 'start' in first place.\n\n\tvar a = Row(value: toSeq(1..n))\n\n\tswap a[1], a[start]\n\ta.sort(2, n)\n\tlet first = a[2]\n\tvar r: Matrix\n\n\tfunc recurse(last: int) =\n\t\t## Recursive closure permutes a[2..^1].\n\t\tif last == first:\n\t\t\t# Bottom of recursion. You get here once for each permutation.\n\t\t\t# Test if permutation is deranged.\n\t\t\tfor i in 2..n:\n\t\t\t\tif a[i] == i: return # No: ignore it.\n\t\t\tr.add a\n\t\t\treturn\n\t\tfor i in countdown(last, 2):\n\t\t\tswap a[i], a[last]\n\t\t\trecurse(last - 1)\n\t\t\tswap a[i], a[last]\n\n\trecurse(n)\n\tresult = r\n\n\nproc reducedLatinSquares(n: Positive; print: bool): int =\n\n\tif n == 1:\n\t\tif print: echo [1]\n\t\treturn 1\n\n\tvar rlatin = newMatrix(n, n)\n\t# Initialize first row.\n\tfor i in 1..n: rlatin[1][i] = i\n\n\tvar count = 0\n\n\tproc recurse(i: int) =\n\t\tlet rows = dList(n, i)\n\t\tfor r in 1..rows.high:\n\t\t\tblock inner:\n\t\t\t\trlatin[i] = rows[r]\n\t\t\t\tfor k in 1.. 2: return\n\t\t\t\tif i < n:\n\t\t\t\t\trecurse(i + 1)\n\t\t\t\telse:\n\t\t\t\t\tinc count\n\t\t\t\t\tif print: echo rlatin\n\n\t# Remaining rows.\n\trecurse(2)\n\tresult = count\n\n\nwhen isMainModule:\n\n\techo \"The four reduced latin squares of order 4 are:\"\n\tdiscard reducedLatinSquares(4, true)\n\n\techo \"The size of the set of reduced latin squares for the following orders\"\n\techo \"and hence the total number of latin squares of these orders are:\"\n\tfor n in 1..6:\n\t\tlet size = reducedLatinSquares(n, false)\n\t\tlet f = fac(n - 1)^2 * n * size\n\t\techo \"Order {n}: Size {size:<4} x {n}! x {n - 1}! => Total {f}\"\n" + }, + { + "id": 1243, + "length": 2351, + "source": "Rosetta Code", + "text": "import math\nimport strformat\n\nconst Values = [float -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]\n\nfunc d2d(x: float): float {.inline.} = x mod 360\nfunc g2g(x: float): float {.inline.} = x mod 400\nfunc m2m(x: float): float {.inline.} = x mod 6400\nfunc r2r(x: float): float {.inline.} = x mod (2 * Pi)\n\nfunc d2g(x: float): float {.inline.} = d2d(x) * 10 / 9\nfunc d2m(x: float): float {.inline.} = d2d(x) * 160 / 9\nfunc d2r(x: float): float {.inline.} = d2d(x) * Pi / 180\n\nfunc g2d(x: float): float {.inline.} = g2g(x) * 9 / 10\nfunc g2m(x: float): float {.inline.} = g2g(x) * 16\nfunc g2r(x: float): float {.inline.} = g2g(x) * Pi / 200\n\nfunc m2d(x: float): float {.inline.} = m2m(x) * 9 / 160\nfunc m2g(x: float): float {.inline.} = m2m(x) / 16\nfunc m2r(x: float): float {.inline.} = m2m(x) * Pi / 3200\n\nfunc r2d(x: float): float {.inline.} = r2r(x) * 180 / Pi\nfunc r2g(x: float): float {.inline.} = r2r(x) * 200 / Pi\nfunc r2m(x: float): float {.inline.} = r2r(x) * 3200 / Pi\n\n# Normalizing and converting degrees.\necho \" Degrees Normalized Gradians Mils Radians\"\necho \"-----------------------------------------------------------------------------------\"\nfor val in Values:\n\techo fmt\"{val:15.7f} {d2d(val):15.7f} {d2g(val):15.7f} {d2m(val):15.7f} {d2r(val):15.7f}\"\n\n# Normalizing and converting gradians.\necho \"\"\necho \" Gradians Normalized Degrees Mils Radians\"\necho \"-----------------------------------------------------------------------------------\"\nfor val in Values:\n\techo fmt\"{val:15.7f} {g2g(val):15.7f} {g2d(val):15.7f} {g2m(val):15.7f} {g2r(val):15.7f}\"\n\n# Normalizing and converting mils.\necho \"\"\necho \" Mils Normalized Degrees Gradians Radians\"\necho \"-----------------------------------------------------------------------------------\"\nfor val in Values:\n\techo fmt\"{val:15.7f} {m2m(val):15.7f} {m2d(val):15.7f} {m2g(val):15.7f} {m2r(val):15.7f}\"\n\n# Normalizing and converting radians.\necho \"\"\necho \" Radians Normalized Degrees Gradians Mils\"\necho \"-----------------------------------------------------------------------------------\"\nfor val in Values:\n\techo fmt\"{val:15.7f} {r2r(val):15.7f} {r2d(val):15.7f} {r2g(val):15.7f} {r2m(val):15.7f}\"\n" + }, + { + "id": 1244, + "length": 994, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc shouldSwap(s: string; start, curr: int): bool =\n\tfor i in start..= n:\n\t\tres.add s\n\t\treturn\n\tvar s = s\n\tfor i in index..= 3:\n\t\tblock checkWord:\n\t\t\tvar w = word\n\t\t\tfor _ in 1..w.len:\n\t\t\t\tw.rotate()\n\t\t\t\tif w notin words or w in result:\n\t\t\t\t\t# Not present in dictionary or already encountered.\n\t\t\t\t\tbreak checkWord\n\t\t\tif word.anyIt(it != word[0]):\n\t\t\t\t# More then one letter.\n\t\t\t\tresult.add word\n\nfor word in result:\n\tvar w = word\n\tstdout.write w\n\tfor _ in 2..w.len:\n\t\tw.rotate()\n\t\tstdout.write \" -> \", w\n\techo()\n" + }, + { + "id": 1246, + "length": 3863, + "source": "Rosetta Code", + "text": "import random, sequtils, strformat, tables, times\n\ntype\n\tVector = seq[int]\n\tMatrix = seq[Vector]\n\tCube = seq[Matrix]\n\tArray16 = array[16, int]\n\tArray25 = array[25, int]\n\n\nfunc newCube(m: Matrix; n: Positive): Cube =\n\tresult.setLen(n)\n\tfor i in 0.. 1: stdout.write \", \"\n\tif (count - 1) mod 8 == 0: echo()\n\tstdout.write \"{count:2}({freq:3})\"\necho '\\n'\n\n# Part 3.\necho \"\\nPart 3: 750 latin squares of order 42, showing the last one:\\n\"\nvar m42: Matrix\nc = newCube(@[], 42)\nfor i in 1..750:\n\tc.shuffle()\n\tif i == 750:\n\t\tm42 = c.toMatrix\nprintMatrix(m42)\n\n# Part 4.\necho \"\\nPart 4: 1000 latin squares of order 256:\\n\"\nlet start = cpuTime()\nc = newCube(@[], 256)\nfor _ in 1..1000:\n\tc.shuffle()\necho \"Generated in {cpuTime() - start:.3f} s.\"\n" + }, + { + "id": 1247, + "length": 772, + "source": "Rosetta Code", + "text": "import os, math, terminal\n\nproc rocket() =\n\techo \" /..\\\\\\n |==|\\n | |\\n | |\\n\",\n\t\t\t \" | |\\n /____\\\\\\n | |\\n |SATU|\\n | |\\n\",\n\t\t\t \" | |\\n /| | |\\\\\\n / | | | \\\\\\n /__|_|__|__\\\\\\n /_\\\\/_\\\\\\n\"\n\nproc exhaust() =\n\techo \" *****\"\n\nproc countDown(secs: Natural) =\n\tstdout.write \"Countdown...T minus \"\n\tstdout.flushFile\n\tfor i in countdown(secs, 1):\n\t\tstdout.write i, \"... \"\n\t\tstdout.flushFile\n\t\tos.sleep(1000)\n\tstdout.write \"LIFTOFF!\"\n\tstdout.flushFile\n\nproc engineBurn(rows: Natural) =\n\techo '\\n'\n\tfor i in 1..rows:\n\t\texhaust()\n\t\tsleep (0.9^i * 1000).toInt\n\nproc testRocket() =\n\teraseScreen()\n\trocket()\n\tcursorUp(16)\n\tcountDown(5)\n\tcursorDown(13)\n\tengineBurn(30)\n\ntestRocket()\n" + }, + { + "id": 1248, + "length": 1389, + "source": "Rosetta Code", + "text": "proc isPrime(n: Positive): bool =\n\t## Check if a number is prime.\n\tif n mod 2 == 0:\n\t\treturn n == 2\n\tif n mod 3 == 0:\n\t\treturn n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0:\n\t\t\treturn false\n\t\tif n mod (d + 2) == 0:\n\t\t\treturn false\n\t\tinc d, 6\n\tresult = true\n\nproc sameDigits(n, b: Positive): bool =\n\t## Check if the digits of \"n\" in base \"b\" are all the same.\n\tvar d = n mod b\n\tvar n = n div b\n\tif d == 0:\n\t\treturn false\n\twhile n > 0:\n\t\tif n mod b != d:\n\t\t\treturn false\n\t\tn = n div b\n\tresult = true\n\nproc isBrazilian(n: Positive): bool =\n\t## Check if a number is brazilian.\n\tif n < 7:\n\t\treturn false\n\tif (n and 1) == 0:\n\t\treturn true\n\tfor b in 2..(n - 2):\n\t\tif sameDigits(n, b):\n\t\t\treturn true\n\n\nwhen isMainModule:\n\timport strutils\n\n\ttemplate printList(title: string; findNextToCheck: untyped) =\n\t\t## Template to print a list of brazilians numbers.\n\t\t## \"findNextTocheck\" is a list of instructions to find the\n\t\t## next candidate starting for the current one \"n\".\n\n\t\tblock:\n\t\t\techo '\\n' & title\n\t\t\tvar n {.inject.} = 7\n\t\t\tvar list: seq[int]\n\t\t\twhile true:\n\t\t\t\tif n.isBrazilian():\n\t\t\t\t\tlist.add(n)\n\t\t\t\t\tif list.len == 20: break\n\t\t\t\tfindNextToCheck\n\t\t\techo list.join(\", \")\n\n\n\tprintList(\"First 20 Brazilian numbers:\"):\n\t\tinc n\n\n\tprintList(\"First 20 odd Brazilian numbers:\"):\n\t\tinc n, 2\n\n\tprintList(\"First 20 prime Brazilian numbers:\"):\n\t\tinc n, 2\n\t\twhile not n.isPrime():\n\t\t\tinc n, 2\n" + }, + { + "id": 1249, + "length": 677, + "source": "Rosetta Code", + "text": "from math import fac\nfrom strutils import join\n\niterator digits(n, base: Natural): Natural =\n\t## Yield the digits of \"n\" in base \"base\".\n\tvar n = n\n\twhile true:\n\t\tyield n mod base\n\t\tn = n div base\n\t\tif n == 0: break\n\nfunc isFactorion(n, base: Natural): bool =\n\t## Return true if \"n\" is a factorion for base \"base\".\n\tvar s = 0\n\tfor d in n.digits(base):\n\t\tinc s, fac(d)\n\tresult = s == n\n\nfunc factorions(base, limit: Natural): seq[Natural] =\n\t## Return the list of factorions for base \"base\" up to \"limit\".\n\tfor n in 1..limit:\n\t\tif n.isFactorion(base):\n\t\t\tresult.add(n)\n\n\nfor base in 9..12:\n\techo \"Factorions for base \", base, ':'\n\techo factorions(base, 1_500_000 - 1).join(\" \")\n" + }, + { + "id": 1250, + "length": 792, + "source": "Rosetta Code", + "text": "import math, strutils\nimport bignum\n\nfunc lah[T: int | Int](n, k: T; signed = false): T =\n\tif n == 0 or k == 0 or k > n: return when T is int: 0 else: newInt(0)\n\tif n == k: return when T is int: 1 else: newInt(1)\n\tif k == 1: return fac(n)\n\tresult = binom(n, k) * binom(n - 1, k - 1) * fac(n - k)\n\tif signed and (n and 1) != 0: result = -result\n\nproc printLahTable(kmax: int) =\n\tstdout.write \" \"\n\tfor k in 0..kmax:\n\t\tstdout.write ($k).align(12)\n\tstdout.write('\\n')\n\tfor n in 0..kmax:\n\t\tstdout.write ($n).align(2)\n\t\tfor k in 0..n:\n\t\t\tstdout.write ($lah(n, k)).align(12)\n\t\tstdout.write('\\n')\n\nprintLahTable(12)\n\nvar maxval = newInt(0)\nlet n = newInt(100)\nfor k in newInt(0)..newInt(100):\n\tlet val = lah(n, k)\n\tif val > maxval: maxval = val\necho \"\\nThe maximum value of lah(100, k) is \", maxval\n" + }, + { + "id": 1251, + "length": 1714, + "source": "Rosetta Code", + "text": "import math, strutils\n\ntemplate isEven(n: int): bool = (n and 1) == 0\ntemplate isOdd(n: int): bool = (n and 1) != 0\n\n\nfunc getDivisors(n: int): seq[int] =\n\tresult = @[1, n]\n\tfor i in 2..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tlet j = n div i\n\t\t\tresult.add i\n\t\t\tif i != j: result.add j\n\n\nfunc isPartSum(divs: seq[int]; sum: int): bool =\n\tif sum == 0: return true\n\tif divs.len == 0: return false\n\tlet last = divs[^1]\n\tlet divs = divs[0..^2]\n\tresult = isPartSum(divs, sum)\n\tif not result and last <= sum:\n\t\tresult = isPartSum(divs, sum - last)\n\n\nfunc isZumkeller(n: int): bool =\n\tlet divs = n.getDivisors()\n\tlet sum = sum(divs)\n\t# If \"sum\" is odd, it can't be split into two partitions with equal sums.\n\tif sum.isOdd: return false\n\t# If \"n\" is odd use \"abundant odd number\" optimization.\n\tif n.isOdd:\n\t\tlet abundance = sum - 2 * n\n\t\treturn abundance > 0 and abundance.isEven\n\t# If \"n\" and \"sum\" are both even, check if there's a partition which totals \"sum / 2\".\n\tresult = isPartSum(divs, sum div 2)\n\n\nwhen isMainModule:\n\n\techo \"The first 220 Zumkeller numbers are:\"\n\tvar n = 2\n\tvar count = 0\n\twhile count < 220:\n\t\tif n.isZumkeller:\n\t\t\tstdout.write align($n, 3)\n\t\t\tinc count\n\t\t\tstdout.write if count mod 20 == 0: '\\n' else: ' '\n\t\tinc n\n\techo()\n\n\techo \"The first 40 odd Zumkeller numbers are:\"\n\tn = 3\n\tcount = 0\n\twhile count < 40:\n\t\tif n.isZumkeller:\n\t\t\tstdout.write align($n, 5)\n\t\t\tinc count\n\t\t\tstdout.write if count mod 10 == 0: '\\n' else: ' '\n\t\tinc n, 2\n\techo()\n\n\techo \"The first 40 odd Zumkeller numbers which don't end in 5 are:\"\n\tn = 3\n\tcount = 0\n\twhile count < 40:\n\t\tif n mod 10 != 5 and n.isZumkeller:\n\t\t\tstdout.write align($n, 7)\n\t\t\tinc count\n\t\t\tstdout.write if count mod 8 == 0: '\\n' else: ' '\n\t\tinc n, 2\n" + }, + { + "id": 1252, + "length": 1476, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc isPrime(n: int): bool =\n\t## Check if \"n\" is prime by trying successive divisions.\n\t## \"n\" is supposed not to be a multiple of 2 or 3.\n\tvar d = 5\n\tvar delta = 2\n\twhile d <= int(sqrt(n.toFloat)):\n\t\tif n mod d == 0: return false\n\t\tinc d, delta\n\t\tdelta = 6 - delta\n\tresult = true\n\nfunc isProduct23(n: int): bool =\n\t## Check if \"n\" has only 2 and 3 for prime divisors\n\t## (i.e. that \"n = 2^u * 3^v\").\n\tvar n = n\n\twhile (n and 1) == 0: n = n shr 1\n\twhile n mod 3 == 0: n = n div 3\n\tresult = n == 1\n\niterator pierpont(maxCount: Positive; k: int): int =\n\t## Yield the Pierpoint primes of first or second kind according\n\t## to the value of \"k\" (+1 for first kind, -1 for second kind).\n\tyield 2\n\tyield 3\n\tvar n = 5\n\tvar delta = 2 # 2 and 4 alternatively to skip the multiples of 2 and 3.\n\tyield n\n\tvar count = 3\n\twhile count < maxCount:\n\t\tinc n, delta\n\t\tdelta = 6 - delta\n\t\tif isProduct23(n - k) and isPrime(n):\n\t\t\tinc count\n\t\t\tyield n\n\ntemplate pierpont1*(maxCount: Positive): int = pierpont(maxCount, +1)\ntemplate pierpont2*(maxCount: Positive): int = pierpont(maxCount, -1)\n\n\nwhen isMainModule:\n\n\techo \"First 50 Pierpont primes of the first kind:\"\n\tvar count = 0\n\tfor n in pierpont1(50):\n\t\tstdout.write ($n).align(9)\n\t\tinc count\n\t\tif count mod 10 == 0: stdout.write '\\n'\n\n\techo \"\"\n\techo \"First 50 Pierpont primes of the second kind:\"\n\tcount = 0\n\tfor n in pierpont2(50):\n\t\tstdout.write ($n).align(9)\n\t\tinc count\n\t\tif count mod 10 == 0: stdout.write '\\n'\n" + }, + { + "id": 1253, + "length": 3205, + "source": "Rosetta Code", + "text": "# Abelian sandpile.\n\nfrom math import sqrt\nfrom nimPNG import savePNG24\nfrom sequtils import repeat\nfrom strformat import fmt\nfrom strutils import strip, addSep, parseInt\n\n# The grid represented as a sequence of sequences of int32.\ntype Grid = seq[seq[int32]]\n\n# Colors to use for PPM and PNG files.\nconst Colors = [[byte 100, 40, 15],\n\t\t\t\t\t\t\t\t[byte 117, 87, 30],\n\t\t\t\t\t\t\t\t[byte 181, 134, 47],\n\t\t\t\t\t\t\t\t[byte 245, 182, 66]]\n\n\nfunc sideLength(initVal: int32): int32 =\n\t# Return the grid side length needed for \"initVal\" particles.\n\t# We make sure that the returned value is odd.\n\tresult = sqrt(initVal.toFloat / 1.75).int32 + 3\n\tresult += result and 1 xor 1\n\n\nfunc doOneStep(grid: var Grid; boundary: var array[4, int]): bool =\n\t## Compute one step.\n\n\tresult = false\n\n\tfor y in boundary[0]..boundary[2]:\n\t\tfor x in boundary[1]..boundary[3]:\n\t\t\tif grid[y][x] >= 4:\n\n\t\t\t\tlet rem = grid[y][x] div 4\n\t\t\t\tgrid[y][x] = grid[y][x] mod 4\n\n\t\t\t\tif y - 1 >= 0:\n\t\t\t\t\tinc grid[y - 1][x], rem\n\t\t\t\t\tif y == boundary[0]:\n\t\t\t\t\t\tdec boundary[0]\n\n\t\t\t\tif x - 1 >= 0:\n\t\t\t\t\tinc grid[y][x - 1], rem\n\t\t\t\t\tif x == boundary[1]:\n\t\t\t\t\t\tdec boundary[1]\n\n\t\t\t\tif y + 1 < grid.len:\n\t\t\t\t\tinc grid[y + 1][x], rem\n\t\t\t\t\tif y == boundary[2]:\n\t\t\t\t\t\tinc boundary[2]\n\n\t\t\t\tif x + 1 < grid.len:\n\t\t\t\t\tinc grid[y][x + 1], rem\n\t\t\t\t\tif x == boundary[3]:\n\t\t\t\t\t\tinc boundary[3]\n\n\t\t\t\tresult = true\n\n\nproc display(grid: Grid; initVal: int) =\n\t## Display the grid as an array of values.\n\n\techo fmt\"Starting with {initVal} particles.\"\n\techo \"\"\n\n\tvar line = newStringOfCap(2 * grid.len - 1)\n\tfor row in grid:\n\t\tfor value in row:\n\t\t\tline.addSep(\" \", 0)\n\t\t\tline.add($value)\n\t\techo line\n\t\tline.setLen(0)\n\techo \"\"\n\n\nproc writePpmFile(grid: Grid; name: string) =\n\t## Write a grid representation in a PPM file.\n\n\tvar file = open(name, fmWrite)\n\tfile.write(fmt\"P6 {grid.len} {grid.len} 255 \")\n\n\tfor row in grid:\n\t\tfor value in row:\n\t\t\tdiscard file.writeBytes(Colors[value], 0, 3)\n\n\tfile.close()\n\techo fmt\"PPM image written in \"\"{name}\"\".\"\n\n\nproc writePngFile(grid: Grid; name: string) =\n\t## Write a grid representation in a PNG file.\n\n\tvar pixels = newSeq[byte](3 * grid.len * grid.len)\n\n\t# Build pixel list.\n\tvar idx = 0\n\tfor row in grid:\n\t\tfor value in row:\n\t\t\tpixels[idx..idx+2] = Colors[value]\n\t\t\tinc idx, 3\n\n\tdiscard savePNG24(name, pixels, grid.len, grid.len)\n\techo fmt\"PNG image written in \"\"{name}\"\".\"\n\n\nproc askInitVal(): int32 =\n\t# Ask user for the number of particles.\n\n\twhile true:\n\t\tstdout.write(\"Number of particles? \")\n\t\ttry:\n\t\t\tlet input = stdin.readLine().strip().parseInt()\n\t\t\tif input in 4..int32.high:\n\t\t\t\treturn input.int32\n\t\t\techo fmt\"Value not in expected range: 4..{int32.high}\"\n\t\texcept ValueError:\n\t\t\techo \"Invalid input\"\n\t\texcept EOFError:\n\t\t\tquit(QuitSuccess)\n\n\n# Initialize the grid.\nlet initVal = askInitVal()\nlet sideLen = sideLength(initVal)\nvar grid = repeat(newSeq[int32](sideLen), sideLen)\nlet origin = grid.len div 2\nvar boundaries: array[4, int] = [origin, origin, origin, origin]\ngrid[origin][origin] = initVal\n\n# Run the simulation.\nwhile doOneStep(grid, boundaries):\n\tdiscard\n\n# Display grid.\nif grid.len <= 20:\n\tgrid.display(initVal)\n#grid.writePpmFile(fmt\"grid_{initVal}.ppm\")\ngrid.writePngFile(fmt\"grid_{initVal}.png\")\n" + }, + { + "id": 1254, + "length": 1279, + "source": "Rosetta Code", + "text": "import sets, strformat\n\n\nproc min[T](s: HashSet[T]): T =\n\t## Return the minimal value in a set.\n\tif s.card == 0:\n\t\traise newException(ValueError, \"set is empty.\")\n\tresult = T.high\n\tfor n in s:\n\t\tif n < result: result = n\n\n\niterator humbleNumbers(): Positive =\n\t## Yield the successive humble numbers.\n\tvar s = [1].toHashSet()\n\twhile true:\n\t\tlet m = min(s)\n\t\tyield m\n\t\ts.excl(m)\n\t\tfor k in [2, 3, 5, 7]: s.incl(k * m)\n\n\nproc showHumbleNumbers(maxCount: Positive) =\n\t## Show the first \"maxCount\" humble numbers.\n\tvar currCount = 0\n\tfor n in humbleNumbers():\n\t\tstdout.write n\n\t\tinc currCount\n\t\tif currCount == maxCount: break\n\t\tstdout.write ' '\n\techo \"\"\n\n\nproc showHumbleCount(ndigits: Positive) =\n\t## Show the number of humble numbers with \"n <= ndigits\" digits.\n\techo \"Digits Count\"\n\techo \"------ -----\"\n\tvar currdigits = 1\n\tvar count = 0\n\tvar next = 10 # First number with \"currdigits + 1\" digits.\n\tfor n in humbleNumbers():\n\t\tif n >= next:\n\t\t\t# Number of digits has changed.\n\t\t\techo \" {currdigits:2d} {count:5d}\"\n\t\t\tinc currdigits\n\t\t\tif currdigits > ndigits: break\n\t\t\tnext *= 10\n\t\t\tcount = 1\n\t\telse:\n\t\t\tinc count\n\n\nwhen isMainModule:\n\techo \"First 50 humble numbers:\"\n\tshowHumbleNumbers(50)\n\techo \"\"\n\techo \"Count of humble numbers with n digits:\"\n\tshowHumbleCount(18)\n" + }, + { + "id": 1255, + "length": 1372, + "source": "Rosetta Code", + "text": "import sequtils, strutils\nimport bignum\n\nconst N = 521\n\n\nfunc initPrimes(): tuple[primes: seq[Int]; smallPrimes: seq[int]] =\n\n\tvar sieve: array[2..N, bool]\n\tfor n in 2..N:\n\t\tif not sieve[n]:\n\t\t\tfor k in countup(n * n, N, n): sieve[k] = true\n\n\tfor n, isComposite in sieve:\n\t\tif not isComposite:\n\t\t\tresult.primes.add newInt(n)\n\t\t\tif n <= 29: result.smallPrimes.add n\n\n# Cache all primes up to N.\nlet (Primes, SmallPrimes) = initPrimes()\n\n\n\nproc nSmooth(n, size: Positive): seq[Int] =\n\tassert n in 2..N, \"'n' must be between 2 and \" & $N\n\n\tlet bn = newInt(n)\n\tassert bn in Primes, \"'n' must be a prime number\"\n\n\tresult.setLen(size)\n\tresult[0] = newInt(1)\n\n\tvar next: seq[Int]\n\tfor prime in Primes:\n\t\tif prime > bn: break\n\t\tnext.add prime\n\n\tvar indices = newSeq[int](next.len)\n\tfor m in 1.. n:\n\t\t\tif n mod p == 0:\n\t\t\t\tsequence &= a[1..p]\n\t\telse:\n\t\t\ta[t] = a[t - p]\n\t\t\tdb(t + 1, p)\n\t\t\tvar j = a[t - p] + 1\n\t\t\twhile j < k.uint:\n\t\t\t\ta[t] = j\n\t\t\t\tdb(t + 1, t)\n\t\t\t\tinc j\n\n\tdb(1, 1)\n\tfor i in sequence:\n\t\tresult &= alphabet[i]\n\tresult &= result[0..(n-2)]\n\n\nproc validate(db: string) =\n\n\tvar found: array[10_000, int]\n\tvar errs: seq[string]\n\n\t## Check all strings of 4 consecutive digits within 'db'\n\t## to see if all 10,000 combinations occur without duplication.\n\tfor i in 0..(db.len - 4):\n\t\tlet s = db[i..(i+3)]\n\t\tvar n: int\n\t\tif s.parseInt(n) == 4:\n\t\t\tinc found[n]\n\n\tfor n, count in found:\n\t\tif count == 0:\n\t\t\terrs &= fmt\" PIN number {n:04d} missing\"\n\t\telif count > 1:\n\t\t\terrs &= fmt\" PIN number {n:04d} occurs {count} times\"\n\n\tif errs.len == 0:\n\t\techo \" No errors found\"\n\telse:\n\t\tlet plural = if errs.len == 1: \"\" else: \"s\"\n\t\techo fmt\" {errs.len} error{plural} found\"\n\t\tfor err in errs: echo err\n\n\nvar db = deBruijn(10, 4)\n\necho fmt\"The length of the de Bruijn sequence is {db.len}\"\necho \"\"\necho fmt\"The first 130 digits of the de Bruijn sequence are: {db[0..129]}\"\necho \"\"\necho fmt\"The last 130 digits of the de Bruijn sequence are: {db[^130..^1]}\"\necho \"\"\n\necho \"Validating the deBruijn sequence:\"\ndb.validate()\necho \"\"\necho \"Validating the reversed deBruijn sequence:\"\nreversed(db).join().validate()\necho \"\"\n\ndb[4443] = '.'\necho \"Validating the overlaid deBruijn sequence:\"\ndb.validate()\n" + }, + { + "id": 1257, + "length": 1104, + "source": "Rosetta Code", + "text": "from math import sqrt\nimport strformat\nimport strutils\n\nconst Tolerance = 1e-10\n\nproc `~=`(a, b: float): bool =\n\t## Check if \"a\" and \"b\" are close.\n\t## We use a relative tolerance to compare the values.\n\tresult = abs(a - b) < max(abs(a), abs(b)) * Tolerance\n\nproc compare(a, b: string) =\n\t## Compare \"a\" and \"b\" transmitted as strings.\n\t## Values are computed using \"parseFloat\".\n\tlet r = a.parseFloat() ~= b.parseFloat()\n\techo fmt\"{a} ~= {b} is {r}\"\n\nproc compare(a: string; avalue: float; b: string) =\n\t## Compare \"a\" and \"b\" transmitted as strings.\n\t## The value of \"a\" is transmitted and not computed.\n\tlet r = avalue ~= b.parseFloat()\n\techo fmt\"{a} ~= {b} is {r}\"\n\n\ncompare(\"100000000000000.01\", \"100000000000000.011\")\ncompare(\"100.01\", \"100.011\")\ncompare(\"10000000000000.001 / 10000.0\", 10000000000000.001 / 10000.0, \"1000000000.0000001000\")\ncompare(\"0.001\", \"0.0010000001\")\ncompare(\"0.000000000000000000000101\", \"0.0\")\ncompare(\"sqrt(2) * sqrt(2)\", sqrt(2.0) * sqrt(2.0), \"2.0\")\ncompare(\"-sqrt(2) * sqrt(2)\", -sqrt(2.0) * sqrt(2.0), \"-2.0\")\ncompare(\"3.14159265358979323846\", \"3.14159265358979324\")\n" + }, + { + "id": 1258, + "length": 1936, + "source": "Rosetta Code", + "text": "# Fraction reduction.\n\nimport strformat\nimport times\n\ntype Result = tuple[n: int, nine: array[1..9, int]]\n\ntemplate find[T; N: static int](a: array[1..N, T]; value: T): int =\n\t## Return the one-based index of a value in an array.\n\t## This is needed as \"system.find\" returns a 0-based index even if the\n\t## array lower bound is not null.\n\tsystem.find(a, value) + 1\n\nfunc toNumber(digits: seq[int]; removeDigit: int = 0): int =\n\t## Convert a list of digits into a number.\n\tvar digits = digits\n\tif removeDigit != 0:\n\t\tlet idx = digits.find(removeDigit)\n\t\tdigits.delete(idx)\n\tfor d in digits:\n\t\tresult = 10 * result + d\n\nfunc nDigits(n: int): seq[Result] =\n\tvar digits = newSeq[int](n + 1) # Allocating one more to work with one-based indexes.\n\tvar used: array[1..9, bool]\n\tfor i in 1..n:\n\t\tdigits[i] = i\n\t\tused[i] = true\n\tvar terminated = false\n\twhile not terminated:\n\t\tvar nine: array[1..9, int]\n\t\tfor i in 1..9:\n\t\t\tif used[i]:\n\t\t\t\tnine[i] = digits.toNumber(i)\n\t\tresult &= (n: digits.toNumber(), nine: nine)\n\t\tblock searchLoop:\n\t\t\tterminated = true\n\t\t\tfor i in countdown(n, 1):\n\t\t\t\tlet d = digits[i]\n\t\t\t\tdoAssert(used[d], \"Encountered an inconsistency with 'used' array\")\n\t\t\t\tused[d] = false\n\t\t\t\tfor j in (d + 1)..9:\n\t\t\t\t\tif not used[j]:\n\t\t\t\t\t\tused[j] = true\n\t\t\t\t\t\tdigits[i] = j\n\t\t\t\t\t\tfor k in (i + 1)..n:\n\t\t\t\t\t\t\tdigits[k] = used.find(false)\n\t\t\t\t\t\t\tused[digits[k]] = true\n\t\t\t\t\t\tterminated = false\n\t\t\t\t\t\tbreak searchLoop\n\n\nlet start = gettime()\n\nfor n in 2..6:\n\tlet rs = nDigits(n)\n\tvar count = 0\n\tvar omitted: array[1..9, int]\n\tfor i in 1.. {yn}/{yd} (removed {k})\"\n\n\techo \"{n}-digit fractions found: {count}, omitted {omitted}\\n\"\necho \"Took {gettime() - start}\"\n" + }, + { + "id": 1259, + "length": 8390, + "source": "Rosetta Code", + "text": "import algorithm, math, strformat, times\n\ntype Llst = seq[seq[int]]\n\nconst\n\t# Powers of 10.\n\tP = block:\n\t\t\t\tvar p: array[19, int64]\n\t\t\t\tp[0] = 1i64\n\t\t\t\tfor i in 1..18: p[i] = 10 * p[i - 1]\n\t\t\t\tp\n\n\t# Digital root lookup array.\n\tDrar = block:\n\t\t\t\t\t var drar: array[19, int]\n\t\t\t\t\t for i in 0..18: drar[i] = i shl 1 mod 9\n\t\t\t\t\t drar\n\nvar\n\td: seq[int] # permutation working slice\n\tdac: seq[int] # running digital root slice\n\tac: seq[int64] # accumulator slice\n\tpp: seq[int64] # coefficient slice that combines with digits of working slice\n\tsr: seq[int64] # temporary list of squares used for building\n\nvar\n\todd = false # flag for odd number of digits\n\tsum: int64 # calculated sum of terms (square candidate)\n\tcn = 0 # solution counter\n\tnd = 2 # number of digits\n\tnd1 = nd - 1 # 'nd' helper\n\tln: int # previous value of 'n' (in recurse())\n\tdl: int # length of 'd' slice\n\nfunc newIntSeq(f, t, s: int): seq[int] =\n\t## Return a sequence of integers.\n\tresult = newSeq[int]((t - f) div s + 1)\n\tvar f = f\n\tfor i in 0..result.high:\n\t\tresult[i] = f\n\t\tinc f, s\n\nconst\n\tTlo = @[0, 1, 4, 5, 6] # primary differences starting point\n\tAll = newIntSeq(-9, 9, 1) # all possible differences\n\tOdl = newIntSeq(-9, 9, 2) # odd possible differences\n\tEvl = newIntSeq(-8, 8, 2) # even possible differences\n\tThi = @[4, 5, 6, 9, 10, 11, 14, 15, 16] # primary sums starting point\n\tAlh = newIntSeq(0, 18, 1) # all possible sums\n\tOdh = newIntSeq(1, 17, 2) # odd possible sums\n\tEvh = newIntSeq(0, 18, 2) # even possible sums\n\tTen = newIntSeq(0, 9, 1) # used for odd number of digits\n\tZ = newIntSeq(0, 0, 1) # no difference, avoids generating a bunch of negative square candidates\n\tT7 = @[-3, 7] # shortcut for low 5\n\tNin = @[9] # shortcut for hi 10\n\tTn = @[10] # shortcut for hi 0 (unused, unneeded)\n\tT12 = @[2, 12] # shortcut for hi 5\n\tO11 = @[1, 11] # shortcut for hi 15\n\tPos = @[0, 1, 4, 5, 6, 9] # shortcut for 2nd lo 0\n\nvar\n\tlul: Llst = @[Z, Odl, @[], @[], Evl, T7, Odl] # shortcut lookup lo primary\n\tluh: Llst = @[Tn, Evh, @[], @[], Evh, T12, Odh, @[], @[],\n\t\t\t\t\t\t\t\tEvh, Nin, Odh, @[], @[], Odh, O11, Evh] # shortcut lookup hi primary\n\tl2l: Llst = @[Pos, @[], @[], @[], All, @[], All] # shortcut lookup lo secondary\n\tl2h: Llst = @[@[], @[], @[], @[], Alh, @[], Alh, @[], @[],\n\t\t\t\t\t\t\t\t@[], Alh, @[], @[], @[], Alh, @[], Alh] # shortcut lookup hi secondary\n\tchTen: Llst = @[@[0, 2, 5, 8, 9], @[0, 3, 4, 6, 9], @[1, 4, 7, 8],\n\t\t\t\t\t\t\t\t\t@[2, 3, 5, 8], @[0, 3, 6, 7, 9], @[1, 2, 4, 7],\n\t\t\t\t\t\t\t\t\t@[2, 5, 6, 8], @[0, 1, 3, 6, 9], @[1, 4, 5, 7]]\n\tchAH: Llst = @[@[0, 2, 5, 8, 9, 11, 14, 17, 18], @[0, 3, 4, 6, 9, 12, 13, 15, 18],\n\t\t\t\t\t\t\t\t @[1, 4, 7, 8, 10, 13, 16, 17], @[2, 3, 5, 8, 11, 12, 14, 17],\n\t\t\t\t\t\t\t\t @[0, 3, 6, 7, 9, 12, 15, 16, 18], @[1, 2, 4, 7, 10, 11, 13, 16],\n\t\t\t\t\t\t\t\t @[2, 5, 6, 8, 11, 14, 15, 17], @[0, 1, 3, 6, 9, 10, 12, 15, 18],\n\t\t\t\t\t\t\t\t @[1, 4, 5, 7, 10, 13, 14, 16]]\n\nvar lu, l2: Llst\n\nfunc isr(s: int64): int64 {.inline.} =\n\t## Return integer square root.\n\tint64(sqrt(float(s)))\n\nproc isRev(nd: int; f, r: int64): bool =\n\t## Recursively determines whether 'r' is the reverse of 'f'.\n\tlet nd = nd - 1\n\tif f div P[nd] != r mod 10: return false\n\tif nd < 1: return true\n\tresult = isRev(nd, f mod P[nd], r div 10)\n\nproc recurseLE5(lst: Llst; lv: int) =\n\t## Recursive function to evaluate the permutations, no shortcuts.\n\tif lv == dl: # Check if on last stage of permutation.\n\t\tsum = ac[lv - 1]\n\t\tif sum > 0:\n\t\t\tlet rt = int64(sqrt(float(sum)))\n\t\t\tif rt * rt == sum: sr.add sum\n\telse:\n\t\tfor n in lst[lv]: # Set up next permutation.\n\t\t\td[lv] = n\n\t\t\tif lv == 0: ac[0] = pp[0] * n\n\t\t\telse: ac[lv] = ac[lv - 1] + pp[lv] * n # Update accumulated sum.\n\t\t\trecurseLE5(lst, lv + 1) # Recursively call next level.\n\nproc recursehi(lst: var Llst; lv: int) =\n\t## Recursive function to evaluate the hi permutations.\n\t## Shortcuts added to avoid generating many non-squares, digital root calc added.\n\tlet lv1 = lv - 1\n\tif lv == dl: # Check if on last stage of permutation.\n\t\tsum = ac[lv1]\n\t\tif (0x202021202030213 and (1 shl (sum and 63))) != 0:\n\t\t\t# Test accumulated sum, append to result if square.\n\t\t\tlet rt = int64(sqrt(float64(sum)))\n\t\t\tif rt * rt == sum: sr.add sum\n\telse:\n\t\tfor n in lst[lv]: # Set up next permutation.\n\t\t\td[lv] = n\n\t\t\tif lv == 0:\n\t\t\t\tac[0] = pp[0] * n\n\t\t\t\tdac[0] = Drar[n] # Update accumulated sum and running dr.\n\t\t\telse:\n\t\t\t\tac[lv] = ac[lv1] + pp[lv] * n\n\t\t\t\tdac[lv] = dac[lv1] + Drar[n]\n\t\t\t\tif dac[lv] > 8: dec dac[lv], 9\n\t\t\tcase lv # Shortcuts to be performed on designated levels.\n\t\t\tof 0: # Primary level: set shortcuts for secondary level.\n\t\t\t\tln = n\n\t\t\t\tlst[1] = lu[ln]\n\t\t\t\tlst[2] = l2[n]\n\t\t\tof 1: # Secondary level: set shortcuts for tertiary level.\n\t\t\t\tcase ln # For sums.\n\t\t\t\tof 5, 15: lst[2] = if n < 10: Evh else: Odh\n\t\t\t\tof 9: lst[2] = if (n shr 1 and 1) == 0: Evh else: Odh\n\t\t\t\tof 11: lst[2] = if (n shr 1 and 1) == 1: Evh else: Odh\n\t\t\t\telse: discard\n\t\t\telse: discard\n\t\t\tif lv == dl - 2:\n\t\t\t\t# Reduce last round according to dr calc.\n\t\t\t\tlst[dl - 1] = if odd: chTen[dac[dl - 2]] else: chAH[dac[dl - 2]]\n\t\t\trecursehi(lst, lv + 1) # Recursively call next level.\n\nproc recurselo(lst: var Llst; lv: int) =\n\t## Recursive function to evaluate the lo permutations.\n\t## Shortcuts added to avoid generating many non-squares.\n\tlet lv1 = lv - 1\n\tif lv == dl: # Check if on last stage of permutation.\n\t\tsum = ac[lv1]\n\t\tif sum > 0:\n\t\t\tlet rt = int64(sqrt(float64(sum)))\n\t\t\tif rt * rt == sum: sr.add sum\n\telse:\n\t\tfor n in lst[lv]: # Set up next permutation.\n\t\t\td[lv] = n\n\t\t\tif lv == 0: ac[0] = pp[0] * n\n\t\t\telse: ac[lv] = ac[lv1] + pp[lv] * n # Update accumulated sum.\n\t\t\tcase lv # Shortcuts to be performed on designated levels.\n\t\t\tof 0: # Primary level: set shortcuts for secondary level.\n\t\t\t\tln = n\n\t\t\t\tlst[1] = lu[ln]\n\t\t\t\tlst[2] = l2[n]\n\t\t\tof 1: # Secondary level: set shortcuts for tertiary level.\n\t\t\t\tcase ln # For difs.\n\t\t\t\tof 1: lst[2] = if ((n + 9) shr 1 and 1) == 0: Evl else: Odl\n\t\t\t\tof 5: lst[2] = if n < 0: Evl else: Odl\n\t\t\t\telse: discard\n\t\t\telse: discard\n\t\t\trecurselo(lst, lv + 1) # Recursively call next level.\n\nproc listEm(lst: var Llst; plu, pl2: Llst): seq[int64] =\n\t## Produces a list of candidate square numbers.\n\tdl = lst.len\n\td = newSeq[int](dl)\n\tsr.setLen(0)\n\tlu = plu\n\tl2 = pl2\n\tac = newSeq[int64](dl)\n\tdac = newSeq[int](dl)\n\tpp = newSeq[int64](dl)\n\t# Build coefficients array.\n\tfor i in 0.. 6: P[nd1 - i] + P[i] else: P[nd1 - i] - P[i]\n\t# Call appropriate recursive function.\n\tif nd <= 5: recurseLE5(lst, 0)\n\telif lst[0].len > 8: recursehi(lst, 0)\n\telse: recurselo(lst, 0)\n\tresult = sr\n\nproc reveal(lo, hi: openArray[int64]) =\n\t## Reveal whether combining two lists of squares can produce a rare number.\n\tvar s: seq[string] # Temporary list of results.\n\tfor l in lo:\n\t\tfor h in hi:\n\t\t\tlet r = (h - l) shr 1\n\t\t\tlet f = h - r # Generate all possible fwd & rev candidates from lists.\n\t\t\tif isRev(nd, f, r):\n\t\t\t\ts.add \"{f:20} {isr(h):11} {isr(l):10} \"\n\ts.sort()\n\tif s.len > 0:\n\t\tfor t in s:\n\t\t\tinc cn\n\t\t\tlet tt = if t != s[^1]: \"\\n\" else: \"\"\n\t\t\tstdout.write \"{cn:2} {t}{tt}\"\n\telse:\n\t\tstdout.write \"{\\\"\\\":48}\"\n\nfunc formatTime(d: Duration): string =\n\tvar f = d.inMilliseconds\n\tvar s = f div 1000\n\tf = f mod 1000\n\tvar m = s div 60\n\ts = s mod 60\n\tlet h = m div 60\n\tm = m mod 60\n\tresult = \"{h:02}:{m:02}:{s:02}.{f:03}\"\n\nvar\n\tlls: Llst = @[Tlo]\n\thls: Llst = @[Thi]\n\nvar bstart, tstart = now()\n\necho \"\"\"nth {\"forward\":>19} {\"rt.sum\":>11} {\"rt.dif\":>10} digs {\"block time\":>11} {\"total time\":>13}\"\"\"\n\nwhile nd <= 18:\n\tif nd > 2:\n\t\tif odd:\n\t\t\thls.add Ten\n\t\telse:\n\t\t\tlls.add All\n\t\t\thls[^1] = Alh\n\treveal(listEm(lls, lul, l2l), listEm(hls, luh, l2h))\n\tif not odd and nd > 5:\n\t\t# Restore last element of hls, so that dr shortcut doesn't mess up next nd.\n\t\thls[^1] = Alh\n\tlet bTime = formatTime(now() - bstart)\n\tlet tTime = formatTime(now() - tstart)\n\techo \"{nd:2}: {bTime} {tTime}\"\n\tbstart = now() # Restart block timing.\n\tnd1 = nd\n\tinc nd\n\todd = not odd\n" + }, + { + "id": 1260, + "length": 1736, + "source": "Rosetta Code", + "text": "import os, strutils\n\ntype CopyPastaError = object of CatchableError\n\ntemplate raiseError(message: string, linenum = 0) =\n\tlet prefix = if linenum != 0: \"Line $1: \".format(linenum) else: \"\"\n\traise newException(CopyPastaError, prefix & message)\n\n\nproc copyPasta() =\n\t## Load and execute a program.\n\n\tvar clipboard: string\n\n\tif paramCount() != 1:\n\t\t\techo \"usage: \", getAppFilename().lastPathPart, \" filename.cp\"\n\t\t\tquit QuitFailure\n\n\tlet path = paramStr(1)\n\tlet code = try: path.readFile()\n\t\t\t\t\t\t except IOError: raiseError(\"Unable to read file $1.\".format(path))\n\n\tlet lines = code.splitLines()\n\n\tvar linenum = 1 # Starting at index one for line number.\n\twhile linenum <= lines.len:\n\t\tlet command = lines[linenum - 1].strip()\n\t\tcase command\n\n\t\tof \"Copy\":\n\t\t\tif linenum == lines.len: raiseError(\"missing string to copy.\", linenum)\n\t\t\tclipboard.add lines[linenum]\n\n\t\tof \"CopyFile\":\n\t\t\tif linenum == lines.len: raiseError(\"missing file to copy from.\", linenum)\n\t\t\tlet fpath = lines[linenum]\n\t\t\tif fpath == \"TheF*ckingCode\":\n\t\t\t\tclipboard.add code\n\t\t\telse:\n\t\t\t\tlet text = try: fpath.readFile()\n\t\t\t\t\t\t\t\t\t except IOError: raiseError(\"unable to read file $1.\".format(fpath), linenum)\n\t\t\t\tclipboard.add text\n\n\t\tof \"Duplicate\":\n\t\t\tif linenum == lines.len: raiseError(\"missing number of repetitions.\", linenum)\n\t\t\tlet n = try: lines[linenum].parseInt()\n\t\t\t\t\t\t\texcept: raiseError(\"wrong number of repetitions.\", linenum + 1)\n\t\t\tclipboard.add repeat(clipboard, n)\n\n\t\tof \"Pasta!\":\n\t\t\tstdout.write clipboard\n\t\t\tbreak\n\n\t\tof \"\": # Empty mine: skip.\n\t\t\tinc linenum\n\t\t\tcontinue\n\n\t\telse:\n\t\t\traiseError(\"unknown command $1.\".format(command), linenum)\n\n\t\tinc linenum, 2\n\ntry:\n\tcopyPasta()\nexcept CopyPastaError:\n\tquit getCurrentExceptionMsg(), QuitFailure\n" + }, + { + "id": 1261, + "length": 1568, + "source": "Rosetta Code", + "text": "import strutils, tables\n\ntype\n\n\tElemKind = enum eValue, eWheel\n\n\tElem = object\n\t\tcase kind: ElemKind\n\t\tof eValue:\n\t\t\tvalue: Natural\n\t\tof eWheel:\n\t\t\tname: char\n\n\tWheel = ref object\n\t\telems: seq[Elem]\n\t\tindex: Natural\n\n\tWheels = Table[char, Wheel]\n\n\tWheelDescription = tuple[name: char; elems: string]\n\n\nfunc initWheels(wheels: openArray[WheelDescription]): Wheels =\n\t## Initialize a table of wheels from an array of wheel descriptions.\n\n\tfor (name, elems) in wheels:\n\t\tlet wheel = new(Wheel)\n\t\tfor e in elems.splitWhitespace():\n\t\t\tif e[0].isUpperAscii():\n\t\t\t\twheel.elems.add Elem(kind: eWheel, name: e[0])\n\t\t\telse:\n\t\t\t\twheel.elems.add Elem(kind: eValue, value: e.parseInt())\n\t\tresult[name] = wheel\n\n\nfunc next(wheels: Wheels; name: char): Natural =\n\t## Return the next element from a wheel.\n\n\tlet wheel = wheels[name]\n\tlet elem = wheel.elems[wheel.index]\n\twheel.index = (wheel.index + 1) mod wheel.elems.len\n\tresult = case elem.kind\n\t\t\t\t\t of eValue: elem.value\n\t\t\t\t\t of eWheel: wheels.next(elem.name)\n\n\nwhen isMainModule:\n\n\tproc generate(wheelList: openArray[WheelDescription]; count: Positive) =\n\t\t## Create the wheels from their description, then display\n\t\t## the first \"count\" values generated by wheel 'A'.\n\n\t\tlet wheels = wheelList.initWheels()\n\t\tfor (name, elems) in wheelList:\n\t\t\techo name, \": \", elems\n\t\techo \"generates:\"\n\t\tfor _ in 1..count:\n\t\t\tstdout.write ' ', wheels.next('A')\n\t\techo '\\n'\n\n\n\t{'A': \"1 2 3\"}.generate(20)\n\t{'A': \"1 B 2\", 'B': \"3 4\"}.generate(20)\n\t{'A': \"1 D D\", 'D': \"6 7 8\"}.generate(20)\n\t{'A': \"1 B C\", 'B': \"3 4\", 'C': \"5 B\"}.generate(20)\n" + }, + { + "id": 1262, + "length": 3259, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\n\n# Nested representation of trees.\n# The tree is simply the first node.\n\ntype\n\n\tNNode*[T] = ref object\n\t\tvalue*: T\n\t\tchildren*: seq[NNode[T]]\n\n\nproc newNNode*[T](value: T; children: varargs[NNode[T]]): NNode[T] =\n\t## Create a node.\n\tNNode[T](value: value, children: @children)\n\n\nproc add*[T](node: NNode[T]; children: varargs[NNode[T]]) =\n\t## Add a list of chlidren to a node.\n\tnode.children.add children\n\n\nproc `$`*[T](node: NNode[T]; depth = 0): string =\n\t## Return a string representation of a tree/node.\n\tresult = repeat(' ', 2 * depth) & $node.value & '\\n'\n\tfor child in node.children:\n\t\tresult.add `$`(child, depth + 1)\n\n\n# Indented representation of trees.\n# The tree is described as the list of the nodes.\n\ntype\n\n\tINode*[T] = object\n\t\tvalue*: T\n\t\tlevel*: Natural\n\n\tITree*[T] = seq[INode[T]]\n\n\nproc initINode*[T](value: T; level: Natural): INode[T] =\n\t## Return a new node.\n\tINode[T](value: value, level: level)\n\n\nproc initItree*[T](value: T): ITree[T] =\n\t## Return a new tree initialized with the first node (root node).\n\tresult = @[initINode(value, 0)]\n\n\nproc add*[T](tree: var ITree[T]; nodes: varargs[INode[T]]) =\n\t## Add a list of nodes to the tree.\n\tfor node in nodes:\n\t\tif node.level - tree[^1].level > 1:\n\t\t\traise newException(ValueError, \"wrong level {node.level} in node {node.value}.\")\n\t\ttree.add node\n\n\nproc `$`*[T](tree: ITree[T]): string =\n\t## Return a string representation of a tree.\n\tfor node in tree:\n\t\tresult.add $node.level & ' ' & $node.value & '\\n'\n\n\n# Conversion between nested form and indented form.\n\nproc toIndented*[T](node: NNode[T]): Itree[T] =\n\t## Convert a tree in nested form to a tree in indented form.\n\n\tproc addNode[T](tree: var Itree[T]; node: NNode[T]; level: Natural) =\n\t\t## Add a node to the tree at the given level.\n\t\ttree.add initINode(node.value, level)\n\t\tfor child in node.children:\n\t\t\ttree.addNode(child, level + 1)\n\n\tresult.addNode(node, 0)\n\n\nproc toNested*[T](tree: Itree[T]): NNode[T] =\n\t## Convert a tree in indented form to a tree in nested form.\n\n\tvar stack: seq[NNode[T]] # Note that stack.len is equal to the current level.\n\tvar nnode = newNNode(tree[0].value) # Root.\n\tfor i in 1..tree.high:\n\t\tlet inode = tree[i]\n\t\tif inode.level > stack.len:\n\t\t\t# Child.\n\t\t\tstack.add nnode\n\t\telif inode.level == stack.len:\n\t\t\t# Sibling.\n\t\t\tstack[^1].children.add nnode\n\t\telse:\n\t\t\t# Branch terminated.\n\t\t\twhile inode.level < stack.len:\n\t\t\t\tstack[^1].children.add nnode\n\t\t\t\tnnode = stack.pop()\n\t\t\tstack[^1].children.add nnode\n\n\t\tnnode = newNNode(inode.value)\n\n\t# Empty the stack.\n\twhile stack.len > 0:\n\t\tstack[^1].children.add nnode\n\t\tnnode = stack.pop()\n\n\tresult = nnode\n\n\nwhen isMainModule:\n\n\techo \"Displaying tree built using nested structure:\"\n\tlet nestedTree = newNNode(\"tree\")\n\tlet rocks = newNNode(\"rocks\")\n\trocks.add newNNode(\"code\"), newNNode(\"comparison\"), newNNode(\"wiki\")\n\tlet mocks = newNNode(\"mocks\", newNNode(\"trolling\"))\n\tnestedTree.add rocks, mocks\n\techo nestedTree\n\n\techo \"Displaying tree converted to indented structure:\"\n\tlet indentedTree = nestedTree.toIndented\n\techo indentedTree\n\n\techo \"Displaying tree converted back to nested structure:\"\n\techo indentedTree.toNested\n\n\techo \"Are they equal? \", if $nestedTree == $indentedTree.toNested: \"yes\" else: \"no\"\n" + }, + { + "id": 1263, + "length": 4236, + "source": "Rosetta Code", + "text": "import strutils\n\nconst Outline = \"\"\"Display an outline as a nested table.\n\t\tParse the outline to a tree,\n\t\t\t\tmeasuring the indent of each line,\n\t\t\t\ttranslating the indentation to a nested structure,\n\t\t\t\tand padding the tree to even depth.\n\t\tcount the leaves descending from each node,\n\t\t\t\tdefining the width of a leaf as 1,\n\t\t\t\tand the width of a parent node as a sum.\n\t\t\t\t\t\t(The sum of the widths of its children)\n\t\tand write out a table with 'colspan' values\n\t\t\t\teither as a wiki table,\n\t\t\t\tor as HTML.\"\"\"\n\ntype Color {.pure.} = enum\n\tNoColor\n\tYellow = \"#ffffe6;\"\n\tOrange = \"#ffebd2;\"\n\tGreen = \"#f0fff0;\"\n\tBlue = \"#e6ffff;\"\n\nconst Line1Color = Yellow\nconst Line2Colors = [Orange, Green, Blue]\n\ntype Node = ref object\n\tvalue: string\n\tlevel: Natural\n\twidth: Natural\n\tcolor: Color\n\tparent: Node\n\tchildren: seq[Node]\n\n\nproc leadingSpaces(line: string): int =\n\t## return the number of leading spaces.\n\twhile line[result] == ' ':\n\t\tinc result\n\n\nproc buildTree(outline: string): tuple[root: Node, depth: Natural] =\n\t## Build the tree for the given outline.\n\n\tresult.root = Node()\n\tvar level: int\n\tvar startPos = @[-1]\n\tvar nodes: seq[Node] = @[result.root]\n\tvar linecount = 0\n\n\tfor line in Outline.splitLines:\n\t\tinc linecount\n\t\tif line.len == 0: continue\n\t\tlet start = line.leadingSpaces()\n\t\tlevel = startPos.find(start)\n\n\t\tif level < 0:\n\t\t\t# Level not yet encountered.\n\t\t\tif start < startPos[^1]:\n\t\t\t\traise newException(ValueError, \"wrong indentation at line \" & $linecount)\n\t\t\tstartPos.add(start)\n\t\t\tnodes.add(nil)\n\t\t\tlevel = startPos.high\n\n\t\t# Create the node.\n\t\tlet node = Node(value: line.strip(), level: level)\n\t\tlet parent = nodes[level - 1]\n\t\tparent.children.add(node)\n\t\tnode.parent = parent\n\t\tnodes[level] = node # Set the node as current node for this level.\n\n\tresult.depth = nodes.high\n\n\nproc padTree(node: Node; depth: Natural) =\n\t## pad the tree with empty nodes to get an even depth.\n\tif node.level == depth:\n\t\treturn\n\tif node.children.len == 0:\n\t\t# Add an empty node.\n\t\tnode.children.add(Node(level: node.level + 1, parent: node))\n\tfor child in node.children:\n\t\tchild.padTree(depth)\n\n\nproc computeWidths(node: Node) =\n\t## Compute the widths.\n\tvar width = 0\n\tif node.children.len == 0:\n\t\twidth = 1\n\telse:\n\t\tfor child in node.children:\n\t\t\tchild.computeWidths()\n\t\t\tinc width, child.width\n\tnode.width = width\n\n\nproc build(nodelists: var seq[seq[Node]]; node: Node) =\n\t## Build the list of nodes per level.\n\tnodelists[node.level].add(node)\n\tfor child in node.children:\n\t\tnodelists.build(child)\n\n\nproc setColors(nodelists: seq[seq[Node]]) =\n\t## Set the colors of the nodes.\n\tfor node in nodelists[1]:\n\t\tnode.color = Line1Color\n\tfor i, node in nodelists[2]:\n\t\tnode.color = Line2Colors[i mod Line2Colors.len]\n\tfor level in 3..nodelists.high:\n\t\tfor node in nodelists[level]:\n\t\t\tnode.color = if node.value.len != 0: node.parent.color else: NoColor\n\n\nproc writeWikiTable(nodelists: seq[seq[Node]]) =\n\t## Output the wikitable.\n\techo \"{| class='wikitable' style='text-align: center;'\"\n\tfor level in 1..nodelists.high:\n\t\techo \"|-\"\n\t\tfor node in nodelists[level]:\n\t\t\tif node.width > 1:\n\t\t\t\t# Node with children.\n\t\t\t\techo \"| style='background: $1 ' colspan=$2 | $3\".format(node.color, node.width, node.value)\n\t\t\telif node.value.len > 0:\n\t\t\t\t# Leaf with contents.\n\t\t\t\techo \"| style='background: $1 ' | $2\".format(node.color, node.value)\n\t\t\telse:\n\t\t\t\t# Empty cell.\n\t\t\t\techo \"| | \"\n\techo \"|}\"\n\n\nproc writeHtml(nodelists: seq[seq[Node]]) =\n\t## Output the HTML.\n\techo \"\"\n\tfor level in 1..nodelists.high:\n\t\techo \" \"\n\t\tfor node in nodelists[level]:\n\t\t\tif node.width > 1:\n\t\t\t\t# Node with children.\n\t\t\t\techo \" \".format(node.width, node.color, node.value)\n\t\t\telif node.value.len > 0:\n\t\t\t\t# Leaf with contents.\n\t\t\t\techo \" \".format(node.color, node.value)\n\t\t\telse:\n\t\t\t\t# Empty cell.\n\t\t\t\techo \" \"\n\t\techo \" \"\n\techo \"
$3$2
\"\n\n\nlet (root, depth) = Outline.buildTree()\nroot.padTree(depth)\nroot.computeWidths()\nvar nodelists = newSeq[seq[Node]](depth + 1)\nnodelists.build(root)\nnodelists.setColors()\necho \"WikiTable:\"\nnodelists.writeWikiTable()\necho \"HTML:\"\nnodelists.writeHtml()\n" + }, + { + "id": 1264, + "length": 1300, + "source": "Rosetta Code", + "text": "import strformat\nimport bignum\n\ntype Metal {.pure.} = enum platinum, golden, silver, bronze, copper, nickel, aluminium, iron, tin, lead\n\niterator sequence(b: int): Int =\n\t## Yield the successive terms if a Lucas sequence.\n\t## The first two terms are ignored.\n\tvar x, y = newInt(1)\n\twhile true:\n\t\tx += b * y\n\t\tswap x, y\n\t\tyield y\n\n\ntemplate plural(n: int): string =\n\tif n >= 2: \"s\" else: \"\"\n\n\nproc computeRatio(b: Natural; digits: Positive) =\n\t## Compute the ratio for the given \"n\" with the required number of digits.\n\n\tlet M = 10^culong(digits)\n\n\tvar niter = 0 # Number of iterations.\n\tvar prevN = newInt(1) # Previous value of \"n\".\n\tvar ratio = M # Current value of ratio.\n\n\tfor n in sequence(b):\n\t\tinc niter\n\t\tlet nextRatio = n * M div prevN\n\t\tif nextRatio == ratio: break\n\t\tprevN = n.clone\n\t\tratio = nextRatio\n\n\tvar str = $ratio\n\tstr.insert(\".\", 1)\n\techo \"Value to {digits} decimal places after {niter} iteration{plural(niter)}: \", str\n\n\nwhen isMainModule:\n\n\tfor b in 0..9:\n\t\techo \"Lucas sequence for {Metal(b)} ratio where b = {b}:\"\n\t\tstdout.write \"First 15 elements: 1 1\"\n\t\tvar count = 2\n\t\tfor n in sequence(b):\n\t\t\tstdout.write ' ', n\n\t\t\tinc count\n\t\t\tif count == 15: break\n\t\techo \"\"\n\t\tcomputeRatio(b, 32)\n\t\techo \"\"\n\n\techo \"Golden ratio where b = 1:\"\n\tcomputeRatio(1, 256)\n" + }, + { + "id": 1265, + "length": 1348, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\n\ntype\n\tSample = tuple\n\t\tsucc: int\n\t\tfail: int\n\nconst\n\tnumPrisoners = 100\n\tnumDrawsEachPrisoner = numPrisoners div 2\n\tnumDrawings: Positive = 1_000_000 div 1\n\nproc `$`(s: Sample): string =\n\t\"Succs: $#\\tFails: $#\\tTotal: $#\\tSuccess Rate: $#%.\" % [$s.succ, $s.fail, $(s.succ + s.fail), $(s.succ.float / (s.succ + s.fail).float * 100.0)]\n\nproc prisonersWillBeReleasedSmart(): bool =\n\tresult = true\n\tvar drawers = toSeq(0.. 9:\n\t\tfirst = first div 10\n\tresult = 10 * first + last\n\n\niterator gapful(start: Positive): Positive =\n\t## Yield the gapful numbers starting from \"start\".\n\n\tvar n = start\n\twhile true:\n\t\tlet d = n.gapfulDivisor()\n\t\tif n mod d == 0: yield n\n\t\tinc n\n\n\nproc displayGapfulNumbers(start, num: Positive) =\n\t## Display the first \"num\" gapful numbers greater or equal to \"start\".\n\n\techo \"\\nFirst $1 gapful numbers >= $2:\".format(num, start)\n\tvar count = 0\n\tvar line: string\n\tfor n in gapful(start):\n\t\tline.addSep(\" \")\n\t\tline.add($n)\n\t\tinc count\n\t\tif count == num: break\n\techo line\n\n\nwhen isMainModule:\n\tdisplayGapfulNumbers(100, 30)\n\tdisplayGapfulNumbers(1_000_000, 15)\n\tdisplayGapfulNumbers(1_000_000_000, 10)\n" + }, + { + "id": 1267, + "length": 2538, + "source": "Rosetta Code", + "text": "import strutils # for number input\nimport times # for timing code execution\nimport unicode # for reversed\n\nproc palindromicgapfuls(digit, count, keep: int): seq[uint64] =\n\tvar palcnt = 0 # count of gapful palindromes\n\tlet to_skip = count - keep # count of unwanted values to skip\n\tvar gapfuls = newSeq[uint64]() # array of palindromic gapfuls\n\tlet nn = digit * 11 # digit gapful divisor: 11, 22,...88, 99\n\tvar (power, base, basep) = (1, 1, 0)\n\twhile true:\n\t\tif (power.inc; power and 1) == 0: base = base * 10\n\t\tvar base11 = base * 11 # value of middle two digits positions: 110..\n\t\tvar this_lo = base * digit # starting half for this digit: 10.. to 90..\n\t\tvar next_lo = base * (digit + 1) # starting half for next digit: 20.. to 100..\n\t\twhile this_lo < next_lo - 1:\n\t\t\tvar (palindrome, palindrome_base, left_half) = (0'u64, 0'u64, this_lo.intToStr)\n\t\t\tlet right_half = left_half.reversed\n\t\t\tif (power and 1) == 1: basep = base11; palindrome_base = (left_half & right_half).parseUInt\n\t\t\telse: basep = base; left_half.removeSuffix(\"0\"); palindrome_base = (left_half & right_half).parseUInt\n\t\t\tfor i in 0..9:\n\t\t\t\tpalindrome = palindrome_base + (basep * i).uint\n\t\t\t\tif (palindrome mod nn.uint) == 0:\n\t\t\t\t\tif palcnt < to_skip: (palcnt += 1; continue)\n\t\t\t\t\tgapfuls.add(palindrome)\n\t\t\t\t\tif gapfuls.len == keep: return gapfuls\n\t\t\tthis_lo += 10\n\nlet start = epochTime()\n\nvar (count, keep) = (20, 20)\necho(\"First 20 palindromic gapful numbers ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (100, 15)\necho(\"\\nLast 15 of first 100 palindromic gapful numbers ending in:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (1_000, 10)\necho(\"\\nLast 10 of first 1000 palindromic gapful numbers ending in:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (100_000, 1)\necho(\"\\n100,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (1_000_000, 1)\necho(\"\\n1,000,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (10_000_000, 1)\necho(\"\\n10,000,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\necho (epochTime() - start)\n" + }, + { + "id": 1268, + "length": 2350, + "source": "Rosetta Code", + "text": "import strutils # for number input\nimport times # for timing code execution\nimport unicode # for reversed\n\nproc palindromicgapfuls(digit, count, keep: int): seq[uint64] =\n\tvar palcnt = 0 # count of gapful palindromes\n\tlet to_skip = count - keep # count of unwanted values to skip\n\tlet nn = digit * 11 # digit gapful divisor: 11, 22,...88, 99\n\tvar (power, base, digit) = (1, 1u64, digit.uint64)\n\twhile true:\n\t\tif (power.inc; power and 1) == 0: base *= 10\n\t\tlet base11 = base * 11 # value of middle two digits positions: 110..\n\t\tlet this_lo = base * digit # starting half for this digit: 10.. to 90..\n\t\tlet next_lo = base * (digit + 1) # starting half for next digit: 20.. to 100..\n\t\tfor front_half in countup(this_lo, next_lo - 2, 10):\n\t\t\tvar\n\t\t\t\tbasep = base11\n\t\t\t\tleft_half = $front_half\n\t\t\tlet right_half = left_half.reversed\n\t\t\tif (power and 1) == 0: basep = base; left_half.setLen left_half.len - 1\n\t\t\tvar palindrome = (left_half.add right_half; left_half).parseUInt.uint64\n\t\t\tfor _ in 0..9:\n\t\t\t\tif palindrome mod nn.uint == 0: (palcnt.inc; if palcnt > to_skip: result.add palindrome)\n\t\t\t\tpalindrome += basep\n\t\t\tif result.len >= keep: result.setLen(keep); return\n\nlet start = epochTime()\n\nvar (count, keep) = (20, 20)\necho(\"First 20 palindromic gapful numbers ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (100, 15)\necho(\"\\nLast 15 of first 100 palindromic gapful numbers ending in:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (1_000, 10)\necho(\"\\nLast 10 of first 1000 palindromic gapful numbers ending in:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (100_000, 1)\necho(\"\\n100,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (1_000_000, 1)\necho(\"\\n1,000,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\n(count, keep) = (10_000_000, 1)\necho(\"\\n10,000,000th palindromic gapful number ending with:\")\nfor digit in 1..9: echo(digit, \" : \", palindromicgapfuls(digit, count, keep) )\n\necho (epochTime() - start)\n" + }, + { + "id": 1269, + "length": 2422, + "source": "Rosetta Code", + "text": "import random\nimport strformat\nimport strutils\n\ntype\n\n\t# Enumeration type for bases.\n\tBase {.pure.} = enum A, C, G, T, Other = \"other\"\n\n\t# Sequence of bases.\n\tDnaSequence = string\n\n\t# Kind of mutation.\n\tMutation = enum mutSwap, mutDelete, mutInsert\n\nconst MaxBaseVal = ord(Base.high) - 1 # Maximum base value.\n\n\ntemplate toChar(base: Base): char = ($base)[0]\n\n\nproc newDnaSeq(length: Natural): DnaSequence =\n\t## Create a DNA sequence of given length.\n\n\tresult = newStringOfCap(length)\n\tfor _ in 1..length:\n\t\tresult.add($Base(rand(MaxBaseVal)))\n\n\nproc mutate(dnaSeq: var DnaSequence) =\n\t## Mutate a sequence (it is changed in place).\n\n\t# Choose randomly the position of mutation.\n\tlet idx = rand(dnaSeq.high)\n\n\t# Choose randomly the kind of mutation.\n\tlet mut = Mutation(rand(ord(Mutation.high)))\n\n\t# Apply the mutation.\n\tcase mut\n\n\tof mutSwap:\n\t\tlet newBase = Base(rand(MaxBaseVal))\n\t\techo fmt\"Changing base at position {idx + 1} from {dnaSeq[idx]} to {newBase}\"\n\t\tdnaSeq[idx] = newBase.toChar\n\n\tof mutDelete:\n\t\techo fmt\"Deleting base {dnaSeq[idx]} at position {idx + 1}\"\n\t\tdnaSeq.delete(idx, idx)\n\n\tof mutInsert:\n\t\tlet newBase = Base(rand(MaxBaseVal))\n\t\techo fmt\"Inserting base {newBase} at position {idx + 1}\"\n\t\tdnaSeq.insert($newBase, idx)\n\n\nproc display(dnaSeq: DnaSequence) =\n\t## Display a DNA sequence using EMBL format.\n\n\tvar counts: array[Base, Natural] # Count of bases.\n\tfor c in dnaSeq:\n\t\tinc counts[parseEnum[Base]($c, Other)] # Use Other as default value.\n\n\t# Display the SQ line.\n\tvar sqline = fmt\"SQ {dnaSeq.len} BP; \"\n\tfor (base, count) in counts.pairs:\n\t\tsqline &= fmt\"{count} {base}; \"\n\techo sqline\n\n\t# Display the sequence.\n\tvar idx = 0\n\tvar row = newStringOfCap(80)\n\tvar remaining = dnaSeq.len\n\n\twhile remaining > 0:\n\t\trow.setLen(0)\n\t\trow.add(\" \")\n\n\t\t# Add groups of 10 bases.\n\t\tfor group in 1..6:\n\t\t\tlet nextIdx = idx + min(10, remaining)\n\t\t\tfor i in idx..8}\")\n\t\techo row\n\n\t# Add termination.\n\techo \"//\"\n\n\nrandomize()\nvar dnaSeq = newDnaSeq(200)\necho \"Initial sequence\"\necho \"---------------\\n\"\ndnaSeq.display()\n\necho \"\\nMutations\"\necho \"---------\\n\"\nfor _ in 1..10:\n\tdnaSeq.mutate()\n\necho \"\\nMutated sequence\"\necho \"----------------\\n\"\ndnaSeq.display()\n" + }, + { + "id": 1270, + "length": 1054, + "source": "Rosetta Code", + "text": "import strutils\n\nconst N = 10_000_000\n\n# Erastosthenes sieve.\nvar composite: array[0..N, bool] # Defualt is false i.e. composite.\ncomposite[0] = true\ncomposite[1] = true\nfor n in 2..N:\n\tif not composite[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tcomposite[k] = true\n\ntemplate isPrime(n: int): bool = not composite[n]\n\n\nproc isUmprimeable(n: Positive): bool =\n\tif n.isPrime: return false\n\tvar nd = $n\n\tfor i, prevDigit in nd:\n\t\tfor newDigit in '0'..'9':\n\t\t\tif newDigit != prevDigit:\n\t\t\t\tnd[i] = newDigit\n\t\t\t\tif nd.parseInt.isPrime: return false\n\t\tnd[i] = prevDigit # Restore initial digit.\n\tresult = true\n\n\necho \"First 35 unprimeable numbers:\"\nvar n = 100\nvar list: seq[int]\nwhile list.len < 35:\n\tif n.isUmprimeable:\n\t\tlist.add n\n\tinc n\necho list.join(\" \"), '\\n'\n\nvar count = 0\nn = 199\nwhile count != 600:\n\tinc n\n\tif n.isUmprimeable: inc count\necho \"600th unprimeable number: \", ($n).insertSep(','), '\\n'\n\nfor d in 0..9:\n\tvar n = 200 + d\n\twhile not n.isUmprimeable:\n\t\tinc n, 10\n\techo \"Lowest unprimeable number ending in \", d, \" is \", ($n).insertSep(',')\n" + }, + { + "id": 1271, + "length": 2443, + "source": "Rosetta Code", + "text": "import algorithm, strutils\n\ntype\n\tPerimeter = seq[int]\n\tFace = tuple[name: char; perimeter: Perimeter]\n\tEdge = tuple[first, last: int]\n\nconst None = -1 # No point.\n\n\nfunc isSame(p1, p2: Perimeter): bool =\n\t## Return \"true\" if \"p1\" and \"p2\" represent the same face.\n\n\tif p1.len != p2.len: return false\n\n\tfor p in p1:\n\t\tif p notin p2: return false\n\n\tvar start = p2.find(p1[0])\n\tif p1 == p2[start..^1] & p2[0.. 0:\n\t\t# Search an edge.\n\t\tvar idx = None\n\t\tfor i, e in edges:\n\t\t\tif e.first == nextPoint or e.last == nextPoint:\n\t\t\t\tidx = i\n\t\t\t\tnextPoint = if nextpoint == e.first: e.last else: e.first\n\t\t\t\tbreak\n\t\tif idx == None:\n\t\t\treturn @[] # No edge found containing \"newPoint\".\n\n\t\t# Add next point to perimeter and remove the edge.\n\t\tresult.add(nextPoint)\n\t\tedges.del(idx)\n\n\t# Check that last added point is the expected one.\n\tif nextPoint != firstEdge.last:\n\t\treturn @[]\n\n\nwhen isMainModule:\n\n\t# List of pairs of perimeter formatted faces to compare.\n\tconst FP = [(('P', @[8, 1, 3]), ('R', @[1, 3, 8])),\n\t\t\t\t\t\t\t(('U', @[18, 8, 14, 10, 12, 17, 19]), ('V', @[8, 14, 10, 12, 17, 19, 18]))]\n\n\techo \"Perimeter comparison:\"\n\tfor (p1, p2) in FP:\n\t\techo p1, if isSame(p1[1], p2[1]): \" is same as \" else: \"is not same as\", p2\n\n\t# List of edge formatted faces.\n\tconst FE = {'E': @[(1, 11), (7, 11), (1, 7)],\n\t\t\t\t\t\t\t'F': @[(11, 23), (1, 17), (17, 23), (1, 11)],\n\t\t\t\t\t\t\t'G': @[(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)],\n\t\t\t\t\t\t\t'H': @[(1, 3), (9, 11), (3, 11), (1, 11)]}\n\n\techo \"\"\n\techo \"Conversion from edge to perimeter format:\"\n\tfor (faceName, edges) in FE:\n\t\tlet perimeter = edges.toPerimeter()\n\t\techo faceName, \": \", if perimeter.len == 0: \"Invalid edge list\" else: $perimeter\n" + }, + { + "id": 1272, + "length": 3438, + "source": "Rosetta Code", + "text": "import strformat, strutils, tables\n\ntype\n\n\tSequence = seq[Natural]\n\n\tContext = object\n\t\tdivisors: seq[int]\n\t\tsubtractors: seq[int]\n\t\tseqCache: Table[int, Sequence] # Mapping number -> sequence to reach 1.\n\t\tstepCache: Table[int, int] # Mapping number -> number of steps to reach 1.\n\n\nproc initContext(divisors, subtractors: openArray[int]): Context =\n\t## Initialize a context.\n\tfor d in divisors: doAssert d > 1, \"divisors must be greater than 1.\"\n\tfor s in subtractors: doAssert s > 0, \"substractors must be greater than 0.\"\n\tresult.divisors = @divisors\n\tresult.subtractors = @subtractors\n\tresult.seqCache[1] = @[Natural 1]\n\tresult.stepCache[1] = 0\n\n\nproc minStepsDown(context: var Context; n: Natural): Sequence =\n\t# Return a minimal sequence to reach the value 1.\n\n\tassert n > 0, \"n must be positive.\"\n\tif n in context.seqCache: return context.seqCache[n]\n\n\tvar\n\t\tminSteps = int.high\n\t\tminPath: Sequence\n\n\tfor val in context.divisors:\n\t\tif n mod val == 0:\n\t\t\tvar path = context.minStepsDown(n div val)\n\t\t\tif path.len < minSteps:\n\t\t\t\tminSteps = path.len\n\t\t\t\tminPath = move(path)\n\n\tfor val in context.subtractors:\n\t\tif n - val > 0:\n\t\t\tvar path = context.minStepsDown(n - val)\n\t\t\tif path.len < minSteps:\n\t\t\t\tminSteps = path.len\n\t\t\t\tminPath = move(path)\n\n\tresult = n & minPath\n\tcontext.seqCache[n] = result\n\n\nproc minStepsDownCount(context: var Context; n: Natural): int =\n\t## Compute the mininum number of steps without keeping the sequence.\n\n\tassert n > 0, \"n must be positive.\"\n\tif n in context.stepCache: return context.stepCache[n]\n\n\tresult = int.high\n\n\tfor val in context.divisors:\n\t\tif n mod val == 0:\n\t\t\tlet steps = context.minStepsDownCount(n div val)\n\t\t\tif steps < result: result = steps\n\n\tfor val in context.subtractors:\n\t\tif n - val > 0:\n\t\t\tlet steps = context.minStepsDownCount(n - val)\n\t\t\tif steps < result: result = steps\n\n\tinc result\n\tcontext.stepCache[n] = result\n\n\ntemplate plural(n: int): string =\n\tif n > 1: \"s\" else: \"\"\n\nproc printMinStepsDown(context: var Context; n: Natural) =\n\t## Search and print the sequence to reach one.\n\n\tlet sol = context.minStepsDown(n)\n\tstdout.write \"{n} takes {sol.len - 1} step{plural(sol.len - 1)}: \"\n\tvar prev = 0\n\tfor val in sol:\n\t\tif prev == 0:\n\t\t\tstdout.write val\n\t\telif prev - val in context.subtractors:\n\t\t\tstdout.write \" - \", prev - val, \" -> \", val\n\t\telse:\n\t\t\tstdout.write \" / \", prev div val, \" -> \", val\n\t\tprev = val\n\tstdout.write '\\n'\n\n\nproc maxMinStepsCount(context: var Context; nmax: Positive): tuple[steps: int; list: seq[int]] =\n\t## Return the maximal number of steps needed for numbers between 1 and \"nmax\"\n\t## and the list of numbers needing this number of steps.\n\n\tfor n in 2..nmax:\n\t\tlet nsteps = context.minStepsDownCount(n)\n\t\tif nsteps == result.steps:\n\t\t\tresult.list.add n\n\t\telif nsteps > result.steps:\n\t\t\tresult.steps = nsteps\n\t\t\tresult.list = @[n]\n\n\nproc run(divisors, subtractors: openArray[int]) =\n\t## Run the search for given divisors and subtractors.\n\n\tvar context = initContext(divisors, subtractors)\n\techo \"Using divisors: {divisors} and substractors: {subtractors}\"\n\tfor n in 1..10: context.printMinStepsDown(n)\n\tfor nmax in [2_000, 20_000]:\n\t\tlet (steps, list) = context.maxMinStepsCount(nmax)\n\t\tstdout.write if list.len == 1: \"There is 1 number \" else: \"There are {list.len} numbers \"\n\t\techo \"below {nmax} that require {steps} steps: \", list.join(\", \")\n\n\nrun(divisors = [2, 3], subtractors = [1])\necho \"\"\nrun(divisors = [2, 3], subtractors = [2])\n" + }, + { + "id": 1273, + "length": 671, + "source": "Rosetta Code", + "text": "template isOdd(n: int): bool = (n and 1) != 0\ntemplate isEven(n: int): bool = (n and 1) == 0\n\n\nfunc jacobi(n, k: int): range[-1..1] =\n\tassert k > 0 and k.isOdd\n\tvar n = n mod k\n\tvar k = k\n\tresult = 1\n\twhile n != 0:\n\t\twhile n.isEven:\n\t\t\tn = n shr 1\n\t\t\tif (k and 7) in [3, 5]:\n\t\t\t\tresult = -result\n\t\tswap n, k\n\t\tif (n and 3) == 3 and (k and 3) == 3:\n\t\t\tresult = -result\n\t\tn = n mod k\n\tif k != 1: result = 0\n\nwhen isMainModule:\n\n\timport strutils\n\n\tstdout.write \"n/k|\"\n\tfor n in 1..20:\n\t\tstdout.write align($n, 3)\n\techo '\\n' & repeat(\"-\", 64)\n\n\tfor k in countup(1, 21, 2):\n\t\tstdout.write align($k, 2), \" |\"\n\t\tfor n in 1..20:\n\t\t\tstdout.write align($jacobi(n, k), 3)\n\t\techo \"\"\n" + }, + { + "id": 1274, + "length": 771, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc digitsSum(n, sum: uint64): uint64 =\n\t## Returns the sum of the digits of n given the sum of the digits of n - 1.\n\tresult = sum + 1\n\tvar n = n\n\twhile n > 0 and n mod 10 == 0:\n\t\tdec result, 9\n\t\tn = n div 10\n\nfunc divisible(n, d: uint64): bool {.inline.} =\n\tif (d and 1) == 0 and (n and 1) == 1:\n\t\treturn false\n\tresult = n mod d == 0\n\nwhen isMainModule:\n\n\techo \"Gap index Gap Niven index Niven number\"\n\n\tvar\n\t\tniven, gap, sum, nivenIndex = 0u64\n\t\tprevious, gapIndex = 1u64\n\n\twhile gapIndex <= 32:\n\t\tinc niven\n\t\tsum = digitsSum(niven, sum)\n\t\tif divisible(niven, sum):\n\t\t\tif niven > previous + gap:\n\t\t\t\tgap = niven - previous\n\t\t\t\techo fmt\"{gapIndex:9d} {gap:4d} {nivenIndex:12d} {previous:13d}\"\n\t\t\t\tinc gapIndex\n\t\t\tprevious = niven\n\t\t\tinc nivenIndex\n" + }, + { + "id": 1275, + "length": 1327, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst\n\tLfloat64 = pow(2.0, 64)\n\tLog10_2_64 = int(Lfloat64 * log10(2.0))\n\n\nfunc ordinal(n: int): string =\n\tcase n\n\tof 1: \"1st\"\n\tof 2: \"2nd\"\n\tof 3: \"3rd\"\n\telse: $n & \"th\"\n\n\nproc findExp(number, countLimit: int) =\n\n\tvar i = number\n\tvar digits = 1\n\twhile i >= 10:\n\t\tdigits *= 10\n\t\ti = i div 10\n\n\tvar lmtLower, lmtUpper: uint64\n\tvar log10num = log10((number + 1) / digits)\n\tif log10num >= 0.5:\n\t\tlmtUpper = if (number + 1) / digits < 10: uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2)\n\t\t\t\t\t\t\t else: 0\n\t\tlog10Num = log10(number / digits)\n\t\tlmtLower = uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2)\n\telse:\n\t\tlmtUpper = uint(log10Num * Lfloat64)\n\t\tlmtLower = uint(log10(number / digits) * Lfloat64)\n\n\tvar count = 0\n\tvar frac64 = 0u64\n\tvar p = 0\n\tif lmtUpper != 0:\n\t\twhile true:\n\t\t\tinc p\n\t\t\tinc frac64, Log10_2_64\n\t\t\tif frac64 in lmtLower..lmtUpper:\n\t\t\t\tinc count\n\t\t\t\tif count >= countLimit:\n\t\t\t\t\tbreak\n\telse:\n\t\t# Searching for \"999...\".\n\t\twhile true:\n\t\t\tinc p\n\t\t\tinc frac64, Log10_2_64\n\t\t\tif frac64 >= lmtLower:\n\t\t\t\tinc count\n\t\t\t\tif count >= countLimit:\n\t\t\t\t\tbreak\n\n\techo fmt\"\"\"The {ordinal(count)} occurrence of 2 raised to a power\"\"\" &\n\t\t\t fmt\"\"\" whose product starts with \"{number}\" is {p}\"\"\"\n\n\nfindExp(12, 1)\nfindExp(12, 2)\n\nfindExp(123, 45)\nfindExp(123, 12345)\nfindExp(123, 678910)\n" + }, + { + "id": 1276, + "length": 719, + "source": "Rosetta Code", + "text": "import sequtils, strformat\n\nfunc mertensNumbers(max: int): seq[int] =\n\tresult = repeat(1, max + 1)\n\tfor n in 2..max:\n\t\tfor k in 2..n:\n\t\t\tdec result[n], result[n div k]\n\nconst Max = 1000\nlet mertens = mertensNumbers(Max)\n\necho \"First 199 Mertens numbers:\"\nconst Count = 200\nvar column = 0\nfor i in 0.. 0: stdout.write ' '\n\tstdout.write if i == 0: \" \" else: \"{mertens[i]:>2}\"\n\tinc column\n\tif column == 20:\n\t\tstdout.write '\\n'\n\t\tcolumn = 0\n\nvar zero, cross, previous = 0\nfor i in 1..Max:\n\tlet m = mertens[i]\n\tif m == 0:\n\t\tinc zero\n\t\tif previous != 0:\n\t\t\tinc cross\n\tprevious = m\n\necho \"\"\necho \"M(n) is zero {zero} times for 1 =< n =< {Max}.\"\necho \"M(n) crosses zero {cross} times for 1 =< n =< {Max}.\"\n" + }, + { + "id": 1277, + "length": 981, + "source": "Rosetta Code", + "text": "import std/[math, sequtils, strformat]\n\nfunc getStep(n: int): int {.inline.} =\n\tresult = 1 + n shl 2 - n shr 1 shl 1\n\nfunc primeFac(n: int): seq[int] =\n\tvar\n\t\tmaxq = int(sqrt(float(n)))\n\t\td = 1\n\t\tq: int = 2 + (n and 1) # Start with 2 or 3 according to oddity.\n\n\twhile q <= maxq and n %% q != 0:\n\t\tq = getStep(d)\n\t\tinc d\n\tif q <= maxq:\n\t\tlet q1 = primeFac(n /% q)\n\t\tlet q2 = primeFac(q)\n\t\tresult = concat(q2, q1, result)\n\telse:\n\t\tresult.add(n)\n\nfunc squareFree(num: int): bool =\n\tlet fact = primeFac num\n\n\tfor i in fact:\n\t\tif fact.count(i) > 1:\n\t\t\treturn false\n\n\treturn true\n\nfunc mobius(num: int): int =\n\tif num == 1: return num\n\n\tlet fact = primeFac num\n\n\tfor i in fact:\n\t\t## check if it has a squared prime factor\n\t\tif fact.count(i) == 2:\n\t\t\treturn 0\n\n\tif num.squareFree:\n\t\tif fact.len mod 2 == 0:\n\t\t\treturn 1\n\t\telse:\n\t\t\treturn -1\n\nwhen isMainModule:\n\techo \"The first 199 mobius numbers are:\"\n\n\tfor i in 1..199:\n\t\tstdout.write fmt\"{mobius(i):4}\"\n\t\tif i mod 20 == 0:\n\t\t\techo \"\"\n" + }, + { + "id": 1278, + "length": 1298, + "source": "Rosetta Code", + "text": "import strformat, strutils, times\nimport bignum\n\nlet\n\tOne = newInt(1)\n\tTwo = newInt(2)\n\tThree = newInt(3)\n\nproc lucas(n: Int): Int =\n\n\tproc inner(n: Int): (Int, Int) =\n\t\tif n.isZero: return (newInt(0), newInt(1))\n\t\tvar t = n shr 1\n\t\tvar (u, v) = inner(t)\n\t\tt = n and Two\n\t\tlet q = t - One\n\t\tvar r = newInt(0)\n\t\tu *= u\n\t\tv *= v\n\t\tt = n and One\n\t\tif t == One:\n\t\t\tt = (u - q) * Two\n\t\t\tr = v * Three\n\t\t\tresult = (u + v, r - t)\n\t\telse:\n\t\t\tt = u * Three\n\t\t\tr = v + q\n\t\t\tr *= Two\n\t\t\tresult = (r - t, u + v)\n\n\tvar t = n shr 1\n\tlet (u, v) = inner(t)\n\tlet l = v * Two - u\n\tt = n and One\n\tif t == One:\n\t\tlet q = n and Two - One\n\t\treturn v * l + q\n\n\treturn u * l\n\nlet start = now()\n\nvar n: Int\nvar i = 10\nwhile i <= 10_000_000:\n\tn = newInt(i)\n\tlet s = $lucas(n)\n\n\techo \"The digits of the {($i).insertSep}th Fibonacci number ({($s.len).insertSep}) are:\"\n\tif s.len > 20:\n\t\techo \" First 20 : {s[0..19]}\"\n\t\tif s.len < 40:\n\t\t\techo \" Final {s.len-20:<2} : {s[20..^1]}\"\n\t\telse:\n\t\t\techo \" Final 20 : {s[^20..^1]}\"\n\telse:\n\t\techo \" All {s.len:<2} : {s}\"\n\techo()\n\ti *= 10\n\nfor e in [culong 16, 32]:\n\tn = One shl e\n\tlet s = $lucas(n)\n\techo \"The digits of the 2^{e}th Fibonacci number ({($s.len).insertSep}) are:\"\n\techo \" First 20 : {s[0..19]}\"\n\techo \" Final 20 : {s[^20..^1]}\"\n\techo()\n\necho \"Took {now() - start}\"\n" + }, + { + "id": 1279, + "length": 906, + "source": "Rosetta Code", + "text": "import math, strutils\n\n\niterator countInBase(b: Positive): seq[Natural] =\n\t## Yield the successive integers in base \"b\" as a sequence of digits.\n\n\tvar value = @[Natural 0]\n\tyield value\n\n\twhile true:\n\n\t\t# Add one to current value.\n\t\tvar c = 1\n\t\tfor i in countdown(value.high, 0):\n\t\t\tlet val = value[i] + c\n\t\t\tif val < b:\n\t\t\t\tvalue[i] = val\n\t\t\t\tc = 0\n\t\t\telse:\n\t\t\t\tvalue[i] = val - b\n\t\t\t\tc = 1\n\n\t\tif c == 1:\n\t\t\t# Add a new digit at the beginning.\n\t\t\t# In this case, for better performances, we could have add it at the end.\n\t\t\tvalue.insert(c, 0)\n\n\t\tyield value\n\n\nfunc thueMorse(b: Positive; count: Natural): seq[Natural] =\n\t## Return the \"count\" first elements of Thue-Morse sequence for base \"b\".\n\n\tvar count = count\n\tfor n in countInBase(b):\n\t\tresult.add(sum(n) mod b)\n\t\tdec count\n\t\tif count == 0: break\n\n\nfor base in [2, 3, 5, 11]:\n\techo \"Base \", ($base & \": \").alignLeft(4), thueMorse(base, 25).join(\" \")\n" + }, + { + "id": 1280, + "length": 1475, + "source": "Rosetta Code", + "text": "import algorithm, math, strformat, strutils\n\nfunc isSquareFree(n: uint64): bool =\n\tconst Primes = [uint64 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n\t\t\t\t\t\t\t\t\t\t\t\t 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n\tfor p in Primes:\n\t\tlet p2 = p * p\n\t\tif p2 > n: break\n\t\tif n mod p2 == 0: return false\n\tresult = true\n\n\nfunc iroot(n: uint64; r: Natural): uint64 =\n\tconst Adj = 1e-6\n\tresult = uint64(pow(float(n), 1 / r) + Adj)\n\n\nfunc powerful(n: uint64; k: Natural): seq[uint64] =\n\tvar res: seq[uint64]\n\n\tfunc f(m: uint64; r: Natural) =\n\t\tif r < k:\n\t\t\tres.add m\n\t\t\treturn\n\t\tlet root = iroot(n div m, r)\n\t\tfor v in 1..root:\n\t\t\tif r > k and (not v.isSquareFree or gcd(m, v) != 1):\n\t\t\t\tcontinue\n\t\t\tf(m * v^r, r - 1)\n\n\tf(1, 2 * k - 1)\n\tres.sort()\n\treturn res\n\n\nfunc powerfulCount(n: uint64; k: Natural): uint64 =\n\tvar count = 0u64\n\n\tfunc f(m: uint64; r: Natural) =\n\t\tlet root = iroot(n div m, r)\n\t\tif r <= k:\n\t\t\tcount += root\n\t\t\treturn\n\t\tfor v in 1..root:\n\t\t\tif v.isSquareFree and gcd(m, v) == 1:\n\t\t\t\tf(m * v^r, r - 1)\n\n\tf(1, 2 * k - 1)\n\treturn count\n\n\nvar p: uint64 = 10\nfor k in 2..10:\n\tp *= 10\n\tlet result = powerful(p, k)\n\tlet head = result[0..4].join(\" \")\n\tlet tail = result[^5..^1].join(\" \")\n\techo \"{result.len} {k:2}-powerful numbers <= 10^{k}: {head} ... {tail}\"\necho()\n\nfor k in 2..10:\n\tp = 1\n\tvar counts: seq[uint64]\n\tfor j in 0..k+9:\n\t\tcounts.add powerfulcount(p, k)\n\t\tp *= 10\n\techo \"Count of {k:2}-powerful numbers <= 10^j, j in 0 <= j < {k+10}: {counts.join(\\\" \\\")}\"\n" + }, + { + "id": 1281, + "length": 1057, + "source": "Rosetta Code", + "text": "import algorithm\n\ntype Digit = range[0..9]\n\nfunc digits(n: Natural): seq[Digit] =\n\t## Return the list of digits of \"n\" in reverse order.\n\tif n == 0: return @[Digit 0]\n\tvar n = n\n\twhile n != 0:\n\t\tresult.add n mod 10\n\t\tn = n div 10\n\nfunc nextHighest(n: Natural): Natural =\n\t## Find the next highest integer of \"n\".\n\t## If none is found, \"n\" is returned.\n\tvar d = digits(n) # Warning: in reverse order.\n\tvar m = d[0]\n\tfor i in 1..d.high:\n\t\tif d[i] < m:\n\t\t\t# Find the digit greater then d[i] and closest to it.\n\t\t\tvar delta = m - d[i] + 1\n\t\t\tvar best: int\n\t\t\tfor j in 0.. 0 and diff < delta:\n\t\t\t\t\t# Greater and closest.\n\t\t\t\t\tdelta = diff\n\t\t\t\t\tbest = j\n\t\t\t# Exchange digits.\n\t\t\tswap d[i], d[best]\n\t\t\t# Sort previous digits.\n\t\t\td[0.. \", nextHighest(n)\n" + }, + { + "id": 1282, + "length": 1283, + "source": "Rosetta Code", + "text": "import math\n\ntype\n\n\tSierpinskiCurve = object\n\t\tx, y: float\n\t\tangle: float\n\t\tlength: int\n\t\tfile: File\n\n\nproc line(sc: var SierpinskiCurve) =\n\tlet theta = degToRad(sc.angle)\n\tsc.x += sc.length.toFloat * cos(theta)\n\tsc.y += sc.length.toFloat * sin(theta)\n\tsc.file.write \" L\", sc.x, ',', sc.y\n\n\nproc execute(sc: var SierpinskiCurve; s: string) =\n\tsc.file.write 'M', sc.x, ',', sc.y\n\tfor c in s:\n\t\tcase c\n\t\tof 'F': sc.line()\n\t\tof '+': sc.angle = floorMod(sc.angle + 90, 360)\n\t\tof '-': sc.angle = floorMod(sc.angle - 90, 360)\n\t\telse: discard\n\n\nfunc rewrite(s: string): string =\n\tfor c in s:\n\t\tif c == 'X':\n\t\t\tresult.add \"XF-F+F-XF+F+XF-F+F-X\"\n\t\telse:\n\t\t\tresult.add c\n\n\nproc write(sc: var SierpinskiCurve; size, length, order: int) =\n\tsc.length = length\n\tsc.x = (size - length) / 2\n\tsc.y = length.toFloat\n\tsc.angle = 0\n\tsc.file.write \"\\n\"\n\tsc.file.write \"\\n\"\n\tsc.file.write \"\\n\\n\"\n\n\nlet outfile = open(\"sierpinski_square.svg\", fmWrite)\nvar sc = SierpinskiCurve(file: outfile)\nsc.write(635, 5, 5)\noutfile.close()\n" + }, + { + "id": 1283, + "length": 1458, + "source": "Rosetta Code", + "text": "import math\n\nconst Sqrt3_2 = sqrt(3.0) / 2.0\n\ntype Point = tuple[x, y: float]\n\n\nfunc sierpinskiArrowheadNext(points: seq[Point]): seq[Point] =\n\tresult.setLen(3 * (points.len - 1) + 1)\n\tvar j = 0\n\tfor i in 0..\\n\"\n\toutfile.write \"\\n\"\n\toutfile.write \"\\n\\n\"\n\n\nlet outfile = open(\"sierpinski_arrowhead.svg\", fmWrite)\noutfile.writeSierpinskiArrowhead(600, 8)\noutfile.close()\n" + }, + { + "id": 1284, + "length": 1661, + "source": "Rosetta Code", + "text": "import math, strformat, tables\n\nfunc primes(n: Positive): seq[int] =\n\t## Return the list of prime divisors of \"n\".\n\tvar n = n.int\n\tfor d in 2..n:\n\t\tvar q = n div d\n\t\tvar m = n mod d\n\t\twhile m == 0:\n\t\t\tresult.add d\n\t\t\tn = q\n\t\t\tq = n div d\n\t\t\tm = n mod d\n\nfunc isPrime(n: Positive): bool =\n\t## Return true if \"n\" is prime.\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d <= sqrt(n.toFloat).int:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nfunc pisanoPeriod(m: Positive): int =\n\t## Calculate the Pisano period of 'm' from first principles.\n\tvar p = 0\n\tvar c = 1\n\tfor i in 0.. 0:\n\t\t\techo \"pisanoPrime({p:2}, 2) = {pp}\"\n\n\techo()\n\tfor p in 2..179:\n\t\tlet pp = pisanoPrime(p, 1)\n\t\tif pp > 0:\n\t\t\techo \"pisanoPrime({p:3}, 1) = {pp}\"\n\n\techo()\n\techo \"pisano(n) for integers 'n' from 1 to 180 are:\"\n\tfor n in 1..180:\n\t\tstdout.write \"{pisano(n):3}\", if n mod 15 == 0: '\\n' else: ' '\n" + }, + { + "id": 1285, + "length": 3118, + "source": "Rosetta Code", + "text": "import math, strutils\n\nconst Eps = 1e-14\n\ntype Point = tuple[x, y: float]\n\nfunc `$`(p: Point): string =\n\tlet x = if p.x == 0.0: 0.0 else: p.x\n\tlet y = if p.y == 0.0: 0.0 else: p.y\n\t\"($1, $2)\".format(x, y)\n\n\nfunc intersects(p1, p2, cp: Point; r: float; segment: bool): seq[Point] =\n\tlet\n\t\t(x0, y0) = cp\n\t\t(x1, y1) = p1\n\t\t(x2, y2) = p2\n\t\tA = y2 - y1\n\t\tB = x1 - x2\n\t\tC = x2 * y1 - x1 * y2\n\tvar\n\t\ta = A^2 + B^2\n\t\tb, c: float\n\t\tbnz = true\n\tif abs(B) >= Eps:\n\t\tb = 2 * (A * C + A * B * y0 - B^2 * x0)\n\t\tc = C^2 + 2 * B * C * y0 - B^2 * (r^2 - x0^2 - y0^2)\n\telse:\n\t\tb = 2 * (B * C + A * B * x0 - A^2 * y0)\n\t\tc = C^2 + 2 * A * C * x0 - A^2 * (r^2 - x0^2 - y0^2)\n\t\tbnz = false\n\tlet d = b^2 - 4 * a * c\n\tif d < 0: return # Line & circle don't intersect.\n\n\tfunc within(x, y: float): bool =\n\t\t## Checks whether a point is within a segment.\n\t\tlet\n\t\t\td1 = sqrt((x2 - x1)^2 + (y2 - y1)^2) # Distance between end-points.\n\t\t\td2 = sqrt((x - x1)^2 + (y - y1)^2) # Distance from point to one end.\n\t\t\td3 = sqrt((x2 - x)^2 + (y2 - y)^2) # Distance from point to other end.\n\t\t\tdelta = d1 - d2 - d3\n\t\tresult = abs(delta) < Eps # True if delta is less than a small tolerance.\n\n\tvar x, y: float\n\ttemplate fx: float = -(A * x + C) / B\n\ttemplate fy: float = -(B * y + C) / A\n\ttemplate rxy() =\n\t\tif not segment or within(x, y):\n\t\t\tresult.add (x, y)\n\n\tif d == 0:\n\t\t# Line is tangent to circle, so just one intersect at most.\n\t\tif bnz:\n\t\t\tx = -b / (2 * a)\n\t\t\ty = fx()\n\t\t\trxy()\n\t\telse:\n\t\t\ty = -b / (2 * a)\n\t\t\tx = fy()\n\t\t\trxy()\n\telse:\n\t\t# Two intersects at most.\n\t\tlet d = sqrt(d)\n\t\tif bnz:\n\t\t\tx = (-b + d) / (2 * a)\n\t\t\ty = fx()\n\t\t\trxy()\n\t\t\tx = (-b - d) / (2 * a)\n\t\t\ty = fx()\n\t\t\trxy()\n\t\telse:\n\t\t\ty = (-b + d) / (2 * a)\n\t\t\tx = fy()\n\t\t\trxy()\n\t\t\ty = (-b - d) / (2 * a)\n\t\t\tx = fy()\n\t\t\trxy()\n\n\nwhen isMainModule:\n\n\tvar cp: Point = (3.0, -5.0)\n\tvar r = 3.0\n\techo \"The intersection points (if any) between:\"\n\techo \"\\n A circle, center (3, -5) with radius 3, and:\"\n\techo \"\\n a line containing the points (-10, 11) and (10, -9) is/are:\"\n\techo \" \", intersects((-10.0, 11.0), (10.0, -9.0), cp, r, false)\n\techo \"\\n a segment starting at (-10, 11) and ending at (-11, 12) is/are\"\n\techo \" \", intersects((-10.0, 11.0), (-11.0, 12.0), cp, r, true)\n\techo \"\\n a horizontal line containing the points (3, -2) and (7, -2) is/are:\"\n\techo \" \", intersects((3.0, -2.0), (7.0, -2.0), cp, r, false)\n\tcp = (0.0, 0.0)\n\tr = 4.0\n\techo \"\\n A circle, center (0, 0) with radius 4, and:\"\n\techo \"\\n a vertical line containing the points (0, -3) and (0, 6) is/are:\"\n\techo \" \", intersects((0.0, -3.0), (0.0, 6.0), cp, r, false)\n\techo \"\\n a vertical segment starting at (0, -3) and ending at (0, 6) is/are:\"\n\techo \" \", intersects((0.0, -3.0), (0.0, 6.0), cp, r, true)\n\tcp = (4.0, 2.0)\n\tr = 5.0\n\techo \"\\n A circle, center (4, 2) with radius 5, and:\"\n\techo \"\\n a line containing the points (6, 3) and (10, 7) is/are:\"\n\techo \" \", intersects((6.0, 3.0), (10.0, 7.0), cp, r, false)\n\techo \"\\n a segment starting at (7, 4) and ending at (11, 8) is/are:\"\n\techo \" \", intersects((7.0, 4.0), (11.0, 8.0), cp, r, true)\n" + }, + { + "id": 1286, + "length": 1290, + "source": "Rosetta Code", + "text": "import math\n\ntype\n\n\tSierpinskiCurve = object\n\t\tx, y: float\n\t\tangle: float\n\t\tlength: int\n\t\tfile: File\n\n\nproc line(sc: var SierpinskiCurve) =\n\tlet theta = degToRad(sc.angle)\n\tsc.x += sc.length.toFloat * cos(theta)\n\tsc.y -= sc.length.toFloat * sin(theta)\n\tsc.file.write \" L\", sc.x, ',', sc.y\n\n\nproc execute(sc: var SierpinskiCurve; s: string) =\n\tsc.file.write 'M', sc.x, ',', sc.y\n\tfor c in s:\n\t\tcase c\n\t\tof 'F', 'G': sc.line()\n\t\tof '+': sc.angle = floorMod(sc.angle + 45, 360)\n\t\tof '-': sc.angle = floorMod(sc.angle - 45, 360)\n\t\telse: discard\n\n\nfunc rewrite(s: string): string =\n\tfor c in s:\n\t\tif c == 'X':\n\t\t\tresult.add \"XF+G+XF--F--XF+G+X\"\n\t\telse:\n\t\t\tresult.add c\n\n\nproc write(sc: var SierpinskiCurve; size, length, order: int) =\n\tsc.length = length\n\tsc.x = length.toFloat / sqrt(2.0)\n\tsc.y = 2 * sc.x\n\tsc.angle = 45\n\tsc.file.write \"\\n\"\n\tsc.file.write \"\\n\"\n\tsc.file.write \"\\n\\n\"\n\n\nlet outfile = open(\"sierpinski_curve.svg\", fmWrite)\nvar sc = SierpinskiCurve(file: outfile)\nsc.write(545, 7, 5)\noutfile.close()\n" + }, + { + "id": 1287, + "length": 3251, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strscans, strutils, tables\n\nconst NoColor = 0\n\ntype\n\n\tColor = range[0..63]\n\n\tNode = ref object\n\t\tnum: Natural # Node number.\n\t\tcolor: Color # Node color.\n\t\tdegree: Natural # Node degree.\n\t\tdsat: Natural # Node Dsaturation.\n\t\tneighbors: seq[Node] # List of neighbors.\n\n\tGraph = seq[Node] # List of nodes ordered by number.\n\n\nproc initGraph(graphRepr: string): Graph =\n\t## Initialize the graph from its string representation.\n\n\tvar mapping: Table[Natural, Node] # Temporary mapping.\n\tfor elem in graphRepr.splitWhitespace():\n\t\tvar num1, num2: int\n\t\tif elem.scanf(\"$i-$i\", num1, num2):\n\t\t\tlet node1 = mapping.mgetOrPut(num1, Node(num: num1))\n\t\t\tlet node2 = mapping.mgetOrPut(num2, Node(num: num2))\n\t\t\tnode1.neighbors.add node2\n\t\t\tnode2.neighbors.add node1\n\t\telif elem.scanf(\"$i\", num1):\n\t\t\tdiscard mapping.mgetOrPut(num1, Node(num: num1))\n\t\telse:\n\t\t\traise newException(ValueError, \"wrong description: \" & elem)\n\n\tfor node in mapping.values:\n\t\tnode.degree = node.neighbors.len\n\tresult = sortedByIt(toSeq(mapping.values), it.num)\n\n\nproc numbers(nodes: seq[Node]): string =\n\t## Return the numbers of a list of nodes.\n\tfor node in nodes:\n\t\tresult.addSep(\" \")\n\t\tresult.add($node.num)\n\n\nproc `$`(graph: Graph): string =\n\t## Return the description of the graph.\n\n\tvar maxColor = NoColor\n\tfor node in graph:\n\t\tstdout.write \"Node \", node.num, \": color = \", node.color\n\t\tif node.color > maxColor: maxColor = node.color\n\t\tif node.neighbors.len > 0:\n\t\t\techo \" neighbors = \", sortedByIt(node.neighbors, it.num).numbers\n\t\telse:\n\t\t\techo \"\"\n\techo \"Number of colors: \", maxColor\n\n\nproc `<`(node1, node2: Node): bool =\n\t## Comparison of nodes, by dsaturation first, then by degree.\n\tif node1.dsat == node2.dsat: node1.degree < node2.degree\n\telse: node1.dsat < node2.dsat\n\n\nproc getMaxDsatNode(nodes: var seq[Node]): Node =\n\t## Return the node with the greatest dsaturation.\n\tlet idx = nodes.maxIndex()\n\tresult = nodes[idx]\n\tnodes.delete(idx)\n\n\nproc minColor(node: Node): COLOR =\n\t## Return the minimum available color for a node.\n\tvar colorUsed: set[Color]\n\tfor neighbor in node.neighbors:\n\t\tcolorUsed.incl neighbor.color\n\tfor color in 1..Color.high:\n\t\tif color notin colorUsed: return color\n\n\nproc distinctColorsCount(node: Node): Natural =\n\t## Return the number of distinct colors of the neighbors of a node.\n\tvar colorUsed: set[Color]\n\tfor neighbor in node.neighbors:\n\t\tcolorUsed.incl neighbor.color\n\tresult = colorUsed.card\n\n\nproc updateDsats(node: Node) =\n\t## Update the dsaturations of the neighbors of a node.\n\tfor neighbor in node.neighbors:\n\t\tif neighbor.color == NoColor:\n\t\t\tneighbor.dsat = neighbor.distinctColorsCount()\n\n\nproc colorize(graphRepr: string) =\n\t## Colorize a graph.\n\n\tlet graph = initGraph(graphRepr)\n\tvar nodes = sortedByIt(graph, -it.degree) # Copy or graph sorted by decreasing degrees.\n\twhile nodes.len > 0:\n\t\tlet node = nodes.getMaxDsatNode()\n\t\tnode.color = node.minColor()\n\t\tnode.updateDsats()\n\n\techo \"Graph: \", graphRepr\n\techo graph\n\n\n\nwhen isMainModule:\n\tcolorize(\"0-1 1-2 2-0 3\")\n\tcolorize(\"1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\")\n\tcolorize(\"1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\")\n\tcolorize(\"1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\")\n" + }, + { + "id": 1288, + "length": 2005, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc isEsthetic(n, b: int64): bool =\n\tif n == 0: return false\n\tvar i = n mod b\n\tvar n = n div b\n\twhile n > 0:\n\t\tlet j = n mod b\n\t\tif abs(i - j) != 1:\n\t\t\treturn false\n\t\tn = n div b\n\t\ti = j\n\tresult = true\n\n\nproc listEsths(n1, n2, m1, m2: int64; perLine: int; all: bool) =\n\tvar esths: seq[int64]\n\n\tfunc dfs(n, m, i: int64) =\n\t\tif i in n..m: esths.add i\n\t\tif i == 0 or i > m: return\n\t\tlet d = i mod 10\n\t\tlet i1 = i * 10 + d - 1\n\t\tlet i2 = i1 + 2\n\t\tcase d\n\t\tof 0:\n\t\t\tdfs(n, m, i2)\n\t\tof 9:\n\t\t\tdfs(n, m, i1)\n\t\telse:\n\t\t\tdfs(n, m, i1)\n\t\t\tdfs(n, m, i2)\n\n\tfor i in 0..9:\n\t\tdfs(n2, m2, i)\n\n\techo \"Base 10: {esths.len} esthetic numbers between {n1} and {m1}:\"\n\tif all:\n\t\tfor i, esth in esths:\n\t\t\tstdout.write esth\n\t\t\tstdout.write if (i + 1) mod perLine == 0: '\\n' else: ' '\n\t\techo()\n\telse:\n\t\tfor i in 0.. 0:\n\t\tresult.add Digits[n mod b]\n\t\tn = n div b\n\tfor i in 0..<(result.len div 2):\n\t\tswap result[i], result[result.high - i]\n\n\nfor b in 2..16:\n\techo \"Base {b}: {4 * b}th to {6 * b}th esthetic numbers:\"\n\tvar n = 1i64\n\tvar c = 0i64\n\twhile c < 6 * b:\n\t\tif n.isEsthetic(b):\n\t\t\tinc c\n\t\t\tif c >= 4 * b: stdout.write n.toBase(b), ' '\n\t\tinc n\n\techo '\\n'\n\n# The following all use the obvious range limitations for the numbers in question.\nlistEsths(1000, 1010, 9999, 9898, 16, true)\nlistEsths(100_000_000, 101_010_101, 130_000_000, 123_456_789, 9, true)\nlistEsths(100_000_000_000, 101_010_101_010, 130_000_000_000, 123_456_789_898, 7, false)\nlistEsths(100_000_000_000_000, 101_010_101_010_101, 130_000_000_000, 123_456_789_898_989, 5, false)\nlistEsths(100_000_000_000_000_000, 101_010_101_010_101_010, 130_000_000_000_000_000, 123_456_789_898_989_898, 4, false)\n" + }, + { + "id": 1289, + "length": 1029, + "source": "Rosetta Code", + "text": "func isPrime(n: Natural): bool =\n\tif n < 2: return\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\treturn true\n\n\nfunc isMagnanimous(n: Natural): bool =\n\tvar p = 10\n\twhile true:\n\t\tlet a = n div p\n\t\tlet b = n mod p\n\t\tif a == 0: break\n\t\tif not isPrime(a + b): return false\n\t\tp *= 10\n\treturn true\n\n\niterator magnanimous(): (int, int) =\n\tvar n, count = 0\n\twhile true:\n\t\tif n.isMagnanimous:\n\t\t\tinc count\n\t\t\tyield (count, n)\n\t\tinc n\n\n\nfor (i, n) in magnanimous():\n\tif i in 1..45:\n\t\tif i == 1: stdout.write \"First 45 magnanimous numbers:\\n \"\n\t\tstdout.write n, if i == 45: '\\n' else: ' '\n\n\telif i in 241..250:\n\t\tif i == 241: stdout.write \"\\n241st through 250th magnanimous numbers:\\n \"\n\t\tstdout.write n, if i == 250: \"\\n\" else: \" \"\n\n\telif i in 391..400:\n\t\tif i == 391: stdout.write \"\\n391st through 400th magnanimous numbers:\\n \"\n\t\tstdout.write n, if i == 400: \"\\n\" else: \" \"\n\n\telif i > 400:\n\t\tbreak\n" + }, + { + "id": 1290, + "length": 1535, + "source": "Rosetta Code", + "text": "import strutils\n\nconst RevDate = \"2021-02-05\"\n\n# We use the concatenation operator \"\" to assemble the strings.\n# This is done at compile time and so the result is a long literal.\nconst ElementString =\n\t\"hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine \" &\n\t\"neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon \" &\n\t\"potassium calcium scandium titanium vanadium chromium manganese iron \" &\n\t\"cobalt nickel copper zinc gallium germanium arsenic selenium bromine \" &\n\t\"krypton rubidium strontium yttrium zirconium niobium molybdenum \" &\n\t\"technetium ruthenium rhodium palladium silver cadmium indium tin \" &\n\t\"antimony tellurium iodine xenon cesium barium lanthanum cerium \" &\n\t\"praseodymium neodymium promethium samarium europium gadolinium terbium \" &\n\t\"dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum \" &\n\t\"tungsten rhenium osmium iridium platinum gold mercury thallium lead \" &\n\t\"bismuth polonium astatine radon francium radium actinium thorium \" &\n\t\"protactinium uranium neptunium plutonium americium curium berkelium \" &\n\t\"californium einsteinium fermium mendelevium nobelium lawrencium \" &\n\t\"rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium \" &\n\t\"roentgenium copernicium nihonium flerovium moscovium livermorium \" &\n\t\"tennessine oganesson\"\n\nwhen isMainModule:\n\n\tconst ElementList = ElementString.split()\n\n\techo \"Last revision date: \", RevDate\n\techo \"Number of elements: \", ElementList.len\n\techo \"Last element in list: \", ElementList[^1]\n" + }, + { + "id": 1291, + "length": 1908, + "source": "Rosetta Code", + "text": "import strutils\n\nconst RevDate = \"2021-02-05\"\n\n# We use a long string literal starting and ending with '\"\"\"'.\n# We eliminate the multiple spaces by using \"splitWhiteSpace\"\n# instead of \"split\".\n\nconst ElementString =\n\t\"\"\"\n\thydrogen helium lithium beryllium\n\tboron carbon nitrogen oxygen\n\tfluorine neon sodium magnesium\n\taluminum silicon phosphorous sulfur\n\tchlorine argon potassium calcium\n\tscandium titanium vanadium chromium\n\tmanganese iron cobalt nickel\n\tcopper zinc gallium germanium\n\tarsenic selenium bromine krypton\n\trubidium strontium yttrium zirconium\n\tniobium molybdenum technetium ruthenium\n\trhodium palladium silver cadmium\n\tindium tin antimony tellurium\n\tiodine xenon cesium barium\n\tlanthanum cerium praseodymium neodymium\n\tpromethium samarium europium gadolinium\n\tterbium dysprosium holmium erbium\n\tthulium ytterbium lutetium hafnium\n\ttantalum tungsten rhenium osmium\n\tiridium platinum gold mercury\n\tthallium lead bismuth polonium\n\tastatine radon francium radium\n\tactinium thorium protactinium uranium\n\tneptunium plutonium americium curium\n\tberkelium californium einsteinium fermium\n\tmendelevium nobelium lawrencium rutherfordium\n\tdubnium seaborgium bohrium hassium\n\tmeitnerium darmstadtium roentgenium copernicium\n\tnihonium flerovium moscovium livermorium\n\ttennessine oganesson\n\t\"\"\"\n\nwhen isMainModule:\n\n\tconst ElementList = ElementString.splitWhitespace()\n\n\techo \"Last revision date: \", RevDate\n\techo \"Number of elements: \", ElementList.len\n\techo \"Last element in list: \", ElementList[^1]\n" + }, + { + "id": 1292, + "length": 988, + "source": "Rosetta Code", + "text": "echo \"A simple string.\"\necho \"A simple string including tabulation special character \\\\t: \\t.\"\n\necho \"\"\"\nFirst part of a multiple string,\nfollowed by second part\nand third part.\n\"\"\"\n\necho r\"A raw string containing a \\.\"\n\n# Interpolation in strings.\nimport strformat\nconst C = \"constant\"\nconst S = fmt\"A string with interpolation of a {C}.\"\necho S\nvar x = 3\necho fmt\"A string with interpolation of expression 2 * x + 3: {2 * x + 3}.\"\necho fmt\"Displaying x with an embedded format: {x:05}.\"\n\n# Regular expression string.\nimport re\nlet r = re\"\\d+\"\n\n# Pegs string.\nimport pegs\nlet e = peg\"\\d+\"\n\n# Array literal.\necho [1, 2, 3] # Element type if implicit (\"int\" here).\necho [byte(1), 2, 3] # Element type is specified by the first element type.\necho [byte 1, 2, 3] # An equivalent way to specify the type.\n\necho @[1, 2, 3] # Sequence of ints.\n\n# Tuples.\necho ('a', 1, true) # Tuple without explicit field names.\necho (x: 1, y: 2) # Tuple with two int fields \"x\" and \"y\".\n" + }, + { + "id": 1293, + "length": 2374, + "source": "Rosetta Code", + "text": "import bignum\nimport strformat\n\nconst SmallPrimes = [\n\t2, 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\t101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n\t211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,\n\t307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,\n\t401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,\n\t503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,\n\t601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n\t701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\n\t809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,\n\t907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]\n\nlet\n\tOne = newInt(1)\n\tTwo = newInt(2)\n\tTen = newInt(10)\n\n\nproc isPrime(n: Int): bool =\n\n\tif n < Two: return false\n\n\tfor sp in SmallPrimes:\n\t\t# let spb = newInt(sp)\n\t\tif n == sp: return true\n\t\tif (n mod sp).isZero: return false\n\t\tif n < sp * sp: return true\n\n\tresult = probablyPrime(n, 25) != 0\n\n\nproc cycle(n: Int): Int =\n\n\tvar m = n\n\tvar p = 1\n\twhile m >= Ten:\n\t\tp *= 10\n\t\tm = m div 10\n\tresult = m + Ten * (n mod p)\n\n\nproc isCircularPrime(p: Int): bool =\n\n\tif not p.isPrime(): return false\n\n\tvar p2 = cycle(p)\n\twhile p2 != p:\n\t\tif p2 < p or not p2.isPrime():\n\t\t\treturn false\n\t\tp2 = cycle(p2)\n\tresult = true\n\n\nproc testRepunit(digits: int) =\n\n\tvar repunit = One\n\tvar count = digits - 1\n\twhile count > 0:\n\t\trepunit = Ten * repunit + One\n\t\tdec count\n\tif repunit.isPrime():\n\t\techo fmt\"R({digits}) is probably prime.\"\n\telse:\n\t\techo fmt\"R({digits}) is not prime.\"\n\n\necho \"First 19 circular primes:\"\nvar p = 2\nvar line = \"\"\nvar count = 0\nwhile count < 19:\n\tif newInt(p).isCircularPrime():\n\t\tif count > 0: line.add(\", \")\n\t\tline.add($p)\n\t\tinc count\n\tinc p\necho line\n\necho \"\"\necho \"Next 4 circular primes:\"\nvar repunit = One\nvar digits = 1\nwhile repunit < p:\n\trepunit = Ten * repunit + One\n\tinc digits\nline = \"\"\ncount = 0\nwhile count < 4:\n\tif repunit.isPrime():\n\t\tif count > 0: line.add(' ')\n\t\tline.add(fmt\"R({digits})\")\n\t\tinc count\n\trepunit = Ten * repunit + One\n\tinc digits\necho line\n\necho \"\"\ntestRepUnit(5003)\ntestRepUnit(9887)\ntestRepUnit(15073)\ntestRepUnit(25031)\ntestRepUnit(35317)\ntestRepUnit(49081)\n" + }, + { + "id": 1294, + "length": 1912, + "source": "Rosetta Code", + "text": "import math, sugar\n\nconst\n\tK = 7.8e9\n\tN0 = 27\n\tActual = [ 27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0,\n\t\t\t\t\t\t\t\t 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0,\n\t\t\t\t\t\t\t\t 60.0, 61.0, 61.0, 66.0, 83.0, 219.0, 239.0,\n\t\t\t\t\t\t\t\t392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,\n\t\t\t\t\t\t\t 4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0,\n\t\t\t\t\t\t\t20615.0, 24522.0, 28273.0, 31491.0, 34933.0, 37552.0, 40540.0,\n\t\t\t\t\t\t\t43105.0, 45177.0, 60328.0, 64543.0, 67103.0, 69265.0, 71332.0,\n\t\t\t\t\t\t\t73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,\n\t\t\t\t\t\t\t80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0,\n\t\t\t\t\t\t\t90664.0, 93077.0, 95316.0, 98172.0, 102133.0, 105824.0, 109695.0,\n\t\t\t\t\t\t 114232.0, 118610.0, 125497.0, 133852.0, 143227.0, 151367.0, 167418.0,\n\t\t\t\t\t\t 180096.0, 194836.0, 213150.0, 242364.0, 271106.0, 305117.0, 338133.0,\n\t\t\t\t\t\t 377918.0, 416845.0, 468049.0, 527767.0, 591704.0, 656866.0, 715353.0,\n\t\t\t\t\t\t 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0]\n\ntype Func = (float) -> float\n\nfunc f(r: float): float =\n\tfor i in 0..Actual.high:\n\t\tlet\n\t\t\teri = exp(r * i.toFloat)\n\t\t\tguess = (N0 * eri) / (1 + N0 * (eri - 1) / K)\n\t\t\tdiff = guess - Actual[i]\n\t\tresult += diff * diff\n\n\nfunc solve(fn: Func; guess = 0.5, epsilon = 0.0): float =\n\t\tresult = guess\n\t\tvar delta = if result != 0: result else: 1.0\n\t\tvar f0 = fn(result)\n\t\tvar factor = 2.0\n\n\t\twhile delta > epsilon and result != result - delta:\n\t\t\tvar nf = fn(result - delta)\n\t\t\tif nf < f0:\n\t\t\t\tf0 = nf\n\t\t\t\tresult -= delta\n\t\t\telse:\n\t\t\t\tnf = fn(result + delta)\n\t\t\t\tif nf < f0:\n\t\t\t\t\tf0 = nf\n\t\t\t\t\tresult += delta\n\t\t\t\telse:\n\t\t\t\t\tfactor = 0.5\n\t\t\tdelta *= factor\n\n\nlet r = f.solve()\nlet r0 = exp(12 * r)\necho \"r = \", r, \", R0 = \", r0\n" + }, + { + "id": 1295, + "length": 1471, + "source": "Rosetta Code", + "text": "import net\nimport strutils\n\n\nproc canonicalize*(address: var IpAddress; nbits: Positive) =\n\t## Canonicalize an IP address.\n\n\tvar zbits = 32 - nbits # Number of bits to reset.\n\n\t# We process byte by byte which avoids byte order issues.\n\tfor idx in countdown(address.address_v4.high, address.address_v4.low):\n\t\tif zbits == 0:\n\t\t\t# No more bits to reset.\n\t\t\tbreak\n\t\tif zbits >= 8:\n\t\t\t# Reset the current byte and continue with the remaining bits.\n\t\t\taddress.address_v4[idx] = 0\n\t\t\tdec zbits, 8\n\t\telse:\n\t\t\t# Use a mask to reset the bits.\n\t\t\taddress.address_v4[idx] = address.address_v4[idx] and (0xff'u8 shl zbits)\n\t\t\tzbits = 0\n\n\nwhen isMainModule:\n\n\timport strformat\n\n\tvar ipAddress: IpAddress\n\tvar nbits: int\n\n\tfor address in [\"87.70.141.1/22\", \"36.18.154.103/12\", \"62.62.197.11/29\",\n\t\t\t\t\t\t\t\t\t\"67.137.119.181/4\", \"161.214.74.21/24\", \"184.232.176.184/18\"]:\n\n\t\t# Parse the address.\n\t\tlet parts = address.split('/')\n\t\ttry:\n\t\t\tipAddress = parseIpAddress(parts[0])\n\t\t\tif ipAddress.family == IPV6:\n\t\t\t\traise newException(ValueError, \"\")\n\t\texcept ValueError:\n\t\t\techo \"Invalid IP V4 address: \", parts[0]\n\t\t\tquit(QuitFailure)\n\n\t\t# Check the number of bits.\n\t\ttry:\n\t\t\tnbits = parseInt(parts[1])\n\t\t\tif nbits notin 1..32:\n\t\t\t\traise newException(ValueError, \"\")\n\t\texcept ValueError:\n\t\t\techo \"Invalid number of bits: \", parts[1]\n\t\t\tquit(QuitFailure)\n\n\t\t# Canonicalize the address and display the result.\n\t\tipAddress.canonicalize(nbits)\n\t\techo \"{address:<18} -> {ipAddress}/{nbits}\"\n" + }, + { + "id": 1296, + "length": 840, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\n\nfunc isqrt*[T: SomeSignedInt | Int](x: T): T =\n\t## Compute integer square root for signed integers\n\t## and for big integers.\n\n\twhen T is Int:\n\t\tresult = newInt()\n\t\tvar q = newInt(1)\n\telse:\n\t\tresult = 0\n\t\tvar q = T(1)\n\n\twhile q <= x:\n\t\tq = q shl 2\n\n\tvar z = x\n\twhile q > 1:\n\t\tq = q shr 2\n\t\tlet t = z - result - q\n\t\tresult = result shr 1\n\t\tif t >= 0:\n\t\t\tz = t\n\t\t\tresult += q\n\n\nwhen isMainModule:\n\n\techo \"Integer square root for numbers 0 to 65:\"\n\tfor n in 0..65:\n\t\tstdout.write ' ', isqrt(n)\n\techo \"\\n\"\n\n\techo \"Integer square roots of odd powers of 7 from 7^1 to 7^73:\"\n\techo \" n\" & repeat(' ', 82) & \"7^n\" & repeat(' ', 34) & \"isqrt(7^n)\"\n\techo repeat(\"-\", 131)\n\n\tvar x = newInt(7)\n\tfor n in countup(1, 73, 2):\n\t\techo \"{n:>2} {insertSep($x, ','):>82} {insertSep($isqrt(x), ','):>41}\"\n\t\tx *= 49\n" + }, + { + "id": 1297, + "length": 2167, + "source": "Rosetta Code", + "text": "import sequtils\nimport strutils\n\ntype SandPile = array[3, array[3, int]]\n\n\niterator neighbors(i, j: int): tuple[a, b: int] =\n\t## Yield the indexes of the neighbours of cell at indexes (i, j).\n\tif i > 0:\n\t\tyield (i - 1, j)\n\tif i < 2:\n\t\tyield (i + 1, j)\n\tif j > 0:\n\t\tyield (i, j - 1)\n\tif j < 2:\n\t\tyield (i, j + 1)\n\n\nproc print(s: openArray[SandPile]) =\n\t## Print a list of sandpiles.\n\tfor i in 0..2:\n\t\tfor n, sp in s:\n\t\t\tif n != 0:\n\t\t\t\tstdout.write(if i == 1: \" => \" else: \" \")\n\t\t\tstdout.write(sp[i].join(\" \"))\n\t\tstdout.write('\\n')\n\n\nproc printSum(s1, s2, s3: SandPile) =\n\t## Print \"s1 + s2 = s3\".\n\tfor i in 0..2:\n\t\tstdout.write(s1[i].join(\" \"))\n\t\tstdout.write(if i == 1: \" + \" else: \" \", s2[i].join(\" \"))\n\t\tstdout.write(if i == 1: \" = \" else: \" \", s3[i].join(\" \"))\n\t\tstdout.write('\\n')\n\n\nfunc isStable(sandPile: SandPile): bool =\n\t## Return true if the sandpile is stable, else false.\n\tresult = true\n\tfor row in sandPile:\n\t\tif row.anyit(it > 3):\n\t\t\treturn false\n\n\nproc topple(sandPile: var SandPile) =\n\t## Eliminate one value > 3, propagating a grain to each neighbor.\n\tfor i, row in sandPile:\n\t\tfor j, val in row:\n\t\t\tif val > 3:\n\t\t\t\tdec sandPile[i][j], 4\n\t\t\t\tfor (i, j) in neighbors(i, j):\n\t\t\t\t\tinc sandPile[i][j]\n\t\t\t\treturn\n\n\nproc stabilize(sandPile: var SandPile) =\n\t## Stabilize a sandpile.\n\twhile not sandPile.isStable():\n\t\tsandPile.topple()\n\n\nproc `+`(s1, s2: SandPile): SandPile =\n\t## Add two sandpiles, stabilizing the result.\n\tfor row in 0..2:\n\t\tfor col in 0..2:\n\t\t\tresult[row][col] = s1[row][col] + s2[row][col]\n\tresult.stabilize()\n\n\nconst Separator = \"\\n-----\\n\"\n\necho \"Avalanche\\n\"\nvar s: SandPile = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]\nvar list = @[s]\nwhile not s.isStable():\n\ts.topple()\n\tlist.add(s)\nlist.print()\necho Separator\n\necho \"s1 + s2 == s2 + s1\\n\"\nlet s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]\nlet s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]\nprintSum(s1, s2, s1 + s2)\necho \"\"\nprintSum(s2, s1, s2 + s1)\necho Separator\n\necho \"s3 + s3_id == s3\\n\"\nlet s3 = [[3, 3, 3], [3, 3, 3], [3, 3, 3]]\nlet s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]\nprintSum(s3, s3_id, s3 + s3_id)\necho Separator\n\necho \"s3_id + s3_id = s3_id\\n\"\nprintSum(s3_id, s3_id, s3_id + s3_id)\n" + }, + { + "id": 1298, + "length": 1126, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nfunc toWord(w: int64): string = \"W{w:05}\"\n\nfunc fromWord(ws: string): int64 = ws[1..5].parseInt()\n\necho \"Starting figures:\"\nvar\n\tlat = 28.3852\n\tlong = -81.5638\necho \" latitude = {lat:0.4f}, longitude = {long:0.4f}\"\n\n# Convert \"lat\" and \"long\" to positive integers.\nvar\n\tilat = int64(lat * 10_000 + 900_000)\n\tilong = int64(long * 10_000 + 1_800_000)\n\n# Build 43 bit int comprising 21 bits (lat) and 22 bits (lon).\nvar latlong = ilat shl 22 + ilong\n\n# Isolate relevant bits.\nvar\n\tw1 = latlong shr 28 and 0x7fff\n\tw2 = latlong shr 14 and 0x3fff\n\tw3 = latlong and 0x3fff\n\n# Convert to word format.\nlet\n\tw1s = w1.toWord\n\tw2s = w2.toWord\n\tw3s = w3.toWord\n\n# Print the results.\necho \"\\nThree word location is:\"\necho \" {w1s} {w2s} {w3s}\"\n\n# Reverse the procedure.\nw1 = w1s.fromWord\nw2 = w2s.fromWord\nw3 = w3s.fromWord\n\nlatlong = w1 shl 28 or w2 shl 14 or w3\nilat = latlong shr 22\nilong = latlong and 0x3fffff\nlat = float(ilat - 900_000) / 10_000\nlong = float(ilong - 1_800_000) / 10_000\n\n# Print the results.\necho \"\\nAfter reversing the procedure:\"\necho \" latitude = {lat:0.4f}, longitude = {long:0.4f}\"\n" + }, + { + "id": 1299, + "length": 642, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils\n\nfunc lcs(list: varargs[string]): string =\n\tif list.len == 0: return\n\tresult = list[0]\n\tfor i in 1..list.high:\n\t\tvar newLength = 0\n\t\tfor j in 1..result.len:\n\t\t\tif j > list[i].len or list[i][^j] != result[^j]:\n\t\t\t\tbreak\n\t\t\tinc newLength\n\t\tresult = result[^newLength..^1]\n\nproc test(list: varargs[string]) =\n\tlet lst = list.mapIt('\"' & it & '\"').join(\", \")\n\techo \"lcs({lst}) = \\\"{lcs(list)}\\\"\"\n\n\ntest(\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\ntest(\"throne\", \"throne\")\ntest(\"throne\", \"dungeon\")\ntest(\"cheese\")\ntest(\"\")\ntest()\ntest(\"prefix\", \"suffix\")\ntest(\"send\", \"lend\")\n" + }, + { + "id": 1300, + "length": 852, + "source": "Rosetta Code", + "text": "import math, strformat, strutils\n\nconst N = 1_000_000_000\n\nproc sieve(n: Positive): seq[bool] =\n\t## Build and fill a sieve of Erathosthenes.\n\tresult.setLen(n + 1) # Default to false which means prime.\n\tresult[0] = true\n\tresult[1] = true\n\tfor n in countup(3, sqrt(N.toFloat).int, 2):\n\t\tif not result[n]:\n\t\t\tfor k in countup(n * n, N, 2 * n):\n\t\t\t\tresult[k] = true\n\nlet composite = sieve(N)\n\nproc findTwins(composite: openArray[bool]) =\n\tvar\n\t\tlim = 10\n\t\tcount = 1 # Start with 3, 5 which is a special case.\n\t\tn = 7 # First prime congruent to 1 modulo 3.\n\twhile true:\n\t\tif not composite[n] and not composite[n - 2]: inc count\n\t\tinc n, 6 # Next odd number congruent to 1 modulo 3.\n\t\tif n > lim:\n\t\t\techo \"There are {insertSep($count)} pairs of twin primes under {insertSep($lim)}.\"\n\t\t\tlim *= 10\n\t\t\tif lim > N: break\n\ncomposite.findTwins()\n" + }, + { + "id": 1301, + "length": 1795, + "source": "Rosetta Code", + "text": "import lenientops\n\nfunc jaroSim(s1, s2: string): float =\n\n\tif s1.len == 0 and s2.len == 0: return 1\n\tif s1.len == 0 or s2.len == 0: return 0\n\n\tlet matchDistance = max(s1.len, s2.len) div 2 - 1\n\tvar s1Matches = newSeq[bool](s1.len)\n\tvar s2Matches = newSeq[bool](s2.len)\n\tvar matches = 0\n\tfor i in 0..s1.high:\n\t\tfor j in max(0, i - matchDistance)..min(i + matchDistance, s2.high):\n\t\t\tif not s2Matches[j] and s1[i] == s2[j]:\n\t\t\t\ts1Matches[i] = true\n\t\t\t\ts2Matches[j] = true\n\t\t\t\tinc matches\n\t\t\t\tbreak\n\tif matches == 0: return 0\n\n\tvar transpositions = 0.0\n\tvar k = 0\n\tfor i in ..s1.high:\n\t\tif not s1Matches[i]: continue\n\t\twhile not s2Matches[k]: inc k\n\t\tif s1[i] != s2[k]: transpositions += 0.5\n\t\tinc k\n\n\tresult = (matches / s1.len + matches / s2.len + (matches - transpositions) / matches) / 3\n\n\nfunc jaroWinklerDist(s, t: string): float =\n\tlet ls = s.len\n\tlet lt = t.len\n\tvar lmax = if ls < lt: ls else: lt\n\tif lmax > 4: lmax = 4\n\tvar l = 0\n\tfor i in 0.. 95:\n\t\t\tdescription = \"peak\"\n\t\telif percentage < -95:\n\t\t\tdescription = \"valley\"\n\t\telif abs(percentage) < 5:\n\t\t\tdescription = \"critical transition\"\n\t\telse:\n\t\t\tlet (trend, next) = Quadrants[quadrant]\n\t\t\tlet transition = targetDate + initDuration(days = (quadrant + 1) * length div 4 - position)\n\t\t\tdescription = fmt\"{percentage}% ({trend}, next {next} {transition.format(DateFormat)})\"\n\n\t\techo fmt\"{cycle} day {position}: {description}\"\n\n\techo \"\"\n\n\nproc biorythms(birthDate, targetDate = \"\") =\n\t## Display biorythms data. Arguments are strings in ISO format year-month-day.\n\tlet date = if targetDate.len == 0: now() else: targetDate.parse(DateFormat)\n\tbiorythms(birthDate.parse(DateFormat), date)\n\n\nwhen isMainModule:\n\n\tbiorythms(\"1943-03-09\", \"1972-07-11\")\n\tbiorythms(\"1809-01-12\", \"1863-11-19\")\n\tbiorythms(\"1809-02-12\", \"1863-11-19\")\n" + }, + { + "id": 1307, + "length": 3515, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, sets, strformat\nimport itertools\n\ntype Die = object\n\tname: string\n\tfaces: seq[int]\n\n\n# Die functions.\n\n\nfunc `$`(die: Die): string =\n\t## Return the string representation of a Die.\n\t\"({die.name}: {($die.faces)[1..^1]})\"\n\n\nfunc cmp(die1, die2: Die): int =\n\t## Compare two die returning 1, -1 or 0 for operators >, < ==.\n\tvar tot: array[3, int]\n\tfor d in product(die1.faces, die2.faces):\n\t\tinc tot[1 + ord(d[1] < d[0]) - ord(d[0] < d[1])]\n\tresult = ord(tot[0] < tot[2]) - ord(tot[2] < tot[0])\n\n\nfunc verboseCmp(die1, die2: Die): string =\n\t## Compare tow die returning a string.\n\tvar win1, win2 = 0\n\tfor (d1, d2) in product(die1.faces, die2.faces):\n\t\tinc win1, ord(d1 > d2)\n\t\tinc win2, ord(d2 > d1)\n\tresult = if win1 > win2: \"{die1.name} > {die2.name}\"\n\t\t\t\t\t elif win1 < win2: \"{die1.name} < {die2.name}\"\n\t\t\t\t\t else: \"{die1.name} = {die2.name}\"\n\n\nfunc `>`(die1, die2: Die): bool = cmp(die1, die2) > 0\nfunc `<=`(die1, die2: Die): bool = cmp(die1, die2) <= 0\n\n\n# Added a permutation iterator as that of \"itertools\" doesn't allow to specify the length.\n\n\niterator permutations[T](values: openArray[T]; r: int): seq[T] {.closure} =\n\t## Yield permutations of length \"r\" with elements taken from \"values\".\n\tlet n = values.len\n\tif r > n: return\n\tvar indices = toSeq(0.. dice[^1]\n\n\nfunc findNonTrans(allDice: openArray[Die]; n = 3): seq[seq[Die]] =\n\t## Return the list of non-transitive dice.\n\tfor perm in permutations(allDice, n):\n\t\tif perm.isNontrans:\n\t\t\tresult.add perm\n\n\nproc possibleDice(sides, maxval: Positive): seq[Die] =\n\t## Return the list of possible dice with given number of sides and maximum value.\n\n\techo \"All possible 1..{maxval} {sides}-sided dice.\"\n\tvar dice: seq[Die]\n\tvar n = 1\n\tfor faces in product(toSeq(1..maxval), repeat = sides):\n\t\tdice.add Die(name: \"D{n}\", faces: faces)\n\t\tinc n\n\techo \" Created {dice.len} dice.\"\n\techo \" Remove duplicate with same bag of numbers on different faces.\"\n\tvar found: HashSet[seq[int]]\n\tfor d in dice:\n\t\tlet count = sorted(d.faces)\n\t\tif count notin found:\n\t\t\tfound.incl count\n\t\t\tresult.add d\n\techo \" Return {result.len} filtered dice.\"\n\n\nfunc verboseDiceCmp(dice: openArray[Die]): string =\n\t## Return the verbose comparison of dice.\n\tfor i in 1..dice.high:\n\t\tresult.add verboseCmp(dice[i-1], dice[i]) & \", \"\n\tresult.add verboseCmp(dice[0], dice[^1])\n\n\n\nwhen isMainModule:\n\n\tlet dice = possibleDice(sides = 4, maxval = 4)\n\tfor n in [3, 4]:\n\t\tlet nonTrans = dice.findNonTrans(n)\n\t\techo \"\\n Non-transitive length-{n} combinations found: {nonTrans.len}.\"\n\t\tfor list in nonTrans:\n\t\t\techo \"\"\n\t\t\tfor i, die in list:\n\t\t\t\techo \" \", if i == 0: '[' else: ' ', die, if i == list.high: \"]\" else: \",\"\n\t\tif nonTrans.len != 0:\n\t\t\techo \"\\n More verbose comparison of last non-transitive result:\"\n\t\t\techo \" \", verboseDiceCmp(nonTrans[^1])\n\t\techo \"\\n ====\"\n" + }, + { + "id": 1308, + "length": 3782, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\ntype Matrix = seq[seq[float]]\n\ntemplate rows(m: Matrix): Positive = m.len\ntemplate cols(m: Matrix): Positive = m[0].len\n\n\nfunc `+`(m1, m2: Matrix): Matrix =\n\tdoAssert m1.rows == m2.rows and m1.cols == m2.cols, \"Matrices must have the same dimensions.\"\n\tresult = newSeqWith(m1.rows, newSeq[float](m1.cols))\n\tfor i in 0.. 0: result.add(\" -> \")\n\t\tresult.add $node.data\n\t\tnode = node.next\n\nvar l = initDoublyLinkedList[int]()\nlet a = newNode(12)\nlet b = newNode(13)\nlet c = newNode(14)\nlet d = newNode(15)\nl.append a\nl.append b\nl.append c\nl.append d\necho l\nl.remove b\necho l\nl.remove a\necho l\nl.remove d\necho l\nl.remove c\necho l\n" + }, + { + "id": 1310, + "length": 758, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\ntype Digit = 0..9\n\nproc toInt(s: seq[Digit]): int =\n\t## Convert a sequence of digits to an integer.\n\tfor n in s:\n\t\tresult = 10 * result + n\n\nconst PrimeDigits = @[Digit 2, 3, 5, 7]\n\nvar list = PrimeDigits.mapIt(@[it]) # List of sequences of digits.\nvar result: seq[int]\nwhile list.len != 0:\n\tvar nextList: seq[seq[Digit]] # List with one more digit.\n\tfor digitSeq in list:\n\t\tlet currSum = sum(digitSeq)\n\t\tfor n in PrimeDigits:\n\t\t\tlet newSum = currSum + n\n\t\t\tlet newDigitSeq = digitSeq & n\n\t\t\tif newSum < 13: nextList.add newDigitSeq\n\t\t\telif newSum == 13: result.add newDigitSeq.toInt\n\t\t\telse: break\n\tlist = move(nextList)\n\nfor i, n in result:\n\tstdout.write ($n).align(6), if (i + 1) mod 9 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1311, + "length": 2021, + "source": "Rosetta Code", + "text": "import bitops, strutils, std/monotimes, times\n\nconst MaxCount = 2 * 1_000_000_000 + 9 * 9\n\n# Bit string used to represent an array of booleans.\ntype BitString = object\n\tlen: Natural # length in bits.\n\tvalues: seq[byte] # Sequence containing the bits.\n\n\nproc newBitString(n: Natural): BitString =\n\t## Return a new bit string of length \"n\" bits.\n\tresult.len = n\n\tresult.values.setLen((n + 7) shr 3)\n\n\ntemplate checkIndex(i, length: Natural) {.used.} =\n\t## Check if index \"i\" is less than the array length.\n\tif i >= length:\n\t\traise newException(IndexDefect, \"index $1 not in 0 .. $2\".format(i, length))\n\n\nproc `[]`(bs: BitString; i: Natural): bool =\n\t## Return the value of bit at index \"i\" as a boolean.\n\twhen compileOption(\"boundchecks\"):\n\t\tcheckIndex(i, bs.len)\n\tresult = bs.values[i shr 3].testbit(i and 0x07)\n\n\nproc `[]=`(bs: var BitString; i: Natural; value: bool) =\n\t## Set the bit at index \"i\" to the given value.\n\twhen compileOption(\"boundchecks\"):\n\t\tcheckIndex(i, bs.len)\n\tif value: bs.values[i shr 3].setBit(i and 0x07)\n\telse: bs.values[i shr 3].clearBit(i and 0x07)\n\n\nproc fill(sieve: var BitString) =\n\t## Fill a sieve.\n\tvar n = 0\n\tfor a in 0..1:\n\t\tfor b in 0..9:\n\t\t\tfor c in 0..9:\n\t\t\t\tfor d in 0..9:\n\t\t\t\t\tfor e in 0..9:\n\t\t\t\t\t\tfor f in 0..9:\n\t\t\t\t\t\t\tfor g in 0..9:\n\t\t\t\t\t\t\t\tfor h in 0..9:\n\t\t\t\t\t\t\t\t\tfor i in 0..9:\n\t\t\t\t\t\t\t\t\t\tfor j in 0..9:\n\t\t\t\t\t\t\t\t\t\t\tsieve[a + b + c + d + e + f + g + h + i + j + n] = true\n\t\t\t\t\t\t\t\t\t\t\tinc n\n\n\nlet t0 = getMonoTime()\n\nvar sieve = newBitString(MaxCount + 1)\nsieve.fill()\necho \"Sieve time: \", getMonoTime() - t0\n\n# Find first 50.\necho \"\\nFirst 50 self numbers:\"\nvar count = 0\nvar line = \"\"\nfor n in 0..MaxCount:\n\tif not sieve[n]:\n\t\tinc count\n\t\tline.addSep(\" \")\n\t\tline.add $n\n\t\tif count == 50: break\necho line\n\n# Find 1st, 10th, 100th, ..., 100_000_000th.\necho \"\\n Rank Value\"\nvar limit = 1\ncount = 0\nfor n in 0..MaxCount:\n\tif not sieve[n]: inc count\n\tif count == limit:\n\t\techo ($count).align(10), ($n).align(12)\n\t\tlimit *= 10\necho \"Total time: \", getMonoTime() - t0\n" + }, + { + "id": 1312, + "length": 2166, + "source": "Rosetta Code", + "text": "import bitops, strutils, std/monotimes, times\n\nconst MaxCount = 103 * 10_000 * 10_000 + 11 * 9 + 1\n\n# Bit string used to represent an array of booleans.\ntype BitString = object\n\tlen: Natural\n\tvalues: seq[byte]\n\n\nproc newBitString(n: Natural): BitString =\n\t## Return a new bit string of length \"n\" bits.\n\tresult.len = n\n\tresult.values.setLen((n + 7) shr 3)\n\n\ntemplate checkIndex(i, length: Natural) {.used.} =\n\t## Check if index \"i\" is less than the array length.\n\tif i >= length:\n\t\traise newException(IndexDefect, \"index $1 not in 0 .. $2\".format(i, length))\n\n\nproc `[]`(bs: BitString; i: Natural): bool =\n\t## Return the value of bit at index \"i\" as a boolean.\n\twhen compileOption(\"boundchecks\"):\n\t\tcheckIndex(i, bs.len)\n\tresult = bs.values[i shr 3].testbit(i and 0x07)\n\n\nproc `[]=`(bs: var BitString; i: Natural; value: bool) =\n\t## Set the bit at index \"i\" to the given value.\n\twhen compileOption(\"boundchecks\"):\n\t\tcheckIndex(i, bs.len)\n\tif value: bs.values[i shr 3].setBit(i and 0x07)\n\telse: bs.values[i shr 3].clearBit(i and 0x07)\n\n\nproc initDigitSum9999(): array[10000, byte] {.compileTime.} =\n\t## Return the array of the digit sums for numbers 0 to 9999.\n\tvar i = 0\n\tfor a in 0..9:\n\t\tfor b in 0..9:\n\t\t\tfor c in 0..9:\n\t\t\t\tfor d in 0..9:\n\t\t\t\t\tresult[i] = byte(a + b + c + d)\n\t\t\t\t\tinc i\n\nconst DigitSum9999 = initDigitSum9999()\n\n\nproc fill(sieve: var BitString) =\n\t## Fill a sieve.\n\tvar n = 0\n\tfor a in 0..102:\n\t\tfor b in 0..9999:\n\t\t\tvar s = DigitSum9999[a].int + DigitSum9999[b].int + n\n\t\t\tfor c in 0..9999:\n\t\t\t\tsieve[DigitSum9999[c].int + s] = true\n\t\t\t\tinc s\n\t\t\tinc n, 10_000\n\n\nlet t0 = getMonoTime()\n\nvar sieve = newBitString(MaxCount + 1)\nsieve.fill()\necho \"Sieve time: \", getMonoTime() - t0\n\n# Find first 50.\necho \"\\nFirst 50 self numbers:\"\nvar count = 0\nvar line = \"\"\nfor n in 0..MaxCount:\n\tif not sieve[n]:\n\t\tinc count\n\t\tline.addSep(\" \")\n\t\tline.add $n\n\t\tif count == 50: break\necho line\n\n# Find 1st, 10th, 100th, ..., 1_000_000_000th.\necho \"\\n Rank Value\"\nvar limit = 1\ncount = 0\nfor n in 0..MaxCount:\n\tif not sieve[n]: inc count\n\tif count == limit:\n\t\techo ($count).align(10), ($n).align(12)\n\t\tlimit *= 10\necho \"Total time: \", getMonoTime() - t0\n" + }, + { + "id": 1313, + "length": 741, + "source": "Rosetta Code", + "text": "import strutils\n\nfunc insequence(n: Positive): bool =\n\t## Return true if \"n\" is in the sequence.\n\tif n < 10: return true\n\tvar diff = 0\n\tvar prev = n mod 10\n\tvar n = n div 10\n\twhile n != 0:\n\t\tlet digit = n mod 10\n\t\tif digit < prev: inc diff\n\t\telif digit > prev: dec diff\n\t\tprev = digit\n\t\tn = n div 10\n\tresult = diff == 0\n\niterator a297712(): (int, int) =\n\t## Yield the positions and the numbers of the sequence.\n\tvar n = 1\n\tvar pos = 0\n\twhile true:\n\t\tif n.insequence:\n\t\t\tinc pos\n\t\t\tyield (pos, n)\n\t\tinc n\n\necho \"First 200 numbers in the sequence:\"\nfor (pos, n) in a297712():\n\tif pos <= 200:\n\t\tstdout.write ($n).align(3), if pos mod 20 == 0: '\\n' else: ' '\n\telif pos == 10_000_000:\n\t\techo \"\\nTen millionth number in the sequence: \", n\n\t\tbreak\n" + }, + { + "id": 1314, + "length": 858, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport decimal\n\nproc fact(n: int): DecimalType =\n\tresult = newDecimal(1)\n\tif n < 2: return\n\tfor i in 2..n:\n\t\tresult *= i\n\nproc almkvistGiullera(n: int): DecimalType =\n\t## Return the integer portion of the nth term of Almkvist-Giullera sequence.\n\tlet t1 = fact(6 * n) * 32\n\tlet t2 = 532 * n * n + 126 * n + 9\n\tlet t3 = fact(n) ^ 6 * 3\n\tresult = t1 * t2 / t3\n\nlet One = newDecimal(1)\n\nsetPrec(78)\necho \"N Integer portion\"\necho repeat('-', 47)\nfor n in 0..9:\n\techo \"{n} {almkvistGiullera(n):>44}\"\necho()\n\necho \"Pi to 70 decimal places:\"\nvar\n\tsum = newDecimal(0)\n\tprev = newDecimal(0)\n\tprec = One.scaleb(newDecimal(-70))\n\tn = 0\nwhile true:\n\tsum += almkvistGiullera(n) / One.scaleb(newDecimal(6 * n + 3))\n\tif abs(sum - prev) < prec: break\n\tprev = sum.clone\n\tinc n\nlet pi = 1 / sqrt(sum)\necho ($pi)[0..71]\n" + }, + { + "id": 1315, + "length": 3473, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strscans, strutils\n\ntype\n\tRange = tuple[low, high: int]\n\tRanges = seq[Range]\n\n\nfunc `$`(ranges: Ranges): string =\n\t## Return the string representation of a list of ranges.\n\tresult.add '\"'\n\tfor r in ranges:\n\t\tresult.addSep(\",\", 1)\n\t\tresult.add \"$1-$2\".format(r.low, r.high)\n\tresult.add '\"'\n\n\nproc initRanges(ranges: varargs[Range]): seq[Range] =\n\t## Create a list of ranges with the given (potentially empty) ranges.\n\tstdout.write \"Start with \"\n\tvar ranges = ranges.filterIt(it.low <= it.high)\n\tif ranges.len <= 1:\n\t\techo ranges\n\t\treturn ranges\n\tranges.sort()\n\tresult = @[ranges[0]]\n\tfor newRange in ranges[1..^1]:\n\t\tif newRange.low <= result[^1].high:\n\t\t\t# Intersection is not empty.\n\t\t\tif newRange.high > result[^1].low: result[^1].high = newRange.high\n\t\telse:\n\t\t\t# New range.\n\t\t\tresult.add newRange\n\techo result\n\n\nproc initRanges(rangeString: string): seq[Range] =\n\t## Create a list fo ranges from a string representation.\n\tif rangeString.len == 0: return\n\tvar ranges: seq[Range]\n\tfor field in rangeString.split(','):\n\t\tvar r: Range\n\t\tif field.scanf(\"$i-$i$.\", r.low, r.high):\n\t\t\tranges.add r\n\t\telse:\n\t\t\traise newException(ValueError, \"Wrong range specification: \" & field)\n\tresult = initRanges(ranges)\n\n\nfunc contains(r: Range; val: int): bool =\n\t## Return true if a range contains a value.\n\t## Used by \"in\" operator.\n\tval >= r.low and val <= r.high\n\n\nproc add(ranges: var Ranges; val: int) =\n\t## Add a value to a list of ranges.\n\tstdout.write \"add \", ($val).alignLeft(2), \" -> \"\n\tif ranges.len == 0:\n\t\tranges.add (val, val)\n\t\techo ranges\n\t\treturn\n\t# Search the range immediately following the value.\n\tvar idx = -1\n\tfor i, r in ranges:\n\t\tif val in r:\n\t\t\t# Already in a range: no changes.\n\t\t\techo ranges\n\t\t\treturn\n\t\tif val < r.low:\n\t\t\tidx = i\n\t\t\tbreak\n\tif idx < 0:\n\t\t# Not found, so to add at the end.\n\t\tif ranges[^1].high == val - 1: ranges[^1].high = val # Extend last range.\n\t\telse: ranges.add (val, val) # Add a range.\n\telif ranges[idx].low == val + 1:\n\t\t# Just before a range.\n\t\tranges[idx].low = val\n\t\tif idx > 0:\n\t\t\tif ranges[idx-1].high >= val - 1:\n\t\t\t\t# Merge two ranges.\n\t\t\t\tranges[idx].low = ranges[idx-1].low\n\t\t\t\tranges.delete(idx - 1)\n\telif idx > 0:\n\t\t# Between two ranges.\n\t\tif ranges[idx-1].high == val - 1: ranges[idx-1].high = val # Extend previous range.\n\t\telse: ranges.insert((val, val), idx) # Insert a range.\n\telse:\n\t\t# At the beginning.\n\t\tranges.insert((val, val), 0)\n\techo ranges\n\n\nproc remove(ranges: var Ranges; val: int) =\n\t## remove a value from a list of ranges.\n\tstdout.write \"remove \", ($val).alignLeft(2), \" -> \"\n\t# Search the range containing the value.\n\tvar idx = - 1\n\tfor i, r in ranges:\n\t\tif val in r:\n\t\t\tidx = i\n\t\t\tbreak\n\t\tif val < r.low: break\n\tif idx < 0:\n\t\t# Not found.\n\t\techo ranges\n\t\treturn\n\tlet r = ranges[idx]\n\tif r.low == val:\n\t\tif r.high == val:\n\t\t\t# Delete the range.\n\t\t\tranges.delete(idx)\n\t\telse:\n\t\t\t# Update the low value.\n\t\t\tranges[idx].low = val + 1\n\telif r.high == val:\n\t\t# Update the high value.\n\t\tranges[idx].high = val - 1\n\telse:\n\t\t# Split the range.\n\t\tranges.insert(r, idx + 1)\n\t\tranges[idx].high = val - 1\n\t\tranges[idx+1].low = val + 1\n\techo ranges\n\n\nvar r = initRanges(\"\")\nr.add 77\nr.add 79\nr.add 78\nr.remove 77\nr.remove 78\nr.remove 79\necho()\n\nr = initRanges(\"1-3,5-5\")\nr.add 1\nr.remove 4\nr.add 7\nr.add 8\nr.add 6\nr.remove 7\necho()\n\nr = initRanges(\"1-5,10-25,27-30\")\nr.add 26\nr.add 9\nr.add 7\nr.remove 26\nr.remove 9\nr.remove 7\n" + }, + { + "id": 1316, + "length": 551, + "source": "Rosetta Code", + "text": "import sequtils, strformat, times\nimport bignum\n\nfunc partitions(n: int): Int =\n\tvar p = newSeqWith(n + 1, newInt())\n\tp[0] = newInt(1)\n\tfor i in 1..n:\n\t\tvar k = 1\n\t\twhile true:\n\t\t\tvar j = k * (3 * k - 1) div 2\n\t\t\tif j > i: break\n\t\t\tif (k and 1) != 0:\n\t\t\t\tinc p[i], p[i - j]\n\t\t\telse:\n\t\t\t\tdec p[i], p[i - j]\n\t\t\tj = k * (3 * k + 1) div 2\n\t\t\tif j > i: break\n\t\t\tif (k and 1) != 0:\n\t\t\t\tinc p[i], p[i - j]\n\t\t\telse:\n\t\t\t\tdec p[i], p[i - j]\n\t\t\tinc k\n\tresult = p[n]\n\nlet t0 = cpuTime()\necho partitions(6666)\necho \"Elapsed time: {(cpuTime() - t0) * 1000:.2f} ms\"\n" + }, + { + "id": 1317, + "length": 1113, + "source": "Rosetta Code", + "text": "import sequtils, strformat, strutils, tables\n\ntype\n\tStepTable = TableRef[seq[int], int]\n\tResult = tuple[steps: int; example: seq[int]]\n\nfunc findMax(t: StepTable): Result =\n\tresult.steps = -1\n\tfor example, steps in t.pairs:\n\t\tif steps > result.steps:\n\t\t\tresult = (steps, example)\n\nfunc partialReversed(arr: openArray[int]; pos: int): seq[int] =\n\tresult.setlen(arr.len)\n\tfor i in 0..2}) = {steps:>2} example: \", example.join(\", \")\n" + }, + { + "id": 1318, + "length": 2592, + "source": "Rosetta Code", + "text": "import math, random, strutils\n\ntype\n\tPoint = tuple[x, y: float]\n\tCircle = tuple[c: Point; r: float]\n\n\nfunc `$`(p: Point): string =\n\t## Return the string representation of a point.\n\t\"($1, $2)\".format(p.x, p.y)\n\n\nfunc dist(a, b: Point): float =\n\t## Return the distance between two points.\n\thypot(a.x - b.x, a.y - b.y)\n\n\nfunc getCircleCenter(bx, by, cx, cy: float): Point =\n\t## Return the center of a circle defined by three points.\n\tlet\n\t\tb = bx * bx + by * by\n\t\tc = cx * cx + cy * cy\n\t\td = bx * cy - by * cx\n\tresult = ((cy * b - by * c) / (2 * d), (bx * c - cx * b) / (2 * d))\n\nfunc contains(ci: Circle; p: Point): bool =\n\t## Return whether a circle contains the point 'p'.\n\t## Used by 'in' and 'notin'.\n\tdist(ci.c, p) <= ci.r\n\n\nfunc contains(ci: Circle; ps: seq[Point]): bool =\n\t## Return whether a circle contains a slice of points.\n\t## Used by 'in'.\n\tfor p in ps:\n\t\tif p notin ci: return false\n\tresult = true\n\n\nfunc `$`(ci: Circle): string =\n\t## Return the string representation of a circle.\n\t\"Center $1, Radius $2\".format(ci.c, ci.r)\n\n\nfunc circleFrom3(a, b, c: Point): Circle =\n\t## Return the smallest circle that intersects three points.\n\tvar i = getCircleCenter(b.x - a.x, b.y - a.y, c.x - a.x, c.y - a.y)\n\ti.x += a.x\n\ti.y += a.y\n\tresult = (c: i, r: dist(i, a))\n\n\nfunc circleFrom2(a, b: Point): Circle =\n\t## Return the smallest circle that intersects two points.\n\tlet c = ((a.x + b.x) * 0.5, (a.y + b.y) * 0.5)\n\tresult = (c: c, r: dist(a, b) * 0.5)\n\n\nfunc secTrivial(rs: seq[Point]): Circle =\n\t## Return the smallest enclosing circle for n <= 3.\n\tcase rs.len\n\tof 0: return ((0.0, 0.0), 0.0)\n\tof 1: return (rs[0], 0.0)\n\tof 2: return circleFrom2(rs[0], rs[1])\n\tof 3: discard\n\telse: raise newException(ValueError, \"There shouldn't be more than three points.\")\n\n\t# Three points.\n\tfor i in 0..1:\n\t\tfor j in (i + 1)..2:\n\t\t\tlet c = circleFrom2(rs[i], rs[j])\n\t\t\tif rs in c: return c\n\tresult = circleFrom3(rs[0], rs[1], rs[2])\n\n\nproc welzl(ps: var seq[Point]; rs: seq[Point]; n: int): Circle =\n\t## Helper function for Welzl method.\n\tvar rc = rs\n\tif n == 0 or rc.len == 3: return secTrivial(rc)\n\tlet idx = rand(n-1)\n\tlet p = ps[idx]\n\tswap ps[idx], ps[n-1]\n\tlet d = welzl(ps, rc, n-1)\n\tif p in d: return d\n\trc.add p\n\tresult = welzl(ps, rc, n-1)\n\n\nproc welzl(ps: seq[Point]): Circle =\n\t# Applies the Welzl algorithm to find the SEC.\n\tvar pc = ps\n\tpc.shuffle()\n\tresult = welzl(pc, @[], pc.len)\n\n\nwhen isMainModule:\n\trandomize()\n\tconst Tests = [@[(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)],\n\t\t\t\t\t\t\t\t @[(5.0, -2.0), (-3.0, -2.0), (-2.0, 5.0), (1.0, 6.0), (0.0, 2.0)]]\n\n\tfor test in Tests:\n\t\techo welzl(test)\n" + }, + { + "id": 1319, + "length": 594, + "source": "Rosetta Code", + "text": "import nimcrypto\n\nconst BlockSize = 1024\n\nvar hashes: seq[MDigest[256]]\n\nlet f = open(\"title.png\")\nvar buffer: array[BlockSize, byte]\nwhile true:\n\tlet n = f.readBytes(buffer, 0, BlockSize)\n\tif n == 0: break\n\thashes.add sha256.digest(buffer[0].addr, n.uint)\nf.close()\n\nvar ctx: sha256\nwhile hashes.len != 1:\n\tvar newHashes: seq[MDigest[256]]\n\tfor i in countup(0, hashes.high, 2):\n\t\tif i < hashes.high:\n\t\t\tctx.init()\n\t\t\tctx.update(hashes[i].data)\n\t\t\tctx.update(hashes[i + 1].data)\n\t\t\tnewHashes.add ctx.finish()\n\t\t\tctx.clear()\n\t\telse:\n\t\t\tnewHashes.add hashes[i]\n\thashes= newHashes\n\necho hashes[0]\n" + }, + { + "id": 1320, + "length": 3028, + "source": "Rosetta Code", + "text": "const Size = 15\n\ntype Canvas = array[Size, array[Size, char]]\n\n\nfunc horizontal(canvas: var Canvas; col1, col2, row: Natural) =\n\tfor col in col1..col2:\n\t\tcanvas[row][col] = 'x'\n\n\nfunc vertical(canvas: var Canvas; row1, row2, col: Natural) =\n\tfor row in row1..row2:\n\t\tcanvas[row][col] = 'x'\n\n\nfunc diagd(canvas: var Canvas; col1, col2, row: Natural) =\n\tfor col in col1..col2:\n\t\tcanvas[row + col - col1][col] = 'x'\n\n\nfunc diagu(canvas: var Canvas; col1, col2, row: Natural) =\n\tfor col in col1..col2:\n\t\tcanvas[row - col + col1][col] = 'x'\n\n\nfunc drawPart(canvas: var Canvas; value: Natural) =\n\n\tcase value\n\tof 1:\n\t\tcanvas.horizontal(6, 10, 0)\n\tof 2:\n\t\tcanvas.horizontal(6, 10, 4)\n\tof 3:\n\t\tcanvas.diagd(6, 10, 0)\n\tof 4:\n\t\tcanvas.diagu(6, 10, 4)\n\tof 5:\n\t\tcanvas.drawPart(1)\n\t\tcanvas.drawPart(4)\n\tof 6:\n\t\tcanvas.vertical(0, 4, 10)\n\tof 7:\n\t\tcanvas.drawPart(1)\n\t\tcanvas.drawPart(6)\n\tof 8:\n\t\tcanvas.drawPart(2)\n\t\tcanvas.drawPart(6)\n\tof 9:\n\t\tcanvas.drawPart(1)\n\t\tcanvas.drawPart(8)\n\tof 10:\n\t\tcanvas.horizontal(0, 4, 0)\n\tof 20:\n\t\tcanvas.horizontal(0, 4, 4)\n\tof 30:\n\t\tcanvas.diagu(0, 4, 4)\n\tof 40:\n\t\tcanvas.diagd(0, 4, 0)\n\tof 50:\n\t\tcanvas.drawPart(10)\n\t\tcanvas.drawPart(40)\n\tof 60:\n\t\tcanvas.vertical(0, 4, 0)\n\tof 70:\n\t\tcanvas.drawPart(10)\n\t\tcanvas.drawPart(60)\n\tof 80:\n\t\tcanvas.drawPart(20)\n\t\tcanvas.drawPart(60)\n\tof 90:\n\t\tcanvas.drawPart(10)\n\t\tcanvas.drawPart(80)\n\tof 100:\n\t\tcanvas.horizontal(6, 10, 14)\n\tof 200:\n\t\tcanvas.horizontal(6, 10, 10)\n\tof 300:\n\t\tcanvas.diagu(6, 10, 14)\n\tof 400:\n\t\tcanvas.diagd(6, 10, 10)\n\tof 500:\n\t\tcanvas.drawPart(100)\n\t\tcanvas.drawPart(400)\n\tof 600:\n\t\tcanvas.vertical(10, 14, 10)\n\tof 700:\n\t\tcanvas.drawPart(100)\n\t\tcanvas.drawPart(600)\n\tof 800:\n\t\tcanvas.drawPart(200)\n\t\tcanvas.drawPart(600)\n\tof 900:\n\t\tcanvas.drawPart(100)\n\t\tcanvas.drawPart(800)\n\tof 1000:\n\t\tcanvas.horizontal(0, 4, 14)\n\tof 2000:\n\t\tcanvas.horizontal(0, 4, 10)\n\tof 3000:\n\t\tcanvas.diagd(0, 4, 10)\n\tof 4000:\n\t\tcanvas.diagu(0, 4, 14)\n\tof 5000:\n\t\tcanvas.drawPart(1000)\n\t\tcanvas.drawPart(4000)\n\tof 6000:\n\t\tcanvas.vertical(10, 14, 0)\n\tof 7000:\n\t\tcanvas.drawPart(1000)\n\t\tcanvas.drawPart(6000)\n\tof 8000:\n\t\tcanvas.drawPart(2000)\n\t\tcanvas.drawPart(6000)\n\tof 9000:\n\t\tcanvas.drawPart(1000)\n\t\tcanvas.drawPart(8000)\n\telse:\n\t\traise newException(ValueError, \"wrong value for 'drawPart'\")\n\n\nfunc draw(canvas: var Canvas; value: Natural) =\n\n\tvar val = value\n\tlet thousands = val div 1000\n\tval = val mod 1000\n\tlet hundreds = val div 100\n\tval = val mod 100\n\tlet tens = val div 10\n\tlet ones = val mod 10\n\n\tif thousands != 0:\n\t\tcanvas.drawPart(1000 * thousands)\n\tif hundreds != 0:\n\t\tcanvas.drawPart(100 * hundreds)\n\tif tens != 0:\n\t\tcanvas.drawPart(10 * tens)\n\tif ones != 0:\n\t\tcanvas.drawPart(ones)\n\n\nfunc cistercian(n: Natural): Canvas =\n\tfor row in result.mitems:\n\t\tfor cell in row.mitems: cell = ' '\n\t\trow[5] = 'x'\n\tresult.draw(n)\n\n\nproc `$`(canvas: Canvas): string =\n\tfor row in canvas:\n\t\tfor cell in row:\n\t\t\tresult.add cell\n\t\tresult.add '\\n'\n\n\nwhen isMainModule:\n\n\tfor number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]:\n\t\techo number, ':'\n\t\techo cistercian(number)\n" + }, + { + "id": 1321, + "length": 2523, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\tEps = 0.001\n\tEps2 = Eps * Eps\n\ntype\n\tPoint = tuple[x, y: float]\n\tTriangle = object\n\t\tp1, p2, p3: Point\n\n\nfunc initTriangle(p1, p2, p3: Point): Triangle =\n\tTriangle(p1: p1, p2: p2, p3: p3)\n\nfunc side(p1, p2, p: Point): float =\n\t(p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y)\n\n\nfunc distanceSquarePointToSegment(p1, p2, p: Point): float =\n\tlet p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)\n\tlet dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength\n\tif dotProduct < 0:\n\t\treturn (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y)\n\tif dotProduct <= 1:\n\t\tlet pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y)\n\t\treturn pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength\n\tresult = (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y)\n\n\nfunc pointInTriangleBoundingBox(t: Triangle; p: Point): bool =\n\tlet xMin = min(t.p1.x, min(t.p2.x, t.p3.x)) - EPS\n\tlet xMax = max(t.p1.x, max(t.p2.x, t.p3.x)) + EPS\n\tlet yMin = min(t.p1.y, min(t.p2.y, t.p3.y)) - EPS\n\tlet yMax = max(t.p1.y, max(t.p2.y, t.p3.y)) + EPS\n\tresult = p.x in xMin..xMax and p.y in yMin..yMax\n\n\nfunc nativePointInTriangle(t: Triangle; p: Point): bool =\n\tlet checkSide1 = side(t.p1, t.p2, p) >= 0\n\tlet checkSide2 = side(t.p2, t.p3, p) >= 0\n\tlet checkSide3 = side(t.p3, t.p1, p) >= 0\n\tresult = checkSide1 and checkSide2 and checkSide3\n\n\nfunc accuratePointInTriangle(t: Triangle; p: Point): bool =\n\tif not t.pointInTriangleBoundingBox(p):\n\t\treturn false\n\tif t.nativePointInTriangle(p):\n\t\treturn true\n\tif distanceSquarePointToSegment(t.p1, t.p2, p) <= Eps2 or\n\t\t distanceSquarePointToSegment(t.p3, t.p1, p) <= Eps2:\n\t\treturn true\n\n\nfunc `$`(p: Point): string = \"({p.x}, {p.y})\"\n\nfunc `$`(t: Triangle): string = \"Triangle[{t.p1}, {t.p2}, {t.p3}]\"\n\nfunc contains(t: Triangle; p: Point): bool = t.accuratePointInTriangle(p)\n\n\nwhen isMainModule:\n\n\tproc test(t: Triangle; p: Point) =\n\t\techo t\n\t\techo \"Point {p} is within triangle ? {p in t}\"\n\n\tvar p1: Point = (1.5, 2.4)\n\tvar p2: Point = (5.1, -3.1)\n\tvar p3: Point = (-3.8, 1.2)\n\tvar tri = initTriangle(p1, p2, p3)\n\ttest(tri, (0.0, 0.0))\n\ttest(tri, (0.0, 1.0))\n\ttest(tri, (3.0, 1.0))\n\techo()\n\tp1 = (1 / 10, 1 / 9)\n\tp2 = (100 / 8, 100 / 3)\n\tp3 = (100 / 4, 100 / 9)\n\ttri = initTriangle(p1, p2, p3)\n\tlet pt = (p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y))\n\ttest(tri, pt)\n\techo()\n\tp3 = (-100 / 8, 100 / 6)\n\ttri = initTriangle(p1, p2, p3)\n\ttest(tri, pt)\n" + }, + { + "id": 1322, + "length": 1419, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst MaxIter = 151\n\n\nfunc minkowski(x: float): float =\n\n\tif x notin 0.0..1.0:\n\t\treturn floor(x) + minkowski(x - floor(x))\n\n\tvar\n\t\tp = x.uint64\n\t\tr = p + 1\n\t\tq, s = 1u64\n\t\td = 1.0\n\t\ty = p.float\n\n\twhile true:\n\t\td /= 2\n\t\tif y + d == y: break\n\t\tlet m = p + r\n\t\tif m < 0 or p < 0: break\n\t\tlet n = q + s\n\t\tif n < 0: break\n\t\tif x < m.float / n.float:\n\t\t\tr = m\n\t\t\ts = n\n\t\telse:\n\t\t\ty += d\n\t\t\tp = m\n\t\t\tq = n\n\n\tresult = y + d\n\n\nfunc minkowskiInv(x: float): float =\n\n\tif x notin 0.0..1.0:\n\t\treturn floor(x) + minkowskiInv(x - floor(x))\n\tif x == 1 or x == 0:\n\t\treturn x\n\n\tvar\n\t\tcontFrac: seq[uint32]\n\t\tcurr = 0u32\n\t\tcount = 1u32\n\t\ti = 0\n\t\tx = x\n\n\twhile true:\n\t\tx *= 2\n\t\tif curr == 0:\n\t\t\tif x < 1:\n\t\t\t\tinc count\n\t\t\telse:\n\t\t\t\tinc i\n\t\t\t\tcontFrac.setLen(i + 1)\n\t\t\t\tcontFrac[i - 1] = count\n\t\t\t\tcount = 1\n\t\t\t\tcurr = 1\n\t\t\t\tx -= 1\n\t\telse:\n\t\t\tif x > 1:\n\t\t\t\tinc count\n\t\t\t\tx -= 1\n\t\t\telse:\n\t\t\t\tinc i\n\t\t\t\tcontFrac.setLen(i + 1)\n\t\t\t\tcontFrac[i - 1] = count\n\t\t\t\tcount = 1\n\t\t\t\tcurr = 0\n\t\tif x == floor(x):\n\t\t\tcontFrac[i] = count\n\t\t\tbreak\n\t\tif i == MaxIter:\n\t\t\tbreak\n\n\tvar ret = 1 / contFrac[i].float\n\tfor j in countdown(i - 1, 0):\n\t\tret = contFrac[j].float + 1 / ret\n\tresult = 1 / ret\n\n\necho \"{minkowski(0.5*(1+sqrt(5.0))):19.16f}, {5/3:19.16f}\"\necho \"{minkowskiInv(-5/9):19.16f}, {(sqrt(13.0)-7)/6:19.16f}\"\necho \"{minkowski(minkowskiInv(0.718281828)):19.16f}, \" &\n\t\t \"{minkowskiInv(minkowski(0.1213141516171819)):19.16f}\"\n" + }, + { + "id": 1323, + "length": 1675, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst MinDelta = 1.0\n\ntype Result = tuple[min, max: float; count: int]\n\n\nfunc getPRangeCount(prices: seq[float]; min, max: float): int =\n\tfor price in prices:\n\t\tif price in min..max:\n\t\t\tinc result\n\n\nfunc get5000(prices: seq[float]; min, max: float; n: int): (float, int) =\n\t\tvar\n\t\t\tcount = prices.getPRangeCount(min, max)\n\t\t\tdelta = (max - min) / 2\n\t\t\tmax = max\n\t\twhile count != n and delta >= MinDelta / 2:\n\t\t\tif count > n: max -= delta\n\t\t\telse: max += delta\n\t\t\tmax = floor(max)\n\t\t\tcount = getPRangeCount(prices, min, max)\n\t\t\tdelta /= 2\n\t\tresult = (max, count)\n\n\nfunc getAll5000(prices: seq[float]; min, max: float; n: int): seq[Result] =\n\t\tvar (pmax, pcount) = prices.get5000(min, max, n)\n\t\tresult = @[(min, pmax, pcount)]\n\t\twhile pmax < max:\n\t\t\tlet pmin = pmax + 1\n\t\t\t(pmax, pcount) = prices.get5000(pmin, max, n)\n\t\t\tif pcount == 0:\n\t\t\t\traise newException(ValueError, \"Price list from {pmin} has too many with same price.\")\n\t\t\tresult.add (pmin, pmax, pcount)\n\n\nwhen isMainModule:\n\timport random, sequtils\n\trandomize()\n\n\tlet numPrices = rand(99_000..101_000)\n\tconst MaxPrice = 100_000\n\tlet prices = newSeqWith(numPrices, rand(1..MaxPrice).toFloat)\n\tlet actualMax = max(prices)\n\techo \"Using {numPrices} items with prices from 0 to {actualMax.int}:\"\n\n\tlet res = prices.getAll5000(0, actualMax, 5000)\n\techo \"Split into {res.len} bins of approx 5000 elements:\"\n\tvar total = 0\n\tfor (minf, maxf, count) in res:\n\t\tlet min = minf.toInt\n\t\tlet max = min(maxf, actualMax).toInt\n\t\tinc total, count\n\t\techo \" From {min:6} to {max:6} with {count:4} items\"\n\n\tif total != numPrices:\n\t\techo \"Something went wrong: grand total of {total} doesn't equal {numPrices}!\"\n" + }, + { + "id": 1324, + "length": 1089, + "source": "Rosetta Code", + "text": "import algorithm, random, sequtils, strformat, strutils, tables\n\ntype\n\tRevolver = array[6, bool]\n\tAction {.pure.} = enum Load, Spin, Fire, Error\n\nconst Actions = {'L': Load, 'S': Spin, 'F': Fire}.toTable\n\nfunc spin(revolver: var Revolver; count: Positive) =\n\trevolver.rotateLeft(-count)\n\nfunc load(revolver: var Revolver) =\n\twhile revolver[1]:\n\t\trevolver.spin(1)\n\trevolver[1] = true\n\trevolver.spin(1)\n\nfunc fire(revolver: var Revolver): bool =\n\tresult = revolver[0]\n\trevolver.spin(1)\n\nproc test(scenario: string) =\n\tlet actions = scenario.mapIt(Actions.getOrDefault(it, Error))\n\tvar deaths = 0\n\tvar count = 100_000\n\tfor _ in 1..count:\n\t\tvar revolver: Revolver\n\t\tfor action in actions:\n\t\t\tcase action\n\t\t\tof Load:\n\t\t\t\trevolver.load()\n\t\t\tof Spin:\n\t\t\t\trevolver.spin(rand(1..6))\n\t\t\tof Fire:\n\t\t\t\tif revolver.fire():\n\t\t\t\t\tinc deaths\n\t\t\t\t\tbreak\n\t\t\tof Error:\n\t\t\t\traise newException(ValueError, \"encountered an unknown action.\")\n\techo \"\"\"{100 * deaths / count:5.2f}% deaths for scenario {actions.join(\", \")}.\"\"\"\n\nrandomize()\nfor scenario in [\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"]:\n\ttest(scenario)\n" + }, + { + "id": 1325, + "length": 644, + "source": "Rosetta Code", + "text": " import strformat, times\n\nfunc ulam(n: Positive): int =\n\tif n <= 2: return n\n\tconst Max = 1352000\n\tvar list = newSeq[int](Max)\n\tlist[0] = 1\n\tlist[1] = 2\n\tvar sums = newSeq[byte](2 * Max + 1)\n\tsums[3] = 1\n\tvar size = 2\n\tvar query: int\n\twhile size < n:\n\t\tquery = list[size-1] + 1\n\t\twhile true:\n\t\t\tif sums[query] == 1:\n\t\t\t\tfor i in 0.. last name.\n\n\tVisit = tuple[date: string; score: float]\n\tVisits = Table[Positive, seq[Visit]] # Mapping id -> list of visits.\n\n\nproc readNames(path: string): Names =\n\t## Read the records (id, lastname) from the CSV file and fill a Names table.\n\tvar parser: CsvParser\n\tparser.open(path)\n\tparser.readHeaderRow()\n\twhile parser.readRow():\n\t\tlet id = parser.row[0].parseInt\n\t\tlet name = parser.row[1]\n\t\tresult[id] = name\n\nproc readVisits(path: string): Visits =\n\t## Read the records (id, date, score) from the CSV file and fill a Visits table.\n\tvar parser: CsvParser\n\tparser.open(path)\n\tparser.readHeaderRow()\n\twhile parser.readRow():\n\t\tlet id = parser.row[0].parseInt\n\t\tlet date = parser.row[1]\n\t\tlet score = if parser.row[2].len == 0: NoValue else: parser.row[2].parseFloat\n\t\tresult.mgetOrPut(id, @[]).add (date, score)\n\n\nvar\n\tnames = readNames(\"patients1.csv\")\n\tvisits = readVisits(\"patients2.csv\")\n\nnames.sort(system.cmp)\n\necho \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\"\nfor (id, name) in names.pairs:\n\tlet visitList = visits.getOrDefault(id).sorted()\n\tlet lastVisit = if visitList.len == 0: \"\" else: visitList[^1].date\n\tvar sum = 0.0\n\tvar count = 0\n\tfor visit in visitList:\n\t\tif visit.score != NoValue:\n\t\t\tsum += visit.score\n\t\t\tinc count\n\tlet scoreSum = if count == 0: \"\" else: \"{sum:>4.1f}\"\n\tlet scoreAvg = if count == 0: \"\" else: \"{sum / count.toFloat: >4.2f}\"\n\techo \"| {id:^10} | {name:^10} | {lastVisit:^10} | {scoreSum:>7} | {scoreAvg:>6} |\"\n" + }, + { + "id": 1330, + "length": 1658, + "source": "Rosetta Code", + "text": "import parseCsv, db_sqlite, sequtils, strutils\n\nconst FNames = [\"patients1.csv\", \"patients2.csv\"]\n\nproc createTableHeaders(conn: DbConn) =\n\t\tconn.exec(sql\"CREATE TABLE names(PATIENT_ID INT, LASTNAME TEXT);\")\n\t\tconn.exec(sql\"CREATE TABLE visits(PATIENT_ID INT, VISIT_DATE DATE, SCORE NUMERIC(4,1));\")\n\n\nproc fillTables(dbc: DbConn) =\n\tfor idx, fname in FNames:\n\t\tdbc.exec(sql\"BEGIN\")\n\t\tvar parser: CsvParser\n\t\tparser.open(fname)\n\t\tparser.readHeaderRow()\n\t\twhile parser.readRow():\n\t\t\tif idx == 0: # \"names\" table.\n\t\t\t\tdbc.exec(sql\"INSERT INTO names VALUES (?, ?);\", parser.row)\n\t\t\telse: # \"visits\" table\n\t\t\t\tdbc.exec(sql\"INSERT INTO visits VALUES (?, ?, ?);\", parser.row)\n\t\tdbc.exec(sql\"COMMIT\")\n\n\nproc joinTablesAndGroup(dbc: DbConn): seq[Row] =\n\tdbc.exec(sql\"\"\"CREATE TABLE answer AS\n\t\t\t\t\t\t\t\t\t SELECT\n\t\t\t\t\t\t\t\t\t\t names.PATIENT_ID,\n\t\t\t\t\t\t\t\t\t\t names.LASTNAME,\n\t\t\t\t\t\t\t\t\t\t MAX(VISIT_DATE) AS LAST_VISIT,\n\t\t\t\t\t\t\t\t\t\t SUM(SCORE) AS SCORE_SUM,\n\t\t\t\t\t\t\t\t\t\t CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG\n\t\t\t\t\t\t\t\t\t FROM\n\t\t\t\t\t\t\t\t\t\t names\n\t\t\t\t\t\t\t\t\t\t LEFT JOIN visits\n\t\t\t\t\t\t\t\t\t\t\t ON visits.PATIENT_ID = names.PATIENT_ID\n\t\t\t\t\t\t\t\t\t GROUP BY\n\t\t\t\t\t\t\t\t\t\t names.PATIENT_ID,\n\t\t\t\t\t\t\t\t\t\t names.LASTNAME\n\t\t\t\t\t\t\t\t\t ORDER BY\n\t\t\t\t\t\t\t\t\t\t names.PATIENT_ID;\"\"\")\n\tresult = dbc.getAllRows(sql\"SELECT * FROM ANSWER\")\n\n# Build the database and execute the request to get the result.\nlet dbc = open(\":memory:\", \"\", \"\", \"\")\ndbc.createTableHeaders()\ndbc.fillTables()\nlet result = dbc.joinTablesAndGroup()\ndbc.close()\n\n# Print the result.\necho \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\"\nfor row in result:\n\techo \"| \" & row.mapit(it.center(10)).join(\" | \") & '|'\n" + }, + { + "id": 1331, + "length": 2223, + "source": "Rosetta Code", + "text": "import strformat\nimport playing_cards\n\nconst\n\tNone = -1\n\tPlayer1 = 0\n\tPlayer2 = 1\n\ntype Player = range[None..Player2]\n\nconst PlayerNames: array[Player1..Player2, string] = [\"Player 1\", \"Player 2\"]\n\n\nproc `<`(a, b: Card): bool =\n\t## Compare two cards by their rank, Ace being the greatest.\n\tif a.rank == Ace: false\n\telif b.rank == Ace: true\n\telse: a.rank < b.rank\n\n\nproc displayRound(round: int; hands: openArray[Hand]; card1, card2: string; text: string) =\n\t## Display text for a round.\n\tstdout.write \"Round {round:<4} \"\n\tstdout.write \"Cards: {hands[Player1].len:>2}/{hands[Player2].len:<2} \"\n\tstdout.write \"{card1:>3} {card2:>3} \"\n\techo text\n\n\nproc outOfCards(player: Player) =\n\t## Display a message when a player has run out of cards.\n\techo \"{PlayerNames[player]} has run out of cards.\"\n\n\nproc doRound(hands: var openArray[Hand]; num: Positive) =\n\t## Execute a round.\n\n\tvar stack1, stack2: seq[Card]\n\tvar winner: Player = None\n\n\twhile winner == None:\n\t\tlet card1 = hands[Player1].draw()\n\t\tlet card2 = hands[Player2].draw()\n\t\tstack1.add card1\n\t\tstack2.add card2\n\t\tif card1.rank != card2.rank:\n\t\t\twinner = if card1 < card2: Player2 else: Player1\n\t\t\tdisplayRound(num, hands, $card1, $card2, \"{PlayerNames[winner]} takes the cards.\")\n\t\telse:\n\t\t\t# There is a war.\n\t\t\tdisplayRound(num, hands, $card1, $card2, \"This is a war.\")\n\t\t\tif hands[Player1].len == 0:\n\t\t\t\twinner = Player2\n\t\t\telif hands[Player2].len == 0:\n\t\t\t\twinner = Player1\n\t\t\telse:\n\t\t\t\t# Add a hidden card on stacks.\n\t\t\t\tstack1.add hands[Player1].draw()\n\t\t\t\tstack2.add hands[Player2].draw()\n\t\t\t\tdisplayRound(num, hands, \" ?\", \" ?\", \"Cards are face down.\")\n\t\t\t\t# Check if each player has enough cards to continue the war.\n\t\t\t\tif hands[Player1].len == 0:\n\t\t\t\t\tPlayer1.outOfCards()\n\t\t\t\t\twinner = Player2\n\t\t\t\telif hands[Player2].len == 0:\n\t\t\t\t\tPlayer2.outOfCards()\n\t\t\t\t\twinner = Player1\n\n\t# Update hands.\n\tvar stack = stack1 & stack2\n\tstack.shuffle()\n\thands[winner] = stack & hands[winner]\n\n\n\nvar deck = initDeck()\ndeck.shuffle()\n\nvar hands = deck.deal(2, 26)\nvar num = 0\nwhile true:\n\tinc num\n\thands.doRound(num)\n\tif hands[Player1].len == 0:\n\t\techo \"Player 2 wins this game.\"\n\t\tbreak\n\tif hands[Player2].len == 0:\n\t\techo \"Player 1 wins this game.\"\n\t\tbreak\n" + }, + { + "id": 1332, + "length": 1044, + "source": "Rosetta Code", + "text": "import math, strutils\n\nfunc hourglassFlipper(hourglasses: openArray[int];\n\t\t\t\t\t\t\t\t\t\t\ttarget: int): tuple[start: int; series: seq[int]] =\n\tvar flippers = @hourglasses\n\tfor _ in 0..10_000:\n\t\tlet n = min(flippers)\n\t\tresult.series.add n\n\t\tfor i in 0..flippers.high:\n\t\t\tdec flippers[i], n\n\t\t\tif flippers[i] == 0: flippers[i] = hourglasses[i]\n\t\tresult.start = result.series.high\n\t\twhile result.start >= 0:\n\t\t\tif sum(result.series[result.start..^1]) == target: return\n\t\t\tdec result.start\n\traise newException(ValueError, \"Unable to find an answer within 10_000 iterations.\")\n\n\necho \"Flip an hourglass every time it runs out of grains, \"\necho \"and note the interval in time.\"\nconst Tests = [(@[4, 7], 9), (@[5, 7, 31], 36)]\nfor test in Tests:\n\tlet\n\t\thourglasses = test[0]\n\t\ttarget = test[1]\n\t\t(start, series) = hourglassFlipper(hourglasses, target)\n\t\t`end` = series.high\n\techo \"\\nSeries: \", series.join(\" \")\n\techo \"Use hourglasses from indices $1 to $2 (inclusive) to sum \".format(start, `end`),\n\t\t\t \"$1 using $2.\".format(target, hourglasses.join(\" \"))\n" + }, + { + "id": 1333, + "length": 1452, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\ntype Solver = object\n\twant: Positive\n\tcount1: Natural\n\tcount2: Natural\n\twidth: Natural\n\nproc count(solver: var Solver; sum: int; used, have, uindices, rindices: seq[int]) =\n\tif sum == solver.want:\n\t\tinc solver.count1\n\t\tinc solver.count2, fac(used.len)\n\t\tif solver.count1 < 11:\n\t\t\tlet uindiceStr = ($uindices.join(\" \")).alignLeft(solver.width)\n\t\t\techo \" indices $1 -> used $2\".format(uindiceStr, used.join(\" \"))\n\telif sum < solver.want and have.len != 0:\n\t\tlet thisCoin = have[0]\n\t\tlet index = rindices[0]\n\t\tlet rest = have[1..^1]\n\t\tlet rindices = rindices[1..^1]\n\t\tsolver.count(sum + thisCoin, used & thisCoin, rest, uindices & index, rindices)\n\t\tsolver.count(sum, used, rest, uindices, rindices)\n\nproc countCoins(want: int; coins: openArray[int]; width: int) =\n\techo \"Sum $# from coins $#\".format(want, coins.join(\" \"))\n\tvar solver = Solver(want: want, width: width)\n\tvar rindices = toSeq(0..coins.high)\n\tsolver.count(0, newSeq[int](), @coins, newSeq[int](), rindices)\n\tif solver.count1 > 10:\n\t\techo \" .......\"\n\t\techo \" (only the first 10 ways generated are shown)\"\n\techo \"Number of ways - order unimportant : \", solver.count1, \" (as above)\"\n\techo \"Number of ways - order important : \", solver.count2, \" (all perms of above indices)\\n\"\n\nwhen isMainModule:\n\tcountCoins(6, [1, 2, 3, 4, 5], 5)\n\tcountCoins(6, [1, 1, 2, 3, 3, 4, 5], 7)\n\tcountCoins(40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100], 18)\n" + }, + { + "id": 1334, + "length": 1116, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\ntype\n\tKind = enum kValue, kList\n\tNode = ref object\n\t\tcase kind: Kind\n\t\tof kValue: value: int\n\t\tof kList: list: seq[Node]\n\n\nproc newTree(s: varargs[int]): Node =\n\t## Build a tree from a list of level values.\n\tvar level = 1\n\tresult = Node(kind: kList)\n\tvar stack = @[result]\n\tfor n in s:\n\t\tif n <= 0:\n\t\t\traise newException(ValueError, \"expected a positive integer, got \" & $n)\n\t\tlet node = Node(kind: kValue, value: n)\n\t\tif n < level:\n\t\t\t# Unstack lists.\n\t\t\tstack.setLen(n)\n\t\t\tlevel = n\n\t\telse:\n\t\t\twhile n > level:\n\t\t\t\t# Create intermediate lists.\n\t\t\t\tlet newList = Node(kind: kList)\n\t\t\t\tstack[^1].list.add newList\n\t\t\t\tstack.add newList\n\t\t\t\tinc level\n\t\t# Add value.\n\t\tstack[^1].list.add node\n\n\nproc `$`(node: Node): string =\n\t## Display a tree using a nested lists representation.\n\tif node.kind == kValue: $node.value\n\telse: '[' & node.list.mapIt($it).join(\", \") & ']'\n\n\nfor list in [newSeq[int](), # Empty list (== @[]).\n\t\t\t\t\t\t @[1, 2, 4],\n\t\t\t\t\t\t @[3, 1, 3, 1],\n\t\t\t\t\t\t @[1, 2, 3, 1],\n\t\t\t\t\t\t @[3, 2, 1, 3],\n\t\t\t\t\t\t @[3, 3, 3, 1, 1, 3, 3, 3]]:\n\techo ($list).align(25), \" -> \", newTree(list)\n" + }, + { + "id": 1335, + "length": 4888, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst\n\tEmx = 64 # Exponent maximum.\n\tDmx = 100000 # Approximation loop maximum.\n\tAmx = 1048576 # Argument maximum.\n\tPMax = 32749 # Prime maximum.\n\ntype\n\n\tRatio = tuple[a, b: int]\n\n\tPadic = object\n\t\tp: int # Prime.\n\t\tk: int # Precision.\n\t\tv: int\n\t\td: array[-Emx..(Emx-1), int]\n\n\tPadicError = object of ValueError\n\n\nproc r2pa(pa: var Padic; q: Ratio; sw: bool) =\n\t## Convert \"q\" to p-adic number, set \"sw\" to print.\n\n\tvar (a, b) = q\n\n\tif b == 0:\n\t\traise newException(PadicError, \"Wrong rational: {a}/{b}\" )\n\tif b < 0:\n\t\tb = -b\n\t\ta = -a\n\tif abs(a) > Amx or b > Amx:\n\t\traise newException(PadicError, \"Rational exceeding limits: {a}/{b}\")\n\tif pa.p < 2:\n\t\traise newException(PadicError, \"Wrong value for p: {pa.p}\")\n\tif pa.k < 1:\n\t\traise newException(PadicError, \"Wrong value for k: {pa.k}\")\n\tpa.p = min(pa.p, PMax) # Maximum short prime.\n\tpa.k = min(pa.k, Emx - 1) # Maximum array length.\n\n\tif sw: echo \"{a}/{b} + 0({pa.p}^{pa.k})\"\n\n\t# Initialize.\n\tpa.v = 0\n\tpa.d.reset()\n\tif a == 0: return\n\tvar i = 0\n\n\t# Find -exponent of \"p\" in \"b\".\n\twhile b mod pa.p == 0:\n\t\tb = b div pa.p\n\t\tdec i\n\n\tvar s = 0\n\tvar r = b mod pa.p\n\n\t# Modular inverse for small \"p\".\n\tvar b1 = 1\n\twhile b1 < pa.p:\n\t\tinc s, r\n\t\tif s >= pa.p: dec s, pa.p\n\t\tif s == 1: break\n\t\tinc b1\n\tif b1 == pa.p:\n\t\traise newException(PadicError, \"Impossible to compute inverse modulo\")\n\tpa.v = Emx\n\twhile true:\n\t\t# Find exponent of \"p\" in \"a\".\n\t\twhile a mod pa.p == 0:\n\t\t\ta = a div pa.p\n\t\t\tinc i\n\t\t# Valuation.\n\t\tif pa.v == Emx: pa.v = i\n\t\t# Upper bound.\n\t\tif i >= Emx: break\n\t\t# Check precision.\n\t\tif i - pa.v > pa.k: break\n\t\t# Next digit.\n\t\tpa.d[i] = floorMod(a * b1, pa.p)\n\t\t# Remainder - digit * divisor.\n\t\tdec a, pa.d[i] * b\n\t\tif a == 0: break\n\n\nfunc dsum(pa: Padic): int =\n\t## Horner's rule.\n\tlet t = min(pa.v, 0)\n\tfor i in countdown(pa.k - 1 + t, t):\n\t\tvar r = result\n\t\tresult *= pa.p\n\t\tif r != 0 and (result div r - pa.p) != 0:\n\t\t\treturn -1 # Overflow.\n\t\tinc result, pa.d[i]\n\n\nfunc `+`(pa, pb: Padic): Padic =\n\t## Add two p-adic numbers.\n\tassert pa.p == pb.p and pa.k == pb.k\n\tresult.p = pa.p\n\tresult.k = pa.k\n\tvar c = 0\n\tresult.v = min(pa.v, pb.v)\n\tfor i in result.v..(pa.k + result.v):\n\t\tinc c, pa.d[i] + pb.d[i]\n\t\tif c >= pa.p:\n\t\t\tresult.d[i] = c - pa.p\n\t\t\tc = 1\n\t\telse:\n\t\t\tresult.d[i] = c\n\t\t\tc = 0\n\n\nfunc cmpt(pa: Padic): Padic =\n\t## Return the complement.\n\tvar c = 1\n\tresult.p = pa.p\n\tresult.k = pa.k\n\tresult.v = pa.v\n\tfor i in pa.v..(pa.k + pa.v):\n\t\tinc c, pa.p - 1 - pa.d[i]\n\t\tif c >= pa.p:\n\t\t\tresult.d[i] = c - pa.p\n\t\t\tc = 1\n\t\telse:\n\t\t\tresult.d[i] = c\n\t\t\tc = 0\n\n\nfunc crat(pa: Padic): string =\n\t## Rational reconstruction.\n\tvar s = pa\n\n\t# Denominator count.\n\tvar i = 1\n\tvar fl = false\n\twhile i <= Dmx:\n\t\t# Check for integer.\n\t\tvar j = pa.k - 1 + pa.v\n\t\twhile j >= pa.v:\n\t\t\tif s.d[j] != 0: break\n\t\t\tdec j\n\t\tfl = (j - pa.v) * 2 < pa.k\n\t\tif fl:\n\t\t\tfl = false\n\t\t\tbreak\n\t\t# Check negative integer.\n\t\tj = pa.k - 1 + pa.v\n\t\twhile j >= pa.v:\n\t\t\tif pa.p - 1 - s.d[j] != 0: break\n\t\t\tdec j\n\t\tfl = (j - pa.v) * 2 < pa.k\n\t\tif fl: break\n\t\t# Repeatedly add \"pa\" to \"s\".\n\t\ts = s + pa\n\t\tinc i\n\n\tif fl: s = s.cmpt()\n\n\t# Numerator: weighted digit sum.\n\tvar x = s.dsum()\n\tvar y = i\n\tif x < 0 or y > Dmx:\n\t\traise newException(PadicError, \"Error during rational reconstruction: {x}, {y}\")\n\t# Negative powers.\n\tfor i in pa.v..(-1): y *= pa.p\n\t# Negative rational.\n\tif fl: x = -x\n\tresult = $x\n\tif y > 1: result.add \"/{y}\"\n\n\nfunc `$`(pa: Padic): string =\n\t## String representation.\n\tlet t = min(pa.v, 0)\n\tfor i in countdown(pa.k - 1 + t, t):\n\t\tresult.add $pa.d[i]\n\t\tif i == 0 and pa.v < 0: result.add \".\"\n\t\tresult.add \" \"\n\n\nproc print(pa: Padic; sw: int) =\n\techo pa\n\t# Rational approximation.\n\tif sw != 0: echo pa.crat()\n\n\nwhen isMainModule:\n\n\t# Rational reconstruction depends on the precision\n\t# until the dsum-loop overflows.\n\tconst Data = [[2, 1, 2, 4, 1, 1],\n\t\t\t\t\t\t\t\t[4, 1, 2, 4, 3, 1],\n\t\t\t\t\t\t\t\t[4, 1, 2, 5, 3, 1],\n\t\t\t\t\t\t\t\t[4, 9, 5, 4, 8, 9],\n\t\t\t\t\t\t\t\t[26, 25, 5, 4, -109, 125],\n\t\t\t\t\t\t\t\t[49, 2, 7, 6, -4851, 2],\n\t\t\t\t\t\t\t\t[-9, 5, 3, 8, 27, 7],\n\t\t\t\t\t\t\t\t[5, 19, 2, 12, -101, 384],\n\t\t\t\t\t\t\t\t# Two decadic pairs.\n\t\t\t\t\t\t\t\t[2, 7, 10, 7, -1, 7],\n\t\t\t\t\t\t\t\t[34, 21, 10, 9, -39034, 791],\n\t\t\t\t\t\t\t\t# Familiar digits.\n\t\t\t\t\t\t\t\t[11, 4, 2, 43, 679001, 207],\n\t\t\t\t\t\t\t\t[-8, 9, 23, 9, 302113, 92],\n\t\t\t\t\t\t\t\t[-22, 7, 3, 23, 46071, 379],\n\t\t\t\t\t\t\t\t[-22, 7, 32749, 3, 46071, 379],\n\t\t\t\t\t\t\t\t[35, 61, 5, 20, 9400, 109],\n\t\t\t\t\t\t\t\t[-101, 109, 61, 7, 583376, 6649],\n\t\t\t\t\t\t\t\t[-25, 26, 7, 13, 5571, 137],\n\t\t\t\t\t\t\t\t[1, 4, 7, 11, 9263, 2837],\n\t\t\t\t\t\t\t\t[122, 407, 7, 11, -517, 1477],\n\t\t\t\t\t\t\t\t# More subtle.\n\t\t\t\t\t\t\t\t[5, 8, 7, 11, 353, 30809]]\n\n\tfor d in Data:\n\t\ttry:\n\t\t\tvar a, b = Padic(p: d[2], k: d[3])\n\t\t\tr2pa(a, (d[0], d[1]), true)\n\t\t\tprint(a, 0)\n\t\t\tr2pa(b, (d[4], d[5]), true)\n\t\t\tprint(b, 0)\n\t\t\techo \"+ =\"\n\t\t\tprint(a + b, 1)\n\t\t\techo \"\"\n\t\texcept PadicError:\n\t\t\techo getCurrentExceptionMsg()\n" + }, + { + "id": 1336, + "length": 2104, + "source": "Rosetta Code", + "text": "import algorithm, strformat\n\nfunc binIt(limits, data: openArray[int]): seq[Natural] =\n\tresult.setLen(limits.len + 1)\n\tfor d in data:\n\t\tinc result[limits.upperBound(d)]\n\nproc binPrint(limits: openArray[int]; bins: seq[Natural]) =\n\techo \" < {limits[0]:3} := {bins[0]:3}\"\n\tfor i in 1..limits.high:\n\t\techo \">= {limits[i-1]:3} .. < {limits[i]:3} := {bins[i]:3}\"\n\techo \">= {limits[^1]:3} := {bins[^1]:3}\"\n\n\nwhen isMainModule:\n\n\techo \"Example 1:\"\n\tconst\n\t\tLimits1 = [23, 37, 43, 53, 67, 83]\n\t\tData1 = [95, 21, 94, 12, 99, 4, 70, 75, 83, 93,\n\t\t\t\t\t\t 52, 80, 57, 5, 53, 86, 65, 17, 92, 83,\n\t\t\t\t\t\t 71, 61, 54, 58, 47, 16, 8, 9, 32, 84,\n\t\t\t\t\t\t\t7, 87, 46, 19, 30, 37, 96, 6, 98, 40,\n\t\t\t\t\t\t 79, 97, 45, 64, 60, 29, 49, 36, 43, 55]\n\tlet bins1 = binIt(Limits1, Data1)\n\tbinPrint(Limits1, bins1)\n\n\techo \"\"\n\techo \"Example 2:\"\n\tconst\n\t\tLimits2 = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n\t\tData2 = [445, 814, 519, 697, 700, 130, 255, 889, 481, 122,\n\t\t\t\t\t\t 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,\n\t\t\t\t\t\t 416, 589, 930, 373, 202, 253, 775, 47, 731, 685,\n\t\t\t\t\t\t 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n\t\t\t\t\t\t 655, 267, 248, 477, 549, 238, 62, 678, 98, 534,\n\t\t\t\t\t\t 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,\n\t\t\t\t\t\t 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n\t\t\t\t\t\t 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n\t\t\t\t\t\t 345, 110, 720, 917, 313, 845, 426, 9, 457, 628,\n\t\t\t\t\t\t 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,\n\t\t\t\t\t\t 854, 740, 83, 216, 421, 94, 517, 479, 292, 963,\n\t\t\t\t\t\t 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,\n\t\t\t\t\t\t 787, 942, 456, 242, 759, 898, 576, 67, 298, 425,\n\t\t\t\t\t\t 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n\t\t\t\t\t\t 698, 765, 331, 487, 251, 600, 879, 342, 982, 527,\n\t\t\t\t\t\t 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,\n\t\t\t\t\t\t 605, 847, 353, 968, 832, 205, 838, 427, 876, 959,\n\t\t\t\t\t\t 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n\t\t\t\t\t\t 466, 23, 707, 467, 33, 670, 921, 180, 991, 396,\n\t\t\t\t\t\t 160, 436, 717, 918, 8, 374, 101, 684, 727, 749]\n\tlet bins2 = binIt(Limits2, Data2)\n\tbinPrint(Limits2, bins2)\n" + }, + { + "id": 1337, + "length": 1344, + "source": "Rosetta Code", + "text": "import math, strutils\n\nconst\n\tLim1 = 100_000 # Limit for untouchable numbers.\n\tLim2 = 14 * Lim1 # Limit for computation of sum of divisors.\n\nproc sumdiv(n: uint): uint =\n\t## Return the sum of the strict divisors of \"n\".\n\tresult = 1\n\tlet r = sqrt(n.float).uint\n\tlet k = if (n and 1) == 0: 1u else: 2u\n\tfor d in countup(k + 1, r, k):\n\t\tif n mod d == 0:\n\t\t\tresult += d\n\t\t\tlet q = n div d\n\t\t\tif q != d: result += q\n\nvar\n\tisSumDiv: array[1..Lim2, bool]\n\tisPrime: array[1..Lim1, bool]\n\n# Fill both sieves in a single pass.\nfor n in 1u..Lim2:\n\tlet s = sumdiv(n)\n\tif s <= Lim2:\n\t\tisSumDiv[s] = true\n\t\tif s == 1 and n <= Lim1:\n\t\t\tisPrime[n] = true\nisPrime[1] = false\n\n# Build list of untouchable numbers.\nvar list = @[2, 5]\nfor n in countup(6, Lim1, 2):\n\tif not (isSumDiv[n] or isPrime[n - 1] or isPrime[n - 3]):\n\t\tlist.add n\n\necho \"Untouchable numbers <= 2000:\"\nvar count, lcount = 0\nfor n in list:\n\tif n <= 2000:\n\t\tstdout.write ($n).align(5)\n\t\tinc count\n\t\tinc lcount\n\t\tif lcount == 20:\n\t\t\techo()\n\t\t\tlcount = 0\n\telse:\n\t\tif lcount > 0: echo()\n\t\tbreak\n\nconst CountMessage = \"There are $1 untouchable numbers <= $2.\"\necho CountMessage.format(count, 2000), '\\n'\n\ncount = 0\nvar lim = 10\nfor n in list:\n\tif n > lim:\n\t\techo CountMessage.format(count, lim)\n\t\tlim *= 10\n\tinc count\nif lim == Lim1:\n\t# Emit last message.\n\techo CountMessage.format(count, lim)\n" + }, + { + "id": 1338, + "length": 726, + "source": "Rosetta Code", + "text": "import strformat, strutils, tables\n\nconst Vowels = {'a', 'e', 'i', 'o', 'u'}\n\ntemplate plural(n: int): string = (if n > 1: \"s\" else: \"\")\n\nvar results: array[0..9, seq[string]]\n\nfor word in \"unixdict.txt\".lines:\n\tif word.len <= 10: continue\n\n\tblock checkWord:\n\t\tlet letterCounts = word.toCountTable\n\t\tvar consonantCount = 0\n\t\tfor key, count in letterCounts.pairs:\n\t\t\tif key notin Vowels:\n\t\t\t\tif count > 1: break checkWord\n\t\t\t\tif count == 1: inc consonantCount\n\t\tresults[consonantCount].add word\n\nfor n in countdown(9, 4):\n\tlet count = results[n].len\n\techo \"\\nFound {count} word{plural(count)} with {n} unique consonants:\"\n\tfor i, word in results[n]:\n\t\tstdout.write word.align(14), if (i + 1) mod 9 == 0: '\\n' else: ' '\n\techo()\n" + }, + { + "id": 1339, + "length": 1136, + "source": "Rosetta Code", + "text": "import algorithm, sequtils\n\nconst PrimeDigits = [2, 3, 5, 7]\n\ntype\n\tDigit = 0..9\n\tDigitSeq = seq[Digit]\n\nfunc toInt(s: DigitSeq): int =\n\t## Convert a sequence of digits to an int.\n\tfor d in s:\n\t\tresult = 10 * result + d\n\n\nproc findStrangeNumbers(ndigits: Positive): seq[int] =\n\t## Return the list of strange numbers with \"ndigits\" digits.\n\tvar list: seq[DigitSeq] = toSeq(1..9).mapIt(@[Digit it]) # Starting digits.\n\tfor _ in 2..ndigits:\n\t\tvar newList: seq[DigitSeq] # List with one more digit.\n\t\tfor dseq in list:\n\t\t\tlet last = dseq[^1]\n\t\t\tfor p in PrimeDigits:\n\t\t\t\tif last - p >= 0:\n\t\t\t\t\tnewList.add dseq & (last - p)\n\t\t\t\tif last + p <= 9:\n\t\t\t\t\tnewList.add dseq & (last + p)\n\t\tlist = move(newList) # \"newList\" becomes the current list.\n\tresult = list.map(toInt)\n\n\nvar result = sorted(findStrangeNumbers(3).filterIt(it < 500))\necho \"Found \", result.len, \" strange numbers between 101 and 499.\"\nfor i, n in result:\n\tstdout.write n, if (i + 1) mod 15 == 0: '\\n' else: ' '\necho()\n\nresult = findStrangeNumbers(10).filterIt(it div 1_000_000_000 == 1)\necho \"\\nFound \", result.len, \" strange numbers with 10 digits and starting with 1.\"\n" + }, + { + "id": 1340, + "length": 828, + "source": "Rosetta Code", + "text": "import random, strformat, strutils, sugar\n\ntype ValRange = range[0.0..1.0]\n\nfunc modifier(x: ValRange): ValRange =\n\tif x < 0.5: 2 * (0.5 - x) else: 2 * (x - 0.5)\n\nproc rand(modifier: (float) -> float): ValRange =\n\twhile true:\n\t\tlet r1 = rand(1.0)\n\t\tlet r2 = rand(1.0)\n\t\tif r2 < modifier(r1):\n\t\t\treturn r1\n\nconst\n\tN = 100_000\n\tNumBins = 20\n\tHistChar = \"X\"\n\tHistCharSize = 125\n\tBinSize = 1 / NumBins\n\nrandomize()\n\nvar bins: array[NumBins, int]\nfor i in 0.. 1: yield 1\n\tvar p = 1.0\n\tvar count = 1\n\twhile count < n:\n\t\tyield (p / S).toInt\n\t\tp *= P\n\t\tinc count\n\n\niterator padovan3(n: Natural): string {.closure.} =\n\t## Yield the strings produced by the L-system.\n\tvar s = \"A\"\n\tvar count = 0\n\twhile count < n:\n\t\tyield s\n\t\tvar next: string\n\t\tfor ch in s:\n\t\t\tnext.add Rules[ch]\n\t\ts = move(next)\n\t\tinc count\n\n\necho \"First 20 terms of the Padovan sequence:\"\necho toSeq(padovan1(20)).join(\" \")\n\nlet list1 = toSeq(padovan1(64))\nlet list2 = toSeq(padovan2(64))\necho \"The first 64 iterative and calculated values \",\n\t\t if list1 == list2: \"are the same.\" else: \"differ.\"\n\necho \"\"\necho \"First 10 L-system strings:\"\necho toSeq(padovan3(10)).join(\" \")\necho \"\"\necho \"Lengths of the 32 first L-system strings:\"\nlet list3 = toSeq(padovan3(32)).mapIt(it.len)\necho list3.join(\" \")\necho \"These lengths are\",\n\t\t if list3 == list1[0..31]: \" \" else: \" not \",\n\t\t \"the 32 first terms of the Padovan sequence.\"\n" + }, + { + "id": 1342, + "length": 1026, + "source": "Rosetta Code", + "text": "import strformat, strutils, sugar\n\nfunc isPrime(n: Positive): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\n\niterator triplets(primes: openArray[int]): (int, int, int) =\n\t## Yield the triplets.\n\tfor i in 0..primes.high-2:\n\t\tlet n = primes[i]\n\t\tfor j in (i+1)..primes.high-1:\n\t\t\tlet m = primes[j]\n\t\t\tfor k in (j+1)..primes.high:\n\t\t\t\tlet p = primes[k]\n\t\t\t\tif (n + m + p).isPrime:\n\t\t\t\t\tyield (n, m, p)\n\n\nconst Primes30 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\necho \"List of strange unique prime triplets for n < m < p < 30:\"\nfor (n, m, p) in Primes30.triplets():\n\techo \"{n:2} + {m:2} + {p:2} = {n+m+p}\"\n\necho()\nconst Primes1000 = collect(newSeq):\n\t\t\t\t\t\t\t\t\t\t for n in 2..999:\n\t\t\t\t\t\t\t\t\t\t\t if n.isPrime: n\nvar count = 0\nfor _ in Primes1000.triplets(): inc count\necho \"Count of strange unique prime triplets for n < m < p < 1000: \", ($count).insertSep()\n" + }, + { + "id": 1343, + "length": 2092, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst M = [uint64 1, 3, 5, 7, 11]\n\ntemplate isqrt(n: uint64): uint64 = uint64(sqrt(float(n)))\ntemplate isEven(n: uint64): bool = (n and 1) == 0\n\nproc squfof(n: uint64): uint64 =\n\n\tif n.isEven: return 2\n\tvar h = uint64(sqrt(float(n)) + 0.5)\n\tif h * h == n: return h\n\n\tfor m in M:\n\t\tif m > 1 and (n mod m == 0): return m\n\t\t# Check overflow m * n.\n\t\tif n > uint64.high div m: break\n\t\tlet mn = m * n\n\t\tvar r = isqrt(mn)\n\t\tif r * r > mn: dec r\n\t\tlet rn = r\n\n\t\t# Principal form.\n\t\tvar b = r\n\t\tvar a = 1u64\n\t\th = (rn + b) div a * a - b\n\t\tvar c = (mn - h * h) div a\n\n\t\tfor i in 2..<(4 * isqrt(2 * r)):\n\t\t\t# Search principal cycle.\n\t\t\tswap a, c\n\t\t\tvar q = (rn + b) div a\n\t\t\tlet t = b\n\t\t\tb = q * a - b\n\t\t\tc += q * (t - b)\n\n\t\t\tif i.isEven:\n\t\t\t\tr = uint64(sqrt(float(c)) + 0.5)\n\t\t\t\tif r * r == c: # Square form found?\n\n\t\t\t\t\t# Inverse square root.\n\t\t\t\t\tq = (rn - b) div r\n\t\t\t\t\tvar v = q * r + b\n\t\t\t\t\tvar w = (mn - v * v) div r\n\n\t\t\t\t\t# Search ambiguous cycle.\n\t\t\t\t\tvar u = r\n\t\t\t\t\twhile true:\n\t\t\t\t\t\tswap w, u\n\t\t\t\t\t\tr = v\n\t\t\t\t\t\tq = (rn + v) div u\n\t\t\t\t\t\tv = q * u - v\n\t\t\t\t\t\tif v == r: break\n\t\t\t\t\t\tw += q * (r - v)\n\n\t\t\t\t\t# Symmetry point.\n\t\t\t\t\th = gcd(n, u)\n\t\t\t\t\tif h != 1: return h\n\n\tresult = 1\n\nconst Data = [2501u64,\n\t\t\t\t\t\t\t12851u64,\n\t\t\t\t\t\t\t13289u64,\n\t\t\t\t\t\t\t75301u64,\n\t\t\t\t\t\t\t120787u64,\n\t\t\t\t\t\t\t967009u64,\n\t\t\t\t\t\t\t997417u64,\n\t\t\t\t\t\t\t7091569u64,\n\t\t\t\t\t\t\t13290059u64,\n\t\t\t\t\t\t\t42854447u64,\n\t\t\t\t\t\t\t223553581u64,\n\t\t\t\t\t\t\t2027651281u64,\n\t\t\t\t\t\t\t11111111111u64,\n\t\t\t\t\t\t\t100895598169u64,\n\t\t\t\t\t\t\t1002742628021u64,\n\t\t\t\t\t\t\t60012462237239u64,\n\t\t\t\t\t\t\t287129523414791u64,\n\t\t\t\t\t\t\t9007199254740931u64,\n\t\t\t\t\t\t\t11111111111111111u64,\n\t\t\t\t\t\t\t314159265358979323u64,\n\t\t\t\t\t\t\t384307168202281507u64,\n\t\t\t\t\t\t\t419244183493398773u64,\n\t\t\t\t\t\t\t658812288346769681u64,\n\t\t\t\t\t\t\t922337203685477563u64,\n\t\t\t\t\t\t\t1000000000000000127u64,\n\t\t\t\t\t\t\t1152921505680588799u64,\n\t\t\t\t\t\t\t1537228672809128917u64,\n\t\t\t\t\t\t\t4611686018427387877u64]\n\necho \"N f N/f\"\necho \"======================================\"\nfor n in Data:\n\tlet f = squfof(n)\n\tlet res = if f == 1: \"fail\" else: \"{f:<10} {n div f}\"\n\techo \"{n:<22} {res}\"\n" + }, + { + "id": 1344, + "length": 653, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nfunc isPrime(n: Positive): bool =\n\tif (n and 1) == 0: return n == 2\n\tvar m = 3\n\twhile m * m <= n:\n\t\tif n mod m == 0: return false\n\t\tinc m, 2\n\tresult = true\n\nfunc sumn(n: Positive): int =\n\tvar n = n.int\n\twhile n != 0:\n\t\tresult += n mod 10\n\t\tn = n div 10\n\nfunc isNicePrime(n: Positive): bool =\n\tif not n.isPrime: return false\n\tvar n = n\n\twhile n notin 1..9:\n\t\tn = sumn(n)\n\tresult = n in [2, 3, 5, 7]\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for n in 501..999:\n\t\t\t\t\t\t\t if n.isNicePrime: n\n\necho \"Found $1 nice primes between 501 and 999:\".format(list.len)\nfor i, n in list:\n\tstdout.write n, if (i + 1) mod 10 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1345, + "length": 1495, + "source": "Rosetta Code", + "text": "import math, strformat, strutils, sugar\nimport bignum\n\nproc pow(a: int; n: Int): Int =\n\t## Compute a^n for \"n\" big integer.\n\tvar n = n\n\tvar a = newInt(a)\n\tif a > 0:\n\t\tresult = newInt(1)\n\t\t# Start with Int values for \"n\".\n\t\twhile not n.isZero:\n\t\t\tif (n and 1) != 0:\n\t\t\t\tresult *= a\n\t\t\tn = n shr 1\n\t\t\ta *= a\n\nfunc sf(n: Natural): Int =\n\tresult = newInt(1)\n\tfor i in 2..n:\n\t\tresult *= fac(i)\n\nfunc hf(n: Natural): Int =\n\tresult = newInt(1)\n\tfor i in 2..n:\n\t\tresult *= pow(i, uint(i))\n\nfunc af(n: Natural): Int =\n\tresult = newInt(0)\n\tvar m = (n and 1) shl 1 - 1\n\tfor i in 1..n:\n\t\tresult += m * fac(i)\n\t\tm = -m\n\nfunc ef(n: Natural): Int =\n\tresult = newInt(1)\n\tfor k in 2..n:\n\t\tresult = pow(k, result)\n\nfunc rf(n: int | Int): int =\n\tif n == 1: return 0\n\tresult = 1\n\tvar p = newInt(1)\n\twhile p < n:\n\t\tinc result\n\t\tp *= result\n\tif p > n: result = -1\n\nlet sfs = collect(newSeq, for n in 0..9: sf(n))\necho \"First {sfs.len} superfactorials: \", sfs.join(\" \")\n\nlet hfs = collect(newSeq, for n in 0..9: hf(n))\necho \"First {hfs.len} hyperfactorials: \", hfs.join(\" \")\n\nlet afs = collect(newSeq, for n in 0..9: af(n))\necho \"First {afs.len} alternating factorials: \", afs.join(\" \")\n\nlet efs = collect(newSeq, for n in 0..4: ef(n))\necho \"First {efs.len} exponential factorials: \", efs.join(\" \")\n\necho \"\\nNumber of digits of ef(5): \", len($ef(5))\n\necho \"\\nReverse factorials:\"\nfor n in [1, 2, 6, 24, 119, 120, 720, 5040, 40320, 362880, 3628800]:\n\tlet r = rf(n)\n\techo \"{n:7}: \", if r >= 0: \"{r:2}\" else: \"undefined\"\n" + }, + { + "id": 1346, + "length": 640, + "source": "Rosetta Code", + "text": "import sets, strutils, sugar\n\nconst N = 1000\n\nfunc isPrime(n: Positive): bool {.compileTime.} =\n\tif (n and 1) == 0: return n == 2\n\tvar m = 3\n\twhile m * m <= n:\n\t\tif n mod m == 0: return false\n\t\tinc m, 2\n\tresult = true\n\nconst\n\tPrimeList = collect(newSeq):\n\t\t\t\t\t\t\t\tfor n in 2..N:\n\t\t\t\t\t\t\t\t\tif n.isPrime: n\n\tPrimeSet = PrimeList.toHashSet\n\nlet cousinList = collect(newSeq):\n\t\t\t\t\t\t\t\t\t for n in PrimeList:\n\t\t\t\t\t\t\t\t\t\t if (n + 4) in PrimeSet: (n, n + 4)\n\necho \"Found $# cousin primes less than $#:\".format(cousinList.len, N)\nfor i, cousins in cousinList:\n\tstdout.write ($cousins).center(10)\n\tstdout.write if (i+1) mod 7 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1347, + "length": 1190, + "source": "Rosetta Code", + "text": "import math, sets, strutils, sugar\n\nconst N = 1_000_000\n\n# Sieve of Erathostenes.\nvar isComposite: array[2..N, bool]\nfor n in 2..N:\n\tlet n2 = n * n\n\tif n2 > N: break\n\tif not isComposite[n]:\n\t\tfor k in countup(n2, N, n):\n\t\t\tisComposite[k] = true\n\ntemplate isPrime(n: int): bool = n > 1 and not isComposite[n]\n\nlet primeList = collect(newSeq):\n\t\t\t\t\t\t\t\t\tfor n in 2..N:\n\t\t\t\t\t\t\t\t\t\tif n.isPrime: n\n\nconst Factorials = collect(newSeq):\n\t\t\t\t\t\t\t\t\t\t for n in 1..20:\n\t\t\t\t\t\t\t\t\t\t\t if fac(n) >= N: break\n\t\t\t\t\t\t\t\t\t\t\t fac(n)\n\n\nproc isErdosPrime(p: int): bool =\n\t## Check if prime \"p\" is an Erdos prime.\n\tfor f in Factorials:\n\t\tif f >= p: break\n\t\tif (p - f).isPrime: return false\n\tresult = true\n\n\nlet erdosList2500 = collect(newSeq):\n\t\t\t\t\t\t\t\t\t\t\tfor p in primeList:\n\t\t\t\t\t\t\t\t\t\t\t\tif p >= 2500: break\n\t\t\t\t\t\t\t\t\t\t\t\tif p.isErdosPrime: p\n\necho \"Found $# Erdos primes less than 2500:\".format(erdosList2500.len)\nfor i, prime in erdosList2500:\n\tstdout.write ($prime).align(5)\n\tstdout.write if (i+1) mod 10 == 0: '\\n' else: ' '\necho()\n\nvar erdos7875: int\nvar count = 0\nfor p in primeList:\n\tif p.isErdosPrime: inc count\n\tif count == 7875:\n\t\terdos7875 = p\n\t\tbreak\necho \"\\nThe 7875th Erdos prime is $#.\".format(erdos7875)\n" + }, + { + "id": 1348, + "length": 785, + "source": "Rosetta Code", + "text": "import strutils\n\nconst Max = 49\n\nfunc starts(k: int): (int, int) =\n\t## Return the starting values of \"k\".\n\t## The first one is less than Max.\n\t## If the first one is in 1..9, the second one is 0 else it is in 1..9.\n\tvar k = k\n\twhile k > Max: k = k div 10\n\tresult[0] = k\n\tif k < 10: return\n\twhile k > 9: k = k div 10\n\tresult[1] = k\n\nvar squares: array[1..Max, int] # Maps \"n\" to the smallest square beginning with \"n\".\nvar count = Max # Number of squares still to found.\nvar n = 0\n\nwhile count > 0:\n\tinc n\n\tlet n2 = n * n\n\tlet (s1, s2) = n2.starts()\n\tif squares[s1] == 0:\n\t\tsquares[s1] = n2\n\t\tdec count\n\tif s2 != 0 and squares[s2] == 0:\n\t\tsquares[s2] = n2\n\t\tdec count\n\nfor i, n2 in squares:\n\tstdout.write ($n2).align(5)\n\tstdout.write if i mod 7 == 0: '\\n' else: ' '\n" + }, + { + "id": 1349, + "length": 670, + "source": "Rosetta Code", + "text": "import math, strutils\n\nconst\n\tN1 = 499 # Limit for the primes.\n\tN2 = 999 # Limit for the reverses of primes.\n\n# Sieve of Erathosthenes.\nvar composite: array[2..N2, bool] # Default is false.\nfor p in 2..sqrt(N2.toFloat).int:\n\tif not composite[p]:\n\t\tfor k in countup(p * p, N2, p):\n\t\t\tcomposite[k] = true\n\ntemplate isPrime(n: int): bool = not composite[n]\n\nfunc reversed(n: int): int =\n\tvar n = n\n\twhile n != 0:\n\t\tresult = 10 * result + n mod 10\n\t\tn = n div 10\n\nvar result: seq[int]\nfor n in 2..N1:\n\tif n.isPrime and reversed(n).isPrime:\n\t\tresult.add n\n\nfor i, n in result:\n\tstdout.write ($n).align(3)\n\tstdout.write if (i + 1) mod 10 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1350, + "length": 650, + "source": "Rosetta Code", + "text": "import math, strutils\n\nconst N = 499\n\n# Sieve of Erathostenes.\nvar composite: array[2..N, bool] # Initialized to false, ie. prime.\n\nfor n in 2..sqrt(N.toFloat).int:\n\tif not composite[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tcomposite[k] = true\n\n\nfunc digitSum(n: Positive): Natural =\n\t## Compute sum of digits.\n\tvar n = n.int\n\twhile n != 0:\n\t\tresult += n mod 10\n\t\tn = n div 10\n\n\necho \"Additive primes less than 500:\"\nvar count = 0\nfor n in 2..N:\n\tif not composite[n] and not composite[digitSum(n)]:\n\t\tinc count\n\t\tstdout.write ($n).align(3)\n\t\tstdout.write if count mod 10 == 0: '\\n' else: ' '\necho()\n\necho \"\\nNumber of additive primes found: \", count\n" + }, + { + "id": 1351, + "length": 938, + "source": "Rosetta Code", + "text": "import random, sequtils, strutils\n\nproc dnaSequence(n: Positive): string =\n\t## Create a random DNA sequence of length \"n\".\n\tnewSeqWith(n, sample(\"ACGT\")).join()\n\nproc positions(dnaSeq, subSeq: string): seq[int] =\n\t## Return the list of starting positions of a subsequence\n\t## \"subSeq\" in a sequence \"dnaSeq\". Positions start at 1.\n\tvar start = 0\n\twhile true:\n\t\tlet pos = dnaSeq.find(subSeq, start)\n\t\tif pos < 0: break\n\t\tresult.add pos + 1\n\t\tstart = pos + 1\n\n\nwhen isMainModule:\n\n\tconst\n\t\tN = 200\n\t\tStep = 20\n\n\trandomize()\n\n\tlet dnaSeq = dnaSequence(N)\n\techo \"DNA sequence:\"\n\tfor i in countup(0, N - 1, Step):\n\t\techo ($(i+1)).align(3), ' ', dnaSeq[i..i+(Step-1)]\n\n\tlet subSeq = dnaSequence(3)\n\techo \"\\nDNA subsequence: \", subSeq\n\n\techo()\n\tlet pos = dnaSeq.positions(subSeq)\n\tif pos.len == 0:\n\t\techo \"Subsequence not found.\"\n\telse:\n\t\tlet tail = if pos.len == 1: \": \" else: \"s: \"\n\t\techo \"Subsequence found at position\", tail, pos.join(\", \")\n" + }, + { + "id": 1352, + "length": 583, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nfunc isPrime(n: Natural): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nfunc digitSum(n: Natural): int =\n\tvar n = n\n\twhile n != 0:\n\t\tresult += n mod 10\n\t\tn = n div 10\n\nlet result = collect(newSeq):\n\t\t\t\t\t\t\t for n in countup(3, 5000, 2):\n\t\t\t\t\t\t\t\t if digitSum(n) == 25 and n.isPrime: n\n\nfor i, n in result:\n\tstdout.write ($n).align(4), if (i + 1) mod 6 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1353, + "length": 816, + "source": "Rosetta Code", + "text": "import math, strutils, sugar\n\nfunc isPrime(n: Natural): bool =\n\tif n < 2: return false\n\tif n mod 2 == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nconst\n\tMax = 16_000\n\tSquares = collect(newSeq):\n\t\t\t\t\t\t\tfor n in countup(2, sqrt(Max.float).int, 2): n * n\n\niterator quadraPrimes(lim: Positive): int =\n\tassert lim >= 3\n\tyield 2\n\tyield 3\n\tvar n = 3\n\tblock mainloop:\n\t\twhile true:\n\t\t\tfor square in Squares:\n\t\t\t\tlet next = n + square\n\t\t\t\tif next > lim: break mainloop\n\t\t\t\tif next.isPrime:\n\t\t\t\t\tn = next\n\t\t\t\t\tyield n\n\t\t\t\t\tbreak\n\necho \"Quadrat special primes < 16000:\"\nvar count = 0\nfor qp in quadraPrimes(Max):\n\tinc count\n\tstdout.write ($qp).align(5), if count mod 7 == 0: '\\n' else: ' '\n" + }, + { + "id": 1354, + "length": 965, + "source": "Rosetta Code", + "text": "import math, strformat\n\nfunc sieve(limit: Positive): seq[bool] =\n\t# True denotes composite, false denotes prime.\n\tresult = newSeq[bool](limit + 1) # All false by default.\n\tresult[0] = true\n\tresult[1] = true\n\t# No need to bother with even numbers over 2 for this task.\n\tvar p = 3\n\twhile true:\n\t\tlet p2 = p * p\n\t\tif p2 > limit: break\n\t\tfor i in countup(p2, limit, 2 * p):\n\t\t\tresult[i] = true\n\t\twhile true:\n\t\t\tinc p, 2\n\t\t\tif not result[p]: break\n\nfunc isCube(n: int): bool =\n\tlet s = cbrt(n.toFloat).int\n\tresult = s * s * s == n\n\nlet c = sieve(14999)\necho \"Cubic special primes under 15_000:\"\necho \" Prime1 Prime2 Gap Cbrt\"\nvar lastCubicSpecial = 3\nvar count = 1\necho \"{2:7} {3:7} {1:6} {1:4}\"\nfor n in countup(5, 14999, 2):\n\tif c[n]: continue\n\tlet gap = n - lastCubicSpecial\n\tif gap.isCube:\n\t\tlet gapCbrt = cbrt(gap.toFloat).int\n\t\techo \"{lastCubicSpecial:7} {n:7} {gap:6} {gapCbrt:4}\"\n\t\tlastCubicSpecial = n\n\t\tinc count\necho \"\\n{count + 1} such primes found.\"\n" + }, + { + "id": 1355, + "length": 844, + "source": "Rosetta Code", + "text": "import intsets, math, sequtils, strutils\n\nfunc properDivisors(n: int): seq[int] =\n\tresult = @[1]\n\tfor i in 2..sqrt(n.toFloat).int:\n\t\tif n mod i == 0:\n\t\t\tlet j = n div i\n\t\t\tresult.add i\n\t\t\tif i != j: result.add j\n\nfunc allSums(n: Positive): IntSet =\n\tlet divs = n.properDivisors()\n\tvar currSet: IntSet\n\tfor d in divs:\n\t\tcurrSet.assign(result) # Make a copy of the set.\n\t\tfor sum in currSet:\n\t\t\tresult.incl sum + d # Add a new sum to the set.\n\t\tresult.incl d # Add the single value.\n\nfunc isPractical(n: Positive): bool =\n\ttoSeq(1.. prev: return false\n\t\tprev = d\n\t\tn = n div 10\n\tresult = true\n\nlet result = collect(newSeq):\n\t\t\t\t\t\t\t for n in 2..999:\n\t\t\t\t\t\t\t\t if n.isPrime and n.isNonDecreasing: n\n\necho \"Found {result.len} primes:\"\nfor i, n in result:\n\tstdout.write \"{n:3}\", if (i + 1) mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 1357, + "length": 665, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nfunc isOddPrime(n: Positive): bool =\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\niterator oddPrimes(): int =\n\tyield 3\n\tvar n = 5\n\twhile true:\n\t\tif n.isOddPrime: yield n\n\t\tinc n, 2\n\t\tif n.isOddPrime: yield n\n\t\tinc n, 4\n\niterator frobenius(lim: Positive): int =\n\tvar p1 = 2\n\tfor p2 in oddPrimes():\n\t\tlet f = p1 * p2 - p1 - p2\n\t\tif f < lim: yield f\n\t\telse: break\n\t\tp1 = p2\n\nconst N = 10_000\nvar result = toSeq(frobenius(10_000))\necho \"Found $1 Frobenius numbers less than $2:\".format(result.len, N)\necho result.join(\" \")\n" + }, + { + "id": 1358, + "length": 666, + "source": "Rosetta Code", + "text": "import algorithm, strutils, sugar\n\nconst\n\tM = 1000 - 1\n\tN = M div 3 # Minimal value for \"p\" is 3.\n\n# Sieve of Eratosthenes.\nvar composite: array[3..N, bool]\n\nfor n in countup(3, N, 2):\n\tlet n2 = n * n\n\tif n2 > N: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, N, 2 * n):\n\t\t\tcomposite[k] = true\n\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t for n in countup(3, N, 2):\n\t\t\t\t\t\t\t\t if not composite[n]: n\n\nvar result: seq[int]\nfor i in 0.. M: break\n\t\tresult.add p * q\nresult.sort()\n\nfor i, n in result:\n\tstdout.write ($n).align(3), if (i + 1) mod 20 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1359, + "length": 1460, + "source": "Rosetta Code", + "text": "import math, strformat, sugar\n\nconst N = 1_000_000\n\n# Erathostenes sieve.\n\nvar composite: array[2..N, bool] # Initialized to false i.e. prime.\n\nfor n in 2..int(sqrt(float(N))):\n\tif not composite[n]:\n\t\tfor k in countup(n * n, N, n):\n\t\t\tcomposite[k] = true\n\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t for n in 2..N:\n\t\t\t\t\t\t\t\t if not composite[n]: n\n\n\n# Longest sequences.\n\ntype Order {.pure.} = enum Ascending, Descending\n\nproc longestSeq(order: Order): seq[int] =\n\t## Return the longest sequence for the given order.\n\n\tlet ascending = order == Ascending\n\tvar\n\t\tcurrseq: seq[int]\n\t\tprevPrime = 2\n\t\tdiff = if ascending: 0 else: N\n\n\tfor prime in primes:\n\t\tlet nextDiff = prime - prevPrime\n\t\tif nextDiff != diff and nextDiff > diff == ascending:\n\t\t\tcurrseq.add prime\n\t\telse:\n\t\t\tif currseq.len > result.len:\n\t\t\t\tresult = move(currseq)\n\t\t\tcurrseq = @[prevPrime, prime]\n\t\tdiff = nextDiff\n\t\tprevPrime = prime\n\n\tif currseq.len > result.len:\n\t\tresult = move(currseq)\n\n\nproc `$`(list: seq[int]): string =\n\t## Return the representation of a list of primes with interleaved differences.\n\tvar prevPrime: int\n\tfor i, prime in list:\n\t\tif i != 0: result.add \" ({prime - prevPrime}) \"\n\t\tresult.addInt prime\n\t\tprevPrime = prime\n\necho \"For primes < 1000000.\\n\"\necho \"First longest sequence of consecutive primes with ascending differences:\"\necho longestSeq(Ascending)\necho()\necho \"First longest sequence of consecutive primes with descending differences:\"\necho longestSeq(Descending)\n" + }, + { + "id": 1360, + "length": 916, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\ntype\n\tDigit = 0..9\n\tDigitSeq = seq[Digit]\n\n\nfunc isOddPrime(n: Positive): bool =\n\t## Check if \"n\" is an odd prime.\n\tassert n > 10\n\tvar d = 3\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\treturn true\n\n\nfunc toInt(s: DigitSeq): int =\n\t## Convert a sequence of digits to an int.\n\tfor d in s:\n\t\tresult = 10 * result + d\n\n\nvar result = @[2, 3, 5, 7]\nvar list: seq[DigitSeq] = result.mapIt(@[Digit it])\nvar primeTestCount = 0\n\nwhile list.len != 0:\n\tvar newList: seq[DigitSeq]\n\tfor dseq in list:\n\t\tfor d in [Digit 3, 7]:\n\t\t\tif dseq[^1] != d: # New digit must be different of last digit.\n\t\t\t\tinc primeTestCount\n\t\t\t\tlet newDseq = dseq & d\n\t\t\t\tlet candidate = newDseq.toInt\n\t\t\t\tif candidate.isOddPrime:\n\t\t\t\t\tnewList.add newDseq\n\t\t\t\t\tresult.add candidate\n\tlist = move(newList)\n\necho \"List of substring primes: \", result.join(\" \")\necho \"Number of primality tests: \", primeTestCount\n" + }, + { + "id": 1361, + "length": 1338, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, sets, strutils\n\niterator substrings(s: string): string =\n\t## Yield the substrings of the given string.\n\tfor istart in 0..s.high:\n\t\tfor istop in istart..s.high:\n\t\t\tyield s[istart..istop]\n\nfunc isPalindrome(s: string): bool =\n\t## Return true if \"s\" is a palindrome.\n\tresult = true\n\tfor i in 0..(s.high div 2):\n\t\tif s[i] != s[s.high - i]: return false\n\nfunc cmpPal(s1, s2: string): int =\n\t## Compare two palindromes (used for sort).\n\tresult = cmp(s1.len, s2.len)\n\tif result == 0:\n\t\tresult = cmp(s1[0], s2[0])\n\nfunc palindromes(str: string): seq[string] =\n\t## Return the sorted list of palindromes contained in \"str\".\n\tvar palSet: HashSet[string]\n\tfor s in substrings(str):\n\t\tif s.isPalindrome: palSet.incl s\n\tresult = sorted(toSeq(palSet), cmpPal)\n\n\nwhen isMainModule:\n\n\tfor n in 100..125:\n\t\techo n, \": \", palindromes($n).mapIt(it.align(3)).join(\" \")\n\n\techo()\n\tfor s in [\"9\", \"169\", \"12769\", \"1238769\", \"123498769\", \"12346098769\",\n\t\t\t\t\t\t\"1234572098769\", \"123456832098769\", \"12345679432098769\",\n\t\t\t\t\t\t\"1234567905432098769\", \"123456790165432098769\",\n\t\t\t\t\t\t\"83071934127905179083\", \"1320267947849490361205695\"]:\n\t\tlet pals2 = palindromes(s).filterIt(it.len >= 2)\n\t\tlet verb = if pals2.len == 0: \" doesn't contain palindromes \"\n\t\t\t\t\t\t\telse: \" contains at least one palindrome \"\n\t\techo s, verb, \"of two digits or more\"\n" + }, + { + "id": 1362, + "length": 715, + "source": "Rosetta Code", + "text": "import strformat, sugar\n\nconst\n\tMax1 = 499 # Maximum for first prime.\n\tMax2 = 251_000 # Maximum for sieve (in fact 250_999 = 499 * 503 + 2).\n\n# Sieve of Erathosthenes: false (default) is composite.\nvar composite: array[3..Max2, bool] # Ignore 2 as 2 * 3 + 8 is not prime.\nvar n = 3\nwhile true:\n\tlet n2 = n * n\n\tif n2 > Max2: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, Max2, 2 * n):\n\t\t\tcomposite[k] = true\n\tinc n, 2\n\ntemplate isPrime(n: int): bool = not composite[n]\n\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t for n in countup(3, Max2, 2):\n\t\t\t\t\t\t\t\t if n.isPrime: n\n\nvar p = primes[0]\nvar i = 0\nwhile p <= Max1:\n\tinc i\n\tlet q = primes[i]\n\tif (p * q + 2).isPrime:\n\t\techo \"{p:3} {q:3} {p*q+2:6}\"\n\tp = q\n" + }, + { + "id": 1363, + "length": 602, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\tN = 5500 - 1\n\tMax = N + 6\n\n# Sieve of Erathosthenes: false (default) is composite.\nvar composite: array[3..Max, bool] # Ignore 2 as all primes should be odd.\nvar n = 3\nwhile true:\n\tlet n2 = n * n\n\tif n2 > Max: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, Max, 2 * n):\n\t\t\tcomposite[k] = true\n\tinc n, 2\n\ntemplate isPrime(n: int): bool = not composite[n]\n\necho \" p p+2 p+6\"\nvar count = 0\nfor n in countup(3, N, 2):\n\tif n.isPrime and (n + 2).isPrime and (n + 6).isPrime:\n\t\techo \"{n:4} {n+2:4} {n+6:4}\"\n\t\tinc count\n\necho \"\\nFound {count} primes triplets for p < {N+1}.\"\n" + }, + { + "id": 1364, + "length": 1137, + "source": "Rosetta Code", + "text": "import math, strformat\n\nconst\n\tRe = 6371000 # Radius of earth in meters.\n\tDd= 0.001 # Integrate in this fraction of the distance already covered.\n\tFin = 1e7 # Integrate only to a height of 10000km, effectively infinity.\n\n\nfunc rho(a: float): float =\n\t## The density of air as a function of height above sea level.\n\texp(-a / 8500)\n\n\nfunc height(a, z, d: float): float =\n\t## Height as a function of altitude (a), zenith angle (z)\n\t## in degrees and distance along line of sight (d).\n\tlet aa = Re + a\n\tlet hh = sqrt(aa * aa + d * d - 2 * d * aa * cos(degToRad(180-z)))\n\tresult = hh - Re\n\n\nfunc columnDensity(a, z: float): float =\n\t## Integrates density along the line of sight.\n\tvar d = 0.0\n\twhile d < Fin:\n\t\tlet delta = max(Dd, Dd * d) # Adaptive step size to avoid it taking forever.\n\t\tresult += rho(height(a, z, d + 0.5 * delta)) * delta\n\t\td += delta\n\n\nfunc airmass(a, z: float): float =\n\tcolumnDensity(a, z) / columnDensity(a, 0)\n\n\necho \"Angle 0 m 13700 m\"\necho \"------------------------------------\"\nvar z = 0.0\nwhile z <= 90:\n\techo \"{z:2} {airmass(0, z):11.8f} {airmass(13700, z):11.8f}\"\n\tz += 5\n" + }, + { + "id": 1365, + "length": 1085, + "source": "Rosetta Code", + "text": "import complex, math, sequtils, strutils\n\nfunc dft(x: openArray[Complex64]): seq[Complex64] =\n\tlet N = x.len\n\tresult.setLen(N)\n\tfor k in 0.. 0: \"+\" else: \"\"\n\t\tresult.add c.im.formatFloat(ffDecimal, precision = 2) & 'i'\n\n\nwhen isMainModule:\n\n\tlet x = [float 2, 3, 5, 7, 11].mapIt(complex64(it))\n\techo \"Original sequence: \", x.join(\", \")\n\tlet y = dft(x)\n\techo \"Discrete Fourier transform: \", y.join(\", \")\n\techo \"Inverse Discrete Fourier Transform: \", idft(y).join(\", \")\n" + }, + { + "id": 1366, + "length": 624, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\tN = 5999\n\tMax = 6003 # 5998 + 5.\n\n# Sieve of Erathosthenes: false (default) is composite.\nvar composite: array[3..Max, bool] # Ignore 2 as all primes should be odd.\nvar n = 3\nwhile true:\n\tlet n2 = n * n\n\tif n2 > Max: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, Max, 2 * n):\n\t\t\tcomposite[k] = true\n\tinc n, 2\n\ntemplate isPrime(n: int): bool = not composite[n]\n\necho \" n n-1 n+3 n+5\"\nvar count = 0\nfor n in countup(4, N, 2):\n\tif (n - 1).isPrime and (n + 3).isPrime and (n + 5).isPrime:\n\t\techo \"{n:4}: {n-1:4} {n+3:4} {n+5:4}\"\n\t\tinc count\n\necho \"\\nFound {count} triplets for n < {N+1}.\"\n" + }, + { + "id": 1367, + "length": 1642, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strformat, strutils\nimport bignum\n\nlet\n\tTwo = newInt(2)\n\tThree = newInt(3)\n\tFive = newInt(5)\n\n\nproc primeFactorsWheel(n: Int): seq[Int] =\n\tconst Inc = [4, 2, 4, 2, 4, 6, 2, 6]\n\tvar n = n\n\twhile (n mod 2).isZero:\n\t\tresult.add Two\n\t\tn = n div 2\n\twhile (n mod 3).isZero:\n\t\tresult.add Three\n\t\tn = n div 3\n\twhile (n mod 5).isZero:\n\t\tresult.add Five\n\t\tn = n div 5\n\tvar k = 7\n\tvar i = 0\n\twhile k * k <= n:\n\t\tif (n mod k).isZero:\n\t\t\tresult.add newInt(k)\n\t\t\tn = n div k\n\t\telse:\n\t\t\tinc k, Inc[i]\n\t\t\ti = (i + 1) and 7\n\tif n > 1: result.add n\n\n\nfunc pollardRho(n : Int): Int =\n\n\tfunc g(x, y: Int): Int = (x * x + 1) mod y\n\n\tvar x, y = newInt(2)\n\tvar z, d = newInt(1)\n\tvar count = 0\n\twhile true:\n\t\tx = g(x, n)\n\t\ty = g(g(y, n), n)\n\t\td = abs(x - y) mod n\n\t\tz *= d\n\t\tinc count\n\t\tif count == 100:\n\t\t\td = gcd(z, n)\n\t\t\tif d != 1: break\n\t\t\tz = newInt(1)\n\t\t\tcount = 0\n\tif d == n: return newInt(0)\n\tresult = d\n\n\nproc primeFactors(n: Int): seq[Int] =\n\tvar n = n\n\twhile n > 1:\n\t\tif n > 100_000_000:\n\t\t\tlet d = pollardRho(n)\n\t\t\tif not d.isZero:\n\t\t\t\tresult.add primeFactorsWheel(d)\n\t\t\t\tn = n div d\n\t\t\t\tif n.probablyPrime(25) != 0:\n\t\t\t\t\tresult.add n\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tresult.add primeFactorsWheel(n)\n\t\t\t\tbreak\n\t\telse:\n\t\t\tresult.add primeFactorsWheel(n)\n\t\t\tbreak\n\tresult.sort()\n\n\nlet list = toSeq(2..20) & 65\nfor i in list:\n\tif i in [2, 3, 5, 7, 11, 13, 17, 19]:\n\t\techo \"HP{i} = {i}\"\n\t\tcontinue\n\tvar n = 1\n\tvar j = newInt(i)\n\tvar h = @[j]\n\twhile true:\n\t\tj = newInt(primeFactors(j).join())\n\t\th.add j\n\t\tif j.probablyPrime(25) != 0:\n\t\t\tfor k in countdown(n, 1):\n\t\t\t\tstdout.write \"HP{h[n-k]}({k}) = \"\n\t\t\techo h[n]\n\t\t\tbreak\n\t\telse:\n\t\t\tinc n\n" + }, + { + "id": 1368, + "length": 778, + "source": "Rosetta Code", + "text": "import strformat, times\n\nconst\n\tNormDoom = [1: 3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n\tLeapDoom = [1: 4, 1, 7, 2, 4, 6, 4, 1, 5, 3, 7, 5]\n\nproc weekday(year, month, day: int): WeekDay =\n\tlet doom = (2 + 5 * (year mod 4) + 4 * (year mod 100) + 6 * (year mod 400)) mod 7\n\tlet anchor = if year.isLeapYear: LeapDoom[month] else: NormDoom[month]\n\tlet wd = (doom + day - anchor + 7) mod 7\n\tresult = if wd == 0: dSun else: WeekDay(wd - 1)\n\nconst Dates = [\"1800-01-06\", \"1875-03-29\", \"1915-12-07\",\n\t\t\t\t\t\t\t \"1970-12-23\", \"2043-05-14\", \"2077-02-12\", \"2101-04-02\"]\n\nfor date in Dates:\n\tlet dt = date.parse(\"yyyy-MM-dd\")\n\tlet wday = weekday(dt.year, ord(dt.month), dt.monthday)\n\tif wday != dt.weekday:\n\t\techo \"For {date}, expected {dt.weekday}, found {wday}.\"\n\telse:\n\t\techo date, \" -> \", wday\n" + }, + { + "id": 1369, + "length": 1988, + "source": "Rosetta Code", + "text": "import sets, strformat, strutils\n\n\nfunc isOneAway(word1, word2: string): bool =\n\t## Return true if \"word1\" and \"word2\" has only one letter of difference.\n\tfor i in 0..word1.high:\n\t\tif word1[i] != word2[i]:\n\t\t\tif result: return false # More than one letter of difference.\n\t\t\telse: result = true # One letter of difference, for now.\n\nvar words: array[1..22, HashSet[string]] # Set of words sorted by length.\n\nfor word in \"unixdict.txt\".lines:\n\twords[word.len].incl word\n\n\nproc path(start, target: string): seq[string] =\n\t## Return a path from \"start\" to \"target\" or an empty list\n\t## if there is no possible path.\n\tlet lg = start.len\n\tdoAssert target.len == lg, \"Source and destination must have same length.\"\n\tdoAssert start in words[lg], \"Source must exist in the dictionary.\"\n\tdoAssert target in words[lg], \"Destination must exist in the dictionary.\"\n\n\tvar currPaths = @[@[start]] # Current list of paths found.\n\tvar pool = words[lg] # List of possible words to use.\n\n\twhile true:\n\t\tvar newPaths: seq[seq[string]] # Next list of paths.\n\t\tvar added: HashSet[string] # Set of words added during the round.\n\t\tfor candidate in pool:\n\t\t\tfor path in currPaths:\n\t\t\t\tif candidate.isOneAway(path[^1]):\n\t\t\t\t\tlet newPath = path & candidate\n\t\t\t\t\tif candidate == target:\n\t\t\t\t\t\t# Found a path.\n\t\t\t\t\t\treturn newPath\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Not the target. Add a new path.\n\t\t\t\t\t\tnewPaths.add newPath\n\t\t\t\t\t\tadded.incl candidate\n\t\t\t\t\t\tbreak\n\t\tif newPaths.len == 0: break # No path.\n\t\tcurrPaths = move(newPaths) # Update list of paths.\n\t\tpool.excl added # Remove added words from pool.\n\n\nwhen isMainModule:\n\tfor (start, target) in [(\"boy\", \"man\"), (\"girl\", \"lady\"), (\"john\", \"jane\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t(\"child\", \"adult\"), (\"cat\", \"dog\"), (\"lead\", \"gold\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t(\"white\", \"black\"), (\"bubble\", \"tickle\")]:\n\t\tlet path = path(start, target)\n\t\tif path.len == 0:\n\t\t\techo \"No path from {start} to {target}.\"\n\t\telse:\n\t\t\techo path.join(\" -> \")\n" + }, + { + "id": 1370, + "length": 600, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nconst Lim = 99_999\n\ntype Digit = 0..15\n\nfunc digitSet(n: Natural; b: Positive): set[Digit] =\n\t## Return the set of digits of \"n\" written in base \"b\".\n\tassert b <= 16\n\tif n == 0: return {Digit 0}\n\tvar n = n\n\twhile n != 0:\n\t\tresult.incl n mod b\n\t\tn = n div b\n\n# Build the list of numbers.\nlet list = collect(newSeq):\n\t\t\t\t\t\t for n in 0..Lim:\n\t\t\t\t\t\t\t if n.digitSet(10) == n.digitSet(16): n\n\n# Display result.\necho \"Found $1 numbers less than $2:\".format(list.len, insertSep($(Lim + 1)))\nfor i, n in list:\n\tstdout.write ($n).align(5), if (i + 1) mod 10 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1371, + "length": 584, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\ntype Digit = 0..15\n\nfunc toBase(n: Natural; b: Positive): seq[Digit] =\n\tif n == 0: return @[Digit 0]\n\tvar n = n\n\twhile n != 0:\n\t\tresult.add n mod b\n\t\tn = n div b\n\nfunc isPalindromic(s: seq[Digit]): bool =\n\tfor i in 1..(s.len div 2):\n\t\tif s[i-1] != s[^i]: return false\n\tresult = true\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for n in 0..<25_000:\n\t\t\t\t\t\t\t if n.toBase(2).isPalindromic and\n\t\t\t\t\t\t\t\t\tn.toBase(4).isPalindromic and\n\t\t\t\t\t\t\t\t\tn.toBase(16).isPalindromic: n\n\necho \"Found \", list.len, \" numbers which are palindromic in bases 2, 4 and 16:\"\necho list.join(\" \")\n" + }, + { + "id": 1372, + "length": 1719, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils\n\nconst\n\tMaxDepth = 6\n\tMax = 36^MaxDepth - 1 # Max value for MaxDepth digits in base 36.\n\tDigits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\n# Sieve of Erathostenes.\nvar composite: array[1..(Max div 2), bool] # Only odd numbers.\nfor i in 1..composite.high:\n\tlet n = 2 * i + 1\n\tlet n2 = n * n\n\tif n2 > Max: break\n\tif not composite[i]:\n\t\tfor k in countup(n2, Max, 2 * n):\n\t\t\tcomposite[k shr 1] = true\n\ntemplate isPrime(n: int): bool =\n\tif n <= 1: false\n\telif (n and 1) == 0: n == 2\n\telse: not composite[n shr 1]\n\ntype Context = object\n\tindices: seq[int]\n\tmostBases: int\n\tmaxStrings: seq[tuple[indices, bases: seq[int]]]\n\nfunc initContext(depth: int): Context =\n\tresult.indices.setLen(depth)\n\tresult.mostBases = -1\n\n\nproc process(ctx: var Context) =\n\tlet minBase = max(2, max(ctx.indices) + 1)\n\tif 37 - minBase < ctx.mostBases: return\n\n\tvar bases: seq[int]\n\tfor b in minBase..36:\n\t\tvar n = 0\n\t\tfor i in ctx.indices:\n\t\t\tn = n * b + i\n\t\tif n.isPrime: bases.add b\n\n\tvar count = bases.len\n\tif count > ctx.mostBases:\n\t\tctx.mostBases = count\n\t\tctx.maxStrings = @{ctx.indices: bases}\n\telif count == ctx.mostBases:\n\t\tctx.maxStrings.add (ctx.indices, bases)\n\n\nproc nestedFor(ctx: var Context; length, level: int) =\n\tif level == ctx.indices.len:\n\t\tctx.process()\n\telse:\n\t\tctx.indices[level] = if level == 0: 1 else: 0\n\t\twhile ctx.indices[level] < length:\n\t\t\tctx.nestedFor(length, level + 1)\n\t\t\tinc ctx.indices[level]\n\n\nfor depth in 1..MaxDepth:\n\tvar ctx = initContext(depth)\n\tctx.nestedFor(Digits.len, 0)\n\techo depth, \" character strings which are prime in most bases: \", ctx.maxStrings[0].bases.len\n\tfor m in ctx.maxStrings:\n\t\techo m.indices.mapIt(Digits[it]).join(), \" -> \", m[1].join(\" \")\n\techo()\n" + }, + { + "id": 1373, + "length": 573, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nconst\n\tN = 1000 - 1 # Maximum value for prime.\n\tS = N * (N + 1) div 2 # Maximum value for sum.\n\nvar composite: array[2..S, bool]\nfor n in 2..S:\n\tlet n2 = n * n\n\tif n2 > S: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, S, n):\n\t\t\tcomposite[k] = true\n\ntemplate isPrime(n: int): bool = not composite[n]\n\nlet primes = collect(newSeq):\n\t\t\t\t\t\t\t\t for n in 2..N:\n\t\t\t\t\t\t\t\t\t if n.isPrime: n\n\nvar list: seq[int]\nvar sum = 0\nfor p in primes:\n\tsum += p\n\tif sum.isPrime:\n\t\tlist.add p\n\necho \"Found $# primes:\".format(list.len)\necho list.join(\" \")\n" + }, + { + "id": 1374, + "length": 1016, + "source": "Rosetta Code", + "text": "import math, sequtils, strformat, strutils\n\n\nfunc divCount(n: Positive): int =\n\tvar n = n\n\tfor d in 1..n:\n\t\tif d * d > n: break\n\t\tif n mod d == 0:\n\t\t\tinc result\n\t\t\tif n div d != d:\n\t\t\t\tinc result\n\n\nfunc isOddPrime(n: Positive): bool =\n\tif n < 3 or n mod 2 == 0: return false\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d <= sqrt(n.toFloat).int:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\n\niterator numWithOddPrimeDivisorCount(lim: Positive): int =\n\tfor k in 1..sqrt(lim.toFloat).int:\n\t\tlet n = k * k\n\t\tif n.divCount().isOddPrime():\n\t\t\tyield n\n\n\nvar list = toSeq(numWithOddPrimeDivisorCount(1000))\n\necho \"Found {list.len} numbers between 1 and 999 whose number of divisors is an odd prime:\"\necho list.join(\" \")\necho()\n\nlist = toSeq(numWithOddPrimeDivisorCount(100_000))\necho \"Found {list.len} numbers between 1 and 99_999 whose number of divisors is an odd prime:\"\nfor i, n in list:\n\tstdout.write \"{n:5}\", if (i + 1) mod 10 == 0: '\\n' else: ' '\necho()\n" + }, + { + "id": 1375, + "length": 855, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nconst N = 1_000_000 - 1 # Sieve of Erathostenes size.\n\n# Sieve of Erathostenes.\nvar composite: array[2..N, bool]\n\nfor n in countup(3, N, 2): # We ignore the even values.\n\tlet n2 = n * n\n\tif n2 > N: break\n\tif not composite[n]:\n\t\tfor k in countup(n2, N, 2 * n):\n\t\t\tcomposite[k] = true\n\ntemplate isPrime(n: Positive): bool = not composite[n]\n\n\niterator primes123(lim: Positive): int =\n\tvar n = 1001 # First odd value with four digits.\n\twhile n <= lim:\n\t\tif n.isPrime and ($n).find(\"123\") >= 0:\n\t\t\tyield n\n\t\tinc n, 2\n\n\nlet list = toSeq(primes123(100_000 - 1))\necho \"Found \", list.len, \" 123 primes less than 100_000:\"\nfor i, n in list:\n\tstdout.write ($n).align(5), if (i + 1) mod 8 == 0: '\\n' else: ' '\necho '\\n'\n\nvar count = 0\nfor _ in primes123(1_000_000): inc count\necho \"Found \", count, \" 123 primes less than 1_000_000.\"\n" + }, + { + "id": 1376, + "length": 696, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\ntype Pair = (float, float)\n\nfunc `$`(p: Pair): string = \"({p[0]:g}, {p[1]:g})\"\n\nfunc maxdiff(list: openArray[float]): tuple[diff: float; list: seq[Pair]] =\n\tassert list.len >= 2\n\tresult = (diff: -1.0, list: @[])\n\tvar prev = list[0]\n\tfor n in list[1..^1]:\n\t\tlet d = abs(n - prev)\n\t\tif d > result.diff:\n\t\t\tresult.diff = d\n\t\t\tresult.list = @[(prev, n)]\n\t\telif d == result.diff:\n\t\t\tresult.list.add (prev, n)\n\t\tprev = n\n\nlet list = [float 1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]\nlet (diff, pairs) = list.maxdiff()\n\necho \"The maximum difference between adjacent pairs of the list is: {diff:g}\"\necho \"The pairs with this difference are: \", pairs.join(\" \")\n" + }, + { + "id": 1377, + "length": 680, + "source": "Rosetta Code", + "text": "import strformat\n\nfunc isPrime(n: Positive): bool =\n\tfor d in countup(3, n, 2):\n\t\tif d * d > n: break\n\t\tif n mod d == 0: return false\n\tresult = true\n\n\niterator primes3x3(lim: Natural): int =\n\tassert lim >= 3\n\tyield 3\n\tvar m = 100\n\twhile m * 3 < lim:\n\t\tfor n in countup(3 * m + 3, 4 * m - 7, 10):\n\t\t\tif n > lim: break\n\t\t\tif n.isPrime: yield n\n\t\tm *= 10\n\nvar list: seq[int]\nvar count = 0\nfor n in primes3x3(1_000_000):\n\tinc count\n\tif n < 4000: list.add n\n\necho \"Found {list.len} primes starting and ending with 3 below 4_000:\"\nfor i, n in list:\n\tstdout.write \"{n:4}\", if (i + 1) mod 11 == 0: '\\n' else: ' '\n\necho \"\\nFound {count} primes starting and ending with 3 below 1_000_000.\"\n" + }, + { + "id": 1378, + "length": 793, + "source": "Rosetta Code", + "text": "import strutils\n\nconst\n\tVowels = {'a', 'e', 'i', 'o', 'u'}\n\tConsonants = {'a'..'z'} - Vowels\n\nfunc value(val: int; unit: string): string =\n\t$val & ' ' & unit & (if val > 1: \"s\" else: \"\")\n\nproc vcCount(text: string) =\n\tvar vowels, consonants: set[char]\n\tvar vowelCount, consonantCount = 0\n\tfor c in text.toLowerAscii:\n\t\tif c in Consonants:\n\t\t\tconsonants.incl c\n\t\t\tinc consonantCount\n\t\telif c in Vowels:\n\t\t\tvowels.incl c\n\t\t\tinc vowelCount\n\techo \"$# contains\" % text\n\techo \" $1 and $2 (distinct)\".format(value(vowels.card, \"vowel\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t value(consonants.card, \"consonant\"))\n\techo \" $1 and $2 (total)\".format(value(vowelCount, \"vowel\"),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalue(consonantCount, \"consonant\"))\n\nvcCount(\"Now is the time for all good men to come to the aid of their country.\")\n" + }, + { + "id": 1379, + "length": 881, + "source": "Rosetta Code", + "text": "import sequtils, strutils\n\nfunc isPrime(n: Positive): bool =\n\tif n == 1: return false\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0:\n\t\t\treturn false\n\t\tinc d, 2\n\t\tif n mod d == 0:\n\t\t\treturn false\n\t\tinc d, 4\n\tresult = true\n\nfunc hasLastDigitOdd(n: Natural): bool =\n\tvar n = n\n\tn = n div 10\n\twhile n != 0:\n\t\tif (n mod 10 and 1) != 0: return false\n\t\tn = n div 10\n\tresult = true\n\niterator primesOneOdd(lim: Positive): int =\n\tvar n = 1\n\twhile n <= lim:\n\t\tif n.hasLastDigitOdd and n.isPrime:\n\t\t\tyield n\n\t\tinc n, 2\n\n\nlet list = toSeq(primesOneOdd(1000))\necho \"Found $# primes with only one odd digit below 1000:\".format(list.len)\nfor i, n in list:\n\tstdout.write ($n).align(3), if (i + 1) mod 9 == 0: '\\n' else: ' '\n\nvar count = 0\nfor _ in primesOneOdd(1_000_000):\n\tinc count\necho \"\\nFound $# primes with only one odd digit below 1_000_000.\".format(count)\n" + }, + { + "id": 1380, + "length": 628, + "source": "Rosetta Code", + "text": "import strformat, strutils\nimport bignum\n\nconst Limit = 11_000\n\n# Build list of primes using \"nextPrime\" function from \"bignum\".\nvar primes: seq[int]\nvar p = newInt(2)\nwhile p < Limit:\n\tprimes.add p.toInt\n\tp = p.nextPrime()\n\n# Build list of factorials.\nvar facts: array[Limit, Int]\nfacts[0] = newInt(1)\nfor i in 1..= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii\n\n\nproc loadWebDictionary(url: string): Dictionary =\n\t## Return appropriate words from a dictionary web page.\n\tlet client = newHttpClient()\n\tfor word in client.getContent(url).splitLines():\n\t\tif word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii\n\n\nproc getPlayers(): seq[string] =\n\t## Return inputted ordered list of contestant names.\n\ttry:\n\t\tstdout.write \"Space separated list of contestants: \"\n\t\tstdout.flushFile()\n\t\tresult = stdin.readLine().splitWhitespace().map(capitalize)\n\t\tif result.len == 0:\n\t\t\tquit \"Empty list of names. Quitting.\", QuitFailure\n\texcept EOFError:\n\t\techo()\n\t\tquit \"Encountered end of file. Quitting.\", QuitFailure\n\n\nproc isWordiffRemoval(word, prev: string; comment = true): bool =\n\t## Is \"word\" derived from \"prev\" by removing one letter?\n\tfor i in 0..prev.high:\n\t\tif word == prev[0.. wordiffs[^1].len: word.isWordiffInsertion(wordiffs[^1], comment)\n\t\t\t\t\t else: word.isWordiffChange(wordiffs[^1], comment)\n\n\nproc couldHaveGot(wordiffs: seq[string]; dict: Dictionary): seq[string] =\n\tfor word in dict - wordiffs.toHashSet:\n\t\tif word.isWordiff(wordiffs, dict, comment = false):\n\t\t\tresult.add word\n\n\nwhen isMainModule:\n\timport random\n\n\trandomize()\n\tlet dict = loadDictionary(DictFname)\n\tlet dict34 = collect(newSeq):\n\t\t\t\t\t\t\t\t for word in dict:\n\t\t\t\t\t\t\t\t\t if word.len in [3, 4]: word\n\tlet start = sample(dict34)\n\tvar wordiffs = @[start]\n\tlet players = getPlayers()\n\tvar iplayer = 0\n\tvar word: string\n\twhile true:\n\t\tlet name = players[iplayer]\n\t\twhile true:\n\t\t\tstdout.write \"$1, input a wordiff from $2: \".format(name, wordiffs[^1])\n\t\t\tstdout.flushFile()\n\t\t\ttry:\n\t\t\t\tword = stdin.readLine().strip()\n\t\t\t\tif word.len > 0: break\n\t\t\texcept EOFError:\n\t\t\t\tquit \"Encountered end of file. Quitting.\", QuitFailure\n\t\tif word.isWordiff(wordiffs, dict):\n\t\t\twordiffs.add word\n\t\telse:\n\t\t\techo \"You have lost, $#.\".format(name)\n\t\t\tlet possibleWords = couldHaveGot(wordiffs, dict)\n\t\t\tif possibleWords.len > 0:\n\t\t\t\techo \"You could have used: \", possibleWords[0..min(possibleWords.high, 20)].join(\" \")\n\t\t\tbreak\n\t\tiplayer = (iplayer + 1) mod players.len\n" + }, + { + "id": 1383, + "length": 755, + "source": "Rosetta Code", + "text": "import algorithm, sequtils, strutils\nimport bignum\n\nconst\n\tN = 50 # Number of fortunate numbers.\n\tLim = 75 # Number of primorials to compute.\n\n\niterator primorials(lim: Positive): Int =\n\tvar prime = newInt(2)\n\tvar primorial = newInt(1)\n\tfor _ in 1..lim:\n\t\tprimorial *= prime\n\t\tprime = prime.nextPrime()\n\t\tyield primorial\n\n\nvar list: seq[int]\nfor p in primorials(Lim):\n\tvar m = 3\n\twhile true:\n\t\tif probablyPrime(p + m, 25) != 0:\n\t\t\tlist.add m\n\t\t\tbreak\n\t\tinc m, 2\n\nlist.sort()\nlist = list.deduplicate(true)\nif list.len < N:\n\tquit \"Not enough values. Wanted $1, got $2.\".format(N, list.len), QuitFailure\nlist.setLen(N)\necho \"First $# fortunate numbers:\".format(N)\nfor i, m in list:\n\tstdout.write ($m).align(3), if (i + 1) mod 10 == 0: '\\n' else: ' '\n" + }, + { + "id": 1384, + "length": 827, + "source": "Rosetta Code", + "text": "import math, strutils, sugar, tables\n\nconst\n\tN = 1_000_000_000\n\tS = sqrt(N.toFloat).int\n\nvar composite: array[3..S, bool]\nfor n in countup(3, S, 2):\n\tif n * n > S: break\n\tif not composite[n]:\n\t\tfor k in countup(n * n, S, 2 * n):\n\t\t\tcomposite[k] = true\n\n# Prime list. Add a dummy zero to start at index 1.\nlet primes = @[0, 2] & collect(newSeq, for n in countup(3, S, 2): (if not composite[n]: n))\n\nvar cache: Table[(Natural, Natural), Natural]\n\nproc phi(x, a: Natural): Natural =\n\tif a == 0: return x\n\tlet pair = (x, a)\n\tif pair in cache: return cache[pair]\n\tresult = phi(x, a - 1) - phi(x div primes[a], a - 1)\n\tcache[pair] = result\n\nproc pi(n: Natural): Natural =\n\tif n <= 2: return 0\n\tlet a = pi(sqrt(n.toFloat).Natural)\n\tresult = phi(n, a) + a - 1\n\nvar n = 1\nfor i in 0..9:\n\techo \"pi(10^$1) = $2\".format(i, pi(n))\n\tn *= 10\n" + }, + { + "id": 1385, + "length": 1692, + "source": "Rosetta Code", + "text": "# compile with: nim c -d:danger -t:-march=native --gc:arc\n\nfrom std/monotimes import getMonoTime, `-`\nfrom std/times import inMilliseconds\nfrom std/math import sqrt\n\nlet masks = [ 1'u8, 2, 4, 8, 16, 32, 64, 128 ] # faster than bit twiddling\nlet masksp = cast[ptr[UncheckedArray[byte]]](unsafeAddr(masks[0]))\n\nproc countPrimes(n: int64): int64 =\n\tif n < 3:\n\t\treturn if n < 2: 0 else: 1\n\telse:\n\t\tlet rtlmt = n.float64.sqrt.int\n\t\tlet mxndx = (rtlmt - 1) div 2\n\t\tlet sz = (mxndx + 8) div 8\n\t\tvar cmpsts = cast[ptr[UncheckedArray[byte]]](alloc0(sz))\n\t\tfor i in 1 .. mxndx:\n\t\t\tif (cmpsts[i shr 3] and masksp[i and 7]) != 0: continue\n\t\t\tlet sqri = (i + i) * (i + 1)\n\t\t\tif sqri > mxndx: break\n\t\t\tlet bp = i + i + 1\n\t\t\tfor c in countup(sqri, mxndx, bp):\n\t\t\t\tlet w = c shr 3; cmpsts[w] = cmpsts[w] or masksp[c and 7]\n\t\tvar pisqrt = 0'i64\n\t\tfor i in 0 .. mxndx:\n\t\t\tif (cmpsts[i shr 3] and masksp[i and 7]) == 0: pisqrt += 1\n\t\tvar primes = cast[ptr[UncheckedArray[uint32]]](alloc(sizeof(uint32) * pisqrt.int))\n\t\tvar j = 0\n\t\tfor i in 0 .. mxndx:\n\t\t\tif (cmpsts[i shr 3] and masksp[i and 7]) == 0: primes[j] = (i + i + 1).uint32; j += 1\n\t\tproc phi(x: int64; a: int): int64 =\n\t\t\tif a <= 1:\n\t\t\t\treturn if a < 1: x else: x - (x shr 1)\n\t\t\tlet p = primes[a - 1].int64\n\t\t\tif x <= p: return 1 # very simple one-line optimization that limits exponential growth!\n\t\t\treturn phi(x, a - 1) - phi((x.float64 / p.float64).int64, a - 1)\n\t\tresult = phi(n, pisqrt.int) + pisqrt - 1\n\t\tcmpsts.dealloc; primes.dealloc\n\nlet nstrt = getMonoTime()\nvar pow = 1'i64\nfor i in 0 .. 9: echo \"pi(10^\", i, \") = \", pow.countPrimes; pow *= 10\nlet nelpsd = (getMonoTime() - nstrt).inMilliseconds\necho \"This took \", nelpsd, \" milliseconds.\"\n" + }, + { + "id": 1386, + "length": 2700, + "source": "Rosetta Code", + "text": "# compile with: nim c -d:danger -t:-march=native --gc:arc\n\nfrom std/monotimes import getMonoTime, `-`\nfrom std/times import inMilliseconds\nfrom std/math import sqrt\n\nlet masks = [ 1'u8, 2, 4, 8, 16, 32, 64, 128 ] # faster than bit twiddling\nlet masksp = cast[ptr[UncheckedArray[byte]]](unsafeAddr(masks[0]))\n\nconst TinyPhiPrimes = [2, 3, 5, 7, 11, 13]\nconst TinyPhiCirc = 3 * 5 * 7 * 11 * 13\nconst TinyPhiRes = 2 * 4 * 6 * 10 * 12\nconst CC = 6\nproc makeTinyPhiLUT(): array[TinyPhiCirc, uint16] =\n\tfor i in 0 .. TinyPhiCirc - 1: result[i] = 1\n\tfor i in 1 .. 6:\n\t\tif result[i] == 0: continue\n\t\tresult[i] = 0; let bp = i + i + 1\n\t\tlet sqri = (i + i) * (i + 1)\n\t\tfor c in countup(sqri, TinyPhiCirc - 1, bp): result[c] = 0\n\tvar acc = 0'u16;\n\tfor i in 0 .. TinyPhiCirc - 1: acc += result[i]; result[i] = acc\nconst TinyPhiLUT = makeTinyPhiLUT()\nproc tinyPhi(x: int64): int64 {.inline.} =\n\tlet ndx = (x - 1) div 2; let numtot = ndx div TinyPhiCirc.int64\n\treturn numtot * TinyPhiRes.int64 + TinyPhiLUT[(ndx - numtot * TinyPhiCirc.int64).int].int64\n\nproc countPrimes(n: int64): int64 =\n\tif n < 169: # below 169 whose sqrt is 13 is where TinyPhi doesn't work...\n\t\tif n < 3: return if n < 2: 0 else: 1\n\t\t# adjust for the missing \"degree\" base primes\n\t\tif n <= 13: return (n - 1) div 2 + (if n < 9: 1 else: 0)\n\t\treturn 5 + TinyPhiLUT[(n - 1).int div 2].int64\n\tlet rtlmt = n.float64.sqrt.int\n\tlet mxndx = (rtlmt - 1) div 2\n\tvar cmpsts = cast[ptr[UncheckedArray[byte]]](alloc0((mxndx + 8) div 8))\n\tfor i in 1 .. mxndx:\n\t\tif (cmpsts[i shr 3] and masksp[i and 7]) != 0: continue\n\t\tlet sqri = (i + i) * (i + 1)\n\t\tif sqri > mxndx: break\n\t\tlet bp = i + i + 1\n\t\tfor c in countup(sqri, mxndx, bp):\n\t\t\tlet w = c shr 3; cmpsts[w] = cmpsts[w] or masksp[c and 7]\n\tvar pisqrt = 0'i64\n\tfor i in 0 .. mxndx:\n\t\tif (cmpsts[i shr 3] and masksp[i and 7]) == 0: pisqrt += 1\n\tlet primes = cast[ptr[UncheckedArray[uint32]]](alloc(sizeof(uint32) * pisqrt.int))\n\tvar j = 0\n\tfor i in 0 .. mxndx:\n\t\tif (cmpsts[i shr 3] and masksp[i and 7]) == 0: primes[j] = (i + i + 1).uint32; j += 1\n\tvar phi = tinyPhi(n)\n\tproc lvl(m, mbf: int64; mxa: int) = # recurse from bottom left of \"tree\"...\n\t\tfor a in CC .. mxa:\n\t\t\tlet p = primes[a].int64\n\t\t\tif m < p * p: phi += mbf * (mxa - a + 1).int64; return # rest of level all ones!\n\t\t\tlet nm = (m.float64 / p.float64).int64; phi += mbf * tinyPhi(nm)\n\t\t\tif a > CC: lvl(nm, -mbf, a - 1) # split\n\t\t# finished level!\n\tlvl(n, -1, pisqrt.int - 1); result = phi + pisqrt - 1\n\tcmpsts.dealloc; primes.dealloc\n\nlet strt = getMonoTime()\nvar pow = 1'i64\nfor i in 0 .. 9: echo \"pi(10^\", i, \") = \", pow.countPrimes; pow *= 10\nlet elpsd = (getMonoTime() - strt).inMilliseconds\necho \"This took \", elpsd, \" milliseconds.\"\n" + }, + { + "id": 1387, + "length": 7044, + "source": "Rosetta Code", + "text": "# compile with: nim c -d:danger -t:-march=native --gc:arc\n\nfrom std/monotimes import getMonoTime, `-`\nfrom std/times import inMilliseconds\nfrom std/math import sqrt\n\nlet masks = [ 1'u8, 2, 4, 8, 16, 32, 64, 128 ] # faster than bit twiddling\nlet masksp = cast[ptr[UncheckedArray[byte]]](unsafeAddr(masks[0]))\n\n# non-recursive Legendre prime counting function for a range `n`...\n# this has O(n^(3/4)/((log n)^2)) time complexity; O(n^(1/2)) space complexity.\nproc countPrimes(n: int64): int64 =\n\tif n < 3: # can't odd sieve for value less than 3!\n\t\treturn if n < 2: 0 else: 1\n\telse:\n\t\tproc half(n: int): int {.inline.} = (n - 1) shr 1 # convenience conversion to index\n\t\t# dividing using float64 is faster than int64 for some CPU's...\n\t\t# precision limits range to maybe 1e16!\n\t\tproc divide(nm, d: int64): int {.inline.} = (nm.float64 / d.float64).int\n\t\tlet rtlmt = n.float64.sqrt.int # precision limits range to maybe 1e16!\n\t\tlet mxndx = (rtlmt - 1) div 2\n\t\tvar smalls = # current accumulated counts of odd primes 1 to sqrt range\n\t\t\tcast[ptr[UncheckedArray[uint32]]](alloc(sizeof(uint32) * (mxndx + 1)))\n\t\t# initialized for no sieving whatsoever other than odds-only - partial sieved by 2:\n\t\t# 0 odd primes to 1; 1 odd prime to 3, etc....\n\t\tfor i in 0 .. mxndx: smalls[i] = i.uint32\n\t\tvar roughs = # current odd k-rough numbers up to sqrt of range; k = 2\n\t\t\tcast[ptr[UncheckedArray[uint32]]](alloc(sizeof(uint32) * (mxndx + 1)))\n\t\t# initialized to all odd positive numbers 1, 3, 5, ... sqrt range...\n\t\tfor i in 0 .. mxndx: roughs[i] = (i + i + 1).uint32\n\t\t# array of current phi counts for above roughs...\n\t\t# these are not strictly `phi`'s since they also include the\n\t\t# count of base primes in order to match the above `smalls` definition!\n\t\tvar larges = # starts as size of counts just as `roughs` so they align!\n\t\t\tcast[ptr[UncheckedArray[int64]]](alloc(sizeof(int64) * (mxndx + 1)))\n\t\t# initialized for current roughs after accounting for even prime of two...\n\t\tfor i in 0 .. mxndx: larges[i] = ((n div (i + i + 1) - 1) div 2).int64\n\t\t# cmpsts is a bit-packed boolean array representing\n\t\t# odd composite numbers from 1 up to rtlmt used for sieving...\n\t\t# initialized as \"zeros\" meaning all odd positives are potentially prime\n\t\t# note that this array starts at (and keeps) 1 to match the algorithm even\n\t\t# though 1 is not a prime, as 1 is important in computation of phi...\n\t\tvar cmpsts = cast[ptr[UncheckedArray[byte]]](alloc0((mxndx + 8) div 8))\n\n\t\t# number of found base primes and current highest used rough index...\n\t\tvar npc = 0; var mxri = mxndx\n\t\tfor i in 1 .. mxndx: # start at index for 3; i will never reach mxndx...\n\t\t\tlet sqri = (i + i) * (i + 1) # computation of square index!\n\t\t\tif sqri > mxndx: break # stop partial sieving due to square index limit!\n\t\t\tif (cmpsts[i shr 3] and masksp[i and 7]) != 0'u8: continue # if not prime\n\t\t\t# culling the base prime from cmpsts means it will never be found again\n\t\t\tcmpsts[i shr 3] = cmpsts[i shr 3] or masksp[i and 7] # cull base prime\n\t\t\tlet bp = i + i + 1 # base prime from index!\n\t\t\tfor c in countup(sqri, mxndx, bp): # SoE culling of all bp multiples...\n\t\t\t\tlet w = c shr 3; cmpsts[w] = cmpsts[w] or masksp[c and 7]\n\t\t\t# partial sieving to current base prime is now completed!\n\n\t\t\tvar ri = 0 # to keep track of current used roughs index!\n\t\t\tfor k in 0 .. mxri: # processing over current roughs size...\n\t\t\t\t# q is not necessarily a prime but may be a\n\t\t\t\t# product of primes not yet culled by partial sieving;\n\t\t\t\t# this is what saves operations compared to recursive Legendre:\n\t\t\t\tlet q = roughs[k].int; let qi = q shr 1 # index of always odd q!\n\t\t\t\t# skip over values of `q` already culled in the last partial sieve:\n\t\t\t\tif (cmpsts[qi shr 3] and masksp[qi and 7]) != 0'u8: continue\n\t\t\t\t# since `q` cannot be equal to bp due to cull of bp and above skip;\n\t\t\t\tlet d = bp * q # `d` is odd product of some combination of odd primes!\n\t\t\t\t# the following computation is essential to the algorithm's speed:\n\t\t\t\t# see above description in the text for how this works:\n\t\t\t\tlarges[ri] = larges[k] -\n\t\t\t\t\t\t\t\t\t\t (if d <= rtlmt: larges[smalls[d shr 1].int - npc]\n\t\t\t\t\t\t\t\t\t\t\telse: smalls[half(divide(n, d.int64))].int64) + npc.int64\n\t\t\t\t# eliminate rough values that have been culled in partial sieve:\n\t\t\t\t# note that `larges` and `roughs` indices relate to each other!\n\t\t\t\troughs[ri] = q.uint32; ri += 1 # update rough value; advance rough index\n\n\t\t\tvar m = mxndx # adjust `smalls` counts for the newly culled odds...\n\t\t\t# this is faster than recounting over the `cmpsts` array for each loop...\n\t\t\tfor k in countdown(((rtlmt div bp) - 1) or 1, bp, 2): # k always odd!\n\t\t\t\t# `c` is correction from current count to desired count...\n\t\t\t\t# `e` is end limit index no correction is necessary for current cull...\n\t\t\t\tlet c = smalls[k shr 1] - npc.uint32; let e = (k * bp) shr 1\n\t\t\t\twhile m >= e: smalls[m] -= c; m -= 1 # correct over range down to `e`\n\t\t\tmxri = ri - 1; npc += 1 # set next loop max roughs index; count base prime\n\t\t# now `smalls` is a LUT of odd prime accumulated counts for all odd primes;\n\t\t# `roughs` is exactly the \"k-roughs\" up to the sqrt of range with `k` the\n\t\t# index of the next prime above the quad root of the range;\n\t\t# `larges` is the partial prime counts for each of the `roughs` values...\n\t\t# note that `larges` values include the count of the odd base primes!!!\n\t\t# `cmpsts` are never used again!\n\n\t\t# the following does the top most \"phi tree\" calculation:\n\t\tresult = larges[0] # the answer to here is all valid `phis`\n\t\tfor i in 1 .. mxri: result -= larges[i] # combined here by subtraction\n\t\t# compensate for the included odd base prime counts over subracted above:\n\t\tresult += ((mxri + 1 + 2 * (npc - 1)) * mxri div 2).int64\n\n\t\t# This loop adds the counts due to the products of the `roughs` primes,\n\t\t# of which we only use two different ones at a time, as all the\n\t\t# combinations with lower primes than the cube root of the range have\n\t\t# already been computed and included with the previous major loop...\n\t\t# see text description above for how this works...\n\t\tfor j in 1 .. mxri: # for all `roughs` (now prime) not including one:\n\t\t\tlet p = roughs[j].int64; let m = n div p # `m` is the `p` quotient\n\t\t\t# so that the end limit `e` can be calculated based on `n`/(`p`^2)\n\t\t\tlet e = smalls[half((m div p).int)].int - npc\n\t\t\t# following break test equivalent to non-memoization/non-splitting optmization:\n\t\t\tif e <= j: break # stop at about `p` of cube root of range!\n\t\t\tfor k in j + 1 .. e: # for all `roughs` greater than `p` to end limit:\n\t\t\t\t result += smalls[half(divide(m, roughs[k].int64))].int64\n\t\t\t# compensate for all the extra base prime counts just added!\n\t\t\tresult -= ((e - j) * (npc + j - 1)).int64\n\n\t\tresult += 1 # include the count for the only even prime of two\n\t\tsmalls.dealloc; roughs.dealloc; larges.dealloc; cmpsts.dealloc\n\nlet strt = getMonoTime()\nvar pow = 1'i64\nfor i in 0 .. 9: echo \"pi(10^\", i, \") = \", pow.countPrimes; pow *= 10\nlet elpsd = (getMonoTime() - strt).inMilliseconds\necho \"This took \", elpsd, \" milliseconds.\"\n" + }, + { + "id": 1388, + "length": 583, + "source": "Rosetta Code", + "text": "import strutils, sugar\n\nconst Max = 100 - 1\n\nfunc isPrime(n: Positive): bool =\n\tif n == 1: return false\n\tif n mod 2 == 0: return n == 2\n\tfor d in countup(3, n, 2):\n\t\tif d * d > n: break\n\t\tif n mod d == 0: return false\n\tresult = true\n\nconst Primes = collect(newSeq):\n\t\t\t\t\t\t\t\t for n in 2..Max:\n\t\t\t\t\t\t\t\t\t if n.isPrime: n\n\nlet list = collect(newSeq):\n\t\t\t\t\t\t for i in 0.. 4:\n\t\t\tfor k in countup(n + step, N, step):\n\t\t\t\tif mark[k] == None: mark[k] = Mark2\n\t\t\tinc step, 2\n\tof Mark2:\n\t\t# Ignore this number.\n\t\tdiscard\n\n\necho \"First 100 Sundaram primes:\"\nfor i, n in list100:\n\tstdout.write ($n).align(3), if (i + 1) mod 10 == 0: '\\n' else: ' '\necho()\nif last == 0:\n\tquit \"Not enough values in sieve. Found only $#.\".format(count), QuitFailure\necho \"The millionth Sundaram prime is \", ($last).insertSep()\n" + }, + { + "id": 1390, + "length": 651, + "source": "Rosetta Code", + "text": "import strformat, strutils\n\nfunc isPrime(n: Positive): bool =\n\tif n == 1: return false\n\tif (n and 1) == 0: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\nfunc motzkin(n: Positive): seq[int64] =\n\tresult.setLen(n + 1)\n\tresult[0] = 1\n\tresult[1] = 1\n\tfor i in 2..n:\n\t\tresult[i] = (result[i-1] * (2 * i + 1) + result[i-2] * (3 * i - 3)) div (i + 2)\n\necho \" n M[n] Prime?\"\necho \"-----------------------------------\"\nvar m = motzkin(41)\nfor i, val in m:\n\techo \"{i:2} {insertSep($val):>23} {val.isPrime}\"\n" + }, + { + "id": 1391, + "length": 1743, + "source": "Rosetta Code", + "text": "import algorithm, math, strformat, strutils\n\n# Ratings on past form, assuming a rating of 100 for horse A.\nvar\n\ta = 100.0\n\tb = a - 8 - 2 * 2 # carried 8 lbs less, finished 2 lengths behind.\n\tc = a + 4 - 2 * 3.5\n\td = a - 4 - 10 * 0.4 # based on relative weight and time.\n\te = d + 7 - 2 * 1\n\tf = d + 11 - 2 * (4 - 2)\n\tg = a - 10 + 10 * 0.2\n\th = g + 6 - 2 * 1.5\n\ti = g + 15 - 2 * 2\n\n# Adjustments to ratings for current race.\nb += 4\nc -= 4\nh += 3\nvar j = a - 3 + 10 * 0.2\n\n# Filly's allowance to give weight adjusted weighting.\nb += 3\nd += 3\ni += 3\nj += 3\n\n# Create table mapping horse to its weight adjusted rating and whether colt.\ntype Pair = tuple[key: char; value: tuple[rating: float; colt: bool]]\nlet list: array[10, Pair] = {'A': (a, true), 'B': (b, false),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'C': (c, true), 'D': (d, false),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'E': (e, true), 'F': (f, true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'G': (g, true), 'H': (h, true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'I': (i, false), 'J': (j, false)}\n\n# Sort in descending order of rating.\nlet slist = list.sortedByIt(-it.value.rating)\n\n# Show expected result of race.\necho \"Race 4\\n\"\necho \"Pos Horse Weight Dist Sex\"\nvar pos = \"\"\nfor i, (key, value) in slist:\n\tlet wt = if value.colt: \"9.00\" else: \"8.11\"\n\tvar dist = 0.0\n\tif i > 0: dist = (slist[i-1].value.rating - value.rating) * 0.5\n\tpos = if i == 0 or dist > 0: $(i + 1)\n\t\t\t\telif not pos.endsWith(\"=\"): $i & '='\n\t\t\t\telse: pos\n\tlet sx = if value.colt: \"colt\" else: \"filly\"\n\techo \"{pos:<2} {key} {wt} {dist:3.1f} {sx}\"\n\n# Weight adjusted rating of winner.\nlet wr = slist[0].value.rating\n\n# Expected time of winner (relative to A's time in Race 1).\nlet t = 96 - (wr - 100) / 10\nvar min = int(t / 60)\nvar sec = t mod 60\necho \"\\nTime {min} minute {sec:.1f} seconds\"\n" + }, + { + "id": 1392, + "length": 2738, + "source": "Rosetta Code", + "text": "import algorithm, random, sequtils, strutils, sugar, tables\n\nconst Adfgvx = \"ADFGVX\"\n\ntype PolybiusSquare = array[6, array[6, char]]\n\n\niterator items(p: PolybiusSquare): (int, int, char) =\n\t## Yield Polybius square characters preceded by row and column numbers.\n\tfor r in 0..5:\n\t\tfor c in 0..5:\n\t\t\tyield (r, c, p[r][c])\n\n\nproc initPolybiusSquare(): PolybiusSquare =\n\t## Initialize a 6x6 Polybius square.\n\tvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\talphabet.shuffle()\n\tfor r in 0..5:\n\t\tfor c in 0..5:\n\t\t\tresult[r][c] = alphabet[6 * r + c]\n\n\nproc createKey(n: Positive): string =\n\t## Create a key using a word from \"unixdict.txt\".\n\tdoAssert n in 7..12, \"Key should be within 7 and 12 letters long.\"\n\tlet candidates = collect(newSeq):\n\t\t\t\t\t\t\t\t\t for word in \"unixdict.txt\".lines:\n\t\t\t\t\t\t\t\t\t\t if word.len == n and\n\t\t\t\t\t\t\t\t\t\t\t\tword.deduplicate().len == n and\n\t\t\t\t\t\t\t\t\t\t\t\tword.allCharsInSet(Letters + Digits): word\n\tresult = candidates[rand(candidates.high)].toUpperAscii\n\n\nfunc encrypt(plainText: string; polybius: PolybiusSquare; key: string): string =\n\t## Encrypt \"plaintext\" using the given Polybius square and the given key.\n\n\t# Replace characters by row+column letters.\n\tvar str: string\n\tfor ch in plainText:\n\t\tfor (r, c, val) in polybius:\n\t\t\tif val == ch:\n\t\t\t\tstr.add Adfgvx[r] & Adfgvx[c]\n\n\t# Build ordered table of columns and sort it by key value.\n\tvar cols: OrderedTable[char, string]\n\tfor i, ch in str:\n\t\tlet tkey = key[i mod key.len]\n\t\tcols.mgetOrPut(tkey, \"\").add ch\n\tcols.sort(cmp)\n\n\t# Build cipher text from sorted column table values.\n\tfor s in cols.values:\n\t\tresult.addSep(\" \")\n\t\tresult.add s\n\n\nfunc decrypt(cipherText: string; polybius: PolybiusSquare; key: string): string =\n\t## Decrypt \"cipherText\" using the given Polybius square and the given key.\n\n\t# Build list of columns.\n\tlet skey = sorted(key)\n\tvar cols = newSeq[string](key.len)\n\tvar idx = 0\n\tfor col in cipherText.split(' '):\n\t\tcols[key.find(skey[idx])] = col\n\t\tinc idx\n\n\t# Build string of row+column values.\n\tvar str: string\n\tfor i in 0..key.high:\n\t\tfor col in cols:\n\t\t\tif i < col.len: str.add col[i]\n\n\t# Build plain text from row+column values.\n\tfor i in countup(0, str.len - 2, 2):\n\t\tlet r = Adfgvx.find(str[i])\n\t\tlet c = Adfgvx.find(str[i+1])\n\t\tresult.add polybius[r][c]\n\n\nrandomize()\n\nvar polybius = initPolybiusSquare()\necho \"6 x 6 Polybius square:\\n\"\necho \" | A D F G V X\"\necho \"---------------\"\nfor i, row in polybius:\n\techo Adfgvx[i], \" | \", row.join(\" \")\n\nlet key = createKey(9)\necho \"\\nThe key is \", key\n\nconst PlainText = \"ATTACKAT1200AM\"\necho \"\\nPlaintext : \", PlainText\n\nlet cipherText = PlainText.encrypt(polybius, key)\necho \"\\nEncrypted : \", cipherText\n\nlet plainText = cipherText.decrypt(polybius, key)\necho \"\\nDecrypted : \", plainText\n" + }, + { + "id": 1393, + "length": 2219, + "source": "Rosetta Code", + "text": "import strformat\n\nconst\n\n\tD = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n\t\t\t [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n\t\t\t [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n\t\t\t [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n\t\t\t [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n\t\t\t [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n\t\t\t [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n\t\t\t [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n\t\t\t [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n\t\t\t [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]\n\n\tInv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\n\tP = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n\t\t\t [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n\t\t\t [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n\t\t\t [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n\t\t\t [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n\t\t\t [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n\t\t\t [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n\t\t\t [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]\n\ntype Digit = 0..9\n\nproc verhoeff[T: SomeInteger](n: T; validate, verbose = false): T =\n\t## Compute or validate a check digit.\n\t## Return the check digit if computation or the number with the check digit\n\t## removed if validation.\n\t## If not in verbose mode, an exception is raised if validation failed.\n\n\tdoAssert n >= 0, \"Argument must not be negative.\"\n\n\t# Extract digits.\n\tvar digits: seq[Digit]\n\tif not validate: digits.add 0\n\tvar val = n\n\twhile val != 0:\n\t\tdigits.add val mod 10\n\t\tval = val div 10\n\n\tif verbose:\n\t\techo if validate: \"Check digit validation for {n}:\" else: \"Check digit computation for {n}:\"\n\t\techo \" i ni p(i, ni) c\"\n\n\t# Compute c.\n\tvar c = 0\n\tfor i, ni in digits:\n\t\tlet p = P[i mod 8][ni]\n\t\tc = D[c][p]\n\t\tif verbose: echo \"{i:2} {ni} {p} {c}\"\n\n\tif validate:\n\t\tif verbose:\n\t\t\tlet verb = if c == 0: \"is\" else: \"is not\"\n\t\t\techo \"Validation {verb} successful.\\n\"\n\t\telif c != 0:\n\t\t\traise newException(ValueError, \"Check digit validation failed for {n}.\")\n\t\tresult = n div 10\n\n\telse:\n\t\tresult = Inv[c]\n\t\tif verbose: echo \"The check digit for {n} is {result}.\\n\"\n\n\nfor n in [236, 12345]:\n\tlet d = verhoeff(n, false, true)\n\tdiscard verhoeff(10 * n + d, true, true)\n\tdiscard verhoeff(10 * n + 9, true, true)\n\nlet n = 123456789012\nlet d = verhoeff(n)\necho \"Check digit for {n} is {d}.\"\ndiscard verhoeff(10 * n + d, true)\necho \"Check digit validation was successful for {10 * n + d}.\"\ntry:\n\tdiscard verhoeff(10 * n + 9, true)\nexcept ValueError:\n\techo getCurrentExceptionMsg()\n" + }, + { + "id": 1394, + "length": 2605, + "source": "Rosetta Code", + "text": "import gintro/[glib, gobject, gtk, gio, cairo]\n\nconst\n\tWidth = 600\n\tHeight = 460\n\ntype\n\tColor = array[3, float]\n\tEdge {.pure.} = enum LT, TR, RB, BL\n\nconst\n\n\tEdges = [[LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],\n\t\t\t\t\t [LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],\n\t\t\t\t\t [TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],\n\t\t\t\t\t [TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT],\n\t\t\t\t\t [RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT],\n\t\t\t\t\t [RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR, TR],\n\t\t\t\t\t [BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB, TR],\n\t\t\t\t\t [BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB, RB],\n\t\t\t\t\t [LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL, RB],\n\t\t\t\t\t [LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL, BL],\n\t\t\t\t\t [TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL],\n\t\t\t\t\t [TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT]]\n\n\tBlack: Color = [0.0, 0.0, 0.0]\n\tBlue: Color = [0.2, 0.3, 1.0]\n\tWhite: Color = [1.0, 1.0, 1.0]\n\tYellow: Color = [0.8, 0.8, 0.0]\n\n\tColors: array[Edge, array[4, Color]] = [[White, Black, Black, White],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[White, White, Black, Black],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[Black, White, White, Black],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[Black, Black, White, White]]\n\n\nproc draw(area: DrawingArea; context: Context) =\n\t## Draw the pattern in the area.\n\n\tfunc line(x1, y1, x2, y2: float; color: Color) =\n\t\tcontext.setSource(color)\n\t\tcontext.moveTo(x1, y1)\n\t\tcontext.lineTo(x2, y2)\n\t\tcontext.stroke\n\n\tcontext.setSource(Yellow)\n\tcontext.rectangle(0, 0, Width, Height)\n\tcontext.fill()\n\n\tfor x in 0..11:\n\t\tlet px = float(86 + x * 36)\n\t\tfor y in 0..11:\n\t\t\tlet py = float(16 + y * 36)\n\t\t\tcontext.setSource(Blue)\n\t\t\tcontext.rectangle(px, py, 24, 24)\n\t\t\tcontext.fill()\n\t\t\tlet carray = Colors[Edges[y][x]]\n\t\t\tcontext.setLineWidth(2)\n\t\t\tline(px, py, px + 23, py, carray[0])\n\t\t\tline(px + 23, py, px + 23, py + 23, carray[1])\n\t\t\tline(px + 23, py + 23, px, py + 23, carray[2])\n\t\t\tline(px, py + 23, px, py, carray[3])\n\n\nproc onDraw(area: DrawingArea; context: Context; data: pointer): bool =\n\t## Callback to draw/redraw the drawing area contents.\n\n\tarea.draw(context)\n\tresult = true\n\n\nproc activate(app: Application) =\n\t## Activate the application.\n\n\tlet window = app.newApplicationWindow()\n\twindow.setSizeRequest(Width, Height)\n\twindow.setTitle(\"Peripheral drift illusion\")\n\n\t# Create the drawing area.\n\tlet area = newDrawingArea()\n\twindow.add(area)\n\n\t# Connect the \"draw\" event to the callback to draw the pattern.\n\tdiscard area.connect(\"draw\", ondraw, pointer(nil))\n\n\twindow.showAll()\n\n\nlet app = newApplication(Application, \"Illusion\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n" + }, + { + "id": 1395, + "length": 606, + "source": "Rosetta Code", + "text": "import strformat\n\ntemplate isOdd(n: Natural): bool = (n and 1) != 0\ntemplate isEven(n: Natural): bool = (n and 1) == 0\n\nfunc isPrime(n: Positive): bool =\n\tif n == 1: return false\n\tif n.isEven: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar d = 5\n\twhile d * d <= n:\n\t\tif n mod d == 0: return false\n\t\tinc d, 2\n\t\tif n mod d == 0: return false\n\t\tinc d, 4\n\tresult = true\n\n# Compute the sums of primes at odd position.\necho \" i p(i) sum\"\nvar idx = 0\nvar sum = 0\nvar p = 1\nwhile p < 1000:\n\tinc p\n\tif p.isPrime:\n\t\tinc idx\n\t\tif idx.isOdd:\n\t\t\tinc sum, p\n\t\t\tif sum.isPrime:\n\t\t\t\techo \"{idx:3} {p:3} {sum:5}\"\n" + }, + { + "id": 1396, + "length": 1274, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils, times\n\nlet t0 = now()\n\ntype PrimeCounter = seq[int]\n\nproc initPrimeCounter(limit: Positive): PrimeCounter =\n\tdoAssert limit > 1\n\tresult = repeat(1, limit)\n\tresult[0] = 0\n\tresult[1] = 0\n\tfor i in countup(4, limit - 1, 2): result[i] = 0\n\tvar p = 3\n\tvar p2 = 9\n\twhile p2 < limit:\n\t\tif result[p] != 0:\n\t\t\tfor q in countup(p2, limit - 1, p shl 1):\n\t\t\t\tresult[q] = 0\n\t\tp2 += (p + 1) shl 2\n\t\tif p2 >= limit: break\n\t\tinc p, 2\n\t# Compute partial sums in place.\n\tvar sum = 0\n\tfor item in result.mitems:\n\t\tsum += item\n\t\titem = sum\n\nfunc ramanujanMax(n: int): int {.inline.} = int(ceil(4 * n.toFloat * ln(4 * n.toFloat)))\n\nproc ramanujanPrime(pi: PrimeCounter; n: int): int =\n\tif n == 1: return 2\n\tvar max = ramanujanMax(n)\n\tif (max and 1) == 1: dec max\n\tfor i in countdown(max, 2, 2):\n\t\tif pi[i] - pi[i div 2] < n:\n\t\t\treturn i + 1\n\nlet pi = initPrimeCounter(1 + ramanujanMax(100_000))\n\nfor n in 1..100:\n\tstdout.write ($ramanujanPrime(pi, n)).align(4), if n mod 20 == 0: '\\n' else: ' '\n\necho \"\\nThe 1000th Ramanujan prime is \", ramanujanPrime(pi, 1_000)\necho \"The 10_000th Ramanujan prime is \", ramanujanPrime(pi, 10_000)\necho \"The 100_000th Ramanujan prime is \", ramanujanPrime(pi, 100_000)\n\necho \"\\nElapsed time: \", (now() - t0).inMilliseconds, \" ms\"\n" + }, + { + "id": 1397, + "length": 1859, + "source": "Rosetta Code", + "text": "import math, sequtils, strutils, sugar, times\n\nlet t0 = now()\n\ntype PrimeCounter = seq[int32]\n\nproc initPrimeCounter(limit: Positive): PrimeCounter {.noInit.} =\n\tdoAssert limit > 1\n\tresult = repeat(1i32, limit)\n\tresult[0] = 0\n\tresult[1] = 0\n\tfor i in countup(4, limit - 1, 2): result[i] = 0\n\tvar p = 3\n\tvar p2 = 9\n\twhile p2 < limit:\n\t\tif result[p] != 0:\n\t\t\tfor q in countup(p2, limit - 1, p + p):\n\t\t\t\tresult[q] = 0\n\t\tinc p, 2\n\t\tp2 = p * p\n\t# Compute partial sums in place.\n\tvar sum = 0i32\n\tfor item in result.mitems:\n\t\tsum += item\n\t\titem = sum\n\nfunc ramanujanMax(n: int): int {.inline.} = int(ceil(4 * n.toFloat * ln(4 * n.toFloat)))\n\nfunc ramanujanPrime(pi: PrimeCounter; n: int): int =\n\tif n == 1: return 2\n\tvar max = ramanujanMax(n)\n\tif (max and 1) == 1: dec max\n\tfor i in countdown(max, 2, 2):\n\t\tif pi[i] - pi[i div 2] < n:\n\t\t\treturn i + 1\n\nfunc primesLe(limit: Positive): seq[int] =\n\tvar composite = newSeq[bool](limit + 1)\n\tvar n = 3\n\tvar n2 = 9\n\twhile n2 <= limit:\n\t\tif not composite[n]:\n\t\t\tfor k in countup(n2, limit, 2 * n):\n\t\t\t\tcomposite[k] = true\n\t\tn2 += (n + 1) shl 2\n\t\tn += 2\n\tresult = @[2]\n\tfor n in countup(3, limit, 2):\n\t\tif not composite[n]: result.add n\n\nproc main() =\n\tconst Lim = 1_000_000\n\tlet pi = initPrimeCounter(1 + ramanujanMax(Lim))\n\tlet rpLim = ramanujanPrime(pi, Lim)\n\techo \"The 1_000_000th Ramanujan prime is $#.\".format(($rpLim).insertSep())\n\tlet r = primesLe(rpLim)\n\tvar c = r.mapIt(pi[it] - pi[it div 2])\n\tvar ok = c[^1]\n\tfor i in countdown(c.len - 2, 0):\n\t\tif c[i] < ok:\n\t\t\tok = c[i]\n\t\telse:\n\t\t\tc[i] = 0\n\tlet fr = collect(newSeq, for i, p in r: (if c[i] != 0: p))\n\tvar twins = 0\n\tvar prev = -1\n\tfor p in fr:\n\t\tif p == prev + 2: inc twins\n\t\tprev = p\n\techo \"There are $1 twins in the first $2 Ramanujan primes.\".format(($twins).insertSep(), ($Lim).insertSep)\n\nmain()\necho \"\\nElapsed time: \", (now() - t0).inMilliseconds, \" ms\"\n" + }, + { + "id": 1398, + "length": 1443, + "source": "Rosetta Code", + "text": "import strformat, strutils, tables\nimport bignum\n\nproc divide(m, n: Int): tuple[repr: string; cycle: string; period: int] =\n\tdoAssert m >= 0, \"m must not be negative.\"\n\tdoAssert n > 0, \"n must be positive.\"\n\n\tvar quotient = \"{m div n}.\"\n\tvar c = m mod n * 10\n\tvar zeros = 0\n\twhile c > 0 and c < n:\n\t\tc *= 10\n\t\tquotient &= '0'\n\t\tinc zeros\n\n\tvar digits = \"\"\n\tvar passed: Table[string, int]\n\tvar i = 0\n\twhile true:\n\t\tlet cs = $c\n\t\tif cs in passed:\n\t\t\tlet idx = passed[cs]\n\t\t\tlet prefix = digits[0..\"\n\techo \"Period is {period}\\n\"\n" + }, + { + "id": 1399, + "length": 655, + "source": "Rosetta Code", + "text": "import random, strutils\n\nrandomize()\n\nconst N = 1000\ntype Digit = 0..9\n\n# Build a 1000-digit number.\nvar number: array[1..N, Digit]\nnumber[1] = rand(1..9) # Make sure the first digit is not 0.\nfor i in 1..N: number[i] = rand(9)\n\nfunc `>`(s1, s2: seq[Digit]): bool =\n\t## Compare two digit sequences.\n\t## Defining `<` rather than `>` would work too.\n\tassert s1.len == s2.len\n\tfor i in 0..s1.high:\n\t\tlet comp = cmp(s1[i], s2[i])\n\t\tif comp != 0: return comp == 1\n\tresult = false\n\nvar max = @[Digit 0, 0, 0, 0, 0]\nfor i in 5..N:\n\tlet n = number[i-4..i]\n\tif n > max: max = n\n\necho \"Largest 5-digit number extracted from random 1000-digit number: \", max.join()\n" + }, + { + "id": 1400, + "length": 1196, + "source": "Rosetta Code", + "text": "import math\n\ntype\n\tVector = tuple[x, y, z: float]\n\tMatrix = array[3, Vector]\n\nfunc norm(v: Vector): float =\n\tsqrt(v.x * v.x + v.y * v.y + v.z * v.z)\n\nfunc normalized(v: Vector): Vector =\n\tlet length = v.norm()\n\tresult = (v.x / length, v.y / length, v.z / length)\n\nfunc scalarProduct(v1, v2: Vector): float =\n\tv1.x * v2.x + v1.y * v2.y + v1.z * v2.z\n\nfunc vectorProduct(v1, v2: Vector): Vector =\n\t(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x)\n\nfunc angle(v1, v2: Vector): float =\n\tarccos(scalarProduct(v1, v2) / (norm(v1) * norm(v2)))\n\nfunc `*`(m: Matrix; v: Vector): Vector =\n\t(scalarProduct(m[0], v), scalarProduct(m[1], v), scalarProduct(m[2], v))\n\nfunc rotate(p, v: Vector; a: float): Vector =\n\tlet ca = cos(a)\n\tlet sa = sin(a)\n\tlet t = 1 - ca\n\tlet r = [(ca + v.x * v.x * t, v.x * v.y * t - v.z * sa, v.x * v.z * t + v.y * sa),\n\t\t\t\t\t (v.x * v.y * t + v.z * sa, ca + v.y * v.y * t, v.y * v.z * t - v.x * sa),\n\t\t\t\t\t (v.z * v.x * t - v.y * sa, v.z * v.y * t + v.x * sa, ca + v.z * v.z * t)]\n\tresult = r * p\n\nlet\n\tv1 = (5.0, -6.0, 4.0)\n\tv2 = (8.0, 5.0, -30.0)\n\ta = angle(v1, v2)\n\tvp = vectorProduct(v1, v2)\n\tnvp = normalized(vp)\n\tnp = v1.rotate(nvp, a)\necho np\n" + }, + { + "id": 1401, + "length": 646, + "source": "Rosetta Code", + "text": "# Without sorting.\nimport strformat\n\nproc extractAndAddTwoSmallest(list: var seq[int]) =\n\tvar min1, min2 = int.high\n\tvar imin1, imin2 = -1\n\tfor i, val in list:\n\t\tif val < min1:\n\t\t\tmin2 = min1\n\t\t\tmin1 = val\n\t\t\timin2 = imin1\n\t\t\timin1 = i\n\t\telif val < min2:\n\t\t\tmin2 = val\n\t\t\timin2 = i\n\techo \"List: {list}; two smallest: {min1}@{imin1} and {min2}@{imin2}; sum = {min1 + min2}\"\n\tif imin1 > imin2: swap imin1, imin2 # Make sure \"imin2\" is the greatest index.\n\tlist.del imin2\n\tlist.del imin1\n\tlist.add min1 + min2\n\nvar list = @[6, 81, 243, 14, 25, 49, 123, 69, 11]\n\nwhile list.len >= 2:\n\tlist.extractAndAddTwoSmallest()\necho \"Last item is {list[0]}.\"\n" + }, + { + "id": 1402, + "length": 699, + "source": "Rosetta Code", + "text": "const\n\tNumbers1 = [ 5, 45, 23, 21, 67]\n\tNumbers2 = [43, 22, 78, 46, 38]\n\tNumbers3 = [ 9, 98, 12, 54, 53]\n\nvar numbers: array[0..Numbers1.high, int]\n\ntemplate isEven(n: int): bool = (n and 1) == 0\n\nfunc isPrime(n: Positive): bool =\n\tif n < 2: return false\n\tif n.isEven: return n == 2\n\tif n mod 3 == 0: return n == 3\n\tvar k = 5\n\tvar delta = 2\n\twhile k * k <= n:\n\t\tif n mod k == 0: return false\n\t\tinc k, delta\n\t\tdelta = 6 - delta\n\tresult = true\n\nfunc minPrime(n: int): int =\n\tif n == 2: return 2\n\tresult = if n.isEven: n + 1 else: n\n\twhile not result.isPrime():\n\t\tinc result, 2\n\nfor i in 0..numbers.high:\n\tlet m = max(max(Numbers1[i], Numbers2[i]), Numbers3[i])\n\tnumbers[i] = minPrime(m)\n\necho numbers\n" + }, + { + "id": 1403, + "length": 1226, + "source": "Rosetta Code", + "text": "import random\nimport imageman\n\nconst\n\tSize = 400 # Area size.\n\tMaxXY = Size - 1 # Maximum possible value for x and y.\n\tNPart = 25_000 # Number of particles.\n\tBackground = ColorRGBU [byte 0, 0, 0] # Background color.\n\tForeground = ColorRGBU [byte 50, 150, 255] # Foreground color.\n\nrandomize()\nvar image = initImage[ColorRGBU](Size, Size)\nimage.fill(Background)\nimage[Size div 2, Size div 2] = Foreground\n\nfor _ in 1..NPart:\n\n\tblock ProcessParticle:\n\t\twhile true: # Repeat until the particle is freezed.\n\n\t\t\t# Choose position of particle.\n\t\t\tvar x, y = rand(MaxXY)\n\t\t\tif image[x, y] == Foreground:\n\t\t\t\tcontinue # Not free. Try again.\n\n\t\t\t# Move the particle.\n\t\t\twhile true:\n\n\t\t\t\t# Choose a motion.\n\t\t\t\tlet dx, dy = rand(-1..1)\n\t\t\t\tinc x, dx\n\t\t\t\tinc y, dy\n\t\t\t\tif x notin 0..MaxXY or y notin 0..MaxXY:\n\t\t\t\t\tbreak # Out of limits. Try again.\n\n\t\t\t\t# Valid move.\n\t\t\t\tif image[x, y] == Foreground:\n\t\t\t\t\t# Not free. Freeze the particle at its previous position.\n\t\t\t\t\timage[x - dx, y - dy] = Foreground\n\t\t\t\t\tbreak ProcessParticle # Done. Process next particle.\n\n# Save into a PNG file.\nimage.savePNG(\"brownian.png\", compression = 9)\n" + }, + { + "id": 1404, + "length": 728, + "source": "Rosetta Code", + "text": "import httpclient, strutils, xmltree, xmlparser, cgi\n\nproc count(s, sub: string): int =\n\tvar i = 0\n\twhile true:\n\t\ti = s.find(sub, i)\n\t\tif i < 0: break\n\t\tinc i\n\t\tinc result\n\nconst\n\tmainSite = \"http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml\"\n\tsubSite = \"http://www.rosettacode.org/mw/index.php?title=$#&action=raw\"\n\nvar client = newHttpClient()\nvar sum = 0\nfor node in client.getContent(mainSite).parseXml().findAll(\"cm\"):\n\tlet t = node.attr(\"title\").replace(\" \", \"_\")\n\tlet c = client.getContent(subSite % encodeUrl(t)).toLower().count(\"{{header|\")\n\techo t.replace(\"_\", \" \"), \": \", c, \" examples.\"\n\tinc sum, c\n\necho \"\\nTotal: \", sum, \" examples.\"\n" + }, + { + "id": 1405, + "length": 961, + "source": "Rosetta Code", + "text": "import httpclient, strutils, xmltree, xmlparser, cgi, os\n\n\nproc findrc(category: string): seq[string] =\n\n\tvar\n\t\tname = \"http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:$#&cmlimit=500&format=xml\" % encodeUrl(category)\n\t\tcmcontinue = \"\"\n\t\tclient = newHttpClient()\n\n\twhile true:\n\t\tvar x = client.getContent(name & cmcontinue).parseXml()\n\t\tfor node in x.findAll(\"cm\"):\n\t\t\tresult.add node.attr(\"title\")\n\n\t\tcmcontinue.setLen(0)\n\t\tfor node in x.findAll(\"categorymembers\"):\n\t\t\tlet u = node.attr(\"cmcontinue\")\n\t\t\tif u.len != 0: cmcontinue = u.encodeUrl()\n\n\t\tif cmcontinue.len > 0: cmcontinue = \"&cmcontinue=\" & cmcontinue\n\t\telse: break\n\n\nproc chooselang(): string =\n\tif paramCount() < 1: \"Nim\" else: paramStr(1)\n\n\nlet alltasks = findrc(\"Programming_Tasks\")\nlet lang = chooselang()\nlet langTasks = lang.findrc()\necho \"Unimplemented tasks for language \", lang, ':'\nfor task in alltasks:\n\tif task notin langTasks:\n\t\techo \" \", task\n" + }, + { + "id": 1406, + "length": 1433, + "source": "Rosetta Code", + "text": "import httpclient, json, re, strformat, strutils, algorithm\n\nconst\n\tLangSite = \"http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json\"\n\tCatSite = \"http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000\"\nlet regex = re\"title=\"\"Category:(.*?)\"\">.+?.*\\((.*) members\\)\"\n\ntype Rank = tuple[lang: string, count: int]\n\nproc cmp(a, b: Rank): int =\n\tresult = cmp(b.count, a.count)\n\tif result == 0: result = cmp(a.lang, b.lang)\n\nproc add(langs: var seq[string]; fromJson: JsonNode) =\n\tfor entry in fromJson{\"query\", \"categorymembers\"}:\n\t\tlangs.add entry[\"title\"].getStr.split(\"Category:\")[1]\n\nvar client = newHttpClient()\nvar langs: seq[string]\nvar url = LangSite\nwhile true:\n\tlet response = client.get(url)\n\tif response.status != $Http200: break\n\tlet fromJson = response.body.parseJson()\n\tlangs.add fromJson\n\tif \"continue\" notin fromJson: break\n\tlet cmcont = fromJson{\"continue\", \"cmcontinue\"}.getStr\n\tlet cont = fromJson{\"continue\", \"continue\"}.getStr\n\turl = LangSite & fmt\"&cmcontinue={cmcont}&continue={cont}\"\n\nvar ranks: seq[Rank]\nfor line in client.getContent(CatSite).findAll(regex):\n\tlet lang = line.replacef(regex, \"$1\")\n\tif lang in langs:\n\t\tlet count = parseInt(line.replacef(regex, \"$2\").replace(\",\", \"\").strip())\n\t\tranks.add (lang, count)\n\nranks.sort(cmp)\nfor i, rank in ranks:\n\techo \"{i + 1:3} {rank.count:4} - {rank.lang}\"\n" + }, + { + "id": 1407, + "length": 3449, + "source": "Rosetta Code", + "text": "import posix\nimport strutils\n\ntype\n\n\t# GECOS representation.\n\tGecos = tuple[fullname, office, extension, homephone, email: string]\n\n\t# Record representation.\n\tRecord = object\n\t\taccount: string\n\t\tpassword: string\n\t\tuid: int\n\t\tgid: int\n\t\tgecos: Gecos\n\t\tdirectory: string\n\t\tshell: string\n\n\nproc str(gecos: Gecos): string =\n\t## Explicit representation of a GECOS.\n\n\tresult = \"(\"\n\tfor name, field in gecos.fieldPairs:\n\t\tresult.addSep(\", \", 1)\n\t\tresult.add(name & \": \" & field)\n\tresult.add(')')\n\n\nproc `$`(gecos: Gecos): string =\n\t## Compact representation of a GECOS.\n\n\tfor field in gecos.fields:\n\t\tresult.addSep(\",\", 0)\n\t\tresult.add(field)\n\n\nproc parseGecos(s: string): Gecos =\n\t## Parse a string and return a Gecos tuple.\n\n\tlet fields = s.split(\",\")\n\tresult = (fields[0], fields[1], fields[2], fields[3], fields[4])\n\n\nproc str(rec: Record): string =\n\t## Explicit representation of a record.\n\n\tfor name, field in rec.fieldPairs:\n\t\tresult.add(name & \": \")\n\t\twhen typeof(field) is Gecos:\n\t\t\tresult.add(str(field))\n\t\telse:\n\t\t\tresult.add($field)\n\t\tresult.add('\\n')\n\n\nproc `$`(rec: Record): string =\n\t# Compact representation fo a record.\n\n\tfor field in rec.fields:\n\t\tresult.addSep(\":\", 0)\n\t\tresult.add($field)\n\n\nproc parseRecord(line: string): Record =\n\t## Parse a string and return a Record object.\n\n\tlet fields = line.split(\":\")\n\tresult.account = fields[0]\n\tresult.password = fields[1]\n\tresult.uid = fields[2].parseInt()\n\tresult.gid = fields[3].parseInt()\n\tresult.gecos = parseGecos(fields[4])\n\tresult.directory = fields[5]\n\tresult.shell = fields[6]\n\n\nproc getLock(f: File): bool =\n\t## Try to get an exclusive write lock on file \"f\". Return false is unsuccessful.\n\n\twhen defined(posix):\n\t\tvar flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0)\n\t\tresult = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0\n\telse:\n\t\tresult = true\n\n\nvar pwfile: File\n\nconst Filename = \"passwd\"\n\nconst Data = [\"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash\",\n\t\t\t\t\t\t\t\"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash\"]\n\n# Prepare initial file.\n# We don''t use a lock here as it is only the preparation.\npwfile = open(FileName, fmWrite)\nfor line in Data:\n\tpwfile.writeLine(line)\npwfile.close()\n\n# Display initial contents.\necho \"Raw content of initial password file:\"\necho \"-------------------------------------\"\nvar records: seq[Record]\nfor line in lines(FileName):\n\techo line\n\trecords.add(line.parseRecord())\n\necho \"\"\necho \"Structured content of initial password file:\"\necho \"--------------------------------------------\"\nfor rec in records:\n\techo str(rec)\n\n# Add a new record at the end of password file.\npwfile = open(Filename, fmAppend)\nlet newRecord = Record(account: \"xyz\",\n\t\t\t\t\t\t\t\t\t\t\t password: \"x\",\n\t\t\t\t\t\t\t\t\t\t\t uid: 1003,\n\t\t\t\t\t\t\t\t\t\t\t gid: 1000,\n\t\t\t\t\t\t\t\t\t\t\t gecos: (\"X Yz\", \"Room 1003\", \"(234)555-8913\", \"(234)555-0033\", \"xyz@rosettacode.org\"),\n\t\t\t\t\t\t\t\t\t\t\t directory: \"/home/xyz\",\n\t\t\t\t\t\t\t\t\t\t\t shell: \"/bin/bash\")\necho \"Appending new record:\"\necho \"---------------------\"\necho str(newRecord)\nif pwfile.getLock():\n\tpwFile.writeLine(newRecord)\n\tpwfile.close()\nelse:\n\techo \"File is locked. Quitting.\"\n\tpwFile.close()\n\tquit(QuitFailure)\n\n# Reopen the file and display its contents.\necho \"Raw content of updated password file:\"\necho \"-------------------------------------\"\nfor line in lines(FileName):\n\techo line\n" + }, + { + "id": 1408, + "length": 2561, + "source": "Rosetta Code", + "text": "import htmlparser, httpclient, os, osproc, re, sets, strutils, xmltree\n\nconst\n\tUrl1 = \"http://rosettacode.org/wiki/Category:Programming_Tasks\"\n\tUrl2 = \"http://rosettacode.org/wiki/Category:Draft_Programming_Tasks\"\n\tUrls = [Url1, Url2]\n\nproc getAllTasks(client: HttpClient): HashSet[string] =\n\tlet regex = re(\"\"\"
  • (.*?)</lang>\".format(lang2, lang3))\n\tvar matches: array[2, string]\n\tlet idx = body.find(regex, matches)\n\tif idx < 0:\n\t\techo \"No runnable task entry for that language was detected.\"\n\t\tcontinue\n\n\tlet source = parseHtml(matches[1]).innerText()\n\techo \"\\nThis is the source code for the first or only runnable program:\\n\"\n\techo source\n\tstdout.write \"\\nDo you want to run it (y/n)? \"\n\tstdout.flushFile()\n\tvar answer = stdin.readLine()\n\tif answer in [\"y\", \"Y\"]:\n\t\tfileName.writeFile(source)\n\t\tlet cmd = case lang\n\t\t\t\t\t\t\tof \"go\": \"go run \" & fileName\n\t\t\t\t\t\t\tof \"nim\": \"nim r -d:release --threads:on -d:ssl \" & fileName\n\t\t\t\t\t\t\tof \"perl\": \"perl \" & fileName\n\t\t\t\t\t\t\tof \"python\": \"python \" & fileName\n\t\t\t\t\t\t\telse: \"\"\n\t\tdiscard execCmd cmd\n\t\tremoveFile fileName\n\n\tstdout.write \"\\nDo another one (y/n)? \"\n\tstdout.flushFile()\n\tanswer = stdin.readLine()\n\tif answer notin [\"y\", \"Y\"]:\n\t\tbreak\n" + }, + { + "id": 1409, + "length": 1682, + "source": "Rosetta Code", + "text": "import algorithm, httpclient, re, strutils, tables\n\nlet\n\tre1 = re(\"\"\"
  • (.*?)