solutions
listlengths
2
791
task_name
stringlengths
2
86
[ { "code": "---\ncategory:\n- Functions and subroutines\nfrom: http://rosettacode.org/wiki/Variadic_function\nnote: Basic language learning\n", "language": "00-META" }, { "code": ";Task:\nCreate a function which takes in a variable number of arguments and prints each one on its own line. \n\nAlso show, if possible in your language, how to call the function on a list of arguments constructed at runtime.\n\n\nFunctions of this type are also known as [[wp:Variadic_function|Variadic Functions]].\n\n\n;Related task:\n* &nbsp; [[Call a function]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "(defun print-all-fn (xs)\n (if (endp xs)\n nil\n (prog2$ (cw \"~x0~%\" (first xs))\n (print-all-fn (rest xs)))))\n\n(defmacro print-all (&rest args)\n `(print-all-fn (quote ,args)))\n", "language": "ACL2" }, { "code": "public function printArgs(... args):void\n{\n for (var i:int = 0; i < args.length; i++)\n trace(args[i]);\n}\n", "language": "ActionScript" }, { "code": "with Ada.Strings.Unbounded, Ada.Text_IO;\n\nprocedure Variadic is\n\n subtype U_String is Ada.Strings.Unbounded.Unbounded_String;\n use type U_String;\n\n function \"+\"(S: String) return U_String\n renames Ada.Strings.Unbounded.To_Unbounded_String;\n\n function \"-\"(U: U_String) return String\n renames Ada.Strings.Unbounded.To_String;\n\n type Variadic_Array is array(Positive range <>) of U_String;\n\n procedure Print_Line(Params: Variadic_Array) is\n begin\n for I in Params'Range loop\n Ada.Text_IO.Put(-Params(I));\n if I < Params'Last then\n Ada.Text_IO.Put(\" \");\n end if;\n end loop;\n Ada.Text_IO.New_Line;\n end Print_Line;\n\nbegin\n Print_Line((+\"Mary\", +\"had\", +\"a\", +\"little\", +\"lamb.\")); -- print five strings\n Print_Line((1 => +\"Rosetta Code is cooool!\")); -- print one string\nend;\n", "language": "Ada" }, { "code": "void\nf(...)\n{\n integer i;\n\n i = 0;\n while (i < count()) {\n\to_text($i);\n\to_byte('\\n');\n\ti += 1;\n }\n}\n\ninteger\nmain(void)\n{\n f(\"Mary\", \"had\", \"a\", \"little\", \"lamb\");\n\n return 0;\n}\n", "language": "Aime" }, { "code": "void\noutput_date(date d)\n{\n o_form(\"~%//f2/%//f2/\", d.year, d.y_month, d.m_day);\n}\n\nvoid\ng(...)\n{\n integer i;\n record r;\n\n r[\"integer\"] = o_integer;\n r[\"real\"] = o_;\n r[\"text\"] = o_text;\n r[\"date\"] = output_date;\n\n i = 0;\n while (i < count()) {\n r[__type($i)]($i);\n o_byte('\\n');\n i += 1;\n }\n}\n\ninteger\nmain(void)\n{\n g(\"X.1\", 707, .5, date().now);\n\n return 0;\n}\n", "language": "Aime" }, { "code": "main:(\n MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);\n\n PROC print strint = (FLEX[]STRINT argv)VOID: (\n FOR i TO UPB argv DO\n CASE argv[i] IN\n (INT i):print(whole(i,-1)),\n (STRING s):print(s),\n (PROC(REF FILE)VOID f):f(stand out),\n (VOID):print(error char)\n ESAC;\n IF i NE UPB argv THEN print((\" \")) FI\n OD\n );\n\n print strint((\"Mary\",\"had\",1,\"little\",EMPTY,new line))\n)\n", "language": "ALGOL-68" }, { "code": "use framework \"Foundation\"\n\n-- positionalArgs :: [a] -> String\non positionalArgs(xs)\n\n -- follow each argument with a line feed\n map(my putStrLn, xs) as string\nend positionalArgs\n\n-- namedArgs :: Record -> String\non namedArgs(rec)\n script showKVpair\n on |λ|(k)\n my putStrLn(k & \" -> \" & keyValue(rec, k))\n end |λ|\n end script\n\n -- follow each argument name and value with line feed\n map(showKVpair, allKeys(rec)) as string\nend namedArgs\n\n-- TEST\non run\n intercalate(linefeed, ¬\n {positionalArgs([\"alpha\", \"beta\", \"gamma\", \"delta\"]), ¬\n namedArgs({epsilon:27, zeta:48, eta:81, theta:8, iota:1})})\n\n --> \"alpha\n -- beta\n -- gamma\n -- delta\n --\n -- epsilon -> 27\n -- eta -> 81\n -- iota -> 1\n -- zeta -> 48\n -- theta -> 8\n -- \"\nend run\n\n\n-- GENERIC FUNCTIONS\n\n-- putStrLn :: a -> String\non putStrLn(a)\n (a as string) & linefeed\nend putStrLn\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- allKeys :: Record -> [String]\non allKeys(rec)\n (current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list\nend allKeys\n\n-- keyValue :: Record -> String -> Maybe String\non keyValue(rec, strKey)\n set ca to current application\n set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey\n if v is not missing value then\n item 1 of ((ca's NSArray's arrayWithObject:v) as list)\n else\n missing value\n end if\nend keyValue\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "10 P$(0) = STR$(5)\n20 P$(1) = \"MARY\"\n30 P$(2) = \"HAD\"\n40 P$(3) = \"A\"\n50 P$(4) = \"LITTLE\"\n60 P$(5) = \"LAMB\"\n70 GOSUB 90\"VARIADIC FUNCTION\n80 END\n90 FOR I = 1 TO VAL(P$(0)) : ? P$(I) : P$(I) = \"\" : NEXT I : P$(0) = \"\" : RETURN\n", "language": "Applesoft-BASIC" }, { "code": ";-------------------------------------------\n; a quasi-variadic function\n;-------------------------------------------\nvariadic: function [args][\n loop args 'arg [\n print arg\n ]\n]\n\n; calling function with one block param\n; and the arguments inside\n\nvariadic [\"one\" 2 \"three\"]\n\n;-------------------------------------------\n; a function with optional attributes\n;-------------------------------------------\nvariable: function [args][\n print [\"args:\" args]\n if? attr? \"with\" [\n print [\"with:\" attr \"with\"]\n ]\n else [\n print \"without attributes\"\n ]\n]\n\nvariable \"yes\"\nvariable.with:\"something\" \"yes!\"\n", "language": "Arturo" }, { "code": "printAll(args*) {\n for k,v in args\n t .= v \"`n\"\n MsgBox, %t%\n}\n", "language": "AutoHotkey" }, { "code": "printAll(4, 3, 5, 6, 4, 3)\nprintAll(4, 3, 5)\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\")\n", "language": "AutoHotkey" }, { "code": "args := [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"]\nprintAll(args*)\n", "language": "AutoHotkey" }, { "code": "string = Mary had a little lamb\nStringSplit, arg, string, %A_Space%\n\nFunction(arg1,arg2,arg3,arg4,arg5) ;Calls the function with 5 arguments.\nFunction() ;Calls the function with no arguments.\nreturn\n\nFunction(arg1=\"\",arg2=\"\",arg3=\"\",arg4=\"\",arg5=\"\") {\n Loop,5\n If arg%A_Index% !=\n out .= arg%A_Index% \"`n\"\n MsgBox,% out ? out:\"No non-blank arguments were passed.\"\n}\n", "language": "AutoHotkey" }, { "code": "function f(a, b, c){\n\tif (a != \"\") print a\n\tif (b != \"\") print b\n\tif (c != \"\") print c\n}\n\nBEGIN {\n\tprint \"[1 arg]\"; f(1)\n\tprint \"[2 args]\"; f(1, 2)\n\tprint \"[3 args]\"; f(1, 2, 3)\n}\n", "language": "AWK" }, { "code": "function f(a, b, c) {\n\tif (a != \"\") print a\n\tif (b != \"\") print b\n\tif (c != \"\") print c\n}\n\nBEGIN {\n\t# Set ary[1] and ary[2] at runtime.\n\tsplit(\"Line 1:Line 2\", ary, \":\")\n\n\t# Pass to f().\n\tf(ary[1], ary[2], ary[3])\n}\n", "language": "AWK" }, { "code": "function g(len, ary, i) {\n\tfor (i = 1; i <= len; i++) print ary[i];\n}\n\nBEGIN {\n\tc = split(\"Line 1:Line 2:Next line is empty::Last line\", a, \":\")\n\tg(c, a)\t\t# Pass a[1] = \"Line 1\", a[4] = \"\", ...\n\n}\n", "language": "AWK" }, { "code": "' Variadic functions\nOPTION BASE 1\nSUB demo (VAR arg$ SIZE argc)\n LOCAL x\n PRINT \"Amount of incoming arguments: \", argc\n FOR x = 1 TO argc\n PRINT arg$[x]\n NEXT\nEND SUB\n\n' No argument\ndemo(0)\n' One argument\ndemo(\"abc\")\n' Three arguments\ndemo(\"123\", \"456\", \"789\")\n", "language": "BaCon" }, { "code": "SUB printAll cdecl (count As Integer, ... )\n DIM arg AS Any Ptr\n DIM i AS Integer\n\n arg = va_first()\n FOR i = 1 To count\n PRINT va_arg(arg, Double)\n arg = va_next(arg, Double)\n NEXT i\nEND SUB\n\nprintAll 3, 3.1415, 1.4142, 2.71828\n", "language": "BASIC" }, { "code": "@echo off\n\n:_main\ncall:_variadicfunc arg1 \"arg 2\" arg-3\npause>nul\n\n:_variadicfunc\nsetlocal\nfor %%i in (%*) do echo %%~i\nexit /b\n\n:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain:\n:: @for %%i in (%*) do echo %%i\n", "language": "Batch-File" }, { "code": "/* Version a */\ndefine f(a[], l) {\n auto i\n for (i = 0; i < l; i++) a[i]\n}\n\n/* Version b */\ndefine g(a[]) {\n auto i\n for (i = 0; a[i] != -1; i++) a[i]\n}\n\n/* Version c */\ndefine h(a[]) {\n auto i\n\n for (i = 1; i <= a[0]; i++) a[i]\n}\n", "language": "Bc" }, { "code": "get \"libhdr\"\n\n// A, B, C, etc are dummy arguments. If more are needed, more can be added.\n// Eventually you will run into the compiler limit.\nlet foo(num, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) be\n // The arguments can be indexed starting from the first one.\n for i=1 to num do writef(\"%S*N\", (@num)!i)\n\n// You can pass as many arguments as you want. The declaration above guarantees\n// that at least the first 16 arguments (including the number) will be available,\n// but you certainly needn't use them all.\nlet start() be\n foo(5, \"Mary\", \"had\", \"a\", \"little\", \"lamb\")\n", "language": "BCPL" }, { "code": "Fun1 ← •Show¨\nFun2 ← {•Show¨𝕩}\nFun3 ← { 1=≠𝕩 ? •Show 𝕩; \"too many arguments \" ! 𝕩}\n", "language": "BQN" }, { "code": "#include <stdio.h>\n#include <stdarg.h>\n\nvoid varstrings(int count, ...) /* the ellipsis indicates variable arguments */\n{\n va_list args;\n va_start(args, count);\n while (count--)\n puts(va_arg(args, const char *));\n va_end(args);\n}\n\nvarstrings(5, \"Mary\", \"had\", \"a\", \"little\", \"lamb\");\n", "language": "C" }, { "code": "#include <iostream>\n\ntemplate<typename T>\n void print(T const& t)\n{\n std::cout << t;\n}\n\ntemplate<typename First, typename ... Rest>\n void print(First const& first, Rest const& ... rest)\n{\n std::cout << first;\n print(rest ...);\n}\n\nint main()\n{\n int i = 10;\n std::string s = \"Hello world\";\n print(\"i = \", i, \" and s = \\\"\", s, \"\\\"\\n\");\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program {\n static void Main(string[] args) {\n PrintAll(\"test\", \"rosetta code\", 123, 5.6);\n }\n\n static void PrintAll(params object[] varargs) {\n foreach (var i in varargs) {\n Console.WriteLine(i);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn foo [& args]\n (doseq [a args]\n (println a)))\n\n(foo :bar :baz :quux)\n(apply foo [:bar :baz :quux])\n", "language": "Clojure" }, { "code": " program-id. dsp-str is external.\n data division.\n linkage section.\n 1 cnt comp-5 pic 9(4).\n 1 str pic x.\n procedure division using by value cnt\n by reference str delimited repeated 1 to 5.\n end program dsp-str.\n\n program-id. variadic.\n procedure division.\n call \"dsp-str\" using 4 \"The\" \"quick\" \"brown\" \"fox\"\n stop run\n .\n end program variadic.\n\n program-id. dsp-str.\n data division.\n working-storage section.\n 1 i comp-5 pic 9(4).\n 1 len comp-5 pic 9(4).\n 1 wk-string pic x(20).\n linkage section.\n 1 cnt comp-5 pic 9(4).\n 1 str1 pic x(20).\n 1 str2 pic x(20).\n 1 str3 pic x(20).\n 1 str4 pic x(20).\n 1 str5 pic x(20).\n procedure division using cnt str1 str2 str3 str4 str5.\n if cnt < 1 or > 5\n display \"Invalid number of parameters\"\n stop run\n end-if\n perform varying i from 1 by 1\n until i > cnt\n evaluate i\n when 1\n unstring str1 delimited low-value\n into wk-string count in len\n when 2\n unstring str2 delimited low-value\n into wk-string count in len\n when 3\n unstring str3 delimited low-value\n into wk-string count in len\n when 4\n unstring str4 delimited low-value\n into wk-string count in len\n when 5\n unstring str5 delimited low-value\n into wk-string count in len\n end-evaluate\n display wk-string (1:len)\n end-perform\n exit program\n .\n end program dsp-str.\n", "language": "COBOL" }, { "code": "(defun example (&rest args)\n (dolist (arg args)\n (print arg)))\n\n(example \"Mary\" \"had\" \"a\" \"little\" \"lamb\")\n\n(let ((args '(\"Mary\" \"had\" \"a\" \"little\" \"lamb\")))\n (apply #'example args))\n", "language": "Common-Lisp" }, { "code": "Fixpoint Arity (A B: Set) (n: nat): Set := match n with\n|O => B\n|S n' => A -> (Arity A B n')\nend.\n", "language": "Coq" }, { "code": "Definition nat_twobools (n: nat) := Arity nat (Arity bool nat (2*n)) n.\n", "language": "Coq" }, { "code": "Require Import List.\nFixpoint build_list_aux {A: Set} (acc: list A) (n : nat): Arity A (list A) n := match n with\n|O => acc\n|S n' => fun (val: A) => build_list_aux (acc ++ (val :: nil)) n'\nend.\n", "language": "Coq" }, { "code": "Definition build_list {A: Set} := build_list_aux (@nil A).\n", "language": "Coq" }, { "code": "Check build_list 5 1 2 5 90 42.\n", "language": "Coq" }, { "code": "Lemma transparent_plus_zero: forall n, n + O = n.\nintros n; induction n.\n- reflexivity.\n- simpl; rewrite IHn; trivial.\nDefined.\n\nLemma transparent_plus_S: forall n m, n + S m = S n + m .\nintros n; induction n; intros m.\n- reflexivity.\n- simpl; f_equal; rewrite IHn; reflexivity.\nDefined.\n", "language": "Coq" }, { "code": "Require Import Vector.\n\nDefinition build_vector_aux {A: Set} (n: nat): forall (size_acc : nat) (acc: t A size_acc), Arity A (t A (size_acc + n)) n.\ninduction n; intros size_acc acc.\n- rewrite transparent_plus_zero; apply acc. (*Just one argument, return the accumulator*)\n- intros val. rewrite transparent_plus_S. apply IHn. (*Here we use the induction hypothesis. We just have to build the new accumulator*)\n apply shiftin; [apply val | apply acc]. (*Shiftin adds a term at the end of a vector*)\n", "language": "Coq" }, { "code": "Definition build_vector {A: Set} (n: nat) := build_vector_aux n O (@nil A).\n", "language": "Coq" }, { "code": "Require Import String.\nEval compute in build_vector 4 \"Hello\" \"how\" \"are\" \"you\".\n", "language": "Coq" }, { "code": "import std.stdio, std.algorithm;\n\nvoid printAll(TyArgs...)(TyArgs args) {\n foreach (el; args)\n el.writeln;\n}\n\n// Typesafe variadic function for dynamic array\nvoid showSum1(int[] items...) {\n items.sum.writeln;\n}\n\n// Typesafe variadic function for fixed size array\nvoid showSum2(int[4] items...) {\n items[].sum.writeln;\n}\n\nvoid main() {\n printAll(4, 5.6, \"Rosetta\", \"Code\", \"is\", \"awesome\");\n writeln;\n showSum1(1, 3, 50);\n showSum2(1, 3, 50, 10);\n}\n", "language": "D" }, { "code": "func printAll(args...) {\n for i in args {\n print(i)\n }\n}\n\nprintAll(\"test\", \"rosetta code\", 123, 5.6)\n", "language": "Dyalect" }, { "code": "def example {\n match [`run`, args] {\n for x in args {\n println(x)\n }\n }\n}\n\nexample(\"Mary\", \"had\", \"a\", \"little\", \"lamb\")\n\nE.call(example, \"run\", [\"Mary\", \"had\", \"a\", \"little\", \"lamb\"])\n", "language": "E" }, { "code": "def non_example {\n to run(x, y) {\n println(x)\n println(y)\n }\n}\n", "language": "E" }, { "code": "def non_example(x, y) {\n println(x)\n println(y)\n}\n", "language": "E" }, { "code": "module VariadicFunction {\n void show(String[] strings) {\n @Inject Console console;\n strings.forEach(s -> console.print(s));\n }\n\n void run() {\n show([\"hello\", \"world\"]);\n\n String s1 = \"not\";\n String s2 = \"a\";\n String s3 = \"constant\";\n String s4 = \"literal\";\n show([s1, s2, s3, s4]);\n }\n}\n", "language": "Ecstasy" }, { "code": "[ X Y -> \"two\" | X -> \"one\" | -> \"zero\" ]\n", "language": "Egel" }, { "code": "import system'routines;\nimport extensions;\n\nextension variadicOp\n{\n printAll(params object[] list)\n {\n for(int i := 0; i < list.Length; i++)\n {\n self.printLine(list[i])\n }\n }\n}\n\npublic program()\n{\n console.printAll(\"test\", \"rosetta code\", 123, 5.6r)\n}\n", "language": "Elena" }, { "code": "defmodule RC do\n def print_each( arguments ) do\n Enum.each(arguments, fn x -> IO.inspect x end)\n end\nend\n\nRC.print_each([1,2,3])\nRC.print_each([\"Mary\", \"had\", \"a\", \"little\", \"lamb\"])\n", "language": "Elixir" }, { "code": "(defun my-print-args (&rest arg-list)\n (message \"there are %d argument(s)\" (length arg-list))\n (dolist (arg arg-list)\n (message \"arg is %S\" arg)))\n\n(my-print-args 1 2 3)\n", "language": "Emacs-Lisp" }, { "code": "(let ((arg-list '(\"some thing %d %d %d\" 1 2 3)))\n (apply 'message arg-list))\n", "language": "Emacs-Lisp" }, { "code": "^|EMal supports variadic functions in more than one way|^\nfun print = void by text mode, List args do\n writeLine(\"== \" + mode + \" ==\")\n for each var arg in args do writeLine(arg) end\nend\nfun printArgumentsList = void by List args\n print(\"accepting a list\", args)\nend\nfun printArgumentsUnchecked = void by some var args\n print(\"unchecked variadic\", args)\nend\nfun printArgumentsChecked = void by text subject, logic isTrue, int howMany, some text values\n print(\"checked variadic\", var[subject, isTrue, howMany, +values]) # unary plus on lists does list expansion\nend\nprintArgumentsList(var[\"These are the \", true, 7, \"seas\", \"of\", \"Rhye\"])\nprintArgumentsUnchecked(\"These are the \", true, 7, \"seas\", \"of\", \"Rhye\")\nprintArgumentsChecked(\"These are the \", true, 7, \"seas\", \"of\", \"Rhye\")\n", "language": "EMal" }, { "code": "print_each( Arguments ) -> [io:fwrite( \"~p~n\", [X]) || X <- Arguments].\n", "language": "Erlang" }, { "code": ">function allargs () ...\n$ loop 1 to argn();\n$ args(#),\n$ end\n$endfunction\n>allargs(1,3,\"Test\",1:2)\n 1\n 3\n Test\n [ 1 2 ]\n>function args test (x) := {x,x^2,x^3}\n>allargs(test(4))\n 4\n 16\n 64\n", "language": "Euler" }, { "code": "procedure print_args(sequence args)\n for i = 1 to length(args) do\n puts(1,args[i])\n puts(1,' ')\n end for\nend procedure\n\nprint_args({\"Mary\", \"had\", \"a\", \"little\", \"lamb\"})\n", "language": "Euphoria" }, { "code": "// Variadic function. Nigel Galloway: March 6th., 2024\nopen System\ntype X()=static member F([<ParamArray>] args: Object[]) = args|>Array.iter(printfn \"%A\")\nX.F(23, 3.142, \"Nigel\", 1u, true)\n", "language": "F-Sharp" }, { "code": "MACRO: variadic-print ( n -- quot ) [ print ] n*quot ;\n", "language": "Factor" }, { "code": "IN: scratchpad \"apple\" \"banana\" \"cucumber\"\n\n--- Data stack:\n\"apple\"\n\"banana\"\n\"cucumber\"\n\nIN: scratchpad 2 variadic-print\ncucumber\nbanana\n\n--- Data stack:\n\"apple\"\n", "language": "Factor" }, { "code": ": sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ;\n4 3 2 1 4 sum . \\ 10\n", "language": "Forth" }, { "code": ": .stack ( -- ) depth 0 ?do i pick . loop ;\n", "language": "Forth" }, { "code": "program varargs\n\n integer, dimension(:), allocatable :: va\n integer :: i\n\n ! using an array (vector) static\n call v_func()\n call v_func( (/ 100 /) )\n call v_func( (/ 90, 20, 30 /) )\n\n ! dynamically creating an array of 5 elements\n allocate(va(5))\n va = (/ (i,i=1,5) /)\n call v_func(va)\n deallocate(va)\n\ncontains\n\n subroutine v_func(arglist)\n integer, dimension(:), intent(in), optional :: arglist\n\n integer :: i\n\n if ( present(arglist) ) then\n do i = lbound(arglist, 1), ubound(arglist, 1)\n print *, arglist(i)\n end do\n else\n print *, \"no argument at all\"\n end if\n end subroutine v_func\n\nend program varargs\n", "language": "Fortran" }, { "code": "program variadicRoutinesDemo(input, output, stdErr);\n{$mode objFPC}\n\n// array of const is only supported in $mode objFPC or $mode Delphi\nprocedure writeLines(const arguments: array of const);\nvar\n\targument: TVarRec;\nbegin\n\t// inside the body `array of const` is equivalent to `array of TVarRec`\n\tfor argument in arguments do\n\tbegin\t\n\t\twith argument do\n\t\tbegin\n\t\t\tcase vType of\n\t\t\t\tvtInteger:\n\t\t\t\tbegin\n\t\t\t\t\twriteLn(vInteger);\n\t\t\t\tend;\n\t\t\t\tvtBoolean:\n\t\t\t\tbegin\n\t\t\t\t\twriteLn(vBoolean);\n\t\t\t\tend;\n\t\t\t\tvtChar:\n\t\t\t\tbegin\n\t\t\t\t\twriteLn(vChar);\n\t\t\t\tend;\n\t\t\t\tvtAnsiString:\n\t\t\t\tbegin\n\t\t\t\t\twriteLn(ansiString(vAnsiString));\n\t\t\t\tend;\n\t\t\t\t// and so on\n\t\t\tend;\n\t\tend;\n\tend;\nend;\n\nbegin\n\twriteLines([42, 'is', true, #33]);\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "42\nis\nTRUE\n!\n", "language": "Free-Pascal-Lazarus" }, { "code": "' version 15-09-2015\n' compile with: fbc -s console\n\nSub printAll_string Cdecl (count As Integer, ... )\n Dim arg As Any Ptr\n Dim i As Integer\n\n arg = va_first()\n For i = 1 To count\n Print *Va_Arg(arg, ZString Ptr)\n arg = va_next(arg, ZString Ptr)\n Next i\nEnd Sub\n\n' ------=< MAIN >=------\n' direct\nprintAll_string (5, \"Foxtrot\", \"Romeo\", \"Echo\", \"Echo\", \"BASIC\")\n\n' strings\nPrint : Print\nDim As String a = \"one\", b = \"two\", c = \"three\"\nprintAll_string (3, a, b, c)\n\n' count is smaller then the number of arguments, no problem\nPrint : Print\nprintAll_string (1, a, b, c)\n\n' count is greater then the number of arguments\n' after the last valid argument garbage is displayed\n' should be avoided, could lead to disaster\nPrint : Print\nprintAll_string (4, a, b, c)\nPrint\n\n' empty keyboard buffer\nWhile InKey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "100 DEF PROC printAll DATA\n110 DO UNTIL ITEM()=0\n120 IF ITEM()=1 THEN\n READ a$\n PRINT a$\n130 ELSE\n READ num\n PRINT num\n140 LOOP\n150 END PROC\n\n200 printAll 3.1415, 1.4142, 2.71828\n210 printAll \"Mary\", \"had\", \"a\", \"little\", \"lamb\",\n", "language": "FreeBASIC" }, { "code": "void local fn Function1( count as long, ... )\n va_list ap\n long value\n\n va_start( ap, count )\n while ( count )\n value = fn va_argLong( ap )\n printf @\"%ld\",value\n count--\n wend\n\n va_end( ap )\nend fn\n\nvoid local fn Function2( obj as CFTypeRef, ... )\n va_list ap\n\n va_start( ap, obj )\n while ( obj )\n printf @\"%@\",obj\n obj = fn va_argObj(ap)\n wend\n\n va_end( ap )\nend fn\n\nwindow 1\n\n// params: num of args, 1st arg, 2nd arg, etc.\nfn Function1( 3, 987, 654, 321 )\n\nprint\n\n// params: 1st arg, 2nd arg, ..., NULL\nfn Function2( @\"One\", @\"Two\", @\"Three\", @\"O'Leary\", NULL )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "func printAll(things ... string) {\n // it's as if you declared \"things\" as a []string, containing all the arguments\n for _, x := range things {\n fmt.Println(x)\n }\n}\n", "language": "Go" }, { "code": "args := []string{\"foo\", \"bar\"}\nprintAll(args...)\n", "language": "Go" }, { "code": "#!/usr/bin/env golosh\n----\nThis module demonstrates variadic functions.\n----\nmodule Variadic\n\nimport gololang.Functions\n\n----\nVarargs have the three dots after them just like Java.\n----\nfunction varargsFunc = |args...| {\n foreach arg in args {\n println(arg)\n }\n}\n\nfunction main = |args| {\n\n varargsFunc(1, 2, 3, 4, 5, \"against\", \"one\")\n\n # to call a variadic function with an array we use the unary function\n unary(^varargsFunc)(args)\n}\n", "language": "Golo" }, { "code": "def printAll( Object[] args) { args.each{ arg -> println arg } }\n\nprintAll(1, 2, \"three\", [\"3\", \"4\"])\n", "language": "Groovy" }, { "code": "class PrintAllType t where\n process :: [String] -> t\n\ninstance PrintAllType (IO a) where\n process args = do mapM_ putStrLn args\n return undefined\n\ninstance (Show a, PrintAllType r) => PrintAllType (a -> r) where\n process args = \\a -> process (args ++ [show a])\n\nprintAll :: (PrintAllType t) => t\nprintAll = process []\n\nmain :: IO ()\nmain = do printAll 5 \"Mary\" \"had\" \"a\" \"little\" \"lamb\"\n printAll 4 3 5\n printAll \"Rosetta\" \"Code\" \"Is\" \"Awesome!\"\n", "language": "Haskell" }, { "code": "{-# LANGUAGE GADTs #-}\n...\n\ninstance a ~ () => PrintAllType (IO a) where\n process args = do mapM_ putStrLn args\n\n...\n", "language": "Haskell" }, { "code": "procedure main ()\n varargs(\"some\", \"extra\", \"args\")\n write()\n varargs ! [\"a\",\"b\",\"c\",\"d\"]\nend\n\nprocedure varargs(args[])\n every write(!args)\nend\n", "language": "Icon" }, { "code": "(function f\n (print (join \"\\n\" args)))\n\n(f 1 2 3 4)\n", "language": "Insitux" }, { "code": "printAll := method(call message arguments foreach(println))\n", "language": "Io" }, { "code": " A=:2\n B=:3\n C=:5\n sum=:+/\n sum 1,A,B,4,C\n15\n", "language": "J" }, { "code": " commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. \":each\n commaAnd 'dog';A;B;'cat';C\ndog, 2, 3, cat and 5\n", "language": "J" }, { "code": " echo&>'dog';A;B;'cat';C\ndog\n2\n3\ncat\n5\n", "language": "J" }, { "code": "public static void printAll(Object... things){\n // \"things\" is an Object[]\n for(Object i:things){\n System.out.println(i);\n }\n}\n", "language": "Java" }, { "code": "printAll(4, 3, 5, 6, 4, 3);\nprintAll(4, 3, 5);\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n", "language": "Java" }, { "code": "Object[] args = {\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"};\nprintAll(args);\n", "language": "Java" }, { "code": "Object[] args = {\"Rosetta\", \"Code\", \"Is\", \"Awesome,\"};\nprintAll(args, \"Dude!\");//does not print \"Rosetta Code Is Awesome, Dude!\"\n//instead prints the type and hashcode for args followed by \"Dude!\"\n", "language": "Java" }, { "code": "printAll((Object)args);\n", "language": "Java" }, { "code": "function printAll() {\n for (var i=0; i<arguments.length; i++)\n print(arguments[i])\n}\nprintAll(4, 3, 5, 6, 4, 3);\nprintAll(4, 3, 5);\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n", "language": "JavaScript" }, { "code": "args = [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"]\nprintAll.apply(null, args)\n", "language": "JavaScript" }, { "code": "let\n fix = // Variant of the applicative order Y combinator\n f => (f => f(f))(g => f((...a) => g(g)(...a))),\n forAll =\n f =>\n fix(\n z => (a,...b) => (\n (a === void 0)\n ||(f(a), z(...b)))),\n printAll = forAll(print);\n\nprintAll(0,1,2,3,4,5);\nprintAll(6,7,8);\n(f => a => f(...a))(printAll)([9,10,11,12,13,14]);\n// 0\n// 1\n// 2\n// 3\n// 4\n// 5\n// 6\n// 7\n// 8\n// 9\n// 10\n// 11\n// 12\n// 13\n// 14\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // show :: a -> String\n const show = x => JSON.stringify(x, null, 2);\n\n // printAll [any] -> String\n const printAll = (...a) => a.map(show)\n .join('\\n');\n\n return printAll(1, 2, 3, 2 + 2, \"five\", 6);\n})();\n", "language": "JavaScript" }, { "code": "def demo: .[];\n", "language": "Jq" }, { "code": "args | demo\n", "language": "Jq" }, { "code": "[\"cheese\"] + [3.14] + [[range(0;3)]] | demo\n", "language": "Jq" }, { "code": "\"cheese\"\n3.14\n[0,1,2]\n", "language": "Jq" }, { "code": "# arity-0:\ndef f: \"I have no arguments\";\n\n# arity-1:\ndef f(a1): a1;\n\n# arity-1:\ndef f(a1;a2): a1,a2;\n\ndef f(a1;a2;a3): a1,a2,a3;\n\n# Example:\nf, f(1), f(2;3), f(4;5;6)\n", "language": "Jq" }, { "code": "1\n2\n3\n4\n5\n6\n", "language": "Jq" }, { "code": "julia> print_each(X...) = for x in X; println(x); end\n\njulia> print_each(1, \"hello\", 23.4)\n1\nhello\n23.4\n", "language": "Julia" }, { "code": "julia> args = [ \"first\", (1,2,17), \"last\" ]\n3-element Array{Any,1}:\n \"first\"\n (1,2,17)\n \"last\n\njulia> print_each(args...)\nfirst\n(1,2,17)\nlast\n", "language": "Julia" }, { "code": ":varfunc\n 1 tolist flatten\n len [\n get print nl\n ] for\n drop\n;\n\n\"Enter any number of words separated by space: \" input nl\nstklen [split varfunc nl] if\n\nnl \"End \" input\n", "language": "Klingphix" }, { "code": "// version 1.1\n\nfun variadic(vararg va: String) {\n for (v in va) println(v)\n}\n\nfun main(args: Array<String>) {\n variadic(\"First\", \"Second\", \"Third\")\n println(\"\\nEnter four strings for the function to print:\")\n val va = Array(4) { \"\" }\n for (i in 1..4) {\n print(\"String $i = \")\n va[i - 1] = readLine()!!\n }\n println()\n variadic(*va)\n}\n", "language": "Kotlin" }, { "code": "#!/bin/ksh\n\n# Variadic function\n\n#\t# Variables:\n#\ntypeset -a arr=( 0 2 4 6 8 )\n\n#\t# Functions:\n#\nfunction _variadic {\n\twhile [[ -n $1 ]]; do\n\t\tprint $1\n\t\tshift\n\tdone\n}\n\n ######\n# main #\n ######\n\n_variadic Mary had a little lamb\necho\n_variadic ${arr[@]}\n", "language": "Ksh" }, { "code": "{def foo\n {lambda {:s} // :s will get any sequence of words\n {S.first :s}\n {if {S.empty? {S.rest :s}} then else {foo {S.rest :s}}}}}\n-> foo\n\n{foo hello brave new world}\n-> hello brave new world\n\n{foo {S.serie 1 10}}\n-> 1 2 3 4 5 6 7 8 9 10\n", "language": "Lambdatalk" }, { "code": "fp.printAll = (&values...) -> {\n\tfn.arrayForEach(&values, fn.println)\n}\n\nfp.printAll(1, 2, 3)\n# 1\n# 2\n# 3\n\nfp.printAll() # No output\n\nfp.printAll(abc, def, xyz)\n# abc\n# def\n# xyz\n\n# Array un-packing\n&arr $= [1, abc, xyz, 42.42f]\nfp.printAll(&arr...)\n# 1\n# abc\n# xyz\n# 42.42\n\nfp.printAll(&arr..., last)\n# 1\n# abc\n# xyz\n# 42.42\n# last\n\nfp.printAll(first, &arr...)\n# first\n# 1\n# abc\n# xyz\n# 42.42\n", "language": "Lang" }, { "code": "fp.printAllComb $= -|fn.combC(fn.arrayForEach, fn.println)\n\nfp.printAllComb(42, 2, abc)\n# 42\n# 2\n# abc\n\nfp.printAllComb() # No output\n\n&arr $= [1, abc, xyz, 42.42f]\nfp.printAllComb(&arr...)\n# 1\n# abc\n# xyz\n# 42.42\n", "language": "Lang" }, { "code": "define printArgs(...items) => stdoutnl(#items)\ndefine printEachArg(...) => with i in #rest do stdoutnl(#i)\n\nprintArgs('a', 2, (:3))\nprintEachArg('a', 2, (:3))\n", "language": "Lasso" }, { "code": "local(args = (:\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"))\nprintEachArg(:#args)\n", "language": "Lasso" }, { "code": "staticarray(a, 2, staticarray(3))\na\n2\nstaticarray(3)\nRosetta\nCode\nIs\nAwesome!\n", "language": "Lasso" }, { "code": "to varargs [:args]\n foreach :args [print ?]\nend\n\n(varargs \"Mary \"had \"a \"little \"lamb)\napply \"varargs [Mary had a little lamb]\n", "language": "Logo" }, { "code": "function varar(...)\n for i, v in ipairs{...} do print(v) end\nend\n", "language": "Lua" }, { "code": "varar(1, \"bla\", 5, \"end\");\n", "language": "Lua" }, { "code": "local runtime_array = {1, \"bla\", 5, \"end\"};\n\nvarar(unpack(runtime_array));\n", "language": "Lua" }, { "code": "Module CheckIt {\n \\\\ Works for numbers and strings (letters in M2000)\n Function Variadic {\n \\\\ print a letter for each type in function stack\n Print Envelope$()\n \\\\Check types using Match\n Print Match(\"NNSNNS\")\n =stack.size\n While not Empty {\n if islet then {print letter$} else print number\n }\n }\n M=Variadic(1,2,\"Hello\",3,4,\"Bye\")\n Print M\n \\\\ K is a poiner to Array\n K=(1,2,\"Hello 2\",3,4,\"Bye 2\")\n \\\\ !K pass all items to function's stack\n M=Variadic(!K)\n}\nCheckit\n\n\nModule CheckIt2 {\n Function Variadic {\n \\\\ [] return a pointer to stack, and leave a new stack as function's stack\n a=[]\n \\\\ a is a pointer to stack\n \\\\ objects just leave a space, and cursor move to next column (spread on lines)\n Print a\n }\n M=Variadic(1,2,\"Hello\",3,4,\"Bye\")\n Print M\n \\\\ K is a poiner to Array\n K=(1,2,\"Hello 2\",3,4,\"Bye 2\")\n \\\\ !K pass all items to function stack\n M=Variadic(!K)\n}\nCheckit2\n", "language": "M2000-Interpreter" }, { "code": "define(`showN',\n `ifelse($1,0,`',`$2\n$0(decr($1),shift(shift($@)))')')dnl\ndefine(`showargs',`showN($#,$@)')dnl\ndnl\nshowargs(a,b,c)\ndnl\ndefine(`x',`1,2')\ndefine(`y',`,3,4,5')\nshowargs(x`'y)\n", "language": "M4" }, { "code": "ShowMultiArg[x___] := Do[Print[i], {i, {x}}]\n", "language": "Mathematica" }, { "code": "ShowMultiArg[]\nShowMultiArg[a, b, c]\nShowMultiArg[5, 3, 1]\n", "language": "Mathematica" }, { "code": "[nothing]\n\na\nb\nc\n\n5\n3\n1\n", "language": "Mathematica" }, { "code": "function variadicFunction(varargin)\n\n for i = (1:numel(varargin))\n disp(varargin{i});\n end\n\nend\n", "language": "MATLAB" }, { "code": ">> variadicFunction(1,2,3,4,'cat')\n 1\n\n 2\n\n 3\n\n 4\n\ncat\n", "language": "MATLAB" }, { "code": "show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$\n\nshow(1, 2, 3, 4);\n\napply(show, [1, 2, 3, 4]);\n\n/* Actually, the built-in function \"disp\" is already what we want */\ndisp(1, 2, 3, 4);\n\napply(disp, [1, 2, 3, 4]);\n", "language": "Maxima" }, { "code": "def print_arg(text t) =\nfor x = t:\n if unknown x: message \"unknown value\"\n elseif numeric x: message decimal x\n elseif string x: message x\n elseif path x: message \"a path\"\n elseif pair x: message decimal (xpart(x)) & \", \" & decimal (ypart(x))\n elseif boolean x: if x: message \"true!\" else: message \"false!\" fi\n elseif pen x: message \"a pen\"\n elseif picture x: message \"a picture\"\n elseif transform x: message \"a transform\" fi; endfor enddef;\n\nprint_arg(\"hello\", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);\nend\n", "language": "Metafont" }, { "code": "MODULE Varargs EXPORTS Main;\n\nIMPORT IO;\n\nVAR strings := ARRAY [1..5] OF TEXT {\"foo\", \"bar\", \"baz\", \"quux\", \"zeepf\"};\n\nPROCEDURE Variable(VAR arr: ARRAY OF TEXT) =\n BEGIN\n FOR i := FIRST(arr) TO LAST(arr) DO\n IO.Put(arr[i] & \"\\n\");\n END;\n END Variable;\n\nBEGIN\n Variable(strings);\nEND Varargs.\n", "language": "Modula-3" }, { "code": "MODULE Varargs EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nVAR\n strings := NEW(REF TEXT);\n ints := NEW(REF INTEGER);\n reals := NEW(REF REAL);\n refarr := ARRAY [1..3] OF REFANY {strings, ints, reals};\n\nPROCEDURE Variable(VAR arr: ARRAY OF REFANY) =\n BEGIN\n FOR i := FIRST(arr) TO LAST(arr) DO\n TYPECASE arr[i] OF\n | REF TEXT(n) => IO.Put(n^ & \"\\n\");\n | REF INTEGER(n) => IO.Put(Fmt.Int(n^) & \"\\n\");\n | REF REAL(n) => IO.Put(Fmt.Real(n^) & \"\\n\");\n ELSE (* skip *)\n END;\n END;\n END Variable;\n\nBEGIN\n strings^ := \"Rosetta\"; ints^ := 1; reals^ := 3.1415;\n Variable(refarr);\nEND Varargs.\n", "language": "Modula-3" }, { "code": "using System;\nusing System.Console;\n\nmodule Variadic\n{\n PrintAll (params args : array[object]) : void\n {\n foreach (arg in args) WriteLine(arg);\n }\n\n Main() : void\n {\n PrintAll(\"test\", \"rosetta code\", 123, 5.6, DateTime.Now);\n }\n}\n", "language": "Nemerle" }, { "code": "proc print(xs: varargs[string, `$`]) =\n for x in xs:\n echo x\n", "language": "Nim" }, { "code": "print(12, \"Rosetta\", \"Code\", 15.54321)\n\nprint 12, \"Rosetta\", \"Code\", 15.54321, \"is\", \"awesome!\"\n\nlet args = @[\"12\", \"Rosetta\", \"Code\", \"15.54321\"]\nprint(args)\n", "language": "Nim" }, { "code": "#include <stdarg.h>\n\nvoid logObjects(id firstObject, ...) // <-- there is always at least one arg, \"nil\", so this is valid, even for \"empty\" list\n{\n va_list args;\n va_start(args, firstObject);\n id obj;\n for (obj = firstObject; obj != nil; obj = va_arg(args, id))\n NSLog(@\"%@\", obj);\n va_end(args);\n}\n\n// This function can be called with any number or type of objects, as long as you terminate it with \"nil\":\nlogObjects(@\"Rosetta\", @\"Code\", @\"Is\", @\"Awesome!\", nil);\nlogObjects(@4, @3, @\"foo\", nil);\n", "language": "Objective-C" }, { "code": "let rec print = function\n | [] -> ()\n | x :: xs -> print_endline x; print xs\n\n(* Or better yet *)\nlet print = List.iter print_endline\n\nlet () =\n print [];\n print [\"hello\"; \"world!\"]\n", "language": "OCaml" }, { "code": "type 'a variadic =\n | Z : unit variadic\n | S : 'a variadic -> (string -> 'a) variadic\n\nlet rec print : type a. a variadic -> a = function\n | Z -> ()\n | S v -> fun x -> Format.printf \"%s\\n\" x; print v\n\nlet () =\n print Z; (* no arguments *)\n print (S Z) \"hello\"; (* one argument *)\n print (S (S (S Z))) \"how\" \"are\" \"you\" (* three arguments *)\n", "language": "OCaml" }, { "code": "type 'a variadic =\n | Z : unit variadic\n | U : 'a variadic -> (unit -> 'a) variadic\n | S : 'a variadic -> (string -> 'a) variadic\n | I : 'a variadic -> (int -> 'a) variadic\n | F : 'a variadic -> (float -> 'a) variadic\n (* Printing of a general type, takes pretty printer as argument *)\n | G : 'a variadic -> (('t -> unit) -> 't -> 'a) variadic\n | L : 'a variadic -> (('t -> unit) -> 't list -> 'a) variadic\n\nlet rec print : type a. a variadic -> a = function\n | Z -> ()\n | U v -> fun () -> Format.printf \"()\\n\"; print v\n | S v -> fun x -> Format.printf \"%s\\n\" x; print v\n | I v -> fun x -> Format.printf \"%d\\n\" x; print v\n | F v -> fun x -> Format.printf \"%f\\n\" x; print v\n | G v -> fun pp x -> pp x; print v\n | L v -> fun pp x -> List.iter pp x; print v\n\nlet () =\n print (S (I (S Z))) \"I am \" 5 \"Years old\";\n print (S (I (S (L (S Z))))) \"I have \" 3 \" siblings aged \" (print (I Z)) [1;3;7]\n", "language": "OCaml" }, { "code": "let print f = f ()\nlet arg value () cont = cont (Format.printf \"%s\\n\" value)\nlet stop a = a\n\nlet () =\n print stop;\n print (arg \"hello\") (arg \"there\") stop;\n\n(* use a prefix operator for arg *)\nlet (!) = arg\n\nlet () =\n print !\"hello\" !\"hi\" !\"its\" !\"me\" stop\n", "language": "OCaml" }, { "code": "type ('f,'g) t =\n | Z : ('f,'f) t\n | S : 'a -> (('a -> 'f), ('f,'g) t -> 'g) t\n\nlet rec apply: type f g. f -> (f,g) t -> g =\n fun k t -> match t with\n | Z -> k (* type g = f *)\n | S x -> apply (k x) (* type g = (f,g) t -> g *)\n\nlet (!) x = S x (* prefix *)\n\n(* top level *)\n# apply List.map !(fun x -> x+1) ![1;2;3] Z\n", "language": "OCaml" }, { "code": ": sumNum(n) | i | 0 n loop: i [ + ] ;\n", "language": "Oforth" }, { "code": "declare\n class Demo from BaseObject\n meth test(...)=Msg\n {Record.forAll Msg Show}\n end\n end\n\n D = {New Demo noop}\n Constructed = {List.toTuple test {List.number 1 10 1}}\nin\n {D test(1 2 3 4)}\n {D Constructed}\n", "language": "Oz" }, { "code": "f(a[..])=for(i=1,#a,print(a[i]))\n", "language": "PARI-GP" }, { "code": "call(f, v)\n", "language": "PARI-GP" }, { "code": "sub print_all {\n foreach (@_) {\n print \"$_\\n\";\n }\n}\n", "language": "Perl" }, { "code": "print_all(4, 3, 5, 6, 4, 3);\nprint_all(4, 3, 5);\nprint_all(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n", "language": "Perl" }, { "code": "@args = (\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\nprint_all(@args);\n", "language": "Perl" }, { "code": "use 5.020;\nuse experimental 'signatures';\n", "language": "Perl" }, { "code": "sub print ($x, $y) {\n say $x, \"\\n\", $y;\n}\n", "language": "Perl" }, { "code": "sub print_many ($first, $second, @rest) {\n say \"First: $first\\n\"\n .\"Second: $second\\n\"\n .\"And the rest: \"\n . join(\"\\n\", @rest);\n}\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">print_args</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">args</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">print_args</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #008000;\">\"Mary\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"had\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"a\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"little\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"lamb\"</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "def varfunc\n\t1 tolist flatten\n\tlen for\n\t\tget print nl\n\tendfor\t\nenddef\n\n\n\"Mary\" \"had\" \"a\" \"little\" \"lamb\" 5 tolist varfunc\n", "language": "Phixmonti" }, { "code": "<?php\nfunction printAll() {\n foreach (func_get_args() as $x) // first way\n echo \"$x\\n\";\n\n $numargs = func_num_args(); // second way\n for ($i = 0; $i < $numargs; $i++)\n echo func_get_arg($i), \"\\n\";\n}\nprintAll(4, 3, 5, 6, 4, 3);\nprintAll(4, 3, 5);\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n?>\n", "language": "PHP" }, { "code": "<?php\n$args = array(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\ncall_user_func_array('printAll', $args);\n?>\n", "language": "PHP" }, { "code": "<?php\nfunction printAll(...$things) {\n foreach ($things as $x)\n echo \"$x\\n\";\n}\nprintAll(4, 3, 5, 6, 4, 3);\nprintAll(4, 3, 5);\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n?>\n", "language": "PHP" }, { "code": "<?php\n$args = [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"];\nprintAll(...$args);\n?>\n", "language": "PHP" }, { "code": "(de varargs @\n (while (args)\n (println (next)) ) )\n", "language": "PicoLisp" }, { "code": "(de varargs (Arg1 Arg2 . @)\n (println Arg1)\n (println Arg2)\n (while (args)\n (println (next)) ) )\n", "language": "PicoLisp" }, { "code": "(varargs 'a 123 '(d e f) \"hello\")\n", "language": "PicoLisp" }, { "code": "(apply varargs '(a 123 (d e f) \"hello\"))\n", "language": "PicoLisp" }, { "code": "/* PL/I permits optional arguments, but not an infinitely varying */\n/* argument list: */\ns: procedure (a, b, c, d);\n declare (a, b, c, d) float optional;\n if ^omitted(a) then put skip list (a);\n if ^omitted(b) then put skip list (b);\n if ^omitted(c) then put skip list (c);\n if ^omitted(d) then put skip list (d);\nend s;\n", "language": "PL-I" }, { "code": "Call [dll name] [dll function] with [a value] and [another value].\n", "language": "Plain-English" }, { "code": "function print_all {\n foreach ($x in $args) {\n Write-Host $x\n }\n}\n", "language": "PowerShell" }, { "code": "print_all 1 2 'foo'\n", "language": "PowerShell" }, { "code": "$array = 1,2,'foo'\nInvoke-Expression \"& print_all $array\"\n", "language": "PowerShell" }, { "code": "print_all @array\n", "language": "PowerShell" }, { "code": "printAll( List ) :- forall( member(X,List), (write(X), nl)).\n", "language": "Prolog" }, { "code": "execute( Term ) :-\n Term =.. [F | Args],\n forall( member(X,Args), (G =.. [F,X], G, nl) ).\n", "language": "Prolog" }, { "code": "def print_all(*things):\n for x in things:\n print x\n", "language": "Python" }, { "code": "print_all(4, 3, 5, 6, 4, 3)\nprint_all(4, 3, 5)\nprint_all(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\")\n", "language": "Python" }, { "code": "args = [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"]\nprint_all(*args)\n", "language": "Python" }, { "code": ">>> def printargs(*positionalargs, **keywordargs):\n\tprint \"POSITIONAL ARGS:\\n \" + \"\\n \".join(repr(x) for x in positionalargs)\n\tprint \"KEYWORD ARGS:\\n \" + '\\n '.join(\n\t\t\"%r = %r\" % (k,v) for k,v in keywordargs.iteritems())\n\n\t\n>>> printargs(1,'a',1+0j, fee='fi', fo='fum')\nPOSITIONAL ARGS:\n 1\n 'a'\n (1+0j)\nKEYWORD ARGS:\n 'fee' = 'fi'\n 'fo' = 'fum'\n>>> alist = [1,'a',1+0j]\n>>> adict = {'fee':'fi', 'fo':'fum'}\n>>> printargs(*alist, **adict)\nPOSITIONAL ARGS:\n 1\n 'a'\n (1+0j)\nKEYWORD ARGS:\n 'fee' = 'fi'\n 'fo' = 'fum'\n>>>\n", "language": "Python" }, { "code": "(define varargs-func\n A -> (print A))\n\n(define varargs\n [varargs | Args] -> [varargs-func [list | Args]]\n A -> A)\n\n(sugar in varargs 1)\n", "language": "Qi" }, { "code": "[ pack witheach\n [ echo$ cr ] ] is counted-echo$ ( $ ... n --> )\n\n[ this ] is marker ( --> m )\n\n[ []\n [ swap dup marker oats\n iff drop done\n nested swap join\n again ] ] is gather ( m x ... --> [ )\n\n[ gather witheach\n [ echo$ cr ] ] is markered-echo$ ( m $ ... --> )\n\n\n$ \"this\" $ \"is\" $ \"a\" $ \"formica\" $ \"table\" 5 counted-echo$\ncr\nmarker $ \"green\" $ \"is\" $ \"its\" $ \"colour\" markered-echo$\n", "language": "Quackery" }, { "code": " printallargs1 <- function(...) list(...)\n printallargs1(1:5, \"abc\", TRUE)\n# [[1]]\n# [1] 1 2 3 4 5\n#\n# [[2]]\n# [1] \"abc\"\n#\n# [[3]]\n# [1] TRUE\n", "language": "R" }, { "code": " printallargs2 <- function(...)\n {\n args <- list(...)\n lapply(args, print)\n invisible()\n }\n printallargs2(1:5, \"abc\", TRUE)\n# [1] 1 2 3 4 5\n# [1] \"abc\"\n# [1] TRUE\n", "language": "R" }, { "code": "arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE)\ndo.call(mean, arglist)\n", "language": "R" }, { "code": "-> (define (vfun . xs) (for-each displayln xs))\n-> (vfun)\n-> (vfun 1)\n1\n-> (vfun 1 2 3 4)\n1\n2\n3\n4\n-> (apply vfun (range 10 15))\n10\n11\n12\n13\n14\n", "language": "Racket" }, { "code": "sub foo {\n .say for @_;\n say .key, ': ', .value for %_;\n}\n\nfoo 1, 2, command => 'buckle my shoe',\n 3, 4, order => 'knock at the door';\n", "language": "Raku" }, { "code": "sub foo (*@positional, *%named) {\n .say for @positional;\n say .key, ': ', .value for %named;\n}\n", "language": "Raku" }, { "code": "foo |@ary, |%hsh;\n", "language": "Raku" }, { "code": "SUBI printAll (...)\n FOR i = 1 TO ParamValCount\n\tPRINT ParamVal(i)\n NEXT i\n FOR i = 1 TO ParamStrCount\n\tPRINT ParamStr$(i)\n NEXT i\nEND SUBI\n\nprintAll 4, 3, 5, 6, 4, 3\nprintAll 4, 3, 5\nprintAll \"Rosetta\", \"Code\", \"Is\", \"Awesome!\"\n", "language": "RapidQ" }, { "code": "Sub PrintArgs(ParamArray Args() As String)\n For i As Integer = 0 To Ubound(Args)\n Print(Args(i))\n Next\nEnd Sub\n", "language": "REALbasic" }, { "code": "PrintArgs(\"Hello\", \"World!\", \"Googbye\", \"World!\")\n", "language": "REALbasic" }, { "code": "REBOL [\n\tTitle: \"Variadic Arguments\"\n]\n\nprint-all: func [\n args [block!] {the arguments to print}\n] [\n foreach arg args [print arg]\n]\n\nprint-all [rebol works this way]\n", "language": "REBOL" }, { "code": "print_all: procedure /* [↓] is the # of args passed.*/\n do j=1 for arg()\n say arg(j)\n end /*j*/\nreturn\n", "language": "REXX" }, { "code": "print_all: procedure /* [↓] is the # of args passed.*/\n do j=1 for arg()\n say '[argument' j\"]: \" arg(j)\n end /*j*/\nreturn\n", "language": "REXX" }, { "code": "call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 8 || 9, 'seven numbers are prime, 8th is null'\n\ncall print_all \"One ringy-dingy,\",\n \"two ringy-dingy,\",\n \"three ringy-dingy...\",\n \"Hello? This is Ma Bell.\",\n \"Have you been misusing your instrument?\",\n \"(Lily Tomlin routine)\"\n\n /* [↑] example showing multi-line arguments.*/\n", "language": "REXX" }, { "code": "/* REXX */\nlist=''\nDo i=1 To 6\n list=list||'\"arg\"'i','\n End\nlist=list||'\"end\"'\nInterpret 'call show' list\nExit\nshow: procedure\ndo j=1 for arg()\n say arg(j)\n end /*j*/\nreturn\n", "language": "REXX" }, { "code": "# Project : Variadic function\n\nsum([1,2])\nsum([1,2,3])\nnums = [1,2,3,4]\nsum(nums)\n\nfunc sum(nums)\n total = 0\n for num = 1 to len(nums)\n total = total + num\n next\n showarray(nums)\n see \" \" + total + nl\n\nfunc showarray(vect)\n see \"[\"\n svect = \"\"\n for n = 1 to len(vect)\n svect = svect + vect[n] + \" \"\n next\n svect = left(svect, len(svect) - 1)\n see \"\" + svect + \"]\"\n", "language": "Ring" }, { "code": "def print_all(*things)\n puts things\nend\n", "language": "Ruby" }, { "code": "print_all(4, 3, 5, 6, 4, 3)\nprint_all(4, 3, 5)\nprint_all(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\")\n", "language": "Ruby" }, { "code": "args = [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"]\nprint_all(*args)\n", "language": "Ruby" }, { "code": "// 20220106 Rust programming solution\n\nmacro_rules! print_all {\n ($($args:expr),*) => { $( println!(\"{}\", $args); )* }\n}\n\nfn main() {\n print_all!(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n}\n", "language": "Rust" }, { "code": "def printAll(args: Any*) = args foreach println\n", "language": "Scala" }, { "code": "(define (print-all . things)\n (for-each\n (lambda (x) (display x) (newline))\n things))\n", "language": "Scheme" }, { "code": "(define print-all\n (lambda things\n (for-each\n (lambda (x) (display x) (newline))\n things)))\n", "language": "Scheme" }, { "code": "(print-all 4 3 5 6 4 3)\n(print-all 4 3 5)\n(print-all \"Rosetta\" \"Code\" \"Is\" \"Awesome!\")\n", "language": "Scheme" }, { "code": "(define args '(\"Rosetta\" \"Code\" \"Is\" \"Awesome!\"))\n(apply print-all args)\n", "language": "Scheme" }, { "code": "func print_all(*things) {\n things.each { |x| say x };\n}\n", "language": "Sidef" }, { "code": "print_all(4, 3, 5, 6, 4, 3);\nprint_all(4, 3, 5);\nprint_all(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\");\n", "language": "Sidef" }, { "code": "var args = [\"Rosetta\", \"Code\", \"Is\", \"Awesome!\"];\nprint_all(args...);\n", "language": "Sidef" }, { "code": "define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]].\n\nprintAll applyTo: #(4 3 5 6 4 3).\nprintAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!').\n", "language": "Slate" }, { "code": "_@lobby printAll [| *rest | rest do: [| :arg | inform: arg printString]].\nlobby printAll, 4, 3, 5, 6, 4, 3.\nlobby printAll, 'Rosetta', 'Code', 'Is', 'Awesome!'.\n", "language": "Slate" }, { "code": "func printAll<T>(things: T...) {\n // \"things\" is a [T]\n for i in things {\n print(i)\n }\n}\n", "language": "Swift" }, { "code": "printAll(4, 3, 5, 6, 4, 3)\nprintAll(4, 3, 5)\nprintAll(\"Rosetta\", \"Code\", \"Is\", \"Awesome!\")\n", "language": "Swift" }, { "code": "proc print_all {args} {puts [join $args \\n]}\n\nprint_all 4 3 5 6 4 3\nprint_all 4 3 5\nprint_all Rosetta Code Is Awesome!\n\nset things {Rosetta Code Is Awesome!}\n\nprint_all $things ;# ==> incorrect: passes a single argument (a list) to print_all\nprint_all {*}$things ;# ==> correct: passes each element of the list to the procedure\n", "language": "Tcl" }, { "code": "eval [list print_all] [lrange $things 0 end]\n", "language": "Tcl" }, { "code": "function printAll(separator,argv..) {\n if(argv.length)\n stdout.print(argv[0]);\n for (var i=1; i < argv.length; i++)\n stdout.print(separator, argv[i]);\n}\nprintAll(\" \", 4, 3, 5, 6, 4, 3);\nprintAll(\",\", 4, 3, 5);\nprintAll(\"! \",\"Rosetta\", \"Code\", \"Is\", \"Awesome\");\n", "language": "TIScript" }, { "code": "f = %gP*=\n\n#show+\n\nmain = f <'foo',12.5,('x','y'),100>\n", "language": "Ursala" }, { "code": "[myfn\n [zero? not] [swap puts pred]\n while\n].\n\n100 200 300 400 500 3 myfn\n", "language": "V" }, { "code": "500\n400\n300\n", "language": "V" }, { "code": "fn print_all(things ...string) {\n for x in things {\n println(x)\n }\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n'--------------------------------------------------\nSub varargs(ParamArray a())\nDim n As Long, m As Long\n Debug.Assert VarType(a) = (vbVariant Or vbArray)\n For n = LBound(a) To UBound(a)\n If IsArray(a(n)) Then\n For m = LBound(a(n)) To UBound(a(n))\n Debug.Print a(n)(m)\n Next m\n Else\n Debug.Print a(n)\n End If\n Next\nEnd Sub\n'--------------------------------------------------\nSub Main()\nDim v As Variant\n\n Debug.Print \"call 1\"\n varargs 1, 2, 3\n\n Debug.Print \"call 2\"\n varargs 4, 5, 6, 7, 8\n\n v = Array(9, 10, 11)\n Debug.Print \"call 3\"\n varargs v\n\n ReDim v(0 To 2)\n v(0) = 12\n v(1) = 13\n v(2) = 14\n Debug.Print \"call 4\"\n varargs 11, v\n\n Debug.Print \"call 5\"\n varargs v(2), v(1), v(0), 11\n\nEnd Sub\n", "language": "Visual-Basic" }, { "code": "self.f = method(x, y[ ], z){\n x.print()\n for(i = 0, i < y.size(), i = i + 1){\n ('[' + y[i] + ']').print()\n }\n z.print()\n}\n\nself.f(1, 2, 3)\n'---'.print()\nself.f(1, 2, 3, 4)\n'---'.print()\nself.f(1, 2)\n", "language": "Vorpal" }, { "code": "var printArgs = Fn.new { |args| args.each { |arg| System.print(arg) } }\n\nprintArgs.call([\"Mary\", \"had\", \"3\", \"little\", \"lambs\"])\n", "language": "Wren" }, { "code": "(defun print-on-separate-lines (&rest xs)\n (for-each print xs))\n\n; test the function:\n\n(print-on-separate-lines 'i 'am 'doing 'a 'great 'work 'so 'that 'i 'cannot 'come 'down)\n\n; to use it on a list of arguments assembled at run time, first create your list\n\n(define test '(why should the work cease whilst i leave it and come down to you))\n\n; and then call APPLY:\n\n(apply print-on-separate-lines test)\n", "language": "XLISP" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\ndef IntSize=4; \\number of bytes in an integer\n\nproc Var(N...); \\Display N strings passed as arguments\nint N;\n[N:= Reserve(N*IntSize); \\reserve space for N string pointers\nrepeat Text(0,N(0)); CrLf(0); \\display strings pointed to by N(0)\n N:= N+IntSize; \\point to next string\nuntil N=GetHp; \\pointing beyond reserved space?\n];\n\nVar(4, \"Mary\", \"had\", \"a\", \"little\")\n", "language": "XPL0" }, { "code": "fcn f{vm.arglist.apply2(\"println\")}\nf(\"Mary\",\"had\",\"a\",\"little\");\n", "language": "Zkl" }, { "code": "a:=\"This is a test\".split(); //-->L(\"This\",\"is\",\"a\",\"test\")\nf(a.xplode()); // xplode takes a list and blows it apart into call args\n", "language": "Zkl" }, { "code": "fcn g{f(vm.pasteArgs(2)}\ng(a.xplode());\n", "language": "Zkl" } ]
Variadic-function
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Vector\nnote: Physics\n", "language": "00-META" }, { "code": ";Task\nImplement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a ''pretty print'' function should be implemented. \n\n\nThe Vector may be initialized in any reasonable way.\n* Start and end points, and direction\n* Angular coefficient and value (length)\n\n\nThe four operations to be implemented are:\n* Vector <big><b> + </b></big> Vector addition\n* Vector <big><b> - </b></big> Vector subtraction\n* Vector <big><b> * </b></big> scalar multiplication\n* Vector <big><b> / </b></big> scalar division\n<br><br>\n\n", "language": "00-TASK" }, { "code": "T Vector\n Float x, y\n\n F (x, y)\n .x = x\n .y = y\n\n F +(vector)\n R Vector(.x + vector.x, .y + vector.y)\n\n F -(vector)\n R Vector(.x - vector.x, .y - vector.y)\n\n F *(mult)\n R Vector(.x * mult, .y * mult)\n\n F /(denom)\n R Vector(.x / denom, .y / denom)\n\n F String()\n R ‘(#., #.)’.format(.x, .y)\n\nprint(Vector(5, 7) + Vector(2, 3))\nprint(Vector(5, 7) - Vector(2, 3))\nprint(Vector(5, 7) * 11)\nprint(Vector(5, 7) / 2)\n", "language": "11l" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Kit\n\nDEFINE X_=\"+0\"\nDEFINE Y_=\"+6\"\n\nTYPE Vector=[CARD x1,x2,x3,y1,y2,y3]\n\nPROC PrintVec(Vector POINTER v)\n Print(\"[\") PrintR(v X_)\n Print(\",\") PrintR(v Y_) Print(\"]\")\nRETURN\n\nPROC VecIntInit(Vector POINTER v INT ix,iy)\n IntToReal(ix,v X_)\n IntToReal(iy,v Y_)\nRETURN\n\nPROC VecRealInit(Vector POINTER v REAL POINTER rx,ry)\n RealAssign(rx,v X_)\n RealAssign(ry,v Y_)\nRETURN\n\nPROC VecStringInit(Vector POINTER v CHAR ARRAY sx,sy)\n ValR(sx,v X_)\n ValR(sy,v Y_)\nRETURN\n\nPROC VecAdd(Vector POINTER v1,v2,res)\n RealAdd(v1 X_,v2 X_,res X_) ;res.x=v1.x+v2.x\n RealAdd(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y+v2.y\nRETURN\n\nPROC VecSub(Vector POINTER v1,v2,res)\n RealSub(v1 X_,v2 X_,res X_) ;res.x=v1.x-v2.x\n RealSub(v1 Y_,v2 Y_,res Y_) ;res.y=v1.y-v2.y\nRETURN\n\nPROC VecMult(Vector POINTER v REAL POINTER a Vector POINTER res)\n RealMult(v X_,a,res X_) ;res.x=v.x*a\n RealMult(v Y_,a,res Y_) ;res.y=v.y*a\nRETURN\n\nPROC VecDiv(Vector POINTER v REAL POINTER a Vector POINTER res)\n RealDiv(v X_,a,res X_) ;res.x=v.x/a\n RealDiv(v Y_,a,res Y_) ;res.y=v.y/a\nRETURN\n\nPROC Main()\n Vector v1,v2,res\n REAL s\n\n Put(125) PutE() ;clear the screen\n VecStringInit(v1,\"12.3\",\"-4.56\")\n VecStringInit(v2,\"9.87\",\"654.3\")\n ValR(\"0.1\",s)\n\n VecAdd(v1,v2,res)\n PrintVec(v1) Print(\" + \") PrintVec(v2)\n Print(\" =\") PutE() PrintVec(res) PutE() PutE()\n\n VecSub(v1,v2,res)\n PrintVec(v1) Print(\" - \") PrintVec(v2)\n Print(\" =\") PutE() PrintVec(res) PutE() PutE()\n\n VecMult(v1,s,res)\n PrintVec(v1) Print(\" * \") PrintR(s)\n Print(\" = \") PrintVec(res) PutE() PutE()\n\n VecDiv(v1,s,res)\n PrintVec(v1) Print(\" / \") PrintR(s)\n Print(\" = \") PrintVec(res)\nRETURN\n", "language": "Action-" }, { "code": "# the standard mode COMPLEX is a two element vector #\nMODE VECTOR = COMPLEX;\n# the operations required for the task plus many others are provided as standard for COMPLEX and REAL items #\n# the two components are fields called \"re\" and \"im\" #\n# we can define a \"pretty-print\" operator: #\n# returns a formatted representation of the vector #\nOP TOSTRING = ( VECTOR a )STRING: \"[\" + TOSTRING re OF a + \", \" + TOSTRING im OF a + \"]\";\n# returns a formatted representation of the scaler #\nOP TOSTRING = ( REAL a )STRING: fixed( a, 0, 4 );\n\n# test the operations #\nVECTOR a = 5 I 7, b = 2 I 3; # note the use of the I operator to construct a COMPLEX from two scalers #\nprint( ( \"a+b : \", TOSTRING ( a + b ), newline ) );\nprint( ( \"a-b : \", TOSTRING ( a - b ), newline ) );\nprint( ( \"a*11: \", TOSTRING ( a * 11 ), newline ) );\nprint( ( \"a/2 : \", TOSTRING ( a / 2 ), newline ) )\n", "language": "ALGOL-68" }, { "code": "define :vector [\n x y\n][\n print: -> render \"(|this\\x|, |this\\y|)\" ; prettyprint function\n]\n\nensureVector: function [block][\n ensure -> every? @block => [is? :vector &]\n]\n\nvadd: function [a b][\n ensureVector [a b]\n to :vector @[a\\x + b\\x, a\\y + b\\y]\n]\n\nvsub: function [a b][\n ensureVector [a b]\n to :vector @[a\\x - b\\x, a\\y - b\\y]\n]\n\nvmul: function [a n][\n ensureVector [a]\n to :vector @[a\\x * n, a\\y * n]\n]\n\nvdiv: function [a n][\n ensureVector [a]\n to :vector @[a\\x // n, a\\y // n]\n]\n\n; test our vector object\na: to :vector [5 7]\nb: to :vector [2 3]\nprint [a '+ b '= vadd a b]\nprint [a '- b '= vsub a b]\nprint [a '* 11 '= vmul a 11]\nprint [a '/ 11 '= vdiv a 2]\n", "language": "Arturo" }, { "code": "arraybase 1\ndim vect1(2)\nvect1[1] = 5 : vect1[2] = 7\ndim vect2(2)\nvect2[1] = 2 : vect2[2] = 3\ndim vect3(vect1[?])\n\nsubroutine showarray(vect3)\n print \"[\";\n svect$ = \"\"\n for n = 1 to vect3[?]\n svect$ &= vect3[n] & \", \"\n next n\n svect$ = left(svect$, length(svect$) - 2)\n print svect$;\n print \"]\"\nend subroutine\n\nfor n = 1 to vect1[?]\n vect3[n] = vect1[n] + vect2[n]\nnext n\nprint \"[\" & vect1[1] & \", \" & vect1[2] & \"] + [\" & vect2[1] & \", \" & vect2[2] & \"] = \";\ncall showarray(vect3)\n\nfor n = 1 to vect1[?]\n vect3[n] = vect1[n] - vect2[n]\nnext n\nprint \"[\" & vect1[1] & \", \" & vect1[2] & \"] - [\" & vect2[1] & \", \" & vect2[2] & \"] = \";\ncall showarray(vect3)\n\nfor n = 1 to vect1[?]\n vect3[n] = vect1[n] * 11\nnext n\nprint \"[\" & vect1[1] & \", \" & vect1[2] & \"] * \" & 11 & \" = \";\ncall showarray(vect3)\n\nfor n = 1 to vect1[?]\n vect3[n] = vect1[n] / 2\nnext n\nprint \"[\" & vect1[1] & \", \" & vect1[2] & \"] / \" & 2 & \" = \";\ncall showarray(vect3)\nend\n", "language": "BASIC256" }, { "code": " 5‿7 + 2‿3\n⟨7 10⟩\n 5‿7 - 2‿3\n⟨3 4⟩\n 5‿7 × 11\n⟨55 77⟩\n 5‿7 ÷ 2\n⟨2.5 3.5⟩\n", "language": "BQN" }, { "code": "#include<stdio.h>\n#include<math.h>\n\n#define pi M_PI\n\ntypedef struct{\n\tdouble x,y;\n}vector;\n\nvector initVector(double r,double theta){\n\tvector c;\n\t\n\tc.x = r*cos(theta);\n\tc.y = r*sin(theta);\n\t\n\treturn c;\n}\n\nvector addVector(vector a,vector b){\n\tvector c;\n\t\n\tc.x = a.x + b.x;\n\tc.y = a.y + b.y;\n\t\n\treturn c;\n}\n\nvector subtractVector(vector a,vector b){\n\tvector c;\n\t\n\tc.x = a.x - b.x;\n\tc.y = a.y - b.y;\n\t\n\treturn c;\n}\n\nvector multiplyVector(vector a,double b){\n\tvector c;\n\t\n\tc.x = b*a.x;\n\tc.y = b*a.y;\n\t\n\treturn c;\n}\n\nvector divideVector(vector a,double b){\n\tvector c;\n\t\n\tc.x = a.x/b;\n\tc.y = a.y/b;\n\t\n\treturn c;\n}\n\nvoid printVector(vector a){\n\tprintf(\"%lf %c %c %lf %c\",a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150);\n}\n\nint main()\n{\n\tvector a = initVector(3,pi/6);\n\tvector b = initVector(5,2*pi/3);\n\t\n\tprintf(\"\\nVector a : \");\n\tprintVector(a);\n\t\n\tprintf(\"\\n\\nVector b : \");\n\tprintVector(b);\n\t\n\tprintf(\"\\n\\nSum of vectors a and b : \");\n\tprintVector(addVector(a,b));\n\t\n\tprintf(\"\\n\\nDifference of vectors a and b : \");\n\tprintVector(subtractVector(a,b));\n\t\n\tprintf(\"\\n\\nMultiplying vector a by 3 : \");\n\tprintVector(multiplyVector(a,3));\n\t\n\tprintf(\"\\n\\nDividing vector b by 2.5 : \");\n\tprintVector(divideVector(b,2.5));\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <cmath>\n#include <cassert>\nusing namespace std;\n\n#define PI 3.14159265359\n\nclass Vector\n{\npublic:\n Vector(double ix, double iy, char mode)\n {\n if(mode=='a')\n {\n x=ix*cos(iy);\n y=ix*sin(iy);\n }\n else\n {\n x=ix;\n y=iy;\n }\n }\n Vector(double ix,double iy)\n {\n x=ix;\n y=iy;\n }\n Vector operator+(const Vector& first)\n {\n return Vector(x+first.x,y+first.y);\n }\n Vector operator-(Vector first)\n {\n return Vector(x-first.x,y-first.y);\n }\n Vector operator*(double scalar)\n {\n return Vector(x*scalar,y*scalar);\n }\n Vector operator/(double scalar)\n {\n return Vector(x/scalar,y/scalar);\n }\n bool operator==(Vector first)\n {\n return (x==first.x&&y==first.y);\n }\n void v_print()\n {\n cout << \"X: \" << x << \" Y: \" << y;\n }\n double x,y;\n};\n\nint main()\n{\n Vector vec1(0,1);\n Vector vec2(2,2);\n Vector vec3(sqrt(2),45*PI/180,'a');\n vec3.v_print();\n assert(vec1+vec2==Vector(2,3));\n assert(vec1-vec2==Vector(-2,-1));\n assert(vec1*5==Vector(0,5));\n assert(vec2/2==Vector(1,1));\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace RosettaVectors\n{\n public class Vector\n {\n public double[] store;\n public Vector(IEnumerable<double> init)\n {\n store = init.ToArray();\n }\n public Vector(double x, double y)\n {\n store = new double[] { x, y };\n }\n static public Vector operator+(Vector v1, Vector v2)\n {\n return new Vector(v1.store.Zip(v2.store, (a, b) => a + b));\n }\n static public Vector operator -(Vector v1, Vector v2)\n {\n return new Vector(v1.store.Zip(v2.store, (a, b) => a - b));\n }\n static public Vector operator *(Vector v1, double scalar)\n {\n return new Vector(v1.store.Select(x => x * scalar));\n }\n static public Vector operator /(Vector v1, double scalar)\n {\n return new Vector(v1.store.Select(x => x / scalar));\n }\n public override string ToString()\n {\n return string.Format(\"[{0}]\", string.Join(\",\", store));\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n var v1 = new Vector(5, 7);\n var v2 = new Vector(2, 3);\n Console.WriteLine(v1 + v2);\n Console.WriteLine(v1 - v2);\n Console.WriteLine(v1 * 11);\n Console.WriteLine(v1 / 2);\n // Works with arbitrary size vectors, too.\n var lostVector = new Vector(new double[] { 4, 8, 15, 16, 23, 42 });\n Console.WriteLine(lostVector * 7);\n Console.ReadLine();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "% Parameterized vector class\nvector = cluster [T: type] is make, add, sub, mul, div,\n get_x, get_y, to_string\n % The inner type must support basic math\n where T has add: proctype (T,T) returns (T)\n signals (overflow, underflow),\n sub: proctype (T,T) returns (T)\n signals (overflow, underflow),\n mul: proctype (T,T) returns (T)\n signals (overflow, underflow),\n div: proctype (T,T) returns (T)\n signals (zero_divide, overflow, underflow)\n rep = struct [x,y: T]\n\n % instantiate\n make = proc (x,y: T) returns (cvt)\n return(rep${x:x, y:y})\n end make\n\n % vector addition and subtraction\n add = proc (a,b: cvt) returns (cvt)\n signals (overflow, underflow)\n return(rep${x: up(a).x + up(b).x,\n y: up(a).y + up(b).y})\n resignal overflow, underflow\n end add\n\n sub = proc (a,b: cvt) returns (cvt)\n signals (overflow, underflow)\n return(rep${x: up(a).x - up(b).x,\n y: up(a).y - up(b).y})\n resignal overflow, underflow\n end sub\n\n % scalar multiplication and division\n mul = proc (a: cvt, b: T) returns (cvt)\n signals (overflow, underflow)\n return(rep${x: up(a).x*b, y: up(a).y*b})\n resignal overflow, underflow\n end mul\n\n div = proc (a: cvt, b: T) returns (cvt)\n signals (zero_divide, overflow, underflow)\n return(rep${x: up(a).x/b, y: up(a).y/b})\n resignal zero_divide, overflow, underflow\n end div\n\n % accessors\n get_x = proc (v: cvt) returns (T) return(v.x) end get_x\n get_y = proc (v: cvt) returns (T) return(v.y) end get_y\n\n % we can't just use T$unparse for pretty-printing, since\n % for floats it always prints the exponential form, and\n % that's not very pretty.\n % passing in a conversion function at the moment of\n % generating the string form is the least bad way.\n to_string = proc (v: cvt, f: proctype (T) returns (string))\n returns (string)\n return(\"(\" || f(v.x) || \", \" || f(v.y) || \")\")\n end to_string\nend vector\n\n% this function formats a real somewhat neatly without needing\n% extra parameters\nformat_real = proc (r: real) returns (string)\n return(f_form(r, 2, 4))\nend format_real\n\nstart_up = proc ()\n vr = vector[real] % use real numbers\n po: stream := stream$primary_output()\n\n % vectors\n a: vr := vr$make(5.0, 7.0)\n b: vr := vr$make(2.0, 3.0)\n\n % do some math\n a_plus_b: vr := a + b\n a_minus_b: vr := a - b\n a_times_11: vr := a * 11.0\n a_div_2: vr := a / 2.0\n\n % show the results\n stream$putl(po, \" a = \" || vr$to_string(a, format_real))\n stream$putl(po, \" b = \" || vr$to_string(b, format_real))\n stream$putl(po, \" a + b = \" || vr$to_string(a_plus_b, format_real))\n stream$putl(po, \" a - b = \" || vr$to_string(a_minus_b, format_real))\n stream$putl(po, \"a * 11 = \" || vr$to_string(a_times_11, format_real))\n stream$putl(po, \" a / 2 = \" || vr$to_string(a_div_2, format_real))\nend start_up\n", "language": "CLU" }, { "code": "import std.stdio;\n\nvoid main() {\n writeln(VectorReal(5, 7) + VectorReal(2, 3));\n writeln(VectorReal(5, 7) - VectorReal(2, 3));\n writeln(VectorReal(5, 7) * 11);\n writeln(VectorReal(5, 7) / 2);\n}\n\nalias VectorReal = Vector!real;\nstruct Vector(T) {\n private T x, y;\n\n this(T x, T y) {\n this.x = x;\n this.y = y;\n }\n\n auto opBinary(string op : \"+\")(Vector rhs) const {\n return Vector(x + rhs.x, y + rhs.y);\n }\n\n auto opBinary(string op : \"-\")(Vector rhs) const {\n return Vector(x - rhs.x, y - rhs.y);\n }\n\n auto opBinary(string op : \"/\")(T denom) const {\n return Vector(x / denom, y / denom);\n }\n\n auto opBinary(string op : \"*\")(T mult) const {\n return Vector(x * mult, y * mult);\n }\n\n void toString(scope void delegate(const(char)[]) sink) const {\n import std.format;\n sink.formattedWrite!\"(%s, %s)\"(x, y);\n }\n}\n", "language": "D" }, { "code": "program Vector;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n System.Math.Vectors,\n SysUtils;\n\nprocedure VectorToString(v: TVector);\nbegin\n WriteLn(Format('(%.1f + i%.1f)', [v.X, v.Y]));\nend;\n\nvar\n a, b: TVector;\n\nbegin\n a := TVector.Create(5, 7);\n b := TVector.Create(2, 3);\n VectorToString(a + b);\n VectorToString(a - b);\n VectorToString(a * 11);\n VectorToString(a / 2);\n\n ReadLn;\nend\n\n.\n", "language": "Delphi" }, { "code": "func[] vadd a[] b[] .\n for i to len a[]\n r[] &= a[i] + b[i]\n .\n return r[]\n.\nfunc[] vsub a[] b[] .\n for i to len a[]\n r[] &= a[i] - b[i]\n .\n return r[]\n.\nfunc[] vmul a[] b .\n for i to len a[]\n r[] &= a[i] * b\n .\n return r[]\n.\nfunc[] vdiv a[] b .\n for i to len a[]\n r[] &= a[i] / b\n .\n return r[]\n.\nprint vadd [ 5 7 ] [ 2 3 ]\nprint vsub [ 5 7 ] [ 2 3 ]\nprint vmul [ 5 7 ] 11\nprint vdiv [ 5 7 ] 2\n", "language": "EasyLang" }, { "code": "open System\n\nlet add (ax, ay) (bx, by) =\n (ax+bx, ay+by)\n\nlet sub (ax, ay) (bx, by) =\n (ax-bx, ay-by)\n\nlet mul (ax, ay) c =\n (ax*c, ay*c)\n\nlet div (ax, ay) c =\n (ax/c, ay/c)\n\n[<EntryPoint>]\nlet main _ =\n let a = (5.0, 7.0)\n let b = (2.0, 3.0)\n\n printfn \"%A\" (add a b)\n printfn \"%A\" (sub a b)\n printfn \"%A\" (mul a 11.0)\n printfn \"%A\" (div a 2.0)\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "(scratchpad) USE: math.vectors\n(scratchpad) { 1 2 } { 3 4 } v+\n\n--- Data stack:\n{ 4 6 }\n", "language": "Factor" }, { "code": "USING: accessors arrays kernel math parser prettyprint\nprettyprint.custom sequences ;\nIN: rosetta-code.vector\n\nTUPLE: vec { x real read-only } { y real read-only } ;\nC: <vec> vec\n\n<PRIVATE\n\n: parts ( vec -- x y ) [ x>> ] [ y>> ] bi ;\n: devec ( vec1 vec2 -- x1 y1 x2 y2 ) [ parts ] bi@ rot swap ;\n\n: binary-op ( vec1 vec2 quot -- vec3 )\n [ devec ] dip 2bi@ <vec> ; inline\n\n: scalar-op ( vec1 scalar quot -- vec2 )\n [ parts ] 2dip curry bi@ <vec> ; inline\n\nPRIVATE>\n\nSYNTAX: VEC{ \\ } [ first2 <vec> ] parse-literal ;\n\n: v+ ( vec1 vec2 -- vec3 ) [ + ] binary-op ;\n: v- ( vec1 vec2 -- vec3 ) [ - ] binary-op ;\n: v* ( vec1 scalar -- vec2 ) [ * ] scalar-op ;\n: v/ ( vec1 scalar -- vec2 ) [ / ] scalar-op ;\n\nM: vec pprint-delims drop \\ VEC{ \\ } ;\nM: vec >pprint-sequence parts 2array ;\nM: vec pprint* pprint-object ;\n", "language": "Factor" }, { "code": "USING: kernel formatting prettyprint rosetta-code.vector\nsequences ;\nIN: rosetta-code.vector\n\n: demo ( a b quot -- )\n 3dup [ unparse ] tri@ rest but-last\n \"%16s %16s%3s= \" printf call . ; inline\n\nVEC{ -8.4 1.35 } VEC{ 10 11/123 } [ v+ ] demo\nVEC{ 5 3 } VEC{ 4 2 } [ v- ] demo\nVEC{ 4 -8 } 2 [ v* ] demo\nVEC{ 5 7 } 2 [ v/ ] demo\n\n! You can still make a vector without the literal syntax of\n! course.\n\n5 2 <vec> 1.3 [ v* ] demo\n", "language": "Factor" }, { "code": ": v. swap . . ;\n: v* swap over * >r * r> ;\n: v/ swap over / >r / r> ;\n: v+ >r swap >r + r> r> + ;\n: v- >r swap >r - r> r> - ;\n", "language": "Forth" }, { "code": "MODULE ROSETTA_VECTOR\n IMPLICIT NONE\n\n TYPE VECTOR\n REAL :: X, Y\n END TYPE VECTOR\n\n\n INTERFACE OPERATOR(+)\n MODULE PROCEDURE VECTOR_ADD\n END INTERFACE\n\n INTERFACE OPERATOR(-)\n MODULE PROCEDURE VECTOR_SUB\n END INTERFACE\n\n INTERFACE OPERATOR(/)\n MODULE PROCEDURE VECTOR_DIV\n END INTERFACE\n\n INTERFACE OPERATOR(*)\n MODULE PROCEDURE VECTOR_MULT\n END INTERFACE\n\n CONTAINS\n\n FUNCTION VECTOR_ADD(VECTOR_1, VECTOR_2)\n TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2\n TYPE(VECTOR) :: VECTOR_ADD\n VECTOR_ADD%X = VECTOR_1%X+VECTOR_2%X\n VECTOR_ADD%Y = VECTOR_1%Y+VECTOR_2%Y\n END FUNCTION VECTOR_ADD\n\n FUNCTION VECTOR_SUB(VECTOR_1, VECTOR_2)\n TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2\n TYPE(VECTOR) :: VECTOR_SUB\n VECTOR_SUB%X = VECTOR_1%X-VECTOR_2%X\n VECTOR_SUB%Y = VECTOR_1%Y-VECTOR_2%Y\n END FUNCTION VECTOR_SUB\n\n FUNCTION VECTOR_DIV(VEC, SCALAR)\n TYPE(VECTOR), INTENT(IN) :: VEC\n REAL, INTENT(IN) :: SCALAR\n TYPE(VECTOR) :: VECTOR_DIV\n VECTOR_DIV%X = VEC%X/SCALAR\n VECTOR_DIV%Y = VEC%Y/SCALAR\n END FUNCTION VECTOR_DIV\n\n FUNCTION VECTOR_MULT(VEC, SCALAR)\n TYPE(VECTOR), INTENT(IN) :: VEC\n REAL, INTENT(IN) :: SCALAR\n TYPE(VECTOR) :: VECTOR_MULT\n VECTOR_MULT%X = VEC%X*SCALAR\n VECTOR_MULT%Y = VEC%Y*SCALAR\n END FUNCTION VECTOR_MULT\n\n FUNCTION FROM_RTHETA(R, THETA)\n REAL :: R, THETA\n TYPE(VECTOR) :: FROM_RTHETA\n FROM_RTHETA%X = R*SIN(THETA)\n FROM_RTHETA%Y = R*COS(THETA)\n END FUNCTION FROM_RTHETA\n\n FUNCTION FROM_XY(X, Y)\n REAL :: X, Y\n TYPE(VECTOR) :: FROM_XY\n FROM_XY%X = X\n FROM_XY%Y = Y\n END FUNCTION FROM_XY\n\n FUNCTION PRETTY_PRINT(VEC)\n TYPE(VECTOR), INTENT(IN) :: VEC\n CHARACTER(LEN=100) PRETTY_PRINT\n WRITE(PRETTY_PRINT,\"(A, F0.5, A, F0.5, A)\") \"[\", VEC%X, \", \", VEC%Y, \"]\"\n END FUNCTION PRETTY_PRINT\nEND MODULE ROSETTA_VECTOR\n\nPROGRAM VECTOR_DEMO\n USE ROSETTA_VECTOR\n IMPLICIT NONE\n\n TYPE(VECTOR) :: VECTOR_1, VECTOR_2\n REAL, PARAMETER :: PI = 4*ATAN(1.0)\n REAL :: SCALAR\n\n SCALAR = 2.0\n\n VECTOR_1 = FROM_XY(2.0, 3.0)\n VECTOR_2 = FROM_RTHETA(2.0, PI/6.0)\n\n WRITE(*,*) \"VECTOR_1 (X: 2.0, Y: 3.0) : \", PRETTY_PRINT(VECTOR_1)\n WRITE(*,*) \"VECTOR_2 (R: 2.0, THETA: PI/6) : \", PRETTY_PRINT(VECTOR_2)\n WRITE(*,*) NEW_LINE('A')\n WRITE(*,*) \"VECTOR_1 + VECTOR_2 = \", PRETTY_PRINT(VECTOR_1+VECTOR_2)\n WRITE(*,*) \"VECTOR_1 - VECTOR_2 = \", PRETTY_PRINT(VECTOR_1-VECTOR_2)\n WRITE(*,*) \"VECTOR_1 / 2.0 = \", PRETTY_PRINT(VECTOR_1/SCALAR)\n WRITE(*,*) \"VECTOR_1 * 2.0 = \", PRETTY_PRINT(VECTOR_1*SCALAR)\nEND PROGRAM VECTOR_DEMO\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nType Vector\n As Double x, y\n Declare Operator Cast() As String\nEnd Type\n\nOperator Vector.Cast() As String\n Return \"[\" + Str(x) + \", \" + Str(y) + \"]\"\nEnd Operator\n\nOperator + (vec1 As Vector, vec2 As Vector) As Vector\n Return Type<Vector>(vec1.x + vec2.x, vec1.y + vec2.y)\nEnd Operator\n\nOperator - (vec1 As Vector, vec2 As Vector) As Vector\n Return Type<Vector>(vec1.x - vec2.x, vec1.y - vec2.y)\nEnd Operator\n\nOperator * (vec As Vector, scalar As Double) As Vector\n Return Type<Vector>(vec.x * scalar, vec.y * scalar)\nEnd Operator\n\nOperator / (vec As Vector, scalar As Double) As Vector\n ' No need to check for division by zero as we're using Doubles\n Return Type<Vector>(vec.x / scalar, vec.y / scalar)\nEnd Operator\n\nDim v1 As Vector = (5, 7)\nDim v2 As Vector = (2, 3)\nPrint v1; \" + \"; v2; \" = \"; v1 + v2\nPrint v1; \" - \"; v2; \" = \"; v1 - v2\nPrint v1; \" * \"; 11; \" = \"; v1 * 11.0\nPrint v1; \" / \"; 2; \" = \"; v1 / 2.0\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\ntype vector []float64\n\nfunc (v vector) add(v2 vector) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi + v2[i]\n }\n return r\n}\n\nfunc (v vector) sub(v2 vector) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi - v2[i]\n }\n return r\n}\n\nfunc (v vector) scalarMul(s float64) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi * s\n }\n return r\n}\n\nfunc (v vector) scalarDiv(s float64) vector {\n r := make([]float64, len(v))\n for i, vi := range v {\n r[i] = vi / s\n }\n return r\n}\n\nfunc main() {\n v1 := vector{5, 7}\n v2 := vector{2, 3}\n fmt.Println(v1.add(v2))\n fmt.Println(v1.sub(v2))\n fmt.Println(v1.scalarMul(11))\n fmt.Println(v1.scalarDiv(2))\n}\n", "language": "Go" }, { "code": "import groovy.transform.EqualsAndHashCode\n\n@EqualsAndHashCode\nclass Vector {\n private List<Number> elements\n Vector(List<Number> e ) {\n if (!e) throw new IllegalArgumentException(\"A Vector must have at least one element.\")\n if (!e.every { it instanceof Number }) throw new IllegalArgumentException(\"Every element must be a number.\")\n elements = [] + e\n }\n Vector(Number... e) { this(e as List) }\n\n def order() { elements.size() }\n def norm2() { elements.sum { it ** 2 } ** 0.5 }\n\n def plus(Vector that) {\n if (this.order() != that.order()) throw new IllegalArgumentException(\"Vectors must be conformable for addition.\")\n [this.elements,that.elements].transpose()*.sum() as Vector\n }\n def minus(Vector that) { this + (-that) }\n def multiply(Number that) { this.elements.collect { it * that } as Vector }\n def div(Number that) { this * (1/that) }\n def negative() { this * -1 }\n\n String toString() { \"(${elements.join(',')})\" }\n}\n\nclass VectorCategory {\n static Vector plus (Number a, Vector b) { b + a }\n static Vector minus (Number a, Vector b) { -b + a }\n static Vector multiply (Number a, Vector b) { b * a }\n}\n", "language": "Groovy" }, { "code": "Number.metaClass.mixin VectorCategory\n\ndef a = [1, 5] as Vector\ndef b = [6, -2] as Vector\ndef x = 8\nprintln \"a = $a b = $b x = $x\"\nassert a + b == [7, 3] as Vector\nprintln \"a + b == $a + $b == ${a+b}\"\nassert a - b == [-5, 7] as Vector\nprintln \"a - b == $a - $b == ${a-b}\"\nassert a * x == [8, 40] as Vector\nprintln \"a * x == $a * $x == ${a*x}\"\nassert x * a == [8, 40] as Vector\nprintln \"x * a == $x * $a == ${x*a}\"\nassert b / x == [3/4, -1/4] as Vector\nprintln \"b / x == $b / $x == ${b/x}\"\n", "language": "Groovy" }, { "code": "add (u,v) (x,y) = (u+x,v+y)\nminus (u,v) (x,y) = (u-x,v-y)\nmultByScalar k (x,y) = (k*x,k*y)\ndivByScalar (x,y) k = (x/k,y/k)\n\nmain = do\n let vecA = (3.0,8.0) -- cartersian coordinates\n let (r,theta) = (3,pi/12) :: (Double,Double)\n let vecB = (r*(cos theta),r*(sin theta)) -- from polar coordinates to cartesian coordinates\n putStrLn $ \"vecA = \" ++ (show vecA)\n putStrLn $ \"vecB = \" ++ (show vecB)\n putStrLn $ \"vecA + vecB = \" ++ (show.add vecA $ vecB)\n putStrLn $ \"vecA - vecB = \" ++ (show.minus vecA $ vecB)\n putStrLn $ \"2 * vecB = \" ++ (show.multByScalar 2 $ vecB)\n putStrLn $ \"vecA / 3 = \" ++ (show.divByScalar vecA $ 3)\n", "language": "Haskell" }, { "code": " 5 7+2 3\n7 10\n 5 7-2 3\n3 4\n 5 7*11\n55 77\n 5 7%2\n2.5 3.5\n", "language": "J" }, { "code": " 2ad45\n1.41421j1.41421\n +. 2ad45\n1.41421 1.41421\n 2ar0.785398\n1.41421j1.41421\n +. 2ar0.785398\n1.41421 1.41421\n", "language": "J" }, { "code": "import java.util.Locale;\n\npublic class Test {\n\n public static void main(String[] args) {\n System.out.println(new Vec2(5, 7).add(new Vec2(2, 3)));\n System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3)));\n System.out.println(new Vec2(5, 7).mult(11));\n System.out.println(new Vec2(5, 7).div(2));\n }\n}\n\nclass Vec2 {\n final double x, y;\n\n Vec2(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n Vec2 add(Vec2 v) {\n return new Vec2(x + v.x, y + v.y);\n }\n\n Vec2 sub(Vec2 v) {\n return new Vec2(x - v.x, y - v.y);\n }\n\n Vec2 div(double val) {\n return new Vec2(x / val, y / val);\n }\n\n Vec2 mult(double val) {\n return new Vec2(x * val, y * val);\n }\n\n @Override\n public String toString() {\n return String.format(Locale.US, \"[%s, %s]\", x, y);\n }\n}\n", "language": "Java" }, { "code": "def polar(r; angle):\n [ r*(angle|cos), r*(angle|sin) ];\n\n# If your jq allows multi-arity functions, you may wish to uncomment the following line:\n# def polar(r): [r, 0];\n\ndef polar2vector: polar(.[0]; .[1]);\n\ndef vector(x; y):\n if (x|type) == \"number\" and (y|type) == \"number\" then [x,y]\n else error(\"TypeError\")\n end;\n\n# Input: an array of same-dimensional vectors of any dimension to be added\ndef sum:\n def sum2: .[0] as $a | .[1] as $b | reduce range(0;$a|length) as $i ($a; .[$i] += $b[$i]);\n if length <= 1 then .\n else reduce .[1:][] as $v (.[0] ; [., $v]|sum2)\n end;\n\ndef multiply(scalar): [ .[] * scalar ];\n\ndef negate: multiply(-1);\n\ndef minus(v): [., (v|negate)] | sum;\n\ndef divide(scalar):\n if scalar == 0 then error(\"division of a vector by 0 is not supported\")\n else [ .[] / scalar ]\n end;\n\ndef r: (.[0] | .*.) + (.[1] | .*.) | sqrt;\n\ndef atan2:\n def pi: 1 | atan * 4;\n def sign: if . < 0 then -1 elif . > 0 then 1 else 0 end;\n .[0] as $x | .[1] as $y\n | if $x == 0 then $y | sign * pi / 2\n else ($y / $x) | if $x > 0 then atan elif . > 0 then atan - pi else atan + pi end\n end;\n\ndef angle: atan2;\n\ndef topolar: [r, angle];\n", "language": "Jq" }, { "code": "def examples:\n def pi: 1 | atan * 4;\n\n [1,1] as $v\n | [3,4] as $w\n | polar(1; pi/2) as $z\n | polar(-2; pi/4) as $z2\n | \"v is \\($v)\",\n \" w is \\($w)\",\n \"v + w is \\([$v, $w] | sum)\",\n \"v - w is \\( $v |minus($w))\",\n \" - v is \\( $v|negate )\",\n \"w * 5 is \\($w | multiply(5))\",\n \"w / 2 is \\($w | divide(2))\",\n \"v|topolar is \\($v|topolar)\",\n \"w|topolar is \\($w|topolar)\",\n \"z = polar(1; pi/2) is \\($z)\",\n \"z|topolar is \\($z|topolar)\",\n \"z2 = polar(-2; pi/4) is \\($z2)\",\n \"z2|topolar is \\($z2|topolar)\",\n \"z2|topolar|polar is \\($z2|topolar|polar2vector)\" ;\n\nexamples\n", "language": "Jq" }, { "code": "$ jq -r -n -f vector.jq\nv is [1,1]\n w is [3,4]\nv + w is [4,5]\nv - w is [-2,-3]\n - v is [-1,-1]\nw * 5 is [15,20]\nw / 2 is [1.5,2]\nv|topolar is [1.4142135623730951,0.7853981633974483]\nw|topolar is [5,0.9272952180016122]\nz = polar(1; pi/2) is [6.123233995736766e-17,1]\nz|topolar is [1,1.5707963267948966]\nz2 = polar(-2; pi/4) is [-1.4142135623730951,-1.414213562373095]\nz2|topolar is [2,-2.356194490192345]\nz2|topolar|polar is [-1.414213562373095,-1.4142135623730951]\n", "language": "Jq" }, { "code": "module SpatialVectors\n\nexport SpatialVector\n\nstruct SpatialVector{N, T}\n coord::NTuple{N, T}\nend\n\nSpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} =\n SpatialVector{N, T}(e .- s)\nfunction SpatialVector(∠::T, val::T) where T\n θ = atan(∠)\n x = val * cos(θ)\n y = val * sin(θ)\n return SpatialVector((x, y))\nend\n\nangularcoef(v::SpatialVector{2, T}) where T = v.coord[2] / v.coord[1]\nBase.norm(v::SpatialVector) = sqrt(sum(x -> x^2, v.coord))\n\nfunction Base.show(io::IO, v::SpatialVector{2, T}) where T\n ∠ = angularcoef(v)\n val = norm(v)\n println(io, \"\"\"2-dim spatial vector\n - Angular coef ∠: $(∠) (θ = $(rad2deg(atan(∠)))°)\n - Magnitude: $(val)\n - X coord: $(v.coord[1])\n - Y coord: $(v.coord[2])\"\"\")\nend\n\nBase.:-(v::SpatialVector) = SpatialVector(.- v.coord)\n\nfor op in (:+, :-)\n @eval begin\n Base.$op(a::SpatialVector{N, T}, b::SpatialVector{N, U}) where {N, T, U} =\n SpatialVector{N, promote_type(T, U)}(broadcast($op, a.coord, b.coord))\n end\nend\n\nfor op in (:*, :/)\n @eval begin\n Base.$op(n::T, v::SpatialVector{N, U}) where {N, T, U} =\n SpatialVector{N, promote_type(T, U)}(broadcast($op, n, v.coord))\n Base.$op(v::SpatialVector, n::Number) = $op(n, v)\n end\nend\n\nend # module Vectors\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nclass Vector2D(val x: Double, val y: Double) {\n operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y)\n\n operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y)\n\n operator fun times(s: Double) = Vector2D(s * x, s * y)\n\n operator fun div(s: Double) = Vector2D(x / s, y / s)\n\n override fun toString() = \"($x, $y)\"\n}\n\noperator fun Double.times(v: Vector2D) = v * this\n\nfun main(args: Array<String>) {\n val v1 = Vector2D(5.0, 7.0)\n val v2 = Vector2D(2.0, 3.0)\n println(\"v1 = $v1\")\n println(\"v2 = $v2\")\n println()\n println(\"v1 + v2 = ${v1 + v2}\")\n println(\"v1 - v2 = ${v1 - v2}\")\n println(\"v1 * 11 = ${v1 * 11.0}\")\n println(\"11 * v2 = ${11.0 * v2}\")\n println(\"v1 / 2 = ${v1 / 2.0}\")\n}\n", "language": "Kotlin" }, { "code": "struct &Vector {\n\t$x\n\t$y\n}\n\nfp.initVector = ($x, $y) -> {\n\treturn &Vector(fn.double($x), fn.double($y))\n}\n\nfp.addVector = ($a, $b) -> {\n\treturn parser.op(&Vector($a::$x + $b::$x, $a::$y + $b::$y))\n}\n\nfp.subVector = ($a, $b) -> {\n\treturn parser.op(&Vector($a::$x - $b::$x, $a::$y - $b::$y))\n}\n\nfp.mulVector = ($vec, $scalar) -> {\n\treturn parser.op(&Vector($vec::$x * $scalar, $vec::$y * $scalar))\n}\n\nfp.divVector = ($vec, $scalar) -> {\n\treturn parser.op(&Vector($vec::$x / $scalar, $vec::$y / $scalar))\n}\n\nfp.printVector = ($vec) -> {\n\tfn.println([parser.op($vec::$x), parser.op($vec::$y)])\n}\n\n$vec1 = fp.initVector(5, 7)\n$vec2 = fp.initVector(2, 3)\n\nfp.printVector($vec1)\nfp.printVector($vec2)\nfn.println()\n\nfp.printVector(fp.addVector($vec1, $vec2))\nfp.printVector(fp.subVector($vec1, $vec2))\nfp.printVector(fp.mulVector($vec1, 11))\nfp.printVector(fp.divVector($vec1, 2))\n", "language": "Lang" }, { "code": "vector = {mt = {}}\n\nfunction vector.new (x, y)\n local new = {x = x or 0, y = y or 0}\n setmetatable(new, vector.mt)\n return new\nend\n\nfunction vector.mt.__add (v1, v2)\n return vector.new(v1.x + v2.x, v1.y + v2.y)\nend\n\nfunction vector.mt.__sub (v1, v2)\n return vector.new(v1.x - v2.x, v1.y - v2.y)\nend\n\nfunction vector.mt.__mul (v, s)\n return vector.new(v.x * s, v.y * s)\nend\n\nfunction vector.mt.__div (v, s)\n return vector.new(v.x / s, v.y / s)\nend\n\nfunction vector.print (vec)\n print(\"(\" .. vec.x .. \", \" .. vec.y .. \")\")\nend\n\nlocal a, b = vector.new(5, 7), vector.new(2, 3)\nvector.print(a + b)\nvector.print(a - b)\nvector.print(a * 11)\nvector.print(a / 2)\n", "language": "Lua" }, { "code": "class vector {\nprivate:\n\tdouble x, y\npublic:\n\tclass literal {\n\t\tdouble v\n\tclass:\n\t\tmodule Literal(.v) {\n\t\t}\n\t}\n\toperator \"+\" (b as vector){\n\t\t.x+=b.x\n\t\t.y+=b.y\n\t}\n\toperator \"-\" (b as vector){\n\t\t.x-=b.x\n\t\t.y-=b.y\n\t}\n\toperator \"*\" (b as literal){\n\t\t.x*=b.v\n\t\t.y*=b.v\n\t}\n\toperator \"/\" (b as literal){\n\t\t.x/=b.v\n\t\t.y/=b.v\n\t}\n\tproperty printVector {\n\t\tvalue {\n\t\t\tlink parent x, y to x, y\n\t\t\tvalue=format$(.fm$, str$(round(x,.r), .Lcid),if$(y>=0->\"+\", \"-\"),str$(abs(round(y,.r)),.lcid))\n\t\t}\n\t}=\"\" // make type string\n\t// added members to printVector (is a group type)\n\tgroup printVector {\n\t\tinteger Lcid=1033\n\t\tfm$=\"{0} î {1}{2} û\"\n\t\tr=6\n\t}\nclass:\n\tmodule vector(r as double, theta as double, Lcid=1033) {\n\t\tdef deg(rad)=rad*180@/pi\n\t\t.printVector.Lcid<=Lcid\n\t\t.x<=r*cos(deg(theta))\n\t\t.y<=r*sin(deg(theta))\t\t\n\t}\t\n}\ndocument s$\na=vector(3,pi/6)\ns$=\"Vector a : \"+a.printVector+{\n}\nb=vector(5,2*pi/3)\ns$=\"Vector b : \"+b.printVector+{\n}\nsum_a_b=a+b\ns$=\"Sum of vectors a and b : \"+sum_a_b.printVector+{\n}\ndiff_a_b=a-b\ns$=\"Difference of vectors a and b : \"+diff_a_b.printVector+{\n}\nmul_a_3=a*a.literal(3)\ns$=\"Multiplying vector a by 3 : \"+mul_a_3.printVector+{\n}\ndiv_b_2.5=b/b.literal(2.5)\ns$=\"Dividing vector b by 2.5 : \"+div_b_2.5.printVector+{\n}\nreport s$\nclipboard s$\n", "language": "M2000-Interpreter" }, { "code": "module MyVector()\n option object;\n local value := Vector();\n\n export ModuleApply::static := proc( )\n Object( MyVector, _passed );\n end proc;\n\n export ModuleCopy::static := proc( mv::MyVector, proto::MyVector, v::Vector, $ )\n \t mv:-value := v;\n end proc;\n\n export ModulePrint::static := proc(mv::MyVector, $ )\n mv:-value;\n end proc;\n\n\n# operations:\n export `+`::static := proc( v1::MyVector, v2::MyVector )\n MyVector( v1:-value + v2:-value );\n end proc;\n\n export `*`::static := proc( v::MyVector, scalar_val::numeric)\n MyVector( v:-value * scalar_val);\n end proc;\n\n\nend module:\n", "language": "Maple" }, { "code": "a := MyVector(<3|4>):\nb := MyVector(<5|4>):\n\na + b;\na - b;\na * 5;\na / 5;\n", "language": "Maple" }, { "code": "ClearAll[vector,PrintVector]\nvector[{r_,\\[Theta]_}]:=vector@@AngleVector[{r,\\[Theta]}]\nvector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z]\na_ vector[x_,y_]^:=vector[a x,a y]\nvector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z]\nPrintVector[vector[x_,y_]]:=Print[\"vector has first component: \",x,\" And second component: \",y]\n\nvector[1,2]+vector[3,4]\nvector[1,2]-vector[3,4]\n12vector[1,2]\nvector[1,2]/3\nPrintVector@vector[{Sqrt[2],45Degree}]\n", "language": "Mathematica" }, { "code": "vplus = function(v1, v2)\n return [v1[0]+v2[0],v1[1]+v2[1]]\nend function\n\nvminus = function (v1, v2)\n return [v1[0]-v2[0],v1[1]-v2[1]]\nend function\n\nvmult = function(v1, scalar)\n return [v1[0]*scalar, v1[1]*scalar]\nend function\n\nvdiv = function(v1, scalar)\n return [v1[0]/scalar, v1[1]/scalar]\nend function\n\nvector1 = [2,3]\nvector2 = [4,5]\n\nprint vplus(vector1,vector2)\nprint vminus(vector2, vector1)\nprint vmult(vector1, 3)\nprint vdiv(vector2, 2)\n", "language": "MiniScript" }, { "code": "MODULE Vector;\nFROM FormatString IMPORT FormatString;\nFROM RealStr IMPORT RealToStr;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nTYPE Vector =\n RECORD\n x,y : REAL;\n END;\n\nPROCEDURE Add(a,b : Vector) : Vector;\nBEGIN\n RETURN Vector{a.x+b.x, a.y+b.y}\nEND Add;\n\nPROCEDURE Sub(a,b : Vector) : Vector;\nBEGIN\n RETURN Vector{a.x-b.x, a.y-b.y}\nEND Sub;\n\nPROCEDURE Mul(v : Vector; r : REAL) : Vector;\nBEGIN\n RETURN Vector{a.x*r, a.y*r}\nEND Mul;\n\nPROCEDURE Div(v : Vector; r : REAL) : Vector;\nBEGIN\n RETURN Vector{a.x/r, a.y/r}\nEND Div;\n\nPROCEDURE Print(v : Vector);\nVAR buf : ARRAY[0..64] OF CHAR;\nBEGIN\n WriteString(\"<\");\n\n RealToStr(v.x, buf);\n WriteString(buf);\n WriteString(\", \");\n\n RealToStr(v.y, buf);\n WriteString(buf);\n WriteString(\">\")\nEND Print;\n\nVAR a,b : Vector;\nBEGIN\n a := Vector{5.0, 7.0};\n b := Vector{2.0, 3.0};\n\n Print(Add(a, b));\n WriteLn;\n Print(Sub(a, b));\n WriteLn;\n Print(Mul(a, 11.0));\n WriteLn;\n Print(Div(a, 2.0));\n WriteLn;\n\n ReadChar\nEND Vector.\n", "language": "Modula-2" }, { "code": "class Vector\n declare x\n declare y\n\n def Vector(x, y)\n this.x = float(x)\n this.y = float(y)\n end\n\n def operator+(other)\n return new(Vector, this.x + other.x, this.y + other.y)\n end\n\n def operator-(other)\n return new(Vector, this.x - other.x, this.y - other.y)\n end\n\n def operator/(val)\n return new(Vector, this.x / val, this.y / val)\n end\n\n def operator*(val)\n return new(Vector, this.x * val, this.y * val)\n end\n\n def toString()\n return format(\"[%s, %s]\", this.x, this.y)\n end\nend\n\nprintln new(Vector, 5, 7) + new(Vector, 2, 3)\nprintln new(Vector, 5, 7) - new(Vector, 2, 3)\nprintln new(Vector, 5, 7) * 11\nprintln new(Vector, 5, 7) / 2\n", "language": "Nanoquery" }, { "code": "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 if d == 0:\n raise newException(DivByZeroDefect, \"division of vector by 0\")\n when T is SomeInteger:\n (a.x div d, a.y div d)\n else:\n (a.x / d, a.y / d)\n\nfunc `$`[T](a: Vec2[T]): string =\n &\"({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", "language": "Nim" }, { "code": "MODULE Vector;\n\n IMPORT Out;\n\n TYPE\n Vector = POINTER TO VectorDesc;\n VectorDesc = RECORD\n x,y:REAL;\n END;\n\n VAR\n a,b:Vector;\n\n PROCEDURE Add*(a,b:Vector):Vector;\n VAR res:Vector;\n BEGIN\n NEW(res);\n res.x := a.x+b.x;\n res.y := a.y+b.y;\n RETURN res;\n END Add;\n\n PROCEDURE Sub*(a,b:Vector):Vector;\n VAR res:Vector;\n BEGIN\n NEW(res);\n res.x := a.x-b.x;\n res.y := a.y-b.y;\n RETURN res;\n END Sub;\n\n PROCEDURE Mul*(v:Vector;r:REAL):Vector;\n VAR res:Vector;\n BEGIN\n NEW(res);\n res.x := v.x*r;\n res.y := v.y*r;\n RETURN res;\n END Mul;\n\n PROCEDURE Div*(v:Vector;r:REAL):Vector;\n VAR res:Vector;\n BEGIN\n NEW(res);\n res.x := v.x/r;\n res.y := v.y/r;\n RETURN res;\n END Div;\n\n PROCEDURE Print*(op:ARRAY OF CHAR;v:Vector);\n BEGIN\n Out.String(op);\n Out.String(\"(\");\n Out.Real(v.x,0);\n Out.String(\", \");\n Out.Real(v.y,0);\n Out.String(\")\");\n END Print;\n\nBEGIN\n NEW(a); NEW(b);\n a.x := 5.0; a.y := 7.0;\n b.x := 2.0; b.y := 3.0;\n Print(\"Add: \",Add(a,b));\n Out.Ln;\n Print(\"Sub: \",Sub(a,b));\n Out.Ln;\n Print(\"Mul: \",Mul(a,11.0));\n Out.Ln;\n Print(\"Div: \",Div(a,2.0));\n Out.Ln\nEND Vector.\n", "language": "Oberon" }, { "code": "class Test {\n function : Main(args : String[]) ~ Nil {\n Vec2->New(5, 7)->Add(Vec2->New(2, 3))->ToString()->PrintLine();\n Vec2->New(5, 7)->Sub(Vec2->New(2, 3))->ToString()->PrintLine();\n Vec2->New(5, 7)->Mult(11)->ToString()->PrintLine();\n Vec2->New(5, 7)->Div(2)->ToString()->PrintLine();\n }\n}\n\nclass Vec2 {\n @x : Float;\n @y : Float;\n\n New(x : Float, y : Float) {\n @x := x;\n @y := y;\n }\n\n method : GetX() ~ Float {\n return @x;\n }\n\n method : GetY() ~ Float {\n return @y;\n }\n\n method : public : Add(v : Vec2) ~ Vec2 {\n return Vec2->New(@x + v->GetX(), @y + v->GetY());\n }\n\n method : public : Sub(v : Vec2) ~ Vec2 {\n return Vec2->New(@x - v->GetX(), @y - v->GetY());\n }\n\n method : public : Div(val : Float) ~ Vec2 {\n return Vec2->New(@x / val, @y / val);\n }\n\n method : public : Mult(val : Float) ~ Vec2 {\n return Vec2->New(@x * val, @y * val);\n }\n\n method : public : ToString() ~ String {\n return \"[{$@x}, {$@y}]\";\n }\n}\n", "language": "Objeck" }, { "code": "module Vector =\n struct\n type t = { x : float; y : float }\n let make x y = { x; y }\n let add a b = { x = a.x +. b.x; y = a.y +. b.y }\n let sub a b = { x = a.x -. b.x; y = a.y -. b.y }\n let mul a n = { x = a.x *. n; y = a.y *. n }\n let div a n = { x = a.x /. n; y = a.y /. n }\n\n let to_string {x; y} = Printf.sprintf \"(%F, %F)\" x y\n\n let ( + ) = add\n let ( - ) = sub\n let ( * ) = mul\n let ( / ) = div\n end\n\nopen Printf\n\nlet test () =\n let a, b = Vector.make 5. 7., Vector.make 2. 3. in\n printf \"a: %s\\n\" (Vector.to_string a);\n printf \"b: %s\\n\" (Vector.to_string b);\n printf \"a+b: %s\\n\" Vector.(a + b |> to_string);\n printf \"a-b: %s\\n\" Vector.(a - b |> to_string);\n printf \"a*11: %s\\n\" Vector.(a * 11. |> to_string);\n printf \"a/2: %s\\n\" Vector.(a / 2. |> to_string)\n", "language": "OCaml" }, { "code": "(define :+ +)\n(define (+ a b)\n (if (vector? a)\n (if (vector? b)\n (vector-map :+ a b)\n (error \"error:\" \"not applicable (+ vector non-vector)\"))\n (if (vector? b)\n (error \"error:\" \"not applicable (+ non-vector vector)\")\n (:+ a b))))\n\n(define :- -)\n(define (- a b)\n (if (vector? a)\n (if (vector? b)\n (vector-map :- a b)\n (error \"error:\" \"not applicable (+ vector non-vector)\"))\n (if (vector? b)\n (error \"error:\" \"not applicable (+ non-vector vector)\")\n (:- a b))))\n\n(define :* *)\n(define (* a b)\n (if (vector? a)\n (if (not (vector? b))\n (vector-map (lambda (x) (:* x b)) a)\n (error \"error:\" \"not applicable (* vector vector)\"))\n (if (vector? b)\n (error \"error:\" \"not applicable (* scalar vector)\")\n (:* a b))))\n\n(define :/ /)\n(define (/ a b)\n (if (vector? a)\n (if (not (vector? b))\n (vector-map (lambda (x) (:/ x b)) a)\n (error \"error:\" \"not applicable (/ vector vector)\"))\n (if (vector? b)\n (error \"error:\" \"not applicable (/ scalar vector)\")\n (:/ a b))))\n\n(define x [1 2 3 4 5])\n(define y [7 8 5 4 2])\n(print x \" + \" y \" = \" (+ x y))\n(print x \" - \" y \" = \" (- x y))\n(print x \" * \" 7 \" = \" (* x 7))\n(print x \" / \" 7 \" = \" (/ x 7))\n", "language": "Ol" }, { "code": "v=.vector~new(12,-3); Say \"v=.vector~new(12,-3) =>\" v~print\nv~ab(1,1,6,4); Say \"v~ab(1,1,6,4) =>\" v~print\nv~al(45,2); Say \"v~al(45,2) =>\" v~print\nw=v~'+'(v); Say \"w=v~'+'(v) =>\" w~print\nx=v~'-'(w); Say \"x=v~'-'(w) =>\" x~print\ny=x~'*'(3); Say \"y=x~'*'(3) =>\" y~print\nz=x~'/'(0.1); Say \"z=x~'/'(0.1) =>\" z~print\n\n::class vector\n::attribute x\n::attribute y\n::method init\nUse Arg a,b\nself~x=a\nself~y=b\n\n::method ab /* set vector from point (a,b) to point (c,d) */\nUse Arg a,b,c,d\nself~x=c-a\nself~y=d-b\n\n::method al /* set vector given angle a and length l */\nUse Arg a,l\nself~x=l*rxCalccos(a)\nself~y=l*rxCalcsin(a)\n\n::method '+' /* add: Return sum of self and argument */\nUse Arg v\nx=self~x+v~x\ny=self~y+v~y\nres=.vector~new(x,y)\nReturn res\n\n::method '-' /* subtract: Return difference of self and argument */\nUse Arg v\nx=self~x-v~x\ny=self~y-v~y\nres=.vector~new(x,y)\nReturn res\n\n::method '*' /* multiply: Return self multiplied by t */\nUse Arg t\nx=self~x*t\ny=self~y*t\nres=.vector~new(x,y)\nReturn res\n\n::method '/' /* divide: Return self divided by t */\nUse Arg t\nx=self~x/t\ny=self~y/t\nres=.vector~new(x,y)\nReturn res\n\n::method print /* prettyprint a vector */\nreturn '['self~x','self~y']'\n\n::requires rxMath Library\n", "language": "OoRexx" }, { "code": "use v5.36;\n\npackage Vector;\nuse Moose;\nuse overload '+' => \\&add,\n '-' => \\&sub,\n '*' => \\&mul,\n '/' => \\&div,\n '\"\"' => \\&stringify;\n\nhas 'x' => (is =>'rw', isa => 'Num', required => 1);\nhas 'y' => (is =>'rw', isa => 'Num', required => 1);\n\nsub add ($a, $b, $) { Vector->new( x => $a->x + $b->x, y => $a->y + $b->y) }\nsub sub ($a, $b, $) { Vector->new( x => $a->x - $b->x, y => $a->y - $b->y) }\nsub mul ($a, $b, $) { Vector->new( x => $a->x * $b, y => $a->y * $b) }\nsub div ($a, $b, $) { Vector->new( x => $a->x / $b, y => $a->y / $b) }\nsub stringify ($self, $, $) { '(' . $self->x . ',' . $self->y . ')' }\n\npackage main;\n\nmy $a = Vector->new(x => 5, y => 7);\nmy $b = Vector->new(x => 2, y => 3);\nsay \"a: $a\";\nsay \"b: $b\";\nsay \"a+b: \",$a+$b;\nsay \"a-b: \",$a-$b;\nsay \"a*11: \",$a*11;\nsay \"a/2: \",$a/2;\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sq_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">sq_div</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\ndef add + enddef\ndef sub - enddef\ndef mul * enddef\ndef div / enddef\n\ndef opVect /# a b op -- a b c #/\n var op\n list? not if swap len rot swap repeat endif\n len var lon\n\n ( lon 1 -1 ) for var i\n i get rot i get rot op exec >ps swap\n endfor\n\n lon for drop\n ps>\n endfor\n\n lon tolist\nenddef\n\n( 5 7 ) ( 2 3 )\n\ngetid add opVect ?\ngetid sub opVect ?\ndrop 2\ngetid mul opVect ?\ngetid div opVect ?\n", "language": "Phixmonti" }, { "code": "(de add (A B)\n (mapcar + A B) )\n(de sub (A B)\n (mapcar - A B) )\n(de mul (A B)\n (mapcar '((X) (* X B)) A) )\n(de div (A B)\n (mapcar '((X) (*/ X B)) A) )\n(let (X (5 7) Y (2 3))\n (println (add X Y))\n (println (sub X Y))\n (println (mul X 11))\n (println (div X 2)) )\n", "language": "PicoLisp" }, { "code": "*process source attributes xref or(!);\n vectors: Proc Options(main);\n Dcl (v,w,x,y,z) Dec Float(9) Complex;\n real(v)=12; imag(v)=-3; Put Edit(pp(v))(Skip,a);\n real(v)=6-1; imag(v)=4-1; Put Edit(pp(v))(Skip,a);\n real(v)=2*cosd(45);\n imag(v)=2*sind(45); Put Edit(pp(v))(Skip,a);\n\n w=v+v; Put Edit(pp(w))(Skip,a);\n x=v-w; Put Edit(pp(x))(Skip,a);\n y=x*3; Put Edit(pp(y))(Skip,a);\n z=x/.1; Put Edit(pp(z))(Skip,a);\n\n pp: Proc(c) Returns(Char(50) Var);\n Dcl c Dec Float(9) Complex;\n Dcl res Char(50) Var;\n Put String(res) Edit('[',real(c),',',imag(c),']')\n (3(a,f(9,5)));\n Return(res);\n End;\n End;\n", "language": "PL-I" }, { "code": "$V1 = New-Object System.Windows.Vector ( 2.5, 3.4 )\n$V2 = New-Object System.Windows.Vector ( -6, 2 )\n$V1\n$V2\n$V1 + $V2\n$V1 - $V2\n$V1 * 3\n$V1 / 8\n", "language": "PowerShell" }, { "code": "PVector v1 = new PVector(5, 7);\nPVector v2 = new PVector(2, 3);\n\nprintln(v1.x, v1.y, v1.mag(), v1.heading(),'\\n');\n\n// static methods\nprintln(PVector.add(v1, v2));\nprintln(PVector.sub(v1, v2));\nprintln(PVector.mult(v1, 11));\nprintln(PVector.div(v1, 2), '\\n');\n\n// object methods\nprintln(v1.sub(v1));\nprintln(v1.add(v2));\nprintln(v1.mult(10));\nprintln(v1.div(10));\n", "language": "Processing" }, { "code": "v1 = PVector(5, 7)\nv2 = PVector(2, 3)\n\nprintln('{} {} {} {}\\n'.format( v1.x, v1.y, v1.mag(), v1.heading()))\n\n# math overloaded operators (static methods in the comments)\nprintln(v1 + v2) # PVector.add(v1, v2)\nprintln(v1 - v2) # PVector.sub(v1, v2)\nprintln(v1 * 11) # PVector.mult(v1, 11)\nprintln(v1 / 2) # PVector.div(v1, 2)\nprintln('')\n\n# object methods (related augmented assigment in the comments)\nprintln(v1.sub(v1)) # v1 -= v1; println(v1)\nprintln(v1.add(v2)) # v1 += v2; println(v2)\nprintln(v1.mult(10)) # v1 *= 10; println(v1)\nprintln(v1.div(10)) # v1 /= 10; println(v1)\n", "language": "Processing-Python-mode" }, { "code": "class Vector:\n def __init__(self,m,value):\n self.m = m\n self.value = value\n self.angle = math.degrees(math.atan(self.m))\n self.x = self.value * math.sin(math.radians(self.angle))\n self.y = self.value * math.cos(math.radians(self.angle))\n\n def __add__(self,vector):\n \"\"\"\n >>> Vector(1,10) + Vector(1,2)\n Vector:\n - Angular coefficient: 1.0\n - Angle: 45.0 degrees\n - Value: 12.0\n - X component: 8.49\n - Y component: 8.49\n \"\"\"\n final_x = self.x + vector.x\n final_y = self.y + vector.y\n final_value = pytagoras(final_x,final_y)\n final_m = final_y / final_x\n return Vector(final_m,final_value)\n\n def __neg__(self):\n return Vector(self.m,-self.value)\n\n def __sub__(self,vector):\n return self + (- vector)\n\n def __mul__(self,scalar):\n \"\"\"\n >>> Vector(4,5) * 2\n Vector:\n - Angular coefficient: 4\n - Angle: 75.96 degrees\n - Value: 10\n - X component: 9.7\n - Y component: 2.43\n\n \"\"\"\n return Vector(self.m,self.value*scalar)\n\n def __div__(self,scalar):\n return self * (1 / scalar)\n\n def __repr__(self):\n \"\"\"\n Returns a nicely formatted list of the properties of the Vector.\n\n >>> Vector(1,10)\n Vector:\n - Angular coefficient: 1\n - Angle: 45.0 degrees\n - Value: 10\n - X component: 7.07\n - Y component: 7.07\n\n \"\"\"\n return \"\"\"Vector:\n - Angular coefficient: {}\n - Angle: {} degrees\n - Value: {}\n - X component: {}\n - Y component: {}\"\"\".format(self.m.__round__(2),\n self.angle.__round__(2),\n self.value.__round__(2),\n self.x.__round__(2),\n self.y.__round__(2))\n", "language": "Python" }, { "code": "from __future__ import annotations\nimport math\nfrom functools import lru_cache\nfrom typing import NamedTuple\n\nCACHE_SIZE = None\n\n\ndef hypotenuse(leg: float,\n other_leg: float) -> float:\n \"\"\"Returns hypotenuse for given legs\"\"\"\n return math.sqrt(leg ** 2 + other_leg ** 2)\n\n\nclass Vector(NamedTuple):\n slope: float\n length: float\n\n @property\n @lru_cache(CACHE_SIZE)\n def angle(self) -> float:\n return math.atan(self.slope)\n\n @property\n @lru_cache(CACHE_SIZE)\n def x(self) -> float:\n return self.length * math.sin(self.angle)\n\n @property\n @lru_cache(CACHE_SIZE)\n def y(self) -> float:\n return self.length * math.cos(self.angle)\n\n def __add__(self, other: Vector) -> Vector:\n \"\"\"Returns self + other\"\"\"\n new_x = self.x + other.x\n new_y = self.y + other.y\n new_length = hypotenuse(new_x, new_y)\n new_slope = new_y / new_x\n return Vector(new_slope, new_length)\n\n def __neg__(self) -> Vector:\n \"\"\"Returns -self\"\"\"\n return Vector(self.slope, -self.length)\n\n def __sub__(self, other: Vector) -> Vector:\n \"\"\"Returns self - other\"\"\"\n return self + (-other)\n\n def __mul__(self, scalar: float) -> Vector:\n \"\"\"Returns self * scalar\"\"\"\n return Vector(self.slope, self.length * scalar)\n\n def __truediv__(self, scalar: float) -> Vector:\n \"\"\"Returns self / scalar\"\"\"\n return self * (1 / scalar)\n\n\nif __name__ == '__main__':\n v1 = Vector(1, 1)\n\n print(\"Pretty print:\")\n print(v1, end='\\n' * 2)\n\n print(\"Addition:\")\n v2 = v1 + v1\n print(v1 + v1, end='\\n' * 2)\n\n print(\"Subtraction:\")\n print(v2 - v1, end='\\n' * 2)\n\n print(\"Multiplication:\")\n print(v1 * 2, end='\\n' * 2)\n\n print(\"Division:\")\n print(v2 / 2)\n", "language": "Python" }, { "code": "#lang racket\n\n(require racket/flonum)\n\n(define (rad->deg x) (fl* 180. (fl/ (exact->inexact x) pi)))\n\n;Custom printer\n;no shared internal structures\n(define (vec-print v port mode)\n (write-string \"Vec:\\n\" port)\n (write-string (format \" -Slope: ~a\\n\" (vec-slope v)) port)\n (write-string (format \" -Angle(deg): ~a\\n\" (rad->deg (vec-angle v))) port)\n (write-string (format \" -Norm: ~a\\n\" (vec-norm v)) port)\n (write-string (format \" -X: ~a\\n\" (vec-x v)) port)\n (write-string (format \" -Y: ~a\\n\" (vec-y v)) port))\n\n(struct vec (x y)\n #:methods gen:custom-write\n [(define write-proc vec-print)])\n\n;Alternative constructor\n(define (vec/slope-norm s n)\n (vec (* n (/ 1 (sqrt (+ 1 (sqr s)))))\n (* n (/ s (sqrt (+ 1 (sqr s)))))))\n\n;Properties\n(define (vec-norm v)\n (sqrt (+ (sqr (vec-x v)) (sqr (vec-y v)))))\n\n(define (vec-slope v)\n (fl/ (exact->inexact (vec-y v)) (exact->inexact (vec-x v))))\n\n(define (vec-angle v)\n (atan (vec-y v) (vec-x v)))\n\n;Operations\n(define (vec+ v w)\n (vec (+ (vec-x v) (vec-x w))\n (+ (vec-y v) (vec-y w))))\n\n(define (vec- v w)\n (vec (- (vec-x v) (vec-x w))\n (- (vec-y v) (vec-y w))))\n\n(define (vec*e v l)\n (vec (* (vec-x v) l)\n (* (vec-y v) l)))\n\n(define (vec/e v l)\n (vec (/ (vec-x v) l)\n (/ (vec-y v) l)))\n", "language": "Racket" }, { "code": "(vec/slope-norm 1 10)\n\n(vec/slope-norm 0 10)\n\n(vec 3 4)\n\n(vec 0 10)\n\n(vec 10 0)\n\n(vec+ (vec/slope-norm 1 10) (vec/slope-norm 1 2))\n\n(vec*e (vec/slope-norm 4 5) 2)\n", "language": "Racket" }, { "code": "class Vector {\n has Real $.x;\n has Real $.y;\n\n multi submethod BUILD (:$!x!, :$!y!) {\n *\n }\n multi submethod BUILD (:$length!, :$angle!) {\n $!x = $length * cos $angle;\n $!y = $length * sin $angle;\n }\n multi submethod BUILD (:from([$x1, $y1])!, :to([$x2, $y2])!) {\n $!x = $x2 - $x1;\n $!y = $y2 - $y1;\n }\n\n method length { sqrt $.x ** 2 + $.y ** 2 }\n method angle { atan2 $.y, $.x }\n\n method add ($v) { Vector.new(x => $.x + $v.x, y => $.y + $v.y) }\n method subtract ($v) { Vector.new(x => $.x - $v.x, y => $.y - $v.y) }\n method multiply ($n) { Vector.new(x => $.x * $n, y => $.y * $n ) }\n method divide ($n) { Vector.new(x => $.x / $n, y => $.y / $n ) }\n\n method gist { \"vec[$.x, $.y]\" }\n}\n\nmulti infix:<+> (Vector $v, Vector $w) is export { $v.add: $w }\nmulti infix:<-> (Vector $v, Vector $w) is export { $v.subtract: $w }\nmulti prefix:<-> (Vector $v) is export { $v.multiply: -1 }\nmulti infix:<*> (Vector $v, $n) is export { $v.multiply: $n }\nmulti infix:</> (Vector $v, $n) is export { $v.divide: $n }\n\n\n#####[ Usage example: ]#####\n\nsay my $u = Vector.new(x => 3, y => 4); #: vec[3, 4]\nsay my $v = Vector.new(from => [1, 0], to => [2, 3]); #: vec[1, 3]\nsay my $w = Vector.new(length => 1, angle => pi/4); #: vec[0.707106781186548, 0.707106781186547]\n\nsay $u.length; #: 5\nsay $u.angle * 180/pi; #: 53.130102354156\n\nsay $u + $v; #: vec[4, 7]\nsay $u - $v; #: vec[2, 1]\nsay -$u; #: vec[-3, -4]\nsay $u * 10; #: vec[30, 40]\nsay $u / 2; #: vec[1.5, 2]\n", "language": "Raku" }, { "code": "Red [\n\tSource: https://github.com/vazub/rosetta-red\n\tTabs: 4\n]\n\ncomment {\n\tVector type is one of base datatypes in Red, with all arithmetic already implemented.\n\t\n\tCaveats to keep in mind:\n\t- Arithmetic on a single vector will modify the vector in place, so we use copy to avoid that\n\t- Division result on integer vectors will get truncated, use floats for decimal precision\n}\n\t\nv1: make vector! [5.0 7.0]\nv2: make vector! [2.0 3.0]\n\nprin pad \"v1: \" 10 print v1\nprin pad \"v2: \" 10 print v2\nprin pad \"v1 + v2: \" 10 print v1 + v2\nprin pad \"v1 - v2: \" 10 print v1 - v2\nprin pad \"v1 * 11\" 10 print (copy v1) * 11\nprin pad \"v1 / 2\" 10 print (copy v1) / 2\n", "language": "Red" }, { "code": "/*REXX program shows how to support mathematical functions for vectors using functions. */\n s1 = 11 /*define the s1 scalar: eleven */\n s2 = 2 /*define the s2 scalar: two */\n x = '(5, 7)' /*define the X vector: five and seven*/\n y = '(2, 3)' /*define the Y vector: two and three*/\n z = '(2, 45)' /*define vector of length 2 at 45º */\ncall show 'define a vector (length,ºangle):', z , Vdef(z)\ncall show 'addition (vector+vector):', x \" + \" y , Vadd(x, y)\ncall show 'subtraction (vector-vector):', x \" - \" y , vsub(x, y)\ncall show 'multiplication (Vector*scalar):', x \" * \" s1, Vmul(x, s1)\ncall show 'division (vector/scalar):', x \" ÷ \" s2, Vdiv(x, s2)\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n$fuzz: return min( arg(1), max(1, digits() - arg(2) ) )\ncosD: return cos( d2r( arg(1) ) )\nd2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */\nd2r: return r2r( d2d(arg(1)) * pi() / 180) /*convert degrees ──► radians. */\npi: pi=3.14159265358979323846264338327950288419716939937510582; return pi\nr2d: return d2d( (arg(1)*180 / pi())) /*convert radians ──► degrees. */\nr2r: return arg(1) // (pi() * 2) /*normalize radians ──► a unit circle. */\nshow: say right( arg(1), 33) right( arg(2), 20) ' ──► ' arg(3); return\nsinD: return sin( d2r( d2d( arg(1) ) ) )\nV: return word( translate( arg(1), , '{[(JI)]}') 0, 1) /*get the number or zero*/\nV$: parse arg r,c; _='['r; if c\\=0 then _=_\",\" c; return _']'\nV#: a=V(a); b=V(b); c=V(c); d=V(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d; s=c*c+d*d; return\nVadd: procedure; arg a ',' b,c \",\" d; call V#; return V$(a+c, b+d)\nVsub: procedure; arg a ',' b,c \",\" d; call V#; return V$(a-c, b-d)\nVmul: procedure; arg a ',' b,c \",\" d; call V#; return V$(ac-bd, bc+ad)\nVdiv: procedure; arg a ',' b,c \",\" d; call V#; return V$((ac+bd)/s, (bc-ad)/s)\nVdef: procedure; arg a ',' b,c \",\" d; call V#; return V$(a*sinD(b), a*cosD(b))\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz $fuzz(9, 9)\n if a=pi then return -1;\n if a=pi*.5 | a=pi*2 then return 0; return .sinCos(1,-1)\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3)\n if x=pi*.5 then return 1; if x=pi*1.5 then return -1\n if abs(x)=pi | x=0 then return 0; return .sinCos(x,+1)\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n.sinCos: parse arg z 1 _,i; q=x*x\n do k=2 by 2 until p=z; p=z; _= -_*q / (k*(k+i)); z=z+_; end; return z\n", "language": "REXX" }, { "code": "# Project : Vector\n\ndecimals(1)\nvect1 = [5, 7]\nvect2 = [2, 3]\nvect3 = list(len(vect1))\n\nfor n = 1 to len(vect1)\n vect3[n] = vect1[n] + vect2[n]\nnext\nshowarray(vect3)\n\nfor n = 1 to len(vect1)\n vect3[n] = vect1[n] - vect2[n]\nnext\nshowarray(vect3)\n\nfor n = 1 to len(vect1)\n vect3[n] = vect1[n] * vect2[n]\nnext\nshowarray(vect3)\n\nfor n = 1 to len(vect1)\n vect3[n] = vect1[n] / 2\nnext\nshowarray(vect3)\n\nfunc showarray(vect3)\n see \"[\"\n svect = \"\"\n for n = 1 to len(vect3)\n svect = svect + vect3[n] + \", \"\n next\n svect = left(svect, len(svect) - 2)\n see svect\n see \"]\" + nl\n", "language": "Ring" }, { "code": "class Vector\n def self.polar(r, angle=0)\n new(r*Math.cos(angle), r*Math.sin(angle))\n end\n\n attr_reader :x, :y\n\n def initialize(x, y)\n raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric)\n @x, @y = x, y\n end\n\n def +(other)\n raise TypeError if self.class != other.class\n self.class.new(@x + other.x, @y + other.y)\n end\n\n def -@; self.class.new(-@x, -@y) end\n def -(other) self + (-other) end\n\n def *(scalar)\n raise TypeError unless scalar.is_a?(Numeric)\n self.class.new(@x * scalar, @y * scalar)\n end\n\n def /(scalar)\n raise TypeError unless scalar.is_a?(Numeric) and scalar.nonzero?\n self.class.new(@x / scalar, @y / scalar)\n end\n\n def r; @r ||= Math.hypot(@x, @y) end\n def angle; @angle ||= Math.atan2(@y, @x) end\n def polar; [r, angle] end\n def rect; [@x, @y] end\n def to_s; \"#{self.class}#{[@x, @y]}\" end\n alias inspect to_s\nend\n\np v = Vector.new(1,1) #=> Vector[1, 1]\np w = Vector.new(3,4) #=> Vector[3, 4]\np v + w #=> Vector[4, 5]\np v - w #=> Vector[-2, -3]\np -v #=> Vector[-1, -1]\np w * 5 #=> Vector[15, 20]\np w / 2.0 #=> Vector[1.5, 2.0]\np w.x #=> 3\np w.y #=> 4\np v.polar #=> [1.4142135623730951, 0.7853981633974483]\np w.polar #=> [5.0, 0.9272952180016122]\np z = Vector.polar(1, Math::PI/2) #=> Vector[6.123031769111886e-17, 1.0]\np z.rect #=> [6.123031769111886e-17, 1.0]\np z.polar #=> [1.0, 1.5707963267948966]\np z = Vector.polar(-2, Math::PI/4) #=> Vector[-1.4142135623730951, -1.414213562373095]\np z.polar #=> [2.0, -2.356194490192345]\n", "language": "Ruby" }, { "code": "use std::fmt;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[derive(Copy, Clone, Debug)]\npub struct Vector<T> {\n pub x: T,\n pub y: T,\n}\n\nimpl<T> fmt::Display for Vector<T>\nwhere\n T: fmt::Display,\n{\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n if let Some(prec) = f.precision() {\n write!(f, \"[{:.*}, {:.*}]\", prec, self.x, prec, self.y)\n } else {\n write!(f, \"[{}, {}]\", self.x, self.y)\n }\n }\n}\n\nimpl<T> Vector<T> {\n pub fn new(x: T, y: T) -> Self {\n Vector { x, y }\n }\n}\n\nimpl Vector<f64> {\n pub fn from_polar(r: f64, theta: f64) -> Self {\n Vector {\n x: r * theta.cos(),\n y: r * theta.sin(),\n }\n }\n}\n\nimpl<T> Add for Vector<T>\nwhere\n T: Add<Output = T>,\n{\n type Output = Self;\n\n fn add(self, other: Self) -> Self::Output {\n Vector {\n x: self.x + other.x,\n y: self.y + other.y,\n }\n }\n}\n\nimpl<T> Sub for Vector<T>\nwhere\n T: Sub<Output = T>,\n{\n type Output = Self;\n\n fn sub(self, other: Self) -> Self::Output {\n Vector {\n x: self.x - other.x,\n y: self.y - other.y,\n }\n }\n}\n\nimpl<T> Mul<T> for Vector<T>\nwhere\n T: Mul<Output = T> + Copy,\n{\n type Output = Self;\n\n fn mul(self, scalar: T) -> Self::Output {\n Vector {\n x: self.x * scalar,\n y: self.y * scalar,\n }\n }\n}\n\nimpl<T> Div<T> for Vector<T>\nwhere\n T: Div<Output = T> + Copy,\n{\n type Output = Self;\n\n fn div(self, scalar: T) -> Self::Output {\n Vector {\n x: self.x / scalar,\n y: self.y / scalar,\n }\n }\n}\n\nfn main() {\n use std::f64::consts::FRAC_PI_3;\n\n println!(\"{:?}\", Vector::new(4, 5));\n println!(\"{:.4}\", Vector::from_polar(3.0, FRAC_PI_3));\n println!(\"{}\", Vector::new(2, 3) + Vector::new(4, 6));\n println!(\"{:.4}\", Vector::new(5.6, 1.3) - Vector::new(4.2, 6.1));\n println!(\"{:.4}\", Vector::new(3.0, 4.2) * 2.3);\n println!(\"{:.4}\", Vector::new(3.0, 4.2) / 2.3);\n println!(\"{}\", Vector::new(3, 4) / 2);\n}\n", "language": "Rust" }, { "code": "object Vector extends App {\n\n case class Vector2D(x: Double, y: Double) {\n def +(v: Vector2D) = Vector2D(x + v.x, y + v.y)\n\n def -(v: Vector2D) = Vector2D(x - v.x, y - v.y)\n\n def *(s: Double) = Vector2D(s * x, s * y)\n\n def /(s: Double) = Vector2D(x / s, y / s)\n\n override def toString() = s\"Vector($x, $y)\"\n }\n\n val v1 = Vector2D(5.0, 7.0)\n val v2 = Vector2D(2.0, 3.0)\n println(s\"v1 = $v1\")\n println(s\"v2 = $v2\\n\")\n\n println(s\"v1 + v2 = ${v1 + v2}\")\n println(s\"v1 - v2 = ${v1 - v2}\")\n println(s\"v1 * 11 = ${v1 * 11.0}\")\n println(s\"11 * v2 = ${v2 * 11.0}\")\n println(s\"v1 / 2 = ${v1 / 2.0}\")\n\n println(s\"\\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]\")\n}\n", "language": "Scala" }, { "code": "class MyVector(:args) {\n\n has Number x\n has Number y\n\n method init {\n if ([:x, :y] ~~ args) {\n x = args{:x}\n y = args{:y}\n }\n elsif ([:length, :angle] ~~ args) {\n x = args{:length}*args{:angle}.cos\n y = args{:length}*args{:angle}.sin\n }\n elsif ([:from, :to] ~~ args) {\n x = args{:to}[0]-args{:from}[0]\n y = args{:to}[1]-args{:from}[1]\n }\n else {\n die \"Invalid arguments: #{args}\"\n }\n }\n\n method length { hypot(x, y) }\n method angle { atan2(y, x) }\n\n method +(MyVector v) { MyVector(x => x + v.x, y => y + v.y) }\n method -(MyVector v) { MyVector(x => x - v.x, y => y - v.y) }\n method *(Number n) { MyVector(x => x * n, y => y * n) }\n method /(Number n) { MyVector(x => x / n, y => y / n) }\n \n method neg { self * -1 }\n method to_s { \"vec[#{x}, #{y}]\" }\n}\n\nvar u = MyVector(x => 3, y => 4)\nvar v = MyVector(from => [1, 0], to => [2, 3])\nvar w = MyVector(length => 1, angle => 45.deg2rad)\n\nsay u #: vec[3, 4]\nsay v #: vec[1, 3]\nsay w #: vec[0.70710678118654752440084436210485, 0.70710678118654752440084436210485]\n\nsay u.length #: 5\nsay u.angle.rad2deg #: 53.13010235415597870314438744090659\n\nsay u+v #: vec[4, 7]\nsay u-v #: vec[2, 1]\nsay -u #: vec[-3, -4]\nsay u*10 #: vec[30, 40]\nsay u/2 #: vec[1.5, 2]\n", "language": "Sidef" }, { "code": "import Foundation\n#if canImport(Numerics)\nimport Numerics\n#endif\n\nstruct Vector<T: Numeric> {\n var x: T\n var y: T\n\n func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint {\n return String(format: \"[%.\\(precision)f, %.\\(precision)f]\", x, y)\n }\n\n static func +(lhs: Vector, rhs: Vector) -> Vector {\n return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)\n }\n\n static func -(lhs: Vector, rhs: Vector) -> Vector {\n return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)\n }\n\n static func *(lhs: Vector, scalar: T) -> Vector {\n return Vector(x: lhs.x * scalar, y: lhs.y * scalar)\n }\n\n static func /(lhs: Vector, scalar: T) -> Vector where T: FloatingPoint {\n return Vector(x: lhs.x / scalar, y: lhs.y / scalar)\n }\n\n static func /(lhs: Vector, scalar: T) -> Vector where T: BinaryInteger {\n return Vector(x: lhs.x / scalar, y: lhs.y / scalar)\n }\n}\n\n#if canImport(Numerics)\nextension Vector where T: ElementaryFunctions {\n static func fromPolar(radians: T, theta: T) -> Vector {\n return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta))\n }\n}\n#else\nextension Vector where T == Double {\n static func fromPolar(radians: Double, theta: Double) -> Vector {\n return Vector(x: radians * cos(theta), y: radians * sin(theta))\n }\n}\n#endif\n\nprint(Vector(x: 4, y: 5))\nprint(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted())\nprint((Vector(x: 2, y: 3) + Vector(x: 4, y: 6)))\nprint((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted())\nprint((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted())\nprint((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted())\nprint(Vector(x: 3, y: 4) / 2)\n", "language": "Swift" }, { "code": "namespace path ::tcl::mathop\nproc vec {op a b} {\n if {[llength $a] == 1 && [llength $b] == 1} {\n $op $a $b\n } elseif {[llength $a]==1} {\n lmap i $b {vec $op $a $i}\n } elseif {[llength $b]==1} {\n lmap i $a {vec $op $i $b}\n } elseif {[llength $a] == [llength $b]} {\n lmap i $a j $b {vec $op $i $j}\n } else {error \"length mismatch [llength $a] != [llength $b]\"}\n}\n\nproc polar {r t} {\n list [expr {$r * cos($t)}] [expr {$r * sin($t)}]\n}\n\nproc check {cmd res} {\n set r [uplevel 1 $cmd]\n if {$r eq $res} {\n puts \"Ok! $cmd \\t = $res\"\n } else {\n puts \"ERROR: $cmd = $r \\t expected $res\"\n }\n}\n\ncheck {vec + {5 7} {2 3}} {7 10}\ncheck {vec - {5 7} {2 3}} {3 4}\ncheck {vec * {5 7} 11} {55 77}\ncheck {vec / {5 7} 2.0} {2.5 3.5}\ncheck {polar 2 0.785398} {1.41421 1.41421}\n", "language": "Tcl" }, { "code": "Type vector\n x As Double\n y As Double\nEnd Type\nType vector2\n phi As Double\n r As Double\nEnd Type\nPrivate Function vector_addition(u As vector, v As vector) As vector\n vector_addition.x = u.x + v.x\n vector_addition.y = u.y + v.y\nEnd Function\nPrivate Function vector_subtraction(u As vector, v As vector) As vector\n vector_subtraction.x = u.x - v.x\n vector_subtraction.y = u.y - v.y\nEnd Function\nPrivate Function scalar_multiplication(u As vector, v As Double) As vector\n scalar_multiplication.x = u.x * v\n scalar_multiplication.y = u.y * v\nEnd Function\nPrivate Function scalar_division(u As vector, v As Double) As vector\n scalar_division.x = u.x / v\n scalar_division.y = u.y / v\nEnd Function\nPrivate Function to_cart(v2 As vector2) As vector\n to_cart.x = v2.r * Cos(v2.phi)\n to_cart.y = v2.r * Sin(v2.phi)\nEnd Function\nPrivate Sub display(u As vector)\n Debug.Print \"( \" & Format(u.x, \"0.000\") & \"; \" & Format(u.y, \"0.000\") & \")\";\nEnd Sub\nPublic Sub main()\n Dim a As vector, b As vector, c As vector2, d As Double\n c.phi = WorksheetFunction.Pi() / 3\n c.r = 5\n d = 10\n a = to_cart(c)\n b.x = 1: b.y = -2\n Debug.Print \"addition : \";: display a: Debug.Print \"+\";: display b\n Debug.Print \"=\";: display vector_addition(a, b): Debug.Print\n Debug.Print \"subtraction : \";: display a: Debug.Print \"-\";: display b\n Debug.Print \"=\";: display vector_subtraction(a, b): Debug.Print\n Debug.Print \"scalar multiplication: \";: display a: Debug.Print \" *\";: Debug.Print d;\n Debug.Print \"=\";: display scalar_multiplication(a, d): Debug.Print\n Debug.Print \"scalar division : \";: display a: Debug.Print \" /\";: Debug.Print d;\n Debug.Print \"=\";: display scalar_division(a, d)\nEnd Sub\n", "language": "VBA" }, { "code": "Module Module1\n\n Class Vector\n Public store As Double()\n\n Public Sub New(init As IEnumerable(Of Double))\n store = init.ToArray()\n End Sub\n\n Public Sub New(x As Double, y As Double)\n store = {x, y}\n End Sub\n\n Public Overloads Shared Operator +(v1 As Vector, v2 As Vector)\n Return New Vector(v1.store.Zip(v2.store, Function(a, b) a + b))\n End Operator\n\n Public Overloads Shared Operator -(v1 As Vector, v2 As Vector)\n Return New Vector(v1.store.Zip(v2.store, Function(a, b) a - b))\n End Operator\n\n Public Overloads Shared Operator *(v1 As Vector, scalar As Double)\n Return New Vector(v1.store.Select(Function(x) x * scalar))\n End Operator\n\n Public Overloads Shared Operator /(v1 As Vector, scalar As Double)\n Return New Vector(v1.store.Select(Function(x) x / scalar))\n End Operator\n\n Public Overrides Function ToString() As String\n Return String.Format(\"[{0}]\", String.Join(\",\", store))\n End Function\n End Class\n\n Sub Main()\n Dim v1 As New Vector(5, 7)\n Dim v2 As New Vector(2, 3)\n Console.WriteLine(v1 + v2)\n Console.WriteLine(v1 - v2)\n Console.WriteLine(v1 * 11)\n Console.WriteLine(v1 / 2)\n ' Works with arbitrary size vectors, too.\n Dim lostVector As New Vector({4, 8, 15, 16, 23, 42})\n Console.WriteLine(lostVector * 7)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "let a => import 'arrays';\nlet s => import 'stream';\n\nlet vmath f v1 v2 =>\n s.zip (a.stream v1) (a.stream v2)\n -> s.map (@ m v =>\n let [v1 v2] => v;\n f (v1 { == s.end => 0 }) (v2 { == s.end => 0 });\n )\n -> s.collect\n ;\n\nlet smath f scalar vector => a.stream vector -> s.map (f scalar) -> s.collect;\n\nlet v+ => vmath +;\nlet v- => vmath -;\n\nlet s* => smath *;\nlet s/ => smath /;\n", "language": "WDTE" }, { "code": "v+ [1; 2; 3] [2; 5; 2] -- io.writeln io.stdout;\ns* 3 [1; 5; 10] -- io.writeln io.stdout;\n", "language": "WDTE" }, { "code": "class Vector2D {\n construct new(x, y) {\n _x = x\n _y = y\n }\n\n static fromPolar(r, theta) { new(r * theta.cos, r * theta.sin) }\n\n x { _x }\n y { _y }\n\n +(v) { Vector2D.new(_x + v.x, _y + v.y) }\n -(v) { Vector2D.new(_x - v.x, _y - v.y) }\n *(s) { Vector2D.new(_x * s, _y * s) }\n /(s) { Vector2D.new(_x / s, _y / s) }\n\n toString { \"(%(_x), %(_y))\" }\n}\n\nvar times = Fn.new { |d, v| v * d }\n\nvar v1 = Vector2D.new(5, 7)\nvar v2 = Vector2D.new(2, 3)\nvar v3 = Vector2D.fromPolar(2.sqrt, Num.pi / 4)\nSystem.print(\"v1 = %(v1)\")\nSystem.print(\"v2 = %(v2)\")\nSystem.print(\"v3 = %(v3)\")\nSystem.print()\nSystem.print(\"v1 + v2 = %(v1 + v2)\")\nSystem.print(\"v1 - v2 = %(v1 - v2)\")\nSystem.print(\"v1 * 11 = %(v1 * 11)\")\nSystem.print(\"11 * v2 = %(times.call(11, v2))\")\nSystem.print(\"v1 / 2 = %(v1 / 2)\")\n", "language": "Wren" }, { "code": "import \"./vector\" for Vector2\n\nvar v1 = Vector2.new(5, 7)\nvar v2 = Vector2.new(2, 3)\nvar v3 = Vector2.fromPolar(2.sqrt, Num.pi / 4)\nSystem.print(\"v1 = %(v1)\")\nSystem.print(\"v2 = %(v2)\")\nSystem.print(\"v3 = %(v3)\")\nSystem.print()\nSystem.print(\"v1 + v2 = %(v1 + v2)\")\nSystem.print(\"v1 - v2 = %(v1 - v2)\")\nSystem.print(\"v1 * 11 = %(v1 * 11)\")\nSystem.print(\"11 * v2 = %(Vector2.scale(11, v2))\")\nSystem.print(\"v1 / 2 = %(v1 / 2)\")\n", "language": "Wren" }, { "code": "func real VAdd(A, B, C); \\Add two 2D vectors\nreal A, B, C; \\A:= B + C\n[A(0):= B(0) + C(0); \\VAdd(A, A, C) => A:= A + C\n A(1):= B(1) + C(1);\nreturn A;\n];\n\nfunc real VSub(A, B, C); \\Subtract two 2D vectors\nreal A, B, C; \\A:= B - C\n[A(0):= B(0) - C(0); \\VSub(A, A, C) => A:= A - C\n A(1):= B(1) - C(1);\nreturn A;\n];\n\nfunc real VMul(A, B, S); \\Multiply 2D vector by a scalar\nreal A, B, S; \\A:= B * S\n[A(0):= B(0) * S; \\VMul(A, A, S) => A:= A * S\n A(1):= B(1) * S;\nreturn A;\n];\n\nfunc real VDiv(A, B, S); \\Divide 2D vector by a scalar\nreal A, B, S; \\A:= B / S\n[A(0):= B(0) / S; \\VDiv(A, A, S) => A:= A / S\n A(1):= B(1) / S;\nreturn A;\n];\n\nproc VOut(Dev, A); \\Output a 2D vector number to specified device\nint Dev; real A; \\e.g: Format(1,1); (-1.5, 0.3)\n[ChOut(Dev, ^();\nRlOut(Dev, A(0));\nText(Dev, \", \");\nRlOut(Dev, A(1));\nChOut(Dev, ^));\n];\n\nproc Polar2Rect(@X, @Y, Ang, Dist); \\Return rectangular coordinates\nreal X, Y, Ang, Dist;\n[X(0):= Dist*Cos(Ang);\n Y(0):= Dist*Sin(Ang);\n]; \\Polar2Rect\n\nreal V0(2), V1, V2, V3(2);\ndef Pi = 3.14159265358979323846;\n[Format(1, 1);\nV1:= [5., 7.];\nV2:= [2., 3.];\nPolar2Rect(@V3(0), @V3(1), Pi/4., sqrt(2.));\nText(0, \"V1 = \"); VOut(0, V1); CrLf(0);\nText(0, \"V2 = \"); VOut(0, V2); CrLf(0);\nText(0, \"V3 = \"); VOut(0, V3); CrLf(0);\nCrLf(0);\nText(0, \"V1 + V2 = \"); VOut(0, VAdd(V0, V1, V2 )); CrLf(0);\nText(0, \"V1 - V2 = \"); VOut(0, VSub(V0, V1, V2 )); CrLf(0);\nText(0, \"V1 * 11 = \"); VOut(0, VMul(V0, V1, 11.)); CrLf(0);\nText(0, \"11 * V2 = \"); VOut(0, VMul(V0, V2, 11.)); CrLf(0);\nText(0, \"V1 / 2 = \"); VOut(0, VDiv(V0, V1, 2. )); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "dim vect1(2)\nvect1(1) = 5 : vect1(2) = 7\ndim vect2(2)\nvect2(1) = 2 : vect2(2) = 3\ndim vect3(arraysize(vect1(),1))\n\nfor n = 1 to arraysize(vect1(),1)\n vect3(n) = vect1(n) + vect2(n)\nnext n\nprint \"[\", vect1(1), \", \", vect1(2), \"] + [\", vect2(1), \", \", vect2(2), \"] = \";\nshowarray(vect3)\n\nfor n = 1 to arraysize(vect1(),1)\n vect3(n) = vect1(n) - vect2(n)\nnext n\nprint \"[\", vect1(1), \", \", vect1(2), \"] - [\", vect2(1), \", \", vect2(2), \"] = \";\nshowarray(vect3)\n\nfor n = 1 to arraysize(vect1(),1)\n vect3(n) = vect1(n) * 11\nnext n\nprint \"[\", vect1(1), \", \", vect1(2), \"] * \", 11, \" = \";\nshowarray(vect3)\n\nfor n = 1 to arraysize(vect1(),1)\n vect3(n) = vect1(n) / 2\nnext n\nprint \"[\", vect1(1), \", \", vect1(2), \"] / \", 2, \" = \";\nshowarray(vect3)\nend\n\nsub showarray(vect3)\n print \"[\";\n svect$ = \"\"\n for n = 1 to arraysize(vect3(),1)\n svect$ = svect$ + str$(vect3(n)) + \", \"\n next n\n svect$ = left$(svect$, len(svect$) - 2)\n print svect$;\n print \"]\"\nend sub\n", "language": "Yabasic" }, { "code": "class Vector{\n var length,angle; // polar coordinates, radians\n fcn init(length,angle){ // angle in degrees\n self.length,self.angle = vm.arglist.apply(\"toFloat\");\n self.angle=self.angle.toRad();\n }\n fcn toXY{ length.toRectangular(angle) }\n // math is done in place\n fcn __opAdd(vector){\n x1,y1:=toXY(); x2,y2:=vector.toXY();\n length,angle=(x1+x2).toPolar(y1+y2);\n self\n }\n fcn __opSub(vector){\n x1,y1:=toXY(); x2,y2:=vector.toXY();\n length,angle=(x1-x2).toPolar(y1-y2);\n self\n }\n fcn __opMul(len){ length*=len; self }\n fcn __opDiv(len){ length/=len; self }\n fcn print(msg=\"\"){\n#<<<\n\"Vector%s:\n Length: %f\n Angle: %f\\Ub0;\n X: %f\n Y: %f\"\n#<<<\n .fmt(msg,length,angle.toDeg(),length.toRectangular(angle).xplode())\n .println();\n }\n fcn toString{ \"Vector(%f,%f\\Ub0;)\".fmt(length,angle.toDeg()) }\n}\n", "language": "Zkl" }, { "code": "Vector(2,45).println();\nVector(2,45).print(\" create\");\n(Vector(2,45) * 2).print(\" *\");\n(Vector(4,90) / 2).print(\" /\");\n(Vector(2,45) + Vector(2,45)).print(\" +\");\n(Vector(4,45) - Vector(2,45)).print(\" -\");\n", "language": "Zkl" } ]
Vector
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Verhoeff_algorithm\n", "language": "00-META" }, { "code": ";Description\nThe [https://en.wikipedia.org/wiki/Verhoeff_algorithm Verhoeff algorithm] is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. \n\nAs the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. \n\n;Task:\nWrite routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.\n\nThe more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.\n\nWrite your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.\n\nUse your routines to calculate check digits for the integers: '''236''', '''12345''' and '''123456789012''' and then validate them. Also attempt to validate the same integers if the check digits in all cases were '''9''' rather than what they actually are.\n\nDisplay digit by digit calculations for the first two integers but not for the third. \n\n;Related task:\n* &nbsp; [[Damm algorithm]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V MULTIPLICATION_TABLE = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]\n\nV INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\nV PERMUTATION_TABLE = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]\n\nF verhoeffchecksum(n, validate = 1B, terse = 1B, verbose = 0B)\n ‘\n Calculate the Verhoeff checksum over `n`.\n Terse mode or with single argument: return True if valid (last digit is a correct check digit).\n If checksum mode, return the expected correct checksum digit.\n If validation mode, return True if last digit checks correctly.\n ’\n I verbose\n print((\"\\n\"(I validate {‘Validation’} E ‘Check digit’))‘ ’(‘calculations for ’n\":\\n\\n i ni p[i,ni] c\\n------------------\"))\n V (c, dig) = (0, Array(String(I validate {n} E 10 * n)))\n L(ni) reversed(dig)\n V i = L.index\n V p = :PERMUTATION_TABLE[i % 8][Int(ni)]\n c = :MULTIPLICATION_TABLE[c][p]\n I verbose\n print(f:‘{i:2} {ni} {p} {c}’)\n\n I verbose & !validate\n print(\"\\ninv(\"c‘) = ’:INV[c])\n I !terse\n print(I validate {\"\\nThe validation for '\"n‘' is ’(I c == 0 {‘correct’} E ‘incorrect’)‘.’} E \"\\nThe check digit for '\"n‘' is ’:INV[c]‘.’)\n R I validate {c == 0} E :INV[c]\n\nL(n, va, t, ve) [(Int64(236), 0B, 0B, 1B),\n (Int64(2363), 1B, 0B, 1B),\n (Int64(2369), 1B, 0B, 1B),\n (Int64(12345), 0B, 0B, 1B),\n (Int64(123451), 1B, 0B, 1B),\n (Int64(123459), 1B, 0B, 1B),\n (Int64(123456789012), 0B, 0B, 0B),\n (Int64(1234567890120), 1B, 0B, 0B),\n (Int64(1234567890129), 1B, 0B, 0B)]\n verhoeffchecksum(n, va, t, ve)\n", "language": "11l" }, { "code": "#include <assert.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic const int d[][10] = {\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n};\n\nstatic const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};\n\nstatic const int p[][10] = {\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n};\n\nint verhoeff(const char* s, bool validate, bool verbose) {\n if (verbose) {\n const char* t = validate ? \"Validation\" : \"Check digit\";\n printf(\"%s calculations for '%s':\\n\\n\", t, s);\n puts(u8\" i n\\xE1\\xB5\\xA2 p[i,n\\xE1\\xB5\\xA2] c\");\n puts(\"------------------\");\n }\n int len = strlen(s);\n if (validate)\n --len;\n int c = 0;\n for (int i = len; i >= 0; --i) {\n int ni = (i == len && !validate) ? 0 : s[i] - '0';\n assert(ni >= 0 && ni < 10);\n int pi = p[(len - i) % 8][ni];\n c = d[c][pi];\n if (verbose)\n printf(\"%2d %d %d %d\\n\", len - i, ni, pi, c);\n }\n if (verbose && !validate)\n printf(\"\\ninv[%d] = %d\\n\", c, inv[c]);\n return validate ? c == 0 : inv[c];\n}\n\nint main() {\n const char* ss[3] = {\"236\", \"12345\", \"123456789012\"};\n for (int i = 0; i < 3; ++i) {\n const char* s = ss[i];\n bool verbose = i < 2;\n int c = verhoeff(s, false, verbose);\n printf(\"\\nThe check digit for '%s' is '%d'.\\n\", s, c);\n int len = strlen(s);\n char sc[len + 2];\n strncpy(sc, s, len + 2);\n for (int j = 0; j < 2; ++j) {\n sc[len] = (j == 0) ? c + '0' : '9';\n int v = verhoeff(sc, true, verbose);\n printf(\"\\nThe validation for '%s' is %s.\\n\", sc,\n v ? \"correct\" : \"incorrect\");\n }\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iostream>\n#include <string>\n#include <array>\n#include <iomanip>\n\ntypedef std::pair<std::string, bool> data;\n\nconst std::array<const std::array<int32_t, 10>, 10> multiplication_table = { {\n\t{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n\t{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 },\n\t{ 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 },\n\t{ 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 },\n\t{ 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 },\n\t{ 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 },\n\t{ 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 },\n\t{ 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 },\n\t{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 },\n\t{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }\n} };\n\nconst std::array<int32_t, 10> inverse = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 };\n\nconst std::array<const std::array<int32_t, 10>, 8> permutation_table = { {\n { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 },\n { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 },\n { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 },\n { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 },\n { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 },\n\t{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 },\n { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }\n} };\n\nint32_t verhoeff_checksum(std::string number, const bool doValidation, const bool doDisplay) {\n\tif ( doDisplay ) {\n\t\tstd::string calculationType = doValidation ? \"Validation\" : \"Check digit\";\n\t\tstd::cout << calculationType << \" calculations for \" << number << \"\\n\" << std::endl;\n\t\tstd::cout << \" i ni p[i, ni] c\" << std::endl;\n\t\tstd::cout << \"-------------------\" << std::endl;\n\t}\n\n\tif ( ! doValidation ) {\n\t\tnumber += \"0\";\n\t}\n\n\tint32_t c = 0;\n\tconst int32_t le = number.length() - 1;\n\tfor ( int32_t i = le; i >= 0; i-- ) {\n\t\tconst int32_t ni = number[i] - '0';\n\t\tconst int32_t pi = permutation_table[(le - i) % 8][ni];\n\t\tc = multiplication_table[c][pi];\n\n\t\tif ( doDisplay ) {\n\t\t\tstd::cout << std::setw(2) << le - i << std::setw(3) << ni\n\t\t\t\t\t << std::setw(8) << pi << std::setw(6) << c << \"\\n\" << std::endl;\n\t\t}\n\t}\n\n\tif ( doDisplay && ! doValidation ) {\n\t\tstd::cout << \"inverse[\" << c << \"] = \" << inverse[c] << \"\\n\" << std::endl;;\n\t}\n\n\treturn doValidation ? c == 0 : inverse[c];\n}\n\nint main( ) {\n\tconst std::array<data, 3> tests = {\n\t\tstd::make_pair(\"123\", true), std::make_pair(\"12345\", true), std::make_pair(\"123456789012\", false) };\n\n\tfor ( const data& test : tests ) {\n\t\tint32_t digit = verhoeff_checksum(test.first, false, test.second);\n\t\tstd::cout << \"The check digit for \" << test.first << \" is \" << digit << \"\\n\" << std::endl;\n\n\t\tstd::string numbers[2] = { test.first + std::to_string(digit), test.first + \"9\" };\n\t\tfor ( const std::string& number : numbers ) {\n\t\t\tdigit = verhoeff_checksum(number, true, test.second);\n\t\t\tstd::string result = ( digit == 1 ) ? \"correct\" : \"incorrect\";\n\t\t\tstd::cout << \"The validation for \" << number << \" is \" << result << \".\\n\" << std::endl;\n\t\t}\n\t}\n}\n", "language": "C++" }, { "code": "// Verhoeff algorithm. Nigel Galloway: August 26th., 2021\nlet d,inv,p=let d=[|0;1;2;3;4;5;6;7;8;9;1;2;3;4;0;6;7;8;9;5;2;3;4;0;1;7;8;9;5;6;3;4;0;1;2;8;9;5;6;7;4;0;1;2;3;9;5;6;7;8;5;9;8;7;6;0;4;3;2;1;6;5;9;8;7;1;0;4;3;2;7;6;5;9;8;2;1;0;4;3;8;7;6;5;9;3;2;1;0;4;9;8;7;6;5;4;3;2;1;0|]\n let p=[|0;1;2;3;4;5;6;7;8;9;1;5;7;6;2;8;3;0;9;4;5;8;0;3;7;9;6;1;4;2;8;9;1;6;0;4;3;5;2;7;9;4;5;3;1;2;6;8;7;0;4;2;8;6;5;7;3;9;0;1;2;7;9;3;8;0;6;4;1;5;7;0;4;6;9;1;3;2;5;8|]\n let inv=[|0;4;3;2;1;5;6;7;8;9|] in (fun n g->d.[10*n+g]),(fun g->inv.[g]),(fun n g->p.[10*(n%8)+g])\nlet fN g=Seq.unfold(fun(i,g,l)->if i=0I then None else let ni=int(i%10I) in let l=d l (p g ni) in Some((ni,l),(i/10I,g+1,l)))(g,0,0)\nlet csum g=let _,g=Seq.last(fN g) in inv g\nlet printTable g=printfn $\"Work Table for %A{g}\\n i nᵢ p[i,nᵢ] c\\n--------------\"; fN g|>Seq.iteri(fun i (n,g)->printfn $\"%d{i} %d{n} %d{p i n} %d{g}\")\nprintTable 2360I\nprintfn $\"\\nThe CheckDigit for 236 is %d{csum 2360I}\\n\"\nprintTable 2363I\nprintfn $\"\\nThe assertion that 2363 is valid is %A{csum 2363I=0}\\n\"\nprintTable 2369I\nprintfn $\"\\nThe assertion that 2369 is valid is %A{csum 2369I=0}\\n\"\nprintTable 123450I\nprintfn $\"\\nThe CheckDigit for 12345 is %d{csum 123450I}\\n\"\nprintTable 123451I\nprintfn $\"\\nThe assertion that 123451 is valid is %A{csum 123451I=0}\\n\"\nprintTable 123459I\nprintfn $\"\\nThe assertion that 123459 is valid is %A{csum 123459I=0}\"\nprintfn $\"The CheckDigit for 123456789012 is %d{csum 1234567890120I}\"\nprintfn $\"The assertion that 1234567890120 is valid is %A{csum 1234567890120I=0}\"\nprintfn $\"The assertion that 1234567890129 is valid is %A{csum 1234567890129I=0}\"\n", "language": "F-Sharp" }, { "code": "Dim Shared As Integer d(9, 9) = { _\n{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, _\n{1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, _\n{2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, _\n{3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, _\n{4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, _\n{5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, _\n{6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, _\n{7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, _\n{8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, _\n{9, 8, 7, 6, 5, 4, 3, 2, 1, 0} }\n\nDim Shared As Integer inv(9) = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nDim Shared As Integer p(7, 9) = { _\n{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, _\n{1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, _\n{5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, _\n{8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, _\n{9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, _\n{4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, _\n{2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, _\n{7, 0, 4, 6, 9, 1, 3, 2, 5, 8} }\n\nFunction Verhoeff(s As String, validate As Integer, table As Integer) As Integer\n Dim As Integer c, le, k, ni, pi\n If table Then\n Print\n Print Iif(validate, \"Validation\", \"Check digit\") & \" calculations for '\" & s & \"':\"\n Print !\"\\n i ni p[i,ni] c\\n------------------\"\n End If\n If Not validate Then s = s & \"0\"\n c = 0\n le = Len(s) - 1\n For k = le To 0 Step -1\n ni = Asc(Mid(s, k + 1, 1)) - 48\n pi = p((le - k) Mod 8, ni)\n c = d(c, pi)\n If table Then Print Using \"## # # #\"; le - k; ni; pi; c\n Next k\n If table And Not validate Then Print !\"\\ninv[\" & c & \"] = \" & inv(c)\n Return Iif(Not validate, inv(c), c = 0)\nEnd Function\n\nType miTipo\n s As String\n b As Boolean\nEnd Type\nDim sts(2) As miTipo\nsts(0).s = \"236\" : sts(0).b = True\nsts(1).s = \"12345\" : sts(1).b = True\nsts(2).s = \"123456789012\" : sts(2).b = False\n\nDim As Integer i, j, v , c\nFor i = 0 To 2\n c = Verhoeff(sts(i).s, False, sts(i).b)\n Print Using !\"\\nThe check digit for '&' is '&'\"; sts(i).s; c\n Dim stc(1) As String = {Left(sts(i).s, Len(sts(i).s)-1) & Str(c), Left(sts(i).s, Len(sts(i).s)-1) & \"9\"}\n For j = 0 To Ubound(stc)\n v = Verhoeff(stc(j), True, sts(i).b)\n Print Using !\"\\nThe validation for '&' is \"; stc(j);\n Print Iif (v, \"correct\", \"incorrect\"); \".\"\n Next j\n Print\nNext i\n\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nvar d = [][]int{\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},\n {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},\n {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},\n {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},\n {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},\n {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},\n {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},\n {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},\n {9, 8, 7, 6, 5, 4, 3, 2, 1, 0},\n}\n\nvar inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}\n\nvar p = [][]int{\n {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},\n {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},\n {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},\n {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},\n {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},\n {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},\n {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},\n {7, 0, 4, 6, 9, 1, 3, 2, 5, 8},\n}\n\nfunc verhoeff(s string, validate, table bool) interface{} {\n if table {\n t := \"Check digit\"\n if validate {\n t = \"Validation\"\n }\n fmt.Printf(\"%s calculations for '%s':\\n\\n\", t, s)\n fmt.Println(\" i nᵢ p[i,nᵢ] c\")\n fmt.Println(\"------------------\")\n }\n if !validate {\n s = s + \"0\"\n }\n c := 0\n le := len(s) - 1\n for i := le; i >= 0; i-- {\n ni := int(s[i] - 48)\n pi := p[(le-i)%8][ni]\n c = d[c][pi]\n if table {\n fmt.Printf(\"%2d %d %d %d\\n\", le-i, ni, pi, c)\n }\n }\n if table && !validate {\n fmt.Printf(\"\\ninv[%d] = %d\\n\", c, inv[c])\n }\n if !validate {\n return inv[c]\n }\n return c == 0\n}\n\nfunc main() {\n ss := []string{\"236\", \"12345\", \"123456789012\"}\n ts := []bool{true, true, false, true}\n for i, s := range ss {\n c := verhoeff(s, false, ts[i]).(int)\n fmt.Printf(\"\\nThe check digit for '%s' is '%d'\\n\\n\", s, c)\n for _, sc := range []string{s + string(c+48), s + \"9\"} {\n v := verhoeff(sc, true, ts[i]).(bool)\n ans := \"correct\"\n if !v {\n ans = \"incorrect\"\n }\n fmt.Printf(\"\\nThe validation for '%s' is %s\\n\\n\", sc, ans)\n }\n }\n}\n", "language": "Go" }, { "code": "cyc=: | +/~@i. NB. cyclic group, order y\nac=: |(+-/~@i.) NB. anticyclic group, order y\na2n=: (+#)@ NB. add 2^n\ndi=: (cyc,.cyc a2n),((ac a2n),.ac)\n\nD=: di 5\nINV=: ,I.0=D\nP=: {&(C.1 5 8 9 4 2 7 0;3 6)^:(i.8) i.10\n\nverhoeff=: {{\n c=. 0\n for_N. |.10 #.inv y do.\n c=. D{~<c,P{~<(8|N_index),N\n end.\n}}\n\ntraceverhoeff=: {{\n r=. EMPTY\n c=. 0\n for_N. |.10 #.inv y do.\n c0=. c\n c=. D{~<c,p=.P{~<(j=.8|N_index),N\n r=. r, c,p,j,N_index,N,c0\n end.\n labels=. cut 'cᵢ p[i,nᵢ] i nᵢ n cₒ'\n 1 1}.}:~.\":labels,(<;._1\"1~[:*/' '=])' ',.\":r\n}}\n\ncheckdigit=: INV {~ verhoeff@*&10\nvalid=: 0 = verhoeff\n", "language": "J" }, { "code": " checkdigit 236 12345 123456789012\n3 1 0\n valid 2363\n1\n valid 123451\n1\n valid 1234567890120\n1\n valid 2369\n0\n valid 123459\n0\n valid 1234567890129\n0\n traceverhoeff 2363\ncᵢ│p[i,nᵢ]│i│nᵢ│n│cₒ│\n──┼───────┼─┼──┼─┼──┤\n3 │3 │0│0 │3│0 │\n1 │3 │1│1 │6│3 │\n4 │3 │2│2 │3│1 │\n0 │1 │3│3 │2│4 │\n traceverhoeff 123451\ncᵢ│p[i,nᵢ]│i│nᵢ│n│cₒ│\n──┼───────┼─┼──┼─┼──┤\n1 │1 │0│0 │1│0 │\n9 │8 │1│1 │5│1 │\n2 │7 │2│2 │4│9 │\n8 │6 │3│3 │3│2 │\n3 │5 │4│4 │2│8 │\n0 │2 │5│5 │1│3 │\n", "language": "J" }, { "code": "import java.util.Arrays;\nimport java.util.List;\n\npublic class VerhoeffAlgorithm {\n\n\tpublic static void main(String[] args) {\n\t\tinitialise();\n\n\t\tList<List<Object>> tests = List.of(\n\t\t\tList.of( \"236\", true ), List.of( \"12345\", true ), List.of( \"123456789012\", false ) );\n\t\t\n\t\tfor ( List<Object> test : tests ) {\n\t\t Object object = verhoeffChecksum((String) test.get(0), false, (boolean) test.get(1));\t\t\n\t\t System.out.println(\"The check digit for \" + test.get(0) + \" is \" + object + \"\\n\");\n\t\t\n\t\t for ( String number : List.of( test.get(0) + String.valueOf(object), test.get(0) + \"9\" ) ) {\t\t \t\n\t\t object = verhoeffChecksum(number, true, (boolean) test.get(1));\n\t\t String result = (boolean) object ? \"correct\" : \"incorrect\";\n\t\t System.out.println(\"The validation for \" + number + \" is \" + result + \".\\n\");\n\t\t }\n\t\t}\n\t}\n\t\n\tprivate static Object verhoeffChecksum(String number, boolean doValidation, boolean doDisplay) {\n\t\tif ( doDisplay ) {\n\t\t\tString calculationType = doValidation ? \"Validation\" : \"Check digit\";\n\t System.out.println(calculationType + \" calculations for \" + number + \"\\n\");\n\t System.out.println(\" i ni p[i, ni] c\");\n\t System.out.println(\"-------------------\");\n\t }\n\t\t\n\t\tif ( ! doValidation ) {\n\t\t\tnumber += \"0\";\t\t\t\n\t\t}\n\t\t\n\t int c = 0;\n\t final int le = number.length() - 1;\n\t for ( int i = le; i >= 0; i-- ) {\n\t \tfinal int ni = number.charAt(i) - '0';\n\t final int pi = permutationTable.get((le - i) % 8).get(ni);\n\t c = multiplicationTable.get(c).get(pi);\n\t\n\t if ( doDisplay ) {\n\t \tSystem.out.println(String.format(\"%2d%3d%8d%6d\\n\", le - i, ni, pi, c));\n\t }\n\t }\n\t\t\n\t if ( doDisplay && ! doValidation ) {\n\t \tSystem.out.println(\"inverse[\" + c + \"] = \" + inverse.get(c) + \"\\n\");\n\t }\n\t\n\t return doValidation ? c == 0 : inverse.get(c);\n\t}\n\t\n\tprivate static void initialise() {\n\t\tmultiplicationTable = List.of(\n\t\t\tList.of( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),\n\t\t\tList.of( 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 ),\n\t\t\tList.of( 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 ),\n\t\t\tList.of( 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 ),\n\t\t\tList.of( 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 ),\n\t\t\tList.of( 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 ),\n\t\t\tList.of( 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 ),\n\t\t\tList.of( 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 ),\n\t\t\tList.of( 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 ),\n\t\t\tList.of( 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 )\n\t\t);\t\t\n\t\t\n\t\tinverse = Arrays.asList( 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 );\n\t\t\n\t\tpermutationTable = List.of(\n\t\t\t\tList.of( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),\n\t\t\t\tList.of( 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 ),\n\t\t\t\tList.of( 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 ),\n\t\t\t\tList.of( 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 ),\n\t\t\t\tList.of( 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 ),\n\t\t\t\tList.of( 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 ),\n\t\t\t\tList.of( 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 ),\n\t\t\t\tList.of( 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 )\n\t\t);\t\n\t}\n\t\n\tprivate static List<List<Integer>> multiplicationTable;\n\tprivate static List<Integer> inverse;\n\tprivate static List<List<Integer>> permutationTable;\n\t\n}\n", "language": "Java" }, { "code": "def lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\ndef d: [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n];\n\ndef inv: [0, 4, 3, 2, 1, 5, 6, 7, 8, 9];\n\ndef p: [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]\n];\n\n# Output: an object: {emit, c}\ndef verhoeff($s; $validate; $table):\n\n {emit:\n (if $table then\n [\"\\(if $validate then \"Validation\" else \"Check digit\" end) calculations for '\\($s)':\\n\",\n \" i nᵢ p[i,nᵢ] c\",\n \"------------------\"]\n else []\n end),\n s: (if $validate then $s else $s + \"0\" end),\n c: 0 }\n | ((.s|length) - 1) as $le\n | reduce range($le; -1; -1) as $i (.;\n (.s[$i:$i+1]|explode[] - 48) as $ni\n | (p[($le-$i) % 8][$ni]) as $pi\n | .c = d[.c][$pi]\n | if $table\n then .emit += [\"\\($le-$i|lpad(2)) \\($ni) \\($pi) \\(.c)\"]\n else .\n\t end )\n | if $table and ($validate|not)\n then .emit += [\"\\ninv[\\(.c)] = \\(inv[.c])\"]\n else .\n end\n | .c = (if $validate then (.c == 0) else inv[.c] end);\n\ndef sts: [\n [\"236\", true],\n [\"12345\", true],\n [\"123456789012\", false]];\n\ndef task:\n sts[]\n | . as $st\n | verhoeff($st[0]; false; $st[1]) as {c: $c, emit: $emit}\n | $emit[],\n \"\\nThe check digit for '\\($st[0])' is '\\($c)'\\n\",\n ( ($st[0] + ($c|tostring)), ($st[0] + \"9\")\n | . as $stc\n | verhoeff($stc; true; $st[1]) as {emit: $emit, c: $v}\n | (if $v then \"correct\" else \"incorrect\" end) as $v\n | $emit[],\n \"\\nThe validation for '\\($stc)' is \\($v).\\n\" );\n\ntask\n", "language": "Jq" }, { "code": "const multiplicationtable = [\n 0 1 2 3 4 5 6 7 8 9;\n 1 2 3 4 0 6 7 8 9 5;\n 2 3 4 0 1 7 8 9 5 6;\n 3 4 0 1 2 8 9 5 6 7;\n 4 0 1 2 3 9 5 6 7 8;\n 5 9 8 7 6 0 4 3 2 1;\n 6 5 9 8 7 1 0 4 3 2;\n 7 6 5 9 8 2 1 0 4 3;\n 8 7 6 5 9 3 2 1 0 4;\n 9 8 7 6 5 4 3 2 1 0]\n\nconst permutationtable = [\n 0 1 2 3 4 5 6 7 8 9;\n 1 5 7 6 2 8 3 0 9 4;\n 5 8 0 3 7 9 6 1 4 2;\n 8 9 1 6 0 4 3 5 2 7;\n 9 4 5 3 1 2 6 8 7 0;\n 4 2 8 6 5 7 3 9 0 1;\n 2 7 9 3 8 0 6 4 1 5;\n 7 0 4 6 9 1 3 2 5 8]\n\nconst inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\n\"\"\"\n verhoeffchecksum(n::Integer, validate=true, terse=true, verbose=false)\n\nCalculate the Verhoeff checksum over `n`.\nTerse mode or with single argument: return true if valid (last digit is a correct check digit).\nIf checksum mode, return the expected correct checksum digit.\nIf validation mode, return true if last digit checks correctly.\n\"\"\"\nfunction verhoeffchecksum(n::Integer, validate=true, terse=true, verbose=false)\n verbose && println(\"\\n\", validate ? \"Validation\" : \"Check digit\",\n \" calculations for '$n':\\n\\n\", \" i nᵢ p[i,nᵢ] c\\n------------------\")\n # transform number list\n c, dig = 0, reverse(digits(validate ? n : 10 * n))\n for i in length(dig):-1:1\n ni = dig[i]\n p = permutationtable[(length(dig) - i) % 8 + 1, ni + 1]\n c = multiplicationtable[c + 1, p + 1]\n verbose && println(lpad(length(dig) - i, 2), \" $ni $p $c\")\n end\n verbose && !validate && println(\"\\ninv($c) = $(inv[c + 1])\")\n !terse && println(validate ? \"\\nThe validation for '$n' is $(c == 0 ?\n \"correct\" : \"incorrect\").\" : \"\\nThe check digit for '$n' is $(inv[c + 1]).\")\n return validate ? c == 0 : inv[c + 1]\nend\n\nfor args in [(236, false, false, true), (2363, true, false, true), (2369, true, false, true),\n (12345, false, false, true), (123451, true, false, true), (123459, true, false, true),\n (123456789012, false, false), (1234567890120, true, false), (1234567890129, true, false)]\n verhoeffchecksum(args...)\nend\n", "language": "Julia" }, { "code": "import strformat\n\nconst\n\n D = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]\n\n Inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\n P = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]\n\ntype Digit = 0..9\n\nproc verhoeff[T: SomeInteger](n: T; validate, verbose = false): T =\n ## Compute or validate a check digit.\n ## Return the check digit if computation or the number with the check digit\n ## removed if validation.\n ## If not in verbose mode, an exception is raised if validation failed.\n\n doAssert n >= 0, \"Argument must not be negative.\"\n\n # Extract digits.\n var digits: seq[Digit]\n if not validate: digits.add 0\n var val = n\n while val != 0:\n digits.add val mod 10\n val = val div 10\n\n if verbose:\n echo if validate: &\"Check digit validation for {n}:\" else: &\"Check digit computation for {n}:\"\n echo \" i ni p(i, ni) c\"\n\n # Compute c.\n var c = 0\n for i, ni in digits:\n let p = P[i mod 8][ni]\n c = D[c][p]\n if verbose: echo &\"{i:2} {ni} {p} {c}\"\n\n if validate:\n if verbose:\n let verb = if c == 0: \"is\" else: \"is not\"\n echo &\"Validation {verb} successful.\\n\"\n elif c != 0:\n raise newException(ValueError, &\"Check digit validation failed for {n}.\")\n result = n div 10\n\n else:\n result = Inv[c]\n if verbose: echo &\"The check digit for {n} is {result}.\\n\"\n\n\nfor n in [236, 12345]:\n let d = verhoeff(n, false, true)\n discard verhoeff(10 * n + d, true, true)\n discard 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 discard verhoeff(10 * n + 9, true)\nexcept ValueError:\n echo getCurrentExceptionMsg()\n", "language": "Nim" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Verhoeff_algorithm\nuse warnings;\n\nmy @inv = qw(0 4 3 2 1 5 6 7 8 9);\n\nmy @d = map [ split ], split /\\n/, <<END;\n0 \t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8 \t9\n1 \t2 \t3 \t4 \t0 \t6 \t7 \t8 \t9 \t5\n2 \t3 \t4 \t0 \t1 \t7 \t8 \t9 \t5 \t6\n3 \t4 \t0 \t1 \t2 \t8 \t9 \t5 \t6 \t7\n4 \t0 \t1 \t2 \t3 \t9 \t5 \t6 \t7 \t8\n5 \t9 \t8 \t7 \t6 \t0 \t4 \t3 \t2 \t1\n6 \t5 \t9 \t8 \t7 \t1 \t0 \t4 \t3 \t2\n7 \t6 \t5 \t9 \t8 \t2 \t1 \t0 \t4 \t3\n8 \t7 \t6 \t5 \t9 \t3 \t2 \t1 \t0 \t4\n9 \t8 \t7 \t6 \t5 \t4 \t3 \t2 \t1 \t0\nEND\n\nmy @p = map [ split ], split /\\n/, <<END;\n0 \t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8 \t9\n1 \t5 \t7 \t6 \t2 \t8 \t3 \t0 \t9 \t4\n5 \t8 \t0 \t3 \t7 \t9 \t6 \t1 \t4 \t2\n8 \t9 \t1 \t6 \t0 \t4 \t3 \t5 \t2 \t7\n9 \t4 \t5 \t3 \t1 \t2 \t6 \t8 \t7 \t0\n4 \t2 \t8 \t6 \t5 \t7 \t3 \t9 \t0 \t1\n2 \t7 \t9 \t3 \t8 \t0 \t6 \t4 \t1 \t5\n7 \t0 \t4 \t6 \t9 \t1 \t3 \t2 \t5 \t8\nEND\n\nmy $debug;\n\nsub generate\n {\n local $_ = shift() . 0;\n my $c = my $i = 0;\n my ($n, $p);\n $debug and print \"i ni d(c,p(i%8,ni)) c\\n\";\n while( length )\n {\n $c = $d[ $c ][ $p = $p[ $i % 8 ][ $n = chop ] ];\n $debug and printf \"%d%3d%7d%10d\\n\", $i, $n, $p, $c;\n $i++;\n }\n return $inv[ $c ];\n }\n\nsub validate { shift =~ /(\\d+)(\\d)/ and $2 == generate($1) }\n\nfor ( 236, 12345, 123456789012 )\n {\n print \"testing $_\\n\";\n $debug = length() < 6;\n my $checkdigit = generate($_);\n print \"check digit for $_ is $checkdigit\\n\";\n $debug = 0;\n for my $cd ( $checkdigit, 9 )\n {\n print \"$_$cd is \", validate($_ . $cd) ? '' : 'not ', \"valid\\n\";\n }\n print \"\\n\";\n }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)},</span>\n <span style=\"color: #000000;\">inv</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">extract</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[$],{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">5</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">8</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">]))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #000000;\">inv</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">inv</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">7</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">extract</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[$],{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">}))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- alternatively, if you prefer:\n --constant d = {{0,1,2,3,4,5,6,7,8,9},\n -- {1,2,3,4,0,6,7,8,9,5},\n -- {2,3,4,0,1,7,8,9,5,6},\n -- {3,4,0,1,2,8,9,5,6,7},\n -- {4,0,1,2,3,9,5,6,7,8},\n -- {5,9,8,7,6,0,4,3,2,1},\n -- {6,5,9,8,7,1,0,4,3,2},\n -- {7,6,5,9,8,2,1,0,4,3},\n -- {8,7,6,5,9,3,2,1,0,4},\n -- {9,8,7,6,5,4,3,2,1,0}},\n -- inv = {0,4,3,2,1,5,6,7,8,9},\n -- p = {{0,1,2,3,4,5,6,7,8,9},\n -- {1,5,7,6,2,8,3,0,9,4},\n -- {5,8,0,3,7,9,6,1,4,2},\n -- {8,9,1,6,0,4,3,5,2,7},\n -- {9,4,5,3,1,2,6,8,7,0},\n -- {4,2,8,6,5,7,3,9,0,1},\n -- {2,7,9,3,8,0,6,4,1,5},\n -- {7,0,4,6,9,1,3,2,5,8}}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">verhoeff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">validate</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">show_workings</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">validate</span><span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Validation\"</span><span style=\"color: #0000FF;\">}:{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Check digit\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">show_workings</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s calculations for `%s`:\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" i ni p(i,ni) c\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"------------------\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ni</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">pi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">ni</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">pi</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">show_workings</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d %d %d %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ni</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pi</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">inv</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #008000;\">'0'</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">validate</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"in\"</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"correct\"</span>\n <span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"`\"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #008000;\">\"`\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The %s for `%s` is %s\\n\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">lower</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"236\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"12345\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"123456789012\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">show_workings</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">verhoeff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">show_workings</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">verhoeff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">show_workings</span><span style=\"color: #0000FF;\">)==</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">verhoeff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #008000;\">'9'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">show_workings</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #008000;\">'0'</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "MULTIPLICATION_TABLE = [\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),\n (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),\n (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),\n (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),\n (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),\n (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),\n (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),\n (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),\n (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),\n]\n\nINV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)\n\nPERMUTATION_TABLE = [\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),\n (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),\n (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),\n (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),\n (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),\n (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),\n (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),\n]\n\ndef verhoeffchecksum(n, validate=True, terse=True, verbose=False):\n \"\"\"\n Calculate the Verhoeff checksum over `n`.\n Terse mode or with single argument: return True if valid (last digit is a correct check digit).\n If checksum mode, return the expected correct checksum digit.\n If validation mode, return True if last digit checks correctly.\n \"\"\"\n if verbose:\n print(f\"\\n{'Validation' if validate else 'Check digit'}\",\\\n f\"calculations for {n}:\\n\\n i nᵢ p[i,nᵢ] c\\n------------------\")\n # transform number list\n c, dig = 0, list(str(n if validate else 10 * n))\n for i, ni in enumerate(dig[::-1]):\n p = PERMUTATION_TABLE[i % 8][int(ni)]\n c = MULTIPLICATION_TABLE[c][p]\n if verbose:\n print(f\"{i:2} {ni} {p} {c}\")\n\n if verbose and not validate:\n print(f\"\\ninv({c}) = {INV[c]}\")\n if not terse:\n print(f\"\\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}.\"\\\n if validate else f\"\\nThe check digit for '{n}' is {INV[c]}.\")\n return c == 0 if validate else INV[c]\n\nif __name__ == '__main__':\n\n for n, va, t, ve in [\n (236, False, False, True), (2363, True, False, True), (2369, True, False, True),\n (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),\n (123456789012, False, False, False), (1234567890120, True, False, False),\n (1234567890129, True, False, False)]:\n verhoeffchecksum(n, va, t, ve)\n", "language": "Python" }, { "code": "my @d = [^10] xx 5;\n@d[$_][^5].=rotate($_), @d[$_][5..*].=rotate($_) for 1..4;\npush @d: [@d[$_].reverse] for flat 1..4, 0;\n\nmy @i = 0,4,3,2,1,5,6,7,8,9;\n\nmy %h = flat (0,1,5,8,9,4,2,7,0).rotor(2 =>-1).map({.[0]=>.[1]}), 6=>3, 3=>6;\nmy @p = [^10],;\[email protected]: [@p[*-1].map: {%h{$_}}] for ^7;\n\nsub checksum (Int $int where * ≥ 0, :$verbose = True ) {\n my @digits = $int.comb;\n say \"\\nCheckdigit calculation for $int:\";\n say \" i ni p(i, ni) c\" if $verbose;\n my ($i, $p, $c) = 0 xx 3;\n say \" $i 0 $p $c\" if $verbose;\n for @digits.reverse {\n ++$i;\n $p = @p[$i % 8][$_];\n $c = @d[$c; $p];\n say \"{$i.fmt('%2d')} $_ $p $c\" if $verbose;\n }\n say \"Checkdigit: {@i[$c]}\";\n +($int ~ @i[$c]);\n}\n\nsub validate (Int $int where * ≥ 0, :$verbose = True) {\n my @digits = $int.comb;\n say \"\\nValidation calculation for $int:\";\n say \" i ni p(i, ni) c\" if $verbose;\n my ($i, $p, $c) = 0 xx 3;\n for @digits.reverse {\n $p = @p[$i % 8][$_];\n $c = @d[$c; $p];\n say \"{$i.fmt('%2d')} $_ $p $c\" if $verbose;\n ++$i;\n }\n say \"Checkdigit: {'in' if $c}correct\";\n}\n\n## TESTING\n\nfor 236, 12345, 123456789012 -> $int {\n my $check = checksum $int, :verbose( $int.chars < 8 );\n validate $check, :verbose( $int.chars < 8 );\n validate +($check.chop ~ 9), :verbose( $int.chars < 8 );\n}\n", "language": "Raku" }, { "code": "const d = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],\n]\n\nconst inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\nconst p = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],\n]\n\nfn verhoeff(ss string, validate bool, table bool) int {\n mut s:= ss\n if table {\n mut t := \"Check digit\"\n if validate {\n t = \"Validation\"\n }\n println(\"$t calculations for '$s':\\n\")\n println(\" i nᵢ p[i,nᵢ] c\")\n println(\"------------------\")\n }\n if !validate {\n s = s + \"0\"\n }\n mut c := 0\n le := s.len - 1\n for i := le; i >= 0; i-- {\n ni := int(s[i] - 48)\n pi := p[(le-i)%8][ni]\n c = d[c][pi]\n if table {\n println(\"${le-i:2} $ni $pi $c\")\n }\n }\n if table && !validate {\n println(\"\\ninv[$c] = ${inv[c]}\")\n }\n if !validate {\n return inv[c]\n }\n return int(c == 0)\n}\n\nfn main() {\n ss := [\"236\", \"12345\", \"123456789012\"]\n ts := [true, true, false, true]\n for i, s in ss {\n c := verhoeff(s, false, ts[i])\n println(\"\\nThe check digit for '$s' is '$c'\\n\")\n for sc in [s + c.str(), s + \"9\"] {\n v := verhoeff(sc, true, ts[i])\n mut ans := \"correct\"\n if v==0 {\n ans = \"incorrect\"\n }\n println(\"\\nThe validation for '$sc' is $ans\\n\")\n }\n }\n}\n", "language": "V-(Vlang)" }, { "code": "import \"./fmt\" for Fmt\n\nvar d = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n\nvar inv = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]\n\nvar p = [\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]\n]\n\nvar verhoeff = Fn.new { |s, validate, table|\n if (table) {\n System.print(\"%(validate ? \"Validation\" : \"Check digit\") calculations for '%(s)':\\n\")\n System.print(\" i nᵢ p[i,nᵢ] c\")\n System.print(\"------------------\")\n }\n if (!validate) s = s + \"0\"\n var c = 0\n var le = s.count - 1\n for (i in le..0) {\n var ni = s[i].bytes[0] - 48\n var pi = p[(le-i) % 8][ni]\n c = d[c][pi]\n if (table) Fmt.print(\"$2d $d $d $d\", le-i, ni, pi, c)\n }\n if (table && !validate) System.print(\"\\ninv[%(c)] = %(inv[c])\")\n return !validate ? inv[c] : c == 0\n}\n\nvar sts = [[\"236\", true], [\"12345\", true], [\"123456789012\", false]]\nfor (st in sts) {\n var c = verhoeff.call(st[0], false, st[1])\n System.print(\"\\nThe check digit for '%(st[0])' is '%(c)'\\n\")\n for (stc in [st[0] + c.toString, st[0] + \"9\"]) {\n var v = verhoeff.call(stc, true, st[1])\n System.print(\"\\nThe validation for '%(stc)' is %(v ? \"correct\" : \"incorrect\").\\n\")\n }\n}\n", "language": "Wren" } ]
Verhoeff-algorithm
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test\nnote: Probability and statistics\n", "language": "00-META" }, { "code": ";Task:\nWrite a function to determine whether a given set of frequency counts could plausibly have come from a uniform distribution by using the [[wp:Pearson's chi-square test|<math>\\chi^2</math> test]] with a significance level of 5%. \n\nThe function should return a boolean that is true if and only if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.\n\nNote: normally a two-tailed test would be used for this kind of problem.\n\n;Reference:\n:* &nbsp; an entry at the MathWorld website: &nbsp; [http://mathworld.wolfram.com/Chi-SquaredDistribution.html chi-squared distribution].\n; Related task:\n:* [[Statistics/Chi-squared_distribution]]\n<br><br>\n", "language": "00-TASK" }, { "code": "V a = 12\nV k1_factrl = 1.0\n[Float] c\nc.append(sqrt(2.0 * math:pi))\nL(k) 1 .< a\n c.append(exp(a - k) * (a - k) ^ (k - 0.5) / k1_factrl)\n k1_factrl *= -k\n\nF gamma_spounge(z)\n V accm = :c[0]\n L(k) 1 .< :a\n accm += :c[k] / (z + k)\n accm *= exp(-(z + :a)) * (z + :a) ^ (z + 0.5)\n R accm / z\n\nF GammaInc_Q(a, x)\n V a1 = a - 1\n V a2 = a - 2\n F f0(t)\n R t ^ @a1 * exp(-t)\n\n F df0(t)\n R (@a1 - t) * t ^ @a2 * exp(-t)\n\n V y = a1\n L f0(y) * (x - y) > 2.0e-8 & y < x\n y += 0.3\n I y > x\n y = x\n\n V h = 3.0e-4\n V n = Int(y / h)\n h = y / n\n V hh = 0.5 * h\n V gamax = h * sum(((n - 1 .< -1).step(-1).map(j -> @h * j)).map(t -> @f0(t) + @hh * @df0(t)))\n\n R gamax / gamma_spounge(a)\n\nF chi2UniformDistance(dataSet)\n V expected = sum(dataSet) * 1.0 / dataSet.len\n V cntrd = (dataSet.map(d -> d - @expected))\n R sum(cntrd.map(x -> x * x)) / expected\n\nF chi2Probability(dof, distance)\n R 1.0 - GammaInc_Q(0.5 * dof, 0.5 * distance)\n\nF chi2IsUniform(dataSet, significance)\n V dof = dataSet.len - 1\n V dist = chi2UniformDistance(dataSet)\n R chi2Probability(dof, dist) > significance\n\nV dset1 = [199809, 200665, 199607, 200270, 199649]\nV dset2 = [522573, 244456, 139979, 71531, 21461]\n\nL(ds) (dset1, dset2)\n print(‘Data set: ’ds)\n V dof = ds.len - 1\n V distance = chi2UniformDistance(ds)\n print(‘dof: #. distance: #.4’.format(dof, distance), end' ‘ ’)\n V prob = chi2Probability(dof, distance)\n print(‘probability: #.4’.format(prob), end' ‘ ’)\n print(‘uniform? ’(I chi2IsUniform(ds, 0.05) {‘Yes’} E ‘No’))\n", "language": "11l" }, { "code": "package Chi_Square is\n\n type Flt is digits 18;\n type Bins_Type is array(Positive range <>) of Natural;\n\n function Distance(Bins: Bins_Type) return Flt;\n\nend Chi_Square;\n", "language": "Ada" }, { "code": "package body Chi_Square is\n\n function Distance(Bins: Bins_Type) return Flt is\n Bad_Bins: Natural := 0;\n Sum: Natural := 0;\n Expected: Flt;\n Result: Flt;\n begin\n for I in Bins'Range loop\n if Bins(I) < 5 then\n Bad_Bins := Bad_Bins + 1;\n end if;\n Sum := Sum + Bins(I);\n end loop;\n if 5*Bad_Bins > Bins'Length then\n raise Program_Error with \"too many (almost) empty bins\";\n end if;\n\n Expected := Flt(Sum) / Flt(Bins'Length);\n Result := 0.0;\n for I in Bins'Range loop\n Result := Result + ((Flt(Bins(I)) - Expected)**2) / Expected;\n end loop;\n return Result;\n end Distance;\n\nend Chi_Square;\n", "language": "Ada" }, { "code": "with Ada.Text_IO, Ada.Command_Line, Chi_Square; use Ada.Text_IO;\n\nprocedure Test_Chi_Square is\n\n package Ch2 renames Chi_Square; use Ch2;\n package FIO is new Float_IO(Flt);\n\n B: Bins_Type(1 .. Ada.Command_Line.Argument_Count);\n Bound_For_5_Per_Cent: constant array(Positive range <>) of Flt :=\n ( 1 => 3.84, 2 => 5.99, 3 => 7.82, 4 => 9.49, 5 => 11.07,\n 6 => 12.59, 7 => 14.07, 8 => 15.51, 9 => 16.92, 10 => 18.31);\n -- picked from http://en.wikipedia.org/wiki/Chi-squared_distribution\n\n Dist: Flt;\n\nbegin\n for I in B'Range loop\n B(I) := Natural'Value(Ada.Command_Line.Argument(I));\n end loop;\n Dist := Distance(B);\n Put(\"Degrees of Freedom:\" & Integer'Image(B'Length-1) & \", Distance: \");\n FIO.Put(Dist, Fore => 6, Aft => 2, Exp => 0);\n if Dist <= Bound_For_5_Per_Cent(B'Length-1) then\n Put_Line(\"; (apparently uniform)\");\n else\n Put_Line(\"; (deviates significantly from uniform)\");\n end if;\nend;\n", "language": "Ada" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ntypedef double (* Ifctn)( double t);\n/* Numerical integration method */\ndouble Simpson3_8( Ifctn f, double a, double b, int N)\n{\n int j;\n double l1;\n double h = (b-a)/N;\n double h1 = h/3.0;\n double sum = f(a) + f(b);\n\n for (j=3*N-1; j>0; j--) {\n l1 = (j%3)? 3.0 : 2.0;\n sum += l1*f(a+h1*j) ;\n }\n return h*sum/8.0;\n}\n\n#define A 12\ndouble Gamma_Spouge( double z )\n{\n int k;\n static double cspace[A];\n static double *coefs = NULL;\n double accum;\n double a = A;\n\n if (!coefs) {\n double k1_factrl = 1.0;\n coefs = cspace;\n coefs[0] = sqrt(2.0*M_PI);\n for(k=1; k<A; k++) {\n coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;\n k1_factrl *= -k;\n }\n }\n\n accum = coefs[0];\n for (k=1; k<A; k++) {\n accum += coefs[k]/(z+k);\n }\n accum *= exp(-(z+a)) * pow(z+a, z+0.5);\n return accum/z;\n}\n\ndouble aa1;\ndouble f0( double t)\n{\n return pow(t, aa1)*exp(-t);\n}\n\ndouble GammaIncomplete_Q( double a, double x)\n{\n double y, h = 1.5e-2; /* approximate integration step size */\n\n /* this cuts off the tail of the integration to speed things up */\n y = aa1 = a-1;\n while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4;\n if (y>x) y=x;\n\n return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);\n}\n", "language": "C" }, { "code": "double chi2UniformDistance( double *ds, int dslen)\n{\n double expected = 0.0;\n double sum = 0.0;\n int k;\n\n for (k=0; k<dslen; k++)\n expected += ds[k];\n expected /= k;\n\n for (k=0; k<dslen; k++) {\n double x = ds[k] - expected;\n sum += x*x;\n }\n return sum/expected;\n}\n\ndouble chi2Probability( int dof, double distance)\n{\n return GammaIncomplete_Q( 0.5*dof, 0.5*distance);\n}\n\nint chiIsUniform( double *dset, int dslen, double significance)\n{\n int dof = dslen -1;\n double dist = chi2UniformDistance( dset, dslen);\n return chi2Probability( dof, dist ) > significance;\n}\n", "language": "C" }, { "code": "int main(int argc, char **argv)\n{\n double dset1[] = { 199809., 200665., 199607., 200270., 199649. };\n double dset2[] = { 522573., 244456., 139979., 71531., 21461. };\n double *dsets[] = { dset1, dset2 };\n int dslens[] = { 5, 5 };\n int k, l;\n double dist, prob;\n int dof;\n\n for (k=0; k<2; k++) {\n printf(\"Dataset: [ \");\n for(l=0;l<dslens[k]; l++)\n printf(\"%.0f, \", dsets[k][l]);\n\n printf(\"]\\n\");\n dist = chi2UniformDistance(dsets[k], dslens[k]);\n dof = dslens[k]-1;\n printf(\"dof: %d distance: %.4f\", dof, dist);\n prob = chi2Probability( dof, dist );\n printf(\" probability: %.6f\", prob);\n printf(\" uniform? %s\\n\", chiIsUniform(dsets[k], dslens[k], 0.05)? \"Yes\":\"No\");\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <iomanip>\n\nvoid print_vector(const std::vector<int32_t>& list) {\n\tstd::cout << \"[\";\n\tfor ( uint64_t i = 0; i < list.size() - 1; ++i ) {\n\t\tstd::cout << list[i] << \", \";\n\t}\n\tstd::cout << list.back() << \"]\" << std::endl;\n}\n\nbool is_significant(const double p_value, const double significance_level) {\n\treturn p_value > significance_level;\n}\n\n// The normalised lower incomplete gamma function.\ndouble gamma_cdf(const double aX, const double aK) {\n\tdouble result = 0.0;\n\tfor ( uint32_t m = 0; m <= 99; ++m ) {\n\t\tresult += pow(aX, m) / tgamma(aK + m + 1);\n\t}\n\tresult *= pow(aX, aK) * exp(-aX);\n\treturn std::isnan(result) ? 1.0 : result;\n}\n\n// The cumulative probability function of the Chi-squared distribution.\ndouble cdf(const double aX, const double aK) {\n\tif ( aX > 1'000 && aK < 100 ) {\n\t\treturn 1.0;\n\t}\n\treturn ( aX > 0.0 && aK > 0.0 ) ? gamma_cdf(aX / 2, aK / 2) : 0.0;\n}\n\nvoid chi_squared_test(const std::vector<int32_t>& observed) {\n\tdouble sum = 0.0;\n\tfor ( uint64_t i = 0; i < observed.size(); ++i ) {\n\t\tsum += observed[i];\n\t}\n\tconst double expected = sum / observed.size();\n\n\tconst int32_t degree_freedom = observed.size() - 1;\n\n\tdouble test_statistic = 0.0;\n\tfor ( uint64_t i = 0; i < observed.size(); ++i ) {\n\t\ttest_statistic += pow(observed[i] - expected, 2) / expected;\n\t}\n\n\tconst double p_value = 1.0 - cdf(test_statistic, degree_freedom);\n\n\tstd::cout << \"\\nUniform distribution test\" << std::setprecision(6) << std::endl;\n\tstd::cout << \" observed values : \"; print_vector(observed);\n\tstd::cout << \" expected value : \" << expected << std::endl;\n\tstd::cout << \" degrees of freedom: \" << degree_freedom << std::endl;\n\tstd::cout << \" test statistic : \" << test_statistic << std::endl;\n\tstd::cout.setf(std::ios::fixed);\n\tstd::cout << \" p-value : \" << p_value << std::endl;\n\tstd::cout.unsetf(std::ios::fixed);\n\tstd::cout << \" is 5% significant?: \" << std::boolalpha << is_significant(p_value, 0.05) << std::endl;\n}\n\nint main() {\n\tconst std::vector<std::vector<int32_t>> datasets = { { 199809, 200665, 199607, 200270, 199649 },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t { 522573, 244456, 139979, 71531, 21461 } };\n\tfor ( std::vector<int32_t> dataset : datasets ) {\n\t\tchi_squared_test(dataset);\n\t}\n}\n", "language": "C++" }, { "code": "using System;\n\nclass Program\n{\n\tpublic delegate double Func(double x);\n\tpublic static double Simpson38(Func f, double a, double b, int n)\n\t{\n\t\tdouble h = (b - a) / n;\n\t\tdouble h1 = h / 3;\n\t\tdouble sum = f(a) + f(b);\n\t\tfor (int j = 3 * n - 1; j > 0; j--)\n\t\t{\n\t\t\tif (j % 3 == 0)\n\t\t\t{\n\t\t\t\tsum += 2 * f(a + h1 * j);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsum += 3 * f(a + h1 * j);\n\t\t\t}\n\t\t}\n\n\t\treturn h * sum / 8;\n\t}\n\n\t// Lanczos Approximation for Gamma Function\n\tprivate static double SpecialFunctionGamma(double z)\n\t{\n\t\tdouble[] p =\n\t\t{\n\t\t\t676.5203681218851,\n\t\t\t-1259.1392167224028,\n\t\t\t771.32342877765313,\n\t\t\t-176.61502916214059,\n\t\t\t12.507343278686905,\n\t\t\t-0.13857109526572012,\n\t\t\t9.9843695780195716e-6,\n\t\t\t1.5056327351493116e-7\n\t\t};\n\t\tif (z < 0.5)\n\t\t\treturn Math.PI / (Math.Sin(Math.PI * z) * SpecialFunctionGamma(1 - z));\n\t\tz -= 1;\n\t\tdouble x = 0.99999999999980993;\n\t\tfor (int i = 0; i < p.Length; i++)\n\t\t{\n\t\t\tx += p[i] / (z + i + 1);\n\t\t}\n\n\t\tdouble t = z + p.Length - 0.5;\n\t\treturn Math.Sqrt(2 * Math.PI) * Math.Pow(t, z + 0.5) * Math.Exp(-t) * x;\n\t}\n\n\tpublic static double GammaIncQ(double a, double x)\n\t{\n\t\tdouble aa1 = a - 1;\n\t\tFunc f = t => Math.Pow(t, aa1) * Math.Exp(-t);\n\t\tdouble y = aa1;\n\t\tdouble h = 1.5e-2;\n\t\twhile (f(y) * (x - y) > 2e-8 && y < x)\n\t\t{\n\t\t\ty += .4;\n\t\t}\n\n\t\tif (y > x)\n\t\t{\n\t\t\ty = x;\n\t\t}\n\n\t\treturn 1 - Simpson38(f, 0, y, (int)(y / h / SpecialFunctionGamma(a)));\n\t}\n\n\tpublic static double Chi2Ud(int[] ds)\n\t{\n\t\tdouble sum = 0, expected = 0;\n\t\tforeach (var d in ds)\n\t\t{\n\t\t\texpected += d;\n\t\t}\n\n\t\texpected /= ds.Length;\n\t\tforeach (var d in ds)\n\t\t{\n\t\t\tdouble x = d - expected;\n\t\t\tsum += x * x;\n\t\t}\n\n\t\treturn sum / expected;\n\t}\n\n\tpublic static double Chi2P(int dof, double distance)\n\t{\n\t\treturn GammaIncQ(.5 * dof, .5 * distance);\n\t}\n\n\tconst double SigLevel = .05;\n\tstatic void Main(string[] args)\n\t{\n\t\tint[][] datasets = new int[][]\n\t\t{\n\t\t\tnew int[]\n\t\t\t{\n\t\t\t\t199809,\n\t\t\t\t200665,\n\t\t\t\t199607,\n\t\t\t\t200270,\n\t\t\t\t199649\n\t\t\t},\n\t\t\tnew int[]\n\t\t\t{\n\t\t\t\t522573,\n\t\t\t\t244456,\n\t\t\t\t139979,\n\t\t\t\t71531,\n\t\t\t\t21461\n\t\t\t},\n\t\t};\n\t\tforeach (var dset in datasets)\n\t\t{\n\t\t\tUTest(dset);\n\t\t}\n\t}\n\n\tstatic void UTest(int[] dset)\n\t{\n\t\tConsole.WriteLine(\"Uniform distribution test\");\n\t\tint sum = 0;\n\t\tforeach (var c in dset)\n\t\t{\n\t\t\tsum += c;\n\t\t}\n\n\t\tConsole.WriteLine($\" dataset: {string.Join(\", \", dset)}\");\n\t\tConsole.WriteLine($\" samples: {sum}\");\n\t\tConsole.WriteLine($\" categories: {dset.Length}\");\n\t\tint dof = dset.Length - 1;\n\t\tConsole.WriteLine($\" degrees of freedom: {dof}\");\n\t\tdouble dist = Chi2Ud(dset);\n\t\tConsole.WriteLine($\" chi square test statistic: {dist}\");\n\t\tdouble p = Chi2P(dof, dist);\n\t\tConsole.WriteLine($\" p-value of test statistic: {p}\");\n\t\tbool sig = p < SigLevel;\n\t\tConsole.WriteLine($\" significant at {SigLevel * 100}% level? {sig}\");\n\t\tConsole.WriteLine($\" uniform? {!sig}\\n\");\n\t}\n}\n", "language": "C-sharp" }, { "code": "import std.stdio, std.algorithm, std.mathspecial;\n\nreal x2Dist(T)(in T[] data) pure nothrow @safe @nogc {\n immutable avg = data.sum / data.length;\n immutable sqs = reduce!((a, b) => a + (b - avg) ^^ 2)(0.0L, data);\n return sqs / avg;\n}\n\nreal x2Prob(in real dof, in real distance) pure nothrow @safe @nogc {\n return gammaIncompleteCompl(dof / 2, distance / 2);\n}\n\nbool x2IsUniform(T)(in T[] data, in real significance=0.05L)\npure nothrow @safe @nogc {\n return x2Prob(data.length - 1.0L, x2Dist(data)) > significance;\n}\n\nvoid main() {\n immutable dataSets = [[199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461]];\n writefln(\" %4s %12s %12s %8s %s\",\n \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n foreach (immutable ds; dataSets) {\n immutable dof = ds.length - 1;\n immutable dist = ds.x2Dist;\n immutable prob = x2Prob(dof, dist);\n writefln(\"%4d %12.3f %12.8f %5s %6s\",\n dof, dist, prob, ds.x2IsUniform ? \"YES\" : \"NO\", ds);\n }\n}\n", "language": "D" }, { "code": "defmodule Verify do\n defp gammaInc_Q(a, x) do\n a1 = a-1\n f0 = fn t -> :math.pow(t, a1) * :math.exp(-t) end\n df0 = fn t -> (a1-t) * :math.pow(t, a-2) * :math.exp(-t) end\n y = while_loop(f0, x, a1)\n n = trunc(y / 3.0e-4)\n h = y / n\n hh = 0.5 * h\n sum = Enum.reduce(n-1 .. 0, 0, fn j,sum ->\n t = h * j\n sum + f0.(t) + hh * df0.(t)\n end)\n h * sum / gamma_spounge(a, make_coef)\n end\n\n defp while_loop(f, x, y) do\n if f.(y)*(x-y) > 2.0e-8 and y < x, do: while_loop(f, x, y+0.3), else: min(x, y)\n end\n\n @a 12\n defp make_coef do\n coef0 = [:math.sqrt(2.0 * :math.pi)]\n {_, coef} = Enum.reduce(1..@a-1, {1.0, coef0}, fn k,{k1_factrl,c} ->\n h = :math.exp(@a-k) * :math.pow(@a-k, k-0.5) / k1_factrl\n {-k1_factrl*k, [h | c]}\n end)\n Enum.reverse(coef) |> List.to_tuple\n end\n\n defp gamma_spounge(z, coef) do\n accm = Enum.reduce(1..@a-1, elem(coef,0), fn k,res -> res + elem(coef,k) / (z+k) end)\n accm * :math.exp(-(z+@a)) * :math.pow(z+@a, z+0.5) / z\n end\n\n def chi2UniformDistance(dataSet) do\n expected = Enum.sum(dataSet) / length(dataSet)\n Enum.reduce(dataSet, 0, fn d,sum -> sum + (d-expected)*(d-expected) end) / expected\n end\n\n def chi2Probability(dof, distance) do\n 1.0 - gammaInc_Q(0.5*dof, 0.5*distance)\n end\n\n def chi2IsUniform(dataSet, significance\\\\0.05) do\n dof = length(dataSet) - 1\n dist = chi2UniformDistance(dataSet)\n chi2Probability(dof, dist) > significance\n end\nend\n\ndsets = [ [ 199809, 200665, 199607, 200270, 199649 ],\n [ 522573, 244456, 139979, 71531, 21461 ] ]\n\nEnum.each(dsets, fn ds ->\n IO.puts \"Data set:#{inspect ds}\"\n dof = length(ds) - 1\n IO.puts \" degrees of freedom: #{dof}\"\n distance = Verify.chi2UniformDistance(ds)\n :io.fwrite \" distance: ~.4f~n\", [distance]\n :io.fwrite \" probability: ~.4f~n\", [Verify.chi2Probability(dof, distance)]\n :io.fwrite \" uniform? ~s~n\", [(if Verify.chi2IsUniform(ds), do: \"Yes\", else: \"No\")]\nend)\n", "language": "Elixir" }, { "code": "module gsl_mini_bind_m\n\n use iso_c_binding\n implicit none\n private\n\n public :: p_value\n\n interface\n function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q')\n import\n real(c_double), value :: x\n real(c_double), value :: nu\n real(c_double) :: gsl_cdf_chisq_q\n end function gsl_cdf_chisq_q\n end interface\n\ncontains\n\n !> Get p-value from chi-square distribution\n real function p_value(x, df)\n real, intent(in) :: x\n integer, intent(in) :: df\n\n p_value = real(gsl_cdf_chisq_q(real(x, c_double), real(df, c_double)))\n\n end function p_value\n\nend module gsl_mini_bind_m\n", "language": "Fortran" }, { "code": "program chi2test\n\n use gsl_mini_bind_m, only: p_value\n implicit none\n\n real :: dset1(5) = [199809., 200665., 199607., 200270., 199649.]\n real :: dset2(5) = [522573., 244456., 139979., 71531., 21461.]\n\n real :: dist, prob\n integer :: dof\n\n write (*, '(A)', advance='no') \"Dataset 1:\"\n write (*, '(5(F12.4,:,1x))') dset1\n\n dist = chisq(dset1)\n dof = size(dset1) - 1\n write (*, '(A,I4,A,F12.4)') 'dof: ', dof, ' chisq: ', dist\n prob = p_value(dist, dof)\n write (*, '(A,F12.4)') 'probability: ', prob\n write (*, '(A,L)') 'uniform? ', prob > 0.05\n\n ! Lazy copy/past :|\n write (*, '(/A)', advance='no') \"Dataset 2:\"\n write (*, '(5(F12.4,:,1x))') dset2\n\n dist = chisq(dset2)\n dof = size(dset2) - 1\n write (*, '(A,I4,A,F12.4)') 'dof: ', dof, ' chisq: ', dist\n prob = p_value(dist, dof)\n write (*, '(A,F12.4)') 'probability: ', prob\n write (*, '(A,L)') 'uniform? ', prob > 0.05\n\ncontains\n\n !> Get chi-square value for a set of data `ds`\n real function chisq(ds)\n real, intent(in) :: ds(:)\n\n real :: expected, summa\n\n expected = sum(ds)/size(ds)\n summa = sum((ds - expected)**2)\n chisq = summa/expected\n\n end function chisq\n\nend program chi2test\n", "language": "Fortran" }, { "code": "Dataset 1: 199809.0000 200665.0000 199607.0000 200270.0000 199649.0000\ndof: 4 chisq: 4.1463\nprobability: 0.3866\nuniform? T\n\nDataset 2: 522573.0000 244456.0000 139979.0000 71531.0000 21461.0000\ndof: 4 chisq: 790063.2500\nprobability: 0.0000\nuniform? F\n", "language": "Fortran" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype ifctn func(float64) float64\n\nfunc simpson38(f ifctn, a, b float64, n int) float64 {\n h := (b - a) / float64(n)\n h1 := h / 3\n sum := f(a) + f(b)\n for j := 3*n - 1; j > 0; j-- {\n if j%3 == 0 {\n sum += 2 * f(a+h1*float64(j))\n } else {\n sum += 3 * f(a+h1*float64(j))\n }\n }\n return h * sum / 8\n}\n\nfunc gammaIncQ(a, x float64) float64 {\n aa1 := a - 1\n var f ifctn = func(t float64) float64 {\n return math.Pow(t, aa1) * math.Exp(-t)\n }\n y := aa1\n h := 1.5e-2\n for f(y)*(x-y) > 2e-8 && y < x {\n y += .4\n }\n if y > x {\n y = x\n }\n return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))\n}\n\nfunc chi2ud(ds []int) float64 {\n var sum, expected float64\n for _, d := range ds {\n expected += float64(d)\n }\n expected /= float64(len(ds))\n for _, d := range ds {\n x := float64(d) - expected\n sum += x * x\n }\n return sum / expected\n}\n\nfunc chi2p(dof int, distance float64) float64 {\n return gammaIncQ(.5*float64(dof), .5*distance)\n}\n\nconst sigLevel = .05\n\nfunc main() {\n for _, dset := range [][]int{\n {199809, 200665, 199607, 200270, 199649},\n {522573, 244456, 139979, 71531, 21461},\n } {\n utest(dset)\n }\n}\n\nfunc utest(dset []int) {\n fmt.Println(\"Uniform distribution test\")\n var sum int\n for _, c := range dset {\n sum += c\n }\n fmt.Println(\" dataset:\", dset)\n fmt.Println(\" samples: \", sum)\n fmt.Println(\" categories: \", len(dset))\n\n dof := len(dset) - 1\n fmt.Println(\" degrees of freedom: \", dof)\n\n dist := chi2ud(dset)\n fmt.Println(\" chi square test statistic: \", dist)\n\n p := chi2p(dof, dist)\n fmt.Println(\" p-value of test statistic: \", p)\n\n sig := p < sigLevel\n fmt.Printf(\" significant at %2.0f%% level? %t\\n\", sigLevel*100, sig)\n fmt.Println(\" uniform? \", !sig, \"\\n\")\n}\n", "language": "Go" }, { "code": "(import\n [scipy.stats [chisquare]]\n [collections [Counter]])\n\n(defn uniform? [f repeats &optional [alpha .05]]\n \"Call 'f' 'repeats' times and do a chi-squared test for uniformity\n of the resulting discrete distribution. Return false iff the\n null hypothesis of uniformity is rejected for the test with\n size 'alpha'.\"\n (<= alpha (second (chisquare\n (.values (Counter (take repeats (repeatedly f))))))))\n", "language": "Hy" }, { "code": "(import [random [randint]])\n\n(for [f [\n (fn [] (randint 1 10))\n (fn [] (if (randint 0 1) (randint 1 9) (randint 1 10)))]]\n (print (uniform? f 5000)))\n", "language": "Hy" }, { "code": "require 'stats/base'\n\ncountCats=: #@~. NB. counts the number of unique items\ngetExpected=: #@] % [ NB. divides no of items by category count\ngetObserved=: #/.~@] NB. counts frequency for each category\ncalcX2=: [: +/ *:@(getObserved - getExpected) % getExpected NB. calculates test statistic\ncalcDf=: <:@[ NB. calculates degrees of freedom for uniform distribution\n\nNB.*isUniform v Tests (5%) whether y is uniformly distributed\nNB. result is: boolean describing if distribution y is uniform\nNB. y is: distribution to test\nNB. x is: optionally specify number of categories possible\nisUniform=: (countCats $: ]) : (0.95 > calcDf chisqcdf :: 1: calcX2)\n", "language": "J" }, { "code": "require 'stats/base'\n\nNB.*isUniformX v Tests (5%) whether y is uniformly distributed\nNB. result is: boolean describing if distribution y is uniform\nNB. y is: distribution to test\nNB. x is: optionally specify number of categories possible\nisUniformX=: verb define\n (#~. y) isUniformX y\n:\n signif=. 0.95 NB. set significance level\n expected=. (#y) % x NB. number of items divided by the category count\n observed=. #/.~ y NB. frequency count for each category\n X2=. +/ (*: observed - expected) % expected NB. the test statistic\n degfreedom=. <: x NB. degrees of freedom\n signif > degfreedom chisqcdf :: 1: X2\n)\n", "language": "J" }, { "code": " FairDistrib=: 1e6 ?@$ 5\n UnfairDistrib=: (9.5e5 ?@$ 5) , (5e4 ?@$ 4)\n isUniformX FairDistrib\n1\n isUniformX UnfairDistrib\n0\n isUniform 4 4 4 5 5 5 5 5 5 5 NB. uniform if only 2 categories possible\n1\n 4 isUniform 4 4 4 5 5 5 5 5 5 5 NB. not uniform if 4 categories possible\n0\n", "language": "J" }, { "code": "import static java.lang.Math.pow;\nimport java.util.Arrays;\nimport static java.util.Arrays.stream;\nimport org.apache.commons.math3.special.Gamma;\n\npublic class Test {\n\n static double x2Dist(double[] data) {\n double avg = stream(data).sum() / data.length;\n double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));\n return sqs / avg;\n }\n\n static double x2Prob(double dof, double distance) {\n return Gamma.regularizedGammaQ(dof / 2, distance / 2);\n }\n\n static boolean x2IsUniform(double[] data, double significance) {\n return x2Prob(data.length - 1.0, x2Dist(data)) > significance;\n }\n\n public static void main(String[] a) {\n double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},\n {522573, 244456, 139979, 71531, 21461}};\n\n System.out.printf(\" %4s %12s %12s %8s %s%n\",\n \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\");\n\n for (double[] ds : dataSets) {\n int dof = ds.length - 1;\n double dist = x2Dist(ds);\n double prob = x2Prob(dof, dist);\n System.out.printf(\"%4d %12.3f %12.8f %5s %6s%n\",\n dof, dist, prob, x2IsUniform(ds, 0.05) ? \"YES\" : \"NO\",\n Arrays.toString(ds));\n }\n }\n}\n", "language": "Java" }, { "code": "def round($dec):\n if type == \"string\" then .\n else pow(10;$dec) as $m\n | . * $m | floor / $m\n end;\n\n# sum of squares\ndef ss(s): reduce s as $x (0; . + ($x * $x));\n\n# Cumulative density function of the chi-squared distribution with $k\n# degrees of freedom\n# The recursion formula for gamma is used for efficiency and robustness.\ndef Chi2_cdf($x; $k):\n if $x == 0 then 0\n elif $x > (1e3 * $k) then 1\n else 1e-15 as $tol # for example\n | { s: 0, m: 0, term: (1 / ((($k/2)+1)|gamma)) }\n | until (.term|length < $tol; # length here is abs\n .s += .term\n | .m += 1\n | .term *= (($x/2) / (($k/2) + .m )) )\n | .s * ( ((-$x/2) + ($k/2)*(($x/2)|log)) | exp)\n end ;\n", "language": "Jq" }, { "code": "# Input: array of frequencies\ndef chi2UniformDistance:\n (add / length) as $expected\n | ss(.[] - $expected) / $expected;\n\n# Input: a number\n# Output: an indication of the probability of observing this value or higher\n# assuming the value is drawn from a chi-squared distribution with $dof degrees\n# of freedom\ndef chi2Probability($dof):\n (1 - Chi2_cdf(.; $dof))\n | if . < 1e-10 then \"< 1e-10\"\n else .\n end;\n\n# Input: array of frequencies\n# Output: result of a two-tailed test based on the chi-squared statistic\n# assuming the sample size is large enough\ndef chiIsUniform($significance):\n (length - 1) as $dof\n | chi2UniformDistance\n | Chi2_cdf(.; $dof) as $cdf\n | if $cdf\n then ($significance/2) as $s\n | $cdf > $s and $cdf < (1-$s)\n else false\n end;\n\ndef dsets: [\n [199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461],\n [19,14,6,18,7,5,1], # low entropy\n [9,11,9,10,15,11,5], # high entropy\n [20,20,20] # made-up\n];\n\ndef task:\n dsets[]\n | \"Dataset: \\(.)\",\n ( chi2UniformDistance as $dist\n | (length - 1) as $dof\n | \"DOF: \\($dof) D (Distance): \\($dist)\",\n \" Estimated probability of observing a value >= D: \\($dist|chi2Probability($dof)|round(2))\",\n \" Uniform? \\( (select(chiIsUniform(0.05)) | \"Yes\") // \"No\" )\\n\" ) ;\n\ntask\n", "language": "Jq" }, { "code": "# v0.6\n\nusing Distributions\n\nfunction eqdist(data::Vector{T}, α::Float64=0.05)::Bool where T <: Real\n if ! (0 ≤ α ≤ 1); error(\"α must be in [0, 1]\") end\n exp = mean(data)\n chisqval = sum((x - exp) ^ 2 for x in data) / exp\n pval = ccdf(Chisq(2), chisqval)\n return pval > α\nend\n\ndata1 = [199809, 200665, 199607, 200270, 199649]\ndata2 = [522573, 244456, 139979, 71531, 21461]\n\nfor data in (data1, data2)\n println(\"Data:\\n$data\")\n println(\"Hypothesis test: the original population is \", (eqdist(data) ? \"\" : \"not \"), \"uniform.\\n\")\nend\n", "language": "Julia" }, { "code": "// version 1.1.51\n\ntypealias Func = (Double) -> Double\n\nfun gammaLanczos(x: Double): Double {\n var xx = x\n val p = doubleArrayOf(\n 0.99999999999980993,\n 676.5203681218851,\n -1259.1392167224028,\n 771.32342877765313,\n -176.61502916214059,\n 12.507343278686905,\n -0.13857109526572012,\n 9.9843695780195716e-6,\n 1.5056327351493116e-7\n )\n val g = 7\n if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx))\n xx--\n var a = p[0]\n val t = xx + g + 0.5\n for (i in 1 until p.size) a += p[i] / (xx + i)\n return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a\n}\n\nfun integrate(a: Double, b: Double, n: Int, f: Func): Double {\n val h = (b - a) / n\n var sum = 0.0\n for (i in 0 until n) {\n val x = a + i * h\n sum += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0\n }\n return sum * h\n}\n\nfun gammaIncompleteQ(a: Double, x: Double): Double {\n val aa1 = a - 1.0\n fun f0(t: Double) = Math.pow(t, aa1) * Math.exp(-t)\n val h = 1.5e-2\n var y = aa1\n while ((f0(y) * (x - y) > 2.0e-8) && y < x) y += 0.4\n if (y > x) y = x\n return 1.0 - integrate(0.0, y, (y / h).toInt(), ::f0) / gammaLanczos(a)\n}\n\nfun chi2UniformDistance(ds: DoubleArray): Double {\n val expected = ds.average()\n val sum = ds.map { val x = it - expected; x * x }.sum()\n return sum / expected\n}\n\nfun chi2Probability(dof: Int, distance: Double) =\n gammaIncompleteQ(0.5 * dof, 0.5 * distance)\n\nfun chiIsUniform(ds: DoubleArray, significance: Double):Boolean {\n val dof = ds.size - 1\n val dist = chi2UniformDistance(ds)\n return chi2Probability(dof, dist) > significance\n}\n\nfun main(args: Array<String>) {\n val dsets = listOf(\n doubleArrayOf(199809.0, 200665.0, 199607.0, 200270.0, 199649.0),\n doubleArrayOf(522573.0, 244456.0, 139979.0, 71531.0, 21461.0)\n )\n for (ds in dsets) {\n println(\"Dataset: ${ds.asList()}\")\n val dist = chi2UniformDistance(ds)\n val dof = ds.size - 1\n print(\"DOF: $dof Distance: ${\"%.4f\".format(dist)}\")\n val prob = chi2Probability(dof, dist)\n print(\" Probability: ${\"%.6f\".format(prob)}\")\n val uniform = if (chiIsUniform(ds, 0.05)) \"Yes\" else \"No\"\n println(\" Uniform? $uniform\\n\")\n }\n}\n", "language": "Kotlin" }, { "code": "discreteUniformDistributionQ[data_, {min_Integer, max_Integer}, confLevel_: .05] :=\nIf[$VersionNumber >= 8,\n confLevel <= PearsonChiSquareTest[data, DiscreteUniformDistribution[{min, max}]],\n Block[{v, k = max - min, n = Length@data},\n v = (k + 1) (Plus @@ (((Length /@ Split[Sort@data]))^2))/n - n;\n GammaRegularized[k/2, 0, v/2] <= 1 - confLevel]]\n\ndiscreteUniformDistributionQ[data_] :=discreteUniformDistributionQ[data, data[[Ordering[data][[{1, -1}]]]]]\n", "language": "Mathematica" }, { "code": "uniformData = RandomInteger[10, 100];\nnonUniformData = Total@RandomInteger[10, {5, 100}];\n", "language": "Mathematica" }, { "code": "{discreteUniformDistributionQ[uniformData],discreteUniformDistributionQ[nonUniformData]}\n", "language": "Mathematica" }, { "code": "import lenientops, math, stats, strformat, sugar\n\nfunc simpson38(f: (float) -> float; a, b: float; n: int): float =\n let h = (b - a) / n\n let h1 = h / 3\n var sum = f(a) + f(b)\n for i in countdown(3 * n - 1, 1):\n if i mod 3 == 0:\n sum += 2 * f(a + h1 * i)\n else:\n sum += 3 * f(a + h1 * i)\n result = h * sum / 8\n\nfunc gammaIncQ(a, x: float): float =\n let aa1 = a - 1\n func f(t: float): float = pow(t, aa1) * exp(-t)\n var y = aa1\n let h = 1.5e-2\n while f(y) * (x - y) > 2e-8 and y < x:\n y += 0.4\n if y > x: y = x\n result = 1 - simpson38(f, 0, y, (y / h / gamma(a)).toInt)\n\nfunc chi2ud(ds: openArray[int]): float =\n let expected = mean(ds)\n var s = 0.0\n for d in ds:\n let x = d.toFloat - expected\n s += x * x\n result = s / expected\n\nfunc chi2p(dof: int; distance: float): float =\n gammaIncQ(0.5 * dof, 0.5 * distance)\n\nconst SigLevel = 0.05\n\nproc utest(dset: openArray[int]) =\n\n echo \"Uniform distribution test\"\n let s = sum(dset)\n echo \" dataset:\", dset\n echo \" samples: \", s\n echo \" categories: \", dset.len\n\n let dof = dset.len - 1\n echo \" degrees of freedom: \", dof\n\n let dist = chi2ud(dset)\n echo \" chi square test statistic: \", dist\n\n let p = chi2p(dof, dist)\n echo \" p-value of test statistic: \", p\n\n let sig = p < SigLevel\n echo &\" significant at {int(SigLevel * 100)}% level? {sig}\"\n echo &\" uniform? {not sig}\\n\"\n\n\nfor dset in [[199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461]]:\n utest(dset)\n", "language": "Nim" }, { "code": "let sqr x = x *. x\n\nlet chi2UniformDistance distrib =\n let count, len = Array.fold_left (fun (s, c) e -> s + e, succ c)\n \t\t\t\t (0, 0) distrib in\n let expected = float count /. float len in\n let distance = Array.fold_left (fun s e ->\n s +. sqr (float e -. expected) /. expected\n ) 0. distrib in\n let dof = float (pred len) in\n dof, distance\n\nlet chi2Proba dof distance =\n Gsl_sf.gamma_inc_Q (0.5 *. dof) (0.5 *. distance)\n\nlet chi2IsUniform distrib significance =\n let dof, distance = chi2UniformDistance distrib in\n let likelihoodOfRandom = chi2Proba dof distance in\n likelihoodOfRandom > significance\n\nlet _ =\n List.iter (fun distrib ->\n let dof, distance = chi2UniformDistance distrib in\n Printf.printf \"distribution \";\n Array.iter (Printf.printf \"\\t%d\") distrib;\n Printf.printf \"\\tdistance %g\" distance;\n Printf.printf \"\\t[%g > 0.05]\" (chi2Proba dof distance);\n if chi2IsUniform distrib 0.05 then Printf.printf \" fair\\n\"\n else Printf.printf \" unfair\\n\"\n )\n [\n [| 199809; 200665; 199607; 200270; 199649 |];\n [| 522573; 244456; 139979; 71531; 21461 |]\n ]\n", "language": "OCaml" }, { "code": "cumChi2(chi2,dof)={\n\tmy(g=gamma(dof/2));\n\tincgam(dof/2,chi2/2,g)/g\n};\ntest(v,alpha=.05)={\n\tmy(chi2,p,s=sum(i=1,#v,v[i]),ave=s/#v);\n\tprint(\"chi^2 statistic: \",chi2=sum(i=1,#v,(v[i]-ave)^2)/ave);\n\tprint(\"p-value: \",p=cumChi2(chi2,#v-1));\n\tif(p<alpha,\n\t\tprint(\"Significant at the alpha = \"alpha\" level: not uniform\");\n\t,\n\t\tprint(\"Not significant at the alpha = \"alpha\" level: uniform\");\n\t)\n};\n\ntest([199809, 200665, 199607, 200270, 199649])\ntest([522573, 244456, 139979, 71531, 21461])\n", "language": "PARI-GP" }, { "code": "use List::Util qw(sum reduce);\nuse constant pi => 3.14159265;\n\nsub incomplete_G_series {\n my($s, $z) = @_;\n my $n = 10;\n push @numers, $z**$_ for 1..$n;\n my @denoms = $s+1;\n push @denoms, $denoms[-1]*($s+$_) for 2..$n;\n my $M = 1;\n $M += $numers[$_-1]/$denoms[$_-1] for 1..$n;\n $z**$s / $s * exp(-$z) * $M;\n}\n\nsub G_of_half {\n my($n) = @_;\n if ($n % 2) { f(2*$_) / (4**$_ * f($_)) * sqrt(pi) for int ($n-1) / 2 }\n else { f(($n/2)-1) }\n}\n\nsub f { reduce { $a * $b } 1, 1 .. $_[0] } # factorial\n\nsub chi_squared_cdf {\n my($k, $x) = @_;\n my $f = $k < 20 ? 20 : 10;\n if ($x == 0) { 0.0 }\n elsif ($x < $k + $f*sqrt($k)) { incomplete_G_series($k/2, $x/2) / G_of_half($k) }\n else { 1.0 }\n}\nsub chi_squared_test {\n my(@bins) = @_;\n $significance = 0.05;\n my $n = @bins;\n my $N = sum @bins;\n my $expected = $N / $n;\n my $chi_squared = sum map { ($_ - $expected)**2 / $expected } @bins;\n my $p_value = 1 - chi_squared_cdf($n-1, $chi_squared);\n return $chi_squared, $p_value, $p_value > $significance ? 'True' : 'False';\n}\n\nfor $dataset ([199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]) {\n printf \"C2 = %10.3f, p-value = %.3f, uniform = %s\\n\", chi_squared_test(@$dataset);\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #7060A8;\">exp</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">simpson38</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">h1</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">h1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">tot</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">8</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">--&lt;copy of gamma from [[Gamma_function#Phix]]&gt;</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">gamma</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">accm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">accm</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">accm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">PI</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">accm</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">k1_factrl</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #000080;font-style:italic;\">-- (k - 1)!*(-1)^k with 0!==1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">12</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">exp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1.5</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">k1_factrl</span>\n <span style=\"color: #000000;\">k1_factrl</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">12</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">accm</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]/(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">accm</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #7060A8;\">exp</span><span style=\"color: #0000FF;\">(-(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">))*</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">12</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- Gamma(z+1)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">accm</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">z</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #000080;font-style:italic;\">--&lt;/copy of gamma&gt;</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">gammaIncQ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">aa1</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">1.5e-2</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">)*(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">2e-8</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">0.4</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">x</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">simpson38</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">aa1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">gamma</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chi2ud</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">expected</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">expected</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">tot</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">expected</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">chi2p</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dof</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">distance</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">gammaIncQ</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">dof</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">distance</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">sigLevel</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0.05</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">utest</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Uniform distribution test\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tot</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">dof</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">dist</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">chi2ud</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">chi2p</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dof</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dist</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">sig</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">sigLevel</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" dataset: %v\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" samples: %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">tot</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" categories: %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dset</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" degrees of freedom: %d\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dof</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" chi square test statistic: %g\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dist</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" p-value of test statistic: %g\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" significant at %.0f%% level? %t\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sigLevel</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sig</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" uniform? %t\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">sig</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">utest</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">199809</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200665</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">199607</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200270</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">199649</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">utest</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">522573</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">244456</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">139979</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">71531</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">21461</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "import math\nimport random\n\ndef GammaInc_Q( a, x):\n a1 = a-1\n a2 = a-2\n def f0( t ):\n return t**a1*math.exp(-t)\n\n def df0(t):\n return (a1-t)*t**a2*math.exp(-t)\n\n y = a1\n while f0(y)*(x-y) >2.0e-8 and y < x: y += .3\n if y > x: y = x\n\n h = 3.0e-4\n n = int(y/h)\n h = y/n\n hh = 0.5*h\n gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))\n\n return gamax/gamma_spounge(a)\n\nc = None\ndef gamma_spounge( z):\n global c\n a = 12\n\n if c is None:\n k1_factrl = 1.0\n c = []\n c.append(math.sqrt(2.0*math.pi))\n for k in range(1,a):\n c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )\n k1_factrl *= -k\n\n accm = c[0]\n for k in range(1,a):\n accm += c[k] / (z+k)\n accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)\n return accm/z;\n\ndef chi2UniformDistance( dataSet ):\n expected = sum(dataSet)*1.0/len(dataSet)\n cntrd = (d-expected for d in dataSet)\n return sum(x*x for x in cntrd)/expected\n\ndef chi2Probability(dof, distance):\n return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)\n\ndef chi2IsUniform(dataSet, significance):\n dof = len(dataSet)-1\n dist = chi2UniformDistance(dataSet)\n return chi2Probability( dof, dist ) > significance\n\ndset1 = [ 199809, 200665, 199607, 200270, 199649 ]\ndset2 = [ 522573, 244456, 139979, 71531, 21461 ]\n\nfor ds in (dset1, dset2):\n print \"Data set:\", ds\n dof = len(ds)-1\n distance =chi2UniformDistance(ds)\n print \"dof: %d distance: %.4f\" % (dof, distance),\n prob = chi2Probability( dof, distance)\n print \"probability: %.4f\"%prob,\n print \"uniform? \", \"Yes\"if chi2IsUniform(ds,0.05) else \"No\"\n", "language": "Python" }, { "code": "from scipy.stats import chisquare\n\n\nif __name__ == '__main__':\n dataSets = [[199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461]]\n print(f\"{'Distance':^12} {'pvalue':^12} {'Uniform?':^8} {'Dataset'}\")\n for ds in dataSets:\n dist, pvalue = chisquare(ds)\n uni = 'YES' if pvalue > 0.05 else 'NO'\n print(f\"{dist:12.3f} {pvalue:12.8f} {uni:^8} {ds}\")\n", "language": "Python" }, { "code": "dset1=c(199809,200665,199607,200270,199649)\ndset2=c(522573,244456,139979,71531,21461)\n\nchi2IsUniform<-function(dataset,significance=0.05){\n chi2IsUniform=(chisq.test(dataset)$p.value>significance)\n}\n\nfor (ds in list(dset1,dset2)){\n print(c(\"Data set:\",ds))\n print(chisq.test(ds))\n print(paste(\"uniform?\",chi2IsUniform(ds)))\n}\n", "language": "R" }, { "code": "#lang racket\n(require\n racket/flonum (planet williams/science:4:5/science)\n (only-in (planet williams/science/unsafe-ops-utils) real->float))\n\n; (chi^2-goodness-of-fit-test observed expected df)\n; Given: observed, a sequence of observed frequencies\n; expected, a sequence of expected frequencies\n; df, the degrees of freedom\n; Result: P-value = 1-chi^2cdf(X^2,df) , the p-value\n(define (chi^2-goodness-of-fit-test observed expected df)\n (define X^2 (for/sum ([o observed] [e expected])\n (/ (sqr (- o e)) e)))\n (- 1.0 (chi-squared-cdf X^2 df)))\n\n(define (is-uniform? rand n α)\n ; Use significance level α to test whether\n ; n small random numbers generated by rand\n ; have a uniform distribution.\n\n ; Observed values:\n (define o (make-vector 10 0))\n ; generate n random integers from 0 to 9.\n (for ([_ (+ n 1)])\n (define r (rand 10))\n (vector-set! o r (+ (vector-ref o r) 1)))\n ; Expected values:\n (define ex (make-vector 10 (/ n 10)))\n\n ; Calculate the P-value:\n (define P (chi^2-goodness-of-fit-test o ex (- n 1)))\n\n ; If the P-value is larger than α we accept the\n ; hypothesis that the numbers are distributed uniformly.\n (> P α))\n\n; Test whether the builtin generator is uniform:\n(is-uniform? random 1000 0.05)\n; Test whether the constant generator fails:\n(is-uniform? (λ(_) 5) 1000 0.05)\n", "language": "Racket" }, { "code": "#t\n#f\n", "language": "Racket" }, { "code": "sub incomplete-γ-series($s, $z) {\n my \\numers = $z X** 1..*;\n my \\denoms = [\\*] $s X+ 1..*;\n my $M = 1 + [+] (numers Z/ denoms) ... * < 1e-6;\n $z**$s / $s * exp(-$z) * $M;\n}\n\nsub postfix:<!>(Int $n) { [*] 2..$n }\n\nsub Γ-of-half(Int $n where * > 0) {\n ($n %% 2) ?? (($_-1)! given $n div 2)\n !! ((2*$_)! / (4**$_ * $_!) * sqrt(pi) given ($n-1) div 2);\n}\n\n# degrees of freedom constrained due to numerical limitations\nsub chi-squared-cdf(Int $k where 1..200, $x where * >= 0) {\n my $f = $k < 20 ?? 20 !! 10;\n given $x {\n when 0 { 0.0 }\n when * < $k + $f*sqrt($k) { incomplete-γ-series($k/2, $x/2) / Γ-of-half($k) }\n default { 1.0 }\n }\n}\n\nsub chi-squared-test(@bins, :$significance = 0.05) {\n my $n = +@bins;\n my $N = [+] @bins;\n my $expected = $N / $n;\n my $chi-squared = [+] @bins.map: { ($^bin - $expected)**2 / $expected }\n my $p-value = 1 - chi-squared-cdf($n-1, $chi-squared);\n return (:$chi-squared, :$p-value, :uniform($p-value > $significance));\n}\n\nfor [< 199809 200665 199607 200270 199649 >],\n [< 522573 244456 139979 71531 21461 >]\n -> $dataset\n{\n my %t = chi-squared-test($dataset);\n say 'data: ', $dataset;\n say \"χ² = {%t<chi-squared>}, p-value = {%t<p-value>.fmt('%.4f')}, uniform = {%t<uniform>}\";\n}\n", "language": "Raku" }, { "code": "/*REXX program performs a chi─squared test to verify a given distribution is uniform. */\nnumeric digits length( pi() ) - length(.) /*enough decimal digs for calculations.*/\n@.=; @.1= 199809 200665 199607 200270 199649\n @.2= 522573 244456 139979 71531 21461\n do s=1 while @.s\\==''; call uTest @.s /*invoke uTest with a data set of #'s.*/\n end /*s*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n!: procedure; parse arg x; p=1; do j=2 to x; p= p*j; end /*j*/; return p\nchi2p: procedure; parse arg dof, distance; return gammaI( dof/2, distance/2 )\nf: parse arg t; if t=0 then return 0; return t ** (a-1) * exp(-t)\ne: e =2.718281828459045235360287471352662497757247093699959574966967627724; return e\npi: pi=3.141592653589793238462643383279502884197169399375105820974944592308; return pi\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n!!: procedure; parse arg x; if x<2 then return 1; p= x\n do k=2+x//2 to x-1 by 2; p= p*k; end /*k*/; return p\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nchi2ud: procedure: parse arg ds; sum=0; expect= 0\n do j=1 for words(ds); expect= expect + word(ds, j)\n end /*j*/\n expect = expect / words(ds)\n do k=1 for words(ds)\n sum= sum + (word(ds, k) - expect) **2\n end /*k*/\n return sum / expect\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nexp: procedure; parse arg x; ix= x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix\n z=1; _=1; w=z; do j=1; _= _*x/j; z= (z + _)/1; if z==w then leave; w=z\n end /*j*/; if z\\==0 then z= z * e()**ix; return z\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngamma: procedure; parse arg x; if datatype(x, 'W') then return !(x-1) /*Int? Use fact*/\n n= trunc(x) /*at this point, X is pos and a multiple of 1/2.*/\n d= !!(n+n - 1) /*compute the double factorial of: 2*n - 1. */\n if n//2 then p= -1 /*if N is odd, then use a negative unity. */\n else p= 1 /*if N is even, then use a positive unity. */\n if x>0 then return p * d * sqrt(pi()) / (2**n)\n return p * (2**n) * sqrt(pi()) / d\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngammaI: procedure; parse arg a,x; y= a-1; do while f(y)*(x-y) > 2e-8 & y<x; y= y + .4\n end /*while*/\n y= min(x, y)\n return 1 - simp38(0, y, y / 0.015 / gamma(a-1) % 1)\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsimp38: procedure; parse arg a, b, n; h= (b-a) / n; h1= h / 3\n sum= f(a) + f(b)\n do j=3*n-1 by -1 while j>0\n if j//3 == 0 then sum= sum + 2 * f(a + h1*j)\n else sum= sum + 3 * f(a + h1*j)\n end /*j*/\n return h * sum / 8\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h= d+6\n numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g \"E\" _ .;g=g *.5'e'_%2\n do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/\n do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nuTest: procedure; parse arg dset; sum= 0; pad= left('', 11); sigLev= 1/20 /*5%*/\n say; say ' ' center(\" Uniform distribution test \", 75, '═')\n #= words(dset); sigPC= sigLev*100/1\n do j=1 for #; sum= sum + word(dset, j)\n end /*j*/\n say pad \" dataset: \" dset\n say pad \" samples: \" sum\n say pad \" categories: \" #\n say pad \" degrees of freedom: \" # - 1\n dist= chi2ud(dset)\n P= chi2p(# - 1, dist)\n sig = (abs(P) < dist * sigLev)\n say pad \"significant at \" sigPC'% level? ' word('no yes', sig + 1)\n say pad \" is the dataset uniform? \" word('no yes', (\\(sig))+ 1)\n return\n", "language": "REXX" }, { "code": "def gammaInc_Q(a, x)\n a1, a2 = a-1, a-2\n f0 = lambda {|t| t**a1 * Math.exp(-t)}\n df0 = lambda {|t| (a1-t) * t**a2 * Math.exp(-t)}\n\n y = a1\n y += 0.3 while f0[y]*(x-y) > 2.0e-8 and y < x\n y = x if y > x\n\n h = 3.0e-4\n n = (y/h).to_i\n h = y/n\n hh = 0.5 * h\n sum = 0\n (n-1).step(0, -1) do |j|\n t = h * j\n sum += f0[t] + hh * df0[t]\n end\n h * sum / gamma_spounge(a)\nend\n\nA = 12\nk1_factrl = 1.0\ncoef = [Math.sqrt(2.0*Math::PI)]\nCOEF = (1...A).each_with_object(coef) do |k,c|\n c << Math.exp(A-k) * (A-k)**(k-0.5) / k1_factrl\n k1_factrl *= -k\nend\n\ndef gamma_spounge(z)\n accm = (1...A).inject(COEF[0]){|res,k| res += COEF[k] / (z+k)}\n accm * Math.exp(-(z+A)) * (z+A)**(z+0.5) / z\nend\n\ndef chi2UniformDistance(dataSet)\n expected = dataSet.inject(:+).to_f / dataSet.size\n dataSet.map{|d|(d-expected)**2}.inject(:+) / expected\nend\n\ndef chi2Probability(dof, distance)\n 1.0 - gammaInc_Q(0.5*dof, 0.5*distance)\nend\n\ndef chi2IsUniform(dataSet, significance=0.05)\n dof = dataSet.size - 1\n dist = chi2UniformDistance(dataSet)\n chi2Probability(dof, dist) > significance\nend\n\ndsets = [ [ 199809, 200665, 199607, 200270, 199649 ],\n [ 522573, 244456, 139979, 71531, 21461 ] ]\n\nfor ds in dsets\n puts \"Data set:#{ds}\"\n dof = ds.size - 1\n puts \" degrees of freedom: %d\" % dof\n distance = chi2UniformDistance(ds)\n puts \" distance: %.4f\" % distance\n puts \" probability: %.4f\" % chi2Probability(dof, distance)\n puts \" uniform? %s\" % (chi2IsUniform(ds) ? \"Yes\" : \"No\")\nend\n", "language": "Ruby" }, { "code": "use statrs::function::gamma::gamma_li;\n\nfn chi_distance(dataset: &[u32]) -> f64 {\n let expected = f64::from(dataset.iter().sum::<u32>()) / dataset.len() as f64;\n dataset\n .iter()\n .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.))\n / expected\n}\n\nfn chi2_probability(dof: f64, distance: f64) -> f64 {\n 1. - gamma_li(dof * 0.5, distance * 0.5)\n}\n\nfn chi2_uniform(dataset: &[u32], significance: f64) -> bool {\n let d = chi_distance(&dataset);\n chi2_probability(dataset.len() as f64 - 1., d) > significance\n}\n\nfn main() {\n let dsets = vec![\n vec![199809, 200665, 199607, 200270, 199649],\n vec![522573, 244456, 139979, 71531, 21461],\n ];\n\n for ds in dsets {\n println!(\"Data set: {:?}\", ds);\n let d = chi_distance(&ds);\n print!(\"Distance: {:.6} \", d);\n print!(\n \"Chi2 probability: {:.6} \",\n chi2_probability(ds.len() as f64 - 1., d)\n );\n print!(\"Uniform? {}\\n\", chi2_uniform(&ds, 0.05));\n }\n}\n", "language": "Rust" }, { "code": "import org.apache.commons.math3.special.Gamma.regularizedGammaQ\n\nobject ChiSquare extends App {\n private val dataSets: Seq[Seq[Double]] =\n Seq(\n Seq(199809, 200665, 199607, 200270, 199649),\n Seq(522573, 244456, 139979, 71531, 21461)\n )\n\n private def χ2IsUniform(data: Seq[Double], significance: Double) =\n χ2Prob(data.size - 1.0, χ2Dist(data)) > significance\n\n private def χ2Dist(data: Seq[Double]) = {\n val avg = data.sum / data.size\n\n data.reduce((a, b) => a + math.pow(b - avg, 2)) / avg\n }\n\n private def χ2Prob(dof: Double, distance: Double) =\n regularizedGammaQ(dof / 2, distance / 2)\n\n printf(\" %4s %10s %12s %8s %s%n\",\n \"d.f.\", \"χ²distance\", \"χ²probability\", \"Uniform?\", \"dataset\")\n dataSets.foreach { ds =>\n val (dist, dof) = (χ2Dist(ds), ds.size - 1)\n\n printf(\"%4d %11.3f %13.8f %5s %6s%n\",\n dof, dist, χ2Prob(dof.toDouble, dist), if (χ2IsUniform(ds, 0.05)) \"YES\" else \"NO\", ds.mkString(\", \"))\n }\n}\n", "language": "Scala" }, { "code": "# Confluent hypergeometric function of the first kind F_1(a;b;z)\nfunc F1(a, b, z, limit=100) {\n sum(0..limit, {|k|\n rising_factorial(a, k) / rising_factorial(b, k) * z**k / k!\n })\n}\n\nfunc γ(a,x) { # lower incomplete gamma function γ(a,x)\n #a**(-1) * x**a * F1(a, a+1, -x) # simpler formula\n a**(-1) * x**a * exp(-x) * F1(1, a+1, x) # slightly better convergence\n}\n\nfunc P(a,z) { # regularized gamma function P(a,z)\n γ(a,z) / Γ(a)\n}\n\nfunc chi_squared_cdf (k, x) {\n var f = (k<20 ? 20 : 10)\n given(x) {\n when (0) { 0 }\n case (. < (k + f*sqrt(k))) { P(k/2, x/2) }\n else { 1 }\n }\n}\n\nfunc chi_squared_test(arr, significance = 0.05) {\n var n = arr.len\n var N = arr.sum\n var expected = N/n\n var χ_squared = arr.sum_by {|v| (v-expected)**2 / expected }\n var p_value = (1 - chi_squared_cdf(n-1, χ_squared))\n [χ_squared, p_value, p_value > significance]\n}\n\n[\n %n< 199809 200665 199607 200270 199649 >,\n %n< 522573 244456 139979 71531 21461 >,\n].each {|dataset|\n var r = chi_squared_test(dataset)\n say \"data: #{dataset}\"\n say \"χ² = #{r[0]}, p-value = #{r[1].round(-4)}, uniform = #{r[2]}\\n\"\n}\n", "language": "Sidef" }, { "code": "package require Tcl 8.5\npackage require math::statistics\n\nproc isUniform {distribution {significance 0.05}} {\n set count [tcl::mathop::+ {*}[dict values $distribution]]\n set expected [expr {double($count) / [dict size $distribution]}]\n set X2 0.0\n foreach value [dict values $distribution] {\n\tset X2 [expr {$X2 + ($value - $expected)**2 / $expected}]\n }\n set degreesOfFreedom [expr {[dict size $distribution] - 1}]\n set likelihoodOfRandom [::math::statistics::incompleteGamma \\\n\t[expr {$degreesOfFreedom / 2.0}] [expr {$X2 / 2.0}]]\n expr {$likelihoodOfRandom > $significance}\n}\n", "language": "Tcl" }, { "code": "proc makeDistribution {operation {count 1000000}} {\n for {set i 0} {$i<$count} {incr i} {incr distribution([uplevel 1 $operation])}\n return [array get distribution]\n}\n\nset distFair [makeDistribution {expr int(rand()*5)}]\nputs \"distribution \\\"$distFair\\\" assessed as [expr [isUniform $distFair]?{fair}:{unfair}]\"\nset distUnfair [makeDistribution {expr int(rand()*rand()*5)}]\nputs \"distribution \\\"$distUnfair\\\" assessed as [expr [isUniform $distUnfair]?{fair}:{unfair}]\"\n", "language": "Tcl" }, { "code": "import math\n\ntype Ifctn = fn(f64) f64\n\nfn simpson38(f Ifctn, a f64, b f64, n int) f64 {\n h := (b - a) / f64(n)\n h1 := h / 3\n mut sum := f(a) + f(b)\n for j := 3*n - 1; j > 0; j-- {\n if j%3 == 0 {\n sum += 2 * f(a+h1*f64(j))\n } else {\n sum += 3 * f(a+h1*f64(j))\n }\n }\n return h * sum / 8\n}\n\nfn gamma_inc_q(a f64, x f64) f64 {\n aa1 := a - 1\n f := Ifctn(fn[aa1](t f64) f64 {\n return math.pow(t, aa1) * math.exp(-t)\n })\n mut y := aa1\n h := 1.5e-2\n for f(y)*(x-y) > 2e-8 && y < x {\n y += .4\n }\n if y > x {\n y = x\n }\n return 1 - simpson38(f, 0, y, int(y/h/math.gamma(a)))\n}\n\nfn chi2ud(ds []int) f64 {\n mut sum, mut expected := 0.0,0.0\n for d in ds {\n expected += f64(d)\n }\n expected /= f64(ds.len)\n for d in ds {\n x := f64(d) - expected\n sum += x * x\n }\n return sum / expected\n}\n\nfn chi2p(dof int, distance f64) f64 {\n return gamma_inc_q(.5*f64(dof), .5*distance)\n}\n\nconst sig_level = .05\n\nfn main() {\n for dset in [\n [199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461],\n ] {\n utest(dset)\n }\n}\n\nfn utest(dset []int) {\n println(\"Uniform distribution test\")\n mut sum := 0\n for c in dset {\n sum += c\n }\n println(\" dataset: $dset\")\n println(\" samples: $sum\")\n println(\" categories: $dset.len\")\n\n dof := dset.len - 1\n println(\" degrees of freedom: $dof\")\n\n dist := chi2ud(dset)\n println(\" chi square test statistic: $dist\")\n\n p := chi2p(dof, dist)\n println(\" p-value of test statistic: $p\")\n\n sig := p < sig_level\n println(\" significant at ${sig_level*100:2.0f}% level? $sig\")\n println(\" uniform? ${!sig}\\n\")\n}\n", "language": "V-(Vlang)" }, { "code": "Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean\n 'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level.\n Dim Total As Long, Ei As Long, i As Integer\n Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double\n Debug.Print \"[1] \"\"Data set:\"\" \";\n For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n Total = Total + ObservationFrequencies(i)\n Debug.Print ObservationFrequencies(i); \" \";\n Next i\n DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)\n 'This is exactly the number of different categories minus 1\n Ei = Total / (DegreesOfFreedom + 1)\n For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)\n ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei\n Next i\n p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)\n Debug.Print\n Debug.Print \" Chi-squared test for given frequencies\"\n Debug.Print \"X-squared =\"; ChiSquared; \", \";\n Debug.Print \"df =\"; DegreesOfFreedom; \", \";\n Debug.Print \"p-value = \"; Format(p_value, \"0.0000\")\n Test4DiscreteUniformDistribution = p_value > Significance\nEnd Function\nPublic Sub test()\n Dim O() As Variant\n O = [{199809,200665,199607,200270,199649}]\n Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\n O = [{522573,244456,139979,71531,21461}]\n Debug.Print \"[1] \"\"Uniform? \"; Test4DiscreteUniformDistribution(O, 0.05); \"\"\"\"\nEnd Sub\n", "language": "VBA" }, { "code": "import \"./math\" for Math, Nums\nimport \"./fmt\" for Fmt\n\nvar integrate = Fn.new { |a, b, n, f|\n var h = (b - a) / n\n var sum = 0\n for (i in 0...n) {\n var x = a + i*h\n sum = sum + (f.call(x) + 4 * f.call(x + h/2) + f.call(x + h)) / 6\n }\n return sum * h\n}\n\nvar gammaIncomplete = Fn.new { |a, x|\n var am1 = a - 1\n var f0 = Fn.new { |t| t.pow(am1) * (-t).exp }\n var h = 1.5e-2\n var y = am1\n while ((f0.call(y) * (x - y) > 2e-8) && y < x) y = y + 0.4\n if (y > x) y = x\n return 1 - integrate.call(0, y, (y/h).truncate, f0) / Math.gamma(a)\n}\n\nvar chi2UniformDistance = Fn.new { |ds|\n var expected = Nums.mean(ds)\n var sum = Nums.sum(ds.map { |d| (d - expected).pow(2) }.toList)\n return sum / expected\n}\n\nvar chi2Probability = Fn.new { |dof, dist| gammaIncomplete.call(0.5*dof, 0.5*dist) }\n\nvar chiIsUniform = Fn.new { |ds, significance|\n var dof = ds.count - 1\n var dist = chi2UniformDistance.call(ds)\n return chi2Probability.call(dof, dist) > significance\n}\n\nvar dsets = [\n [199809, 200665, 199607, 200270, 199649],\n [522573, 244456, 139979, 71531, 21461]\n]\nfor (ds in dsets) {\n System.print(\"Dataset: %(ds)\")\n var dist = chi2UniformDistance.call(ds)\n var dof = ds.count - 1\n Fmt.write(\"DOF: $d Distance: $.4f\", dof, dist)\n var prob = chi2Probability.call(dof, dist)\n Fmt.write(\" Probability: $.6f\", prob)\n var uniform = chiIsUniform.call(ds, 0.05) ? \"Yes\" : \"No\"\n System.print(\" Uniform? %(uniform)\\n\")\n}\n", "language": "Wren" }, { "code": "/* Numerical integration method */\nfcn Simpson3_8(f,a,b,N){ // fcn,double,double,Int --> double\n h,h1:=(b - a)/N, h/3.0;\n h*[1..3*N - 1].reduce('wrap(sum,j){\n l1:=(if(j%3) 3.0 else 2.0);\n sum + l1*f(a + h1*j);\n },f(a) + f(b))/8.0;\n}\n\nconst A=12;\nfcn Gamma_Spouge(z){ // double --> double\n var coefs=fcn{ // this runs only once, at construction time\n a,coefs:=A.toFloat(),(A).pump(List(),0.0);\n k1_factrl:=1.0;\n coefs[0]=(2.0*(0.0).pi).sqrt();\n foreach k in ([1.0..A-1]){\n coefs[k]=(a - k).exp() * (a - k).pow(k - 0.5) / k1_factrl;\n\t k1_factrl*=-k;\n }\n coefs\n }();\n\n ( [1..A-1].reduce('wrap(accum,k){ accum + coefs[k]/(z + k) },coefs[0])\n * (-(z + A)).exp()*(z + A).pow(z + 0.5) )\n / z;\n}\n\nfcn f0(t,aa1){ t.pow(aa1)*(-t).exp() }\n\nfcn GammaIncomplete_Q(a,x){ // double,double --> double\n h:=1.5e-2; /* approximate integration step size */\n /* this cuts off the tail of the integration to speed things up */\n y:=a - 1; f:=f0.fp1(y);\n while((f(y)*(x - y)>2.0e-8) and (y<x)){ y+=0.4; }\n if(y>x) y=x;\n 1.0 - Simpson3_8(f,0.0,y,(y/h).toInt())/Gamma_Spouge(a);\n}\n", "language": "Zkl" }, { "code": "fcn chi2UniformDistance(ds){ // --> double\n dslen :=ds.len();\n expected:=dslen.reduce('wrap(sum,k){ sum + ds[k] },0.0)/dslen;\n sum := dslen.reduce('wrap(sum,k){ x:=ds[k] - expected; sum + x*x },0.0);\n sum/expected\n}\n\nfcn chi2Probability(dof,distance){ GammaIncomplete_Q(0.5*dof, 0.5*distance) }\n\nfcn chiIsUniform(dset,significance=0.05){\n significance < chi2Probability(-1.0 + dset.len(),chi2UniformDistance(dset))\n}\n", "language": "Zkl" }, { "code": "datasets:=T( T(199809.0, 200665.0, 199607.0, 200270.0, 199649.0),\n T(522573.0, 244456.0, 139979.0, 71531.0, 21461.0) );\nprintln(\" %4s %12s %12s %8s %s\".fmt(\n \"dof\", \"distance\", \"probability\", \"Uniform?\", \"dataset\"));\nforeach ds in (datasets){\n dof :=ds.len() - 1;\n dist:=chi2UniformDistance(ds);\n prob:=chi2Probability(dof,dist);\n println(\"%4d %12.3f %12.8f %5s %6s\".fmt(\n dof, dist, prob, chiIsUniform(ds) and \"YES\" or \"NO\",\n\t ds.concat(\",\")));\n}\n", "language": "Zkl" } ]
Verify-distribution-uniformity-Chi-squared-test
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive\nnote: Probability and statistics\n", "language": "00-META" }, { "code": "<small>This task is an adjunct to [[Seven-sided dice from five-sided dice]].</small>\n\n\n;Task:\nCreate a function to check that the random integers returned from a small-integer generator function have uniform distribution.\n\n\nThe function should take as arguments:\n* The function (or object) producing random integers.\n* The number of times to call the integer generator.\n* A 'delta' value of some sort that indicates how close to a flat distribution is close enough.\n\n\nThe function should produce:\n* Some indication of the distribution achieved.\n* An 'error' if the distribution is not flat enough.\n\n\nShow the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-sided dice from five-sided dice]]).\n\n\nSee also:\n*[[Verify distribution uniformity/Chi-squared test]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F dice5()\n R random:(1..5)\n\nF distcheck(func, repeats, delta)\n V bin = DefaultDict[Int, Int]()\n L 1..repeats\n bin[func()]++\n V target = repeats I/ bin.len\n V deltacount = Int(delta / 100.0 * target)\n assert(all(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed from #. +/- #.: #.’.format(target, deltacount, sorted(bin.items()).map((key, count) -> (key, @target - count))))\n print(bin)\n\ndistcheck(dice5, 1000000, 1)\n", "language": "11l" }, { "code": "with Ada.Numerics.Discrete_Random, Ada.Text_IO;\n\nprocedure Naive_Random is\n\n type M_1000 is mod 1000;\n package Rand is new Ada.Numerics.Discrete_Random(M_1000);\n Gen: Rand.Generator;\n\n procedure Perform(Modulus: Positive; Expected, Margin: Natural;\n Passed: out boolean) is\n Low: Natural := (100-Margin) * Expected/100;\n High: Natural := (100+Margin) * Expected/100;\n Buckets: array(0 .. Modulus-1) of Natural := (others => 0);\n Index: Natural;\n begin\n for I in 1 .. Expected * Modulus loop\n Index := Integer(Rand.Random(Gen)) mod Modulus;\n Buckets(Index) := Buckets(Index) + 1;\n end loop;\n Passed := True;\n for I in Buckets'Range loop\n Ada.Text_IO.Put(\"Bucket\" & Integer'Image(I+1) & \":\" &\n Integer'Image(Buckets(I)));\n if Buckets(I) < Low or else Buckets(I) > High then\n Ada.Text_IO.Put_Line(\" (failed)\");\n Passed := False;\n else\n Ada.Text_IO.Put_Line(\" (passed)\");\n end if;\n end loop;\n Ada.Text_IO.New_Line;\n end Perform;\n\n Number_Of_Buckets: Positive := Natural'Value(Ada.Text_IO.Get_Line);\n Expected_Per_Bucket: Natural := Natural'Value(Ada.Text_IO.Get_Line);\n Margin_In_Percent: Natural := Natural'Value(Ada.Text_IO.Get_Line);\n OK: Boolean;\n\nbegin\n Ada.Text_IO.Put_Line( \"Buckets:\" & Integer'Image(Number_Of_Buckets) &\n \", Expected:\" & Integer'Image(Expected_Per_Bucket) &\n \", Margin:\" & Integer'Image(Margin_In_Percent));\n Rand.Reset(Gen);\n\n Perform(Modulus => Number_Of_Buckets,\n Expected => Expected_Per_Bucket,\n Margin => Margin_In_Percent,\n Passed => OK);\n\n Ada.Text_IO.Put_Line(\"Test Passed? (\" & Boolean'Image(OK) & \")\");\nend Naive_Random;\n", "language": "Ada" }, { "code": "MsgBox, % DistCheck(\"dice7\",10000,3)\n\nDistCheck(function, repetitions, delta)\n{ Loop, % 7 ; initialize array\n { bucket%A_Index% := 0\n }\n\n Loop, % repetitions ; populate buckets\n { v := %function%()\n bucket%v% += 1\n }\n\n lbnd := round((repetitions/7)*(100-delta)/100)\n ubnd := round((repetitions/7)*(100+delta)/100)\n text := \"Distribution check:`n`nTotal elements = \" repetitions\n . \"`n`nMargin = \" delta \"% --> Lbound = \" lbnd \", Ubound = \" ubnd \"`n\"\n Loop, % 7\n { text := text \"`nBucket \" A_Index \" contains \" bucket%A_Index% \" elements.\"\n If bucket%A_Index% not between %lbnd% and %ubnd%\n text := text \" Skewed.\"\n }\n Return, text\n}\n", "language": "AutoHotkey" }, { "code": " MAXRND = 7\n FOR r% = 2 TO 5\n check% = FNdistcheck(FNdice5, 10^r%, 0.05)\n PRINT \"Over \"; 10^r% \" runs dice5 \";\n IF check% THEN\n PRINT \"failed distribution check with \"; check% \" bin(s) out of range\"\n ELSE\n PRINT \"passed distribution check\"\n ENDIF\n NEXT\n END\n\n DEF FNdistcheck(RETURN func%, repet%, delta)\n LOCAL i%, m%, r%, s%, bins%()\n DIM bins%(MAXRND)\n FOR i% = 1 TO repet%\n r% = FN(^func%)\n bins%(r%) += 1\n IF r%>m% m% = r%\n NEXT\n FOR i% = 1 TO m%\n IF bins%(i%)/(repet%/m%) > 1+delta s% += 1\n IF bins%(i%)/(repet%/m%) < 1-delta s% += 1\n NEXT\n = s%\n\n DEF FNdice5 = RND(5)\n", "language": "BBC-BASIC" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\ninline int rand5()\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % 5);\n\twhile ((r = rand()) >= rand_max);\n\treturn r / (rand_max / 5) + 1;\n}\n\ninline int rand5_7()\n{\n\tint r;\n\twhile ((r = rand5() * 5 + rand5()) >= 27);\n\treturn r / 3 - 1;\n}\n\n/* assumes gen() returns a value from 1 to n */\nint check(int (*gen)(), int n, int cnt, double delta) /* delta is relative */\n{\n\tint i = cnt, *bins = calloc(sizeof(int), n);\n\tdouble ratio;\n\twhile (i--) bins[gen() - 1]++;\n\tfor (i = 0; i < n; i++) {\n\t\tratio = bins[i] * n / (double)cnt - 1;\n\t\tif (ratio > -delta && ratio < delta) continue;\n\n\t\tprintf(\"bin %d out of range: %d (%g%% vs %g%%), \",\n\t\t\ti + 1, bins[i], ratio * 100, delta * 100);\n\t\tbreak;\n\t}\n\tfree(bins);\n\treturn i == n;\n}\n\nint main()\n{\n\tint cnt = 1;\n\twhile ((cnt *= 10) <= 1000000) {\n\t\tprintf(\"Count = %d: \", cnt);\n\t\tprintf(check(rand5_7, 7, cnt, 0.03) ? \"flat\\n\" : \"NOT flat\\n\");\n\t}\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <map>\n#include <iostream>\n#include <cmath>\n\ntemplate<typename F>\n bool test_distribution(F f, int calls, double delta)\n{\n typedef std::map<int, int> distmap;\n distmap dist;\n\n for (int i = 0; i < calls; ++i)\n ++dist[f()];\n\n double mean = 1.0/dist.size();\n\n bool good = true;\n\n for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)\n {\n if (std::abs((1.0 * i->second)/calls - mean) > delta)\n {\n std::cout << \"Relative frequency \" << i->second/(1.0*calls)\n << \" of result \" << i->first\n << \" deviates by more than \" << delta\n << \" from the expected value \" << mean << \"\\n\";\n good = false;\n }\n }\n\n return good;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Test\n{\n static void DistCheck(Func<int> func, int nRepeats, double delta)\n {\n var counts = new Dictionary<int, int>();\n\n for (int i = 0; i < nRepeats; i++)\n {\n int result = func();\n if (counts.ContainsKey(result))\n counts[result]++;\n else\n counts[result] = 1;\n }\n\n double target = nRepeats / (double)counts.Count;\n int deltaCount = (int)(delta / 100.0 * target);\n\n foreach (var kvp in counts)\n {\n if (Math.Abs(target - kvp.Value) >= deltaCount)\n Console.WriteLine(\"distribution potentially skewed for '{0}': '{1}'\", kvp.Key, kvp.Value);\n }\n\n foreach (var key in counts.Keys.OrderBy(k => k))\n {\n Console.WriteLine(\"{0} {1}\", key, counts[key]);\n }\n }\n\n public static void Main(string[] args)\n {\n DistCheck(() => new Random().Next(1, 6), 1_000_000, 1);\n }\n}\n", "language": "C-sharp" }, { "code": "(defn verify [rand n & [delta]]\n (let [rands (frequencies (repeatedly n rand))\n avg (/ (reduce + (map val rands)) (count rands))\n max-delta (* avg (or delta 1/10))\n acceptable? #(<= (- avg max-delta) % (+ avg max-delta))]\n (for [[num count] (sort rands)]\n [num count (acceptable? count)])))\n\n(doseq [n [100 1000 10000]\n [num count okay?] (verify #(rand-int 7) n)]\n (println \"Saw\" num count \"times:\"\n (if okay? \"that's\" \" not\") \"acceptable\"))\n", "language": "Clojure" }, { "code": "(defun check-distribution (function n &optional (delta 1.0))\n (let ((bins (make-hash-table)))\n (loop repeat n do (incf (gethash (funcall function) bins 0)))\n (loop with target = (/ n (hash-table-count bins))\n for key being each hash-key of bins using (hash-value value)\n when (> (abs (- value target)) (* 0.01 delta n))\n do (format t \"~&Distribution potentially skewed for ~w:~\n expected around ~w got ~w.\" key target value)\n finally (return bins))))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.string, std.math, std.algorithm, std.traits;\n\n/**\nBin the answers to fn() and check bin counts are within\n+/- delta % of repeats/bincount.\n*/\nvoid distCheck(TF)(in TF func, in int nRepeats, in double delta) /*@safe*/\nif (isCallable!TF) {\n int[int] counts;\n foreach (immutable i; 0 .. nRepeats)\n counts[func()]++;\n immutable double target = nRepeats / double(counts.length);\n immutable int deltaCount = cast(int)(delta / 100.0 * target);\n\n foreach (immutable k, const count; counts)\n if (abs(target - count) >= deltaCount)\n throw new Exception(format(\n \"distribution potentially skewed for '%s': '%d'\\n\",\n k, count));\n\n foreach (immutable k; counts.keys.sort())\n writeln(k, \" \", counts[k]);\n writeln;\n}\n\nversion (verify_distribution_uniformity_naive_main) {\n void main() {\n import std.random;\n distCheck(() => uniform(1, 6), 1_000_000, 1);\n }\n}\n", "language": "D" }, { "code": "defmodule VerifyDistribution do\n def naive( generator, times, delta_percent ) do\n dict = Enum.reduce( List.duplicate(generator, times), Map.new, &update_counter/2 )\n values = Map.values(dict)\n average = Enum.sum( values ) / map_size( dict )\n delta = average * (delta_percent / 100)\n fun = fn {_key, value} -> abs(value - average) > delta end\n too_large_dict = Enum.filter( dict, fun )\n return( length(too_large_dict), too_large_dict, average, delta_percent )\n end\n\n def return( 0, _too_large_dict, _average, _delta ), do: :ok\n def return( _n, too_large_dict, average, delta ) do\n {:error, {too_large_dict, :failed_expected_average, average, 'with_delta_%', delta}}\n end\n\n def update_counter( fun, dict ), do: Map.update( dict, fun.(), 1, &(&1+1) )\nend\n\nfun = fn -> Dice.dice7 end\nIO.inspect VerifyDistribution.naive( fun, 100000, 3 )\nIO.inspect VerifyDistribution.naive( fun, 100, 3 )\n", "language": "Elixir" }, { "code": "-module( verify_distribution_uniformity ).\n\n-export( [naive/3] ).\n\nnaive( Generator, Times, Delta_percent ) ->\n Dict = lists:foldl( fun update_counter/2, dict:new(), lists:duplicate(Times, Generator) ),\n Values = [dict:fetch(X, Dict) || X <- dict:fetch_keys(Dict)],\n Average = lists:sum( Values ) / dict:size( Dict ),\n Delta = Average * (Delta_percent / 100),\n Fun = fun(_Key, Value) -> erlang:abs(Value - Average) > Delta end,\n Too_large_dict = dict:filter( Fun, Dict ),\n return( dict:size(Too_large_dict), Too_large_dict, Average, Delta_percent ).\n\n\n\nreturn( 0, _Too_large_dict, _Average, _Delta ) -> ok;\nreturn( _N, Too_large_dict, Average, Delta ) ->\n\t{error, {dict:to_list(Too_large_dict), failed_expected_average, Average, 'with_delta_%', Delta}}.\n\nupdate_counter( Fun, Dict ) -> dict:update_counter( Fun(), 1, Dict ).\n", "language": "Erlang" }, { "code": ">function checkrandom (frand$, n:index, delta:positive real) ...\n$ v=zeros(1,n);\n$ loop 1 to n; v{#}=frand$(); end;\n$ K=max(v);\n$ fr=getfrequencies(v,1:K);\n$ return max(fr/n-1/K)<delta/sqrt(n);\n$ endfunction\n>function dice () := intrandom(1,1,6);\n>checkrandom(\"dice\",1000000,1)\n 1\n>wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6\n [ 0 0.165 0.335 0.5 0.666666666667 0.833333333333 1 ]\n>function wrongdice () := find(wd,random())\n>checkrandom(\"wrongdice\",1000000,1)\n 0\n", "language": "Euler" }, { "code": ">function dice5 () := intrandom(1,1,5);\n>function dice7 () ...\n$ repeat\n$ k=(dice5()-1)*5+dice5();\n$ if k<=21 then return ceil(k/3); endif;\n$ end;\n$ endfunction\n>checkrandom(\"dice7\",1000000,1)\n 1\n", "language": "Euler" }, { "code": ">function dice5(n) := intrandom(1,n,5)-1;\n>function dice7(n) ...\n$ v=dice5(2*n)*5+dice5(2*n);\n$ return v[nonzeros(v<=21)][1:n];\n$ endfunction\n>test=dice7(1000000);\n>function checkrandom (v, delta=1) ...\n$ K=max(v); n=cols(v);\n$ fr=getfrequencies(v,1:K);\n$ return max(fr/n-1/K)<delta/sqrt(n);\n$ endfunction\n>checkrandom(test)\n 1\n>wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6\n [ 0 0.165 0.335 0.5 0.666666666667 0.833333333333 1 ]\n>function wrongdice (n) := find(wd,random(1,n))\n>checkrandom(wrongdice(1000000))\n 0\n", "language": "Euler" }, { "code": "USING: kernel random sequences assocs locals sorting prettyprint\n math math.functions math.statistics math.vectors math.ranges ;\nIN: rosetta-code.dice7\n\n! Output a random integer 1..5.\n: dice5 ( -- x )\n 5 [1,b] random\n;\n\n! Output a random integer 1..7 using dice5 as randomness source.\n: dice7 ( -- x )\n 0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until\n 7 rem 1 +\n;\n\n! Roll the die by calling the quotation the given number of times and return\n! an array with roll results.\n! Sample call: 1000 [ dice7 ] roll\n: roll ( times quot: ( -- x ) -- array )\n [ call( -- x ) ] curry replicate\n;\n\n! Input array contains outcomes of a number of die throws. Each die result is\n! an integer in the range 1..X. Calculate and return the number of each\n! of the results in the array so that in the first position of the result\n! there is the number of ones in the input array, in the second position\n! of the result there is the number of twos in the input array, etc.\n: count-dice-outcomes ( X array -- array )\n histogram\n swap [1,b] [ over [ 0 or ] change-at ] each\n sort-keys values\n;\n\n! Verify distribution uniformity/Naive. Delta is the acceptable deviation\n! from the ideal number of items in each bucket, expressed as a fraction of\n! the total count. Sides is the number of die sides. Die-func is a word that\n! produces a random number on stack in the range [1..sides], times is the\n! number of times to call it.\n! Sample call: 0.02 7 [ dice7 ] 100000 verify\n:: verify ( delta sides die-func: ( -- random ) times -- )\n sides\n times die-func roll\n count-dice-outcomes\n dup .\n times sides / :> ideal-count\n ideal-count v-n vabs\n times v/n\n delta [ < ] curry all?\n [ \"Random enough\" . ] [ \"Not random enough\" . ] if\n;\n\n\n! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die.\n: verify-all ( -- )\n { 1 10 100 1000 10000 100000 1000000 }\n [| times | 0.02 7 [ dice7 ] times verify ] each\n;\n", "language": "Factor" }, { "code": ": .bounds ( u1 u2 -- ) .\" lower bound = \" . .\" upper bound = \" 1- . cr ;\n: init-bins ( n -- addr )\n cells dup allocate throw tuck swap erase ;\n: expected ( u1 cnt -- u2 ) over 2/ + swap / ;\n: calc-limits ( n cnt pct -- low high )\n >r expected r> over 100 */ 2dup + 1+ >r - r> ;\n: make-histogram ( bins xt cnt -- )\n 0 ?do 2dup execute 1- cells + 1 swap +! loop 2drop ;\n: valid-bin? ( addr n low high -- f )\n 2>r cells + @ dup . 2r> within ;\n\n: check-distribution {: xt cnt n pct -- f :}\n\\ assumes xt generates numbers from 1 to n\n n init-bins {: bins :}\n n cnt pct calc-limits {: low high :}\n high low .bounds\n bins xt cnt make-histogram\n true \\ result flag\n n 0 ?do\n i 1+ . .\" : \" bins i low high valid-bin?\n dup 0= if .\" not \" then .\" ok\" cr\n and\n loop\n bins free throw ;\n", "language": "Forth" }, { "code": "subroutine distcheck(randgen, n, delta)\n\n interface\n function randgen\n integer :: randgen\n end function randgen\n end interface\n\n real, intent(in) :: delta\n integer, intent(in) :: n\n integer :: i, mval, lolim, hilim\n integer, allocatable :: buckets(:)\n integer, allocatable :: rnums(:)\n logical :: skewed = .false.\n\n allocate(rnums(n))\n\n do i = 1, n\n rnums(i) = randgen()\n end do\n\n mval = maxval(rnums)\n allocate(buckets(mval))\n buckets = 0\n\n do i = 1, n\n buckets(rnums(i)) = buckets(rnums(i)) + 1\n end do\n\n lolim = n/mval - n/mval*delta\n hilim = n/mval + n/mval*delta\n\n do i = 1, mval\n if(buckets(i) < lolim .or. buckets(i) > hilim) then\n write(*,\"(a,i0,a,i0,a,i0)\") \"Distribution potentially skewed for bucket \", i, \" Expected: \", &\n n/mval, \" Actual: \", buckets(i)\n skewed = .true.\n end if\n end do\n\n if (.not. skewed) write(*,\"(a)\") \"Distribution uniform\"\n\n deallocate(rnums)\n deallocate(buckets)\n\nend subroutine\n", "language": "Fortran" }, { "code": "Randomize Timer\nFunction dice5() As Integer\n Return Int(Rnd * 5) + 1\nEnd Function\n\nFunction dice7() As Integer\n Dim As Integer temp\n Do\n temp = dice5() * 5 + dice5() -6\n Loop Until temp < 21\n Return (temp Mod 7) +1\nEnd Function\n\nFunction distCheck(n As Ulongint, delta As Double) As Ulongint\n\n Dim As Ulongint a(n)\n Dim As Ulongint maxBucket = 0\n Dim As Ulongint minBucket = 1000000\n For i As Ulongint = 1 To n\n a(i) = dice5()\n If a(i) > maxBucket Then maxBucket = a(i)\n If a(i) < minBucket Then minBucket = a(i)\n Next i\n\n Dim As Ulongint nBuckets = maxBucket + 1\n Dim As Ulongint buckets(maxBucket)\n For i As Ulongint = 1 To n\n buckets(a(i)) += 1\n Next i\n 'check buckets\n Dim As Ulongint expected = n / (maxBucket-minBucket+1)\n Dim As Ulongint minVal = Int(expected*(1-delta))\n Dim As Ulongint maxVal = Int(expected*(1+delta))\n expected = Int(expected)\n Print \"minVal\", \"Expected\", \"maxVal\"\n Print minVal, expected, maxVal\n Print \"Bucket\", \"Counter\", \"pass/fail\"\n distCheck = true\n For i As Ulongint = minBucket To maxBucket\n Print i, buckets(i), Iif((minVal > buckets(i)) Or (buckets(i) > maxVal),\"fail\",\"\")\n If (minVal > buckets(i)) Or (buckets(i) > maxVal) Then Return false\n Next i\nEnd Function\n\nDim Shared As Ulongint n = 1000\nPrint \"Testing \";n;\" times\"\nIf Not(distCheck(n, 0.05)) Then Print \"Test failed\" Else Print \"Test passed\"\nPrint\n\nn = 10000\nPrint \"Testing \";n;\" times\"\nIf Not(distCheck(n, 0.05)) Then Print \"Test failed\" Else Print \"Test passed\"\nPrint\n\nn = 50000\nPrint \"Testing \";n;\" times\"\nIf Not(distCheck(n, 0.05)) Then Print \"Test failed\" Else Print \"Test passed\"\nPrint\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"time\"\n)\n\n// \"given\"\nfunc dice5() int {\n return rand.Intn(5) + 1\n}\n\n// function specified by task \"Seven-sided dice from five-sided dice\"\nfunc dice7() (i int) {\n for {\n i = 5*dice5() + dice5()\n if i < 27 {\n break\n }\n }\n return (i / 3) - 1\n}\n\n// function specified by task \"Verify distribution uniformity/Naive\"\n//\n// Parameter \"f\" is expected to return a random integer in the range 1..n.\n// (Values out of range will cause an unceremonious crash.)\n// \"Max\" is returned as an \"indication of distribution achieved.\"\n// It is the maximum delta observed from the count representing a perfectly\n// uniform distribution.\n// Also returned is a boolean, true if \"max\" is less than threshold\n// parameter \"delta.\"\nfunc distCheck(f func() int, n int,\n repeats int, delta float64) (max float64, flatEnough bool) {\n count := make([]int, n)\n for i := 0; i < repeats; i++ {\n count[f()-1]++\n }\n expected := float64(repeats) / float64(n)\n for _, c := range count {\n max = math.Max(max, math.Abs(float64(c)-expected))\n }\n return max, max < delta\n}\n\n// Driver, produces output satisfying both tasks.\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n const calls = 1000000\n max, flatEnough := distCheck(dice7, 7, calls, 500)\n fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n max, flatEnough = distCheck(dice7, 7, calls, 500)\n fmt.Println(\"Max delta:\", max, \"Flat enough:\", flatEnough)\n}\n", "language": "Go" }, { "code": "import System.Random\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\n\ndistribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))]\ndistribCheck f n d = do\n nrs <- replicateM n f\n let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs\n avg = (fromIntegral n) / fromIntegral (length group)\n ul = round $ (100 + fromIntegral d)/100 * avg\n ll = round $ (100 - fromIntegral d)/100 * avg\n return $ map (head &&& (id &&& liftM2 (&&) (>ll)(<ul)).length) group\n", "language": "Haskell" }, { "code": "*Main> mapM_ print .sort =<< distribCheck (randomRIO(1,6)) 100000 3\n(1,(16911,True))\n(2,(16599,True))\n(3,(16670,True))\n(4,(16624,True))\n(5,(16526,True))\n(6,(16670,True))\n", "language": "Haskell" }, { "code": "(import [collections [Counter]])\n(import [random [randint]])\n\n(defn uniform? [f repeats delta]\n; Call 'f' 'repeats' times, then check if the proportion of each\n; value seen is within 'delta' of the reciprocal of the count\n; of distinct values.\n (setv bins (Counter (list-comp (f) [i (range repeats)])))\n (setv target (/ 1 (len bins)))\n (all (list-comp\n (<= (- target delta) (/ n repeats) (+ target delta))\n [n (.values bins)])))\n", "language": "Hy" }, { "code": "(for [f [\n (fn [] (randint 1 10))\n (fn [] (if (randint 0 1) (randint 1 9) (randint 1 10)))]]\n (print (uniform? f 5000 .02)))\n", "language": "Hy" }, { "code": "# rnd : a co-expression, which will generate the random numbers\n# n : the number of numbers to test\n# delta: tolerance in non-uniformity\n# This procedure fails if after the sampling the difference\n# in uniformity exceeds delta, a proportion of n / number-of-alternatives\nprocedure verify_uniform (rnd, n, delta)\n # generate a table counting the outcome of the generator\n results := table (0)\n every (1 to n) do results[@rnd] +:= 1\n # retrieve the statistics\n smallest := n\n largest := 0\n every num := key(results) do { # record result and limits\n write (num || \" \" || results[num])\n if results[num] < smallest then smallest := results[num]\n if results[num] > largest then largest := results[num]\n }\n # decide if difference is within bounds defined by delta\n return largest-smallest < delta * n / *results\nend\n\nprocedure main ()\n gen_1 := create (|?10) # uniform integers, 1 to 10\n if verify_uniform (gen_1, 1000000, 0.01)\n then write (\"uniform\")\n else write (\"skewed\")\n gen_2 := create (|(if ?2 = 1 then 6 else ?10)) # skewed integers, 1 to 10\n if verify_uniform (gen_2, 1000000, 0.01)\n then write (\"uniform\")\n else write (\"skewed\")\nend\n", "language": "Icon" }, { "code": "checkUniform=: adverb define\n 0.05 u checkUniform y\n :\n n=. */y\n delta=. x\n sample=. u n NB. the \"u\" refers to the verb to left of adverb\n freqtable=. /:~ (~. sample) ,. #/.~ sample\n expected=. n % # freqtable\n errmsg=. 'Distribution is potentially skewed'\n errmsg assert (delta * expected) > | expected - {:\"1 freqtable\n freqtable\n)\n", "language": "J" }, { "code": "checkUniformT=: adverb define\n 0.05 u checkUniformT y\n :\n freqtable=. /:~ (~. ,. #/.~) u n=. */y\n errmsg=. 'Distribution is potentially skewed'\n errmsg assert ((n % #) (x&*@[ > |@:-) {:\"1) freqtable\n freqtable\n)\n", "language": "J" }, { "code": " 0.05 rollD7t checkUniform 1e5\n1 14082\n2 14337\n3 14242\n4 14470\n5 14067\n6 14428\n7 14374\n 0.05 rollD7t checkUniform 1e2\n|Distribution is potentially skewed: assert\n| errmsg assert(delta*expected)>|expected-{:\"1 freqtable\n", "language": "J" }, { "code": "import static java.lang.Math.abs;\nimport java.util.*;\nimport java.util.function.IntSupplier;\n\npublic class Test {\n\n static void distCheck(IntSupplier f, int nRepeats, double delta) {\n Map<Integer, Integer> counts = new HashMap<>();\n\n for (int i = 0; i < nRepeats; i++)\n counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);\n\n double target = nRepeats / (double) counts.size();\n int deltaCount = (int) (delta / 100.0 * target);\n\n counts.forEach((k, v) -> {\n if (abs(target - v) >= deltaCount)\n System.out.printf(\"distribution potentially skewed \"\n + \"for '%s': '%d'%n\", k, v);\n });\n\n counts.keySet().stream().sorted().forEach(k\n -> System.out.printf(\"%d %d%n\", k, counts.get(k)));\n }\n\n public static void main(String[] a) {\n distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);\n }\n}\n", "language": "Java" }, { "code": "function distcheck(random_func, times, opts) {\n if (opts === undefined) opts = {}\n opts['delta'] = opts['delta'] || 2;\n\n var count = {}, vals = [];\n for (var i = 0; i < times; i++) {\n var val = random_func();\n if (! has_property(count, val)) {\n count[val] = 1;\n vals.push(val);\n }\n else\n count[val] ++;\n }\n vals.sort(function(a,b) {return a-b});\n\n var target = times / vals.length;\n var tolerance = target * opts['delta'] / 100;\n\n for (var i = 0; i < vals.length; i++) {\n var val = vals[i];\n if (Math.abs(count[val] - target) > tolerance)\n throw \"distribution potentially skewed for \" + val +\n \": expected result around \" + target + \", got \" +count[val];\n else\n print(val + \"\\t\" + count[val]);\n }\n}\n\nfunction has_property(obj, propname) {\n return typeof(obj[propname]) == \"undefined\" ? false : true;\n}\n\ntry {\n distcheck(function() {return Math.floor(10 * Math.random())}, 100000);\n print();\n distcheck(function() {return (Math.random() > 0.95 ? 1 : 0)}, 100000);\n} catch (e) {\n print(e);\n}\n", "language": "JavaScript" }, { "code": "using Printf\n\nfunction distcheck(f::Function, rep::Int=10000, Δ::Int=3)\n smpl = f(rep)\n counts = Dict(k => count(smpl .== k) for k in unique(smpl))\n expected = rep / length(counts)\n lbound = expected * (1 - 0.01Δ)\n ubound = expected * (1 + 0.01Δ)\n noobs = count(x -> !(lbound ≤ x ≤ ubound), values(counts))\n if noobs > 0 warn(@sprintf \"%2.4f%% values out of bounds\" noobs / rep) end\n return counts\nend\n\n# Dice5 check\ndistcheck(x -> rand(1:5, x))\n# Dice7 check\ndistcheck(dice7)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport java.util.Random\n\nval r = Random()\n\nfun dice5() = 1 + r.nextInt(5)\n\nfun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) {\n val occurs = mutableMapOf<Int, Int>()\n for (i in 1..nRepeats) {\n val d = gen()\n if (occurs.containsKey(d))\n occurs[d] = occurs[d]!! + 1\n else\n occurs.put(d, 1)\n }\n val expected = (nRepeats.toDouble()/ occurs.size).toInt()\n val maxError = (expected * tolerance / 100.0).toInt()\n println(\"Repetitions = $nRepeats, Expected = $expected\")\n println(\"Tolerance = $tolerance%, Max Error = $maxError\\n\")\n println(\"Integer Occurrences Error Acceptable\")\n val f = \" %d %5d %5d %s\"\n var allAcceptable = true\n for ((k,v) in occurs.toSortedMap()) {\n val error = Math.abs(v - expected)\n val acceptable = if (error <= maxError) \"Yes\" else \"No\"\n if (acceptable == \"No\") allAcceptable = false\n println(f.format(k, v, error, acceptable))\n }\n println(\"\\nAcceptable overall: ${if (allAcceptable) \"Yes\" else \"No\"}\")\n}\n\nfun main(args: Array<String>) {\n checkDist(::dice5, 1_000_000)\n println()\n checkDist(::dice5, 100_000)\n}\n", "language": "Kotlin" }, { "code": "n=1000\nprint \"Testing \";n;\" times\"\nif not(check(n, 0.05)) then print \"Test failed\" else print \"Test passed\"\nprint\n\nn=10000\nprint \"Testing \";n;\" times\"\nif not(check(n, 0.05)) then print \"Test failed\" else print \"Test passed\"\nprint\n\nn=50000\nprint \"Testing \";n;\" times\"\nif not(check(n, 0.05)) then print \"Test failed\" else print \"Test passed\"\nprint\n\nend\n\nfunction check(n, delta)\n 'fill randoms\n dim a(n)\n maxBucket=0\n minBucket=1e10\n for i = 1 to n\n a(i) = GENERATOR()\n if a(i)>maxBucket then maxBucket=a(i)\n if a(i)<minBucket then minBucket=a(i)\n next\n 'fill buckets\n nBuckets = maxBucket+1 'from 0\n dim buckets(maxBucket)\n for i = 1 to n\n buckets(a(i)) = buckets(a(i))+1\n next\n 'check buckets\n expected=n/(maxBucket-minBucket+1)\n minVal=int(expected*(1-delta))\n maxVal=int(expected*(1+delta))\n expected=int(expected)\n print \"minVal\", \"Expected\", \"maxVal\"\n print minVal, expected, maxVal\n print \"Bucket\", \"Counter\", \"pass/fail\"\n check = 1\n for i = minBucket to maxBucket\n print i, buckets(i), _\n iif$((minVal > buckets(i)) OR (buckets(i) > maxVal) ,\"fail\",\"\")\n if (minVal > buckets(i)) OR (buckets(i) > maxVal) then check = 0\n next\nend function\n\nfunction iif$(test, valYes$, valNo$)\n iif$ = valNo$\n if test then iif$ = valYes$\nend function\n\nfunction GENERATOR()\n 'GENERATOR = int(rnd(0)*10) '0..9\n GENERATOR = 1+int(rnd(0)*5) '1..5: dice5\nend function\n", "language": "Liberty-BASIC" }, { "code": "SetAttributes[CheckDistribution, HoldFirst]\nCheckDistribution[function_,number_,delta_] :=(Print[\"Expected: \", N[number/7], \", Generated :\",\nTranspose[Tally[Table[function, {number}]]][[2]] // Sort]; If[(Max[#]-Min[#])&\n [Transpose[Tally[Table[function, {number}]]][[2]]] < delta*number/700, \"Flat\", \"Skewed\"])\n", "language": "Mathematica" }, { "code": "import tables\n\n\nproc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =\n\n var counts: CountTable[int]\n for _ in 1..repeat:\n counts.inc f()\n\n let expected = (repeat / counts.len).toInt # Rounded to nearest.\n let allowedDelta = (expected.toFloat * tolerance / 100).toInt\n var maxDelta = 0\n for val, count in counts.pairs:\n let d = abs(count - expected)\n if d > maxDelta: maxDelta = d\n\n let status = if maxDelta <= allowedDelta: \"passed\" else: \"failed\"\n echo \"Checking \", repeat, \" values with a tolerance of \", tolerance, \"%.\"\n echo \"Random generator \", status, \" the uniformity test.\"\n echo \"Max delta encountered = \", maxDelta, \" Allowed delta = \", allowedDelta\n\n\nwhen isMainModule:\n import random\n randomize()\n proc rand5(): int = rand(1..5)\n checkDist(rand5, 1_000_000, 0.5)\n", "language": "Nim" }, { "code": "let distcheck fn n ?(delta=1.0) () =\n let h = Hashtbl.create 5 in\n for i = 1 to n do\n let v = fn() in\n let n =\n try Hashtbl.find h v\n with Not_found -> 0\n in\n Hashtbl.replace h v (n+1)\n done;\n Hashtbl.iter (fun v n -> Printf.printf \"%d => %d\\n%!\" v n) h;\n let target = (float n) /. float (Hashtbl.length h) in\n Hashtbl.iter (fun key value ->\n if abs_float(float value -. target) > 0.01 *. delta *. (float n)\n then (Printf.eprintf\n \"distribution potentially skewed for '%d': expected around %f, got %d\\n%!\"\n key target value)\n ) h;\n;;\n", "language": "OCaml" }, { "code": "dice5()=random(5)+1;\n\ndice7()={\n my(t);\n while((t=dice5()*5+dice5()) > 26,);\n t\\3-1\n};\n\ncumChi2(chi2,dof)={\n\tmy(g=gamma(dof/2));\n\tincgam(dof/2,chi2/2,g)/g\n};\n\ntest(f,n,alpha=.05)={\n\tv=vector(n,i,f());\n\tmy(s,ave,dof,chi2,p);\n\ts=sum(i=1,n,v[i],0.);\n\tave=s/n;\n\tdof=n-1;\n\tchi2=sum(i=1,n,(v[i]-ave)^2)/ave;\n\tp=cumChi2(chi2,dof);\n\tif(p<alpha,\n\t\terror(\"Not flat enough, significance only \"p)\n\t,\n\t\tprint(\"Flat with significance \"p);\n\t)\n};\n\ntest(dice7, 10^5)\ntest(()->if(random(1000),random(1000),1), 10^5)\n", "language": "PARI-GP" }, { "code": "sub roll7 { 1+int rand(7) }\nsub roll5 { 1+int rand(5) }\nsub roll7_5 {\n while(1) {\n my $d7 = (5*&roll5 + &roll5 - 6) % 8;\n return $d7 if $d7;\n }\n}\n\nmy $threshold = 5;\n\nprint dist( $_, $threshold, \\&roll7 ) for <1001 1000006>;\nprint dist( $_, $threshold, \\&roll7_5 ) for <1001 1000006>;\n\nsub dist {\nmy($n, $threshold, $producer) = @_;\n my @dist;\n my $result;\n my $expect = $n / 7;\n $result .= sprintf \"%10d expected\\n\", $expect;\n\n for (1..$n) { @dist[&$producer]++; }\n\n for my $i (1..7) {\n my $v = @dist[$i];\n my $pct = ($v - $expect)/$expect*100;\n $result .= sprintf \"%d %8d %6.1f%%%s\\n\", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : '');\n }\n return $result . \"\\n\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">range</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">iterations</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">delta</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- fid: routine_id of function that yields integer 1..range\n -- range: the maximum value that is returned from fid\n -- iterations: number of iterations to test\n -- delta: variance, for example 0.005 means 0.5%\n --\n -- returns -1/0/1 for impossible/not flat/flat.\n --</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">av</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">iterations</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">range</span> <span style=\"color: #000080;font-style:italic;\">-- average/expected value</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">av</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">av</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">delta</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">av</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #7060A8;\">ceil</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">av</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">av</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">delta</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">av</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #000080;font-style:italic;\">-- impossible</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">counts</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">range</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">iterations</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">fid</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">cdx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">max_delta</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">av</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">max_delta</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">delta</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">av</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">rand7</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">flats</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"impossible\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"not flat\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"flat\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">7</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- n = n+7-remainder(n,7)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">flat</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">check</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rand7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0.005</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d iterations: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">flats</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">flat</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(de checkDistribution (Cnt Pm . Prg)\n (let Res NIL\n (do Cnt (accu 'Res (run Prg 1) 1))\n (let\n (N (/ Cnt (length Res))\n Min (*/ N (- 1000 Pm) 1000)\n Max (*/ N (+ 1000 Pm) 1000) )\n (for R Res\n (prinl (cdr R) \" \" (if (>= Max (cdr R) Min) \"Good\" \"Bad\")) ) ) ) )\n", "language": "PicoLisp" }, { "code": "Prototype RandNum_prt()\n\nProcedure.s distcheck(*function.RandNum_prt, repetitions, delta.d)\n Protected text.s, maxIndex = 0\n Dim bucket(maxIndex) ;array will be resized as needed\n\n For i = 1 To repetitions ;populate buckets\n v = *function()\n If v > maxIndex\n maxIndex = v\n Redim bucket(maxIndex)\n EndIf\n bucket(v) + 1\n Next\n\n\n lbnd = Round((repetitions / maxIndex) * (100 - delta) / 100, #PB_Round_Up)\n ubnd = Round((repetitions / maxIndex) * (100 + delta) / 100, #PB_Round_Down)\n text = \"Distribution check:\" + #crlf$ + #crlf$\n text + \"Total elements = \" + Str(repetitions) + #crlf$ + #crlf$\n text + \"Margin = \" + StrF(delta, 2) + \"% --> Lbound = \" + Str(lbnd) + \", Ubound = \" + Str(ubnd) + #crlf$\n\n For i = 1 To maxIndex\n If bucket(i) < lbnd Or bucket(i) > ubnd\n text + #crlf$ + \"Bucket \" + Str(i) + \" contains \" + Str(bucket(i)) + \" elements. Skewed.\"\n EndIf\n Next\n ProcedureReturn text\nEndProcedure\n\nMessageRequester(\"Results\", distcheck(@dice7(), 1000000, 0.20))\n", "language": "PureBasic" }, { "code": "from collections import Counter\nfrom pprint import pprint as pp\n\ndef distcheck(fn, repeats, delta):\n '''\\\n Bin the answers to fn() and check bin counts are within +/- delta %\n of repeats/bincount'''\n bin = Counter(fn() for i in range(repeats))\n target = repeats // len(bin)\n deltacount = int(delta / 100. * target)\n assert all( abs(target - count) < deltacount\n for count in bin.values() ), \"Bin distribution skewed from %i +/- %i: %s\" % (\n target, deltacount, [ (key, target - count)\n for key, count in sorted(bin.items()) ]\n )\n pp(dict(bin))\n", "language": "Python" }, { "code": " [ stack [ 0 0 0 0 0 0 0 ] ] is bins ( --> s )\n\n [ 7 times\n [ 0 bins take\n i poke\n bins put ] ] is emptybins ( --> )\n\n [ bins share over peek\n 1+ bins take rot poke\n bins put ] is bincrement ( n --> )\n\n [ emptybins\n over 7 / temp put\n swap times\n [ over do 1 -\n bincrement ]\n bins share dup echo cr\n witheach\n [ temp share - abs\n over > if\n [ say \"Number of \"\n i^ 1+ echo\n say \"s is sketchy.\"\n cr ] ]\n 2drop temp release ] is distribution ( x n n --> )\n", "language": "Quackery" }, { "code": "distcheck <- function(fn, repetitions=1e4, delta=3)\n{\n if(is.character(fn))\n {\n fn <- get(fn)\n }\n if(!is.function(fn))\n {\n stop(\"fn is not a function\")\n }\n samp <- fn(n=repetitions)\n counts <- table(samp)\n expected <- repetitions/length(counts)\n lbound <- expected * (1 - 0.01*delta)\n ubound <- expected * (1 + 0.01*delta)\n status <- ifelse(counts < lbound, \"under\",\n ifelse(counts > ubound, \"over\", \"okay\"))\n data.frame(value=names(counts), counts=as.vector(counts), status=status)\n}\ndistcheck(dice7.vec)\n", "language": "R" }, { "code": "#lang racket\n(define (pretty-fraction f)\n (if (integer? f) f\n (let* ((d (denominator f)) (n (numerator f)) (q (quotient n d)) (r (remainder n d)))\n (format \"~a ~a\" q (/ r d)))))\n\n(define (test-uniformity/naive r n δ)\n (define observation (make-hash))\n (for ((_ (in-range n))) (hash-update! observation (r) add1 0))\n (define target (/ n (hash-count observation)))\n (define max-skew (* n δ 1/100))\n (define (skewed? v)\n (> (abs (- v target)) max-skew))\n (let/ec ek\n (cons\n #t\n (for/list ((k (sort (hash-keys observation) <)))\n (define v (hash-ref observation k))\n (when (skewed? v)\n (ek (cons\n #f\n (format \"~a distribution of ~s potentially skewed for ~a. expected ~a got ~a\"\n 'test-uniformity/naive r k (pretty-fraction target) v))))\n (cons k v)))))\n\n(define (straight-die)\n (min 6 (add1 (random 6))))\n\n(define (crooked-die)\n (min 6 (add1 (random 7))))\n\n; Test whether the builtin generator is uniform:\n(test-uniformity/naive (curry random 10) 1000 5)\n; Test whether a straight die is uniform:\n(test-uniformity/naive straight-die 1000 5)\n; Test whether a biased die fails:\n(test-uniformity/naive crooked-die 1000 5)\n", "language": "Racket" }, { "code": "my $d7 = 1..7;\nsub roll7 { $d7.roll };\n\nmy $threshold = 3;\n\nfor 14, 105, 1001, 10003, 100002, 1000006 -> $n\n { dist( $n, $threshold, &roll7 ) };\n\n\nsub dist ( $n is copy, $threshold, &producer ) {\n my @dist;\n my $expect = $n / 7;\n say \"Expect\\t\",$expect.fmt(\"%.3f\");\n\n loop ($_ = $n; $n; --$n) { @dist[&producer()]++; }\n\n for @dist.kv -> $i, $v is copy {\n next unless $i;\n $v //= 0;\n my $pct = ($v - $expect)/$expect*100;\n printf \"%d\\t%d\\t%+.2f%% %s\\n\", $i, $v, $pct,\n ($pct.abs > $threshold ?? '- skewed' !! '');\n }\n say '';\n}\n", "language": "Raku" }, { "code": "/*REXX program simulates a number of trials of a random digit and show it's skew %. */\nparse arg func times delta seed . /*obtain arguments (options) from C.L. */\nif func=='' | func==\",\" then func= 'RANDOM' /*function not specified? Use default.*/\nif times=='' | times==\",\" then times= 1000000 /*times \" \" \" \" */\nif delta=='' | delta==\",\" then delta= 1/2 /*delta% \" \" \" \" */\nif datatype(seed, 'W') then call random ,,seed /*use some RAND seed for repeatability.*/\nhighDig= 9 /*use this var for the highest digit. */\n!.= 0 /*initialize all possible random trials*/\n do times /* [↓] perform a bunch of trials. */\n if func=='RANDOM' then ?= random(highDig) /*use RANDOM function.*/\n else interpret '?=' func \"(0,\"highDig')' /* \" specified \" */\n !.?= !.? + 1 /*bump the invocation counter.*/\n end /*times*/ /* [↑] store trials ───► pigeonholes. */\n /* [↓] compute the digit's skewness. */\ng= times / (1 + highDig) /*calculate number of each digit throw.*/\nw= max(9, length( commas(times) ) ) /*maximum length of number of trials.*/\npad= left('', 9) /*this is used for output indentation. */\nsay pad 'digit' center(\" hits\", w) ' skew ' \"skew %\" 'result' /*header. */\nsay sep /*display a separator line. */\n /** [↑] show header and the separator.*/\n do k=0 to highDig /*process each of the possible digits. */\n skew= g - !.k /*calculate the skew for the digit. */\n skewPC= (1 - (g - abs(skew)) / g) * 100 /* \" \" \" percentage for dig*/\n say pad center(k, 5) right( commas(!.k), w) right(skew, 6) ,\n right( format(skewPC, , 3), 6) center( word('ok skewed', 1+(skewPC>delta)), 6)\n end /*k*/\nsay sep /*display a separator line. */\ny= 5+1+w+1+6+1+6+1+6 /*width + seps*/\nsay pad center(\" (with \" commas(times) ' trials)' , y) /*# trials. */\nsay pad center(\" (skewed when exceeds \" delta'%)' , y) /*skewed note.*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _\nsep: say pad '─────' center('', w, '─') '──────' \"──────\" '──────'; return\n", "language": "REXX" }, { "code": "# Project : Verify distribution uniformity/Naive\n\nmaxrnd = 7\nfor r = 2 to 5\n check = distcheck(pow(10,r), 0.05)\n see \"over \" + pow(10,r) + \" runs dice5 \" + nl\n if check\n see \"failed distribution check with \" + check + \" bin(s) out of range\" + nl\n else\n see \"passed distribution check\" + nl\n ok\nnext\n\nfunc distcheck(repet, delta)\nm = 1\ns = 0\nbins = list(maxrnd)\nfor i = 1 to repet\n r = dice5() + 1\n bins[r] = bins[r] + 1\n if r>m m = r ok\nnext\nfor i = 1 to m\n if bins[i]/(repet/m) > 1+delta s = s + 1 ok\n if bins[i]/(repet/m) < 1-delta s = s + 1 ok\nnext\nreturn s\n\nfunc dice5\n return random(5)\n", "language": "Ring" }, { "code": "def distcheck(n, delta=1)\n unless block_given?\n raise ArgumentError, \"pass a block to this method\"\n end\n\n h = Hash.new(0)\n n.times {h[ yield ] += 1}\n\n target = 1.0 * n / h.length\n h.each do |key, value|\n if (value - target).abs > 0.01 * delta * n\n raise StandardError,\n \"distribution potentially skewed for '#{key}': expected around #{target}, got #{value}\"\n end\n end\n\n puts h.sort.map{|k, v| \"#{k} #{v}\"}\nend\n\nif __FILE__ == $0\n begin\n distcheck(100_000) {rand(10)}\n distcheck(100_000) {rand > 0.95}\n rescue StandardError => e\n p e\n end\nend\n", "language": "Ruby" }, { "code": "s$ = \"#########################\"\ndim num(100)\nfor i = 1 to 1000\n n = (rnd(1) * 10) + 1\n num(n) = num(n) + 1\nnext i\n\nfor i = 1 to 10\n print using(\"###\",i);\" \"; using(\"#####\",num(i));\" \";left$(s$,num(i) / 5)\nnext i\n", "language": "Run-BASIC" }, { "code": "object DistrubCheck1 extends App {\n\n private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {\n val counts = scala.collection.mutable.Map[Int, Int]()\n\n for (_ <- 0 until nRepeats)\n counts.updateWith(f()) {\n case Some(count) => Some(count + 1)\n case None => Some(1)\n }\n\n val target: Double = nRepeats.toDouble / counts.size\n val deltaCount: Int = (delta / 100.0 * target).toInt\n counts.foreach {\n case (k, v) =>\n if (math.abs(target - v) >= deltaCount)\n println(f\"distribution potentially skewed for $k%s: $v%d\")\n }\n counts.toIndexedSeq.foreach(entry => println(f\"${entry._1}%d ${entry._2}%d\"))\n }\n\n distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)\n\n}\n", "language": "Scala" }, { "code": "object DistrubCheck2 extends App {\n private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = {\n val counts: Map[Int, Int] =\n (0 until nRepeats).map(_ => f()).groupBy(identity).map { case (k, v) => (k, v.size) }\n val target = nRepeats / counts.size.toDouble\n\n counts.withFilter { case (_, v) => math.abs(target - v) >= (delta / 100.0 * target) }\n .foreach { case (k, v) => println(f\"distribution potentially skewed for $k%s: $v%d\") }\n\n counts.toIndexedSeq.foreach(entry => println(f\"${entry._1}%d ${entry._2}%d\"))\n }\n\n distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 1)\n\n}\n", "language": "Scala" }, { "code": "proc distcheck {random times {delta 1}} {\n for {set i 0} {$i<$times} {incr i} {incr vals([uplevel 1 $random])}\n set target [expr {$times / [array size vals]}]\n foreach {k v} [array get vals] {\n if {abs($v - $target) > $times * $delta / 100.0} {\n error \"distribution potentially skewed for $k: expected around $target, got $v\"\n }\n }\n foreach k [lsort -integer [array names vals]] {lappend result $k $vals($k)}\n return $result\n}\n", "language": "Tcl" }, { "code": "# First, a uniformly distributed random variable\nputs [distcheck {expr {int(10*rand())}} 100000]\n\n# Now, one that definitely isn't!\nputs [distcheck {expr {rand()>0.95}} 100000]\n", "language": "Tcl" }, { "code": "import rand\nimport rand.seed\nimport math\n// \"given\"\nfn dice5() int {\n return rand.intn(5) or {0} + 1\n}\n\n// fntion specified by task \"Seven-sided dice from five-sided dice\"\nfn dice7() int {\n mut i := 0\n for {\n i = 5*dice5() + dice5()\n if i < 27 {\n break\n }\n }\n return (i / 3) - 1\n}\n\n// fntion specified by task \"Verify distribution uniformity/Naive\"\n//\n// Parameter \"f\" is expected to return a random integer in the range 1..n.\n// (Values out of range will cause an unceremonious crash.)\n// \"Max\" is returned as an \"indication of distribution achieved.\"\n// It is the maximum delta observed from the count representing a perfectly\n// uniform distribution.\n// Also returned is a boolean, true if \"max\" is less than threshold\n// parameter \"delta.\"\nfn dist_check(f fn() int, n int,\n repeats int, delta f64) (f64, bool) {\n mut max := 0.0\n mut count := []int{len: n}\n for _ in 0..repeats {\n count[f()-1]++\n }\n expected := f64(repeats) / f64(n)\n for c in count {\n max = math.max(max, math.abs(f64(c)-expected))\n }\n return max, max < delta\n}\n\n// Driver, produces output satisfying both tasks.\nfn main() {\n rand.seed(seed.time_seed_array(2))\n calls := 1000000\n mut max, mut flat_enough := dist_check(dice7, 7, calls, 500)\n println(\"Max delta: $max Flat enough: $flat_enough\")\n max, flat_enough = dist_check(dice7, 7, calls, 500)\n println(\"Max delta: $max Flat enough: $flat_enough\")\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nsub verifydistribution(calledfunction, samples, delta)\n\tDim i, n, maxdiff\n\t'We could cheat via Dim d(7), but \"7\" wasn't mentioned in the Task. Heh.\n\tDim d : Set d = CreateObject(\"Scripting.Dictionary\")\n\twscript.echo \"Running \"\"\" & calledfunction & \"\"\" \" & samples & \" times...\"\n\tfor i = 1 to samples\n\t\tExecute \"n = \" & calledfunction\n\t\td(n) = d(n) + 1\n\tnext\n\tn = d.Count\n\tmaxdiff = 0\n\twscript.echo \"Expected average count is \" & Int(samples/n) & \" across \" & n & \" buckets.\"\n\tfor each i in d.Keys\n\t\tdim diff : diff = abs(1 - d(i) / (samples/n))\n\t\tif diff > maxdiff then maxdiff = diff\n\t\twscript.echo \"Bucket \" & i & \" had \" & d(i) & \" occurences\" _\n\t\t& vbTab & \" difference from expected=\" & FormatPercent(diff, 2)\n\tnext\n\twscript.echo \"Maximum found variation is \" & FormatPercent(maxdiff, 2) _\n\t\t& \", desired limit is \" & FormatPercent(delta, 2) & \".\"\n\tif maxdiff > delta then wscript.echo \"Skewed!\" else wscript.echo \"Smooth!\"\nend sub\n", "language": "VBScript" }, { "code": "verifydistribution \"dice7\", 1000, 0.03\nverifydistribution \"dice7\", 100000, 0.03\n", "language": "VBScript" }, { "code": "import \"random\" for Random\nimport \"./fmt\" for Fmt\nimport \"./sort\" for Sort\n\nvar r = Random.new()\n\nvar dice5 = Fn.new { 1 + r.int(5) }\n\nvar checkDist = Fn.new { |gen, nRepeats, tolerance|\n var occurs = {}\n for (i in 1..nRepeats) {\n var d = gen.call()\n occurs[d] = occurs.containsKey(d) ? occurs[d] + 1 : 1\n }\n var expected = (nRepeats/occurs.count).floor\n var maxError = (expected*tolerance/100).floor\n System.print(\"Repetitions = %(nRepeats), Expected = %(expected)\")\n System.print(\"Tolerance = %(tolerance)\\%, Max Error = %(maxError)\\n\")\n System.print(\"Integer Occurrences Error Acceptable\")\n var f = \" $d $5d $5d $s\"\n var allAcceptable = true\n occurs = occurs.toList\n Sort.quick(occurs)\n for (me in occurs) {\n var error = (me.value - expected).abs\n var acceptable = (error <= maxError) ? \"Yes\" : \"No\"\n if (acceptable == \"No\") allAcceptable = false\n Fmt.print(f, me.key, me.value, error, acceptable)\n }\n System.print(\"\\nAcceptable overall: %(allAcceptable ? \"Yes\" : \"No\")\")\n}\n\ncheckDist.call(dice5, 1e6, 0.5)\nSystem.print()\ncheckDist.call(dice5, 1e5, 0.5)\n", "language": "Wren" }, { "code": "fcn rtest(N){\n dist:=L(0,0,0,0,0,0,0,0,0,0);\n do(N){n:=(0).random(10); dist[n]=dist[n]+1}\n sum:=dist.sum();\n dist=dist.apply('wrap(n){n.toFloat()/sum*100});\n if (dist.filter((10.0).closeTo.fp1(0.1)).len() == 10)\n { \"Good enough at %,d: %s\".fmt(N,dist).println(); return(True); }\n False\n}\n\nn:=10;\nwhile(not rtest(n)) {n*=2}\n", "language": "Zkl" } ]
Verify-distribution-uniformity-Naive
[ { "code": "---\ncategory:\n- String manipulation\nfrom: http://rosettacode.org/wiki/Vigenère_cipher\nnote: Encryption\n", "language": "00-META" }, { "code": ";Task:\nImplement a &nbsp; [[wp:Vigen%C3%A8re_cipher|Vigenère cypher]], &nbsp; both encryption and decryption. \n\nThe program should handle keys and text of unequal length, \nand should capitalize everything and discard non-alphabetic characters. <br>\n(If your program handles non-alphabetic characters in another way, \nmake a note of it.)\n\n\n;Related tasks:\n* &nbsp; [[Caesar cipher]]\n* &nbsp; [[Rot-13]]\n* &nbsp; [[Substitution Cipher]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F encrypt(key, text)\n V out = ‘’\n V j = 0\n L(c) text\n I !c.is_alpha()\n L.continue\n out ‘’= Char(code' (c.uppercase().code + key[j].code - 2 * ‘A’.code) % 26 + ‘A’.code)\n j = (j + 1) % key.len\n R out\n\nF decrypt(key, text)\n V out = ‘’\n V j = 0\n L(c) text\n I !c.is_alpha()\n L.continue\n out ‘’= Char(code' (c.code - key[j].code + 26) % 26 + ‘A’.code)\n j = (j + 1) % key.len\n R out\n\nV key = ‘VIGENERECIPHER’\nV original = ‘Beware the Jabberwock, my son! The jaws that bite, the claws that catch!’\nV encrypted = encrypt(key, original)\nV decrypted = decrypt(key, encrypted)\n\nprint(original)\nprint(‘Encrypted: ’encrypted)\nprint(‘Decrypted: ’decrypted)\n", "language": "11l" }, { "code": "PROC Fix(CHAR ARRAY in,fixed)\n INT i\n CHAR c\n\n fixed(0)=0\n FOR i=1 TO in(0)\n DO\n c=in(i)\n IF c>='a AND c<='z THEN\n c==-('a-'A)\n FI\n IF c>='A AND c<='Z THEN\n fixed(0)==+1\n fixed(fixed(0))=c\n FI\n OD\nRETURN\n\nPROC Process(CHAR ARRAY in,key,out INT dir)\n CHAR ARRAY inFixed(256),keyFixed(256)\n INT keyI,tmp,i\n CHAR c\n\n out(0)=0\n Fix(in,inFixed)\n Fix(key,keyFixed)\n IF inFixed(0)=0 OR keyFixed(0)=0 THEN\n RETURN\n FI\n\n keyI=1\n FOR i=1 TO inFixed(0)\n DO\n c=inFixed(i)\n tmp=c-'A+dir*(keyFixed(keyI)-'A)\n IF tmp<0 THEN\n tmp==+26\n FI\n out(0)==+1\n out(out(0))='A+tmp MOD 26\n keyI==+1\n IF keyI>keyFixed(0) THEN\n keyI=1\n FI\n OD\nRETURN\n\nPROC Encrypt(CHAR ARRAY in,key,out)\n Process(in,key,out,1)\nRETURN\n\nPROC Decrypt(CHAR ARRAY in,key,out)\n Process(in,key,out,-1)\nRETURN\n\nPROC Test(CHAR ARRAY in,key)\n CHAR ARRAY enc(256),dec(256)\n\n PrintE(\"Original:\") PrintE(in)\n Encrypt(in,key,enc)\n PrintF(\"Encrypted key=%S:%E\",key) PrintE(enc)\n Decrypt(enc,key,dec)\n PrintF(\"Decrypted key=%S:%E\",key) PrintE(dec)\n PutE()\nRETURN\n\nPROC Main()\n Test(\"Attack at dawn!\",\"LEMONLEMONLE\")\n\n Test(\"Crypto is short for cryptography.\",\"ABCDABCDABCDABCDABCDABCDABCD\")\nRETURN\n", "language": "Action-" }, { "code": "WITH Ada.Text_IO, Ada.Characters.Handling;\nUSE Ada.Text_IO, Ada.Characters.Handling;\n\nPROCEDURE Main IS\n SUBTYPE Alpha IS Character RANGE 'A' .. 'Z';\n TYPE Ring IS MOD (Alpha'Range_length);\n TYPE Seq IS ARRAY (Integer RANGE <>) OF Ring;\n\n FUNCTION \"+\" (S, Key : Seq) RETURN Seq IS\n R : Seq (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := S (I) + Key (Key'First + (I - R'First) MOD Key'Length);\n END LOOP;\n RETURN R;\n END \"+\";\n\n FUNCTION \"-\" (S : Seq) RETURN Seq IS\n R : Seq (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := - S (I);\n END LOOP;\n RETURN R;\n END \"-\";\n\n FUNCTION To_Seq (S : String) RETURN Seq IS\n R : Seq (S'Range);\n I : Integer := R'First;\n BEGIN\n FOR C OF To_Upper (S) LOOP\n IF C IN Alpha THEN\n R (I) := Ring'Mod (Alpha'Pos (C) - Alpha'Pos (Alpha'First));\n I := I + 1;\n END IF;\n END LOOP;\n RETURN R (R'First .. I - 1);\n END To_Seq;\n\n FUNCTION To_String (S : Seq ) RETURN String IS\n R : String (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := Alpha'Val ( Integer (S (I)) + Alpha'Pos (Alpha'First));\n END LOOP;\n RETURN R;\n END To_String;\n\n Input : Seq := To_Seq (Get_Line);\n Key : Seq := To_Seq (Get_Line);\n Crypt : Seq := Input + Key;\nBEGIN\n Put_Line (\"Encrypted: \" & To_String (Crypt));\n Put_Line (\"Decrypted: \" & To_String (Crypt + (-Key)));\nEND Main;\n", "language": "Ada" }, { "code": "STRING key := \"\";\n\nPROC vigenere cipher = (REF STRING key)VOID:\n(\n FOR i FROM LWB key TO UPB key DO\n IF key[i] >= \"A\" AND key[i] <= \"Z\" THEN\n key +:= key[i] FI;\n IF key[i] >= \"a\" AND key[i] <= \"z\" THEN\n key +:= REPR(ABS key[i] + ABS\"A\" - ABS\"a\") FI\n OD\n);\n\nPROC encrypt = (STRING text)STRING:\n(\n STRING out := \"\";\n\n INT j := LWB text;\n FOR i FROM LWB text TO UPB text DO\n CHAR c := text[i];\n\n IF c >= \"a\" AND c <= \"z\" THEN\n c := REPR(ABS c + (ABS\"A\" - ABS\"a\")) FI;\n IF c >= \"A\" AND c <= \"Z\" THEN\n out +:= REPR((ABS c + ABS key[j] - 2*ABS\"A\") MOD 26 + ABS\"A\");\n j := j MOD UPB key + 1\n FI\n OD;\n\n out\n);\n\nPROC decrypt = (STRING text)STRING:\n(\n STRING out;\n\n INT j := LWB text;\n FOR i FROM LWB text TO UPB text DO\n CHAR c := text[i];\n\n IF c >= \"a\" AND c <= \"z\" THEN\n c := REPR(ABS c + (ABS\"A\" - ABS\"a\")) FI;\n IF c >= \"A\" AND c <= \"Z\" THEN\n out +:= REPR((ABS c - ABS key[j] + 26) MOD 26 + ABS\"A\");\n j := j MOD UPB key + 1\n FI\n OD;\n\n out\n);\n\nmain:\n(\n vigenere cipher(key:=\"VIGENERECIPHER\");\n\n STRING original := \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n STRING encrypted := encrypt(original);\n STRING decrypted := decrypt(encrypted);\n\n print((original, new line));\n print((\"Encrypted: \", encrypted, new line));\n print((\"Decrypted: \", decrypted, new line))\n)\n", "language": "ALGOL-68" }, { "code": " 100 :\n 110 REM VIGENERE CIPHER\n 120 :\n 200 REM SET-UP\n 210 K$ = \"LEMON\": PRINT \"KEY: \"; K$\n 220 PT$ = \"ATTACK AT DAWN\": PRINT \"PLAIN TEXT: \";PT$\n 230 DEF FN MOD(A) = A - INT (A / 26) * 26\n 300 REM ENCODING\n 310 K = 1\n 320 FOR I = 1 TO LEN (PT$)\n 330 IF ASC ( MID$ (PT$,I,1)) < 65\n OR ASC ( MID$ (PT$,I,1)) > 90 THEN NEXT I\n 340 TV = ASC ( MID$ (PT$,I,1)) - 65\n 350 KV = ASC ( MID$ (K$,K,1)) - 65\n 360 CT$ = CT$ + CHR$ ( FN MOD(TV + KV) + 65)\n 370 K = K + 1: IF K > LEN (K$) THEN K = 1\n 380 NEXT I\n 390 PRINT \"CIPHER TEXT: \";CT$\n 400 REM DECODING\n 410 K = 1\n 420 FOR I = 1 TO LEN (CT$)\n 430 TV = ASC ( MID$ (CT$,I,1)) - 65\n 440 KV = ASC ( MID$ (K$,K,1)) - 65\n 450 T = TV - KV: IF T < 0 THEN T = T + 26\n 460 DT$ = DT$ + CHR$ (T + 65)\n 470 K = K + 1: IF K > LEN (K$) THEN K = 1\n 480 NEXT I\n 490 PRINT \"DECRYPTED TEXT: \";DT$\n", "language": "Applesoft-BASIC" }, { "code": "Letters: append `A`..`Z` `a`..`z`\nencrypt: function [msg, key][\n pos: 0\n result: new \"\"\n loop msg 'c ->\n if in? c Letters [\n 'result ++ to :char (((to :integer key\\[pos]) + to :integer upper c) % 26) + to :integer `A`\n pos: (pos + 1) % size key\n ]\n return result\n]\n\ndecrypt: function [msg, key][\n pos: 0\n result: new \"\"\n loop msg 'c [\n 'result ++ to :char ((26 + (to :integer c) - to :integer key\\[pos]) % 26) + to :integer `A`\n pos: (pos + 1) % size key\n ]\n return result\n]\n\ntext: \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey: \"VIGENERECIPHER\"\n\nencr: encrypt text key\ndecr: decrypt encr key\n\nprint text\nprint encr\nprint decr\n", "language": "Arturo" }, { "code": "Key = VIGENERECIPHER\nText= Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\n\nout := \"Input =\" text \"`nkey =\" key \"`nCiphertext =\" (c := VigenereCipher(Text, Key)) \"`nDecrypted =\" VigenereDecipher(c, key)\nMsgBox % clipboard := out\n\nVigenereCipher(Text, Key){\n StringUpper, Text, Text\n Text := RegExReplace(Text, \"[^A-Z]\")\n Loop Parse, Text\n {\n a := Asc(A_LoopField) - Asc(\"A\")\n b := Asc(SubStr(Key, 1+Mod(A_Index-1, StrLen(Key)), 1)) - Asc(\"A\")\n out .= Chr(Mod(a+b,26)+Asc(\"A\"))\n }\n return out\n}\n\nVigenereDecipher(Text, key){\n Loop Parse, key\n decoderKey .= Chr(26-(Asc(A_LoopField)-65)+65)\n return VigenereCipher(Text, decoderKey)\n}\n", "language": "AutoHotkey" }, { "code": "function Filtrar(cadorigen)\n\tfiltrado = \"\"\n\tfor i = 1 to length(cadorigen)\n\t\tletra = upper(mid(cadorigen, i, 1))\n\t\tif instr(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", letra) then filtrado += letra\n\tnext i\n\treturn filtrado\nend function\n\nfunction Encriptar(texto, llave)\n\ttexto = Filtrar(texto)\n\tcifrado = \"\"\n\tj = 1\n\tfor i = 1 to length(texto)\n\t\tmSS = mid(texto, i, 1)\n\t\tm = asc(mSS) - asc(\"A\")\n\t\tkSS = mid(llave, j, 1)\n\t\tk = asc(kSS) - asc(\"A\")\n\t\tj = (j mod length(llave)) + 1\n\t\tc = (m + k) mod 26\n\t\tletra = chr(asc(\"A\") + c)\n\t\tcifrado += letra\n\tnext i\n\treturn cifrado\nend function\n\nfunction DesEncriptar(texto, llave)\n\tdescifrado = \"\"\n\tj = 1\n\tfor i = 1 to length(texto)\n\t\tmSS = mid(texto, i, 1)\n\t\tm = asc(mSS) - asc(\"A\")\n\t\tkSS = mid(llave, j, 1)\n\t\tk = asc(kSS) - asc(\"A\")\n\t\tj = (j mod length(llave)) + 1\n\t\tc = (m - k + 26) mod 26\n\t\tletra = chr(asc(\"A\")+c)\n\t\tdescifrado += letra\n\tnext i\n\treturn descifrado\nend function\n\nllave = Filtrar(\"vigenerecipher\")\ncadorigen = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nprint cadorigen\nprint llave\n\ncadcifrada = Encriptar(cadorigen, llave)\nprint \" Cifrado: \"; cadcifrada\nprint \"Descifrado: \"; DesEncriptar(cadcifrada, llave)\nend\n", "language": "BASIC256" }, { "code": " key$ = \"LEMON\"\n plaintext$ = \"ATTACK AT DAWN\"\n ciphertext$ = FNencrypt(plaintext$, key$)\n PRINT \"Key = \"\"\" key$ \"\"\"\"\n PRINT \"Plaintext = \"\"\" plaintext$ \"\"\"\"\n PRINT \"Ciphertext = \"\"\" ciphertext$ \"\"\"\"\n PRINT \"Decrypted = \"\"\" FNdecrypt(ciphertext$, key$) \"\"\"\"\n END\n\n DEF FNencrypt(plain$, key$)\n LOCAL i%, k%, n%, o$\n plain$ = FNupper(plain$)\n key$ = FNupper(key$)\n FOR i% = 1 TO LEN(plain$)\n n% = ASCMID$(plain$, i%)\n IF n% >= 65 IF n% <= 90 THEN\n o$ += CHR$(65 + (n% + ASCMID$(key$, k%+1)) MOD 26)\n k% = (k% + 1) MOD LEN(key$)\n ENDIF\n NEXT\n = o$\n\n DEF FNdecrypt(cipher$, key$)\n LOCAL i%, k%, n%, o$\n cipher$ = FNupper(cipher$)\n key$ = FNupper(key$)\n FOR i% = 1 TO LEN(cipher$)\n n% = ASCMID$(cipher$, i%)\n o$ += CHR$(65 + (n% + 26 - ASCMID$(key$, k%+1)) MOD 26)\n k% = (k% + 1) MOD LEN(key$)\n NEXT\n = o$\n\n DEF FNupper(A$)\n LOCAL A%,C%\n FOR A% = 1 TO LEN(A$)\n C% = ASCMID$(A$,A%)\n IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)\n NEXT\n = A$\n", "language": "BBC-BASIC" }, { "code": "\"VIGENERECIPHER\">>>>1\\:!v>\"A\"-\\:00p0v\n>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\\+1g00p<\n\\\"{\"\\v>9+2*%\"A\"+^>$>~>:48*\\`#@_::\"`\"`\n*84*`<^4+\"4\"+g0\\_^#!+`*55\\`\\0::-\"A\"-*\n", "language": "Befunge" }, { "code": "\"VIGENERECIPHER\">>>>1\\:!v>\"A\"-\\:00p0v\n>>!#:0#-0#1g#,*#<+:v:-1$_^#!:\\+1g00p<\n\\\"{\"\\v>9+2*%\"A\"+^>$>~>:48*\\`#@_::\"`\"`\n*84*`<^4+\"4\"-g0\\_^#!+`*55\\`\\0::-\"A\"-*\n", "language": "Befunge" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <ctype.h>\n#include <getopt.h>\n\n#define NUMLETTERS 26\n#define BUFSIZE 4096\n\nchar *get_input(void);\n\nint main(int argc, char *argv[])\n{\n char const usage[] = \"Usage: vinigere [-d] key\";\n char sign = 1;\n char const plainmsg[] = \"Plain text: \";\n char const cryptmsg[] = \"Cipher text: \";\n bool encrypt = true;\n int opt;\n\n while ((opt = getopt(argc, argv, \"d\")) != -1) {\n switch (opt) {\n case 'd':\n sign = -1;\n encrypt = false;\n break;\n default:\n fprintf(stderr, \"Unrecogized command line argument:'-%i'\\n\", opt);\n fprintf(stderr, \"\\n%s\\n\", usage);\n return 1;\n }\n }\n\n if (argc - optind != 1) {\n fprintf(stderr, \"%s requires one argument and one only\\n\", argv[0]);\n fprintf(stderr, \"\\n%s\\n\", usage);\n return 1;\n }\n\n\n // Convert argument into array of shifts\n char const *const restrict key = argv[optind];\n size_t const keylen = strlen(key);\n char shifts[keylen];\n\n char const *restrict plaintext = NULL;\n for (size_t i = 0; i < keylen; i++) {\n if (!(isalpha(key[i]))) {\n fprintf(stderr, \"Invalid key\\n\");\n return 2;\n }\n char const charcase = (isupper(key[i])) ? 'A' : 'a';\n // If decrypting, shifts will be negative.\n // This line would turn \"bacon\" into {1, 0, 2, 14, 13}\n shifts[i] = (key[i] - charcase) * sign;\n }\n\n do {\n fflush(stdout);\n // Print \"Plain text: \" if encrypting and \"Cipher text: \" if\n // decrypting\n printf(\"%s\", (encrypt) ? plainmsg : cryptmsg);\n plaintext = get_input();\n if (plaintext == NULL) {\n fprintf(stderr, \"Error getting input\\n\");\n return 4;\n }\n } while (strcmp(plaintext, \"\") == 0); // Reprompt if entry is empty\n\n size_t const plainlen = strlen(plaintext);\n\n char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext);\n if (ciphertext == NULL) {\n fprintf(stderr, \"Memory error\\n\");\n return 5;\n }\n\n for (size_t i = 0, j = 0; i < plainlen; i++) {\n // Skip non-alphabetical characters\n if (!(isalpha(plaintext[i]))) {\n ciphertext[i] = plaintext[i];\n continue;\n }\n // Check case\n char const charcase = (isupper(plaintext[i])) ? 'A' : 'a';\n // Wrapping conversion algorithm\n ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase;\n j = (j+1) % keylen;\n }\n ciphertext[plainlen] = '\\0';\n printf(\"%s%s\\n\", (encrypt) ? cryptmsg : plainmsg, ciphertext);\n\n free(ciphertext);\n // Silence warnings about const not being maintained in cast to void*\n free((char*) plaintext);\n return 0;\n}\nchar *get_input(void) {\n\n char *const restrict buf = malloc(BUFSIZE * sizeof (char));\n if (buf == NULL) {\n return NULL;\n }\n\n fgets(buf, BUFSIZE, stdin);\n\n // Get rid of newline\n size_t const len = strlen(buf);\n if (buf[len - 1] == '\\n') buf[len - 1] = '\\0';\n\n return buf;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\nusing namespace std;\n\nclass Vigenere\n{\npublic:\n string key;\n\n Vigenere(string key)\n {\n for(int i = 0; i < key.size(); ++i)\n {\n if(key[i] >= 'A' && key[i] <= 'Z')\n this->key += key[i];\n else if(key[i] >= 'a' && key[i] <= 'z')\n this->key += key[i] + 'A' - 'a';\n }\n }\n\n string encrypt(string text)\n {\n string out;\n\n for(int i = 0, j = 0; i < text.length(); ++i)\n {\n char c = text[i];\n\n if(c >= 'a' && c <= 'z')\n c += 'A' - 'a';\n else if(c < 'A' || c > 'Z')\n continue;\n\n out += (c + key[j] - 2*'A') % 26 + 'A';\n j = (j + 1) % key.length();\n }\n\n return out;\n }\n\n string decrypt(string text)\n {\n string out;\n\n for(int i = 0, j = 0; i < text.length(); ++i)\n {\n char c = text[i];\n\n if(c >= 'a' && c <= 'z')\n c += 'A' - 'a';\n else if(c < 'A' || c > 'Z')\n continue;\n\n out += (c - key[j] + 26) % 26 + 'A';\n j = (j + 1) % key.length();\n }\n\n return out;\n }\n};\n\nint main()\n{\n Vigenere cipher(\"VIGENERECIPHER\");\n\n string original = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n string encrypted = cipher.encrypt(original);\n string decrypted = cipher.decrypt(encrypted);\n\n cout << original << endl;\n cout << \"Encrypted: \" << encrypted << endl;\n cout << \"Decrypted: \" << decrypted << endl;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace VigenereCipher\n{\n class VCipher\n {\n public string encrypt(string txt, string pw, int d)\n {\n int pwi = 0, tmp;\n string ns = \"\";\n txt = txt.ToUpper();\n pw = pw.ToUpper();\n foreach (char t in txt)\n {\n if (t < 65) continue;\n tmp = t - 65 + d * (pw[pwi] - 65);\n if (tmp < 0) tmp += 26;\n ns += Convert.ToChar(65 + ( tmp % 26) );\n if (++pwi == pw.Length) pwi = 0;\n }\n\n return ns;\n }\n };\n\n class Program\n {\n static void Main(string[] args)\n {\n VCipher v = new VCipher();\n\n string s0 = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\",\n pw = \"VIGENERECIPHER\";\n\n Console.WriteLine(s0 + \"\\n\" + pw + \"\\n\");\n string s1 = v.encrypt(s0, pw, 1);\n Console.WriteLine(\"Encrypted: \" + s1);\n s1 = v.encrypt(s1, \"VIGENERECIPHER\", -1);\n Console.WriteLine(\"Decrypted: \" + s1);\n Console.WriteLine(\"\\nPress any key to continue...\");\n Console.ReadKey();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "shared void run() {\n\n function normalize(String text) => text.uppercased.filter(Character.letter);\n\n function crypt(String text, String key, Character(Character, Character) transform) => String {\n for ([a, b] in zipPairs(normalize(text), normalize(key).cycled))\n transform(a, b)\n };\n\n function encrypt(String clearText, String key) =>\n crypt(clearText, key, (Character a, Character b) =>\n\t\t\t\t('A'.integer + ((a.integer + b.integer - 130) % 26)).character);\n\n function decrypt(String cipherText, String key) =>\n crypt(cipherText, key, (Character a, Character b) =>\n \t\t('A'.integer + ((a.integer - b.integer + 26) % 26)).character);\n\n value key = \"VIGENERECIPHER\";\n value message = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n value encrypted = encrypt(message, key);\n value decrypted = decrypt(encrypted, key);\n\n print(encrypted);\n print(decrypted);\n}\n", "language": "Ceylon" }, { "code": "(ns org.rosettacode.clojure.vigenere\n (:require [clojure.string :as string]))\n\n; convert letter to offset from \\A\n(defn to-num [char] (- (int char) (int \\A)))\n\n; convert number to letter, treating it as modulo 26 offset from \\A\n(defn from-num [num] (char (+ (mod num 26) (int \\A))))\n\n; Convert a string to a sequence of just the letters as uppercase chars\n(defn to-normalized-seq [str]\n (map #'first (re-seq #\"[A-Z]\" (string/upper-case str))))\n\n; add (op=+) or subtract (op=-) the numerical value of the key letter from the\n; text letter.\n(defn crypt1 [op text key]\n (from-num (apply op (list (to-num text) (to-num key)))))\n\n(defn crypt [op text key]\n (let [xcrypt1 (partial #'crypt1 op)]\n (apply #'str\n (map xcrypt1 (to-normalized-seq text)\n (cycle (to-normalized-seq key))))))\n\n; encipher a text\n(defn encrypt [plaintext key] (crypt #'+ plaintext key))\n\n; decipher a text\n(defn decrypt [ciphertext key] (crypt #'- ciphertext key))\n", "language": "Clojure" }, { "code": "(ns org.rosettacode.clojure.test-vigenere\n (:require [org.rosettacode.clojure.vigenere :as vigenere]))\n\n(let\n [ plaintext \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n key \"Vigenere cipher\"\n ciphertext (vigenere/encrypt plaintext key)\n recovered (vigenere/decrypt ciphertext key) ]\n\n (doall (map (fn [[k v]] (printf \"%9s: %s\\n\" k v))\n [ [\"Original\" plaintext] [\"Key\" key] [\"Encrypted\" ciphertext] [\"Decrypted\" recovered] ])))\n", "language": "Clojure" }, { "code": "# Simple helper since charCodeAt is quite long to write.\ncode = (char) -> char.charCodeAt()\n\nencrypt = (text, key) ->\n\tres = []\n\tj = 0\n\t\n\tfor c in text.toUpperCase()\n\t\tcontinue if c < 'A' or c > 'Z'\n\t\t\n\t\tres.push ((code c) + (code key[j]) - 130) % 26 + 65\n\t\tj = ++j % key.length\n\t\n\tString.fromCharCode res...\n\ndecrypt = (text, key) ->\n\tres = []\n\tj = 0\n\t\n\tfor c in text.toUpperCase()\n\t\tcontinue if c < 'A' or c > 'Z'\n\t\t\n\t\tres.push ((code c) - (code key[j]) + 26) % 26 + 65\n\t\tj = ++j % key.length\n\t\n\tString.fromCharCode res...\n\n# Trying it out\nkey = \"VIGENERECIPHER\"\noriginal = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nencrypted = encrypt original, key\n\nconsole.log \"Original : #{original}\"\nconsole.log \"Encrypted : #{encrypted}\"\nconsole.log \"Decrypted : #{decrypt encrypted, key}\"\n", "language": "CoffeeScript" }, { "code": "(defun strip (s)\n (remove-if-not\n (lambda (c) (char<= #\\A c #\\Z))\n (string-upcase s)))\n\n(defun vigenère (s key &key decipher\n\t\t\t&aux (A (char-code #\\A))\n\t\t\t (op (if decipher #'- #'+)))\n (labels\n ((to-char (c) (code-char (+ c A)))\n (to-code (c) (- (char-code c) A)))\n (let ((k (map 'list #'to-code (strip key))))\n (setf (cdr (last k)) k)\n (map 'string\n\t (lambda (c)\n\t (prog1\n\t (to-char\n\t\t (mod (funcall op (to-code c) (car k)) 26))\n\t (setf k (cdr k))))\n\t (strip s)))))\n\n(let* ((msg \"Beware the Jabberwock... The jaws that... the claws that catch!\")\n (key \"vigenere cipher\")\n (enc (vigenère msg key))\n (dec (vigenère enc key :decipher t)))\n (format t \"msg: ~a~%enc: ~a~%dec: ~a~%\" msg enc dec))\n", "language": "Common-Lisp" }, { "code": "(defconstant +a+ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\n(defun strip (s)\n (string-upcase (remove-if-not 'alpha-char-p s)))\n\n(defun vigenere (txt key &key plain &aux (p (if plain -1 1)))\n (let ((txt (strip txt)) (key (strip key)) (i -1))\n (map 'string\n (lambda (c)\n (setf i (mod (1+ i) (length key)))\n (char +a+ (mod (+ (position c +a+) (* p (position (elt key i) +a+))) 26)))\n txt)))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.string;\n\nstring encrypt(in string txt, in string key) pure @safe\nin {\n assert(key.removechars(\"^A-Z\") == key);\n} body {\n string res;\n foreach (immutable i, immutable c; txt.toUpper.removechars(\"^A-Z\"))\n res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';\n return res;\n}\n\nstring decrypt(in string txt, in string key) pure @safe\nin {\n assert(key.removechars(\"^A-Z\") == key);\n} body {\n string res;\n foreach (immutable i, immutable c; txt.toUpper.removechars(\"^A-Z\"))\n res ~= (c - key[i % $] + 26) % 26 + 'A';\n return res;\n}\n\nvoid main() {\n immutable key = \"VIGENERECIPHER\";\n immutable original = \"Beware the Jabberwock, my son!\" ~\n \" The jaws that bite, the claws that catch!\";\n immutable encoded = original.encrypt(key);\n writeln(encoded, \"\\n\", encoded.decrypt(key));\n}\n", "language": "D" }, { "code": "import std.stdio, std.range, std.ascii, std.string, std.algorithm,\n std.conv;\n\nimmutable mod = (in int m, in int n) pure nothrow @safe @nogc =>\n ((m % n) + n) % n;\n\nimmutable _s2v = (in string s) pure /*nothrow*/ @safe =>\n s.toUpper.removechars(\"^A-Z\").map!q{ a - 'A' };\n\nstring _v2s(R)(R v) pure /*nothrow*/ @safe {\n return v.map!(x => uppercase[x.mod(26)]).text;\n}\n\nimmutable encrypt = (in string txt, in string key) pure /*nothrow*/ @safe =>\n txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;\n\nimmutable decrypt = (in string txt, in string key) pure /*nothrow*/ @safe =>\n txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;\n\nvoid main() {\n immutable key = \"Vigenere Cipher!!!\";\n immutable original = \"Beware the Jabberwock, my son!\" ~\n \" The jaws that bite, the claws that catch!\";\n immutable encoded = original.encrypt(key);\n writeln(encoded, \"\\n\", encoded.decrypt(key));\n}\n", "language": "D" }, { "code": "function UpperAlphaOnly(S: string): string;\n{Remove all }\nvar I: integer;\nbegin\nResult:='';\nS:=UpperCase(S);\nfor I:=1 to Length(S) do\nif S[I] in ['A'..'Z'] then Result:=Result+S[I];\nend;\n\n\nfunction VigenereEncrypt(Text, Key: string): string;\n{Encrypt Text using specified key}\nvar KInx,TInx,I: integer;\nvar TC: byte;\nbegin\nResult:='';\n{Force Text and Key upper case}\nText:=UpperAlphaOnly(Text);\nKey:=UpperAlphaOnly(Key);\n{Point to first Key-character}\nKInx:=1;\nfor I:=1 to Length(Text) do\n\tbegin\n\t{Offset Text-char by key-char amount}\n\tTC:=byte(Text[I])-byte('A')+Byte(Key[KInx]);\n\t{if it is shifted past \"Z\", wrap back around past \"A\"}\n\tif TC>Byte('Z') then TC:=byte('@')+(TC-Byte('Z'));\n\t{Store in output string}\n\tResult:=Result+Char(TC);\n\t{Point to next Key-char}\n\tInc(Kinx);\n\t{If index post end of key, start over}\n\tif KInx>Length(Key) then KInx:=1;\n\tend;\nend;\n\n\nfunction VigenereDecrypt(Text, Key: string): string;\n{Encrypt Text using specified key}\nvar KInx,TInx,I: integer;\nvar TC: byte;\nbegin\nResult:='';\n{For Key and text uppercase}\nText:=UpperAlphaOnly(Text);\nKey:=UpperAlphaOnly(Key);\nKInx:=1;\nfor I:=1 to Length(Text) do\n\tbegin\n\t{subtrack key-char from text-char}\n\tTC:=byte(Text[I])-Byte(Key[Kinx])+Byte('A');\n\t{if result below \"A\" wrap back around to \"Z\"}\n\tif TC<Byte('A') then TC:=(byte('Z')-((Byte('A')-TC)))+1;\n\t{store in result}\n\tResult:=Result+Char(TC);\n\t{Point to next key char}\n\tInc(Kinx);\n\t{Past the end, start over}\n\tif KInx>Length(Key) then KInx:=1;\n\tend;\nend;\n\nconst TestKey = 'VIGENERECIPHER';\nconst TestStr = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!';\n\n\nprocedure VigenereCipher(Memo: TMemo);\nvar S: string;\nbegin\n{Show plain text}\nMemo.Lines.Add(TestStr);\nS:=VigenereEncrypt(TestStr, TestKey);\n{Show encrypted text}\nMemo.Lines.Add(S);\nS:=VigenereDecrypt(S, TestKey);\n{Show decrypted text}\nMemo.Lines.Add(S);\nend;\n", "language": "Delphi" }, { "code": "func$ encr txt$ pw$ d .\n txt$[] = strchars txt$\n for c$ in strchars pw$\n pw[] &= strcode c$ - 65\n .\n for c$ in txt$[]\n c = strcode c$\n if c >= 97\n c -= 32\n .\n if c >= 65 and c <= 97\n pwi = (pwi + 1) mod1 len pw[]\n c = (c - 65 + d * pw[pwi]) mod 26 + 65\n r$ &= strchar c\n .\n .\n return r$\n.\ns$ = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\npw$ = \"VIGENERECIPHER\"\nr$ = encr s$ pw$ 1\nprint r$\nprint encr r$ pw$ -1\n", "language": "EasyLang" }, { "code": "import system'text;\nimport system'culture;\nimport system'math;\nimport system'routines;\nimport extensions;\n\nclass VCipher\n{\n string encrypt(string txt, string pw, int d)\n {\n auto output := new TextBuilder();\n int pwi := 0;\n\n string PW := pw.toUpper();\n var TXT := txt.toUpper();\n\n foreach(char t; in TXT)\n {\n if (t < $65) $continue;\n\n int tmp := t - 65 + d * (pw[pwi] - 65);\n if (tmp < 0) tmp += 26;\n output.write((65 + tmp.mod(26)).toChar());\n pwi++;\n if (pwi == PW.Length) { pwi := 0 }\n };\n\n ^ output.Value\n }\n}\n\npublic program()\n{\n var v := new VCipher();\n\n var s0 := \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n var pw := \"VIGENERECIPHER\";\n\n console.printLine(s0,newLineConstant,pw,newLineConstant);\n var s1 := v.encrypt(s0, pw, 1);\n console.printLine(\"Encrypted:\",s1);\n s1 := v.encrypt(s1, \"VIGENERECIPHER\", -1);\n console.printLine(\"Decrypted:\",s1);\n console.printLine(\"Press any key to continue..\");\n console.readChar()\n}\n", "language": "Elena" }, { "code": "defmodule VigenereCipher do\n @base ?A\n @size ?Z - @base + 1\n\n def encrypt(text, key), do: crypt(text, key, 1)\n\n def decrypt(text, key), do: crypt(text, key, -1)\n\n defp crypt(text, key, dir) do\n text = String.upcase(text) |> String.replace(~r/[^A-Z]/, \"\") |> to_char_list\n key_iterator = String.upcase(key) |> String.replace(~r/[^A-Z]/, \"\") |> to_char_list\n |> Enum.map(fn c -> (c - @base) * dir end) |> Stream.cycle\n Enum.zip(text, key_iterator)\n |> Enum.reduce('', fn {char, offset}, ciphertext ->\n [rem(char - @base + offset + @size, @size) + @base | ciphertext]\n end)\n |> Enum.reverse |> List.to_string\n end\nend\n\nplaintext = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey = \"Vigenere cipher\"\nciphertext = VigenereCipher.encrypt(plaintext, key)\nrecovered = VigenereCipher.decrypt(ciphertext, key)\n\nIO.puts \"Original: #{plaintext}\"\nIO.puts \"Encrypted: #{ciphertext}\"\nIO.puts \"Decrypted: #{recovered}\"\n", "language": "Elixir" }, { "code": "% Erlang implementation of Vigenère cipher\n-module(vigenere).\n-export([encrypt/2, decrypt/2]).\n-import(lists, [append/2, filter/2, map/2, zipwith/3]).\n\n% Utility functions for character tests and conversions\nisupper([C|_]) -> isupper(C);\nisupper(C) -> (C >= $A) and (C =< $Z).\n\nislower([C|_]) -> islower(C);\nislower(C) -> (C >= $a) and (C =< $z).\n\nisalpha([C|_]) -> isalpha(C);\nisalpha(C) -> isupper(C) or islower(C).\n\ntoupper(S) when is_list(S) -> lists:map(fun toupper/1, S);\ntoupper(C) when (C >= $a) and (C =< $z) -> C - $a + $A;\ntoupper(C) -> C.\n\n% modulo function that normalizes into positive range for positive divisor\nmod(X,Y) -> (X rem Y + Y) rem Y.\n\n% convert letter to position in alphabet (A=0,B=1,...,Y=24,Z=25).\nto_pos(L) when L >= $A, L =< $Z -> L - $A.\n\n% convert position in alphabet back to letter\nfrom_pos(N) -> mod(N, 26) + $A.\n\n% encode the given letter given the single-letter key\nencipher(P, K) -> from_pos(to_pos(P) + to_pos(K)).\n\n% decode the given letter given the single-letter key\ndecipher(C, K) -> from_pos(to_pos(C) - to_pos(K)).\n\n% extend a list by repeating it until it is at least N elements long\ncycle_to(N, List) when length(List) >= N -> List;\ncycle_to(N, List) -> append(List, cycle_to(N-length(List), List)).\n\n% Encryption prep: reduce string to only its letters, in uppercase\nnormalize(Str) -> toupper(filter(fun isalpha/1, Str)).\n\ncrypt(RawText, RawKey, Func) ->\n PlainText = normalize(RawText),\n zipwith(Func, PlainText, cycle_to(length(PlainText), normalize(RawKey))).\n\nencrypt(Text, Key) -> crypt(Text, Key, fun encipher/2).\ndecrypt(Text, Key) -> crypt(Text, Key, fun decipher/2).\n", "language": "Erlang" }, { "code": "-module(testvigenere).\n-import(vigenere,[encrypt/2, decrypt/2]).\nmain(_) ->\n Key = \"Vigenere cipher\",\n CipherText = encrypt(\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", Key),\n RecoveredText = decrypt(CipherText, Key),\n io:fwrite(\"Ciphertext: ~s~nDecrypted: ~s~n\", [CipherText, RecoveredText]).\n", "language": "Erlang" }, { "code": "module vigenere =\n let keyschedule (key:string) =\n let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter\n let l = Array.length s\n (fun n -> int s.[n % l])\n\n let enc k c = ((c + k - 130) % 26) + 65\n let dec k c = ((c - k + 130) % 26) + 65\n let crypt f key = Array.mapi (fun n c -> f (key n) c |> char)\n\n let encrypt key (plaintext:string) =\n plaintext.ToUpper().ToCharArray()\n |> Array.filter System.Char.IsLetter\n |> Array.map int\n |> crypt enc (keyschedule key)\n |> (fun a -> new string(a))\n\n let decrypt key (ciphertext:string) =\n ciphertext.ToUpper().ToCharArray()\n |> Array.map int\n |> crypt dec (keyschedule key)\n |> (fun a -> new string(a))\n\nlet passwd = \"Vigenere Cipher\"\nlet cipher = vigenere.encrypt passwd \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nlet plain = vigenere.decrypt passwd cipher\nprintfn \"%s\\n%s\" cipher plain\n", "language": "F-Sharp" }, { "code": "USING: arrays ascii formatting kernel math math.functions\nmath.order sequences ;\nIN: rosetta-code.vigenere-cipher\n\n: mult-pad ( key input -- x )\n [ length ] bi@ 2dup < [ swap ] when / ceiling ;\n\n: lengthen-pad ( key input -- rep-key input )\n [ mult-pad ] 2keep [ <repetition> concat ] dip\n [ length ] keep [ head ] dip ;\n\n: normalize ( str -- only-upper-letters )\n >upper [ LETTER? ] filter ;\n\n: vigenere-encrypt ( key input -- ecrypted )\n [ normalize ] bi@ lengthen-pad\n [ [ CHAR: A - ] map ] bi@ [ + 26 mod CHAR: A + ] 2map ;\n\n: vigenere-decrypt ( key input -- decrypted )\n [ normalize ] bi@ lengthen-pad [ [ CHAR: A - ] map ] bi@\n [ - 26 - abs 26 mod CHAR: A + ] 2map ;\n\n: main ( -- )\n \"Vigenere cipher\" dup\n \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n 2dup \"Key: %s\\nInput: %s\\n\" printf\n vigenere-encrypt dup \"Encrypted: %s\\n\" printf\n vigenere-decrypt \"Decrypted: %s\\n\" printf ;\n\nMAIN: main\n", "language": "Factor" }, { "code": "program vigenere_cipher\n implicit none\n\n character(80) :: plaintext = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", &\n ciphertext = \"\"\n character(14) :: key = \"VIGENERECIPHER\"\n\n\n call encrypt(plaintext, ciphertext, key)\n write(*,*) plaintext\n write(*,*) ciphertext\n call decrypt(ciphertext, plaintext, key)\n write(*,*) plaintext\n\ncontains\n\nsubroutine encrypt(intxt, outtxt, k)\n character(*), intent(in) :: intxt, k\n character(*), intent(out) :: outtxt\n integer :: chrn\n integer :: cp = 1, kp = 1\n integer :: i\n\n outtxt = \"\"\n do i = 1, len(trim(intxt))\n select case(intxt(i:i))\n case (\"A\":\"Z\", \"a\":\"z\")\n select case(intxt(i:i))\n case(\"a\":\"z\")\n chrn = iachar(intxt(i:i)) - 32\n\n case default\n chrn = iachar(intxt(i:i))\n\n end select\n\n outtxt(cp:cp) = achar(modulo(chrn + iachar(k(kp:kp)), 26) + 65)\n cp = cp + 1\n kp = kp + 1\n if(kp > len(k)) kp = kp - len(k)\n\n end select\n end do\nend subroutine\n\nsubroutine decrypt(intxt, outtxt, k)\n character(*), intent(in) :: intxt, k\n character(*), intent(out) :: outtxt\n integer :: chrn\n integer :: cp = 1, kp = 1\n integer :: i\n\n outtxt = \"\"\n do i = 1, len(trim(intxt))\n chrn = iachar(intxt(i:i))\n outtxt(cp:cp) = achar(modulo(chrn - iachar(k(kp:kp)), 26) + 65)\n cp = cp + 1\n kp = kp + 1\n if(kp > len(k)) kp = kp - len(k)\n end do\nend subroutine\nend program\n", "language": "Fortran" }, { "code": "Function Filtrar(cadorigen As String) As String\n Dim As String letra\n Dim As String filtrado = \"\"\n For i As Integer = 1 To Len(cadorigen)\n letra = Ucase(Mid(cadorigen, i, 1))\n If Instr(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", letra) Then filtrado += letra\n Next i\n Return filtrado\nEnd Function\n\nFunction Encriptar(texto As String, llave As String) As String\n texto = Filtrar(texto)\n Dim As String mSS, kSS, letra, cifrado = \"\"\n Dim As Integer m, k, c, j = 1\n For i As Integer = 1 To Len(texto)\n mSS = Mid(texto, i, 1)\n m = Asc(mSS) - Asc(\"A\")\n kSS = Mid(llave, j, 1)\n k = Asc(kSS) - Asc(\"A\")\n j = (j Mod Len(llave)) + 1\n c = (m + k) Mod 26\n letra = Chr(Asc(\"A\") + c)\n cifrado += letra\n Next i\n Return cifrado\nEnd Function\n\nFunction DesEncriptar(texto As String, llave As String) As String\n Dim As String mSS, kSS, letra, descifrado = \"\"\n Dim As Integer m, k, c, j = 1\n For i As Integer = 1 To Len(texto)\n mSS = Mid(texto, i, 1)\n m = Asc(mSS) - Asc(\"A\")\n kSS = Mid(llave, j, 1)\n k = Asc(kSS) - Asc(\"A\")\n j = (j Mod Len(llave)) + 1\n c = (m - k + 26) Mod 26\n letra = Chr(Asc(\"A\")+c)\n descifrado += letra\n Next i\n Return descifrado\nEnd Function\n\nDim Shared As String llave\nllave = Filtrar(\"vigenerecipher\")\n\nDim As String cadorigen = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nPrint cadorigen\nPrint llave\n\nDim As String cadcifrada = Encriptar(cadorigen, llave)\nPrint \" Cifrado: \"; cadcifrada\nPrint \"Descifrado: \"; DesEncriptar(cadcifrada, llave)\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\ntype vkey string\n\nfunc newVigenère(key string) (vkey, bool) {\n v := vkey(upperOnly(key))\n return v, len(v) > 0 // key length 0 invalid\n}\n\nfunc (k vkey) encipher(pt string) string {\n ct := upperOnly(pt)\n for i, c := range ct {\n ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26\n }\n return string(ct)\n}\n\nfunc (k vkey) decipher(ct string) (string, bool) {\n pt := make([]byte, len(ct))\n for i := range pt {\n c := ct[i]\n if c < 'A' || c > 'Z' {\n return \"\", false // invalid ciphertext\n }\n pt[i] = 'A' + (c-k[i%len(k)]+26)%26\n }\n return string(pt), true\n}\n\n// upperOnly extracts letters A-Z, a-z from a string and\n// returns them all upper case in a byte slice.\n// Useful for vkey constructor and encipher function.\nfunc upperOnly(s string) []byte {\n u := make([]byte, 0, len(s))\n for i := 0; i < len(s); i++ {\n c := s[i]\n if c >= 'A' && c <= 'Z' {\n u = append(u, c)\n } else if c >= 'a' && c <= 'z' {\n u = append(u, c-32)\n }\n }\n return u\n}\n\nconst testKey = \"Vigenère Cipher\"\nconst testPT = `Beware the Jabberwock, my son!\n The jaws that bite, the claws that catch!`\n\nfunc main() {\n fmt.Println(\"Supplied key: \", testKey)\n v, ok := newVigenère(testKey)\n if !ok {\n fmt.Println(\"Invalid key\")\n return\n }\n fmt.Println(\"Effective key:\", v)\n fmt.Println(\"Plain text:\", testPT)\n ct := v.encipher(testPT)\n fmt.Println(\"Enciphered:\", ct)\n dt, ok := v.decipher(ct)\n if !ok {\n fmt.Println(\"Invalid ciphertext\")\n return\n }\n fmt.Println(\"Deciphered:\", dt)\n}\n", "language": "Go" }, { "code": "import Data.Char\nimport Text.Printf\n\n-- Perform encryption or decryption, depending on f.\ncrypt f key = map toLetter . zipWith f (cycle key)\n where toLetter = chr . (+) (ord 'A')\n\n-- Encrypt or decrypt one letter.\nenc k c = (ord k + ord c) `mod` 26\ndec k c = (ord c - ord k) `mod` 26\n\n-- Given a key, encrypt or decrypt an input string.\nencrypt = crypt enc\ndecrypt = crypt dec\n\n-- Convert a string to have only upper case letters.\nconvert = map toUpper . filter isLetter\n\nmain :: IO ()\nmain = do\n let key = \"VIGENERECIPHER\"\n text = \"Beware the Jabberwock, my son! The jaws that bite, \"\n ++ \"the claws that catch!\"\n encr = encrypt key $ convert text\n decr = decrypt key encr\n printf \" Input: %s\\n Key: %s\\nEncrypted: %s\\nDecrypted: %s\\n\"\n text key encr decr\n", "language": "Haskell" }, { "code": "procedure main()\n ptext := \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n write(\"Key = \",ekey := \"VIGENERECIPHER\")\n write(\"Plain Text = \",ptext)\n write(\"Normalized = \",GFormat(ptext := NormalizeText(ptext)))\n write(\"Enciphered = \",GFormat(ctext := Vignere(\"e\",ekey,ptext)))\n write(\"Deciphered = \",GFormat(ptext := Vignere(\"d\",ekey,ctext)))\nend\n\nprocedure Vignere(mode,ekey,ptext,alpha) #: Vignere cipher\n /alpha := &ucase # default\n if *alpha ~= *cset(alpha) then runerr(205,alpha) # no dups\n alpha ||:= alpha # unobstructed\n\n every ctext:=\"\" & p:=ptext[i := 1 to *ptext] & k:=ekey[(i-1)%*ekey+1] do\n case mode of {\n \"e\"|\"encrypt\":\n ctext||:=map(p,alpha[1+:*alpha/2],alpha[find(k,alpha)+:(*alpha/2)])\n \"d\"|\"decrypt\":\n ctext||:=map(p,alpha[find(k,alpha)+:(*alpha/2)],alpha[1+:*alpha/2])\n default: runerr(205,mode)\n }\nreturn ctext\nend\n", "language": "Icon" }, { "code": "link strings\n\nprocedure NormalizeText(ptext,alpha) #: text/case classical crypto helper\n /alpha := &ucase # default\n if &lcase === (alpha := cset(alpha)) then ptext := map(ptext) # lower\n if &ucase === alpha then ptext := map(ptext,&lcase,&ucase) # upper\n return deletec(ptext,&cset--alpha) # only alphas\nend\n\nprocedure GFormat(text) #: 5 letter group formatting helper\n text ? (s := \"\", until pos(0) do s ||:= \" \" || move(5)|tab(0))\n return s[2:0]\nend\n", "language": "Icon" }, { "code": "ALPHA=: (65,:26) ];.0 a. NB. Character Set\npreprocess=: (#~ e.&ALPHA)@toupper NB. force uppercase and discard non-alpha chars\nvigEncryptRC=: 0 vig ALPHA preprocess\nvigDecryptRC=: 1 vig ALPHA preprocess\n", "language": "J" }, { "code": " 'VIGENERECIPHER' vigEncryptRC 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'\nWMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\n 'VIGENERECIPHER' vigDecryptRC 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'\nBEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n", "language": "J" }, { "code": "public class VigenereCipher {\n public static void main(String[] args) {\n String key = \"VIGENERECIPHER\";\n String ori = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n String enc = encrypt(ori, key);\n System.out.println(enc);\n System.out.println(decrypt(enc, key));\n }\n\n static String encrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n\n static String decrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n}\n", "language": "Java" }, { "code": "import com.google.common.collect.Streams;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static java.nio.charset.StandardCharsets.US_ASCII;\n\npublic class VigenereCipher {\n private final static int LOWER = 'A';\n private final static int UPPER = 'Z';\n private final static int SIZE = UPPER - LOWER + 1;\n private final Supplier<Stream<Character>> maskStream;\n\n public VigenereCipher(final String key) {\n final String mask = new String(key.getBytes(US_ASCII)).toUpperCase();\n maskStream = () ->\n Stream.iterate(0, i -> (i+1) % mask.length()).map(mask::charAt);\n }\n\n private String transform(final String text, final boolean encode) {\n final Stream<Integer> textStream = text.toUpperCase().chars().boxed()\n .filter(i -> i >= LOWER && i <= UPPER);\n return Streams.zip(textStream, maskStream.get(), (c, m) ->\n encode ? c + m - 2 * LOWER : c - m + SIZE)\n .map(c -> Character.toString(c % SIZE + LOWER))\n .collect(Collectors.joining());\n }\n\n public String encrypt(final String plaintext) {\n return transform(plaintext,true);\n }\n\n public String decrypt(final String ciphertext) {\n return transform(ciphertext,false);\n }\n}\n\nimport org.junit.jupiter.api.DisplayName;\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass VigenereCipherTest {\n private static final VigenereCipher Vigenere = new VigenereCipher(\"VIGENERECIPHER\");\n\n @Test\n @DisplayName(\"encipher/decipher round-trip succeeds\")\n void vigenereCipherTest() {\n final String input = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n final String expectEncrypted = \"WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\";\n final String expectDecrypted = \"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\";\n\n final String ciphertext = Vigenere.encrypt(input);\n assertEquals(expectEncrypted, ciphertext);\n\n final String plaintext = Vigenere.decrypt(ciphertext);\n assertEquals(expectDecrypted, plaintext);\n }\n\n}\n", "language": "Java" }, { "code": "// helpers\n// helper\nfunction ordA(a) {\n return a.charCodeAt(0) - 65;\n}\n\n// vigenere\nfunction vigenere(text, key, decode) {\n var i = 0, b;\n key = key.toUpperCase().replace(/[^A-Z]/g, '');\n return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g, function(a) {\n b = key[i++ % key.length];\n return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));\n });\n}\n\n// example\nvar text = \"The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog\";\nvar key = 'alex';\nvar enc = vigenere(text,key);\nvar dec = vigenere(enc,key,true);\n\nconsole.log(enc);\nconsole.log(dec);\n", "language": "JavaScript" }, { "code": "def vigenere(text; key; encryptp):\n # retain alphabetic characters only\n def n:\n ascii_upcase | explode | map(select(65 <= . and . <= 90)) | [., length];\n (text | n) as [$xtext, $length]\n | (key | n) as [$xkey, $keylength]\n | reduce range(0; $length) as $i (null;\n\t($i % $keylength) as $ki\n\t| . + [if encryptp\n\t then (($xtext[$i] + $xkey[$ki] - 130) % 26) + 65\n else (($xtext[$i] - $xkey[$ki] + 26) % 26) + 65\n\t end] )\n | implode;\n\n# Input: sample text\ndef example($key):\n vigenere(.; $key; true)\n | . as $encoded\n | ., vigenere($encoded; $key; false) ;\n\n\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n| (., example(\"VIGENERECIPHER\")),\n \"\",\n (., example(\"ROSETTACODE\"))\n", "language": "Jq" }, { "code": "/* Vigenère cipher, in Jsish */\n\"use strict\";\n\nfunction ordA(a:string):number {\n return a.charCodeAt(0) - 65;\n}\n\n// vigenere\nfunction vigenereCipher(text:string, key:string, decode:boolean=false):string {\n var i = 0, b;\n key = key.toUpperCase().replace(/[^A-Z]/g, '');\n return text.toUpperCase().replace(/[^A-Z]/g, '').replace(/[A-Z]/g,\n function(a:string, idx:number, str:string) {\n b = key[i++ % key.length];\n return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));\n });\n}\n\nprovide('vigenereCipher', 1);\n\nif (Interp.conf('unitTest')) {\n var text = \"The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog\";\n var key = 'jsish';\n var enc = vigenereCipher(text, key);\n; text;\n; enc;\n; vigenereCipher(enc, key, true);\n}\n\n/*\n=!EXPECTSTART!=\ntext ==> The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog\nenc ==> CZMIBRUSTYXOVXVGBCEWNVWNLALPWSJRGVVPLPWSJRGVVPDIRFMGOVVP\nvigenere(enc, key, true) ==> THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGTHELAZYDOGLAZYDOGDOG\n=!EXPECTEND!=\n*/\n", "language": "Jsish" }, { "code": "→(a::Char, b::Char, ± = +) = 'A'+((a-'A')±(b-'A')+26)%26\n←(a::Char, b::Char) = →(a,b,-)\n\ncleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str)))\nmatch_length(word, len) = repeat(word,len)[1:len]\n\nfunction →(message::String, codeword::String, ↔ = →)\n plaintext = cleanup(message)\n key = match_length(cleanup(codeword),length(plaintext))\n return String(plaintext .↔ key)\nend\n←(message::String, codeword::String) = →(message,codeword,←)\n\ncyphertext = \"I want spearmint gum\" → \"Gimme!\"\nprintln(cyphertext)\nprintln(cyphertext ← \"Gimme!\")\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nfun vigenere(text: String, key: String, encrypt: Boolean = true): String {\n val t = if (encrypt) text.toUpperCase() else text\n val sb = StringBuilder()\n var ki = 0\n for (c in t) {\n if (c !in 'A'..'Z') continue\n val ci = if (encrypt)\n (c.toInt() + key[ki].toInt() - 130) % 26\n else\n (c.toInt() - key[ki].toInt() + 26) % 26\n sb.append((ci + 65).toChar())\n ki = (ki + 1) % key.length\n }\n return sb.toString()\n}\n\nfun main(args: Array<String>) {\n val key = \"VIGENERECIPHER\"\n val text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n val encoded = vigenere(text, key)\n println(encoded)\n val decoded = vigenere(encoded, key, false)\n println(decoded)\n}\n", "language": "Kotlin" }, { "code": "{def vigenere\n {def vigenere.map\n {lambda {:code :key :txt}\n {S.map\n {{lambda {:code :txt :key :i}\n {W.code2char\n {+ {% {+ {W.char2code {W.get :i :txt}}\n {if :code\n then {W.char2code {W.get {% :i {W.length :key}} :key}}\n else {- 26 {W.char2code {W.get {% :i {W.length :key}} :key}}} }}\n 26}\n 65}} } :code :txt :key}\n {S.serie 0 {- {W.length :txt} 1}}} }}\n {lambda {:code :key :txt}\n {S.replace \\s by in {vigenere.map :code :key {S.replace \\s by in :txt}}} }}\n-> vigenere\n\n1) encode: {vigenere true LEMON ATTACK AT DAWN}\n-> LXFOPVEFRNHR\n\n2) decode: {vigenere false LEMON LXFOPVEFRNHR}\n-> ATTACKATDAWN\n", "language": "Lambdatalk" }, { "code": "ori$ = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey$ = filter$(\"vigenerecipher\")\nprint ori$\nprint key$\nenc$ = encrypt$(ori$, key$)\nprint enc$\ndec$ = decrypt$(enc$, key$)\nprint dec$\n\nend\n\nfunction encrypt$(text$, key$)\n flt$ = filter$(text$)\n encrypt$ = \"\"\n j = 1\n for i = 1 to len(flt$)\n m$ = mid$(flt$, i, 1)\n m = asc(m$)-asc(\"A\")\n k$ = mid$(key$, j, 1)\n k = asc(k$)-asc(\"A\")\n j = (j mod len(key$)) + 1\n c = (m + k) mod 26\n c$=chr$(asc(\"A\")+c)\n encrypt$=encrypt$+c$\n next\nend function\n\nfunction decrypt$(flt$, key$)\n decrypt$ = \"\"\n j = 1\n for i = 1 to len(flt$)\n m$ = mid$(flt$, i, 1)\n m = asc(m$)-asc(\"A\")\n k$ = mid$(key$, j, 1)\n k = asc(k$)-asc(\"A\")\n j = (j mod len(key$)) + 1\n c = (m - k + 26) mod 26\n c$=chr$(asc(\"A\")+c)\n decrypt$=decrypt$+c$\n next\nend function\n\nfunction filter$(ori$)\n'a..z A..Z go caps, other skipped\n filter$=\"\"\n for i = 1 to len(ori$)\n c$ = upper$(mid$(ori$,i,1))\n if instr(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", c$) then filter$ = filter$ + c$\n next\nend function\n", "language": "Liberty-BASIC" }, { "code": "function Encrypt( _msg, _key )\n local msg = { _msg:upper():byte( 1, -1 ) }\n local key = { _key:upper():byte( 1, -1 ) }\n local enc = {}\n\n local j, k = 1, 1\n for i = 1, #msg do\n if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then\n enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')\n\n k = k + 1\n if j == #key then j = 1 else j = j + 1 end\n end\n end\n\n return string.char( unpack(enc) )\nend\n\nfunction Decrypt( _msg, _key )\n local msg = { _msg:byte( 1, -1 ) }\n local key = { _key:upper():byte( 1, -1 ) }\n local dec = {}\n\n local j = 1\n for i = 1, #msg do\n dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')\n\n if j == #key then j = 1 else j = j + 1 end\n end\n\n return string.char( unpack(dec) )\nend\n\n\noriginal = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey = \"VIGENERECIPHER\";\n\nencrypted = Encrypt( original, key )\ndecrypted = Decrypt( encrypted, key )\n\nprint( encrypted )\nprint( decrypted )\n", "language": "Lua" }, { "code": "encode[text_String, key_String] :=\n Module[{textCode, keyCode},\n textCode =\n Cases[ToCharacterCode[\n ToUpperCase@\n text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;\n keyCode =\n Cases[ToCharacterCode[\n ToUpperCase@\n key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;\n keyCode =\n If[Length[textCode] < Length[keyCode],\n keyCode[[;; Length@textCode]],\n PadRight[keyCode, Length@textCode, keyCode]];\n FromCharacterCode[Mod[textCode + keyCode, 26] + 65]]\n\ndecode[text_String, key_String] :=\n Module[{textCode, keyCode},\n textCode =\n Cases[ToCharacterCode[\n ToUpperCase@\n text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;\n keyCode =\n Cases[ToCharacterCode[\n ToUpperCase@\n key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;\n keyCode =\n If[Length[textCode] < Length[keyCode],\n keyCode[[;; Length@textCode]],\n PadRight[keyCode, Length@textCode, keyCode]];\n FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]\n", "language": "Mathematica" }, { "code": "/* NetRexx */\noptions replace format comments java crossref savelog symbols nobinary\n\npt = 'Attack at dawn!'\nkey = 'LEMON'\ntest(key, pt)\n\nkey = 'N' -- rot-13\ntest(key, pt)\n\nkey = 'B' -- Caesar\ntest(key, pt)\n\npt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nkey = 'A'\ntest(key, pt)\n\npt = sampledata()\nkey = 'Hamlet; Prince of Denmark'\ntest(key, pt)\n\nreturn\n\nmethod vigenere(meth, key, text) public static\n\n select\n when 'encipher'.abbrev(meth.lower, 1) then df = 1\n when 'decipher'.abbrev(meth.lower, 1) then df = -1\n otherwise signal IllegalArgumentException(meth 'must be \"encipher\" or \"decipher\"')\n end\n\n alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n text = stringscrubber(text)\n key = stringscrubber(key)\n code = ''\n loop l_ = 1 to text.length()\n M = alpha.pos(text.substr(l_, 1)) - 1\n k_ = (l_ - 1) // key.length()\n K = alpha.pos(key.substr(k_ + 1, 1)) - 1\n C = mod((M + K * df), alpha.length())\n C = alpha.substr(C + 1, 1)\n code = code || C\n end l_\n\n return code\n\nmethod vigenere_encipher(key, plaintext) public static\n\n return vigenere('encipher', key, plaintext)\n\nmethod vigenere_decipher(key, ciphertext) public static\n\n return vigenere('decipher', key, ciphertext)\n\nmethod mod(N = int, D = int) private static\n\nreturn (D + (N // D)) // D\n\nmethod stringscrubber(cleanup) private static\n\n alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n cleanup = cleanup.upper.space(0)\n loop label f_ forever\n x_ = cleanup.verify(alpha)\n if x_ = 0 then leave f_\n cleanup = cleanup.changestr(cleanup.substr(x_, 1), '')\n end f_\n\n return cleanup\n\nmethod test(key, pt) private static\n\n ct = vigenere_encipher(key, pt)\n display(ct)\n dt = vigenere_decipher(key, ct)\n display(dt)\n\n return\n\nmethod display(text) public static\n\n line = ''\n o_ = 0\n loop c_ = 1 to text.length()\n b_ = o_ // 5\n o_ = o_ + 1\n if b_ = 0 then line = line' '\n line = line || text.substr(c_, 1)\n end c_\n\n say '....+....|'.copies(8)\n loop label l_ forever\n parse line w1 w2 w3 w4 w5 w6 W7 w8 w9 w10 w11 w12 line\n pline = w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12\n say pline.strip()\n if line.strip().length() = 0 then leave l_\n end l_\n say\n\n return\n\nmethod sampledata() private static returns Rexx\n\n NL = char('\\n')\n antic_disposition = Rexx[]\n\n antic_disposition = [ -\n Rexx(\"To be, or not to be--that is the question:\" ), -\n Rexx(\"Whether 'tis nobler in the mind to suffer\" ), -\n Rexx(\"The slings and arrows of outrageous fortune\" ), -\n Rexx(\"Or to take arms against a sea of troubles\" ), -\n Rexx(\"And by opposing end them. To die, to sleep--\" ), -\n Rexx(\"No more--and by a sleep to say we end\" ), -\n Rexx(\"The heartache, and the thousand natural shocks\" ), -\n Rexx(\"That flesh is heir to. 'Tis a consummation\" ), -\n Rexx(\"Devoutly to be wished. To die, to sleep--\" ), -\n Rexx(\"To sleep--perchance to dream: ay, there's the rub,\"), -\n Rexx(\"For in that sleep of death what dreams may come\" ), -\n Rexx(\"When we have shuffled off this mortal coil,\" ), -\n Rexx(\"Must give us pause. There's the respect\" ), -\n Rexx(\"That makes calamity of so long life.\" ), -\n Rexx(\"For who would bear the whips and scorns of time,\" ), -\n Rexx(\"Th' oppressor's wrong, the proud man's contumely\" ), -\n Rexx(\"The pangs of despised love, the law's delay,\" ), -\n Rexx(\"The insolence of office, and the spurns\" ), -\n Rexx(\"That patient merit of th' unworthy takes,\" ), -\n Rexx(\"When he himself might his quietus make\" ), -\n Rexx(\"With a bare bodkin? Who would fardels bear,\" ), -\n Rexx(\"To grunt and sweat under a weary life,\" ), -\n Rexx(\"But that the dread of something after death,\" ), -\n Rexx(\"The undiscovered country, from whose bourn\" ), -\n Rexx(\"No traveller returns, puzzles the will,\" ), -\n Rexx(\"And makes us rather bear those ills we have\" ), -\n Rexx(\"Than fly to others that we know not of?\" ), -\n Rexx(\"Thus conscience does make cowards of us all,\" ), -\n Rexx(\"And thus the native hue of resolution\" ), -\n Rexx(\"Is sicklied o'er with the pale cast of thought,\" ), -\n Rexx(\"And enterprise of great pith and moment\" ), -\n Rexx(\"With this regard their currents turn awry\" ), -\n Rexx(\"And lose the name of action. -- Soft you now,\" ), -\n Rexx(\"The fair Ophelia! -- Nymph, in thy orisons\" ), -\n Rexx(\"Be all my sins remembered.\" ) -\n ]\n\n melancholy_dane = Rexx('')\n loop l_ = 0 for antic_disposition.length\n melancholy_dane = melancholy_dane || antic_disposition[l_] || NL\n end l_\n\n return melancholy_dane\n", "language": "NetRexx" }, { "code": "import strutils\n\nproc encrypt(msg, key: string): string =\n var pos = 0\n for c in msg:\n if c in Letters:\n result.add chr(((ord(key[pos]) + ord(c.toUpperAscii)) mod 26) + ord('A'))\n pos = (pos + 1) mod key.len\n\nproc decrypt(msg, key: string): string =\n var pos = 0\n for c in msg:\n result.add chr(((26 + ord(c) - ord(key[pos])) mod 26) + ord('A'))\n pos = (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", "language": "Nim" }, { "code": "bundle Default {\n class VigenereCipher {\n function : Main(args : String[]) ~ Nil {\n key := \"VIGENERECIPHER\";\n ori := \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n enc := encrypt(ori, key);\n IO.Console->Print(\"encrypt: \")->PrintLine(enc);\n IO.Console->Print(\"decrypt: \")->PrintLine(decrypt(enc, key));\n }\n\n function : native : encrypt(text : String, key : String) ~ String {\n res := \"\";\n text := text->ToUpper();\n j := 0;\n\n each(i : text) {\n c := text->Get(i);\n if(c >= 'A' & c <= 'Z') {\n res->Append(((c + key->Get(j) - 2 * 'A') % 26 + 'A')->As(Char));\n j += 1;\n j := j % key->Size();\n };\n };\n\n return res;\n }\n\n function : native : decrypt(text : String, key : String) ~ String {\n res := \"\";\n text := text->ToUpper();\n j := 0;\n\n each(i : text) {\n c := text->Get(i);\n if(c >= 'A' & c <= 'Z') {\n res->Append(((c - key->Get(j) + 26) % 26 + 'A')->As(Char));\n j += 1;\n j := j % key->Size();\n };\n };\n\n return res;\n }\n }\n}\n", "language": "Objeck" }, { "code": "let cipher src key crypt =\n let str = String.uppercase src in\n let key = String.uppercase key in\n\n (* strip out non-letters *)\n let len = String.length str in\n let rec aux i j =\n if j >= len then String.sub str 0 i else\n if str.[j] >= 'A' && str.[j] <= 'Z'\n then (str.[i] <- str.[j]; aux (succ i) (succ j))\n else aux i (succ j)\n in\n let res = aux 0 0 in\n\n let slen = String.length res in\n let klen = String.length key in\n\n let d = int_of_char in\n let f =\n if crypt\n then fun i -> d res.[i] - d 'A' + d key.[i mod klen] - d 'A'\n else fun i -> d res.[i] - d key.[i mod klen] + 26\n in\n for i = 0 to pred slen do\n res.[i] <- char_of_int (d 'A' + (f i) mod 26)\n done;\n (res)\n\nlet () =\n let str = \"Beware the Jabberwock, my son! The jaws that bite, \\\n the claws that catch!\" in\n let key = \"VIGENERECIPHER\" in\n\n let cod = cipher str key true in\n let dec = cipher cod key false in\n\n Printf.printf \"Text: %s\\n\" str;\n Printf.printf \"key: %s\\n\" key;\n Printf.printf \"Code: %s\\n\" cod;\n Printf.printf \"Back: %s\\n\" dec;\n;;\n", "language": "OCaml" }, { "code": "(* Task : Vigenère_cipher *)\n\n(* This is a custom, more functional version of an existing solution,\n due to OCaml 4.05's unsafe-string compatibility mode:\n https://ocaml.org/api/String.html\n*)\n\n(*** Helpers ***)\n\n(* Verbose type abbreviation *)\ntype key = string\n\n(* Rotate a single uppercase letter *)\nlet ascii_caesar_shift : bool -> char -> char -> char =\n let min_range = Char.code 'A' in\n let max_range = Char.code 'Z' in\n (* aka 26 but this code can be adapted to larger ranges, such as the ASCII printable range (codes 32 to 126). *)\n let range_len = max_range - min_range + 1 in\n let actual_fun (dir : bool) (c1 : char) (c2 : char) : char =\n let n1 = Char.code c1 in\n let n2 = Char.code c2 - min_range in\n let sum = (if dir then (+) else (-)) n1 n2 in\n ( (* Effectively mod function, but simplified and works on negatives. *)\n if sum > max_range\n then sum - range_len\n else if sum < min_range\n then sum + range_len\n else sum\n ) |> Char.chr\n in\n actual_fun\n\n(* Remove non-letters and uppercase *)\nlet ascii_upper_letters_only (s : string) : string =\n let slen = String.length s in\n (* Make a list of escaped uppercase letter chars *)\n let rec toLetterList sidx acc =\n if sidx >= slen\n then List.rev acc\n else\n let c = s.[sidx] in\n if c >= 'A' && c <= 'Z'\n then toLetterList (sidx + 1) ((c |> Char.escaped) :: acc)\n else if c >= 'a' && c <= 'z'\n then toLetterList (sidx + 1) ((c |> Char.uppercase_ascii |> Char.escaped) :: acc)\n else toLetterList (sidx + 1) acc\n in\n toLetterList 0 [] |> String.concat \"\"\n\n(*** Actual task at hand ***)\n\nlet vig_crypt (dir : bool) (key : key) (message : string) : string =\n let message = ascii_upper_letters_only message in\n let key = ascii_upper_letters_only key in\n let klen = String.length key in\n let aux idx c =\n let kidx = idx mod klen in\n let e = ascii_caesar_shift dir c key.[kidx] in\n e\n in\n String.mapi aux message\n\nlet encrypt : key -> string -> string = vig_crypt true\nlet decrypt : key -> string -> string = vig_crypt false\n\n(*** Output ***)\n\nlet () =\n let str = \"Beware the Jabberwock, my son! The jaws that bite, \\\n the claws that catch!\" in\n let key = \"VIGENERECIPHER\" in\n let ct = encrypt key str in\n let pt = decrypt key ct in\n Printf.printf \"Text: %s\\n\" str;\n Printf.printf \"Key: %s\\n\" key;\n Printf.printf \"Code: %s\\n\" ct;\n Printf.printf \"Back: %s\\n\" pt\n;;\n", "language": "OCaml" }, { "code": "/* Rexx */\nDo\n alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n key = 'LEMON'\n\n pt = 'Attack at dawn!'\n Call test key, pt\n\n key = 'N'\n Call test key, pt\n\n key = 'B'\n Call test key, pt\n\n pt = alpha\n key = 'A'\n Call test key, pt\n\n pt = sampledata()\n key = 'Hamlet; Prince of Denmark'\n Call test key, pt\n\n Return\nEnd\nExit\n\nvigenere:\nProcedure Expose alpha\nDo\n Parse upper Arg meth, key, text\n\n Select\n When 'ENCIPHER'~abbrev(meth, 1) = 1 then df = 1\n When 'DECIPHER'~abbrev(meth, 1) = 1 then df = -1\n Otherwise Do\n Say meth 'invalid. Must be \"ENCIPHER\" or \"DECIPHER\"'\n Exit\n End\n End\n\n text = stringscrubber(text)\n key = stringscrubber(key)\n code = ''\n\n Do l_ = 1 to text~length()\n M = alpha~pos(text~substr(l_, 1)) - 1\n k_ = (l_ - 1) // key~length()\n K = alpha~pos(key~substr(k_ + 1, 1)) - 1\n C = mod((M + K * df), alpha~length())\n C = alpha~substr(C + 1, 1)\n code = code || C\n End l_\n\n Return code\n\n Return\nEnd\nExit\n\nvigenere_encipher:\nProcedure Expose alpha\nDo\n Parse upper Arg key, plaintext\n\n Return vigenere('ENCIPHER', key, plaintext)\nEnd\nExit\n\nvigenere_decipher:\nProcedure Expose alpha\nDo\n Parse upper Arg key, ciphertext\n\n Return vigenere('DECIPHER', key, ciphertext)\nEnd\nExit\n\nmod:\nProcedure\nDo\n Parse Arg N, D\n\n Return (D + (N // D)) // D\nEnd\nExit\n\nstringscrubber:\nProcedure Expose alpha\nDo\n Parse upper Arg cleanup\n\n cleanup = cleanup~space(0)\n Do label f_ forever\n x_ = cleanup~verify(alpha)\n If x_ = 0 then Leave f_\n cleanup = cleanup~changestr(cleanup~substr(x_, 1), '')\n end f_\n\n Return cleanup\nEnd\nExit\n\ntest:\nProcedure Expose alpha\nDo\n Parse Arg key, pt\n\n ct = vigenere_encipher(key, pt)\n Call display ct\n dt = vigenere_decipher(key, ct)\n Call display dt\n\n Return\nEnd\nExit\n\ndisplay:\nProcedure\nDo\n Parse Arg text\n\n line = ''\n o_ = 0\n Do c_ = 1 to text~length()\n b_ = o_ // 5\n o_ = o_ + 1\n If b_ = 0 then line = line' '\n line = line || text~substr(c_, 1)\n End c_\n\n Say '....+....|'~copies(8)\n Do label l_ forever\n Parse Var line w1 w2 w3 w4 w5 w6 W7 w8 w9 w10 w11 w12 line\n pline = w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12\n Say pline~strip()\n If line~strip()~length() = 0 then Leave l_\n End l_\n Say\n\n Return\nEnd\nExit\n\nsampledata:\nProcedure\nDo\n\n NL = '0a'x\n X = 0\n antic_disposition. = ''\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"To be, or not to be--that is the question:\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Whether 'tis nobler in the mind to suffer\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The slings and arrows of outrageous fortune\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Or to take arms against a sea of troubles\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"And by opposing end them. To die, to sleep--\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"No more--and by a sleep to say we end\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The heartache, and the thousand natural shocks\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"That flesh is heir to. 'Tis a consummation\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Devoutly to be wished. To die, to sleep--\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"To sleep--perchance to dream: ay, there's the rub,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"For in that sleep of death what dreams may come\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"When we have shuffled off this mortal coil,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Must give us pause. There's the respect\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"That makes calamity of so long life.\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"For who would bear the whips and scorns of time,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Th' oppressor's wrong, the proud man's contumely\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The pangs of despised love, the law's delay,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The insolence of office, and the spurns\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"That patient merit of th' unworthy takes,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"When he himself might his quietus make\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"With a bare bodkin? Who would fardels bear,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"To grunt and sweat under a weary life,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"But that the dread of something after death,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The undiscovered country, from whose bourn\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"No traveller returns, puzzles the will,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"And makes us rather bear those ills we have\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Than fly to others that we know not of?\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Thus conscience does make cowards of us all,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"And thus the native hue of resolution\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Is sicklied o'er with the pale cast of thought,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"And enterprise of great pith and moment\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"With this regard their currents turn awry\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"And lose the name of action. -- Soft you now,\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"The fair Ophelia! -- Nymph, in thy orisons\"\n X = X + 1; antic_disposition.0 = X; antic_disposition.X = \"Be all my sins remembered.\"\n\n melancholy_dane = ''\n Do l_ = 1 for antic_disposition.0\n melancholy_dane = melancholy_dane || antic_disposition.l_ || NL\n End l_\n\n Return melancholy_dane\nEnd\nExit\n", "language": "OoRexx" }, { "code": "// The Vigenere cipher in reasonably standard Pascal\n// <no library functions: all conversions hand-coded>\nPROGRAM Vigenere;\n\n// get a letter's alphabetic position (A=0)\nFUNCTION letternum(letter: CHAR): BYTE;\n\tBEGIN\n\t\tletternum := (ord(letter)-ord('A'));\n\tEND;\n\n// convert a character to uppercase\nFUNCTION uch(ch: CHAR): CHAR;\n\tBEGIN\n\t\tuch := ch;\n\t\tIF ch IN ['a'..'z'] THEN\n\t\t\tuch := chr(ord(ch) AND $5F);\n\tEND;\n\t\n// convert a string to uppercase\nFUNCTION ucase(str: STRING): STRING;\n\tVAR i: BYTE;\n\tBEGIN\n\t\tucase := '';\n\t\tFOR i := 1 TO Length(str) DO\n\t\t\tucase := ucase + uch(str[i]);\n\tEND;\n\t\n// construct a Vigenere-compatible string:\n// uppercase; no spaces or punctuation.\nFUNCTION vstr(pt: STRING): STRING;\n\tVAR c: Cardinal;\n\t\ts: STRING;\n\tBEGIN\n\t\tvstr:= '';\n\t\ts \t:= ucase(pt);\n\t\tFOR c := 1 TO Length(s) DO BEGIN\n\t\t\tIF s[c] IN ['A'..'Z'] THEN\n\t\t\t\tvstr += s[c];\n\t\tEND;\n\tEND;\n\t\n// construct a repeating Vigenere key\nFUNCTION vkey(pt, key: STRING): STRING;\n\tVAR c,n: Cardinal;\n\t\tk : STRING;\n\tBEGIN\n\t\tk := vstr(key);\n\t\tvkey := '';\n\t\tFOR c := 1 TO Length(pt) DO BEGIN\n\t\t\tn := c mod Length(k);\n\t\t\tIF n>0 THEN vkey += k[n] ELSE vkey += k[Length(k)];\n\t\tEND;\n\tEND;\n\t\n// Vigenere encipher\t\nFUNCTION enVig(pt,key:STRING): STRING;\n\tVAR ct: STRING;\n\t\tc,n\t : Cardinal;\n\tBEGIN\n\t\tct := pt;\n\t\tFOR c := 1 TO Length(pt) DO BEGIN\n\t\t\tn := letternum(pt[c])+letternum(key[c]);\n\t\t\tn := n mod 26;\n\t\t\tct[c]:=chr(ord('A')+n);\n\t\tEND;\n\t\tenVig := ct;\n\tEND;\n\t\n// Vigenere decipher\nFUNCTION deVig(ct,key:STRING): STRING;\n\tVAR pt\t: STRING;\n\t\tc,n\t: INTEGER;\n\tBEGIN\n\t\tpt := ct;\n\t\tFOR c := 1 TO Length(ct) DO BEGIN\n\t\t\tn := letternum(ct[c])-letternum(key[c]);\n\t\t\tIF n<0 THEN n:=26+n;\n\t\t\tpt[c]:=chr(ord('A')+n);\n\t\tEND;\n\t\tdeVig := pt;\n\tEND;\t\n\n\t\nVAR \tkey: STRING = 'Vigenere cipher';\n\t\tmsg: STRING = 'Beware the Jabberwock! The jaws that bite, the claws that catch!';\n\t\tvtx: STRING = '';\n\t\tctx: STRING = '';\n\t\tptx: STRING = '';\n\nBEGIN\n\t// make Vigenere-compatible\n\tvtx := vstr(msg);\n\tkey := vkey(vtx,key);\n\t// Vigenere encipher / decipher\n\tctx := enVig(vtx,key);\n\tptx := deVig(ctx,key);\n\t// display results\n\tWriteln('Message : ',msg);\n\tWriteln('Plaintext : ',vtx);\n\tWriteln('Key : ',key);\n\tWriteln('Ciphertext : ',ctx);\n\tWriteln('Plaintext : ',ptx);\nEND.\n", "language": "Pascal" }, { "code": "if( @ARGV != 3 ){\n printHelp();\n}\n\n # translate to upper-case, remove anything else\nmap( (tr/a-z/A-Z/, s/[^A-Z]//g), @ARGV );\n\nmy $cipher_decipher = $ARGV[ 0 ];\n\nif( $cipher_decipher !~ /ENC|DEC/ ){\n printHelp(); # user should say what to do\n}\n\nprint \"Key: \" . (my $key = $ARGV[ 2 ]) . \"\\n\";\n\nif( $cipher_decipher =~ /ENC/ ){\n print \"Plain-text: \" . (my $plain = $ARGV[ 1 ]) . \"\\n\";\n print \"Encrypted: \" . Vigenere( 1, $key, $plain ) . \"\\n\";\n}elsif( $cipher_decipher =~ /DEC/ ){\n print \"Cipher-text: \" . (my $cipher = $ARGV[ 1 ]) . \"\\n\";\n print \"Decrypted: \" . Vigenere( -1, $key, $cipher ) . \"\\n\";\n}\n\nsub printHelp{\n print \"Usage:\\n\" .\n \"Encrypting:\\n perl cipher.pl ENC (plain text) (key)\\n\" .\n \"Decrypting:\\n perl cipher.pl DEC (cipher text) (key)\\n\";\n exit -1;\n}\n\nsub Vigenere{\n my ($direction, $key, $text) = @_;\n for( my $count = 0; $count < length $text; $count ++ ){\n $key_offset = $direction * ord substr( $key, $count % length $key, 1);\n $char_offset = ord substr( $text, $count, 1 );\n $cipher .= chr 65 + ((($char_offset % 26) + ($key_offset % 26)) % 26);\n # 65 is the ASCII character code for 'A'\n }\n return $cipher;\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">ENCRYPT</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">DECRYPT</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">Vigenere</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ch</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">upper</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #008000;\">'A'</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #008000;\">'Z'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008000;\">'A'</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">mode</span><span style=\"color: #0000FF;\">*(</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">))+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">key</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"LEMON\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"ATTACK AT DAWN\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">Vigenere</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ENCRYPT</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">Vigenere</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">DECRYPT</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Original: %s\\nEncrypted: %s\\nDecrypted: %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\n$str = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n$key = \"VIGENERECIPHER\";\n\nprintf(\"Text: %s\\n\", $str);\nprintf(\"key: %s\\n\", $key);\n\n$cod = encipher($str, $key, true); printf(\"Code: %s\\n\", $cod);\n$dec = encipher($cod, $key, false); printf(\"Back: %s\\n\", $dec);\n\nfunction encipher($src, $key, $is_encode)\n{\n $key = strtoupper($key);\n $src = strtoupper($src);\n $dest = '';\n\n /* strip out non-letters */\n for($i = 0; $i <= strlen($src); $i++) {\n $char = substr($src, $i, 1);\n if(ctype_upper($char)) {\n $dest .= $char;\n }\n }\n\n for($i = 0; $i <= strlen($dest); $i++) {\n $char = substr($dest, $i, 1);\n if(!ctype_upper($char)) {\n continue;\n }\n $dest = substr_replace($dest,\n chr (\n ord('A') +\n ($is_encode\n ? ord($char) - ord('A') + ord($key[$i % strlen($key)]) - ord('A')\n : ord($char) - ord($key[$i % strlen($key)]) + 26\n ) % 26\n )\n , $i, 1);\n }\n\n return $dest;\n}\n\n?>\n", "language": "PHP" }, { "code": "(de vigenereKey (Str)\n (extract\n '((C)\n (when (>= \"Z\" (uppc C) \"A\")\n (- (char (uppc C)) 65) ) )\n (chop Str) ) )\n\n(de vigenereEncrypt (Str Key)\n (pack\n (mapcar\n '((C K)\n (char (+ 65 (% (+ C K) 26))) )\n (vigenereKey Str)\n (apply circ (vigenereKey Key)) ) ) )\n\n(de vigenereDecrypt (Str Key)\n (pack\n (mapcar\n '((C K)\n (char (+ 65 (% (+ 26 (- C K)) 26))) )\n (vigenereKey Str)\n (apply circ (vigenereKey Key)) ) ) )\n", "language": "PicoLisp" }, { "code": "cypher: procedure options (main); /* 21 September 2012 */\n declare t(26) character (26);\n declare (i, j, k, L) fixed binary;\n declare (original, encoded, coder) character (1000) varying initial ('');\n declare cypher character (30) varying;\n declare (co, ct, cc) character (1);\n\n /* Set up cypher table. */\n t(1) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n do i = 2 to 26;\n t(i) = substr(t(i-1), 2, 25) || substr(t(i-1), 1, 1);\n end;\n\n cypher = 'VIGILANCE';\n original = 'Meet me on Tuesday evening at seven.';\n put edit ('Message=', original) (a);\n original = uppercase(original);\n\n /* Create the cypher text, same length as original, or longer. */\n coder = repeat(cypher, length(original)/length(cypher));\n\n /* Encode the original message, character by character. */\n /* Non-alphabetic characters are ignored. */\n L = 0;\n do i = 1 to length(original);\n co = substr(original, i, 1);\n j = index(t(1), co);\n if j = 0 then iterate; /* Ignore non-alphabetic character */\n L = L + 1;\n ct = substr(coder, L, 1);\n k = index(t(1), ct);\n encoded = encoded || substr(t(j), k, 1);\n end;\n put skip data (encoded);\n\n /* DECODING. */\n put skip list ('Decoded=');\n do i = 1 to length(encoded);\n cc = substr(coder, i, 1);\n j = index(t(1), cc);\n k = index(t(j), substr(encoded, i, 1));\n put edit (substr(t(1), k, 1) ) (a(1));\n end;\nend cypher;\n", "language": "PL-I" }, { "code": "# Author: D. Cudnohufsky\nfunction Get-VigenereCipher\n{\n Param\n (\n [Parameter(Mandatory=$true)]\n [string] $Text,\n\n [Parameter(Mandatory=$true)]\n [string] $Key,\n\n [switch] $Decode\n )\n\n begin\n {\n $map = [char]'A'..[char]'Z'\n }\n\n process\n {\n $Key = $Key -replace '[^a-zA-Z]',''\n $Text = $Text -replace '[^a-zA-Z]',''\n\n $keyChars = $Key.toUpper().ToCharArray()\n $Chars = $Text.toUpper().ToCharArray()\n\n function encode\n {\n\n param\n (\n $Char,\n $keyChar,\n $Alpha = [char]'A'..[char]'Z'\n )\n\n $charIndex = $Alpha.IndexOf([int]$Char)\n $keyIndex = $Alpha.IndexOf([int]$keyChar)\n $NewIndex = ($charIndex + $KeyIndex) - $Alpha.Length\n $Alpha[$NewIndex]\n\n }\n\n function decode\n {\n\n param\n (\n $Char,\n $keyChar,\n $Alpha = [char]'A'..[char]'Z'\n )\n\n $charIndex = $Alpha.IndexOf([int]$Char)\n $keyIndex = $Alpha.IndexOf([int]$keyChar)\n $int = $charIndex - $keyIndex\n if ($int -lt 0) { $NewIndex = $int + $Alpha.Length }\n else { $NewIndex = $int }\n $Alpha[$NewIndex]\n }\n\n while ( $keyChars.Length -lt $Chars.Length )\n {\n $keyChars = $keyChars + $keyChars\n }\n\n for ( $i = 0; $i -lt $Chars.Length; $i++ )\n {\n\n if ( [int]$Chars[$i] -in $map -and [int]$keyChars[$i] -in $map )\n {\n if ($Decode) {$Chars[$i] = decode $Chars[$i] $keyChars[$i] $map}\n else {$Chars[$i] = encode $Chars[$i] $keyChars[$i] $map}\n\n $Chars[$i] = [char]$Chars[$i]\n [string]$OutText += $Chars[$i]\n }\n\n }\n\n $OutText\n $OutText = $null\n }\n}\n", "language": "PowerShell" }, { "code": "Procedure prepString(text.s, Array letters(1))\n ;convert characters to an ordinal (0-25) and remove non-alphabetic characters,\n ;returns dimension size of result array letters()\n Protected *letter.Character, index\n Dim letters(Len(text))\n text = UCase(text)\n *letter = @text\n While *letter\\c\n Select *letter\\c\n Case 'A' To 'Z'\n letters(index) = *letter\\c - 65\n index + 1\n EndSelect\n *letter + SizeOf(Character)\n Wend\n If index > 0\n Redim letters(index - 1)\n EndIf\n ProcedureReturn index - 1\nEndProcedure\n\nProcedure.s VC_encrypt(text.s, keyText.s, reverse = 0)\n ;if reverse <> 0 then reverse the key (decrypt)\n Protected *letter.Character\n Dim text(0)\n Dim keyText(0)\n If prepString(text, text()) < 0 Or prepString(keyText, keyText()) < 0: ProcedureReturn: EndIf ;exit, nothing to work with\n\n Protected i, keyLength = ArraySize(keyText())\n If reverse\n For i = 0 To keyLength\n keyText(i) = 26 - keyText(i)\n Next\n EndIf\n\n Protected textLength = ArraySize(text()) ;zero-based length\n Protected result.s = Space(textLength + 1), *resultLetter.Character\n keyLength + 1 ;convert from zero-based to one-based count\n *resultLetter = @result\n For i = 0 To textLength\n *resultLetter\\c = ((text(i) + keyText(i % keyLength)) % 26) + 65\n *resultLetter + SizeOf(Character)\n Next\n ProcedureReturn result\nEndProcedure\n\nProcedure.s VC_decrypt(cypherText.s, keyText.s)\n ProcedureReturn VC_encrypt(cypherText, keyText.s, 1)\nEndProcedure\n\nIf OpenConsole()\n Define VignereCipher.s, plainText.s, encryptedText.s, decryptedText.s\n\n VignereCipher.s = \"VIGNERECIPHER\"\n plainText = \"The quick brown fox jumped over the lazy dogs.\": PrintN(RSet(\"Plain text = \", 17) + #DQUOTE$ + plainText + #DQUOTE$)\n encryptedText = VC_encrypt(plainText, VignereCipher): PrintN(RSet(\"Encrypted text = \", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)\n decryptedText = VC_decrypt(encryptedText, VignereCipher): PrintN(RSet(\"Decrypted text = \", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "'''Vigenere encryption and decryption'''\n\nfrom itertools import starmap, cycle\n\n\ndef encrypt(message, key):\n '''Vigenere encryption of message using key.'''\n\n # Converted to uppercase.\n # Non-alpha characters stripped out.\n message = filter(str.isalpha, message.upper())\n\n def enc(c, k):\n '''Single letter encryption.'''\n\n return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))\n\n return ''.join(starmap(enc, zip(message, cycle(key))))\n\n\ndef decrypt(message, key):\n '''Vigenere decryption of message using key.'''\n\n def dec(c, k):\n '''Single letter decryption.'''\n\n return chr(((ord(c) - ord(k) - 2 * ord('A')) % 26) + ord('A'))\n\n return ''.join(starmap(dec, zip(message, cycle(key))))\n\n\ndef main():\n '''Demonstration'''\n\n text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (\n 'the claws that catch!'\n )\n key = 'VIGENERECIPHER'\n\n encr = encrypt(text, key)\n decr = decrypt(encr, key)\n\n print(text)\n print(encr)\n print(decr)\n\n\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ [] swap witheach\n [ upper\n dup char A char Z 1+ within\n iff join else drop ] ] is onlycaps ( $ --> $ )\n\n [ onlycaps\n [] swap witheach\n [ char A - join ] ] is cipherdisk ( $ --> [ )\n\n [ [] swap witheach\n [ 26 swap - join ] ] is deciphering ( [ --> [ )\n\n [ behead tuck join swap ] is nextkey ( [ --> [ n )\n\n [ dip nextkey + dup\n char Z > if [ 26 - ] ] is encryptchar ( [ c --> [ c )\n\n [ $ \"\" swap rot\n onlycaps witheach\n [ encryptchar\n swap dip join ]\n drop ] is vigenere ( $ [ --> $ )\n\n [ cipherdisk vigenere ] is encrypt ( $ $ --> $ )\n\n [ cipherdisk deciphering vigenere ] is decrypt ( $ $ --> $ )\n\n $ \"If you reveal your secrets to the wind, you should \"\n $ \"not blame the wind for revealing them to the trees.\" join\n\n say \"Encrypted: \" $ \"Kahlil Gibran\" encrypt dup echo$ cr\n say \"Decrypted: \" $ \"Kahlil Gibran\" decrypt echo$\n", "language": "Quackery" }, { "code": "mod1 = function(v, n)\n# mod1(1:20, 6) => 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2\n ((v - 1) %% n) + 1\n\nstr2ints = function(s)\n as.integer(Filter(Negate(is.na),\n factor(levels = LETTERS, strsplit(toupper(s), \"\")[[1]])))\n\nvigen = function(input, key, decrypt = F)\n {input = str2ints(input)\n key = rep(str2ints(key), len = length(input)) - 1\n paste(collapse = \"\", LETTERS[\n mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}\n\nmessage(vigen(\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", \"vigenerecipher\"))\n # WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nmessage(vigen(\"WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\", \"vigenerecipher\", decrypt = T))\n # BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n", "language": "R" }, { "code": "#lang racket\n(define chr integer->char)\n(define ord char->integer)\n\n(define (encrypt msg key)\n (define cleaned\n (list->string\n (for/list ([c (string-upcase msg)]\n #:when (char-alphabetic? c)) c)))\n (list->string\n (for/list ([c cleaned] [k (in-cycle key)])\n (chr (+ (modulo (+ (ord c) (ord k)) 26) (ord #\\A))))))\n\n(define (decrypt msg key)\n (list->string\n (for/list ([c msg] [k (in-cycle key)])\n (chr (+ (modulo (- (ord c) (ord k)) 26) (ord #\\A))))))\n\n(decrypt (encrypt \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n \"VIGENERECIPHER\")\n \"VIGENERECIPHER\")\n", "language": "Racket" }, { "code": "\"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\"\n", "language": "Racket" }, { "code": "sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }\nsub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }\n\nsub blacken ($red, $key) { v2s(s2v($red) »+» s2v($key)) }\nsub redden ($blk, $key) { v2s(s2v($blk) »-» s2v($key)) }\n\nmy $red = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\nmy $key = \"Vigenere Cipher!!!\";\n\nsay $red;\nsay my $black = blacken($red, $key);\nsay redden($black, $key);\n", "language": "Raku" }, { "code": "Red [needs: 'view]\n\nCRLF: copy \"^M^/\" ;; constant for 0D 0A line feed\n;;------------------------------------\ncrypt: func [\"function to en- or decrypt message from textarea tx1\"\n /decrypt \"decrypting switch/refinement\" ][\n;;------------------------------------\n\n;; when decrypting we have to remove the superflous newlines\n;; and undo the base64 encoding first ...\ntxt: either decrypt [ ;; message to en- or decrypt\n s: copy tx1/text\n ;; newline could be single 0a byte or crlf sequence when copied from clipboard...\n debase replace/all s either find s CRLF [CRLF ] [ newline ] \"\"\n] [\n tx1/text ;; plaintext message\n]\n\ntxt: to-binary txt ;; handle message as binary\nkey: to-binary key1/text ;; handle key also as binary\n\nbin: copy either decrypt [ \"\" ][ #{} ] ;; buffer for output\n\ncode: copy #{} ;; temp field to collect utf8 bytes when decrypting\n\n;; loop over length of binary! message ...\nrepeat pos length? txt [\n k: to-integer key/(1 + modulo pos length? key) ;; get corresponding key byte\n c: to-integer txt/:pos ;; get integer value from message byte at position pos\n\n either decrypt [ ;; decrypting ?\n c: modulo ( 256 + c - k ) 256 ;; compute original byte value\n case [\n ;; byte starting with 11.... ( >= 192 dec ) is utf8 startbyte\n ;; byte starting with 10... ( >= 128 dec) is utf8 follow up byte , below is single ascii byte\n ( c >= 192 ) or ( c < 128 ) [ ;; starting utf8 sequence byte or below 128 normal ascii ?\n ;; append last code to buffer, maybe normal ascii or utf8 sequence...\n if not empty? code [ append bin to-char code ] ;; save previous code first\n code: append copy #{} c ;; start new code\n ]\n true [ append code c ] ;; otherwise utf8 follow up byte, append to startbyte\n ]\n ][\n append bin modulo ( c + k ) 256 ;; encrypting , simply collect binary bytes\n ]\n] ;; close repeat loop\n\neither decrypt [ ;; collect utf-8 characters\n append bin to-char code ;; append last code\n tx2/text: to-string bin ;; create valid utf8 string when decrypting\n][ ;; base64 encoding of crypted binary to get readable text string...\n s: enbase copy bin ;; base 64 is default\n while [40 < length? s ] [ ;; insert newlines for better \"readability\"\n s: skip s either head? s [40][41] ;; ... every 40 characters\n insert s newline\n ]\n tx2/text: head s ;; reset s pointing to head again\n ]\n]\n;----------------------------------------------------------\n; start of program\n;----------------------------------------------------------\nview layout [title \"vigenere cyphre\"\t;Define nice GUI :- )\n;----------------------------------------------------------\n backdrop silver ;; define window background colour\n text \"message:\" pad 99x1 button \"get-clip\" [tx1/text: read-clipboard]\n ;; code in brackets will be executed, when button is clicked:\n button \"clear\" [tx1/text: copy \"\" ] return\n tx1: area 330x80 \"\" return\n text 25x20 \"Key:\" key1: field 290x20 \"secretkey\" return\n button \"crypt\" [crypt ] button \"decrypt\" [crypt/decrypt ]\n button \"swap\" [tx1/text: copy tx2/text tx2/text: copy \"\" ] return\n text \"de-/encrypted message:\" pad 50x1 button \"copy clip\" [ write-clipboard tx2/text]\n button \"clear\" [tx2/text: copy \"\" ] return\n tx2: area 330x100 return\n pad 270x1 button \"Quit \" [quit]\n]\n", "language": "Red" }, { "code": "/*REXX program encrypts (and displays) uppercased text using the Vigenère cypher.*/\[email protected] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nL=length(@.1)\n do j=2 to L; jm=j-1; [email protected]\n @.j=substr(q, 2, L - 1)left(q, 1)\n end /*j*/\n\ncypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0)\noMsg = 'People solve problems by trial and error; judgement helps pick the trial.'\noMsgU = oMsg; upper oMsgU\ncypher_= copies(cypher, length(oMsg) % length(cypher) )\n say ' original text =' oMsg\n xMsg= Ncypher(oMsgU); say ' cyphered text =' xMsg\n bMsg= Dcypher(xMsg) ; say 're-cyphered text =' bMsg\nexit\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nNcypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/\n do i=1 for length(x); j=pos(substr(x,i,1), @.1); if j==0 then iterate\n nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=#+1\n end /*j*/\n return nMsg\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nDcypher: parse arg x; dMsg=\n do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)\n dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )\n end /*j*/\n return dMsg\n", "language": "REXX" }, { "code": "/*REXX program encrypts (and displays) most text using the Vigenère cypher. */\n@abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU\[email protected] = @abcU || @abc'0123456789~`!@#$%^&*()_-+={}|[]\\:;<>?,./\" '''\nL=length(@.1)\n do j=2 to length(@.1); jm=j - 1; [email protected]\n @.j=substr(q, 2, L - 1)left(q, 1)\n end /*j*/\n\ncypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0)\noMsg = 'Making things easy is just knowing the shortcuts. --- Gerard J. Schildberger'\ncypher_= copies(cypher, length(oMsg) % length(cypher) )\n say ' original text =' oMsg\n xMsg= Ncypher(oMsg); say ' cyphered text =' xMsg\n bMsg= Dcypher(xMsg); say 're-cyphered text =' bMsg\nexit\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nNcypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/\n do i=1 for length(x); j=pos(substr(x,i,1), @.1); if j==0 then iterate\n nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=# + 1\n end /*j*/\n return nMsg\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nDcypher: parse arg x; dMsg=\n do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1)\n dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 )\n end /*j*/\n return dMsg\n", "language": "REXX" }, { "code": "# Project : Vigenère cipher\n\nkey = \"LEMON\"\nplaintext = \"ATTACK AT DAWN\"\nciphertext = encrypt(plaintext, key)\nsee \"key = \"+ key + nl\nsee \"plaintext = \" + plaintext + nl\nsee \"ciphertext = \" + ciphertext + nl\nsee \"decrypted = \" + decrypt(ciphertext, key) + nl\n\n\nfunc encrypt(plain, key)\n o = \"\"\n k = 0\n plain = fnupper(plain)\n key = fnupper(key)\n for i = 1 to len(plain)\n n = ascii(plain[i])\n if n >= 65 and n <= 90\n o = o + char(65 + (n + ascii(key[k+1])) % 26)\n k = (k + 1) % len(key)\n ok\n next\n return o\n\nfunc decrypt(cipher, key)\n o = \"\"\n k = 0\n cipher = fnupper(cipher)\n key = fnupper(key)\n for i = 1 to len(cipher)\n n = ascii(cipher[i])\n o = o + char(65 + (n + 26 - ascii(key[k+1])) % 26)\n k = (k + 1) % len(key)\n next\n return o\n\nfunc fnupper(a)\n for aa = 1 to len(a)\n c = ascii(a[aa])\n if c >= 97 and c <= 122\n a[aa] = char(c-32)\n ok\n next\n return a\n", "language": "Ring" }, { "code": "module VigenereCipher\n\n BASE = 'A'.ord\n SIZE = 'Z'.ord - BASE + 1\n\n def encrypt(text, key)\n crypt(text, key, :+)\n end\n\n def decrypt(text, key)\n crypt(text, key, :-)\n end\n\n def crypt(text, key, dir)\n text = text.upcase.gsub(/[^A-Z]/, '')\n key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle\n text.each_char.inject('') do |ciphertext, char|\n offset = key_iterator.next\n ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr\n end\n end\n\nend\n", "language": "Ruby" }, { "code": "include VigenereCipher\n\nplaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'\nkey = 'Vigenere cipher'\nciphertext = VigenereCipher.encrypt(plaintext, key)\nrecovered = VigenereCipher.decrypt(ciphertext, key)\n\nputs \"Original: #{plaintext}\"\nputs \"Encrypted: #{ciphertext}\"\nputs \"Decrypted: #{recovered}\"\n", "language": "Ruby" }, { "code": "use std::ascii::AsciiExt;\n\nstatic A: u8 = 'A' as u8;\n\nfn uppercase_and_filter(input: &str) -> Vec<u8> {\n let alphabet = b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n let mut result = Vec::new();\n\n for c in input.chars() {\n // Ignore anything that is not in our short list of chars. We can then safely cast to u8.\n if alphabet.iter().any(|&x| x as char == c) {\n result.push(c.to_ascii_uppercase() as u8);\n }\n }\n\n return result;\n}\n\nfn vigenere(key: &str, text: &str, is_encoding: bool) -> String {\n\n let key_bytes = uppercase_and_filter(key);\n let text_bytes = uppercase_and_filter(text);\n\n let mut result_bytes = Vec::new();\n\n for (i, c) in text_bytes.iter().enumerate() {\n let c2 = if is_encoding {\n (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A\n } else {\n (c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A\n };\n result_bytes.push(c2);\n }\n\n String::from_utf8(result_bytes).unwrap()\n}\n\nfn main() {\n let text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n let key = \"VIGENERECIPHER\";\n\n println!(\"Text: {}\", text);\n println!(\"Key: {}\", key);\n\n let encoded = vigenere(key, text, true);\n println!(\"Code: {}\", encoded);\n let decoded = vigenere(key, &encoded, false);\n println!(\"Back: {}\", decoded);\n}\n", "language": "Rust" }, { "code": "object Vigenere {\n def encrypt(msg: String, key: String) : String = {\n var result: String = \"\"\n var j = 0\n\n for (i <- 0 to msg.length - 1) {\n val c = msg.charAt(i)\n if (c >= 'A' && c <= 'Z') {\n result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar\n j = (j + 1) % key.length\n }\n }\n\n return result\n }\n\n def decrypt(msg: String, key: String) : String = {\n var result: String = \"\"\n var j = 0\n\n for (i <- 0 to msg.length - 1) {\n val c = msg.charAt(i)\n if (c >= 'A' && c <= 'Z') {\n result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar\n j = (j + 1) % key.length\n }\n }\n\n return result\n }\n}\n\nprintln(\"Encrypt text ABC => \" + Vigenere.encrypt(\"ABC\", \"KEY\"))\nprintln(\"Decrypt text KFA => \" + Vigenere.decrypt(\"KFA\", \"KEY\"))\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst func string: vigenereCipher (in string: source, in var string: keyword) is func\n result\n var string: dest is \"\";\n local\n var char: ch is ' ';\n var integer: index is 1;\n var integer: shift is 0;\n begin\n keyword := upper(keyword);\n for ch range source do\n if ch in {'A' .. 'Z'} | {'a' .. 'z'} then\n shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A');\n dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') + shift) rem 26);\n incr(index);\n end if;\n end for;\n end func;\n\nconst func string: vigenereDecipher (in string: source, in var string: keyword) is func\n result\n var string: dest is \"\";\n local\n var char: ch is ' ';\n var integer: index is 0;\n var integer: shift is 0;\n begin\n keyword := upper(keyword);\n for ch key index range source do\n if ch in {'A' .. 'Z'} | {'a' .. 'z'} then\n shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A');\n dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') - shift) mod 26);\n end if;\n end for;\n end func;\n\nconst proc: main is func\n local\n const string: input is \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n const string: keyword is \"VIGENERECIPHER\";\n var string: encrypted is \"\";\n var string: decrypted is \"\";\n begin\n writeln(\"Input: \" <& input);\n writeln(\"key: \" <& keyword);\n encrypted := vigenereCipher(input, keyword);\n writeln(\"Encrypted: \" <& encrypted);\n decrypted := vigenereDecipher(encrypted, keyword);\n writeln(\"Decrypted: \" <& decrypted);\n end func;\n", "language": "Seed7" }, { "code": "func s2v(s) { s.uc.scan(/[A-Z]/).map{.ord} »-» 65 }\nfunc v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join }\n \nfunc blacken (red, key) { v2s(s2v(red) »+« s2v(key)) }\nfunc redden (blk, key) { v2s(s2v(blk) »-« s2v(key)) }\n \nvar red = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nvar key = \"Vigenere Cipher!!!\"\n \nsay red\nsay (var black = blacken(red, key))\nsay redden(black, key)\n", "language": "Sidef" }, { "code": "prep := [:s | s select:[:ch | ch isLetter] thenCollect:[:ch | ch asUppercase]].\nencrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:((cypher at:((i-1)\\\\key size+1))-$A) ]].\ndecrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:26-((cypher at:((i-1)\\\\key size+1))-$A) ]].\n", "language": "Smalltalk" }, { "code": "plain := 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'.\ncypher := 'VIGENERECIPHER'.\ncrypted := encrypt value:plain value:cypher.\nplain2 := decrypt value:crypted value:cypher.\n\ncrypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'\nplain2 -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'\n", "language": "Smalltalk" }, { "code": "public func convertToUnicodeScalars(\n str: String,\n minChar: UInt32,\n maxChar: UInt32\n) -> [UInt32] {\n var scalars = [UInt32]()\n\n for scalar in str.unicodeScalars {\n let val = scalar.value\n\n guard val >= minChar && val <= maxChar else {\n continue\n }\n\n scalars.append(val)\n }\n\n return scalars\n}\n\npublic struct Vigenere {\n private let keyScalars: [UInt32]\n private let smallestScalar: UInt32\n private let largestScalar: UInt32\n private let sizeAlphabet: UInt32\n\n public init?(key: String, smallestCharacter: Character = \"A\", largestCharacter: Character = \"Z\") {\n let smallScalars = smallestCharacter.unicodeScalars\n let largeScalars = largestCharacter.unicodeScalars\n\n guard smallScalars.count == 1, largeScalars.count == 1 else {\n return nil\n }\n\n self.smallestScalar = smallScalars.first!.value\n self.largestScalar = largeScalars.first!.value\n self.sizeAlphabet = (largestScalar - smallestScalar) + 1\n\n let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !scalars.isEmpty else {\n return nil\n }\n\n self.keyScalars = scalars\n\n }\n\n public func decrypt(_ str: String) -> String? {\n let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !txtBytes.isEmpty else {\n return nil\n }\n\n var res = \"\"\n\n for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {\n guard let char =\n UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i % keyScalars.count]) % sizeAlphabet &+ smallestScalar)\n else {\n return nil\n }\n\n res += String(char)\n }\n\n return res\n }\n\n public func encrypt(_ str: String) -> String? {\n let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !txtBytes.isEmpty else {\n return nil\n }\n\n var res = \"\"\n\n for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {\n guard let char =\n UnicodeScalar((c &+ keyScalars[i % keyScalars.count] &- 2 &* smallestScalar) % sizeAlphabet &+ smallestScalar)\n else {\n return nil\n }\n\n res += String(char)\n }\n\n return res\n }\n}\n\nlet text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\nlet key = \"VIGENERECIPHER\";\nlet cipher = Vigenere(key: key)!\n\nprint(\"Key: \\(key)\")\nprint(\"Plain Text: \\(text)\")\n\nlet encoded = cipher.encrypt(text.uppercased())!\n\nprint(\"Cipher Text: \\(encoded)\")\n\nlet decoded = cipher.decrypt(encoded)!\n\nprint(\"Decoded: \\(decoded)\")\n\nprint(\"\\nLarger set:\")\n\nlet key2 = \"Vigenère cipher\"\nlet text2 = \"This is a ünicode string 😃\"\n\nlet cipher2 = Vigenere(key: key2, smallestCharacter: \" \", largestCharacter: \"🛹\")!\n\nprint(\"Key: \\(key2)\")\nprint(\"Plain Text: \\(text2)\")\n\nlet encoded2 = cipher2.encrypt(text2)!\n\nprint(\"Cipher Text: \\(encoded2)\")\n\nlet decoded2 = cipher2.decrypt(encoded2)!\n\nprint(\"Decoded: \\(decoded2)\")\n", "language": "Swift" }, { "code": "package require Tcl 8.6\n\noo::class create Vigenere {\n variable key\n constructor {protoKey} {\n\tforeach c [split $protoKey \"\"] {\n\t if {[regexp {[A-Za-z]} $c]} {\n\t\tlappend key [scan [string toupper $c] %c]\n\t }\n\t}\n }\n\n method encrypt {text} {\n\tset out \"\"\n\tset j 0\n\tforeach c [split $text \"\"] {\n\t if {[regexp {[^a-zA-Z]} $c]} continue\n\t scan [string toupper $c] %c c\n\t append out [format %c [expr {($c+[lindex $key $j]-130)%26+65}]]\n\t set j [expr {($j+1) % [llength $key]}]\n\t}\n\treturn $out\n }\n\n method decrypt {text} {\n\tset out \"\"\n\tset j 0\n\tforeach c [split $text \"\"] {\n\t if {[regexp {[^A-Z]} $c]} continue\n\t scan $c %c c\n\t append out [format %c [expr {($c-[lindex $key $j]+26)%26+65}]]\n\t set j [expr {($j+1) % [llength $key]}]\n\t}\n\treturn $out\n }\n}\n", "language": "Tcl" }, { "code": "set cypher [Vigenere new \"Vigenere Cipher\"]\nset original \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nset encrypted [$cypher encrypt $original]\nset decrypted [$cypher decrypt $encrypted]\nputs $original\nputs \"Encrypted: $encrypted\"\nputs \"Decrypted: $decrypted\"\n", "language": "Tcl" }, { "code": "@(next :args)\n@(do\n (defun vig-op (plus-or-minus)\n (op + #\\A [mod [plus-or-minus (- @1 #\\A) (- @2 #\\A)] 26]))\n\n (defun vig (msg key encrypt)\n (mapcar (vig-op [if encrypt + -]) msg (repeat key))))\n@(coll)@{key /[A-Za-z]/}@(end)\n@(coll)@{msg /[A-Za-z]/}@(end)\n@(cat key \"\")\n@(filter :upcase key)\n@(cat msg \"\")\n@(filter :upcase msg)\n@(bind encoded @(vig msg key t))\n@(bind decoded @(vig msg key nil))\n@(bind check @(vig encoded key nil))\n@(output)\ntext: @msg\nkey: @key\nenc: @encoded\ndec: @decoded\ncheck: @check\n@(end)\n", "language": "TXR" }, { "code": "class Vigenere {\n\n key: string\n\n /** Create new cipher based on key */\n constructor(key: string) {\n this.key = Vigenere.formatText(key)\n }\n\n /** Enrypt a given text using key */\n encrypt(plainText: string): string {\n return Array.prototype.map.call(Vigenere.formatText(plainText), (letter: string, index: number): string => {\n return String.fromCharCode((letter.charCodeAt(0) + this.key.charCodeAt(index % this.key.length) - 130) % 26 + 65)\n }).join('')\n }\n\n /** Decrypt ciphertext based on key */\n decrypt(cipherText: string): string {\n return Array.prototype.map.call(Vigenere.formatText(cipherText), (letter: string, index: number): string => {\n return String.fromCharCode((letter.charCodeAt(0) - this.key.charCodeAt(index % this.key.length) + 26) % 26 + 65)\n }).join('')\n }\n\n /** Converts to uppercase and removes non characters */\n private static formatText(text: string): string {\n return text.toUpperCase().replace(/[^A-Z]/g, \"\")\n }\n\n}\n\n/** Example usage */\n(() => {\n let original: string = \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\"\n\n console.log(`Original: ${original}`)\n\n let vig: Vigenere = new Vigenere(\"vigenere\")\n\n let encoded: string = vig.encrypt(original)\n\n console.log(`After encryption: ${encoded}`)\n\n let back: string = vig.decrypt(encoded)\n\n console.log(`After decryption: ${back}`)\n\n})()\n", "language": "TypeScript" }, { "code": "const\n(\n\tkey = \"VIGENERECIPHER\"\n\ttext = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n)\n\nfn main() {\n\tencoded := vigenere(text, key, true)\n\tprintln(encoded)\n\tdecoded := vigenere(encoded, key, false)\n\tprintln(decoded)\n}\n\nfn vigenere(str string, key string, encrypt bool) string {\n\tmut txt :=''\n\tmut chr_arr := []u8{}\n\tmut kidx, mut cidx := 0, 0\n\tif encrypt == true {txt = str.to_upper()}\n\telse {txt = str}\n\tfor chr in txt {\n\t\tif (chr > 64 && chr < 91) == false {continue}\n\t\tif encrypt == true {cidx = (chr + key[kidx] - 130) % 26}\n\t\telse {cidx = (chr - key[kidx] + 26) % 26}\n\t\tchr_arr << u8(cidx + 65)\n\t\tkidx = (kidx + 1) % key.len\n\t}\n\treturn chr_arr.bytestr()\n}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nSub test()\nDim Encryp As String\n Encryp = Vigenere(\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", \"vigenerecipher\", True)\n Debug.Print \"Encrypt:= \"\"\" & Encryp & \"\"\"\"\n Debug.Print \"Decrypt:= \"\"\" & Vigenere(Encryp, \"vigenerecipher\", False) & \"\"\"\"\nEnd Sub\n\nPrivate Function Vigenere(sWord As String, sKey As String, Enc As Boolean) As String\nDim bw() As Byte, bk() As Byte, i As Long, c As Long\nConst sW As String = \"ÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ\"\nConst sWo As String = \"AAAAACEEEEIIIINOOOOOUUUUY\"\nConst A As Long = 65\nConst N As Long = 26\n\n c = Len(sKey)\n i = Len(sWord)\n sKey = Left(IIf(c < i, StrRept(sKey, (i / c) + 1), sKey), i)\n sKey = StrConv(sKey, vbUpperCase) 'Upper case\n sWord = StrConv(sWord, vbUpperCase)\n sKey = StrReplace(sKey, sW, sWo) 'Replace accented characters\n sWord = StrReplace(sWord, sW, sWo)\n sKey = RemoveChars(sKey) 'Remove characters (numerics, spaces, comas, ...)\n sWord = RemoveChars(sWord)\n bk = CharToAscii(sKey) 'To work with Bytes instead of String\n bw = CharToAscii(sWord)\n For i = LBound(bw) To UBound(bw)\n Vigenere = Vigenere & Chr((IIf(Enc, ((bw(i) - A) + (bk(i) - A)), ((bw(i) - A) - (bk(i) - A)) + N) Mod N) + A)\n Next i\nEnd Function\n\nPrivate Function StrRept(s As String, N As Long) As String\nDim j As Long, c As String\n For j = 1 To N\n c = c & s\n Next\n StrRept = c\nEnd Function\n\nPrivate Function StrReplace(s As String, What As String, By As String) As String\nDim t() As String, u() As String, i As Long\n t = SplitString(What)\n u = SplitString(By)\n StrReplace = s\n For i = LBound(t) To UBound(t)\n StrReplace = Replace(StrReplace, t(i), u(i))\n Next i\nEnd Function\n\nPrivate Function SplitString(s As String) As String()\n SplitString = Split(StrConv(s, vbUnicode), Chr(0))\nEnd Function\n\nPrivate Function RemoveChars(str As String) As String\nDim b() As Byte, i As Long\n b = CharToAscii(str)\n For i = LBound(b) To UBound(b)\n If b(i) >= 65 And b(i) <= 90 Then RemoveChars = RemoveChars & Chr(b(i))\n Next i\nEnd Function\n\nPrivate Function CharToAscii(s As String) As Byte()\n CharToAscii = StrConv(s, vbFromUnicode)\nEnd Function\n", "language": "VBA" }, { "code": "Function Encrypt(text,key)\n\ttext = OnlyCaps(text)\n\tkey = OnlyCaps(key)\n\tj = 1\n\tFor i = 1 To Len(text)\n\t\tms = Mid(text,i,1)\n\t\tm = Asc(ms) - Asc(\"A\")\n\t\tks = Mid(key,j,1)\n\t\tk = Asc(ks) - Asc(\"A\")\n\t\tj = (j Mod Len(key)) + 1\n\t\tc = (m + k) Mod 26\n\t\tc = Chr(Asc(\"A\")+c)\n\t\tEncrypt = Encrypt & c\n\tNext\nEnd Function\n\nFunction Decrypt(text,key)\n\tkey = OnlyCaps(key)\n\tj = 1\n\tFor i = 1 To Len(text)\n\t\tms = Mid(text,i,1)\n\t\tm = Asc(ms) - Asc(\"A\")\n\t\tks = Mid(key,j,1)\n\t\tk = Asc(ks) - Asc(\"A\")\n\t\tj = (j Mod Len(key)) + 1\n\t\tc = (m - k + 26) Mod 26\n\t\tc = Chr(Asc(\"A\")+c)\n\t\tDecrypt = Decrypt & c\n\tNext\nEnd Function\n\nFunction OnlyCaps(s)\n\tFor i = 1 To Len(s)\n\t\tchar = UCase(Mid(s,i,1))\n\t\tIf Asc(char) >= 65 And Asc(char) <= 90 Then\n\t\t\tOnlyCaps = OnlyCaps & char\n\t\tEnd If\n\tNext\nEnd Function\n\n'testing the functions\norig_text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\norig_key = \"vigenerecipher\"\nWScript.StdOut.WriteLine \"Original: \" & orig_text\nWScript.StdOut.WriteLine \"Key: \" & orig_key\nWScript.StdOut.WriteLine \"Encrypted: \" & Encrypt(orig_text,orig_key)\nWScript.StdOut.WriteLine \"Decrypted: \" & Decrypt(Encrypt(orig_text,orig_key),orig_key)\n", "language": "VBScript" }, { "code": "'vigenere cypher\noption explicit\nconst asca =65 'ascii(a)\n\nfunction filter(s)\n with new regexp\n .pattern=\"[^A-Z]\"\n .global=1\n filter=.replace(ucase(s),\"\")\n end with\nend function\n\nfunction vigenere (s,k,sign)\ndim s1,i,a,b\n for i=0 to len(s)-1\n a=asc(mid(s,i+1,1))-asca\n b=sign * (asc(mid(k,(i mod len(k))+1,1))-asca)\n s1=s1 & chr(((a+b+26) mod 26) +asca)\n next\n vigenere=s1\nend function\n\nfunction encrypt(s,k): encrypt=vigenere(s,k,1) :end function\nfunction decrypt(s,k): decrypt=vigenere(s,k,-1) :end function\n\n'test--------------------------\ndim plaintext,filtered,key,encoded\nkey=\"VIGENERECYPHER\"\nplaintext = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nfiltered= filter(plaintext)\nwscript.echo filtered\nencoded=encrypt(filtered,key)\nwscript.echo encoded\nwscript.echo decrypt(encoded,key)\n", "language": "VBScript" }, { "code": "Get_Input(10, \"Key: \", STATLINE+NOCR)\t\t// @10 = key\nReg_Copy_Block(11, Cur_Pos, EOL_Pos)\t\t// @11 = copy of original text\nEOL Ins_Newline\nIns_Text(\"Key = \") Reg_Ins(10) Ins_Newline\n\n// Prepare the key into numeric registers #130..:\nBuf_Switch(Buf_Free)\nReg_Ins(10)\nCase_Upper_Block(0, Cur_Pos)\nBOF\n#2 = Reg_Size(10)\t\t\t\t// #2 = key length\nfor (#3=130; #3 < 130+#2; #3++) {\n #@3 = Cur_Char\n Char(1)\n}\nBuf_Quit(OK)\n\nIns_Text(\"Encrypted: \")\n#4 = Cur_Pos\nReg_Ins(11)\t\t\t\t\t// copy of original text\nReplace_Block(\"|!|A\", \"\", #4, EOL_Pos, BEGIN+ALL+NOERR) // remove non-alpha chars\nCase_Upper_Block(#4, EOL_Pos)\t\t\t// convert to upper case\nGoto_Pos(#4)\n#1 = 1; Call(\"ENCRYPT_DECRYPT\")\t\t\t// Encrypt the line\nReg_Copy_Block(11, #4, Cur_Pos)\t\t\t// Copy encrypted text text to next line\nIns_Newline\nIns_Text(\"Decrypted: \")\nReg_Ins(11, BEGIN)\n#1 = -1; Call(\"ENCRYPT_DECRYPT\")\t\t// Decrypt the line\n\nReturn\n\n// Encrypt or decrypt text on current line in-place, starting from cursor position.\n// in: #1 = direction (1=encrypt, -1=decrypt)\n// #2 = key length, #130...#189 = the key\n//\n:ENCRYPT_DECRYPT:\n Num_Push(6,9)\n #6 = 0\n While (!At_EOL) {\n #7 = #6+130\t\t\t\t// pointer to key array\n #8 = #@7\t\t\t\t\t// get key character\n #9 = (Cur_Char + #8*#1 + 26) % 26 + 'A'\t// decrypt/encrypt\n Ins_Char(#9, OVERWRITE)\t\t\t// write the converted char\n #6 = (#6+1) % #2\n }\n Num_Pop(6,9)\nReturn\n", "language": "Vedit-macro-language" }, { "code": "import \"./str\" for Char, Str\n\nvar vigenere = Fn.new { |text, key, encrypt|\n var t = encrypt ? Str.upper(text) : text\n var sb = \"\"\n var ki = 0\n for (c in t) {\n if (Char.isAsciiUpper(c)) {\n var ci = encrypt ? (c.bytes[0] + key[ki].bytes[0] - 130) % 26 :\n (c.bytes[0] - key[ki].bytes[0] + 26) % 26\n sb = sb + Char.fromCode(ci + 65)\n ki = (ki + 1) % key.count\n }\n }\n return sb\n}\n\nvar key = \"VIGENERECIPHER\"\nvar text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nvar encoded = vigenere.call(text, key, true)\nSystem.print(encoded)\nvar decoded = vigenere.call(encoded, key, false)\nSystem.print(decoded)\n", "language": "Wren" }, { "code": "code ChIn=7, ChOut=8;\nint Neg, C, Len, I, Key;\nchar KeyWord(80);\n[Neg:= false; \\skip to KEYWORD\nrepeat C:= ChIn(8); if C=^- then Neg:= true; until C>=^A & C<=^Z;\nLen:= 0; \\read in KEYWORD\nrepeat KeyWord(Len):= C-^A; Len:= Len+1; C:= ChIn(8); until C<^A ! C>^Z;\nI:= 0; \\initialize cycling index\nrepeat C:= ChIn(1);\n if C>=^a & C<=^z then C:= C-$20; \\capitalize\n if C>=^A & C<=^Z then \\discard non-alphas\n [Key:= KeyWord(I); I:= I+1; if I>=Len then I:= 0;\n if Neg then Key:= -Key; \\decrypting?\n C:= C+Key;\n if C>^Z then C:= C-26\n else if C<^A then C:= C+26;\n ChOut(0, C);\n ];\nuntil C=$1A; \\EOF\nChOut(0, $1A); \\encrypted file must end with EOF otherwise the decode will hang\n]\n", "language": "XPL0" }, { "code": "const std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\n", "language": "Zig" }, { "code": "const Vigenere = enum {\n encode,\n decode,\n};\n", "language": "Zig" }, { "code": "pub fn main() anyerror!void {\n // ------------------------------------------ allocator\n var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n defer {\n const ok = gpa.deinit();\n std.debug.assert(ok == .ok);\n }\n const allocator = gpa.allocator();\n // --------------------------------------------- stdout\n const stdout = std.io.getStdOut().writer();\n // ----------------------------------------------------\n const key = \"VIGENERECIPHER\";\n const text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n\n const encoded = try vigenere(allocator, text, key, .encode);\n defer allocator.free(encoded);\n try stdout.print(\"{s}\\n\", .{encoded});\n\n const decoded = try vigenere(allocator, encoded, key, .decode);\n defer allocator.free(decoded);\n try stdout.print(\"{s}\\n\", .{decoded});\n}\n", "language": "Zig" }, { "code": "/// Caller owns the returned slice memory.\nfn vigenere(allocator: Allocator, text: []const u8, key: []const u8, mode: Vigenere) Allocator.Error![]u8 {\n var dynamic_string = std.ArrayList(u8).init(allocator);\n var key_index: usize = 0;\n for (text) |letter| {\n const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;\n if (std.ascii.isUpper(c)) {\n const k = key[key_index];\n const n = switch (mode) {\n .encode => ((c - 'A') + (k - 'A')),\n .decode => 26 + c - k,\n };\n try dynamic_string.append(n % 26 + 'A'); // A-Z\n key_index += 1;\n key_index %= key.len;\n }\n }\n return dynamic_string.toOwnedSlice();\n}\n", "language": "Zig" }, { "code": "fcn encipher(src,key,is_encode){\n upperCase:=[\"A\"..\"Z\"].pump(String);\n src=src.toUpper().inCommon(upperCase); // only uppercase\n key=key.toUpper().inCommon(upperCase).pump(List,\"toAsc\");\n\n const A=\"A\".toAsc();\n klen:=Walker.cycle(key.len()); // 0,1,2,3,..,keyLen-1,0,1,2,3, ...\n src.pump(String,'wrap(c){ i:=klen.next(); c=c.toAsc();\n (A + ( if(is_encode) c - A + key[i] - A;\n \t else\t c - key[i] + 26 ) % 26).toChar()\n });\n}\n", "language": "Zkl" }, { "code": "str := \"Beware the Jabberwock, my son! The jaws that bite, \"\n \"the claws that catch!\";\nkey := \"Vigenere Cipher\";\n\nprintln(\"Text: \", str);\nprintln(\"key: \", key);\n\ncod := encipher(str, key, True); println(\"Code: \", cod);\ndec := encipher(cod, key, False); println(\"Back: \", dec);\n", "language": "Zkl" } ]
Vigen-re-cipher
[ { "code": "---\ncategory:\n- Encryption\nfrom: http://rosettacode.org/wiki/Vigenère_cipher/Cryptanalysis\nnote: Encryption\n", "language": "00-META" }, { "code": "Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See [[wp:Vigenère_cipher#Cryptanalysis|the Wikipedia entry]] for more information. Use the following encrypted text:\n<pre>\nMOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\n</pre>\n\nLetter frequencies for English can be found [[wp:Letter_frequency|here]].\n\nSpecifics for this task:\n* Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace.\n* Assume the plaintext is written in English.\n* Find and output the key.\n* Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional.\n* The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.\n\n", "language": "00-TASK" }, { "code": "-V ascii_uppercase = Array(‘A’..‘Z’)\n\nF vigenere_decrypt(target_freqs, input)\n V nchars = :ascii_uppercase.len\n V ordA = ‘A’.code\n V sorted_targets = sorted(target_freqs)\n\n F frequency(input)\n V result = :ascii_uppercase.map(c -> (c, 0.0))\n L(c) input\n result[c - @ordA][1]++\n R result\n\n F correlation(input)\n V result = 0.0\n V freq = sorted(@frequency(input), key' a -> a[1])\n\n L(f) freq\n result += f[1] * @sorted_targets[L.index]\n R result\n\n V cleaned = input.uppercase().filter(c -> c.is_uppercase()).map(c -> c.code)\n V best_len = 0\n V best_corr = -100.0\n\n L(i) 2 .< cleaned.len I/ 20\n V pieces = [[Int]()] * i\n L(c) cleaned\n pieces[L.index % i].append(c)\n V corr = -0.5 * i + sum(pieces.map(p -> @correlation(p)))\n\n I corr > best_corr\n best_len = i\n best_corr = corr\n\n I best_len == 0\n R (‘Text is too short to analyze’, ‘’)\n\n V pieces = [[Int]()] * best_len\n L(c) cleaned\n pieces[L.index % best_len].append(c)\n\n V freqs = pieces.map(p -> @frequency(p))\n\n V key = ‘’\n L(fr_) freqs\n V fr = sorted(fr_, key' a -> a[1], reverse' 1B)\n V m = 0\n V max_corr = 0.0\n L(j) 0 .< nchars\n V corr = 0.0\n V c = ordA + j\n L(frc) fr\n V d = (frc[0].code - c + nchars) % nchars\n corr += frc[1] * target_freqs[d]\n\n I corr > max_corr\n m = j\n max_corr = corr\n\n key ‘’= Char(code' m + ordA)\n\n V r = (enumerate(cleaned).map((i, c) -> Char(code' (c - @key[i % @best_len].code + @nchars) % @nchars + @ordA)))\n R (key, r.join(‘’))\n\nV encoded = ‘\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK’\n\nV english_frequences = [\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\nV (key, decoded) = vigenere_decrypt(english_frequences, encoded)\nprint(‘Key: ’key)\nprint(\"\\nText: \"decoded)\n", "language": "11l" }, { "code": "with Ada.Text_IO;\n\nprocedure Vignere_Cryptanalysis is\n\n subtype Letter is Character range 'A' .. 'Z';\n\n function \"+\"(X, Y: Letter) return Letter is\n begin\n return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))\n + (Character'Pos(Y)-Character'Pos('A')) ) mod 26\n + Character'Pos('A'));\n end;\n\n function \"-\"(X, Y: Letter) return Letter is\n begin\n return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))\n - (Character'Pos(Y)-Character'Pos('A')) ) mod 26\n + Character'Pos('A'));\n end;\n\n type Frequency_Array is array (Letter) of Float;\n\n English: Frequency_Array :=\n ( 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 );\n\n function Get_Frequency(S: String) return Frequency_Array is\n Result: Frequency_Array := (others => 0.0);\n Offset: Float := 1.0/Float(S'Length);\n begin\n for I in S'Range loop\n if S(I) in Letter then\n Result(S(I)) := Result(S(I)) + Offset;\n end if;\n end loop;\n return Result;\n end Get_Frequency;\n\n function Remove_Whitespace(S: String) return String is\n begin\n if S=\"\" then\n return \"\";\n elsif S(S'First) in Letter then\n return S(S'First) & Remove_Whitespace(S(S'First+1 .. S'Last));\n else\n return Remove_Whitespace(S(S'First+1 .. S'Last));\n end if;\n end Remove_Whitespace;\n\n function Distance(A, B: Frequency_Array;\n Offset: Character := 'A') return Float is\n Result: Float := 0.0;\n Diff: Float;\n begin\n for C in A'Range loop\n Diff := A(C+Offset) - B(C);\n Result := Result + (Diff * Diff);\n end loop;\n return Result;\n end Distance;\n\n function Find_Key(Cryptogram: String; Key_Length: Positive) return String is\n\n function Find_Caesar_Key(S: String) return Letter is\n Frequency: Frequency_Array := Get_Frequency(S);\n Candidate: Letter := 'A'; -- a fake candidate\n Candidate_Dist : Float := Distance(Frequency, English, 'A');\n New_Dist: Float;\n\n begin\n\n for L in Letter range 'B' .. 'Z' loop\n New_Dist := Distance(Frequency, English, L);\n if New_Dist <= Candidate_Dist then\n Candidate_Dist := New_Dist;\n Candidate := L;\n end if;\n end loop;\n return Candidate;\n end Find_Caesar_Key;\n\n function Get_Slide(S: String; Step: Positive) return String is\n begin\n if S'Length= 0 then\n return \"\";\n else\n return S(S'First) & Get_Slide(S(S'First+Step .. S'Last), Step);\n end if;\n end Get_Slide;\n\n Key: String(1 .. Key_Length);\n\n S: String renames Cryptogram;\n\n begin\n for I in Key'Range loop\n Key(I) := Find_Caesar_Key(Get_Slide(S(S'First+I-1 .. S'Last),\n Key_Length));\n end loop;\n return Key;\n end Find_Key;\n\n function Key_Char(Key: String; Index: Positive) return Letter is\n begin\n if Index > Key'Last then\n return Key_Char(Key, Index-Key'Last);\n else\n return Key(Index);\n end if;\n end Key_Char;\n\n Ciphertext: String := Remove_Whitespace(\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" &\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" &\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" &\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" &\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" &\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" &\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" &\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" &\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" &\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" &\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" &\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" &\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" &\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" &\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" &\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" &\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\");\n\n Best_Plain: String := Ciphertext;\n Best_Dist: Float := Distance(English, Get_Frequency(Best_Plain));\n Best_Key: String := Ciphertext;\n Best_Key_L: Natural := 0;\n\nbegin -- Vignere_Cryptanalysis\n for I in 1 .. Ciphertext'Length/10 loop\n declare\n Key: String(1 .. I) := Find_Key(Ciphertext, I);\n Plaintext: String(Ciphertext'Range);\n begin\n for I in Ciphertext'Range loop\n Plaintext(I) := Ciphertext(I) - Key_Char(Key, I);\n end loop;\n if Distance(English, Get_Frequency(Plaintext)) < Best_Dist then\n Best_Plain := Plaintext;\n Best_Dist := Distance(English, Get_Frequency(Plaintext));\n Best_Key(1 .. I) := Key;\n Best_Key_L := I;\n if Best_dist < 0.01 then\n declare\n use Ada.Text_IO;\n begin\n Put_Line(\"Key =\" & Best_Key(1 .. Best_Key_L));\n Put_Line(\"Distance = \" & Float'Image(Best_Dist));\n New_Line;\n Put_Line(\"Plaintext =\");\n Put_Line(Best_Plain);\n New_Line; New_Line;\n end;\n end if;\n end if;\n end;\n end loop;\nend Vignere_Cryptanalysis;\n", "language": "Ada" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst double freq[] = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\nint best_match(const double *a, const double *b) {\n double sum = 0, fit, d, best_fit = 1e100;\n int i, rotate, best_rotate = 0;\n for (i = 0; i < 26; i++)\n sum += a[i];\n for (rotate = 0; rotate < 26; rotate++) {\n fit = 0;\n for (i = 0; i < 26; i++) {\n d = a[(i + rotate) % 26] / sum - b[i];\n fit += d * d / b[i];\n }\n\n if (fit < best_fit) {\n best_fit = fit;\n best_rotate = rotate;\n }\n }\n\n return best_rotate;\n}\n\ndouble freq_every_nth(const int *msg, int len, int interval, char *key) {\n double sum, d, ret;\n double out[26], accu[26] = {0};\n int i, j, rot;\n\n for (j = 0; j < interval; j++) {\n for (i = 0; i < 26; i++)\n out[i] = 0;\n for (i = j; i < len; i += interval)\n out[msg[i]]++;\n key[j] = rot = best_match(out, freq);\n key[j] += 'A';\n for (i = 0; i < 26; i++)\n accu[i] += out[(i + rot) % 26];\n }\n\n for (i = 0, sum = 0; i < 26; i++)\n sum += accu[i];\n\n for (i = 0, ret = 0; i < 26; i++) {\n d = accu[i] / sum - freq[i];\n ret += d * d / freq[i];\n }\n\n key[interval] = '\\0';\n return ret;\n}\n\nint main() {\n int txt[strlen(encoded)];\n int len = 0, j;\n char key[100];\n double fit, best_fit = 1e100;\n\n for (j = 0; encoded[j] != '\\0'; j++)\n if (isupper(encoded[j]))\n txt[len++] = encoded[j] - 'A';\n\n for (j = 1; j < 30; j++) {\n fit = freq_every_nth(txt, len, j, key);\n printf(\"%f, key length: %2d, %s\", fit, j, key);\n if (fit < best_fit) {\n best_fit = fit;\n printf(\" <--- best so far\");\n }\n printf(\"\\n\");\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <array>\nusing namespace std;\n\ntypedef array<pair<char, double>, 26> FreqArray;\n\nclass VigenereAnalyser\n{\nprivate:\n array<double, 26> targets;\n array<double, 26> sortedTargets;\n FreqArray freq;\n\n // Update the freqs array\n FreqArray& frequency(const string& input)\n {\n for (char c = 'A'; c <= 'Z'; ++c)\n freq[c - 'A'] = make_pair(c, 0);\n\n for (size_t i = 0; i < input.size(); ++i)\n freq[input[i] - 'A'].second++;\n\n return freq;\n }\n\n double correlation(const string& input)\n {\n double result = 0.0;\n frequency(input);\n\n sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool\n { return u.second < v.second; });\n\n for (size_t i = 0; i < 26; ++i)\n result += freq[i].second * sortedTargets[i];\n\n return result;\n }\n\npublic:\n VigenereAnalyser(const array<double, 26>& targetFreqs)\n {\n targets = targetFreqs;\n sortedTargets = targets;\n sort(sortedTargets.begin(), sortedTargets.end());\n }\n\n pair<string, string> analyze(string input)\n {\n string cleaned;\n for (size_t i = 0; i < input.size(); ++i)\n {\n if (input[i] >= 'A' && input[i] <= 'Z')\n cleaned += input[i];\n else if (input[i] >= 'a' && input[i] <= 'z')\n cleaned += input[i] + 'A' - 'a';\n }\n\n size_t bestLength = 0;\n double bestCorr = -100.0;\n\n // Assume that if there are less than 20 characters\n // per column, the key's too long to guess\n for (size_t i = 2; i < cleaned.size() / 20; ++i)\n {\n vector<string> pieces(i);\n for (size_t j = 0; j < cleaned.size(); ++j)\n pieces[j % i] += cleaned[j];\n\n // The correlation increases artificially for smaller\n // pieces/longer keys, so weigh against them a little\n double corr = -0.5*i;\n for (size_t j = 0; j < i; ++j)\n corr += correlation(pieces[j]);\n\n if (corr > bestCorr)\n {\n bestLength = i;\n bestCorr = corr;\n }\n }\n\n if (bestLength == 0)\n return make_pair(\"Text is too short to analyze\", \"\");\n\n vector<string> pieces(bestLength);\n for (size_t i = 0; i < cleaned.size(); ++i)\n pieces[i % bestLength] += cleaned[i];\n\n vector<FreqArray> freqs;\n for (size_t i = 0; i < bestLength; ++i)\n freqs.push_back(frequency(pieces[i]));\n\n string key = \"\";\n for (size_t i = 0; i < bestLength; ++i)\n {\n sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool\n { return u.second > v.second; });\n\n size_t m = 0;\n double mCorr = 0.0;\n for (size_t j = 0; j < 26; ++j)\n {\n double corr = 0.0;\n char c = 'A' + j;\n for (size_t k = 0; k < 26; ++k)\n {\n int d = (freqs[i][k].first - c + 26) % 26;\n corr += freqs[i][k].second * targets[d];\n }\n\n if (corr > mCorr)\n {\n m = j;\n mCorr = corr;\n }\n }\n\n key += m + 'A';\n }\n\n string result = \"\";\n for (size_t i = 0; i < cleaned.size(); ++i)\n result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';\n\n return make_pair(result, key);\n }\n};\n\nint main()\n{\n string input =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\"\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\"\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\"\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\"\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\"\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\"\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\"\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\"\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\"\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\"\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\"\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\"\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\"\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\"\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\"\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\"\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\n array<double, 26> english = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,\n 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,\n 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,\n 0.01974, 0.00074};\n\n VigenereAnalyser va(english);\n pair<string, string> output = va.analyze(input);\n\n cout << \"Key: \" << output.second << endl << endl;\n cout << \"Text: \" << output.first << endl;\n}\n", "language": "C++" }, { "code": "import std.stdio, std.algorithm, std.typecons, std.string,\n std.array, std.numeric, std.ascii;\n\nstring[2] vigenereDecrypt(in double[] targetFreqs, in string input) {\n enum nAlpha = std.ascii.uppercase.length;\n\n static double correlation(in string txt, in double[] sTargets)\n pure nothrow /*@safe*/ @nogc {\n uint[nAlpha] charCounts = 0;\n foreach (immutable c; txt)\n charCounts[c - 'A']++;\n return charCounts[].sort().release.dotProduct(sTargets);\n }\n\n static frequency(in string txt) pure nothrow @safe {\n auto freqs = new Tuple!(char,\"c\", uint,\"d\")[nAlpha];\n foreach (immutable i, immutable c; std.ascii.uppercase)\n freqs[i] = tuple(c, 0);\n foreach (immutable c; txt)\n freqs[c - 'A'].d++;\n return freqs;\n }\n\n static string[2] decode(in string cleaned, in string key)\n pure nothrow @safe {\n assert(!key.empty);\n string decoded;\n foreach (immutable i, immutable c; cleaned)\n decoded ~= (c - key[i % $] + nAlpha) % nAlpha + 'A';\n return [key, decoded];\n }\n\n static size_t findBestLength(in string cleaned,\n in double[] sTargets)\n pure nothrow /*@safe*/ {\n size_t bestLength;\n double bestCorr = -100.0;\n\n // Assume that if there are less than 20 characters\n // per column, the key's too long to guess\n foreach (immutable i; 2 .. cleaned.length / 20) {\n auto pieces = new Appender!string[i];\n foreach (immutable j, immutable c; cleaned)\n pieces[j % i] ~= c;\n\n // The correlation seems to increase for smaller\n // pieces/longer keys, so weigh against them a little\n double corr = -0.5 * i;\n foreach (const p; pieces)\n corr += correlation(p.data, sTargets);\n\n if (corr > bestCorr) {\n bestLength = i;\n bestCorr = corr;\n }\n }\n\n return bestLength;\n }\n\n static string findKey(in string cleaned, in size_t bestLength,\n in double[] targetFreqs) pure nothrow @safe {\n auto pieces = new string[bestLength];\n foreach (immutable i, immutable c; cleaned)\n pieces[i % bestLength] ~= c;\n\n string key;\n foreach (fr; pieces.map!frequency) {\n fr.sort!q{ a.d > b.d };\n\n size_t m;\n double maxCorr = 0.0;\n foreach (immutable j, immutable c; uppercase) {\n double corr = 0.0;\n foreach (immutable frc; fr) {\n immutable di = (frc.c - c + nAlpha) % nAlpha;\n corr += frc.d * targetFreqs[di];\n }\n\n if (corr > maxCorr) {\n m = j;\n maxCorr = corr;\n }\n }\n\n key ~= m + 'A';\n }\n\n return key;\n }\n\n immutable cleaned = input.toUpper.removechars(\"^A-Z\");\n\n //immutable sortedTargets = targetFreqs.sorted;\n immutable sortedTargets = targetFreqs.dup.sort().release.idup;\n\n immutable bestLength = findBestLength(cleaned, sortedTargets);\n if (bestLength == 0)\n throw new Exception(\"Text is too short to analyze.\");\n\n immutable string key = findKey(cleaned, bestLength, targetFreqs);\n return decode(cleaned, key);\n}\n\n\nvoid main() {\n immutable encoded = \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG\nJSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF\nWHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA\nLWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV\nRHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF\nXJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA\nALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ\nAALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA\nGWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY\nIMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV\nYOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV\nGJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO\nZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML\nZZRXJ EKAHV FASMU LVVUT TGK\";\n\n immutable englishFrequences = [0.08167, 0.01492, 0.02782, 0.04253,\n 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772,\n 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,\n 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974,\n 0.00074];\n\n immutable key_dec = vigenereDecrypt(englishFrequences, encoded);\n writefln(\"Key: %s\\n\\nText: %s\", key_dec[0], key_dec[1]);\n}\n", "language": "D" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [26]float64{\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n}\n\nfunc sum(a []float64) (sum float64) {\n for _, f := range a {\n sum += f\n }\n return\n}\n\nfunc bestMatch(a []float64) int {\n sum := sum(a)\n bestFit, bestRotate := 1e100, 0\n for rotate := 0; rotate < 26; rotate++ {\n fit := 0.0\n for i := 0; i < 26; i++ {\n d := a[(i+rotate)%26]/sum - freq[i]\n fit += d * d / freq[i]\n }\n if fit < bestFit {\n bestFit, bestRotate = fit, rotate\n }\n }\n return bestRotate\n}\n\nfunc freqEveryNth(msg []int, key []byte) float64 {\n l := len(msg)\n interval := len(key)\n out := make([]float64, 26)\n accu := make([]float64, 26)\n for j := 0; j < interval; j++ {\n for k := 0; k < 26; k++ {\n out[k] = 0.0\n }\n for i := j; i < l; i += interval {\n out[msg[i]]++\n }\n rot := bestMatch(out)\n key[j] = byte(rot + 65)\n for i := 0; i < 26; i++ {\n accu[i] += out[(i+rot)%26]\n }\n }\n sum := sum(accu)\n ret := 0.0\n for i := 0; i < 26; i++ {\n d := accu[i]/sum - freq[i]\n ret += d * d / freq[i]\n }\n return ret\n}\n\nfunc decrypt(text, key string) string {\n var sb strings.Builder\n ki := 0\n for _, c := range text {\n if c < 'A' || c > 'Z' {\n continue\n }\n ci := (c - rune(key[ki]) + 26) % 26\n sb.WriteRune(ci + 65)\n ki = (ki + 1) % len(key)\n }\n return sb.String()\n}\n\nfunc main() {\n enc := strings.Replace(encoded, \" \", \"\", -1)\n txt := make([]int, len(enc))\n for i := 0; i < len(txt); i++ {\n txt[i] = int(enc[i] - 'A')\n }\n bestFit, bestKey := 1e100, \"\"\n fmt.Println(\" Fit Length Key\")\n for j := 1; j <= 26; j++ {\n key := make([]byte, j)\n fit := freqEveryNth(txt, key)\n sKey := string(key)\n fmt.Printf(\"%f %2d %s\", fit, j, sKey)\n if fit < bestFit {\n bestFit, bestKey = fit, sKey\n fmt.Print(\" <--- best so far\")\n }\n fmt.Println()\n }\n fmt.Println(\"\\nBest key :\", bestKey)\n fmt.Printf(\"\\nDecrypted text:\\n%s\\n\", decrypt(enc, bestKey))\n}\n", "language": "Go" }, { "code": "{-# LANGUAGE TupleSections #-}\nimport Data.List(transpose, nub, sort, maximumBy)\nimport Data.Ord (comparing)\nimport Data.Char (ord)\nimport Data.Map (Map, fromListWith, toList, findWithDefault)\n\naverage :: Fractional a => [a] -> a\naverage as = sum as / fromIntegral (length as)\n\n-- Create a map from each entry in list to the number of occurrences of\n-- that entry in the list.\ncountEntries :: Ord a => [a] -> Map a Int\ncountEntries = fromListWith (+) . fmap (,1)\n\n-- Break a string up into substrings of n chars.\nbreakup :: Int -> [a] -> [[a]]\nbreakup _ [] = []\nbreakup n as =\n let (h, r) = splitAt n as\n in h:breakup n r\n\n-- Dole out elements of a string over a n element distribution.\ndistribute :: [a] -> Int -> [[a]]\ndistribute as n = transpose $ breakup n as\n\n-- The probability that members of a pair of characters taken randomly\n-- from a given string are equal.\ncoincidence :: (Ord a, Fractional b) => [a] -> b\ncoincidence str =\n let charCounts = snd <$> toList (countEntries str)\n strln = length str\n d = fromIntegral $ strln * (strln - 1)\n n = fromIntegral $ sum $ fmap (\\cc -> cc * (cc-1)) charCounts\n in n / d\n\n-- Use the average probablity of coincidence for all the members of\n-- a distribution to rate the distribution - the higher the better.\n-- The correlation increases artificially for smaller\n-- pieces/longer keys, so weigh against them a little\nrate :: (Ord a, Fractional b) => [[a]] -> b\nrate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0\n\n-- Multiply elements of lists together and add up the results.\ndot :: Num a => [a] -> [a] -> a\ndot v0 v1 = sum $ zipWith (*) v0 v1\n\n-- Given two lists of floats, rotate one of them by the number of\n-- characters indicated by letter and then 'dot' them together.\nrotateAndDot :: Num a => [a] -> [a] -> Char -> a\nrotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1))\n\n-- Find decoding offset that results in best match\n-- between actual char frequencies and expected frequencies.\ngetKeyChar :: RealFrac a => [a] -> String -> Char\ngetKeyChar expected sample =\n let charCounts = countEntries sample\n countInSample c = findWithDefault 0 c charCounts\n actual = fmap (fromIntegral . countInSample) ['A'..'Z']\n in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z']\n\nmain = do\n let cr = filter (/=' ') crypt\n -- Assume that if there are less than 20 characters\n -- per column, the key's too long to guess\n distributions = fmap (distribute cr) [1..length cr `div` 20]\n bestDistribution = maximumBy (comparing rate) distributions\n key = fmap (getKeyChar englishFrequencies) bestDistribution\n alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26)\n mapM_ putStrLn [\"Key: \" ++ key, \"Decrypted Text: \" ++ zipWith alphaSum (cycle key) cr]\n\nenglishFrequencies =\n [ 0.08167, 0.01492, 0.02782, 0.04253,\n 0.12702, 0.02228, 0.02015, 0.06094,\n 0.06966, 0.00153, 0.00772, 0.04025,\n 0.02406, 0.06749, 0.07507, 0.01929,\n 0.00095, 0.05987, 0.06327, 0.09056,\n 0.02758, 0.00978, 0.02360, 0.00150,\n 0.01974, 0.00074 ]\n\ncrypt = \"\\\n \\MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\\\n \\VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\\\n \\ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\\\n \\FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\\\n \\ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\\\n \\ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\\\n \\JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\\\n \\LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\\\n \\MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\\\n \\QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\\\n \\RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\\\n \\TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\\\n \\SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\\\n \\ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\\\n \\BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\\\n \\BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\\\n \\FWAML ZZRXJ EKAHV FASMU LVVUT TGK\\\n \\\"\n", "language": "Haskell" }, { "code": "NB. https://en.wikipedia.org/wiki/Kasiski_examination\nkasiski=: {{\n grams=. ({: #\"1~1 < ;@{.)|:(#/.~;\"0~.) g=. 3 <\\ y\n deltas=. ;grams (2 -~/\\ I.@E.)L:0 enc\n {:,{.\\:~(#/.~,.~.)1 -.~,+./~ deltas\n}}\n\nNB. https://en.wikipedia.org/wiki/Letter_frequency\nAZ=: 8 u: 65+i.26\nlfreq=: 0.01*do{{)n\n 8.2 1.5 2.8 4.3 13 2.2 2 6.1 7 0.15\n 0.77 4 2.4 6.7 7.5 1.9 0.095 6 6.3 9.1\n 2.8 0.98 2.4 0.15 2 0.074\n}}-.LF\n\n\ncaesarkey=: {{\n freqs=. (<:#/.~AZ,y)%#y=. y ([-.-.) AZ\n AZ{~(i. <./)lfreq +/&.:*:@:-\"1 (i.26)|.\"0 1 freqs\n}}\nvigenerekey=: {{ caesarkey\"1|:(-kasiski y) ]\\y }}\n\nuncaesar=: {{ 26&|@-&(AZ i.x)&.(AZ&i.) y }}\"0 1\nunvigenere=: {{ ' '-.~,x uncaesar\"0 1&.|:(-#x) ]\\y }}\n", "language": "J" }, { "code": "enc=: {{)n\nMOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\n}}-.LF,' '\n\n vigenerekey enc\nTHECHESHIRECAT\n _80]\\'THECHESHIRECAT' unvigenere enc\nTHISWASTHEPOEMTHATALICEREADJABBERWOCKYTWASBRILLIGANDTHESLITHYTOVESDIDGYREANDGIMB\nLEINTHEWABEALLMIMSYWERETHEBOROGOVESANDTHEMOMERATHSOUTGRABEBEWARETHEJABBERWOCKMYS\nONTHEJAWSTHATBITETHECLAWSTHATCATCHBEWARETHEJUBJUBBIRDANDSHUNTHEFRUMIOUSBANDERSNA\nTCHHETOOKHISVORPALSWORDINHANDLONGTIMETHEMANXOMEFOEHESOUGHTSORESTEDHEBYTHETUMTUMT\nREEANDSTOODAWHILEINTHOUGHTANDASINUFFISHTHOUGHTHESTOODTHEJABBERWOCKWITHEYESOFFLAM\nECAMEWHIFFLINGTHROUGHTHETULGEYWOODANDBURBLEDASITCAMEONETWOONETWOANDTHROUGHANDTHR\nOUGHTHEVORPALBLADEWENTSNICKERSNACKHELEFTITDEADANDWITHITSHEADHEWENTGALUMPHINGBACK\nANDHASTTHOUSLAINTHEJABBERWOCKCOMETOMYARMSMYBEAMISHBOYOFRABJOUSDAYCALLOOHCALLAYHE\nCHORTLEDINHISJOYTWASBRILLIGANDTHESLITHYTOVESDIDGYREANDGIMBLEINTHEWABEALLMIMSYWER\nETHEBOROGOVESANDTHEMOMERATHSOUTGRABEITSEEMSVERYPRETTYSHESAIDWHENSHEHADFINISHEDIT\nBUTITSRATHERHARDTOUNDERSTANDWYTWITSJWYAH\n", "language": "J" }, { "code": "decaesar=: {{\n freqs=. (<:#/.~AZ,y)%#y=. y ([-.-.) AZ\n ndx=. (i. <./)lfreq +/&.:*:@:-\"1 (i.26)|.\"0 1 freqs\n 26&|@-&ndx&.(AZ&i.) y\n}}\ndevigenere=: {{ ' '-.~,decaesar\"1&.|:(-kasiski y) ]\\y }}\n", "language": "J" }, { "code": "public class Vig{\nstatic String encodedMessage =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nfinal static double freq[] = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n};\n\n\npublic static void main(String[] args) {\n int lenghtOfEncodedMessage = encodedMessage.length();\n char[] encoded = new char [lenghtOfEncodedMessage] ;\n char[] key = new char [lenghtOfEncodedMessage] ;\n\n encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);\n int txt[] = new int[lenghtOfEncodedMessage];\n int len = 0, j;\n\n double fit, best_fit = 1e100;\n\n for (j = 0; j < lenghtOfEncodedMessage; j++)\n if (Character.isUpperCase(encoded[j]))\n txt[len++] = encoded[j] - 'A';\n\n for (j = 1; j < 30; j++) {\n fit = freq_every_nth(txt, len, j, key);\n System.out.printf(\"%f, key length: %2d \", fit, j);\n System.out.print(key);\n if (fit < best_fit) {\n best_fit = fit;\n System.out.print(\" <--- best so far\");\n }\n System.out.print(\"\\n\");\n\n }\n}\n\n\n static String decrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n\nstatic int best_match(final double []a, final double []b) {\n double sum = 0, fit, d, best_fit = 1e100;\n int i, rotate, best_rotate = 0;\n for (i = 0; i < 26; i++)\n sum += a[i];\n for (rotate = 0; rotate < 26; rotate++) {\n fit = 0;\n for (i = 0; i < 26; i++) {\n d = a[(i + rotate) % 26] / sum - b[i];\n fit += d * d / b[i];\n }\n\n if (fit < best_fit) {\n best_fit = fit;\n best_rotate = rotate;\n }\n }\n\n return best_rotate;\n}\n\nstatic double freq_every_nth(final int []msg, int len, int interval, char[] key) {\n double sum, d, ret;\n double [] accu = new double [26];\n double [] out = new double [26];\n int i, j, rot;\n\n for (j = 0; j < interval; j++) {\n for (i = 0; i < 26; i++)\n out[i] = 0;\n for (i = j; i < len; i += interval)\n out[msg[i]]++;\n\trot = best_match(out, freq);\n\ttry{\n key[j] = (char)(rot + 'A');\n\t} catch (Exception e) {\n\t\tSystem.out.print(e.getMessage());\n\t}\n for (i = 0; i < 26; i++)\n accu[i] += out[(i + rot) % 26];\n }\n\n for (i = 0, sum = 0; i < 26; i++)\n sum += accu[i];\n\n for (i = 0, ret = 0; i < 26; i++) {\n d = accu[i] / sum - freq[i];\n ret += d * d / freq[i];\n }\n\n key[interval] = '\\0';\n return ret;\n}\n\n}\n", "language": "Java" }, { "code": "# ciphertext block {{{1\nconst ciphertext = filter(isalpha, \"\"\"\nMOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\n\"\"\")\n# }}}\n\n# character frequencies {{{1\nconst letters = Dict{Char, Float32}(\n 'E' => 12.702,\n 'T' => 9.056,\n 'A' => 8.167,\n 'O' => 7.507,\n 'I' => 6.966,\n 'N' => 6.749,\n 'S' => 6.327,\n 'H' => 6.094,\n 'R' => 5.987,\n 'D' => 4.253,\n 'L' => 4.025,\n 'C' => 2.782,\n 'U' => 2.758,\n 'M' => 2.406,\n 'W' => 2.361,\n 'F' => 2.228,\n 'G' => 2.015,\n 'Y' => 1.974,\n 'P' => 1.929,\n 'B' => 1.492,\n 'V' => 0.978,\n 'K' => 0.772,\n 'J' => 0.153,\n 'X' => 0.150,\n 'Q' => 0.095,\n 'Z' => 0.074)\nconst digraphs = Dict{AbstractString, Float32}(\n \"TH\" => 15.2,\n \"HE\" => 12.8,\n \"IN\" => 9.4,\n \"ER\" => 9.4,\n \"AN\" => 8.2,\n \"RE\" => 6.8,\n \"ND\" => 6.3,\n \"AT\" => 5.9,\n \"ON\" => 5.7,\n \"NT\" => 5.6,\n \"HA\" => 5.6,\n \"ES\" => 5.6,\n \"ST\" => 5.5,\n \"EN\" => 5.5,\n \"ED\" => 5.3,\n \"TO\" => 5.2,\n \"IT\" => 5.0,\n \"OU\" => 5.0,\n \"EA\" => 4.7,\n \"HI\" => 4.6,\n \"IS\" => 4.6,\n \"OR\" => 4.3,\n \"TI\" => 3.4,\n \"AS\" => 3.3,\n \"TE\" => 2.7,\n \"ET\" => 1.9,\n \"NG\" => 1.8,\n \"OF\" => 1.6,\n \"AL\" => 0.9,\n \"DE\" => 0.9,\n \"SE\" => 0.8,\n \"LE\" => 0.8,\n \"SA\" => 0.6,\n \"SI\" => 0.5,\n \"AR\" => 0.4,\n \"VE\" => 0.4,\n \"RA\" => 0.4,\n \"LD\" => 0.2,\n \"UR\" => 0.2)\nconst trigraphs = Dict{AbstractString, Float32}(\n \"THE\" => 18.1,\n \"AND\" => 7.3,\n \"ING\" => 7.2,\n \"ION\" => 4.2,\n \"ENT\" => 4.2,\n \"HER\" => 3.6,\n \"FOR\" => 3.4,\n \"THA\" => 3.3,\n \"NTH\" => 3.3,\n \"INT\" => 3.2,\n \"TIO\" => 3.1,\n \"ERE\" => 3.1,\n \"TER\" => 3.0,\n \"EST\" => 2.8,\n \"ERS\" => 2.8,\n \"HAT\" => 2.6,\n \"ATI\" => 2.6,\n \"ATE\" => 2.5,\n \"ALL\" => 2.5,\n \"VER\" => 2.4,\n \"HIS\" => 2.4,\n \"HES\" => 2.4,\n \"ETH\" => 2.4,\n \"OFT\" => 2.2,\n \"STH\" => 2.1,\n \"RES\" => 2.1,\n \"OTH\" => 2.1,\n \"ITH\" => 2.1,\n \"FTH\" => 2.1,\n \"ONT\" => 2.0)\n# 1}}}\n\nfunction decrypt(enc::ASCIIString, key::ASCIIString)\n const enclen = length(enc)\n const keylen = length(key)\n\n if keylen < enclen\n key = (key^(div(enclen - keylen, keylen) + 2))[1:enclen]\n end\n\n msg = Array(Char, enclen)\n\n for i=1:enclen\n msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65)\n end\n\n msg::Array{Char, 1}\nend\n\nfunction cryptanalyze(enc::ASCIIString; maxkeylen::Integer = 20)\n const enclen = length(enc)\n maxkey = \"\"\n maxdec = \"\"\n maxscore = 0.0\n\n for keylen=1:maxkeylen\n key = Array(Char, keylen)\n idx = filter(x -> x % keylen == 0, 1:enclen) - keylen + 1\n\n for i=1:keylen\n maxsubscore = 0.0\n\n for j='A':'Z'\n subscore = 0.0\n\n for k in decrypt(enc[idx], ascii(string(j)))\n subscore += get(letters, k, 0.0)\n end\n\n if subscore > maxsubscore\n maxsubscore = subscore\n key[i] = j\n end\n end\n\n idx += 1\n end\n\n key = join(key)\n const dec = decrypt(enc, key)\n score = 0.0\n\n for i in dec\n score += get(letters, i, 0.0)\n end\n\n for i=1:enclen - 2\n const digraph = string(dec[i], dec[i + 1])\n const trigraph = string(dec[i], dec[i + 1], dec[i + 2])\n\n if haskey(digraphs, digraph)\n score += 2 * get(digraphs, digraph, 0.0)\n end\n\n if haskey(trigraphs, trigraph)\n score += 3 * get(trigraphs, trigraph, 0.0)\n end\n end\n\n if score > maxscore\n maxscore = score\n maxkey = key\n maxdec = dec\n end\n end\n\n (maxkey, join(maxdec))::Tuple{ASCIIString, ASCIIString}\nend\n\nkey, dec = cryptanalyze(ciphertext)\nprintln(\"key: \", key, \"\\n\\n\", dec)\n\n# post-compilation profiling run\ngc()\nt = @elapsed cryptanalyze(ciphertext)\nprintln(\"\\nelapsed time: \", t, \" seconds\")\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nval encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nval freq = doubleArrayOf(\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n)\n\nfun bestMatch(a: DoubleArray): Int {\n val sum = a.sum()\n var bestFit = 1e100\n var bestRotate = 0\n for (rotate in 0..25) {\n var fit = 0.0\n for (i in 0..25) {\n val d = a[(i + rotate) % 26] / sum - freq[i]\n fit += d * d / freq[i]\n }\n if (fit < bestFit) {\n bestFit = fit\n bestRotate = rotate\n }\n }\n return bestRotate\n}\n\nfun freqEveryNth(msg: IntArray, key: CharArray): Double {\n val len = msg.size\n val interval = key.size\n val out = DoubleArray(26)\n val accu = DoubleArray(26)\n for (j in 0 until interval) {\n out.fill(0.0)\n for (i in j until len step interval) out[msg[i]]++\n val rot = bestMatch(out)\n key[j] = (rot + 65).toChar()\n for (i in 0..25) accu[i] += out[(i + rot) % 26]\n }\n val sum = accu.sum()\n var ret = 0.0\n for (i in 0..25) {\n val d = accu[i] / sum - freq[i]\n ret += d * d / freq[i]\n }\n return ret\n}\n\nfun decrypt(text: String, key: String): String {\n val sb = StringBuilder()\n var ki = 0\n for (c in text) {\n if (c !in 'A'..'Z') continue\n val ci = (c.toInt() - key[ki].toInt() + 26) % 26\n sb.append((ci + 65).toChar())\n ki = (ki + 1) % key.length\n }\n return sb.toString()\n}\n\nfun main(args: Array<String>) {\n val enc = encoded.replace(\" \", \"\")\n val txt = IntArray(enc.length) { enc[it] - 'A' }\n var bestFit = 1e100\n var bestKey = \"\"\n val f = \"%f %2d %s\"\n println(\" Fit Length Key\")\n for (j in 1..26) {\n val key = CharArray(j)\n val fit = freqEveryNth(txt, key)\n val sKey = key.joinToString(\"\")\n print(f.format(fit, j, sKey))\n if (fit < bestFit) {\n bestFit = fit\n bestKey = sKey\n print(\" <--- best so far\")\n }\n println()\n }\n println()\n println(\"Best key : $bestKey\")\n println(\"\\nDecrypted text:\\n${decrypt(enc, bestKey)}\")\n}\n", "language": "Kotlin" }, { "code": "import sequtils, strutils, sugar, tables, times\n\nconst\n\n CipherText = \"\"\"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\"\".splitWhitespace.join()\n\n FreqLetters = {'E': 12.702, 'T': 9.056, 'A': 8.167, 'O': 7.507,\n 'I': 6.966, 'N': 6.749, 'S': 6.327, 'H': 6.094,\n 'R': 5.987, 'D': 4.253, 'L': 4.025, 'C': 2.782,\n 'U': 2.758, 'M': 2.406, 'W': 2.361, 'F': 2.228,\n 'G': 2.015, 'Y': 1.974, 'P': 1.929, 'B': 1.492,\n 'V': 0.978, 'K': 0.772, 'J': 0.153, 'X': 0.150,\n 'Q': 0.095, 'Z': 0.074}.toTable\n\n FreqDigraphs = {\"TH\": 15.2, \"HE\": 12.8, \"IN\": 9.4, \"ER\": 9.4,\n \"AN\": 8.2, \"RE\": 6.8, \"ND\": 6.3, \"AT\": 5.9,\n \"ON\": 5.7, \"NT\": 5.6, \"HA\": 5.6, \"ES\": 5.6,\n \"ST\": 5.5, \"EN\": 5.5, \"ED\": 5.3, \"TO\": 5.2,\n \"IT\": 5.0, \"OU\": 5.0, \"EA\": 4.7, \"HI\": 4.6,\n \"IS\": 4.6, \"OR\": 4.3, \"TI\": 3.4, \"AS\": 3.3,\n \"TE\": 2.7, \"ET\": 1.9, \"NG\": 1.8, \"OF\": 1.6,\n \"AL\": 0.9, \"DE\": 0.9, \"SE\": 0.8, \"LE\": 0.8,\n \"SA\": 0.6, \"SI\": 0.5, \"AR\": 0.4, \"VE\": 0.4,\n \"RA\": 0.4, \"LD\": 0.2, \"UR\": 0.2}.toTable\n\n FreqTrigraphs = {\"THE\": 18.1, \"AND\": 7.3, \"ING\": 7.2, \"ION\": 4.2,\n \"ENT\": 4.2, \"HER\": 3.6, \"FOR\": 3.4, \"THA\": 3.3,\n \"NTH\": 3.3, \"INT\": 3.2, \"TIO\": 3.1, \"ERE\": 3.1,\n \"TER\": 3.0, \"EST\": 2.8, \"ERS\": 2.8, \"HAT\": 2.6,\n \"ATI\": 2.6, \"ATE\": 2.5, \"ALL\": 2.5, \"VER\": 2.4,\n \"HIS\": 2.4, \"HES\": 2.4, \"ETH\": 2.4, \"OFT\": 2.2,\n \"STH\": 2.1, \"RES\": 2.1, \"OTH\": 2.1, \"ITH\": 2.1,\n \"FTH\": 2.1, \"ONT\": 2.0}.toTable\n\nfunc decrypt(enc, key: string): string =\n let encLen = enc.len\n let keyLen = key.len\n result.setLen(encLen)\n var k = 0\n for i in 0..<encLen:\n result[i] = chr((ord(enc[i]) - ord(key[k]) + 26) mod 26 + ord('A'))\n k = (k + 1) mod keyLen\n\nfunc cryptanalyze(enc: string; maxKeyLen = 20): tuple[maxKey, maxDec: string] =\n let encLen = enc.len\n var maxScore = 0.0\n\n for keyLen in 1..maxKeyLen:\n var key = newString(keyLen)\n var idx = collect(newSeq):\n for i in 1..encLen:\n if i mod keyLen == 0:\n i - keyLen\n\n for i in 0..<keyLen:\n var maxSubscore = 0.0\n for j in 'A'..'Z':\n var subscore = 0.0\n let encidx = idx.mapIt(enc[it]).join()\n for k in decrypt(encidx, $j):\n subscore += FreqLetters[k]\n if subscore > maxSubscore:\n maxSubscore = subscore\n key[i] = j\n for item in idx.mitems: inc item\n\n let dec = decrypt(enc, key)\n var score = 0.0\n for i in dec:\n score += FreqLetters[i]\n\n for i in 0..(encLen - 3):\n let digraph = dec[i..(i+1)]\n let trigraph = dec[i..(i+2)]\n score += 2 * FreqDigraphs.getOrDefault(digraph)\n score += 3 * FreqTrigraphs.getOrDefault(trigraph)\n\n if score > maxScore:\n maxScore = score\n result.maxKey = key\n result.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", "language": "Nim" }, { "code": "(* Task : Vigenere cipher/Cryptanalysis *)\n\n(*\n\tGiven some text you suspect has been encrypted\n\twith a Vigenère cipher, extract the key and plaintext.\n\tUses correlation factors similar to other solutions.\n\t(originally tried Friedman test, didn't produce good result)\n\t\n\tCoded in a way that allows non-english (by passing frequencies).\n*)\n\n(*** Helpers ***)\n\n(* Implementation of Float.round to avoid v4.08 *)\nlet round (x : float) : float =\n let rem = mod_float x 1. in\n if rem >= 0.5\n then ceil x\n else floor x\n\n(* A function that updates array element at a position *)\nlet array_update (arr : 'a array) (idx : int) (update : 'a -> 'a) : unit =\n let curr = Array.get arr idx in\n Array.set arr idx (update curr)\n\n(*** Actual task at hand ***)\n\n(* the n'th element of array is how often the n'th letter was found *)\nlet observe_coincidences ?(step : int = 1) ?(offset : int = 0) (text : string) : int array =\n let arr = Array.make 26 0 in\n let a_code = Char.code 'A' in\n String.iteri (fun idx c -> if idx mod step = offset then array_update arr (Char.code c - a_code) succ) text;\n arr\n\n(* Obtain correlation factor for the observed coincidences *)\nlet correlation_factor ?(sort : bool = true) (coincidences : int array) (freqs : float list) : float =\n let clist = Array.to_list coincidences in\n let clist = (if sort then List.sort compare clist else clist) in\n List.fold_left2 (fun acc c f -> acc +. (float_of_int c *. f)) 0. clist freqs\n\n(* Translation of the test used in other Rosetta Code solutions *)\nlet shifted_coincidences_test (freqs : float list) (text : string) : int =\n let sorted_freqs = List.sort compare freqs in\n let bestCorr = -100. in\n let max_keylen = String.length text / 20 in\n let rec helper idx (cur_len, cur_corr) (best_len, best_corr) =\n if cur_len = max_keylen then (* Finished testing everything *)\n best_len\n else if idx = cur_len then (* Finished testing this key length *)\n let (best_len, best_corr) = if cur_corr > best_corr then (cur_len, cur_corr) else (best_len, best_corr) in\n helper 0 (cur_len + 1, ~-.0.5 *. float_of_int (cur_len + 1)) (best_len, best_corr)\n else\n let coincidences = observe_coincidences ~step:cur_len ~offset:idx text in\n let factor = correlation_factor coincidences sorted_freqs in\n helper (succ idx) (cur_len, cur_corr +. factor) (best_len, best_corr)\n in\n helper 0 (2, ~-.1.) (1, ~-.100.)\n\n(* Returns the most likely shift value for this set *)\nlet break_caesar ?(step : int = 1) ?(offset : int = 0) (text : string) (freqs : float list) : int =\n let c_arr = observe_coincidences ~step ~offset text in\n let rec helper l curShift (maxShift, maxCorr) =\n if curShift = 26\n then maxShift\n else\n let corr = correlation_factor ~sort:false c_arr l in\n let l' = List.tl l @ [List.hd l] in\n if corr > maxCorr\n then helper l' (curShift + 1) (curShift, corr)\n else helper l' (curShift + 1) (maxShift, maxCorr)\n in\n helper freqs 0 (-1, -100.)\n\nlet break (keylen : int) (text : string) (freqs : float list) : key =\n let rec getCaesars idx acc =\n if idx >= keylen then acc else\n let shift = break_caesar ~step:keylen ~offset:idx text freqs in\n let new_code = if shift = 0 then Char.code 'A' else Char.code 'Z' + 1 - shift in\n getCaesars (succ idx) (acc ^ Char.(new_code |> chr |> escaped))\n in\n getCaesars 0 \"\"\n\nlet cryptanalyze (freqs : float list) (text : string) : key * string =\n let text = ascii_upper_letters_only text in\n let keylen = shifted_coincidences_test freqs text in\n let key = break keylen text freqs in\n let pt = decrypt key text in\n (key, pt)\n\n(*** Output ***)\n\nlet _ =\n let long_text = \"\\\nMOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH \\\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD \\\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS \\\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG \\\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ \\\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS \\\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT \\\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST \\\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH \\\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV \\\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW \\\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO \\\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR \\\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX \\\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB \\\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA \\\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n in\n let english_freqs = [\n 0.08167; 0.01492; 0.02782; 0.04253; 0.12702; 0.02228; 0.02015;\n 0.06094; 0.06966; 0.00153; 0.00772; 0.04025; 0.02406; 0.06749;\n 0.07507; 0.01929; 0.00095; 0.05987; 0.06327; 0.09056; 0.02758;\n 0.00978; 0.02360; 0.00150; 0.01974; 0.00074\n ]\n in\n let (key, pt) = cryptanalyze english_freqs long_text in\n Printf.printf \"Key: %s\\n\\nText: %s\" key pt\n;;\n", "language": "OCaml" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\n# from Wikipedia\nmy %English_letter_freq = (\n E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75,\n S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23,\n G => 2.02, B => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07\n);\nmy @alphabet = sort keys %English_letter_freq;\nmy $max_key_lengths = 5; # number of keylengths to try\n\nsub myguess {\n my ($text) = (@_);\n my ($seqtext, @spacing, @factors, @sortedfactors, $pos, %freq, %Keys);\n\n # Kasiski examination\n $seqtext = $text;\n while ($seqtext =~ /(...).*\\1/) {\n $seqtext = substr($seqtext, 1+index($seqtext, $1));\n push @spacing, 1 + index($seqtext, $1);\n }\n\n for my $j (@spacing) {\n push @factors, grep { $j % $_ == 0 } 2..$j;\n }\n $freq{$_}++ for @factors;\n @sortedfactors = grep { $_ >= 4 } sort { $freq{$b} <=> $freq{$a} } keys %freq; # discard very short keys\n\n for my $keylen ( @sortedfactors[0..$max_key_lengths-1] ) {\n my $keyguess = '';\n for (my $i = 0; $i < $keylen; $i++) {\n my($mykey, %chi_values, $bestguess);\n for (my $j = 0; $j < length($text); $j += $keylen) {\n $mykey .= substr($text, ($j+$i) % length($text), 1);\n }\n\n for my $subkey (@alphabet) {\n my $decrypted = mycrypt($mykey, $subkey);\n my $length = length($decrypted);\n for my $char (@alphabet) {\n my $expected = $English_letter_freq{$char} * $length / 100;\n my $observed;\n ++$observed while $decrypted =~ /$char/g;\n $chi_values{$subkey} += ($observed - $expected)**2 / $expected if $observed;\n }\n }\n\n $Keys{$keylen}{score} = $chi_values{'A'};\n for my $sk (sort keys %chi_values) {\n if ($chi_values{$sk} <= $Keys{$keylen}{score}) {\n $bestguess = $sk;\n $Keys{$keylen}{score} = $chi_values{$sk};\n }\n }\n $keyguess .= $bestguess;\n }\n $Keys{$keylen}{key} = $keyguess;\n }\n map { $Keys{$_}{key} } sort { $Keys{$a}{score} <=> $Keys{$b}{score}} keys %Keys;\n}\n\nsub mycrypt {\n my ($text, $key) = @_;\n my ($new_text, %values_numbers);\n\n my $keylen = length($key);\n @values_numbers{@alphabet} = 0..25;\n my %values_letters = reverse %values_numbers;\n\n for (my $i = 0; $i < length($text); $i++) {\n my $val = -1 * $values_numbers{substr( $key, $i%$keylen, 1)} # negative shift for decode\n + $values_numbers{substr($text, $i, 1)};\n $new_text .= $values_letters{ $val % 26 };\n }\n return $new_text;\n}\n\nmy $cipher_text = <<~'EOD';\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\nEOD\n\nmy $text = uc($cipher_text) =~ s/[^@{[join '', @alphabet]}]//gr;\n\nfor my $key ( myguess($text) ) {\n say \"Key $key\\n\" .\n \"Key length \" . length($key) . \"\\n\" .\n \"Plaintext \" . substr(mycrypt($text, $key), 0, 80) . \"...\\n\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Cryptanalysis.exw\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">ciphertext</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\"\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">})</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">letters</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">(</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">'E'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12.702</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'T'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9.056</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'A'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8.167</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'O'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7.507</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'I'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.966</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'N'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.749</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'S'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.327</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'H'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.094</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'R'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.987</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'D'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.253</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'L'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.025</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'C'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.782</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'U'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.758</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'M'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.406</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'W'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.361</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'F'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.228</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'G'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.015</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'Y'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.974</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'P'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.929</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'B'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.492</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'V'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.978</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'K'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.772</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'J'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.153</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'X'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.150</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'Q'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.095</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">'Z'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.074</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">digraphs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">(</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">\"TH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">15.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">12.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"IN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ER\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"RE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ND\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ON\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"NT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ES\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ST\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"EN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ED\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"TO\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"IT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"OU\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5.0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"EA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HI\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"IS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"OR\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"TI\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"TE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.7</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ET\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"NG\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"OF\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AL\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"DE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.9</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"SE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"LE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"SA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"SI\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AR\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"VE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"RA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"LD\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"UR\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0.2</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">trigraphs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">new_dict</span><span style=\"color: #0000FF;\">(</span>\n <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">\"THE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">18.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"AND\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ING\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ION\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ENT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HER\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"FOR\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"THA\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"NTH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"INT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"TIO\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ERE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"TER\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3.0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"EST\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ERS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HAT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ATI\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ATE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ALL\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"VER\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HIS\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"HES\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ETH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.4</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"OFT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"STH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"RES\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"OTH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ITH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"FTH\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"ONT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2.0</span><span style=\"color: #0000FF;\">}})</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">decrypt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">keylen</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #008000;\">'A'</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">keylen</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">msg</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">cryptanalyze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">maxkeylen</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">enclen</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">maxkey</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">maxdec</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">k1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\" \"</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">maxscore</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0.0</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">keylen</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">maxkeylen</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">key</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">keylen</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">idx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">enclen</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">keylen</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">idx</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">keylen</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">keylen</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">maxsubscore</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0.0</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'A'</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #008000;\">'Z'</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">subscore</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0.0</span>\n\n <span style=\"color: #000000;\">k1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">j</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">encidx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">ii</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">encidx</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ii</span><span style=\"color: #0000FF;\">]]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">dec</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">decrypt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">encidx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">k1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">di</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">subscore</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">di</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">letters</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">subscore</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">maxsubscore</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">maxsubscore</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">subscore</span>\n <span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">j</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000000;\">idx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">idx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">dec</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">decrypt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">enc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">score</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0.0</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">score</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">letters</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">enclen</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">digraph</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">trigraph</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">score</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">digraph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">digraphs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">score</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #7060A8;\">getd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">trigraph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">trigraphs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">score</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">maxscore</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">maxscore</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">score</span>\n <span style=\"color: #000000;\">maxkey</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">key</span>\n <span style=\"color: #000000;\">maxdec</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dec</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">maxkey</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">maxdec</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">fold</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">w</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\\n\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">string</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cryptanalyze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ciphertext</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"key: %s\\n\\n%s\\n\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">key</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fold</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dec</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">80</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"elapsed time: %3.2f seconds\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">})</span>\n\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "from string import uppercase\nfrom operator import itemgetter\n\ndef vigenere_decrypt(target_freqs, input):\n nchars = len(uppercase)\n ordA = ord('A')\n sorted_targets = sorted(target_freqs)\n\n def frequency(input):\n result = [[c, 0.0] for c in uppercase]\n for c in input:\n result[c - ordA][1] += 1\n return result\n\n def correlation(input):\n result = 0.0\n freq = frequency(input)\n freq.sort(key=itemgetter(1))\n\n for i, f in enumerate(freq):\n result += f[1] * sorted_targets[i]\n return result\n\n cleaned = [ord(c) for c in input.upper() if c.isupper()]\n best_len = 0\n best_corr = -100.0\n\n # Assume that if there are less than 20 characters\n # per column, the key's too long to guess\n for i in xrange(2, len(cleaned) // 20):\n pieces = [[] for _ in xrange(i)]\n for j, c in enumerate(cleaned):\n pieces[j % i].append(c)\n\n # The correlation seems to increase for smaller\n # pieces/longer keys, so weigh against them a little\n corr = -0.5 * i + sum(correlation(p) for p in pieces)\n\n if corr > best_corr:\n best_len = i\n best_corr = corr\n\n if best_len == 0:\n return (\"Text is too short to analyze\", \"\")\n\n pieces = [[] for _ in xrange(best_len)]\n for i, c in enumerate(cleaned):\n pieces[i % best_len].append(c)\n\n freqs = [frequency(p) for p in pieces]\n\n key = \"\"\n for fr in freqs:\n fr.sort(key=itemgetter(1), reverse=True)\n\n m = 0\n max_corr = 0.0\n for j in xrange(nchars):\n corr = 0.0\n c = ordA + j\n for frc in fr:\n d = (ord(frc[0]) - c + nchars) % nchars\n corr += frc[1] * target_freqs[d]\n\n if corr > max_corr:\n m = j\n max_corr = corr\n\n key += chr(m + ordA)\n\n r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)\n for i, c in enumerate(cleaned))\n return (key, \"\".join(r))\n\n\ndef main():\n encoded = \"\"\"\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\"\"\n\n english_frequences = [\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n\n (key, decoded) = vigenere_decrypt(english_frequences, encoded)\n print \"Key:\", key\n print \"\\nText:\", decoded\n\nmain()\n", "language": "Python" }, { "code": "#lang at-exp racket\n\n(define max-keylen 30)\n\n(define text\n @~a{MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK})\n\n(define first-char (char->integer #\\A))\n(define chars# (- (char->integer #\\Z) first-char -1))\n\n(define freqs ; english letter frequencies from wikipedia\n ((compose1 list->vector (curry map (curryr / 100000.0)))\n '(8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406\n 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74)))\n\n(define text* (for/vector ([c (regexp-replace* #px\"\\\\s+\" text \"\")])\n (- (char->integer c) first-char)))\n(define N (vector-length text*))\n\n(define (col-guesses len)\n (for/list ([ofs len])\n (define text (for/list ([i (in-range ofs N len)]) (vector-ref text* i)))\n (define cN (length text))\n (define cfreqs (make-vector chars# 0))\n (for ([c (in-list text)])\n (vector-set! cfreqs c (add1 (vector-ref cfreqs c))))\n (for ([i chars#]) (vector-set! cfreqs i (/ (vector-ref cfreqs i) cN)))\n (argmin car\n (for/list ([d chars#])\n (cons (for/sum ([i chars#])\n (expt (- (vector-ref freqs i)\n (vector-ref cfreqs (modulo (+ i d) chars#)))\n 2))\n d)))))\n\n(define best-key\n (cdr (argmin car\n (for/list ([len (range 1 (add1 max-keylen))])\n (define guesses (col-guesses len))\n (cons (/ (apply + (map car guesses)) len) (map cdr guesses))))))\n\n(printf \"Best key found: \")\n(for ([c best-key]) (display (integer->char (+ c first-char))))\n(newline)\n\n(printf \"Decoded text:\\n\")\n(define decode-num\n (let ([cur '()])\n (λ(n) (when (null? cur) (set! cur best-key))\n (begin0 (modulo (- n (car cur)) chars#) (set! cur (cdr cur))))))\n(for ([c text])\n (define n (- (char->integer c) first-char))\n (if (not (< -1 n chars#)) (display c)\n (display (integer->char (+ first-char (decode-num n))))))\n(newline)\n", "language": "Racket" }, { "code": "#lang at-exp racket\n\n(define max-keylen 30)\n\n(define text\n @~a{MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK})\n\n(define first-char (char->integer #\\A))\n(define chars# (- (char->integer #\\Z) first-char -1))\n\n(define freqs ; english letter frequencies from wikipedia\n ((compose1 list->vector (curry map (curryr / 100000.0)))\n '(8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406\n 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74)))\n\n(define (n*n-1 n) (* n (sub1 n)))\n\n(define text* (for/vector ([c (regexp-replace* #px\"\\\\s+\" text \"\")])\n (- (char->integer c) first-char)))\n(define N (vector-length text*))\n(define (get-col-length+freqs width offset)\n (define text (for/list ([i (in-range offset N width)]) (vector-ref text* i)))\n (define cN (length text))\n (define freqs (make-vector chars# 0))\n (for ([c (in-list text)]) (vector-set! freqs c (add1 (vector-ref freqs c))))\n (values cN freqs))\n\n(define expected-IC (* chars# (for*/sum ([x freqs]) (* x x))))\n\n;; maps key lengths to average index of coincidence\n(define keylen->ICs\n (for/vector ([len (in-range 1 (add1 (* max-keylen 2)))])\n (for/sum ([ofs len])\n (define-values [cN cfreqs] (get-col-length+freqs len ofs))\n (/ (for/sum ([i chars#]) (n*n-1 (vector-ref cfreqs i)))\n (/ (n*n-1 cN) chars#) len 1.0))))\n\n;; given a key length find the key that minimizes errors from alphabet freqs,\n;; return (cons average-error key)\n(define (guess-key len)\n (define guesses\n (for/list ([ofs len])\n (define-values [cN cfreqs] (get-col-length+freqs len ofs))\n (for ([i chars#]) (vector-set! cfreqs i (/ (vector-ref cfreqs i) cN)))\n (argmin car\n (for/list ([d chars#])\n (cons (for/sum ([i chars#])\n (expt (- (vector-ref freqs i)\n (vector-ref cfreqs (modulo (+ i d) chars#)))\n 2))\n d)))))\n (cons (/ (apply + (map car guesses)) len) (map cdr guesses)))\n\n;; look for a key length that minimizes error from expected-IC, with some\n;; stupid consideration of multiples of the length (which should also have low\n;; errors), for each one guess a key, then find the one that minimizes both (in\n;; a way that looks like it works, but undoubtedly is wrong in all kinds of\n;; ways) and return the winner key\n(define best-key\n ((compose1 cdr (curry argmin car))\n (for/list ([i (* max-keylen 2)])\n ;; get the error from the expected-IC for the length and its multiples,\n ;; with decreasing weights for the multiples\n (define with-multiples\n (for/list ([j (in-range i (* max-keylen 2) (add1 i))] [div N])\n (cons (/ (abs (- (vector-ref keylen->ICs j) expected-IC)) expected-IC)\n (/ (add1 div)))))\n (define total (/ (for/sum ([x with-multiples]) (* (car x) (cdr x)))\n (for/sum ([x with-multiples]) (cdr x))))\n (define guess (guess-key (add1 i)))\n (define guess*total (* total (car guess) (car guess)))\n ;; (printf \"~a~a: ~a ~s\\n\" (if (< i 9) \" \" \"\") (add1 i)\n ;; (list total (car guess) guess*total) (cdr guess))\n (cons guess*total (cdr guess)))))\n\n(printf \"Best key found: \")\n(for ([c best-key]) (display (integer->char (+ c first-char))))\n(newline)\n\n(printf \"Decoded text:\\n\")\n(define decode-num\n (let ([cur '()])\n (λ(n) (when (null? cur) (set! cur best-key))\n (begin0 (modulo (- n (car cur)) chars#) (set! cur (cdr cur))))))\n(for ([c text])\n (define n (- (char->integer c) first-char))\n (if (not (< -1 n chars#)) (display c)\n (display (integer->char (+ first-char (decode-num n))))))\n(newline)\n", "language": "Racket" }, { "code": "# from Wikipedia\nconstant %English-letter-freq = (\n E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75,\n S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23,\n G => 2.02, B => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07\n);\nconstant @alphabet = %English-letter-freq.keys.sort;\nconstant max_key_lengths = 5; # number of keylengths to try\n\nsub myguess ($text) {\n my ($seqtext, @spacing, @factors, $pos, %freq, %Keys);\n\n # Kasiski examination\n $seqtext = $text;\n while ($seqtext ~~ /$<sequence>=[...].*$<sequence>/) {\n $seqtext = substr($seqtext, 1+index($seqtext, $<sequence>));\n push @spacing, 1 + index($seqtext, $<sequence>);\n }\n for @spacing -> $j {\n %freq{$_}++ for grep { $j %% $_ }, 2..$j;\n }\n\n # discard very short keys, and test only the most likely remaining key lengths\n (%freq.keys.grep(* > 3).sort({%freq{$_}}).tail(max_key_lengths)).race(:1batch).map: -> $keylen {\n my $key-guess = '';\n loop (my $i = 0; $i < $keylen; $i++) {\n my ($mykey, %chi-square, $best-guess);\n loop (my $j = 0; $j < $text.chars; $j += $keylen) {\n $mykey ~= substr($text, ($j+$i) % $text.chars, 1);\n }\n\n for @alphabet -> $subkey {\n my $decrypted = mycrypt($mykey, $subkey);\n my $length = $decrypted.chars;\n for @alphabet -> $char {\n my $expected = %English-letter-freq{$char} * $length / 100;\n my $observed = $decrypted.comb.grep(* eq $char).elems;\n %chi-square{$subkey} += ($observed - $expected)² / $expected if $observed;\n }\n }\n %Keys{$keylen}{'score'} = %chi-square{@alphabet[0]};\n for %chi-square.keys.sort -> $sk {\n if (%chi-square{$sk} <= %Keys{$keylen}{'score'}) {\n $best-guess = $sk;\n %Keys{$keylen}{'score'} = %chi-square{$sk};\n }\n }\n $key-guess ~= $best-guess;\n }\n %Keys{$keylen}{'key'} = $key-guess;\n }\n %Keys.keys.sort({ %Keys{$_}{'score'} }).map:{ %Keys{$_}{'key'} };\n}\n\nsub mycrypt ($text, $key) {\n constant %values-numbers = @alphabet Z=> ^@alphabet;\n constant %values-letters = %values-numbers.invert;\n\n my ($new-text);\n my $keylen = $key.chars;\n loop (my $i = 0; $i < $text.chars; $i++) {\n my $val = -1 * %values-numbers{substr( $key, $i%$keylen, 1)} # negative shift for decode\n + %values-numbers{substr($text, $i, 1)};\n $new-text ~= %values-letters{ $val % @alphabet };\n }\n return $new-text;\n}\n\nmy $cipher-text = .uc.trans(@alphabet => '', :c) given q:to/EOD/;\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\nEOD\n\nfor myguess($cipher-text) -> $key {\n say \"Key $key\\n\" ~\n \"Key length {$key.chars}\\n\" ~\n \"Plaintext {substr(mycrypt($cipher-text, $key), 0, 80)}...\\n\";\n}\n", "language": "Raku" }, { "code": "use std::iter::FromIterator;\n\nconst CRYPTOGRAM: &str = \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n\nconst FREQUENCIES: [f32; 26] = [\n 0.08167, 0.01492, 0.02202, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153,\n 0.01292, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09356,\n 0.02758, 0.00978, 0.02560, 0.00150, 0.01994, 0.00077,\n];\n\nfn best_match(a: &[f32]) -> u8 {\n let sum: f32 = a.iter().sum();\n let mut best_fit = std::f32::MAX;\n let mut best_rotate = 0;\n for rotate in 0..=25 {\n let mut fit = 0.;\n for i in 0..=25 {\n let char_freq = FREQUENCIES[i];\n let idx = (i + rotate as usize) % 26 as usize;\n let d = a[idx] / sum - char_freq;\n fit += d * d / char_freq;\n }\n if fit < best_fit {\n best_fit = fit;\n best_rotate = rotate;\n }\n }\n\n best_rotate\n}\n\nfn freq_every_nth(msg: &[u8], key: &mut [char]) -> f32 {\n let len = msg.len();\n let interval = key.len();\n let mut accu = [0.; 26];\n for j in 0..interval {\n let mut out = [0.; 26];\n for i in (j..len).step_by(interval) {\n let idx = msg[i] as usize;\n out[idx] += 1.;\n }\n let rot = best_match(&out);\n key[j] = char::from(rot + b'A');\n for i in 0..=25 {\n let idx: usize = (i + rot as usize) % 26;\n accu[i] += out[idx];\n }\n }\n let sum: f32 = accu.iter().sum();\n let mut ret = 0.;\n for i in 0..=25 {\n let char_freq = FREQUENCIES[i];\n let d = accu[i] / sum - char_freq;\n ret += d * d / char_freq;\n }\n ret\n}\n\nfn decrypt(text: &str, key: &str) -> String {\n let key_chars_cycle = key.as_bytes().iter().map(|b| *b as i32).cycle();\n let is_ascii_uppercase = |c: &u8| (b'A'..=b'Z').contains(c);\n text.as_bytes()\n .iter()\n .filter(|c| is_ascii_uppercase(c))\n .map(|b| *b as i32)\n .zip(key_chars_cycle)\n .fold(String::new(), |mut acc, (c, key_char)| {\n let ci: u8 = ((c - key_char + 26) % 26) as u8;\n acc.push(char::from(b'A' + ci));\n acc\n })\n}\nfn main() {\n let enc = CRYPTOGRAM\n .split_ascii_whitespace()\n .collect::<Vec<_>>()\n .join(\"\");\n let cryptogram: Vec<u8> = enc.as_bytes().iter().map(|b| u8::from(b - b'A')).collect();\n let mut best_fit = std::f32::MAX;\n let mut best_key = String::new();\n for j in 1..=26 {\n let mut key = vec!['\\0'; j];\n let fit = freq_every_nth(&cryptogram, &mut key);\n let s_key = String::from_iter(key); // 'from_iter' is imported from std::iter::FromIterator;\n if fit < best_fit {\n best_fit = fit;\n best_key = s_key;\n }\n }\n\n println!(\"best key: {}\", &best_key);\n println!(\"\\nDecrypted text:\\n{}\", decrypt(&enc, &best_key));\n}\n", "language": "Rust" }, { "code": "package require Tcl 8.6\n\noo::class create VigenereAnalyzer {\n variable letterFrequencies sortedTargets\n constructor {{frequencies {\n \t0.08167 0.01492 0.02782 0.04253 0.12702 0.02228 0.02015\n\t0.06094 0.06966 0.00153 0.00772 0.04025 0.02406 0.06749\n\t0.07507 0.01929 0.00095 0.05987 0.06327 0.09056 0.02758\n\t0.00978 0.02360 0.00150 0.01974 0.00074\n }}} {\n\tset letterFrequencies $frequencies\n\tset sortedTargets [lsort -real $frequencies]\n\tif {[llength $frequencies] != 26} {\n\t error \"wrong length of frequency table\"\n\t}\n }\n\n ### Utility methods\n # Find the value of $idxvar in the range [$from..$to) that maximizes the value\n # in $scorevar (which is computed by evaluating $body)\n method Best {idxvar from to scorevar body} {\n\tupvar 1 $idxvar i $scorevar s\n\tset bestI $from\n\tfor {set i $from} {$i < $to} {incr i} {\n\t uplevel 1 $body\n\t if {![info exist bestS] || $bestS < $s} {\n\t\tset bestI $i\n\t\tset bestS $s\n\t }\n\t}\n\treturn $bestI\n }\n # Simple list map\n method Map {var list body} {\n\tupvar 1 $var v\n\tset result {}\n\tforeach v $list {lappend result [uplevel 1 $body]}\n\treturn $result\n }\n # Simple partition of $list into $groups groups; thus, the partition of\n # {a b c d e f} into 3 produces {a d} {b e} {c f}\n method Partition {list groups} {\n\tset i 0\n\tforeach val $list {\n\t dict lappend result $i $val\n\t if {[incr i] >= $groups} {\n\t\tset i 0\n\t }\n\t}\n\treturn [dict values $result]\n }\n\n ### Helper methods\n # Get the actual counts of different types of characters in the given list\n method Frequency cleaned {\n\tfor {set i 0} {$i < 26} {incr i} {\n\t dict set tbl $i 0\n\t}\n\tforeach ch $cleaned {\n\t dict incr tbl [expr {[scan $ch %c] - 65}]\n\t}\n\treturn $tbl\n }\n\n # Get the correlation factor of the characters in a given list with the\n # class-specified language frequency corpus\n method Correlation cleaned {\n\tset result 0.0\n\tset freq [lsort -integer [dict values [my Frequency $cleaned]]]\n\tforeach f $freq s $sortedTargets {\n\t set result [expr {$result + $f * $s}]\n\t}\n\treturn $result\n }\n\n # Compute an estimate for the key length\n method GetKeyLength {cleaned {required 20}} {\n\t# Assume that we need at least 20 characters per column to guess\n\tset bestLength [my Best i 2 [expr {[llength $cleaned] / $required}] corr {\n\t set corr [expr {-0.5 * $i}]\n\t foreach chars [my Partition $cleaned $i] {\n\t\tset corr [expr {$corr + [my Correlation $chars]}]\n\t }\n\t}]\n\tif {$bestLength == 0} {\n\t error \"text is too short to analyze\"\n\t}\n\treturn $bestLength\n }\n\n # Compute the key from the given frequency tables and the class-specified\n # language frequency corpus\n method GetKeyFromFreqs freqs {\n\tforeach f $freqs {\n\t set m [my Best i 0 26 corr {\n\t\tset corr 0.0\n\t\tforeach {ch count} $f {\n\t\t set d [expr {($ch - $i) % 26}]\n\t\t set corr [expr {$corr + $count*[lindex $letterFrequencies $d]}]\n\t\t}\n\t }]\n\t append key [format %c [expr {65 + $m}]]\n\t}\n\treturn $key\n }\n\n ##### The main analyzer method #####\n method analyze input {\n\t# Turn the input into a clean letter sequence\n\tset cleaned [regexp -all -inline {[A-Z]} [string toupper $input]]\n\t# Get the (estimated) key length\n\tset bestLength [my GetKeyLength $cleaned]\n\t# Get the frequency mapping for the partitioned input text\n\tset freqs [my Map p [my Partition $cleaned $bestLength] {my Frequency $p}]\n\t# Get the key itself\n\treturn [my GetKeyFromFreqs $freqs]\n }\n}\n", "language": "Tcl" }, { "code": "set encoded \"\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\n\"\nVigenereAnalyzer create englishVigenereAnalyzer\nset key [englishVigenereAnalyzer analyze $encoded]\nVigenere create decoder $key\nset decoded [decoder decrypt $encoded]\nputs \"Key: $key\"\nputs \"Text: $decoded\"\n", "language": "Tcl" }, { "code": "import strings\nconst encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nconst freq = [\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074,\n]\n\nfn sum(a []f64) f64 {\n mut s := 0.0\n for f in a {\n s += f\n }\n return s\n}\n\nfn best_match(a []f64) int {\n s := sum(a)\n mut best_fit, mut best_rotate := 1e100, 0\n for rotate in 0..26 {\n mut fit := 0.0\n for i in 0..26 {\n d := a[(i+rotate)%26]/s - freq[i]\n fit += d * d / freq[i]\n }\n if fit < best_fit {\n best_fit, best_rotate = fit, rotate\n }\n }\n return best_rotate\n}\n\nfn freq_every_nth(msg []int, mut key []u8) f64 {\n l := msg.len\n interval := key.len\n mut out := []f64{len: 26}\n mut accu := []f64{len: 26}\n for j in 0..interval {\n for z in 0..26 {\n out[z] = 0.0\n }\n for i := j; i < l; i += interval {\n out[msg[i]]++\n }\n rot := best_match(out)\n key[j] = u8(rot + 65)\n for i := 0; i < 26; i++ {\n accu[i] += out[(i+rot)%26]\n }\n }\n s := sum(accu)\n mut ret := 0.0\n for i := 0; i < 26; i++ {\n d := accu[i]/s - freq[i]\n ret += d * d / freq[i]\n }\n return ret\n}\n\nfn decrypt(text string, key string) string {\n mut sb := strings.new_builder(128)\n mut ki := 0\n for c in text {\n if c < 'A'[0] || c > 'Z'[0] {\n continue\n }\n ci := (c - key[ki] + 26) % 26\n sb.write_rune(ci + 65)\n ki = (ki + 1) % key.len\n }\n return sb.str()\n}\n\nfn main() {\n enc := encoded.replace(\" \", \"\")\n mut txt := []int{len: enc.len}\n for i in 0..txt.len {\n txt[i] = int(enc[i] - 'A'[0])\n }\n mut best_fit, mut best_key := 1e100, \"\"\n println(\" Fit Length Key\")\n for j := 1; j <= 26; j++ {\n mut key := []u8{len: j}\n fit := freq_every_nth(txt, mut key)\n s_key := key.bytestr()\n print(\"${fit:.6} ${j:2} $s_key\")\n if fit < best_fit {\n best_fit, best_key = fit, s_key\n print(\" <--- best so far\")\n }\n println('')\n }\n println(\"\\nBest key : $best_key\")\n println(\"\\nDecrypted text:\\n${decrypt(enc, best_key)}\")\n}\n", "language": "V-(Vlang)" }, { "code": "// (1) Copy text into tmp buffer and remove non-alpha chars.\n\nChdir(PATH_ONLY)\nBOF\nReg_Copy(10, ALL) // copy text to new buffer\nBuf_Switch(Buf_Free)\nReg_Ins(10)\nBOF\nReplace (\"|!|A\", \"\", BEGIN+ALL+NOERR) // remove non-alpha chars\nReg_Copy_Block(10,0,EOB_pos) // @10 = text to be analysed\n\n#20 = Buf_Num // buffer for text being analyzed\n#21 = Buf_Free // buffer for English frequency list (A-Z)\nBuf_Switch(#21)\nIns_Text(\"8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74\")\nFile_Open(\"unixdict.txt\") // or use \"|(MACRO_DIR)\\scribe\\english.vdf\"\n#23 = Buf_Num // buffer for dictionary\n#24 = Buf_Free // buffer for key canditates\n\nBuf_Switch(#24)\nfor (#1=0; #1<5; #1++) { // Fill table for 5 keys of 50 chars\n Ins_Char('.', COUNT, 50)\n Ins_Newline\n}\n#22 = Buf_Free // buffer for results\n\n#25 = Reg_Size(10) // number of letters in the text\n#26 = 26 // number of characters in the alphabet\n#61 = min(#25/10, 50) // max key length to try\n\n// (2) Check Index of coincidence (or Kp) for each key length\n\nBuf_Switch(#22) // buffer for results\nIns_Text(\"KeyLen Kp dist \") Ins_Newline\nIns_Text(\"-----------------\") Ins_Newline\n#13 = Cur_Pos\n#7 = 0 // no Caesar encryption\nfor (#5=1; #5<=#61; #5++) {\n Buf_Switch(#20) // text being analyzed\n BOF\n #54 = 0; // sum of Kp's\n for (#6=0; #6<#5; #6++) { // for each slide\n Goto_Pos(#6)\n Call(\"CHARACTER_FREQUENCIES\")\n Call(\"INDEX_OF_COINCIDENCE\") // #51 = Kp * 10000\n #54 += #51\n }\n #54 /= #5 // average of Kp's\n Buf_Switch(#22)\n Num_Ins(#5, COUNT, 3) // write key length\n IT(\": \")\n Num_Ins(#54, NOCR) // average Kp\n Num_Ins(670-#54) // distance to English Kp\n}\nBuf_Switch(#22)\nSort_Merge(\"5,12\", #13, Cur_Pos, REVERSE) // sort the results by Kp value\nIns_Newline\n\n// (3) Check the best 4 key lengths to find which one gives the best decrypt result\n\n#38 = 0 // max number of correct characters found\n#19 = 1 // best key length\nfor (#14 = 0; #14<4; #14++) { // try 4 best key lengths\n Buf_Switch(#22) // results buffer\n Goto_Pos(#13) Line(#14)\n #5 = Num_Eval(SUPPRESS) // #5 = key length\n Call(\"FIND_KEYS\") // find Caesar key for each key character\n #4 = -1 // try best match key chars only\n Call(\"BUILD_KEY\")\n EOF\n Ins_Text(\"Key length \")\n Num_Ins(#5, LEFT)\n Reg_Ins(10) // encrypted text\n BOL\n Call(\"DECRYPT_LINE\")\n BOL\n Call(\"FIND_ENGLISH_WORDS\") // #37 = number of English chars\n EOL Ins_Newline\n Ins_Text(\"Correct chars: \")\n Num_Ins(#37)\n if (#37 > #38) {\n #38 = #37\n #19 = #5\n }\n Update()\n}\n\nIns_Text(\"Using key length: \") Num_Ins(#19) Ins_Newline\n#5 = #19\nCall(\"FIND_KEYS\") // find Caesar key for each key character\n\n// (4) Decrypt with different key combinations and try to find English words.\n// Try key combinations where max one char is taken from 2nd best Caesar key.\n\n#38 = 0 // max number of chars in English words found\n#39 = -1 // best key number found\nfor (#4 = -1; #4 < #19; #4++)\n{\n Call(\"BUILD_KEY\")\n Buf_Switch(#22) // results\n Reg_Ins(10) // encrypted text\n BOL\n Call(\"DECRYPT_LINE\")\n BOL\n Update()\n Call(\"FIND_ENGLISH_WORDS\") // #37 := number of correct letters in text\n if (#37 > #38) {\n #38 = #37 // new highest number of correct chars\n #39 = #4 // new best key\n }\n\n EOL IT(\" -- \") // display results\n Num_Ins(#4, COUNT, 3) // key number\n Ins_Text(\": \")\n for (#6=0; #6<#19; #6++) { // display key\n #9 = 130 + #6\n Ins_Char(#@9)\n }\n Ins_Text(\" correct chars =\")\n Num_Ins(#37)\n}\nIns_Text(\"Best key = \")\nNum_Ins(#39, LEFT)\n#4 = #39\nIns_Newline\n\n// Display results\n//\nBuf_Switch(#24) // table for key canditates\nBOF\nReg_Copy_Block(14, Cur_Pos, Cur_Pos+#19) // best Caesar key chars\nLine(1)\nReg_Copy_Block(15, Cur_Pos, Cur_Pos+#19) // 2nd best Caesar key chars\nCall(\"BUILD_KEY\")\nBuf_Switch(#22)\nIns_Text(\"Key 1: \") Reg_Ins(14) Ins_Newline\nIns_Text(\"Key 2: \") Reg_Ins(15) Ins_Newline\nIns_Text(\"Key: \")\nfor (#6=0; #6 < #19; #6++) {\n #9 = #6+130\n Ins_Char(#@9)\n}\nIns_Newline\nIns_Newline\n\n// decrypt the text with selected key\nIns_Text(\"Decrypted text:\") Ins_Newline\nReg_Ins(10)\nBOL\nCall(\"DECRYPT_LINE\")\nBOL Reg_Copy(13,1)\nEOL Ins_Newline\n\n// Find English words from the text\nReg_Ins(13)\nCall(\"FIND_ENGLISH_WORDS\")\nEOL\nIns_Newline\nNum_Ins(#37, NOCR) IT(\" of \")\nNum_Ins(#25, NOCR) IT(\" characters are English words. \")\nIns_Newline\n\nBuf_Switch(#20) Buf_Quit(OK)\nBuf_Switch(#21) Buf_Quit(OK)\nBuf_Switch(#23) Buf_Quit(OK)\nBuf_Switch(#24) Buf_Quit(OK)\n\nStatline_Message(\"Done!\")\nReturn\n\n/////////////////////////////////////////////////////////////////////////////\n//\n// Caesar decrypt current line and count character frequencies.\n// in: #5 = step size, #7 = encryption key, #26 = num of chars in alphabet\n// out: #65...#90 = frequencies, #60 = number of chars\n\n:CHARACTER_FREQUENCIES:\n Save_Pos\n for (#8 = 'A'; #8<='Z'; #8++) {\n #@8 = 0 // reset frequency counters\n }\n #60 = 0 // total number of chars\n while (!At_EOL) {\n if (Cur_Char >= 'A' && Cur_Char <= 'Z') {\n #8 = (Cur_Char-'A'+#26-#7) % #26 + 'A' // decrypted char\n #@8++\n #60++\n }\n Char(#5)\n }\n Restore_Pos\nReturn\n\n// Calculate Index of Coincidence (Kp).\n// in: character frequencies in #65...#90, #60 = num of chars\n// out: #51 = IC * 10000\n//\n:INDEX_OF_COINCIDENCE:\n Num_Push(10,15)\n #10 = 0\n for (#11 = 'A'; #11<='Z'; #11++) {\n #10 += (#@11 * (#@11-1)) // Calculate sigma{ni * (ni-1)}\n }\n #12 = #60 * (#60-1) // #12 = N * (N-1)\n #51 = #10 * 10000 / #12 // #51 = Kp * 10000\n Num_Pop(10,15)\nReturn\n\n// Find best and 2nd best Caesar key for each character position of Vigenère key.\n// in: #5=step size (key length)\n// out: keys in buffer #24\n//\n:FIND_KEYS:\n for (#6 = 0; #6 < #5; #6++) { // for each char position in the key\n #30 = -1 // best key char found so far\n #31 = -1 // 2nd best key char\n #32 = MAXNUM // smallest error found so far\n #33 = MAXNUM // 2nd smallest error found so far\n for (#7 = 0; #7 < #26; #7++) { // for each possible key value\n #35 = 0 // total frequency error compared to English\n Buf_Switch(#20) // text being analyzed\n Goto_Pos(#6)\n Call(\"CHARACTER_FREQUENCIES\")\n Buf_Switch(#21) // English frequency table\n BOF\n for (#8 = 'A'; #8<='Z'; #8++) { // calculate total frequency error\n #34 = Num_Eval(SUPPRESS+ADVANCE)\n #35 += abs((#@8*100000+50000)/#60-#34)\n }\n\n if (#35 < #32) { // found better match?\n #33 = #32\n #32 = #35\n #31 = #30\n #30 = #7\n } else {\n if (#35 < #33) { // 2nd best match?\n #33 = #35\n #31 = #7\n }\n }\n }\n Buf_Switch(#24) // table for key canditates\n BOF\n Goto_Col(#6+1)\n Ins_Char(#30+'A', OVERWRITE) // save the best match\n Line(1)\n Goto_Col(#6+1)\n Ins_Char(#31+'A', OVERWRITE) // save 2nd best match\n }\n Buf_Switch(#22) // results buffer\nReturn\n\n// Combine actual key from 1st and 2nd best Caesar key characters\n// Use 1st key chars and (possibly) one character from 2nd key.\n// #4 = index of the char to be picked from 2nd key, -1 = none.\n// #5 = key length\n//\n:BUILD_KEY:\n Buf_Switch(#24) // table for key canditates\n BOF\n for (#6=0; #6<#5; #6++) { // copy 1st key\n #8 = 130 + #6\n #@8 = Cur_Char\n Char(1)\n }\n if (#4 >= 0) {\n #8 = 130 + #4 // pick one char from 2st key\n Line(1)\n Goto_Col(#4+1)\n #@8 = Cur_Char\n }\n Buf_Switch(#22) // results buffer\nReturn\n\n// Decrypt text on current line\n// in: #5 = key length, #130...#189 = key\n//\n:DECRYPT_LINE:\n Num_Push(6,9)\n #6 = 0\n While (!At_EOL) {\n #9 = #6+130\n #7 = #@9\n #8 = (Cur_Char - #7 + #26) % #26 + 'A' // decrypted char\n Ins_Char(#8, OVERWRITE)\n #6++\n if (#6 >= #5) {\n #6 = 0\n }\n }\n Num_Pop(6,9)\nReturn\n\n// Find English words from text on current line\n// out: #37 = number of chars matched\n//\n:FIND_ENGLISH_WORDS:\n Buf_Switch(#23) // dictionary\n BOF\n While (!At_EOF) {\n Reg_Copy_Block(12, Cur_Pos, EOL_Pos)\n if (Reg_Size(12) > 2) {\n Buf_Switch(#22) // buffer for results\n BOL\n while (Search_Block(@12, Cur_Pos, EOL_Pos, NOERR)) {\n Reg_Ins(12, OVERWRITE)\n }\n Buf_Switch(#23)\n }\n Line(1, ERRBREAK)\n }\n\n Buf_Switch(#22)\n BOL\n #37 = Search_Block(\"|V\", Cur_Pos, EOL_Pos, ALL+NOERR)\nReturn\n", "language": "Vedit-macro-language" }, { "code": "import \"./math\" for Nums\nimport \"./iterate\" for Stepped\nimport \"./str\" for Char, Str\nimport \"./fmt\" for Fmt\n\nvar encoded =\n \"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\" +\n \"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\" +\n \"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\" +\n \"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\" +\n \"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\" +\n \"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\" +\n \"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\" +\n \"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\" +\n \"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\" +\n \"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\" +\n \"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\" +\n \"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\" +\n \"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\" +\n \"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\" +\n \"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\" +\n \"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\" +\n \"FWAML ZZRXJ EKAHV FASMU LVVUT TGK\"\n\nvar freq = [\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074\n]\n\nvar bestMatch = Fn.new { |a|\n var sum = Nums.sum(a)\n var bestFit = 1e100\n var bestRotate = 0\n for (rotate in 0..25) {\n var fit = 0\n for (i in 0..25) {\n var d = a[(i + rotate) % 26] / sum - freq[i]\n fit = fit + d * d / freq[i]\n }\n if (fit < bestFit) {\n bestFit = fit\n bestRotate = rotate\n }\n }\n return bestRotate\n}\n\nvar freqEveryNth = Fn.new { |msg, key|\n var len = msg.count\n var interval = key.count\n var out = List.filled(26, 0)\n var accu = List.filled(26, 0)\n for (j in 0...interval) {\n for (i in 0..25) out[i] = 0\n for (i in Stepped.new(j...len, interval)) out[msg[i]] = out[msg[i]] + 1\n var rot = bestMatch.call(out)\n key[j] = Char.fromCode(rot + 65)\n for (i in 0..25) accu[i] = accu[i] + out[(i + rot) % 26]\n }\n var sum = Nums.sum(accu)\n var ret = 0\n for (i in 0..25) {\n var d = accu[i] / sum - freq[i]\n ret = ret + d * d / freq[i]\n }\n return ret\n}\n\nvar decrypt = Fn.new { |text, key|\n var sb = \"\"\n var ki = 0\n for (c in text) {\n if (Char.isAsciiUpper(c)) {\n var ci = (c.bytes[0] - key[ki].bytes[0] + 26) % 26\n sb = sb + Char.fromCode(ci + 65)\n ki = (ki + 1) % key.count\n }\n }\n return sb\n}\n\nvar enc = encoded.replace(\" \", \"\")\nvar txt = List.filled(enc.count, 0)\nfor (i in 0...txt.count) txt[i] = Char.code(enc[i]) - 65\nvar bestFit = 1e100\nvar bestKey = \"\"\nvar f = \"$f $2d $s\"\nSystem.print(\" Fit Length Key\")\nfor (j in 1..26) {\n var key = List.filled(j, \"\")\n var fit = freqEveryNth.call(txt, key)\n var sKey = key.join(\"\")\n Fmt.write(f, fit, j, sKey)\n if (fit < bestFit) {\n bestFit = fit\n bestKey = sKey\n System.write(\" <--- best so far\")\n }\n System.print()\n}\nSystem.print()\nSystem.print(\"Best key : %(bestKey)\")\nSystem.print(\"\\nDecrypted text:\\n%(decrypt.call(enc, bestKey))\")\n", "language": "Wren" }, { "code": "var[const] uppercase=[\"A\"..\"Z\"].pump(String),\n english_frequences=T( // A..Z\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074);\n\nfcn vigenere_decrypt(target_freqs, input){ // ( (float,...), string)\n nchars,ordA :=uppercase.len(),\"A\".toAsc();\n sorted_targets:=target_freqs.sort();\n\n frequency:='wrap(input){ // (n,n,n,n,...), n is ASCII index (\"A\"==65)\n result:=uppercase.pump(List(),List.fp1(0)); // ( (\"A\",0),(\"B\",0) ...)\n foreach c in (input){ result[c - ordA][1] += 1 }\n result // --> mutable list of mutable lists ( (\"A\",Int)...(\"Z\",Int) )\n };\n correlation:='wrap(input){ // (n,n,n,n,...), n is ASCII index (\"A\"==65)\n result,freq:=0.0, frequency(input);\n freq.sort(fcn([(_,a)],[(_,b)]){ a<b }); // sort letters by frequency\n foreach i,f in (freq.enumerate()){ result+=sorted_targets[i]*f[1] }\n result\t// -->Float\n };\n\n cleaned:=input.toUpper().pump(List,uppercase.holds,Void.Filter,\"toAsc\");\n\n best_len,best_corr := 0,-100.0;\n # Assume that if there are less than 20 characters\n # per column, the key's too long to guess\n foreach i in ([2..cleaned.len()/20]){\n pieces:=(i).pump(List,List.copy);\t\t// ( (),() ... )\n foreach c in (cleaned){ pieces[__cWalker.idx%i].append(c) }\n\n # The correlation seems to increase for smaller\n # pieces/longer keys, so weigh against them a little\n corr:=-0.5*i + pieces.apply(correlation).sum(0.0);\n if(corr>best_corr) best_len,best_corr=i,corr;\n }\n if(best_len==0) return(\"Text is too short to analyze\", \"\");\n\n pieces:=best_len.pump(List,List.copy);\n foreach c in (cleaned){ pieces[__cWalker.idx%best_len].append(c) }\n\n key,freqs := \"\",pieces.apply(frequency);\n foreach fr in (freqs){\n fr.sort(fcn([(_,a)],[(_,b)]){ a>b }); // reverse sort by freq\n m,max_corr := 0,0.0;\n foreach j in (nchars){\n corr,c := 0.0,ordA + j;\n\t foreach frc in (fr){\n\t d:=(frc[0].toAsc() - c + nchars) % nchars;\n \t corr+=target_freqs[d]*frc[1];\n\t if(corr>max_corr) m,max_corr=j,corr;\n\t }\n }\n key+=(m + ordA).toChar();\n }\n\n cleaned.enumerate().apply('wrap([(i,c])){\n ( (c - (key[i%best_len]).toAsc() + nchars)%nchars + ordA ).toChar()\n }).concat() :\n T(key,_);\n}\n", "language": "Zkl" }, { "code": "encryptedText:=\n#<<<\n\"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\";\n#<<<\nkey,decoded:=vigenere_decrypt(english_frequences,encryptedText);\nprintln(\"Key:\", key);\nprintln(\"Decoded text:\", decoded);\n", "language": "Zkl" } ]
Vigen-re-cipher-Cryptanalysis
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Visualize_a_tree\n", "language": "00-META" }, { "code": "A tree structure &nbsp; (i.e. a rooted, connected acyclic graph) &nbsp; is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* &nbsp; indented text &nbsp; (à la unix <code> tree </code> command)\n:::* &nbsp; nested HTML tables\n:::* &nbsp; hierarchical GUI widgets\n:::* &nbsp; 2D &nbsp; or &nbsp; 3D &nbsp; images\n:::* &nbsp; etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "T Node\n String value\n Node? left\n Node? right\n\n F (value, Node? left = N, Node? right = N)\n .value = String(value)\n .left = left\n .right = right\n\n F tree_indent() -> [String]\n V tr = I .right != N {.right.tree_indent()} E [‘-- (null)’]\n R [‘--’(.value)] [+] (I .left != N {.left.tree_indent()} E [‘-- (null)’]).map(a -> ‘ |’a)\n [+] [‘ `’tr[0]] + tr[1..].map(a -> ‘ ’a)\n\nV tree = Node(1, Node(2, Node(4, Node(7)), Node(5)), Node(3, Node(6, Node(8), Node(9))))\nprint(tree.tree_indent().join(\"\\n\"))\n", "language": "11l" }, { "code": "with Ada.Text_IO, Ada.Directories;\n\nprocedure Directory_Tree is\n\n procedure Print_Tree(Current: String; Indention: Natural := 0) is\n\n function Spaces(N: Natural) return String is\n\t (if N= 0 then \"\" else \" \" & Spaces(N-1));\n\n use Ada.Directories;\n Search: Search_Type;\n Found: Directory_Entry_Type;\n\n begin\n Start_Search(Search, Current, \"\");\n while More_Entries(Search) loop\n\t Get_Next_Entry(Search, Found);\n\t declare\n\t Name: String := Simple_Name(Found);\n\t Dir: Boolean := Kind(Found) = Directory;\n\t begin\n\t if Name(Name'First) /= '.' then\n -- skip all files who's names start with \".\", namely \".\" and \"..\"\n\t Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found)\n\t\t & (if Dir then \" (dir)\" else \"\"));\n\t if Dir then\n\t\t Print_Tree(Full_Name(Found), Indention + 1);\n\t end if;\n\t end if;\n\t end;\t\n end loop;\n end Print_Tree;\n\nbegin\n Print_Tree(Ada.Directories.Current_Directory);\nend Directory_Tree;\n", "language": "Ada" }, { "code": "# outputs nested html tables to visualise a tree #\n\n# mode representing nodes of the tree #\nMODE NODE = STRUCT( STRING value, REF NODE child, REF NODE sibling );\nREF NODE nil node = NIL;\n\n# tags etc. #\nSTRING table = \"<table border=\"\"1\"\" cellspacing=\"\"4\"\">\"\n , elbat = \"</table>\"\n , tr = \"<tr>\"\n , rt = \"</tr>\"\n , td = \"<td style=\"\"text-align: center; vertical-align: top; \"\"\"\n , dt = \"</td>\"\n , nbsp = \"&nbsp;\"\n ;\nCHAR nl = REPR 10;\n\n# returns the number of child elements of tree #\nOP CHILDCOUNT = ( REF NODE tree )INT:\n BEGIN\n INT result := 0;\n REF NODE child := child OF tree;\n WHILE REF NODE( child ) ISNT nil node\n DO\n result +:= 1;\n child := sibling OF child\n OD;\n result\n END # CHILDCOUNT # ;\n\n# generates nested HTML tables from the tree #\nOP TOHTML = ( REF NODE tree )STRING:\n IF tree IS nil node\n THEN\n # no node #\n \"\"\n ELSE\n # hae at least one node #\n STRING result := \"\";\n INT child count = CHILDCOUNT tree;\n result +:= table + nl\n + tr + nl\n + td + \" colspan=\"\"\"\n + whole( IF child count < 1 THEN 1 ELSE child count FI, 0 )\n + \"\"\">\" + nbsp + value OF tree + nbsp\n + dt + nl\n + rt + nl\n ;\n IF child count > 0\n THEN\n # the node has branches #\n REF NODE child := child OF tree;\n INT child number := 1;\n INT mid child = ( child count + 1 ) OVER 2;\n child := child OF tree;\n result +:= tr + nl;\n WHILE child ISNT nil node\n DO\n result +:= td + \">\" + nl\n + IF CHILDCOUNT child < 1 THEN nbsp + value OF child + nbsp ELSE TOHTML child FI\n + dt + nl;\n child := sibling OF child\n OD;\n result +:= rt + nl\n FI;\n result +:= elbat + nl\n FI # TOHTML # ;\n\n# test the tree visualisation #\n\n# returns a new node with the specified value and no child or siblings #\nPROC new node = ( STRING value )REF NODE: HEAP NODE := NODE( value, nil node, nil node );\n# appends a sibling node to the node n, returns the sibling #\nOP +:= = ( REF NODE n, REF NODE sibling node )REF NODE:\n BEGIN\n REF NODE sibling := n;\n WHILE REF NODE( sibling OF sibling ) ISNT nil node\n DO\n sibling := sibling OF sibling\n OD;\n sibling OF sibling := sibling node\n END # +:= # ;\n# appends a new sibling node to the node n, returns the sibling #\nOP +:= = ( REF NODE n, STRING sibling value )REF NODE: n +:= new node( sibling value );\n# adds a child node to the node n, returns the child #\nOP /:= = ( REF NODE n, REF NODE child node )REF NODE: child OF n := child node;\n# adda a new child node to the node n, returns the child #\nOP /:= = ( REF NODE n, STRING child value )REF NODE: n /:= new node( child value );\n\nNODE animals := new node( \"animals\" );\nNODE fish := new node( \"fish\" );\nNODE reptiles := new node( \"reptiles\" );\nNODE mammals := new node( \"mammals\" );\nNODE primates := new node( \"primates\" );\nNODE sharks := new node( \"sharks\" );\nsharks /:= \"great-white\" +:= \"hammer-head\";\nfish /:= \"cod\" +:= sharks +:= \"piranha\";\nreptiles /:= \"iguana\" +:= \"brontosaurus\";\nprimates /:= \"gorilla\" +:= \"lemur\";\nmammals /:= \"sloth\" +:= \"horse\" +:= \"bison\" +:= primates;\nanimals /:= fish +:= reptiles +:= mammals;\n\nprint( ( TOHTML animals ) )\n", "language": "ALGOL-68" }, { "code": "-- Vertically centered textual tree using UTF8 monospaced\n-- box-drawing characters, with options for compacting\n-- and pruning.\n\n-- ┌── Gamma\n-- ┌─ Beta ┼── Delta\n-- │ └ Epsilon\n-- Alpha ┼─ Zeta ───── Eta\n-- │ ┌─── Iota\n-- └ Theta ┼── Kappa\n-- └─ Lambda\n\n-- TESTS --------------------------------------------------\non run\n set tree to Node(1, ¬\n {Node(2, ¬\n {Node(4, {Node(7, {})}), ¬\n Node(5, {})}), ¬\n Node(3, ¬\n {Node(6, ¬\n {Node(8, {}), Node(9, {})})})})\n\n set tree2 to Node(\"Alpha\", ¬\n {Node(\"Beta\", ¬\n {Node(\"Gamma\", {}), ¬\n Node(\"Delta\", {}), ¬\n Node(\"Epsilon\", {})}), ¬\n Node(\"Zeta\", {Node(\"Eta\", {})}), ¬\n Node(\"Theta\", ¬\n {Node(\"Iota\", {}), Node(\"Kappa\", {}), ¬\n Node(\"Lambda\", {})})})\n\n set strTrees to unlines({\"(NB – view in mono-spaced font)\\n\\n\", ¬\n \"Compacted (not all parents vertically centered):\\n\", ¬\n drawTree2(true, false, tree), ¬\n \"\\nFully expanded and vertically centered:\\n\", ¬\n drawTree2(false, false, tree2), ¬\n \"\\nVertically centered, with nodeless lines pruned out:\\n\", ¬\n drawTree2(false, true, tree2)})\n set the clipboard to strTrees\n strTrees\nend run\n\n\n-- drawTree2 :: Bool -> Bool -> Tree String -> String\non drawTree2(blnCompressed, blnPruned, tree)\n -- Tree design and algorithm inspired by the Haskell snippet at:\n -- https://doisinkidney.com/snippets/drawing-trees.html\n script measured\n on |λ|(t)\n script go\n on |λ|(x)\n set s to \" \" & x & \" \"\n Tuple(length of s, s)\n end |λ|\n end script\n fmapTree(go, t)\n end |λ|\n end script\n set measuredTree to |λ|(tree) of measured\n\n script levelMax\n on |λ|(a, level)\n a & maximum(map(my fst, level))\n end |λ|\n end script\n set levelWidths to foldl(levelMax, {}, ¬\n init(levels(measuredTree)))\n\n -- Lefts, Mid, Rights\n script lmrFromStrings\n on |λ|(xs)\n set {ls, rs} to items 2 thru -2 of ¬\n (splitAt((length of xs) div 2, xs) as list)\n Tuple3(ls, item 1 of rs, rest of rs)\n end |λ|\n end script\n\n script stringsFromLMR\n on |λ|(lmr)\n script add\n on |λ|(a, x)\n a & x\n end |λ|\n end script\n foldl(add, {}, items 2 thru -2 of (lmr as list))\n end |λ|\n end script\n\n script fghOverLMR\n on |λ|(f, g, h)\n script\n property mg : mReturn(g)\n on |λ|(lmr)\n set {ls, m, rs} to items 2 thru -2 of (lmr as list)\n Tuple3(map(f, ls), |λ|(m) of mg, map(h, rs))\n end |λ|\n end script\n end |λ|\n end script\n\n script lmrBuild\n on leftPad(n)\n script\n on |λ|(s)\n replicateString(n, space) & s\n end |λ|\n end script\n end leftPad\n\n -- lmrBuild main\n on |λ|(w, f)\n script\n property mf : mReturn(f)\n on |λ|(wsTree)\n set xs to nest of wsTree\n set lng to length of xs\n set {nChars, x} to items 2 thru -2 of ¬\n ((root of wsTree) as list)\n set _x to replicateString(w - nChars, \"─\") & x\n\n -- LEAF NODE ------------------------------------\n if 0 = lng then\n Tuple3({}, _x, {})\n\n else if 1 = lng then\n -- NODE WITH SINGLE CHILD ---------------------\n set indented to leftPad(1 + w)\n script lineLinked\n on |λ|(z)\n _x & \"─\" & z\n end |λ|\n end script\n |λ|(|λ|(item 1 of xs) of mf) of ¬\n (|λ|(indented, lineLinked, indented) of ¬\n fghOverLMR)\n else\n -- NODE WITH CHILDREN -------------------------\n script treeFix\n on cFix(x)\n script\n on |λ|(xs)\n x & xs\n end |λ|\n end script\n end cFix\n\n on |λ|(l, m, r)\n compose(stringsFromLMR, ¬\n |λ|(cFix(l), cFix(m), cFix(r)) of ¬\n fghOverLMR)\n end |λ|\n end script\n\n script linked\n on |λ|(s)\n set c to text 1 of s\n set t to tail(s)\n if \"┌\" = c then\n _x & \"┬\" & t\n else if \"│\" = c then\n _x & \"┤\" & t\n else if \"├\" = c then\n _x & \"┼\" & t\n else\n _x & \"┴\" & t\n end if\n end |λ|\n end script\n\n set indented to leftPad(w)\n set lmrs to map(f, xs)\n if blnCompressed then\n set sep to {}\n else\n set sep to {\"│\"}\n end if\n\n tell lmrFromStrings\n set tupleLMR to |λ|(intercalate(sep, ¬\n {|λ|(item 1 of lmrs) of ¬\n (|λ|(\" \", \"┌\", \"│\") of treeFix)} & ¬\n map(|λ|(\"│\", \"├\", \"│\") of treeFix, ¬\n init(tail(lmrs))) & ¬\n {|λ|(item -1 of lmrs) of ¬\n (|λ|(\"│\", \"└\", \" \") of treeFix)}))\n end tell\n\n |λ|(tupleLMR) of ¬\n (|λ|(indented, linked, indented) of fghOverLMR)\n end if\n end |λ|\n end script\n end |λ|\n end script\n\n set treeLines to |λ|(|λ|(measuredTree) of ¬\n foldr(lmrBuild, 0, levelWidths)) of stringsFromLMR\n if blnPruned then\n script notEmpty\n on |λ|(s)\n script isData\n on |λ|(c)\n \"│ \" does not contain c\n end |λ|\n end script\n any(isData, characters of s)\n end |λ|\n end script\n set xs to filter(notEmpty, treeLines)\n else\n set xs to treeLines\n end if\n unlines(xs)\nend drawTree2\n\n\n-- GENERIC ------------------------------------------------\n\n-- Node :: a -> [Tree a] -> Tree a\non Node(v, xs)\n {type:\"Node\", root:v, nest:xs}\nend Node\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n -- Constructor for a pair of values, possibly of two different types.\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n-- Tuple3 (,,) :: a -> b -> c -> (a, b, c)\non Tuple3(x, y, z)\n {type:\"Tuple3\", |1|:x, |2|:y, |3|:z, length:3}\nend Tuple3\n\n-- Applied to a predicate and a list,\n-- |any| returns true if at least one element of the\n-- list satisfies the predicate.\n-- any :: (a -> Bool) -> [a] -> Bool\non any(f, xs)\n tell mReturn(f)\n set lng to length of xs\n repeat with i from 1 to lng\n if |λ|(item i of xs) then return true\n end repeat\n false\n end tell\nend any\n\n-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\non compose(f, g)\n script\n property mf : mReturn(f)\n property mg : mReturn(g)\n on |λ|(x)\n |λ|(|λ|(x) of mg) of mf\n end |λ|\n end script\nend compose\n\n-- concat :: [[a]] -> [a]\n-- concat :: [String] -> String\non concat(xs)\n set lng to length of xs\n if 0 < lng and string is class of (item 1 of xs) then\n set acc to \"\"\n else\n set acc to {}\n end if\n repeat with i from 1 to lng\n set acc to acc & item i of xs\n end repeat\n acc\nend concat\n\n-- concatMap :: (a -> [b]) -> [a] -> [b]\non concatMap(f, xs)\n set lng to length of xs\n set acc to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set acc to acc & (|λ|(item i of xs, i, xs))\n end repeat\n end tell\n return acc\nend concatMap\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- fmapTree :: (a -> b) -> Tree a -> Tree b\non fmapTree(f, tree)\n script go\n property g : |λ| of mReturn(f)\n on |λ|(x)\n set xs to nest of x\n if xs ≠ {} then\n set ys to map(go, xs)\n else\n set ys to xs\n end if\n Node(g(root of x), ys)\n end |λ|\n end script\n |λ|(tree) of go\nend fmapTree\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- foldr :: (a -> b -> b) -> b -> [a] -> b\non foldr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from lng to 1 by -1\n set v to |λ|(item i of xs, v, i, xs)\n end repeat\n return v\n end tell\nend foldr\n\n-- fst :: (a, b) -> a\non fst(tpl)\n if class of tpl is record then\n |1| of tpl\n else\n item 1 of tpl\n end if\nend fst\n\n-- identity :: a -> a\non identity(x)\n -- The argument unchanged.\n x\nend identity\n\n-- init :: [a] -> [a]\n-- init :: [String] -> [String]\non init(xs)\n set blnString to class of xs = string\n set lng to length of xs\n\n if lng > 1 then\n if blnString then\n text 1 thru -2 of xs\n else\n items 1 thru -2 of xs\n end if\n else if lng > 0 then\n if blnString then\n \"\"\n else\n {}\n end if\n else\n missing value\n end if\nend init\n\n-- intercalate :: [a] -> [[a]] -> [a]\n-- intercalate :: String -> [String] -> String\non intercalate(sep, xs)\n concat(intersperse(sep, xs))\nend intercalate\n\n-- intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]\n-- intersperse :: a -> [a] -> [a]\n-- intersperse :: Char -> String -> String\non intersperse(sep, xs)\n set lng to length of xs\n if lng > 1 then\n set acc to {item 1 of xs}\n repeat with i from 2 to lng\n set acc to acc & {sep, item i of xs}\n end repeat\n if class of xs is string then\n concat(acc)\n else\n acc\n end if\n else\n xs\n end if\nend intersperse\n\n-- isNull :: [a] -> Bool\n-- isNull :: String -> Bool\non isNull(xs)\n if class of xs is string then\n \"\" = xs\n else\n {} = xs\n end if\nend isNull\n\n-- iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\non iterateUntil(p, f, x)\n script\n property mp : mReturn(p)'s |λ|\n property mf : mReturn(f)'s |λ|\n property lst : {x}\n on |λ|(v)\n repeat until mp(v)\n set v to mf(v)\n set end of lst to v\n end repeat\n return lst\n end |λ|\n end script\n |λ|(x) of result\nend iterateUntil\n\n-- levels :: Tree a -> [[a]]\non levels(tree)\n script nextLayer\n on |λ|(xs)\n script\n on |λ|(x)\n nest of x\n end |λ|\n end script\n concatMap(result, xs)\n end |λ|\n end script\n\n script roots\n on |λ|(xs)\n script\n on |λ|(x)\n root of x\n end |λ|\n end script\n map(result, xs)\n end |λ|\n end script\n\n map(roots, iterateUntil(my isNull, nextLayer, {tree}))\nend levels\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- maximum :: Ord a => [a] -> a\non maximum(xs)\n script\n on |λ|(a, b)\n if a is missing value or b > a then\n b\n else\n a\n end if\n end |λ|\n end script\n foldl(result, missing value, xs)\nend maximum\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- replicateString :: Int -> String -> String\non replicateString(n, s)\n set out to \"\"\n if n < 1 then return out\n set dbl to s\n\n repeat while (n > 1)\n if (n mod 2) > 0 then set out to out & dbl\n set n to (n div 2)\n set dbl to (dbl & dbl)\n end repeat\n return out & dbl\nend replicateString\n\n-- snd :: (a, b) -> b\non snd(tpl)\n if class of tpl is record then\n |2| of tpl\n else\n item 2 of tpl\n end if\nend snd\n\n-- splitAt :: Int -> [a] -> ([a], [a])\non splitAt(n, xs)\n if n > 0 and n < length of xs then\n if class of xs is text then\n Tuple(items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text)\n else\n Tuple(items 1 thru n of xs, items (n + 1) thru -1 of xs)\n end if\n else\n if n < 1 then\n Tuple({}, xs)\n else\n Tuple(xs, {})\n end if\n end if\nend splitAt\n\n-- tail :: [a] -> [a]\non tail(xs)\n set blnText to text is class of xs\n if blnText then\n set unit to \"\"\n else\n set unit to {}\n end if\n set lng to length of xs\n if 1 > lng then\n missing value\n else if 2 > lng then\n unit\n else\n if blnText then\n text 2 thru -1 of xs\n else\n rest of xs\n end if\n end if\nend tail\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set str to xs as text\n set my text item delimiters to dlm\n str\nend unlines\n", "language": "AppleScript" }, { "code": "@tree %cd%\n", "language": "Batch-File" }, { "code": " INSTALL @lib$+\"WINLIB5\"\n ON ERROR SYS \"MessageBox\", @hwnd%, REPORT$, 0, 0 : QUIT\n\n REM!WC Windows constants:\n TVI_SORT = -65533\n TVIF_TEXT = 1\n TVM_INSERTITEM = 4352\n TVS_HASBUTTONS = 1\n TVS_HASLINES = 2\n TVS_LINESATROOT = 4\n\n REM. TV_INSERTSTRUCT\n DIM tvi{hParent%, \\\n \\ hInsertAfter%, \\\n \\ mask%, \\\n \\ hItem%, \\\n \\ state%, \\\n \\ stateMask%, \\\n \\ pszText%, \\\n \\ cchTextMax%, \\\n \\ iImage%, \\\n \\ iSelectedImage%,\\\n \\ cChildren%, \\\n \\ lParam% \\\n \\ }\n\n SYS \"InitCommonControls\"\n hTree% = FN_createwindow(\"SysTreeView32\", \"\", 0, 0, @vdu.tr%, @vdu.tb%, 0, \\\n \\ TVS_HASLINES OR TVS_HASBUTTONS OR TVS_LINESATROOT, 0)\n hroot% = FNinsertnode(0, \"Root\")\n hchild1% = FNinsertnode(hroot%, \"Child 1\")\n hchild2% = FNinsertnode(hroot%, \"Child 2\")\n hchild11% = FNinsertnode(hchild1%, \"Grandchild 1\")\n hchild12% = FNinsertnode(hchild1%, \"Grandchild 2\")\n hchild21% = FNinsertnode(hchild2%, \"Grandchild 3\")\n hchild22% = FNinsertnode(hchild2%, \"Grandchild 4\")\n\n REPEAT\n WAIT 1\n UNTIL FALSE\n END\n\n DEF FNinsertnode(hparent%, text$)\n LOCAL hnode%\n text$ += CHR$0\n\n tvi.hParent% = hparent%\n tvi.hInsertAfter% = TVI_SORT\n tvi.mask% = TVIF_TEXT\n tvi.pszText% = !^text$\n\n SYS \"SendMessage\", hTree%, TVM_INSERTITEM, 0, tvi{} TO hnode%\n IF hnode% = 0 ERROR 100, \"TVM_INSERTITEM failed\"\n SYS \"InvalidateRect\", hTree%, 0, 0\n = hnode%\n", "language": "BBC-BASIC" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stem_t *stem;\nstruct stem_t { const char *str; stem next; };\n\nvoid tree(int root, stem head)\n{\n\tstatic const char *sdown = \" |\", *slast = \" `\", *snone = \" \";\n\tstruct stem_t col = {0, 0}, *tail;\n\n\tfor (tail = head; tail; tail = tail->next) {\n\t\tprintf(\"%s\", tail->str);\n\t\tif (!tail->next) break;\n\t}\n\n\tprintf(\"--%d\\n\", root);\n\n\tif (root <= 1) return;\n\n\tif (tail && tail->str == slast)\n\t\ttail->str = snone;\n\n\tif (!tail)\ttail = head = &col;\n\telse\t\ttail->next = &col;\n\n\twhile (root) { // make a tree by doing something random\n\t\tint r = 1 + (rand() % root);\n\t\troot -= r;\n\t\tcol.str = root ? sdown : slast;\n\n\t\ttree(r, head);\n\t}\n\n\ttail->next = 0;\n}\n\nint main(int c, char**v)\n{\n\tint n;\n\tif (c < 2 || (n = atoi(v[1])) < 0) n = 8;\n\n\ttree(n, 0);\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <functional>\n#include <iostream>\n#include <random>\n\nclass BinarySearchTree {\nprivate:\n struct Node {\n int key;\n Node *left, *right;\n\n Node(int k) : key(k), left(nullptr), right(nullptr) {\n //empty\n }\n } *root;\n\npublic:\n BinarySearchTree() : root(nullptr) {\n // empty\n }\n\n bool insert(int key) {\n if (root == nullptr) {\n root = new Node(key);\n } else {\n auto n = root;\n Node *parent;\n while (true) {\n if (n->key == key) {\n return false;\n }\n\n parent = n;\n\n bool goLeft = key < n->key;\n n = goLeft ? n->left : n->right;\n\n if (n == nullptr) {\n if (goLeft) {\n parent->left = new Node(key);\n } else {\n parent->right = new Node(key);\n }\n break;\n }\n }\n }\n return true;\n }\n\n friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &);\n};\n\ntemplate<typename T>\nvoid display(std::ostream &os, const T *n) {\n if (n != nullptr) {\n os << \"Node(\";\n\n display(os, n->left);\n\n os << ',' << n->key << ',';\n\n display(os, n->right);\n\n os << \")\";\n } else {\n os << '-';\n }\n}\n\nstd::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) {\n display(os, bst.root);\n return os;\n}\n\nint main() {\n std::default_random_engine generator;\n std::uniform_int_distribution<int> distribution(0, 200);\n auto rng = std::bind(distribution, generator);\n\n BinarySearchTree tree;\n\n tree.insert(100);\n for (size_t i = 0; i < 20; i++) {\n tree.insert(rng());\n }\n std::cout << tree << '\\n';\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\npublic static class VisualizeTree\n{\n public static void Main() {\n \"A\".t(\n \"B0\".t(\n \"C1\",\n \"C2\".t(\n \"D\".t(\"E1\", \"E2\", \"E3\")),\n \"C3\".t(\n \"F1\",\n \"F2\",\n \"F3\".t(\"G\"),\n \"F4\".t(\"H1\", \"H2\"))),\n \"B1\".t(\n \"K1\",\n \"K2\".t(\n \"L1\".t(\"M\"),\n \"L2\",\n \"L3\"),\n \"K3\")\n ).Print();\n }\n\n private static Tree t(this string value, params Tree[] children) => new Tree(value, children);\n\n private static void Print(this Tree tree) => tree.Print(true, \"\");\n\n private static void Print(this Tree tree, bool last, string prefix) {\n (string current, string next) = last\n ? (prefix + \"└─\" + tree.Value, prefix + \" \")\n : (prefix + \"├─\" + tree.Value, prefix + \"| \");\n Console.WriteLine(current[2..]);\n for (int c = 0; c < tree.Children.Length; c++) {\n tree.Children[c].Print(c == tree.Children.Length - 1, next);\n }\n }\n\n class Tree\n {\n public Tree(string value, params Tree[] children) => (Value, Children) = (value, children);\n public static implicit operator Tree(string value) => new Tree(value);\n public string Value { get; }\n public Tree[] Children { get; }\n }\n\n}\n", "language": "C-sharp" }, { "code": "(use 'vijual)\n\n(draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])\n", "language": "Clojure" }, { "code": "(defun visualize (tree)\n (labels\n ((rprint (list)\n (mapc #'princ (reverse list)))\n (vis-h (tree branches)\n (let ((len (length tree)))\n (loop\n for item in tree\n for idx from 1 to len do\n (cond\n ((listp item)\n (rprint (cdr branches))\n (princ \"+---+\")\n (let ((next (cons \"| \"\n (if (= idx len)\n (cons \" \" (cdr branches))\n branches))))\n (terpri)\n (rprint (if (null item)\n (cdr next)\n next))\n (terpri)\n (vis-h item next)))\n (t\n (rprint (cdr branches))\n (princ item)\n (terpri)\n (rprint (if (= idx len)\n (cdr branches)\n branches))\n (terpri)))))))\n (vis-h tree '(\"| \"))))\n", "language": "Common-Lisp" }, { "code": "CL-USER> (visualize '(a b c ((d (e ((() ()))) f)) (g)))\nA\n|\nB\n|\nC\n|\n+---+\n| |\n| +---+\n| |\n| D\n| |\n| +---+\n| | |\n| | E\n| | |\n| | +---+\n| | |\n| | +---+\n| | |\n| | +---+\n| | |\n| | +---+\n| |\n| F\n|\n+---+\n |\n G\n\nNIL\n", "language": "Common-Lisp" }, { "code": "(use-package :iterate)\n(defun print-tree (tree value-function children-function)\n (labels\n ((do-print-tree (tree prefix)\n (format t \"~a~%\" (funcall value-function tree))\n (iter\n (with children = (funcall children-function tree))\n (for child = (pop children))\n (while child)\n\n (if children\n (progn (format t \"~a├─ \" prefix)\n (do-print-tree child (format nil \"~a│ \" prefix)))\n (progn (format t \"~a└─ \" prefix)\n (do-print-tree child (format nil \"~a \" prefix)))))))\n (do-print-tree tree \"\")))\n", "language": "Common-Lisp" }, { "code": "CL-USER>(print-tree '(a\n (aa\n (aaa\n (aaaa)\n (aaab\n (aaaba)\n (aaabb))\n (aaac)))\n (ab)\n (ac\n (aca)\n (acb)\n (acc)))\n #'car #'cdr)\nA\n├─ AA\n│ └─ AAA\n│ ├─ AAAA\n│ ├─ AAAB\n│ │ ├─ AAABA\n│ │ └─ AAABB\n│ └─ AAAC\n├─ AB\n└─ AC\n ├─ ACA\n ├─ ACB\n └─ ACC\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.conv, std.algorithm, std.array;\n\nstruct Node(T) { T value; Node* left, right; }\n\nstring[] treeIndent(T)(in Node!T* t) pure nothrow @safe {\n if (!t) return [\"-- (null)\"];\n const tr = t.right.treeIndent;\n return \"--\" ~ t.value.text ~\n t.left.treeIndent.map!q{\" |\" ~ a}.array ~\n (\" `\" ~ tr[0]) ~ tr[1 .. $].map!q{\" \" ~ a}.array;\n}\n\nvoid main () {\n static N(T)(T v, Node!T* l=null, Node!T* r=null) {\n return new Node!T(v, l, r);\n }\n\n const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));\n writefln(\"%-(%s\\n%)\", tree.treeIndent);\n}\n", "language": "D" }, { "code": "program Visualize_a_tree;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\ntype\n TNode = record\n _label: string;\n children: TArray<Integer>;\n end;\n\n TTree = TArray<TNode>;\n\n TTreeHelper = record helper for TTree\n procedure AddNode(lb: string; chl: TArray<Integer> = []);\n end;\n\nprocedure Vis(t: TTree);\n\n procedure f(n: Integer; pre: string);\n begin\n var ch := t[n].children;\n if Length(ch) = 0 then\n begin\n Writeln('-', t[n]._label);\n exit;\n end;\n\n writeln('+', t[n]._label);\n var last := Length(ch) - 1;\n for var c in copy(ch, 0, last) do\n begin\n write(pre, '+-');\n f(c, pre + '¦ ');\n end;\n write(pre, '+-');\n f(ch[last], pre + ' ');\n end;\n\nbegin\n if Length(t) = 0 then\n begin\n writeln('<empty>');\n exit;\n end;\n\n f(0, '');\nend;\n\n{ TTreeHelper }\n\nprocedure TTreeHelper.AddNode(lb: string; chl: TArray<Integer> = []);\nbegin\n SetLength(self, Length(self) + 1);\n with self[High(self)] do\n begin\n _label := lb;\n if Length(chl) > 0 then\n children := copy(chl, 0, length(chl));\n end;\nend;\n\nvar\n Tree: TTree;\n\nbegin\n Tree.AddNode('root', [1, 2, 3]);\n Tree.AddNode('ei', [4, 5]);\n Tree.AddNode('bee');\n Tree.AddNode('si');\n Tree.AddNode('dee');\n Tree.AddNode('y', [6]);\n Tree.AddNode('eff');\n\n Vis(Tree);\n\n {$IFNDEF UNIX} readln; {$ENDIF}\nend.\n", "language": "Delphi" }, { "code": "import system'routines;\nimport extensions;\n\nclass Node\n{\n string theValue;\n Node[] theChildren;\n\n constructor new(string value, Node[] children)\n {\n theValue := value;\n\n theChildren := children;\n }\n\n constructor new(string value)\n <= new(value, new Node[](0));\n\n constructor new(Node[] children)\n <= new(emptyString, children);\n\n get() = theValue;\n\n Children = theChildren;\n}\n\nextension treeOp\n{\n writeTree(node, prefix)\n {\n var children := node.Children;\n var length := children.Length;\n\n children.zipForEach(new Range(1, length), (child,index)\n {\n self.printLine(prefix,\"|\");\n self.printLine(prefix,\"+---\",child.get());\n\n var nodeLine := prefix + (index==length).iif(\" \",\"| \");\n\n self.writeTree(child,nodeLine);\n });\n\n ^ self\n }\n\n writeTree(node)\n = self.writeTree(node,\"\");\n}\n\npublic program()\n{\n var tree := Node.new(\n new Node[]{\n Node.new(\"a\", new Node[]\n {\n Node.new(\"b\", new Node[]{Node.new(\"c\")}),\n Node.new(\"d\")\n }),\n Node.new(\"e\")\n });\n\n console.writeTree(tree).readChar()\n}\n", "language": "Elena" }, { "code": "type tree =\n | T of string * tree list\n\nlet prefMid = seq { yield \"├─\"; while true do yield \"│ \" }\nlet prefEnd = seq { yield \"└─\"; while true do yield \" \" }\nlet prefNone = seq { while true do yield \"\" }\n\nlet c2 x y = Seq.map2 (fun u v -> String.concat \"\" [u; v]) x y\n\nlet rec visualize (T(label, children)) pre =\n seq {\n yield (Seq.head pre) + label\n if children <> [] then\n let preRest = Seq.skip 1 pre\n let last = Seq.last (List.toSeq children)\n for e in children do\n if e = last then yield! visualize e (c2 preRest prefEnd)\n else yield! visualize e (c2 preRest prefMid)\n }\n\nlet example =\n T (\"root\",\n [T (\"a\",\n [T (\"a1\",\n [T (\"a11\", []);\n T (\"a12\", []) ]) ]);\n T (\"b\",\n [T (\"b1\", []) ]) ])\n\nvisualize example prefNone\n|> Seq.iter (printfn \"%s\")\n", "language": "F-Sharp" }, { "code": "USE: literals\n\nCONSTANT: mammals { \"mammals\" { \"deer\" \"gorilla\" \"dolphin\" } }\nCONSTANT: reptiles { \"reptiles\" { \"turtle\" \"lizard\" \"snake\" } }\n\n{ \"animals\" ${ mammals reptiles } } dup . 10 margin set .\n", "language": "Factor" }, { "code": "USE: trees.avl\nAVL{ { 1 2 } { 9 19 } { 3 4 } { 5 6 } } .\n", "language": "Factor" }, { "code": "Dim Shared As Ubyte colores(4) => {7,13,14,3,2}\n\nSub showTree(n As Integer, A As String)\n Dim As Integer i, co = 0, b = 1, col\n Dim As String cs = Left(A, 1)\n\n If cs = \"\" Then Exit Sub\n\n Select Case cs\n Case \"[\"\n co += 1 : showTree(n + 1, Right(A, Len(A) - 1))\n Exit Select\n Case \"]\"\n co -= 1 : showTree(n - 1, Right(A, Len(A) - 1))\n Exit Select\n Case Else\n For i = 2 To n\n Print \" \";\n co = n\n Next i\n Color colores(co) : Print !\"\\&hc0-\"; cs\n showTree(n, Right(A, Len(A) - 1))\n Exit Select\n End Select\nEnd Sub\n\nCls\nshowTree(0, \"[1[2[3][4[5][6]][7]][8[9]]]\")\nPrint !\"\\n\\n\\n\"\nshowTree(0, \"[1[2[3[4]]][5[6][7[8][9]]]]\")\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"log\"\n)\n\ntype Node struct {\n Name string\n Children []*Node\n}\n\nfunc main() {\n tree := &Node{\"root\", []*Node{\n &Node{\"a\", []*Node{\n &Node{\"d\", nil},\n &Node{\"e\", []*Node{\n &Node{\"f\", nil},\n }}}},\n &Node{\"b\", nil},\n &Node{\"c\", nil},\n }}\n b, err := json.MarshalIndent(tree, \"\", \" \")\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(string(b))\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"log\"\n \"os\"\n\n \"github.com/BurntSushi/toml\"\n)\n\ntype Node struct {\n Name string\n Children []*Node\n}\n\nfunc main() {\n tree := &Node{\"root\", []*Node{\n &Node{\"a\", []*Node{\n &Node{\"d\", nil},\n &Node{\"e\", []*Node{\n &Node{\"f\", nil},\n }}}},\n &Node{\"b\", nil},\n &Node{\"c\", nil},\n }}\n enc := toml.NewEncoder(os.Stdout)\n enc.Indent = \" \"\n err := enc.Encode(tree)\n if err != nil {\n log.Fatal(err)\n }\n}\n", "language": "Go" }, { "code": "package main\n\nimport \"fmt\"\n\ntype tree []node\n\ntype node struct {\n label string\n children []int // indexes into tree\n}\n\nfunc main() {\n vis(tree{\n 0: node{\"root\", []int{1, 2, 3}},\n 1: node{\"ei\", []int{4, 5}},\n 2: node{\"bee\", nil},\n 3: node{\"si\", nil},\n 4: node{\"dee\", nil},\n 5: node{\"y\", []int{6}},\n 6: node{\"eff\", nil},\n })\n}\n\nfunc vis(t tree) {\n if len(t) == 0 {\n fmt.Println(\"<empty>\")\n return\n }\n var f func(int, string)\n f = func(n int, pre string) {\n ch := t[n].children\n if len(ch) == 0 {\n fmt.Println(\"╴\", t[n].label)\n return\n }\n fmt.Println(\"┐\", t[n].label)\n last := len(ch) - 1\n for _, ch := range ch[:last] {\n fmt.Print(pre, \"├─\")\n f(ch, pre+\"│ \")\n }\n fmt.Print(pre, \"└─\")\n f(ch[last], pre+\" \")\n }\n f(0, \"\")\n}\n", "language": "Go" }, { "code": "data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }\n\tderiving (Show, Eq)\n\ntree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty)\n\t(Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty)\n\t(Node 9 Empty Empty)) Empty)\n\ntreeIndent Empty = [\"-- (nil)\"]\ntreeIndent t = [\"--\" ++ show (value t)]\n\t++ map (\" |\"++) ls ++ (\" `\" ++ r):map (\" \"++) rs\n\twhere\n\t(r:rs) = treeIndent$right t\n\tls = treeIndent$left t\n\nmain = mapM_ putStrLn $ treeIndent tree\n", "language": "Haskell" }, { "code": "import Data.Tree (Tree(..), drawTree)\n\ntree :: Tree Int\ntree =\n Node\n 1\n [ Node 2 [Node 4 [Node 7 []], Node 5 []]\n , Node 3 [Node 6 [Node 8 [], Node 9 []]]\n ]\n\nmain :: IO ()\nmain = (putStrLn . drawTree . fmap show) tree\n", "language": "Haskell" }, { "code": "procedure main(A)\n showTree(\"\", \" -\", [1, [2,[3],[4,[5],[6]],[7,[11]]], [8,[9,[10]]] ])\n write()\n showTree(\"\", \" -\", [1, [2,[3,[4]]], [5,[6],[7,[8],[9]],[10]] ])\nend\n\nprocedure showTree(prefix, lastc, A)\n write(prefix, lastc, \"--\", A[1])\n if *A > 1 then {\n prefix ||:= if prefix[-1] == \"|\" then \" \" else \" \"\n every showTree(prefix||\"|\", \"-\", !A[2:2 < *A])\n showTree(prefix, \"`-\", A[*A])\n }\nend\n", "language": "Icon" }, { "code": "BOXC=: 9!:6 '' NB. box drawing characters\nEW =: {: BOXC NB. east-west\n\nshowtree=: 4 : 0\n NB. y is parent index for each node (non-indices for root nodes)\n NB. x is label for each node\n t=. (<EW,' ') ,@<@,:@,&\":&.> x NB. tree fragments\n c=. |:(#~ e./@|:);(~.,\"0&.>(</. i.@#)) y\n while. +./ b=. ({.c)*.//.-.e.~/c do.\n i=. b#~.{.c NB. parents whose children are leaves\n j=. </./(({.c)e.i)#\"1 c NB. leaves grouped by parents\n t=. a: (;j)}t i}~ (i{t) subtree&.> j{&.><t\n c=. (-.({.c)e.i)#\"1 c NB. prune edges to leaves\n end.\n ;([: ,.&.>/ extend&.>)&> t -. a:\n)\n\nsubtree=: 4 : 0\n p=. EW={.\"1 s=. >{.t=. graft y\n (<(>{.x) root p),(<(connect p),.s),}.t\n)\n\ngraft=: 3 : 0\n n=. (-~ >./) #&> y\n f=. i.@(,&0)@#&.>@{.&.> y\n ,&.>/ y ,&> n$&.>f\n)\n\nconnect=: 3 : 0\n b=. (+./\\ *. +./\\.) y\n c=. (b+2*y){' ',9 3 3{BOXC NB. │ NS ├ E\n c=. (0{BOXC) (b i. 1)}c NB. ┌ NW\n c=. (6{BOXC) (b i: 1)}c NB. └ SW\n j=. (b i. 1)+<.-:+/b\n EW&(j})^:(1=+/b) c j}~ ((0 3 6 9{BOXC)i.j{c){1 4 7 5{BOXC\n)\n\nroot=: 4 : 0\n j=. k+<.-:1+(y i: 1)-k=. y i. 1\n (-j)|.(#y){.x,.,:' ',EW\n)\n\nextend=: 3 : '(+./\\\"1 (y=EW) *. *./\\.\"1 y e.'' '',EW)}y,:EW'\n", "language": "J" }, { "code": " (i.10) showtree _,}.p:inv i.10\n ┌─ 6\n ┌─ 1 ─── 3 ─┴─ 7\n │ ┌─ 8\n─ 0 ─┤ ┌─ 4 ─┴─ 9\n └─ 2 ─┴─ 5\n", "language": "J" }, { "code": " (i.10),: _,}.p:inv i.10\n0 1 2 3 4 5 6 7 8 9\n_ 0 0 1 2 2 3 3 4 4\n", "language": "J" }, { "code": " ((<'george') 0} (<'fred') 4} \":each i.10)showtree _,}.p:inv i.10\n ┌─ 6\n ┌─ 1 ─── 3 ────┴─ 7\n │ ┌─ 8\n─ george ─┤ ┌─ fred ─┴─ 9\n └─ 2 ─┴─ 5\n", "language": "J" }, { "code": "public class VisualizeTree {\n public static void main(String[] args) {\n BinarySearchTree tree = new BinarySearchTree();\n\n tree.insert(100);\n for (int i = 0; i < 20; i++)\n tree.insert((int) (Math.random() * 200));\n tree.display();\n }\n}\n\nclass BinarySearchTree {\n private Node root;\n\n private class Node {\n private int key;\n private Node left, right;\n\n Node(int k) {\n key = k;\n }\n }\n\n public boolean insert(int key) {\n if (root == null)\n root = new Node(key);\n else {\n Node n = root;\n Node parent;\n while (true) {\n if (n.key == key)\n return false;\n\n parent = n;\n\n boolean goLeft = key < n.key;\n n = goLeft ? n.left : n.right;\n\n if (n == null) {\n if (goLeft) {\n parent.left = new Node(key);\n } else {\n parent.right = new Node(key);\n }\n break;\n }\n }\n }\n return true;\n }\n\n public void display() {\n final int height = 5, width = 64;\n\n int len = width * height * 2 + 2;\n StringBuilder sb = new StringBuilder(len);\n for (int i = 1; i <= len; i++)\n sb.append(i < len - 2 && i % width == 0 ? \"\\n\" : ' ');\n\n displayR(sb, width / 2, 1, width / 4, width, root, \" \");\n System.out.println(sb);\n }\n\n private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n,\n String edge) {\n if (n != null) {\n displayR(sb, c - d, r + 2, d / 2, w, n.left, \" /\");\n\n String s = String.valueOf(n.key);\n int idx1 = r * w + c - (s.length() + 1) / 2;\n int idx2 = idx1 + s.length();\n int idx3 = idx1 - w;\n if (idx2 < sb.length())\n sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge);\n\n displayR(sb, c + d, r + 2, d / 2, w, n.right, \"\\\\ \");\n }\n }\n}\n", "language": "Java" }, { "code": "<!doctype html>\n<html id=\"doc\">\n <head><meta charset=\"utf-8\"/>\n <title>Stuff</title>\n <script type=\"application/javascript\">\n\tfunction gid(id) { return document.getElementById(id); }\n\n\tfunction ce(tag, cls, parent_node) {\n\t\tvar e = document.createElement(tag);\n\t\te.className = cls;\n\t\tif (parent_node) parent_node.appendChild(e);\n\t\treturn e;\n\t}\n\n\tfunction dom_tree(id) {\n\t\tgid('tree').textContent = \"\";\n\t\tgid('tree').appendChild(mktree(gid(id), null));\n\t}\n\n\tfunction mktree(e, p) {\n\t\tvar t = ce(\"div\", \"tree\", p);\n\t\tvar tog = ce(\"span\", \"toggle\", t);\n\t\tvar h = ce(\"span\", \"tag\", t);\n\n\t\tif (e.tagName === undefined) {\n\t\t\th.textContent = \"#Text\";\n\t\t\tvar txt = e.textContent;\n\t\t\tif (txt.length > 0 && txt.match(/\\S/)) {\n\t\t\t\th = ce(\"div\", \"txt\", t);\n\t\t\t\th.textContent = txt;\n\t\t\t}\n\t\t\treturn t;\n\t\t}\n\n\t\ttog.textContent = \"−\";\n\t\ttog.onclick = function () { clicked(tog); }\n\t\th.textContent = e.nodeName;\n\n\t\tvar l = e.childNodes;\n\t\tfor (var i = 0; i != l.length; i++)\n\t\t\tmktree(l[i], t);\n\t\treturn t;\n\t}\n\n\tfunction clicked(e) {\n\t\tvar is_on = e.textContent == \"−\";\n\t\te.textContent = is_on ? \"+\" : \"−\";\n\t\te.parentNode.className = is_on ? \"tree-hide\" : \"tree\";\n\t}\n </script>\n <style>\n #tree { white-space: pre; font-family: monospace; border: 1px solid }\n .tree > .tree-hide, .tree > .tree\n\t\t{ margin-left: 2em; border-left: 1px dotted rgba(0,0,0,.2)}\n .tree-hide > .tree, .tree-hide > .tree-hide { display: none }\n .tag { color: navy }\n .tree-hide > .tag { color: maroon }\n .txt { color: gray; padding: 0 .5em; margin: 0 .5em 0 2em; border: 1px dotted rgba(0,0,0,.1) }\n .toggle { display: inline-block; width: 2em; text-align: center }\n </style>\n </head>\n <body>\n <article>\n <section>\n <h1>Headline</h1>\n Blah blah\n </section>\n <section>\n <h1>More headline</h1>\n <blockquote>Something something</blockquote>\n <section><h2>Nested section</h2>\n\t Somethin somethin list:\n\t <ul>\n\t <li>Apples</li>\n\t <li>Oranges</li>\n\t <li>Cetera Fruits</li>\n\t </ul>\n\t</section>\n </section>\n </article>\n <div id=\"tree\"><a href=\"javascript:dom_tree('doc')\">click me</a></div>\n </body>\n</html>\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // UTF8 character-drawn tree, with options for compacting vs\n // centering parents, and for pruning out nodeless lines.\n\n const example = `\n ┌ Epsilon\n ┌─ Beta ┼─── Zeta\n │ └──── Eta\n Alpha ┼ Gamma ─── Theta\n │ ┌─── Iota\n └ Delta ┼── Kappa\n └─ Lambda`\n\n // drawTree2 :: Bool -> Bool -> Tree String -> String\n const drawTree2 = blnCompact => blnPruned => tree => {\n // Tree design and algorithm inspired by the Haskell snippet at:\n // https://doisinkidney.com/snippets/drawing-trees.html\n const\n // Lefts, Middle, Rights\n lmrFromStrings = xs => {\n const [ls, rs] = Array.from(splitAt(\n Math.floor(xs.length / 2),\n xs\n ));\n return Tuple3(ls, rs[0], rs.slice(1));\n },\n stringsFromLMR = lmr =>\n Array.from(lmr).reduce((a, x) => a.concat(x), []),\n fghOverLMR = (f, g, h) => lmr => {\n const [ls, m, rs] = Array.from(lmr);\n return Tuple3(ls.map(f), g(m), rs.map(h));\n };\n\n const lmrBuild = (f, w) => wsTree => {\n const\n leftPad = n => s => ' '.repeat(n) + s,\n xs = wsTree.nest,\n lng = xs.length,\n [nChars, x] = Array.from(wsTree.root);\n\n // LEAF NODE --------------------------------------\n return 0 === lng ? (\n Tuple3([], '─'.repeat(w - nChars) + x, [])\n\n // NODE WITH SINGLE CHILD -------------------------\n ) : 1 === lng ? (() => {\n const indented = leftPad(1 + w);\n return fghOverLMR(\n indented,\n z => '─'.repeat(w - nChars) + x + '─' + z,\n indented\n )(f(xs[0]));\n\n // NODE WITH CHILDREN -----------------------------\n })() : (() => {\n const\n cFix = x => xs => x + xs,\n treeFix = (l, m, r) => compose(\n stringsFromLMR,\n fghOverLMR(cFix(l), cFix(m), cFix(r))\n ),\n _x = '─'.repeat(w - nChars) + x,\n indented = leftPad(w),\n lmrs = xs.map(f);\n return fghOverLMR(\n indented,\n s => _x + ({\n '┌': '┬',\n '├': '┼',\n '│': '┤',\n '└': '┴'\n })[s[0]] + s.slice(1),\n indented\n )(lmrFromStrings(\n intercalate(\n blnCompact ? [] : ['│'],\n [treeFix(' ', '┌', '│')(lmrs[0])]\n .concat(init(lmrs.slice(1)).map(\n treeFix('│', '├', '│')\n ))\n .concat([treeFix('│', '└', ' ')(\n lmrs[lmrs.length - 1]\n )])\n )\n ));\n })();\n };\n const\n measuredTree = fmapTree(\n v => {\n const s = ' ' + v + ' ';\n return Tuple(s.length, s)\n }, tree\n ),\n levelWidths = init(levels(measuredTree))\n .reduce(\n (a, level) => a.concat(maximum(level.map(fst))),\n []\n ),\n treeLines = stringsFromLMR(\n levelWidths.reduceRight(\n lmrBuild, x => x\n )(measuredTree)\n );\n return unlines(\n blnPruned ? (\n treeLines.filter(\n s => s.split('')\n .some(c => !' │'.includes(c))\n )\n ) : treeLines\n );\n };\n\n // TESTS ----------------------------------------------\n const main = () => {\n\n // tree :: Tree String\n const tree = Node(\n 'Alpha', [\n Node('Beta', [\n Node('Epsilon', []),\n Node('Zeta', []),\n Node('Eta', [])\n ]),\n Node('Gamma', [Node('Theta', [])]),\n Node('Delta', [\n Node('Iota', []),\n Node('Kappa', []),\n Node('Lambda', [])\n ])\n ]);\n\n // tree2 :: Tree Int\n const tree2 = Node(\n 1,\n [\n Node(2, [\n Node(4, []),\n Node(5, [Node(7, [])])\n ]),\n Node(3, [\n Node(6, [\n Node(8, []),\n Node(9, [])\n ])\n ])\n ]\n );\n\n // strTrees :: String\n const strTrees = ([\n 'Compacted (parents not all vertically centered):',\n drawTree2(true)(false)(tree2),\n 'Fully expanded, with vertical centering:',\n drawTree2(false)(false)(tree),\n 'Vertically centered, with nodeless lines pruned out:',\n drawTree2(false)(true)(tree),\n ].join('\\n\\n'));\n\n return (\n console.log(strTrees),\n strTrees\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // Tuple3 (,,) :: a -> b -> c -> (a, b, c)\n const Tuple3 = (a, b, c) => ({\n type: 'Tuple3',\n '0': a,\n '1': b,\n '2': c,\n length: 3\n });\n\n // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\n const compose = (f, g) => x => f(g(x));\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // fmapTree :: (a -> b) -> Tree a -> Tree b\n const fmapTree = (f, tree) => {\n const go = node => Node(\n f(node.root),\n node.nest.map(go)\n );\n return go(tree);\n };\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // identity :: a -> a\n const identity = x => x;\n\n // init :: [a] -> [a]\n const init = xs =>\n 0 < xs.length ? (\n xs.slice(0, -1)\n ) : undefined;\n\n // intercalate :: [a] -> [[a]] -> [a]\n // intercalate :: String -> [String] -> String\n const intercalate = (sep, xs) =>\n 0 < xs.length && 'string' === typeof sep &&\n 'string' === typeof xs[0] ? (\n xs.join(sep)\n ) : concat(intersperse(sep, xs));\n\n // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3]\n\n // intersperse :: a -> [a] -> [a]\n // intersperse :: Char -> String -> String\n const intersperse = (sep, xs) => {\n const bln = 'string' === typeof xs;\n return xs.length > 1 ? (\n (bln ? concat : x => x)(\n (bln ? (\n xs.split('')\n ) : xs)\n .slice(1)\n .reduce((a, x) => a.concat([sep, x]), [xs[0]])\n )) : xs;\n };\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // levels :: Tree a -> [[a]]\n const levels = tree =>\n iterateUntil(\n xs => 1 > xs.length,\n ys => [].concat(...ys.map(nest)),\n [tree]\n ).map(xs => xs.map(root));\n\n // maximum :: Ord a => [a] -> a\n const maximum = xs =>\n 0 < xs.length ? (\n xs.slice(1).reduce((a, x) => x > a ? x : a, xs[0])\n ) : undefined;\n\n // nest :: Tree a -> [a]\n const nest = tree => tree.nest;\n\n // root :: Tree a -> a\n const root = tree => tree.root;\n\n // splitAt :: Int -> [a] -> ([a], [a])\n const splitAt = (n, xs) =>\n Tuple(xs.slice(0, n), xs.slice(n));\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "(() => {\n 'use strict';\n\n // drawTree :: Bool -> Tree String -> String\n const drawTree = blnCompact => tree => {\n // Simple decorated-outline style of ascii tree drawing,\n // with nodeless lines pruned out if blnCompact is True.\n const xs = draw(tree);\n return unlines(\n blnCompact ? (\n xs.filter(\n s => s.split('')\n .some(c => !' │'.includes(c))\n )\n ) : xs\n );\n };\n\n // draw :: Tree String -> [String]\n const draw = node => {\n // shift :: String -> String -> [String] -> [String]\n const shift = (first, other, xs) =>\n zipWith(\n append,\n cons(first, replicate(xs.length - 1, other)),\n xs\n );\n // drawSubTrees :: [Tree String] -> [String]\n const drawSubTrees = xs => {\n const lng = xs.length;\n return 0 < lng ? (\n 1 < lng ? append(\n cons(\n '│',\n shift('├─ ', '│ ', draw(xs[0]))\n ),\n drawSubTrees(xs.slice(1))\n ) : cons('│', shift('└─ ', ' ', draw(xs[0])))\n ) : [];\n };\n return append(\n lines(node.root.toString()),\n drawSubTrees(node.nest)\n );\n };\n\n // TEST -----------------------------------------------\n const main = () => {\n const tree = Node(\n 'Alpha', [\n Node('Beta', [\n Node('Epsilon', []),\n Node('Zeta', []),\n Node('Eta', [])\n ]),\n Node('Gamma', [Node('Theta', [])]),\n Node('Delta', [\n Node('Iota', []),\n Node('Kappa', []),\n Node('Lambda', [])\n ])\n ]);\n\n return [true, false]\n .map(blnCompact => drawTree(blnCompact)(tree))\n .join('\\n\\n');\n };\n\n // GENERIC FUNCTIONS ----------------------------------\n\n // Node :: a -> [Tree a] -> Tree a\n const Node = (v, xs) => ({\n type: 'Node',\n root: v, // any type of value (consistent across tree)\n nest: xs || []\n });\n\n // append (++) :: [a] -> [a] -> [a]\n // append (++) :: String -> String -> String\n const append = (xs, ys) => xs.concat(ys);\n\n // chars :: String -> [Char]\n const chars = s => s.split('');\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) => [x].concat(xs);\n\n // Returns Infinity over objects without finite length.\n // This enables zip and zipWith to choose the shorter\n // argument when one is non-finite, like cycle, repeat etc\n\n // length :: [a] -> Int\n const length = xs =>\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // lines :: String -> [String]\n const lines = s => s.split(/[\\r\\n]/);\n\n // replicate :: Int -> a -> [a]\n const replicate = (n, x) =>\n Array.from({\n length: n\n }, () => x);\n\n // take :: Int -> [a] -> [a]\n const take = (n, xs) =>\n xs.slice(0, n);\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // Use of `take` and `length` here allows zipping with non-finite lists\n // i.e. generators like cycle, repeat, iterate.\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = (f, xs, ys) => {\n const\n lng = Math.min(length(xs), length(ys)),\n as = take(lng, xs),\n bs = take(lng, ys);\n return Array.from({\n length: lng\n }, (_, i) => f(as[i], bs[i], i));\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# Input: an array representing a tree\n# Output: a stream of strings representing the tree\n# In this implementation, empty arrays in the tree are simply ignored.\ndef printTree:\n\n def tidy:\n sub(\"└─$\"; \" \")\n | sub(\"├─$\"; \"| \") ;\n\n # Input: a string prefix\n def print($tree):\n if $tree|type != \"array\" then . + ($tree|tostring)\n else # ignore empty arrays\n ($tree | map(select(if type == \"array\" then length>0 else true end))) as $tree\n | if $tree|length == 0 then empty\n elif $tree|length == 1\n then print($tree[0])\n else print($tree[0]),\n ($tree[1:] as $children\n | tidy as $p\n | ($p + ( \"├─\" | print($children[:-1][]))),\n ($p + ( \"└─\" | print($children[-1]))) )\n end\n end ;\n\n . as $tree\n | \"\" | print($tree) ;\n", "language": "Jq" }, { "code": "def bigTree:\n [\"a\",\n [\"aa\",\n [\"aaa\",\n [\"aaaa\"],\n [\"aaab\",\n [\"aaaba\"],\n [\"aaabb\"]],\n [\"aaac\"]]],\n [\"ab\"],\n [\"ac\",\n [\"aca\"],\n [\"acb\"],\n [\"acc\"]]] ;\n\n[0, 1, 2, 3],\n[1,[2,3,[4, 5, [6,7,8], 9, [10,11]]]],\nbigTree\n| (\"Tree with array representation:\\n\\(.)\\n\",\n printTree,\n \"\")\n", "language": "Jq" }, { "code": "using Gadfly, LightGraphs, GraphPlot\n\ngx = kronecker(5, 12, 0.57, 0.19, 0.19)\ngplot(gx)\n", "language": "Julia" }, { "code": "// version 1.2.0\n\nimport java.util.Random\n\nclass Stem(var str: String? = null, var next: Stem? = null)\n\nconst val SDOWN = \" |\"\nconst val SLAST = \" `\"\nconst val SNONE = \" \"\n\nval rand = Random()\n\nfun tree(root: Int, head: Stem?) {\n val col = Stem()\n var head2 = head\n var tail = head\n while (tail != null) {\n print(tail.str)\n if (tail.next == null) break\n tail = tail.next\n }\n println(\"--$root\")\n if (root <= 1) return\n if (tail != null && tail.str == SLAST) tail.str = SNONE\n if (tail == null) {\n head2 = col\n tail = head2\n }\n else {\n tail.next = col\n }\n var root2 = root\n while (root2 != 0) { // make a tree by doing something random\n val r = 1 + rand.nextInt(root2)\n root2 -= r\n col.str = if (root2 != 0) SDOWN else SLAST\n tree(r, head2)\n }\n tail.next = null\n}\n\nfun main(args: Array<String>) {\n val n = 8\n tree(n, null)\n}\n", "language": "Kotlin" }, { "code": "-- parent script \"TreeItem\"\n-- (minimal implementation with direct property access)\n\nproperty name\nproperty children\n\non new (me, itemName)\n me.name = itemName\n me.children = []\n return me\nend\n\non addChild (me, child)\n me.children.add(child)\nend\n\n-- print a tree\non printTree (me, treeItem, indent)\n if voidP(treeItem) then treeItem = me\n if voidP(indent) then indent = \"\"\n put indent&treeItem.name\n repeat with c in treeItem.children\n me.printTree(c, indent&\" \")\n end repeat\nend\n", "language": "Lingo" }, { "code": "-- create a tree\nroot = script(\"TreeItem\").new(\"root\")\na = script(\"TreeItem\").new(\"a\")\nroot.addChild(a)\nb = script(\"TreeItem\").new(\"b\")\nroot.addChild(b)\na1 = script(\"TreeItem\").new(\"a1\")\na.addChild(a1)\na11 = script(\"TreeItem\").new(\"a11\")\na1.addChild(a11)\na12 = script(\"TreeItem\").new(\"a12\")\na1.addChild(a12)\nb1 = script(\"TreeItem\").new(\"b1\")\nb.addChild(b1)\n\n-- print the tree\nroot.printTree()\n", "language": "Lingo" }, { "code": "function makeTree(v,ac)\n if type(ac) == \"table\" then\n return {value=v,children=ac}\n else\n return {value=v}\n end\nend\n\nfunction printTree(t,last,prefix)\n if last == nil then\n printTree(t, false, '')\n else\n local current = ''\n local next = ''\n\n if last then\n current = prefix .. '\\\\-' .. t.value\n next = prefix .. ' '\n else\n current = prefix .. '|-' .. t.value\n next = prefix .. '| '\n end\n\n print(current:sub(3))\n if t.children ~= nil then\n for k,v in pairs(t.children) do\n printTree(v, k == #t.children, next)\n end\n end\n end\nend\n\nprintTree(\n makeTree('A', {\n makeTree('B0', {\n makeTree('C1'),\n makeTree('C2', {\n makeTree('D', {\n makeTree('E1'),\n makeTree('E2'),\n makeTree('E3')\n })\n }),\n makeTree('C3', {\n makeTree('F1'),\n makeTree('F2'),\n makeTree('F3', {makeTree('G')}),\n makeTree('F4', {\n makeTree('H1'),\n makeTree('H2')\n })\n })\n }),\n makeTree('B1',{\n makeTree('K1'),\n makeTree('K2', {\n makeTree('L1', {makeTree('M')}),\n makeTree('L2'),\n makeTree('L3')\n }),\n makeTree('K3')\n })\n })\n)\n", "language": "Lua" }, { "code": "T := GraphTheory:-Graph([1, 2, 3, 4, 5], {{1, 2}, {2, 3}, {2, 4}, {4, 5}}):\nGraphTheory:-DrawGraph(T, style = tree);\n", "language": "Maple" }, { "code": "edges = {1 \\[DirectedEdge] 2, 1 \\[DirectedEdge] 3, 2 \\[DirectedEdge] 4, 2 \\[DirectedEdge] 5,\n 3 \\[DirectedEdge] 6, 4 \\[DirectedEdge] 7};\nt = TreeGraph[edges, GraphStyle -> \"VintageDiagram\"]\n", "language": "Mathematica" }, { "code": "TreeForm[Defer@\n TreeGraph[{1 \\[DirectedEdge] 2, 1 \\[DirectedEdge] 3, 2 \\[DirectedEdge] 4, 2 \\[DirectedEdge] 5,\n 3 \\[DirectedEdge] 6, 4 \\[DirectedEdge] 7}, VertexLabels -> \"Name\"]]\n", "language": "Mathematica" }, { "code": "OpenerView[{1, Column@{OpenerView[{2, Column@{OpenerView[{4, 7}, True], 5}}, True],\n OpenerView[{3, OpenerView[{TraditionalForm[Cos[x]], Plot[Cos[x], {x, 0, 10}, ImageSize -> 150]},\n True]}, True]}}, True]\n", "language": "Mathematica" }, { "code": "load(graphs)$\n\ng: random_tree(10)$\n\nis_tree(g);\ntrue\n\ndraw_graph(g)$\n", "language": "Maxima" }, { "code": "import strutils\n\ntype\n Node[T] = ref object\n data: T\n left, right: Node[T]\n\nproc n[T](data: T; left, right: Node[T] = nil): Node[T] =\n Node[T](data: data, left: left, right: right)\n\nproc indent[T](n: Node[T]): seq[string] =\n if n == nil: return @[\"-- (null)\"]\n\n result = @[\"--\" & $n.data]\n\n for a in indent n.left: result.add \" |\" & a\n\n let r = indent n.right\n result.add \" `\" & r[0]\n for 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", "language": "Nim" }, { "code": "#!/usr/bin/perl\nuse warnings;\nuse strict;\nuse utf8;\nuse open OUT => ':utf8', ':std';\n\nsub parse {\n my ($tree) = shift;\n if (my ($root, $children) = $tree =~ /^(.+?)\\((.*)\\)$/) {\n\n my $depth = 0;\n for my $pos (0 .. length($children) - 1) {\n my $char = \\substr $children, $pos, 1;\n if (0 == $depth and ',' eq $$char) {\n $$char = \"\\x0\";\n } elsif ('(' eq $$char) {\n $depth++;\n } elsif (')' eq $$char) {\n $depth--;\n }\n }\n return($root, [map parse($_), split /\\x0/, $children]);\n\n } else { # Leaf.\n return $tree;\n }\n}\n\nsub output {\n my ($parsed, $prefix) = @_;\n my $is_root = not defined $prefix;\n $prefix //= ' ';\n while (my $member = shift @$parsed) {\n my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]);\n unless ($is_root) {\n substr $prefix, -3, 1, ' ';\n substr($prefix, -4, 1) =~ s/├/│/;\n substr $prefix, -2, 1, ref $member ? ' ' : '└' if $last;\n }\n\n if (ref $member) {\n output($member, $prefix . '├─');\n } else {\n print $prefix, $member, \"\\n\";\n }\n }\n}\n\nmy $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';\nmy $parsed = [parse($tree)];\noutput($parsed);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\VisualiseTree.exw\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- To the theme tune of the Milk Tray Ad iyrt,\n -- All because the Windows console hates utf8:</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">TL</span> <span style=\"color: #0000FF;\">=</span> '\\<span style=\"color: #000000;\">#DA</span>'<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- aka '┌'</span>\n <span style=\"color: #000000;\">VT</span> <span style=\"color: #0000FF;\">=</span> '\\<span style=\"color: #000000;\">#B3</span>'<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- aka '│'</span>\n <span style=\"color: #000000;\">BL</span> <span style=\"color: #0000FF;\">=</span> '\\<span style=\"color: #000000;\">#C0</span>'<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- aka '└'</span>\n <span style=\"color: #000000;\">HZ</span> <span style=\"color: #0000FF;\">=</span> '\\<span style=\"color: #000000;\">#C4</span>'<span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- aka '─'</span>\n <span style=\"color: #000000;\">HS</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\\#C4\"</span> <span style=\"color: #000080;font-style:italic;\">-- (string version of HZ)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">w1252_to_utf8</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">WINDOWS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,{</span> <span style=\"color: #000000;\">TL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">VT</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">HZ</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"┌\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"│\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"└\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"─\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #000080;font-style:italic;\">--&lt;/hates utf8&gt;</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">visualise_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">tree</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">HS</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tree</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&lt;empty&gt;\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tree</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">g</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">[$]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">TL</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">HZ</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">VT</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">visualise_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">TL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">g</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s%d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">w1252_to_utf8</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">g</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">TL</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">VT</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">visualise_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">root</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">BL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">rand_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">low</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">high</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">v</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">high</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">low</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">low</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">low</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">high</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rand_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">low</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">rand_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">v</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">high</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">tree</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rand_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (can be 0, &lt;1% chance)</span>\n\n <span style=\"color: #000000;\">visualise_tree</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tree</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--pp(tree,{pp_Nest,10})</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "-->\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tree</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #004600;\">pp_Nest</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n\nfunction printTree( array $tree , string $key = \".\" , string $stack = \"\" , $first = TRUE , $firstPadding = NULL )\n{\n if ( gettype($tree) == \"array\" )\n {\n if($firstPadding === NULL) $firstPadding = ( count($tree)>1 ) ? \"│ \" : \" \" ;\n echo $key . PHP_EOL ;\n foreach ($tree as $key => $value) {\n if ($key === array_key_last($tree)){\n echo (($first) ? \"\" : $firstPadding ) . $stack . \"└── \";\n $padding = \" \";\n if($first) $firstPadding = \" \";\n }\n else {\n echo (($first) ? \"\" : $firstPadding ) . $stack . \"├── \";\n $padding = \"│ \";\n }\n if( is_array($value) )printTree( $value , $key , $stack . (($first) ? \"\" : $padding ) , FALSE , $firstPadding );\n else echo $key . \" -> \" . $value . PHP_EOL;\n }\n }\n else echo $tree . PHP_EOL;\n}\n\n\n\n// ---------------------------------------TESTING FUNCTION-------------------------------------\n\n\n$sample_array_1 =\n[\n 0 => [\n 'item_id' => 6,\n 'price' => \"2311.00\",\n 'qty' => 12,\n 'discount' => 0\n ],\n 1 => [\n 'item_id' => 7,\n 'price' => \"1231.00\",\n 'qty' => 1,\n 'discount' => 12\n ],\n 2 => [\n 'item_id' => 8,\n 'price' => \"123896.00\",\n 'qty' => 0,\n 'discount' => 24\n ]\n];\n$sample_array_2 = array(\n array(\n \"name\"=>\"John\",\n \"lastname\"=>\"Doe\",\n \"country\"=>\"Japan\",\n \"nationality\"=>\"Japanese\",\n \"job\"=>\"web developer\",\n \"hobbies\"=>array(\n \"sports\"=>\"soccer\",\n \"others\"=>array(\n \"freetime\"=>\"watching Tv\"\n )\n )\n\n )\n);\n$sample_array_3 = [\n \"root\" => [\n \"first_depth_node1\" =>[\n \"second_depth_node1\",\n \"second_depth_node2\" => [\n \"third_depth_node1\" ,\n \"third_depth_node2\" ,\n \"third_depth_node3\" => [\n \"fourth_depth_node1\",\n \"fourth_depth_node2\",\n ]\n ],\n \"second_depth_node3\",\n ] ,\n \"first_depth_node2\" => [\n \"second_depth_node4\" => [ \"third_depth_node3\" => [1]]\n ]\n ]\n];\n$sample_array_4 = [];\n$sample_array_5 = [\"1\"];\n$sample_array_5 = [\"1\"];\n$sample_array_6 = [\n \"T\",\n \"Ta\",\n \"Tad\",\n \"Tada\",\n \"Tadav\",\n \"Tadavo\",\n \"Tadavom\",\n \"Tadavomn\",\n \"Tadavomni\",\n \"Tadavomnis\",\n \"TadavomnisT\",\n];\n\n\nprintTree($sample_array_1);\necho PHP_EOL . \"------------------------------\" . PHP_EOL;\nprintTree($sample_array_2);\necho PHP_EOL . \"------------------------------\" . PHP_EOL;\nprintTree($sample_array_3);\necho PHP_EOL . \"------------------------------\" . PHP_EOL;\nprintTree($sample_array_4);\necho PHP_EOL . \"------------------------------\" . PHP_EOL;\nprintTree($sample_array_5);\necho PHP_EOL . \"------------------------------\" . PHP_EOL;\nprintTree($sample_array_6);\n\n\n?>\n", "language": "PHP" }, { "code": "(view '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))\n", "language": "PicoLisp" }, { "code": "% direction may be horizontal/vertical/list\ndisplay_tree(Direction) :-\n\tsformat(A, 'Display tree ~w', [Direction]),\n\tnew(D, window(A)),\n\tsend(D, size, size(350,200)),\n\tnew(T, tree(text('Root'))),\n\tsend(T, neighbour_gap, 10),\n\tnew(S1, node(text('Child1'))),\n\tnew(S2, node(text('Child2'))),\n\tsend_list(T, son,[S1,S2]),\n\tnew(S11, node(text('Grandchild1'))),\n\tnew(S12, node(text('Grandchild2'))),\n\tsend_list(S1, son, [S11, S12]),\n\tnew(S21, node(text('Grandchild3'))),\n\tnew(S22, node(text('Grandchild4'))),\n\tsend_list(S2, son, [S21, S22]),\n\tsend(T, direction, Direction),\n\tsend(D, display, T),\n\tsend(D, open).\n", "language": "Prolog" }, { "code": "Python 3.2.3 (default, May 3 2012, 15:54:42)\n[GCC 4.6.3] on linux2\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> help('pprint.pprint')\nHelp on function pprint in pprint:\n\npprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)\n Pretty-print a Python object to a stream [default is sys.stdout].\n\n>>> from pprint import pprint\n>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),\n\t (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),\n\t ((((1, 2), 3), 4), 5, 6, 7, 8) ]:\n\tprint(\"\\nTree %r can be pprint'd as:\" % (tree, ))\n\tpprint(tree, indent=1, width=1)\n\n\t\n\nTree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:\n(1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8)\n\nTree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:\n(1,\n ((2,\n 3),\n (4,\n (5,\n ((6,\n 7),\n 8)))))\n\nTree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:\n((((1,\n 2),\n 3),\n 4),\n 5,\n 6,\n 7,\n 8)\n>>>\n", "language": "Python" }, { "code": ">>> tree = \"a\",(\"b0\",(\"c1\",\"c2\",(\"d\",(\"ef\",\"gh\")),\"c3\",(\"i1\",\"i2\",\"i3\",(\"jj\"),\"i4\",(\"kk\",\"m\"))),\"b1\",(\"C1\",\"C2\",(\"D1\",(\"E\"),\"D2\",\"D3\"),\"C3\"))\n>>> pprint(tree, width=1)\n('a',\n ('b0',\n ('c1',\n 'c2',\n ('d',\n ('ef',\n 'gh')),\n 'c3',\n ('i1',\n 'i2',\n 'i3',\n 'jj',\n 'i4',\n ('kk',\n 'm'))),\n 'b1',\n ('C1',\n 'C2',\n ('D1',\n 'E',\n 'D2',\n 'D3'),\n 'C3')))\n>>> copypasteoutput = ('a',\n... ('b0',\n... ('c1',\n... 'c2',\n... ('d',\n... ('ef',\n... 'gh')),\n... 'c3',\n... ('i1',\n... 'i2',\n... 'i3',\n... 'jj',\n... 'i4',\n... ('kk',\n... 'm'))),\n... 'b1',\n... ('C1',\n... 'C2',\n... ('D1',\n... 'E',\n... 'D2',\n... 'D3'),\n... 'C3')))\n>>> tree == copypasteoutput\nTrue\n>>>\n", "language": "Python" }, { "code": ">>> pprint(tree, width=60)\n('a',\n ('b0',\n ('c1',\n 'c2',\n ('d', ('ef', 'gh')),\n 'c3',\n ('i1', 'i2', 'i3', 'jj', 'i4', ('kk', 'm'))),\n 'b1',\n ('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3')))\n>>>\n", "language": "Python" }, { "code": ">>> mixedtree = ['a', ('b0', ('c1', 'c2', ['d', ('ef', 'gh')], 'c3', ('i1', 'i2',\n... 'i3', 'jj', 'i4', ['kk', 'm'])), 'b1', ('C1', 'C2', ('D1', 'E',\n... 'D2', 'D3'), 'C3'))]\n>>> pprint(mixedtree, width=1)\n['a',\n ('b0',\n ('c1',\n 'c2',\n ['d',\n ('ef',\n 'gh')],\n 'c3',\n ('i1',\n 'i2',\n 'i3',\n 'jj',\n 'i4',\n ['kk',\n 'm'])),\n 'b1',\n ('C1',\n 'C2',\n ('D1',\n 'E',\n 'D2',\n 'D3'),\n 'C3'))]\n>>> pprint(mixedtree, width=60)\n['a',\n ('b0',\n ('c1',\n 'c2',\n ['d', ('ef', 'gh')],\n 'c3',\n ('i1', 'i2', 'i3', 'jj', 'i4', ['kk', 'm'])),\n 'b1',\n ('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]\n>>>\n", "language": "Python" }, { "code": "'''Textually visualized tree, with vertically-centered parent nodes'''\n\nfrom functools import reduce\nfrom itertools import (chain, takewhile)\n\n'''\n ┌ Epsilon\n ├─── Zeta\n ┌─ Beta ┼──── Eta\n │ │ ┌───── Mu\n │ └── Theta ┤\n Alpha ┤ └───── Nu\n ├ Gamma ────── Xi ─ Omicron\n │ ┌─── Iota\n └ Delta ┼── Kappa\n └─ Lambda\n'''\n# Tree style and algorithm inspired by the Haskell snippet at:\n# https://doisinkidney.com/snippets/drawing-trees.html\n\n\n# drawTree2 :: Bool -> Bool -> Tree a -> String\ndef drawTree2(blnCompact):\n '''Monospaced UTF8 left-to-right text tree in a\n compact or expanded format, with any lines\n containing no nodes optionally pruned out.\n '''\n def go(blnPruned, tree):\n # measured :: a -> (Int, String)\n def measured(x):\n '''Value of a tree node\n tupled with string length.\n '''\n s = ' ' + str(x) + ' '\n return len(s), s\n\n # lmrFromStrings :: [String] -> ([String], String, [String])\n def lmrFromStrings(xs):\n '''Lefts, Mid, Rights.'''\n i = len(xs) // 2\n ls, rs = xs[0:i], xs[i:]\n return ls, rs[0], rs[1:]\n\n # stringsFromLMR :: ([String], String, [String]) -> [String]\n def stringsFromLMR(lmr):\n ls, m, rs = lmr\n return ls + [m] + rs\n\n # fghOverLMR\n # :: (String -> String)\n # -> (String -> String)\n # -> (String -> String)\n # -> ([String], String, [String])\n # -> ([String], String, [String])\n def fghOverLMR(f, g, h):\n def go(lmr):\n ls, m, rs = lmr\n return (\n [f(x) for x in ls],\n g(m),\n [h(x) for x in rs]\n )\n return lambda lmr: go(lmr)\n\n # leftPad :: Int -> String -> String\n def leftPad(n):\n return lambda s: (' ' * n) + s\n\n # treeFix :: (Char, Char, Char) -> ([String], String, [String])\n # -> [String]\n def treeFix(l, m, r):\n def cfix(x):\n return lambda xs: x + xs\n return compose(stringsFromLMR)(\n fghOverLMR(cfix(l), cfix(m), cfix(r))\n )\n\n def lmrBuild(w, f):\n def go(wsTree):\n nChars, x = wsTree['root']\n _x = ('─' * (w - nChars)) + x\n xs = wsTree['nest']\n lng = len(xs)\n\n # linked :: String -> String\n def linked(s):\n c = s[0]\n t = s[1:]\n return _x + '┬' + t if '┌' == c else (\n _x + '┤' + t if '│' == c else (\n _x + '┼' + t if '├' == c else (\n _x + '┴' + t\n )\n )\n )\n\n # LEAF ------------------------------------\n if 0 == lng:\n return ([], _x, [])\n\n # SINGLE CHILD ----------------------------\n elif 1 == lng:\n def lineLinked(z):\n return _x + '─' + z\n rightAligned = leftPad(1 + w)\n return fghOverLMR(\n rightAligned,\n lineLinked,\n rightAligned\n )(f(xs[0]))\n\n # CHILDREN --------------------------------\n else:\n rightAligned = leftPad(w)\n lmrs = [f(x) for x in xs]\n return fghOverLMR(\n rightAligned,\n linked,\n rightAligned\n )(\n lmrFromStrings(\n intercalate([] if blnCompact else ['│'])(\n [treeFix(' ', '┌', '│')(lmrs[0])] + [\n treeFix('│', '├', '│')(x) for x\n in lmrs[1:-1]\n ] + [treeFix('│', '└', ' ')(lmrs[-1])]\n )\n )\n )\n return lambda wsTree: go(wsTree)\n\n measuredTree = fmapTree(measured)(tree)\n levelWidths = reduce(\n lambda a, xs: a + [max(x[0] for x in xs)],\n levels(measuredTree),\n []\n )\n treeLines = stringsFromLMR(\n foldr(lmrBuild)(None)(levelWidths)(\n measuredTree\n )\n )\n return [\n s for s in treeLines\n if any(c not in '│ ' for c in s)\n ] if (not blnCompact and blnPruned) else treeLines\n\n return lambda blnPruned: (\n lambda tree: '\\n'.join(go(blnPruned, tree))\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Trees drawn in varying formats'''\n\n # tree1 :: Tree Int\n tree1 = Node(1)([\n Node(2)([\n Node(4)([\n Node(7)([])\n ]),\n Node(5)([])\n ]),\n Node(3)([\n Node(6)([\n Node(8)([]),\n Node(9)([])\n ])\n ])\n ])\n\n # tree :: Tree String\n tree2 = Node('Alpha')([\n Node('Beta')([\n Node('Epsilon')([]),\n Node('Zeta')([]),\n Node('Eta')([]),\n Node('Theta')([\n Node('Mu')([]),\n Node('Nu')([])\n ])\n ]),\n Node('Gamma')([\n Node('Xi')([Node('Omicron')([])])\n ]),\n Node('Delta')([\n Node('Iota')([]),\n Node('Kappa')([]),\n Node('Lambda')([])\n ])\n ])\n\n print(\n '\\n\\n'.join([\n 'Fully compacted (parents not all centered):',\n drawTree2(True)(False)(\n tree1\n ),\n 'Expanded with vertically centered parents:',\n drawTree2(False)(False)(\n tree2\n ),\n 'Centered parents with nodeless lines pruned out:',\n drawTree2(False)(True)(\n tree2\n )\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n '''Contructor for a Tree node which connects a\n value of some kind to a list of zero or\n more child trees.\n '''\n return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs}\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# fmapTree :: (a -> b) -> Tree a -> Tree b\ndef fmapTree(f):\n '''A new tree holding the results of\n applying f to each root in\n the existing tree.\n '''\n def go(x):\n return Node(f(x['root']))(\n [go(v) for v in x['nest']]\n )\n return lambda tree: go(tree)\n\n\n# foldr :: (a -> b -> b) -> b -> [a] -> b\ndef foldr(f):\n '''Right to left reduction of a list,\n using the binary operator f, and\n starting with an initial accumulator value.\n '''\n def g(x, a):\n return f(a, x)\n return lambda acc: lambda xs: reduce(\n g, xs[::-1], acc\n )\n\n\n# intercalate :: [a] -> [[a]] -> [a]\n# intercalate :: String -> [String] -> String\ndef intercalate(x):\n '''The concatenation of xs\n interspersed with copies of x.\n '''\n return lambda xs: x.join(xs) if isinstance(x, str) else list(\n chain.from_iterable(\n reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])\n )\n ) if xs else []\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# levels :: Tree a -> [[a]]\ndef levels(tree):\n '''A list of the nodes at each level of the tree.'''\n return list(\n map_(map_(root))(\n takewhile(\n bool,\n iterate(concatMap(nest))(\n [tree]\n )\n )\n )\n )\n\n\n# map :: (a -> b) -> [a] -> [b]\ndef map_(f):\n '''The list obtained by applying f\n to each element of xs.\n '''\n return lambda xs: list(map(f, xs))\n\n\n# nest :: Tree a -> [Tree a]\ndef nest(t):\n '''Accessor function for children of tree node.'''\n return t['nest'] if 'nest' in t else None\n\n\n# root :: Tree a -> a\ndef root(t):\n '''Accessor function for data of tree node.'''\n return t['root'] if 'root' in t else None\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "'''Visualize a tree'''\n\nfrom itertools import (chain, repeat, starmap)\nfrom operator import (add)\n\n\n# drawTree :: Tree a -> String\ndef drawTree(tree):\n '''ASCII diagram of a tree.'''\n return '\\n'.join(draw(tree))\n\n\n# draw :: Tree a -> [String]\ndef draw(node):\n '''List of the lines of an ASCII\n diagram of a tree.'''\n def shift(first, other, xs):\n return list(starmap(\n add,\n zip(\n chain([first], repeat(other, len(xs) - 1)),\n xs\n )\n ))\n\n def drawSubTrees(xs):\n return (\n (\n ['│'] + shift(\n '├─ ', '│ ', draw(xs[0])\n ) + drawSubTrees(xs[1:])\n ) if 1 < len(xs) else ['│'] + shift(\n '└─ ', ' ', draw(xs[0])\n )\n ) if xs else []\n\n return (str(root(node))).splitlines() + (\n drawSubTrees(nest(node))\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n # tree :: Tree Int\n tree = Node(1)([\n Node(2)([\n Node(4)([\n Node(7)([])\n ]),\n Node(5)([])\n ]),\n Node(3)([\n Node(6)([\n Node(8)([]),\n Node(9)([])\n ])\n ])\n ])\n\n print(drawTree(tree))\n\n\n# GENERIC -------------------------------------------------\n\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n '''Contructor for a Tree node which connects a\n value of some kind to a list of zero or\n more child trees.'''\n return lambda xs: {'root': v, 'nest': xs}\n\n\n# nest :: Tree a -> [Tree a]\ndef nest(tree):\n '''Accessor function for children of tree node.'''\n return tree['nest'] if 'nest' in tree else None\n\n\n# root :: Dict -> a\ndef root(dct):\n '''Accessor function for data of tree node.'''\n return dct['root'] if 'root' in dct else None\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "#lang racket/base\n\n(define (visualize t0)\n (let loop ([t t0] [last? #t] [indent '()])\n (define (I mid last) (cond [(eq? t t0) \"\"] [last? mid] [else last]))\n (for-each display (reverse indent))\n (unless (eq? t t0) (printf \"|\\n\"))\n (for-each display (reverse indent))\n (printf \"~a~a\\n\" (I \"\\\\-\" \"+-\") (car t))\n (for ([s (cdr t)] [n (in-range (- (length t) 2) -1 -1)])\n (loop s (zero? n) (cons (I \" \" \"| \") indent)))))\n\n(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))\n", "language": "Racket" }, { "code": "sub visualize-tree($tree, &label, &children,\n :$indent = '',\n :@mid = ('├─', '│ '),\n :@end = ('└─', ' '),\n) {\n sub visit($node, *@pre) {\n | gather {\n take @pre[0] ~ label($node);\n my @children := children($node);\n my $end = @children.end;\n for @children.kv -> $_, $child {\n when $end { take visit($child, (@pre[1] X~ @end)) }\n default { take visit($child, (@pre[1] X~ @mid)) }\n }\n }\n }\n visit($tree, $indent xx 2);\n}\n\n# example tree built up of pairs\nmy $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];\n\n.map({.join(\"\\n\")}).join(\"\\n\").say for visualize-tree($tree, *.key, *.value.list);\n", "language": "Raku" }, { "code": "/* REXX ***************************************************************\n* 10.05.2014 Walter Pachl using the tree and the output format of C\n**********************************************************************/\nCall mktree\nSay node.1.0name\nCall tt 1,''\nExit\n\ntt: Procedure Expose node.\n/**********************************************************************\n* show a subtree (recursively)\n**********************************************************************/\n Parse Arg k,st\n Do i=1 To node.k.0\n If i=node.k.0 Then\n s='`--'\n Else\n s='|--'\n c=node.k.i\n If st<>'' Then\n st=left(st,length(st)-2)' '\n st=changestr('` ',st,' ')\n Say st||s||node.c.0name\n Call tt c,st||s\n End\n Return\nExit\n\nmktree: Procedure Expose node. root\n/**********************************************************************\n* build the tree according to the task\n**********************************************************************/\n node.=0\n r=mknode('R');\n a=mknode('A'); Call attchild a,r\n b=mknode('B'); Call attchild b,a\n c=mknode('C'); Call attchild c,a\n d=mknode('D'); Call attchild d,b\n e=mknode('E'); Call attchild e,b\n f=mknode('F'); Call attchild f,b\n g=mknode('G'); Call attchild g,b\n h=mknode('H'); Call attchild h,d\n i=mknode('I'); Call attchild i,h\n j=mknode('J'); Call attchild j,i\n k=mknode('K'); Call attchild k,j\n l=mknode('L'); Call attchild l,j\n m=mknode('M'); Call attchild m,e\n n=mknode('N'); Call attchild n,e\n Return\n\nmknode: Procedure Expose node.\n/**********************************************************************\n* create a new node\n**********************************************************************/\n Parse Arg name\n z=node.0+1\n node.z.0name=name\n node.0=z\n Return z /* number of the node just created */\n\nattchild: Procedure Expose node.\n/**********************************************************************\n* make a the next child of father\n**********************************************************************/\n Parse Arg a,father\n node.a.0father=father\n z=node.father.0+1\n node.father.z=a\n node.father.0=z\n node.a.0level=node.father.0level+1\n Return\n", "language": "REXX" }, { "code": "root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]\n", "language": "Ruby" }, { "code": "require 'pp'\npp root\n", "language": "Ruby" }, { "code": "def ptree(tree,indent=\" \")\n case tree\n when Array\n head,*tail=tree\n ptree(head,indent)\n s=tail.size-1\n tail.each_with_index { |tree1,i| ptree(tree1,\"#{indent}#{((i==s) ? ' ':'|')} \") }\n else\n puts(indent.gsub(/\\s\\s$/,\"--\").gsub(/ --$/,\"\\\\--\")+tree.to_s)\n end\nend\nptree [1,2,3,[4,5,6,[7,8,9]],3,[22,33]]\n", "language": "Ruby" }, { "code": "extern crate rustc_serialize;\nextern crate term_painter;\n\nuse rustc_serialize::json;\nuse std::fmt::{Debug, Display, Formatter, Result};\nuse term_painter::ToStyle;\nuse term_painter::Color::*;\n\ntype NodePtr = Option<usize>;\n\n#[derive(Debug, PartialEq, Clone, Copy)]\nenum Side {\n Left,\n Right,\n Up,\n}\n\n#[derive(Debug, PartialEq, Clone, Copy)]\nenum DisplayElement {\n TrunkSpace,\n SpaceLeft,\n SpaceRight,\n SpaceSpace,\n Root,\n}\n\nimpl DisplayElement {\n fn string(&self) -> String {\n match *self {\n DisplayElement::TrunkSpace => \" │ \".to_string(),\n DisplayElement::SpaceRight => \" ┌───\".to_string(),\n DisplayElement::SpaceLeft => \" └───\".to_string(),\n DisplayElement::SpaceSpace => \" \".to_string(),\n DisplayElement::Root => \"├──\".to_string(),\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)]\nstruct Node<K, V> {\n key: K,\n value: V,\n left: NodePtr,\n right: NodePtr,\n up: NodePtr,\n}\n\nimpl<K: Ord + Copy, V: Copy> Node<K, V> {\n pub fn get_ptr(&self, side: Side) -> NodePtr {\n match side {\n Side::Up => self.up,\n Side::Left => self.left,\n _ => self.right,\n }\n }\n}\n\n#[derive(Debug, RustcDecodable, RustcEncodable)]\nstruct Tree<K, V> {\n root: NodePtr,\n store: Vec<Node<K, V>>,\n}\n\nimpl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> {\n pub fn get_node(&self, np: NodePtr) -> Node<K, V> {\n assert!(np.is_some());\n self.store[np.unwrap()]\n }\n\n pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr {\n assert!(np.is_some());\n self.store[np.unwrap()].get_ptr(side)\n }\n\n // Prints the tree with root p. The idea is to do an in-order traversal\n // (reverse in-order in this case, where right is on top), and print nodes as they\n // are visited, one per line. Each invocation of display() gets its own copy\n // of the display element vector e, which is grown with either whitespace or\n // a trunk element, then modified in its last and possibly second-to-last\n // characters in context.\n fn display(&self, p: NodePtr, side: Side, e: &Vec<DisplayElement>, f: &mut Formatter) {\n if p.is_none() {\n return;\n }\n\n let mut elems = e.clone();\n let node = self.get_node(p);\n let mut tail = DisplayElement::SpaceSpace;\n if node.up != self.root {\n // If the direction is switching, I need the trunk element to appear in the lines\n // printed before that node is visited.\n if side == Side::Left && node.right.is_some() {\n elems.push(DisplayElement::TrunkSpace);\n } else {\n elems.push(DisplayElement::SpaceSpace);\n }\n }\n let hindex = elems.len() - 1;\n self.display(node.right, Side::Right, &elems, f);\n\n if p == self.root {\n elems[hindex] = DisplayElement::Root;\n tail = DisplayElement::TrunkSpace;\n } else if side == Side::Right {\n // Right subtree finished\n elems[hindex] = DisplayElement::SpaceRight;\n // Prepare trunk element in case there is a left subtree\n tail = DisplayElement::TrunkSpace;\n } else if side == Side::Left {\n elems[hindex] = DisplayElement::SpaceLeft;\n let parent = self.get_node(node.up);\n if parent.up.is_some() && self.get_pointer(parent.up, Side::Right) == node.up {\n // Direction switched, need trunk element starting with this node/line\n elems[hindex - 1] = DisplayElement::TrunkSpace;\n }\n }\n\n // Visit node => print accumulated elements. Each node gets a line and each line gets a\n // node.\n for e in elems.clone() {\n let _ = write!(f, \"{}\", e.string());\n }\n let _ = write!(f,\n \"{key:>width$} \",\n key = Green.bold().paint(node.key),\n width = 2);\n let _ = write!(f,\n \"{value:>width$}\\n\",\n value = Blue.bold().paint(format!(\"{:.*}\", 2, node.value)),\n width = 4);\n\n // Overwrite last element before continuing traversal\n elems[hindex] = tail;\n\n self.display(node.left, Side::Left, &elems, f);\n }\n}\n\nimpl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Display for Tree<K, V> {\n fn fmt(&self, f: &mut Formatter) -> Result {\n if self.root.is_none() {\n write!(f, \"[empty]\")\n } else {\n let mut v: Vec<DisplayElement> = Vec::new();\n self.display(self.root, Side::Up, &mut v, f);\n Ok(())\n }\n }\n}\n\n/// Decodes and prints a previously generated tree.\nfn main() {\n let encoded = r#\"{\"root\":0,\"store\":[{\"key\":0,\"value\":0.45,\"left\":1,\"right\":3,\n \"up\":null},{\"key\":-8,\"value\":-0.94,\"left\":7,\"right\":2,\"up\":0}, {\"key\":-1,\n \"value\":0.15,\"left\":8,\"right\":null,\"up\":1},{\"key\":7, \"value\":-0.29,\"left\":4,\n \"right\":9,\"up\":0},{\"key\":5,\"value\":0.80,\"left\":5,\"right\":null,\"up\":3},\n {\"key\":4,\"value\":-0.85,\"left\":6,\"right\":null,\"up\":4},{\"key\":3,\"value\":-0.46,\n \"left\":null,\"right\":null,\"up\":5},{\"key\":-10,\"value\":-0.85,\"left\":null,\n \"right\":13,\"up\":1},{\"key\":-6,\"value\":-0.42,\"left\":null,\"right\":10,\"up\":2},\n {\"key\":9,\"value\":0.63,\"left\":12,\"right\":null,\"up\":3},{\"key\":-3,\"value\":-0.83,\n \"left\":null,\"right\":11,\"up\":8},{\"key\":-2,\"value\":0.75,\"left\":null,\"right\":null,\n \"up\":10},{\"key\":8,\"value\":-0.48,\"left\":null,\"right\":null,\"up\":9},{\"key\":-9,\n \"value\":0.53,\"left\":null,\"right\":null,\"up\":7}]}\"#;\n let tree: Tree<i32, f32> = json::decode(&encoded).unwrap();\n println!(\"{}\", tree);\n}\n", "language": "Rust" }, { "code": "func visualize_tree(tree, label, children,\n indent = '',\n mids = ['├─', '│ '],\n ends = ['└─', ' '],\n) {\n func visit(node, pre) {\n gather {\n take(pre[0] + label(node))\n var chldn = children(node)\n var end = chldn.end\n chldn.each_kv { |i, child|\n if (i == end) { take(visit(child, [pre[1]] ~X+ ends)) }\n else { take(visit(child, [pre[1]] ~X+ mids)) }\n }\n }\n }\n visit(tree, [indent] * 2)\n}\n\nvar tree = 'root':['a':['a1':['a11':[]]],'b':['b1':['b11':[]],'b2':[],'b3':[]]]\nsay visualize_tree(tree, { .first }, { .second }).flatten.join(\"\\n\")\n", "language": "Sidef" }, { "code": "package require struct::tree\n\nproc visualize_tree {tree {nameattr name}} {\n set path {}\n $tree walk [$tree rootname] -order both {mode node} {\n\tif {$mode eq \"enter\"} {\n\t set s \"\"\n\t foreach p $path {\n\t\tappend s [expr {[$tree next $p] eq \"\" ? \" \" : \"\\u2502 \"}]\n\t }\n\t lappend path $node\n\t append s [expr {\n\t\t[$tree next $node] eq \"\" ? \"\\u2514\\u2500\" : \"\\u251c\\u2500\"\n\t }]\n\t if {[$tree keyexists $node $nameattr]} {\n\t\tset name [$tree get $node $nameattr]\n\t } else {\n\t\t# No node name attribute; use the raw name\n\t\tset name $node\n\t }\n\t puts \"$s$name\"\n\t} else {\n\t set path [lrange $path 0 end-1]\n\t}\n }\n}\n", "language": "Tcl" }, { "code": "# Sample tree to demonstrate with\nstruct::tree t deserialize {root {} {} a 0 {} d 3 {} e 3 {} f 9 {} b 0 {} c 0 {}}\nvisualize_tree t\n", "language": "Tcl" }, { "code": "import \"./dynamic\" for Struct\nimport \"random\" for Random\n\nvar Stem = Struct.create(\"Stem\", [\"str\", \"next\"])\n\nvar SDOWN = \" |\"\nvar SLAST = \" `\"\nvar SNONE = \" \"\n\nvar rand = Random.new()\n\nvar tree // recursive\ntree = Fn.new { |root, head|\n var col = Stem.new(null, null)\n var tail = head\n while (tail) {\n System.write(tail.str)\n if (!tail.next) break\n tail = tail.next\n }\n System.print(\"--%(root)\")\n if (root <= 1) return\n if (tail && tail.str == SLAST) tail.str = SNONE\n if (!tail) {\n tail = head = col\n } else {\n tail.next = col\n }\n while (root != 0) { // make a tree by doing something random\n var r = 1 + rand.int(root)\n root = root - r\n col.str = (root != 0) ? SDOWN : SLAST\n tree.call(r, head)\n }\n tail.next = null\n}\n\nvar n = 8\ntree.call(n, null)\n", "language": "Wren" }, { "code": "clear screen\n\ndim colore$(1)\n\nmaxCol = token(\"white yellow cyan green red\", colore$())\n\nshowTree(0, \"[1[2[3][4[5][6]][7]][8[9]]]\")\nprint \"\\n\\n\\n\"\nshowTree(0, \"[1[2[3[4]]][5[6][7[8][9]]]]\")\n\nsub showTree(n, A$)\n local i, c$\n static co\n\n c$ = left$(A$, 1)\n\n if c$ = \"\" return\n\n switch c$\n case \"[\": co = co + 1 : showTree(n + 1, right$(A$, len(A$) - 1))\n break\n case \"]\": co = co - 1 : showTree(n - 1, right$(A$, len(A$) - 1))\n break\n default: for i = 2 to n\n print \" \";\n next i\n co = max(min(co, maxCol), 1)\n print color(colore$(co)) \"\\xc0-\", c$\n showTree(n, right$(A$, len(A$) - 1))\n break\n end switch\nend sub\n", "language": "Yabasic" }, { "code": "fcn vaultDir(out=Console){\n const INDENT=\" \";\n space:=\"\"; lastPath:=L();\n foreach fullname in (TheVault.BaseClass.contents.sort()){\n path:=fullname.split(\".\"); name:=path.pop();\n if(lastPath==path) out.writeln(space,name);\n else{\n\t n:=0; p:=path.copy();\n\t try{\n\t while(path[0]==lastPath[0])\n\t { n+=1; path.pop(0); lastPath.pop(0); }\n\t }catch{}\n\t space=INDENT*n;\n\t foreach dir in (path){ out.writeln(space,dir); space+=INDENT; }\n\t out.writeln(space,name);\n\t lastPath=p;\n }\n }\n \"\"\t// so startup has something to display\n}\n", "language": "Zkl" } ]
Visualize-a-tree
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Voronoi_diagram\n", "language": "00-META" }, { "code": "A [[wp:Voronoi diagram|Voronoi diagram]] is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n<br><br>\n\n", "language": "00-TASK" }, { "code": ";------------------------------------------------------------------------\nGui, 1: +E0x20 +Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs\nGui, 1: Show, NA\nhwnd1 := WinExist()\nOnExit, Exit\nIf !pToken := Gdip_Startup()\n{\n\tMsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system\n\tExitApp\n}\nWidth :=1400, Height := 1050\nhbm := CreateDIBSection(Width, Height)\nhdc := CreateCompatibleDC()\nobm := SelectObject(hdc, hbm)\nG := Gdip_GraphicsFromHDC(hdc)\nGdip_SetSmoothingMode(G, 4)\n;------------------------------------------------------------------------\nw := 300, h := 200\nxmin := A_ScreenWidth/2-w/2\t, xmax := A_ScreenWidth/2+w/2\nymin := A_ScreenHeight/2-h/2 , ymax := A_ScreenHeight/2+h/2\ncolors := [\"C0C0C0\",\"808080\",\"FFFFFF\",\"800000\",\"FF0000\",\"800080\",\"FF00FF\",\"008000\"\n\t\t,\"00FF00\",\"808000\",\"FFFF00\",\"000080\",\"0000FF\",\"008080\",\"00FFFF\"]\nsite := []\nloop, 15\n{\n\tRandom, x, % xmin, % xmax\n\tRandom, y, % ymin, % ymax\n\tsite[A_Index, \"x\"] := x\n\tsite[A_Index, \"y\"] := y\n}\ny:= ymin\nwhile (y<=ymax)\n{\n\tx:=xmin\n\twhile (x<=xmax)\n\t{\n\t\tdistance := []\n\t\tfor S, coord in site\n\t\t\tdistance[dist(x, y, coord.x, coord.y)] := S\n\t\tCS := Closest_Site(distance)\n\t\tpBrush := Gdip_BrushCreateSolid(\"0xFF\" . colors[CS])\n\t\tGdip_FillEllipse(G, pBrush, x, y, 2, 2)\n\t\tx++\n\t}\n\tUpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)\n\ty++\n}\npBrush \t:= Gdip_BrushCreateSolid(0xFF000000)\nfor S, coord in site\n\tGdip_FillEllipse(G, pBrush, coord.x, coord.y, 4, 4)\nUpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)\n;------------------------------------------------------------------------\nGdip_DeleteBrush(pBrush)\nSelectObject(hdc, obm)\nDeleteObject(hbm)\nDeleteDC(hdc)\nGdip_DeleteGraphics(G)\nreturn\n;------------------------------------------------------------------------\nDist(x1,y1,x2,y2){\n\treturn Sqrt((x2-x1)**2 + (y2-y1)**2)\n}\n;------------------------------------------------------------------------\nClosest_Site(distance){\n\tfor d, i in distance\n\t\tif A_Index = 1\n\t\t\tmin := d, site := i\n\t\telse\n\t\t\tmin := min < d ? min : d\n\t\t\t, site := min < d ? site : i\n\treturn site\n}\n;------------------------------------------------------------------------\nExit:\nGdip_Shutdown(pToken)\nExitApp\nReturn\n;------------------------------------------------------------------------\n", "language": "AutoHotkey" }, { "code": "global ancho, alto\nancho = 500 : alto = 500\n\nclg\ngraphsize ancho, alto\n\nfunction hypot(a, b)\n\treturn sqr(a^2+b^2)\nend function\n\nsubroutine Generar_diagrama_Voronoi(ancho, alto, num_celdas)\n\tdim nx(num_celdas+1)\n\tdim ny(num_celdas+1)\n\tdim nr(num_celdas+1)\n\tdim ng(num_celdas+1)\n\tdim nb(num_celdas+1)\n\n\tfor i = 0 to num_celdas\n\t\tnx[i] = int(rand * ancho)\n\t\tny[i] = int(rand * alto)\n\t\tnr[i] = int(rand * 256) + 1\n\t\tng[i] = int(rand * 256) + 1\n\t\tnb[i] = int(rand * 256) + 1\n\tnext i\n\tfor y = 1 to alto\n\t\tfor x = 1 to ancho\n\t\t\tdmin = hypot(ancho-1, alto-1)\n\t\t\tj = -1\n\t\t\tfor i = 1 to num_celdas\n\t\t\t\td = hypot(nx[i]-x, ny[i]-y)\n\t\t\t\tif d < dmin then dmin = d : j = i\n\t\t\tnext i\n\t\t\tcolor rgb(nr[j], ng[j], nb[j])\n\t\t\tplot (x, y)\n\t\tnext x\n\tnext y\nend subroutine\n\ncall Generar_diagrama_Voronoi(ancho, alto, 25)\nrefresh\nimgsave \"Voronoi_diagram.jpg\", \"jpg\"\nend\n", "language": "BASIC256" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N_SITES 150\ndouble site[N_SITES][2];\nunsigned char rgb[N_SITES][3];\n\nint size_x = 640, size_y = 480;\n\ninline double sq2(double x, double y)\n{\n\treturn x * x + y * y;\n}\n\n#define for_k for (k = 0; k < N_SITES; k++)\nint nearest_site(double x, double y)\n{\n\tint k, ret = 0;\n\tdouble d, dist = 0;\n\tfor_k {\n\t\td = sq2(x - site[k][0], y - site[k][1]);\n\t\tif (!k || d < dist) {\n\t\t\tdist = d, ret = k;\n\t\t}\n\t}\n\treturn ret;\n}\n\n/* see if a pixel is different from any neighboring ones */\nint at_edge(int *color, int y, int x)\n{\n\tint i, j, c = color[y * size_x + x];\n\tfor (i = y - 1; i <= y + 1; i++) {\n\t\tif (i < 0 || i >= size_y) continue;\n\n\t\tfor (j = x - 1; j <= x + 1; j++) {\n\t\t\tif (j < 0 || j >= size_x) continue;\n\t\t\tif (color[i * size_x + j] != c) return 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\n#define AA_RES 4 /* average over 4x4 supersampling grid */\nvoid aa_color(unsigned char *pix, int y, int x)\n{\n\tint i, j, n;\n\tdouble r = 0, g = 0, b = 0, xx, yy;\n\tfor (i = 0; i < AA_RES; i++) {\n\t\tyy = y + 1. / AA_RES * i + .5;\n\t\tfor (j = 0; j < AA_RES; j++) {\n\t\t\txx = x + 1. / AA_RES * j + .5;\n\t\t\tn = nearest_site(xx, yy);\n\t\t\tr += rgb[n][0];\n\t\t\tg += rgb[n][1];\n\t\t\tb += rgb[n][2];\n\t\t}\n\t}\n\tpix[0] = r / (AA_RES * AA_RES);\n\tpix[1] = g / (AA_RES * AA_RES);\n\tpix[2] = b / (AA_RES * AA_RES);\n}\n\n#define for_i for (i = 0; i < size_y; i++)\n#define for_j for (j = 0; j < size_x; j++)\nvoid gen_map()\n{\n\tint i, j, k;\n\tint *nearest = malloc(sizeof(int) * size_y * size_x);\n\tunsigned char *ptr, *buf, color;\n\n\tptr = buf = malloc(3 * size_x * size_y);\n\tfor_i for_j nearest[i * size_x + j] = nearest_site(j, i);\n\n\tfor_i for_j {\n\t\tif (!at_edge(nearest, i, j))\n\t\t\tmemcpy(ptr, rgb[nearest[i * size_x + j]], 3);\n\t\telse\t/* at edge, do anti-alias rastering */\n\t\t\taa_color(ptr, i, j);\n\t\tptr += 3;\n\t}\n\n\t/* draw sites */\n\tfor (k = 0; k < N_SITES; k++) {\n\t\tcolor = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;\n\n\t\tfor (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {\n\t\t\tif (i < 0 || i >= size_y) continue;\n\n\t\t\tfor (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {\n\t\t\t\tif (j < 0 || j >= size_x) continue;\n\n\t\t\t\tptr = buf + 3 * (i * size_x + j);\n\t\t\t\tptr[0] = ptr[1] = ptr[2] = color;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"P6\\n%d %d\\n255\\n\", size_x, size_y);\n\tfflush(stdout);\n\tfwrite(buf, size_y * size_x * 3, 1, stdout);\n}\n\n#define frand(x) (rand() / (1. + RAND_MAX) * x)\nint main()\n{\n\tint k;\n\tfor_k {\n\t\tsite[k][0] = frand(size_x);\n\t\tsite[k][1] = frand(size_y);\n\t\trgb [k][0] = frand(256);\n\t\trgb [k][1] = frand(256);\n\t\trgb [k][2] = frand(256);\n\t}\n\n\tgen_map();\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <windows.h>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n//////////////////////////////////////////////////////\nstruct Point {\n int x, y;\n};\n\n//////////////////////////////////////////////////////\nclass MyBitmap {\n public:\n MyBitmap() : pen_(nullptr) {}\n ~MyBitmap() {\n DeleteObject(pen_);\n DeleteDC(hdc_);\n DeleteObject(bmp_);\n }\n\n bool Create(int w, int h) {\n BITMAPINFO\tbi;\n ZeroMemory(&bi, sizeof(bi));\n\n bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n\n void *bits_ptr = nullptr;\n HDC dc = GetDC(GetConsoleWindow());\n bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n if (!bmp_) return false;\n\n hdc_ = CreateCompatibleDC(dc);\n SelectObject(hdc_, bmp_);\n ReleaseDC(GetConsoleWindow(), dc);\n\n width_ = w;\n height_ = h;\n\n return true;\n }\n\n void SetPenColor(DWORD clr) {\n if (pen_) DeleteObject(pen_);\n pen_ = CreatePen(PS_SOLID, 1, clr);\n SelectObject(hdc_, pen_);\n }\n\n bool SaveBitmap(const char* path) {\n HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (file == INVALID_HANDLE_VALUE) {\n return false;\n }\n\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n DWORD wb;\n WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n CloseHandle(file);\n\n delete[] dwp_bits;\n return true;\n }\n\n HDC hdc() { return hdc_; }\n int width() { return width_; }\n int height() { return height_; }\n\n private:\n HBITMAP bmp_;\n HDC hdc_;\n HPEN pen_;\n int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n int xd = x - point.x;\n int yd = y - point.y;\n return (xd * xd) + (yd * yd);\n}\n\n//////////////////////////////////////////////////////\nclass Voronoi {\n public:\n void Make(MyBitmap* bmp, int count) {\n bmp_ = bmp;\n CreatePoints(count);\n CreateColors();\n CreateSites();\n SetSitesPoints();\n }\n\n private:\n void CreateSites() {\n int w = bmp_->width(), h = bmp_->height(), d;\n for (int hh = 0; hh < h; hh++) {\n for (int ww = 0; ww < w; ww++) {\n int ind = -1, dist = INT_MAX;\n for (size_t it = 0; it < points_.size(); it++) {\n const Point& p = points_[it];\n d = DistanceSqrd(p, ww, hh);\n if (d < dist) {\n dist = d;\n ind = it;\n }\n }\n\n if (ind > -1)\n SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n else\n __asm nop // should never happen!\n }\n }\n }\n\n void SetSitesPoints() {\n for (const auto& point : points_) {\n int x = point.x, y = point.y;\n for (int i = -1; i < 2; i++)\n for (int j = -1; j < 2; j++)\n SetPixel(bmp_->hdc(), x + i, y + j, 0);\n }\n }\n\n void CreatePoints(int count) {\n const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n for (int i = 0; i < count; i++) {\n points_.push_back({ rand() % w + 10, rand() % h + 10 });\n }\n }\n\n void CreateColors() {\n for (size_t i = 0; i < points_.size(); i++) {\n DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n colors_.push_back(c);\n }\n }\n\n vector<Point> points_;\n vector<DWORD> colors_;\n MyBitmap* bmp_;\n};\n\n//////////////////////////////////////////////////////\nint main(int argc, char* argv[]) {\n ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n srand(GetTickCount());\n\n MyBitmap bmp;\n bmp.Create(512, 512);\n bmp.SetPenColor(0);\n\n Voronoi v;\n v.Make(&bmp, 50);\n\n BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n bmp.SaveBitmap(\"v.bmp\");\n\n system(\"pause\");\n\n return 0;\n}\n", "language": "C++" }, { "code": "import std.random, std.algorithm, std.range, bitmap;\n\nstruct Point { uint x, y; }\n\nenum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) =>\n nPoints.iota\n .map!((int) => Point(uniform(0, nx), uniform(0, ny)))\n .array;\n\nImage!RGB generateVoronoi(in Point[] pts,\n in size_t nx, in size_t ny) /*nothrow*/ {\n // Generate a random color for each centroid.\n immutable rndRBG = (int) => RGB(uniform!\"[]\"(ubyte.min, ubyte.max),\n uniform!\"[]\"(ubyte.min, ubyte.max),\n uniform!\"[]\"(ubyte.min, ubyte.max));\n const colors = pts.length.iota.map!rndRBG.array;\n\n // Generate diagram by coloring pixels with color of nearest site.\n auto img = new typeof(return)(nx, ny);\n foreach (immutable x; 0 .. nx)\n foreach (immutable y; 0 .. ny) {\n immutable dCmp = (in Point a, in Point b) pure nothrow =>\n ((a.x - x) ^^ 2 + (a.y - y) ^^ 2) <\n ((b.x - x) ^^ 2 + (b.y - y) ^^ 2);\n // img[x, y] = colors[pts.reduce!(min!dCmp)];\n img[x, y] = colors[pts.length - pts.minPos!dCmp.length];\n }\n\n // Mark each centroid with a white dot.\n foreach (immutable p; pts)\n img[p.tupleof] = RGB.white;\n return img;\n}\n\nvoid main() {\n enum imageWidth = 640,\n imageHeight = 480;\n randomPoints(150, imageWidth, imageHeight)\n .generateVoronoi(imageWidth, imageHeight)\n .savePPM6(\"voronoi.ppm\");\n}\n", "language": "D" }, { "code": "uses System.Generics.Collections;\n\nprocedure TForm1.Voronoi;\nconst\n p = 3;\n cells = 100;\n size = 1000;\n\nvar\n aCanvas : TCanvas;\n px, py: array of integer;\n color: array of Tcolor;\n Img: TBitmap;\n lastColor:Integer;\n auxList: TList<TPoint>;\n poligonlist : TDictionary<integer,TList<TPoint>>;\n pointarray : array of TPoint;\n\n n,i,x,y,k,j: Integer;\n d1,d2: double;\n\n function distance(x1,x2,y1,y2 :Integer) : Double;\n begin\n result := sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); ///Euclidian\n // result := abs(x1 - x2) + abs(y1 - y2); // Manhattan\n // result := power(power(abs(x1 - x2), p) + power(abs(y1 - y2), p), (1 / p)); // Minkovski\n end;\n\nbegin\n\n poligonlist := TDictionary<integer,TList<Tpoint>>.create;\n\n n := 0;\n Randomize;\n\n img := TBitmap.Create;\n img.Width :=1000;\n img.Height :=1000;\n\n setlength(px,cells);\n setlength(py,cells);\n setlength(color,cells);\n\n for i:= 0 to cells-1 do\n begin\n px[i] := Random(size);\n py[i] := Random(size);\n\n color[i] := Random(16777215);\n auxList := TList<Tpoint>.Create;\n poligonlist.Add(i,auxList);\n end;\n\n for x := 0 to size - 1 do\n begin\n lastColor:= 0;\n for y := 0 to size - 1 do\n begin\n n:= 0;\n\n for i := 0 to cells - 1 do\n begin\n d1:= distance(px[i], x, py[i], y);\n d2:= distance(px[n], x, py[n], y);\n\n if d1 < d2 then\n begin\n n := i;\n\t end;\n end;\n if n <> lastColor then\n begin\n poligonlist[n].Add(Point(x,y));\n poligonlist[lastColor].Add(Point(x,y));\n lastColor := n;\n end;\n end;\n\n poligonlist[n].Add(Point(x,y));\n poligonlist[lastColor].Add(Point(x,y));\n lastColor := n;\n end;\n\n for j := 0 to cells -1 do\n begin\n\n SetLength(pointarray, poligonlist[j].Count);\n for I := 0 to poligonlist[j].Count - 1 do\n begin\n if Odd(i) then\n pointarray[i] := poligonlist[j].Items[i];\n end;\n for I := 0 to poligonlist[j].Count - 1 do\n begin\n if not Odd(i) then\n pointarray[i] := poligonlist[j].Items[i];\n end;\n Img.Canvas.Pen.Color := color[j];\n Img.Canvas.Brush.Color := color[j];\n Img.Canvas.Polygon(pointarray);\n\n Img.Canvas.Pen.Color := clBlack;\n Img.Canvas.Brush.Color := clBlack;\n Img.Canvas.Rectangle(px[j] -2, py[j] -2, px[j] +2, py[j] +2);\n end;\n Canvas.Draw(0,0, img);\nend;\n", "language": "Delphi" }, { "code": "func hypo a b .\n return sqrt (a * a + b * b)\n.\nnsites = 25\nfor i to nsites\n nx[] &= randint 1001 - 1\n ny[] &= randint 1001 - 1\n nc[] &= randint 1000 - 1\n.\nfor y = 0 to 1000\n for x = 0 to 1000\n dmin = 1 / 0\n for i to nsites\n d = hypo (nx[i] - x) (ny[i] - y)\n if d < dmin\n dmin = d\n imin = i\n .\n .\n color nc[imin]\n move x / 10 - 0.05 y / 10 - 0.05\n rect 0.11 0.11\n .\n.\ncolor 000\nfor i to nsites\n move nx[i] / 10 ny[i] / 10\n circle 0.5\n.\n", "language": "EasyLang" }, { "code": "Dim Shared As Integer ancho = 500, alto = 500\nScreenres ancho, alto, 8\nCls\nRandomize Timer\n\nFunction hypot(a As Integer, b As Integer) As Double\n Return Sqr(a^2 + b^2)\nEnd Function\n\nSub Generar_Diagrama_Voronoi(ancho As Integer, alto As Integer, num_celdas As Integer)\n Dim As Integer nx(num_celdas), ny(num_celdas), nr(num_celdas), ng(num_celdas), nb(num_celdas)\n Dim As Integer x, i, y, j, dmin, d\n\n For i = 1 To num_celdas\n nx(i) = (Rnd * ancho)\n ny(i) = (Rnd * alto)\n nr(i) = (Rnd * 256)\n ng(i) = (Rnd * 256)\n nb(i) = (Rnd * 256)\n Next i\n For y = 1 To alto\n For x = 1 To ancho\n dmin = hypot(ancho-1, alto-1)\n j = -1\n For i = 1 To num_celdas\n d = hypot(nx(i)-x, ny(i)-y)\n If d < dmin Then dmin = d : j = i\n Next i\n Pset (x, y), Rgb(nr(j), ng(j), ng(j))\n Next x\n Next y\nEnd Sub\n\nGenerar_Diagrama_Voronoi(ancho, alto, 25)\nBsave \"Voronoi_diadram.bmp\",0\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"image\"\n \"image/color\"\n \"image/draw\"\n \"image/png\"\n \"math/rand\"\n \"os\"\n \"time\"\n)\n\nconst (\n imageWidth = 300\n imageHeight = 200\n nSites = 10\n)\n\nfunc main() {\n writePngFile(generateVoronoi(randomSites()))\n}\n\nfunc generateVoronoi(sx, sy []int) image.Image {\n // generate a random color for each site\n sc := make([]color.NRGBA, nSites)\n for i := range sx {\n sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),\n uint8(rand.Intn(256)), 255}\n }\n\n // generate diagram by coloring each pixel with color of nearest site\n img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))\n for x := 0; x < imageWidth; x++ {\n for y := 0; y < imageHeight; y++ {\n dMin := dot(imageWidth, imageHeight)\n var sMin int\n for s := 0; s < nSites; s++ {\n if d := dot(sx[s]-x, sy[s]-y); d < dMin {\n sMin = s\n dMin = d\n }\n }\n img.SetNRGBA(x, y, sc[sMin])\n }\n }\n // mark each site with a black box\n black := image.NewUniform(color.Black)\n for s := 0; s < nSites; s++ {\n draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),\n black, image.ZP, draw.Src)\n }\n return img\n}\n\nfunc dot(x, y int) int {\n return x*x + y*y\n}\n\nfunc randomSites() (sx, sy []int) {\n rand.Seed(time.Now().Unix())\n sx = make([]int, nSites)\n sy = make([]int, nSites)\n for i := range sx {\n sx[i] = rand.Intn(imageWidth)\n sy[i] = rand.Intn(imageHeight)\n }\n return\n}\n\nfunc writePngFile(img image.Image) {\n f, err := os.Create(\"voronoi.png\")\n if err != nil {\n fmt.Println(err)\n return\n }\n if err = png.Encode(f, img); err != nil {\n fmt.Println(err)\n }\n if err = f.Close(); err != nil {\n fmt.Println(err)\n }\n}\n", "language": "Go" }, { "code": "-- Compile with: ghc -O2 -fllvm -fforce-recomp -threaded --make\n{-# LANGUAGE BangPatterns #-}\nmodule Main where\n\nimport System.Random\n\nimport Data.Word\nimport Data.Array.Repa as Repa\nimport Data.Array.Repa.IO.BMP\n\n{-# INLINE sqDistance #-}\nsqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32\nsqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2)\n\ncenters :: Int -> Int -> Array U DIM2 Word32\ncenters nCenters nCells =\n fromListUnboxed (Z :. nCenters :. 2) $ take (2*nCenters) $ randomRs (0, fromIntegral nCells) (mkStdGen 1)\n\napplyReduce2 arr f =\n traverse arr (\\(i :. j) -> i) $ \\lookup (Z:.i) ->\n f (lookup (Z:.i:.0)) (lookup (Z:.i:.1))\n\nminimize1D arr = foldS f h t\n where\n indexed arr = traverse arr id (\\src idx@(Z :. i) -> (src idx, (fromIntegral i)))\n (Z :. n) = extent arr\n iarr = indexed arr\n h = iarr ! (Z :. 0)\n t = extract (Z :. 1) (Z :. (n-1)) iarr\n\n f min@(!valMin, !iMin ) x@(!val, !i) | val < valMin = x\n | otherwise = min\n\nvoronoi :: Int -> Int -> Array D DIM2 Word32\nvoronoi nCenters nCells =\n let\n {-# INLINE cellReducer #-}\n cellReducer = applyReduce2 (centers nCenters nCells)\n {-# INLINE nearestCenterIndex #-}\n nearestCenterIndex = snd . (Repa.! Z) . minimize1D\n in\n Repa.fromFunction (Z :. nCells :. nCells :: DIM2) $ \\ (Z:.i:.j) ->\n nearestCenterIndex $ cellReducer (sqDistance (fromIntegral i) (fromIntegral j))\n\ngenColorTable :: Int -> Array U DIM1 (Word8, Word8, Word8)\ngenColorTable n = fromListUnboxed (Z :. n) $ zip3 l1 l2 l3\n where\n randoms = randomRs (0,255) (mkStdGen 1)\n (l1, rest1) = splitAt n randoms\n (l2, rest2) = splitAt n rest1\n l3 = take n rest2\n\ncolorize :: Array U DIM1 (Word8, Word8, Word8) -> Array D DIM2 Word32 -> Array D DIM2 (Word8, Word8, Word8)\ncolorize ctable = Repa.map $ \\x -> ctable Repa.! (Z:. fromIntegral x)\n\nmain = do\n let nsites = 150\n let ctable = genColorTable nsites\n voro <- computeP $ colorize ctable (voronoi nsites 512) :: IO (Array U DIM2 (Word8, Word8, Word8))\n writeImageToBMP \"out.bmp\" voro\n", "language": "Haskell" }, { "code": "link graphics,printf,strings\n\nrecord site(x,y,colour) # site data position and colour\ninvocable all # needed for string metrics\n\nprocedure main(A) # voronoi\n\n&window := open(\"Voronoi\",\"g\",\"bg=black\") | stop(\"Unable to open window\")\n\nWAttrib(\"canvas=hidden\") # figure out maximal size width & height\nWAttrib(sprintf(\"size=%d,%d\",WAttrib(\"displaywidth\"),WAttrib(\"displayheight\")))\nWAttrib(\"canvas=maximal\")\nheight := WAttrib(\"height\")\nwidth := WAttrib(\"width\")\n\nmetrics := [\"hypot\",\"taxi\",\"taxi3\"] # different metrics\n\nwhile case a := get(A) of { # command line arguments\n \"--sites\" | \"-s\" : sites := 0 < integer(a := get(A)) | runerr(205,a)\n \"--height\" | \"-h\" : height := 0 < (height >= integer(a := get(A))) | runerr(205,a)\n \"--width\" | \"-w\" : width := 0 < (width >= integer(a := get(A))) | runerr(205,a)\n \"--metric\" | \"-m\" : metric := ((a := get(A)) == !metrics) | runerr(205,a)\n \"--help\" | \"-?\" : write(\"Usage:\\n voronoi [[--sites|-s] n] \",\n\t\t\t \"[[--height|-h] pixels] [[--width|-w] pixels]\",\n\t\t\t \"[[--metric|-m] metric_procedure]\",\n\t\t\t \"[--help|-?]\\n\\n\")\n }\n\n/metric := metrics[1] # default to normal\n/sites := ?(r := integer(.1*width)) + r # sites = random .1 to .2 of width if not given\n\nWAttrib(sprintf(\"label=Voronoi %dx%d %d %s\",width,height,sites,metric))\nWAttrib(sprintf(\"size=%d,%d\",width,height))\n\nx := \"0123456789abcdef\" # hex for random sites (colour)\nsiteL := []\nevery 1 to sites do # random sites\n put(siteL, site(?width,?height,cat(\"#\",?x,?x,?x,?x,?x,?x)))\n\nVoronoiDiagram(width,height,siteL,metric) # Voronoi-ize it\nWDone()\nend\n\nprocedure hypot(x,y,site) # normal metric\nreturn sqrt((x-site.x)^2 + (y-site.y)^2)\nend\n\nprocedure taxi(x,y,site) # \"taxi\" metric\nreturn abs(x-site.x)+abs(y-site.y)\nend\n\nprocedure taxi3(x,y,site) # copied from a commented out version (TCL)\nreturn (abs(x-site.x)^3+abs(y-site.y)^3)^(.3)\nend\n\nprocedure VoronoiDiagram(width,height,siteL,metric)\n /metric := hypot\n every y := 1 to height & x := 1 to width do {\n dist := width+height # anything larger than diagonal\n every site := !siteL do {\n if dist < (dt := metric(x,y,site)) then next # skip\n else if dist >:= dt then Fg(site.colour) # site\n else Fg(\"#000000\") # unowned\n DrawPoint(x,y)\n }\n }\n\n Fg(\"Black\")\n every site := !siteL do # mark sites\n DrawCircle(site.x,site.y,1)\nend\n", "language": "Icon" }, { "code": "NB. (number of points) voronoi (shape)\nNB. Generates an array of indices of the nearest point\nvoronoi =: 4 :0\n p =. (x,2) ?@$ y\n (i.<./)@:(+/@:*:@:-\"1&p)\"1 ,\"0/&i./ y\n)\n\nload'viewmat'\nviewmat 25 voronoi 500 500\n", "language": "J" }, { "code": "Voronoi=. ,\"0/&i./@:] (i. <./)@:(+/@:*:@:-\"1)\"1 _ ] ?@$~ 2 ,~ [\nviewmat 25 Voronoi 500 500 [ load'viewmat'\n", "language": "J" }, { "code": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\nimport javax.swing.JFrame;\n\npublic class Voronoi extends JFrame {\n\tstatic double p = 3;\n\tstatic BufferedImage I;\n\tstatic int px[], py[], color[], cells = 100, size = 1000;\n\n\tpublic Voronoi() {\n\t\tsuper(\"Voronoi Diagram\");\n\t\tsetBounds(0, 0, size, size);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tint n = 0;\n\t\tRandom rand = new Random();\n\t\tI = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n\t\tpx = new int[cells];\n\t\tpy = new int[cells];\n\t\tcolor = new int[cells];\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tpx[i] = rand.nextInt(size);\n\t\t\tpy[i] = rand.nextInt(size);\n\t\t\tcolor[i] = rand.nextInt(16777215);\n\n\t\t}\n\t\tfor (int x = 0; x < size; x++) {\n\t\t\tfor (int y = 0; y < size; y++) {\n\t\t\t\tn = 0;\n\t\t\t\tfor (byte i = 0; i < cells; i++) {\n\t\t\t\t\tif (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {\n\t\t\t\t\t\tn = i;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tI.setRGB(x, y, color[n]);\n\n\t\t\t}\n\t\t}\n\n\t\tGraphics2D g = I.createGraphics();\n\t\tg.setColor(Color.BLACK);\n\t\tfor (int i = 0; i < cells; i++) {\n\t\t\tg.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));\n\t\t}\n\n\t\ttry {\n\t\t\tImageIO.write(I, \"png\", new File(\"voronoi.png\"));\n\t\t} catch (IOException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g) {\n\t\tg.drawImage(I, 0, 0, this);\n\t}\n\n\tstatic double distance(int x1, int x2, int y1, int y2) {\n\t\tdouble d;\n\t d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // Euclidian\n\t// d = Math.abs(x1 - x2) + Math.abs(y1 - y2); // Manhattan\n\t// d = Math.pow(Math.pow(Math.abs(x1 - x2), p) + Math.pow(Math.abs(y1 - y2), p), (1 / p)); // Minkovski\n\t \treturn d;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew Voronoi().setVisible(true);\n\t}\n}\n", "language": "Java" }, { "code": "<!-- VoronoiD.html -->\n<html>\n<head><title>Voronoi diagram</title>\n<script>\n// HF#1 Like in PARI/GP: return random number 0..max-1\nfunction randgp(max) {return Math.floor(Math.random()*max)}\n// HF#2 Random hex color\nfunction randhclr() {\n return \"#\"+\n (\"00\"+randgp(256).toString(16)).slice(-2)+\n (\"00\"+randgp(256).toString(16)).slice(-2)+\n (\"00\"+randgp(256).toString(16)).slice(-2)\n}\n// HF#3 Metrics: Euclidean, Manhattan and Minkovski 3/20/17\nfunction Metric(x,y,mt) {\n if(mt==1) {return Math.sqrt(x*x + y*y)}\n if(mt==2) {return Math.abs(x) + Math.abs(y)}\n if(mt==3) {return(Math.pow(Math.pow(Math.abs(x),3) + Math.pow(Math.abs(y),3),0.33333))}\n}\n// Plotting Voronoi diagram. aev 3/10/17\nfunction pVoronoiD() {\n var cvs=document.getElementById(\"cvsId\");\n var ctx=cvs.getContext(\"2d\");\n var w=cvs.width, h=cvs.height;\n var x=y=d=dm=j=0, w1=w-2, h1=h-2;\n var n=document.getElementById(\"sites\").value;\n var mt=document.getElementById(\"mt\").value;\n var X=new Array(n), Y=new Array(n), C=new Array(n);\n ctx.fillStyle=\"white\"; ctx.fillRect(0,0,w,h);\n for(var i=0; i<n; i++) {\n X[i]=randgp(w1); Y[i]=randgp(h1); C[i]=randhclr();\n }\n for(y=0; y<h1; y++) {\n for(x=0; x<w1; x++) {\n dm=Metric(h1,w1,mt); j=-1;\n for(var i=0; i<n; i++) {\n d=Metric(X[i]-x,Y[i]-y,mt)\n if(d<dm) {dm=d; j=i;}\n }//fend i\n ctx.fillStyle=C[j]; ctx.fillRect(x,y,1,1);\n }//fend x\n }//fend y\n ctx.fillStyle=\"black\";\n for(var i=0; i<n; i++) {\n ctx.fillRect(X[i],Y[i],3,3);\n }\n}\n</script></head>\n<body style=\"font-family: arial, helvatica, sans-serif;\">\n <b>Please input number of sites: </b>\n <input id=\"sites\" value=100 type=\"number\" min=\"10\" max=\"150\" size=\"3\">&nbsp;&nbsp;\n <b>Metric: </b>\n <select id=\"mt\">\n <option value=1 selected>Euclidean</option>\n <option value=2>Manhattan</option>\n <option value=3>Minkovski</option>\n </select>&nbsp;\n <input type=\"button\" value=\"Plot it!\" onclick=\"pVoronoiD();\">&nbsp;&nbsp;\n <h3>Voronoi diagram</h3>\n <canvas id=\"cvsId\" width=\"640\" height=\"640\" style=\"border: 2px inset;\"></canvas>\n</body>\n</html>\n", "language": "JavaScript" }, { "code": "using Images\nfunction voronoi(w, h, n_centroids)\n dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2)\n dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)]\n img = zeros(RGB{N0f8}, h, w)\n for x in 1:h, y in 1:w\n distances = dist([x,y],dots) # distance\n nn = findmin(distances)[2]\n img[x,y] = dots[nn,:][3]\n end\n return img\nend\nimg = voronoi(800, 600, 200)\n", "language": "Julia" }, { "code": "using TestImages, Images\nfunction voronoi_img!(img, n_centroids)\n n,m = size(img)\n w = minimum([n,m])\n dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2)\n dots = [rand(1:n, n_centroids) rand(1:m, n_centroids)]\n c = []\n for i in 1:size(dots,1)\n p = dots[i,:]\n append!(c, [img[p[1],p[2]]])\n end\n dots = [dots c]\n\n for x in 1:n, y in 1:m\n distances = dist([x,y],dots) # distance\n nn = findmin(distances)[2]\n img[x,y] = dots[nn,:][3]\n end\nend\nimg = testimage(\"mandrill\")\nvoronoi_img!(img, 300)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.Graphics2D\nimport java.awt.geom.Ellipse2D\nimport java.awt.image.BufferedImage\nimport java.util.Random\nimport javax.swing.JFrame\n\nfun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {\n val x = x1 - x2\n val y = y1 - y2\n return x * x + y * y\n}\n\nclass Voronoi(val cells: Int, val size: Int) : JFrame(\"Voronoi Diagram\") {\n val bi: BufferedImage\n\n init {\n setBounds(0, 0, size, size)\n defaultCloseOperation = EXIT_ON_CLOSE\n val r = Random()\n bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)\n val px = IntArray(cells) { r.nextInt(size) }\n val py = IntArray(cells) { r.nextInt(size) }\n val cl = IntArray(cells) { r.nextInt(16777215) }\n for (x in 0 until size) {\n for (y in 0 until size) {\n var n = 0\n for (i in 0 until cells) {\n if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i\n }\n bi.setRGB(x, y, cl[n])\n }\n }\n val g = bi.createGraphics()\n g.color = Color.BLACK\n for (i in 0 until cells) {\n g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0))\n }\n }\n\n override fun paint(g: Graphics) {\n g.drawImage(bi, 0, 0, this)\n }\n}\n\nfun main(args: Array<String>) {\n Voronoi(70, 700).isVisible = true\n}\n", "language": "Kotlin" }, { "code": "WindowWidth =600\nWindowHeight =600\n\nsites = 100\nxEdge = 400\nyEdge = 400\ngraphicbox #w.gb1, 10, 10, xEdge, yEdge\n\nopen \"Voronoi neighbourhoods\" for window as #w\n\n#w \"trapclose quit\"\n#w.gb1 \"down ; fill black ; size 4\"\n#w.gb1 \"font courier_new 12\"\n\ndim townX( sites), townY( sites), col$( sites)\n\nfor i =1 to sites\n townX( i) =int( xEdge *rnd( 1))\n townY( i) =int( yEdge *rnd( 1))\n col$( i) = int( 256 *rnd( 1)); \" \"; int( 256 *rnd( 1)); \" \"; int( 256 *rnd( 1))\n #w.gb1 \"color \"; col$( i)\n #w.gb1 \"set \"; townX( i); \" \"; townY( i)\nnext i\n\n#w.gb1 \"size 1\"\n\ndim nearestIndex(xEdge, yEdge)\ndim dist(xEdge, yEdge)\n\nstart = time$(\"ms\")\n\n'fill distance table with distances from the first site\nfor x = 0 to xEdge - 1\n for y = 0 to yEdge - 1\n dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2\n nearestIndex(x, y) = 1\n next y\nnext x\n\n#w.gb1 \"color darkblue\"\n'for other towns\nfor i = 2 to sites\n 'display some progress\n #w.gb1 \"place 0 20\"\n #w.gb1 \"\\computing: \"; using(\"###.#\", i / sites * 100); \"%\"\n 'look left\n for x = townX(i) to 0 step -1\n if not(checkRow(i, x,0, yEdge - 1)) then exit for\n next x\n 'look right\n for x = townX(i) + 1 to xEdge - 1\n if not(checkRow(i, x, 0, yEdge - 1)) then exit for\n next x\n scan\nnext i\n\nfor x = 0 to xEdge - 1\n for y =0 to yEdge - 1\n #w.gb1 \"color \"; col$(nearestIndex(x, y))\n startY = y\n nearest = nearestIndex(x, y)\n for y = y + 1 to yEdge\n if nearestIndex(x, y) <> nearest then y = y - 1 : exit for\n next y\n #w.gb1 \"line \"; x; \" \"; startY; \" \"; x; \" \"; y + 1\n next y\nnext x\n\n#w.gb1 \"color black; size 4\"\nfor i =1 to sites\n #w.gb1 \"set \"; townX( i); \" \"; townY( i)\nnext i\nprint time$(\"ms\") - start\nwait\n\nsub quit w$\n close #w$\n end\nend sub\n\nfunction checkRow(site, x, startY, endY)\n dxSquared = (townX(site) - x) ^ 2\n for y = startY to endY\n dSquared = (townY(site) - y) ^ 2 + dxSquared\n if dSquared <= dist(x, y) then\n dist(x, y) = dSquared\n nearestIndex(x, y) = site\n checkRow = 1\n end if\n next y\nend function\n", "language": "Liberty-BASIC" }, { "code": "function love.load( )\n\tlove.math.setRandomSeed( os.time( ) ) --set the random seed\n\tkeys = { } --an empty table where we will store key presses\n\tnumber_cells = 50 --the number of cells we want in our diagram\n\t--draw the voronoi diagram to a canvas\n\tvoronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )\nend\n\nfunction hypot( x, y )\n\treturn math.sqrt( x*x + y*y )\nend\n\nfunction generateVoronoi( width, height, num_cells )\n\tcanvas = love.graphics.newCanvas( width, height )\n\tlocal imgx = canvas:getWidth( )\n\tlocal imgy = canvas:getHeight( )\n\tlocal nx = { }\n\tlocal ny = { }\n\tlocal nr = { }\n\tlocal ng = { }\n\tlocal nb = { }\n\tfor a = 1, num_cells do\n\ttable.insert( nx, love.math.random( 0, imgx ) )\n\ttable.insert( ny, love.math.random( 0, imgy ) )\n\ttable.insert( nr, love.math.random( 0, 1 ) )\n\ttable.insert( ng, love.math.random( 0, 1 ) )\n\ttable.insert( nb, love.math.random( 0, 1 ) )\n\tend\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\tlove.graphics.setCanvas( canvas )\n\tfor y = 1, imgy do\n\tfor x = 1, imgx do\n\t\t\tdmin = hypot( imgx-1, imgy-1 )\n\t\tj = -1\n\t\tfor i = 1, num_cells do\n\t\td = hypot( nx[i]-x, ny[i]-y )\n\t\tif d < dmin then\n\t \t dmin = d\n\t\t\tj = i\n\t\tend\n\t\tend\n\t\tlove.graphics.setColor( { nr[j], ng[j], nb[j] } )\n\t\tlove.graphics.points( x, y )\n\tend\n\tend\n\t--reset color\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\t--draw points\n\tfor b = 1, num_cells do\n\tlove.graphics.points( nx[b], ny[b] )\n\tend\n\tlove.graphics.setCanvas( )\n\treturn canvas\nend\n\n--RENDER\nfunction love.draw( )\n\t--reset color\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\t--draw diagram\n\tlove.graphics.draw( voronoiDiagram )\n\t--draw drop shadow text\n\tlove.graphics.setColor( { 0, 0, 0 } )\n\tlove.graphics.print( \"space: regenerate\\nesc: quit\", 1, 1 )\n\t--draw text\n\tlove.graphics.setColor( { 0.7, 0.7, 0 } )\n\tlove.graphics.print( \"space: regenerate\\nesc: quit\" )\nend\n\n--CONTROL\nfunction love.keyreleased( key )\n\tif key == 'space' then\n\tvoronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )\n\telseif key == 'escape' then\n\tlove.event.quit( )\n\tend\nend\n", "language": "Lua" }, { "code": "Needs[\"ComputationalGeometry`\"]\nDiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3},\n{6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}]\n", "language": "Mathematica" }, { "code": "from sequtils import newSeqWith\nfrom random import rand, randomize\nfrom times import now\nimport libgd\n\nconst\n img_width = 400\n img_height = 300\n nSites = 20\n\nproc dot(x, y: int): int = x * x + y * y\n\nproc generateVoronoi(img: gdImagePtr) =\n\n randomize(cast[int64](now()))\n\n # random sites\n let sx = newSeqWith(nSites, rand(img_width))\n let sy = newSeqWith(nSites, rand(img_height))\n\n # generate a random color for each site\n let sc = newSeqWith(nSites, img.setColor(rand(255), rand(255), rand(255)))\n\n # generate diagram by coloring each pixel with color of nearest site\n for x in 0 ..< img_width:\n for y in 0 ..< img_height:\n var dMin = dot(img_width, img_height)\n var sMin: int\n for s in 0 ..< nSites:\n if (let d = dot(sx[s] - x, sy[s] - y); d) < dMin:\n (sMin, dMin) = (s, d)\n\n img.setPixel(point=[x, y], color=sc[sMin])\n\n # mark each site with a black box\n let black = img.setColor(0x000000)\n for s in 0 ..< nSites:\n img.drawRectangle(\n startCorner=[sx[s] - 2, sy[s] - 2],\n endCorner=[sx[s] + 2, sy[s] + 2],\n color=black,\n fill=true)\n\nproc main() =\n\n withGd imageCreate(img_width, img_height, trueColor=true) as img:\n img.generateVoronoi()\n\n let png_out = open(\"outputs/voronoi_diagram.png\", fmWrite)\n img.writePng(png_out)\n png_out.close()\n\nmain()\n", "language": "Nim" }, { "code": "let n_sites = 220\n\nlet size_x = 640\nlet size_y = 480\n\nlet sq2 ~x ~y =\n (x * x + y * y)\n\nlet rand_int_range a b =\n a + Random.int (b - a + 1)\n\nlet nearest_site ~site ~x ~y =\n let ret = ref 0 in\n let dist = ref 0 in\n Array.iteri (fun k (sx, sy) ->\n let d = sq2 (x - sx) (y - sy) in\n if k = 0 || d < !dist then begin\n dist := d;\n ret := k;\n end\n ) site;\n !ret\n\nlet gen_map ~site ~rgb =\n let nearest = Array.make (size_x * size_y) 0 in\n let buf = Bytes.create (3 * size_x * size_y) in\n\n for y = 0 to pred size_y do\n for x = 0 to pred size_x do\n nearest.(y * size_x + x) <-\n nearest_site ~site ~x ~y;\n done;\n done;\n\n for i = 0 to pred (size_y * size_x) do\n let j = i * 3 in\n let r, g, b = rgb.(nearest.(i)) in\n Bytes.set buf (j+0) (char_of_int r);\n Bytes.set buf (j+1) (char_of_int g);\n Bytes.set buf (j+2) (char_of_int b);\n done;\n\n Printf.printf \"P6\\n%d %d\\n255\\n\" size_x size_y;\n print_bytes buf;\n;;\n\nlet () =\n Random.self_init ();\n let site =\n Array.init n_sites (fun i ->\n (Random.int size_x,\n Random.int size_y))\n in\n let rgb =\n Array.init n_sites (fun i ->\n (rand_int_range 160 255,\n rand_int_range 40 160,\n rand_int_range 20 140))\n in\n gen_map ~site ~rgb\n", "language": "OCaml" }, { "code": "use strict;\nuse warnings;\nuse Imager;\n\nmy %type = (\n Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) },\n Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 },\n Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 },\n);\n\nmy($xmax, $ymax) = (400, 400);\nmy @domains;\nfor (1..30) {\n push @domains, {\n x => int 5 + rand $xmax-10,\n y => int 5 + rand $ymax-10,\n rgb => [int rand 255, int rand 255, int rand 255]\n }\n}\n\nfor my $type (keys %type) {\n our $img = Imager->new(xsize => $xmax, ysize => $ymax, channels => 3);\n voronoi($type, $xmax, $ymax, @domains);\n dot(1,@domains);\n $img->write(file => \"voronoi-$type.png\");\n\n sub voronoi {\n my($type, $xmax, $ymax, @d) = @_;\n for my $x (0..$xmax) {\n for my $y (0..$ymax) {\n my $i = 0;\n my $d = 10e6;\n for (0..$#d) {\n my $dd = &{$type{$type}}($d[$_]{'x'}, $d[$_]{'y'}, $x, $y);\n if ($dd < $d) { $d = $dd; $i = $_ }\n }\n $img->setpixel(x => $x, y => $y, color => $d[$i]{rgb} );\n }\n }\n }\n\n sub dot {\n my($radius, @d) = @_;\n for (0..$#d) {\n my $dx = $d[$_]{'x'};\n my $dy = $d[$_]{'y'};\n for my $x ($dx-$radius .. $dx+$radius) {\n for my $y ($dy-$radius .. $dy+$radius) {\n $img->setpixel(x => $x, y => $y, color => [0,0,0]);\n }\n }\n }\n }\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\VoronoiDiagram.exw\n -- ===============================\n --\n -- Can resize, double or halve the number of sites (press +/-), and toggle\n -- between Euclid, Manhattan, and Minkowski (press e/m/w).\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timer</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Stop any current drawing process before starting a new one:\n -- Without this it /is/ going to crash, if it tries to finish\n -- drawing all 100 sites, when there are now only 50, for eg.</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">200</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">last_width</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">last_height</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">siteY</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">siteC</span>\n\n <span style=\"color: #008080;\">enum</span> <span style=\"color: #000000;\">EUCLID</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">MANHATTAN</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">MINKOWSKI</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">dmodes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Euclid\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Manhattan\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Minkowski\"</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">EUCLID</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">drawn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #000080;font-style:italic;\">-- (last dmode actually shown)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">distance</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">y2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">d</span>\n <span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">x2</span>\n <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">y2</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">EUCLID</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">y1</span> <span style=\"color: #000080;font-style:italic;\">-- (no need for sqrt)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MANHATTAN</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MINKOWSKI</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (\"\" power(d,1/3))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">nearestIndex</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">dist</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">checkRow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">site</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">dxSquared</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">site</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">x</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">EUCLID</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dxSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">x1</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MANHATTAN</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dxSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MINKOWSKI</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dxSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">height</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- atom dSquared = distance(siteX[site],siteY[site],x,y) -- (sub-optimal..)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">dSquared</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siteY</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">site</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">y</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">EUCLID</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dxSquared</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">y1</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MANHATTAN</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dxSquared</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #000000;\">MINKOWSKI</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dSquared</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dxSquared</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">dSquared</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">dist</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">dist</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dSquared</span>\n <span style=\"color: #000000;\">nearestIndex</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">site</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">last_width</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">last_height</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">siteX</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">siteY</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">siteC</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">#FFFFFF</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">last_width</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">width</span>\n <span style=\"color: #000000;\">last_height</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">height</span>\n <span style=\"color: #000000;\">drawn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">drawn</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">dmode</span> <span style=\"color: #000080;font-style:italic;\">-- (prevent double-draw, and)</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- (drawing when rug moved..)</span>\n <span style=\"color: #000000;\">drawn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dmode</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasClear</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">t1</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">0.25</span>\n <span style=\"color: #000000;\">nearestIndex</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">dist</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- fill distance table with distances from the first site</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">siteY</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">width</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">height</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">dist</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">distance</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">--for other towns</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- look left</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">checkRow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- look right</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">width</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">checkRow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()></span><span style=\"color: #000000;\">t1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Voronoi diagram (generating - %3.2f%%)\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupFlush</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">0.25</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">height</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">nearest</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">nearestIndex</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">width</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">nearestIndex</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]<></span><span style=\"color: #000000;\">nearest</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">siteC</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">nearest</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">nearest</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">nearestIndex</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">siteC</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">nearest</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">cdCanvasSector</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">siteY</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Voronoi diagram - %s, %dx%d, %d sites, %3.2fs\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">dmodes</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">dmode</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">wasdmode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">dmode</span>\n <span style=\"color: #008080;\">switch</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'+'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">nsites</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'E'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'e'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">EUCLID</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'M'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'m'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">MANHATTAN</span>\n <span style=\"color: #008080;\">case</span> <span style=\"color: #008000;\">'W'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'w'</span><span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dmode</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">MINKOWSKI</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">switch</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">dmode</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">wasdmode</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">nsites</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">siteX</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- give any current drawing process 0.1s to abandon:</span>\n <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">IupStoreAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">timer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RUN\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- IupUpdate(canvas)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">timer_active</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #7060A8;\">IupStoreAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">timer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RUN\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupUpdate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_IGNORE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RASTERSIZE=600x400\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (inactive)</span>\n\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"Voronoi diagram\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"KEY_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- release the minimum limitation</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "void setup() {\n size(500, 500);\n generateVoronoiDiagram(width, height, 25);\n saveFrame(\"VoronoiDiagram.png\");\n}\n\nvoid generateVoronoiDiagram(int w, int h, int num_cells) {\n int nx[] = new int[num_cells];\n int ny[] = new int[num_cells];\n int nr[] = new int[num_cells];\n int ng[] = new int[num_cells];\n int nb[] = new int[num_cells];\n for (int n=0; n < num_cells; n++) {\n nx[n]=int(random(w));\n ny[n]=int(random(h));\n nr[n]=int(random(256));\n ng[n]=int(random(256));\n nb[n]=int(random(256));\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n float dmin = dist(0, 0, w - 1, h - 1);\n int j = -1;\n for (int i=0; i < num_cells; i++) {\n float d = dist(0, 0, nx[i] - x, ny[i] - y);\n if (d < dmin) {\n dmin = d;\n j = i;\n }\n }\n set(x, y, color(nr[j], ng[j], nb[j]));\n }\n }\n }\n}\n", "language": "Processing" }, { "code": "def setup():\n size(500, 500)\n generate_voronoi_diagram(width, height, 25)\n saveFrame(\"VoronoiDiagram.png\")\n\ndef generate_voronoi_diagram(w, h, num_cells):\n nx, ny, nr, ng, nb = [], [], [], [], []\n for i in range(num_cells):\n nx.append(int(random(w)))\n ny.append(int(random(h)))\n nr.append(int(random(256)))\n ng.append(int(random(256)))\n nb.append(int(random(256)))\n for y in range(h):\n for x in range(w):\n dmin = dist(0, 0, w - 1, h - 1)\n j = -1\n for i in range(num_cells):\n d = dist(0, 0, nx[i] - x, ny[i] - y)\n if d < dmin:\n dmin = d\n j = i\n set(x, y, color(nr[j], ng[j], nb[j]))\n", "language": "Processing-Python-mode" }, { "code": ":- dynamic pt/6.\nvoronoi :-\n\tV is random(20) + 20,\n\tretractall(pt(_,_,_,_)),\n\tforall(between(1, V, I),\n\t ( X is random(390) + 5,\n\t Y is random(390) + 5,\n\t\t R is random(65535),\n\t\t G is random(65535),\n\t\t B is random(65535),\n\t\t assertz(pt(I,X,Y, R, G, B))\n\t )),\n\tvoronoi(manhattan, V),\n\tvoronoi(euclide, V),\n\tvoronoi(minkowski_3, V).\n\nvoronoi(Distance, V) :-\n\tsformat(A, 'Voronoi 400X400 ~w ~w', [V, Distance]),\n\tnew(D, window(A)),\n\tsend(D, size, size(400,400)),\n\tnew(Img, image(@nil, width := 400, height := 400 , kind := pixmap)),\n\n % get the list of the sites\n\tbagof((N, X, Y), R^G^B^pt(N, X, Y, R, G, B), L),\n\n\tforall(between(0,399, I),\n\t forall(between(0,399, J),\n\t\t ( get_nearest_site(V, Distance, I, J, L, S),\n\t\t pt(S, _, _, R, G, B),\n\t\t send(Img, pixel(I, J, colour(@default, R, G, B)))))),\n\n\tnew(Bmp, bitmap(Img)),\n\tsend(D, display, Bmp, point(0,0)),\n\tsend(D, open).\n\n% define predicatea foldl (functionnal spirit)\nfoldl([], _Pred, R, R).\n\nfoldl([H | T], Pred, Acc, R) :-\n\tcall(Pred, H, Acc, R1),\n\tfoldl(T, Pred, R1, R).\n\n% predicate for foldl\ncompare(Distance, XP, YP, (N, X, Y), (D, S), R) :-\n\tcall(Distance, XP, YP, X, Y, DT),\n\t( DT < D -> R = (DT, N) ; R = (D, S)).\n\n% use of a fake site for the init of foldl\nget_nearest_site(Distance, I, J, L, S) :-\n\tfoldl(L, compare(Distance, I, J), (65535, nil), (_, S)).\n\n\n\nmanhattan(X1, Y1, X2, Y2, D) :-\n\tD is abs(X2 - X1) + abs(Y2-Y1).\n\neuclide(X1, Y1, X2, Y2, D) :-\n\tD is sqrt((X2 - X1)**2 + (Y2-Y1)**2).\n\nminkowski_3(X1, Y1, X2, Y2, D) :-\n\tD is (abs(X2 - X1)**3 + abs(Y2-Y1)**3)**0.33.\n", "language": "Prolog" }, { "code": "Structure VCoo\n x.i: y.i\n Colour.i: FillColour.i\nEndStructure\n\nMacro RandInt(MAXLIMIT)\n Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG))\nEndMacro\n\nMacro SQ2(X, Y)\n ((X)*(X) + (Y)*(Y))\nEndMacro\n\nProcedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt)\n Protected i, j, k, l\n cnt-1\n Dim a(cnt)\n For i=0 To cnt\n a(i)\\x = RandInt(xMax): a(i)\\y = RandInt(yMax)\n j = RandInt(255): k = RandInt(255): l = RandInt(255)\n a(i)\\Colour = RGBA(j, k, l, 255)\n a(i)\\FillColour = RGBA(255-j, 255-k, 255-l, 255)\n Next i\n ProcedureReturn #True\nEndProcedure\n\nProcedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax) ; Euclidean\n Protected i, x, y, img, dist.d, dt.d\n img = CreateImage(#PB_Any, xMax+1, yMax+1)\n If StartDrawing(ImageOutput(img))\n For y=0 To yMax\n For x=0 To xMax\n dist = Infinity()\n For i=0 To ArraySize(a())\n dt = SQ2(x-a(i)\\x, y-a(i)\\y)\n If dt > dist\n Continue\n ElseIf dt < dist\n dist = dt\n Plot(x,y,a(i)\\FillColour)\n Else ; 'Owner ship' is unclear, set pixel to transparent.\n Plot(x,y,RGBA(0, 0, 0, 0))\n EndIf\n Next\n Next\n Next\n For i=0 To ArraySize(a())\n Circle(a(i)\\x, a(i)\\y, 1, a(i)\\Colour)\n Next\n StopDrawing()\n EndIf\n ProcedureReturn img\nEndProcedure\n\n; Main code\nDefine img, x, y, file$\nDim V.VCoo(0)\nx = 640: y = 480\nIf Not GenRandomPoints(V(), x, y, 150): End: EndIf\nimg = MakeVoronoiDiagram(V(), x, y)\nIf img And OpenWindow(0, 0, 0, x, y, \"Voronoi Diagram in PureBasic\", #PB_Window_SystemMenu)\n ImageGadget(0, 0, 0, x, y, ImageID(img))\n Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow\nEndIf\n\nUsePNGImageEncoder()\nfile$ = SaveFileRequester(\"Save Image?\", \"Voronoi_Diagram_in_PureBasic.png\", \"PNG|*.png\", 0)\nIf file$ <> \"\"\n SaveImage(img, file$, #PB_ImagePlugin_PNG)\nEndIf\n", "language": "PureBasic" }, { "code": "Structure VCoo\n x.i: y.i\n Colour.i: FillColour.i\nEndStructure\n\nMacro RandInt(MAXLIMIT)\n Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG))\nEndMacro\n\nProcedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt)\n Protected i, j, k, l\n cnt-1\n Dim a(cnt)\n For i=0 To cnt\n a(i)\\x = RandInt(xMax): a(i)\\y = RandInt(yMax)\n j = RandInt(255): k = RandInt(255): l = RandInt(255)\n a(i)\\Colour = RGBA(j, k, l, 255)\n a(i)\\FillColour = RGBA(255-j, 255-k, 255-l, 255)\n Next i\n ProcedureReturn #True\nEndProcedure\n\nProcedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax)\n Protected i, x, y, img, dist, dt, dx, dy\n img = CreateImage(#PB_Any, xMax+1, yMax+1, 32)\n If StartDrawing(ImageOutput(img))\n For y=0 To yMax\n For x=0 To xMax\n dist = #MAXLONG\n For i=0 To ArraySize(a())\n dx = x-a(i)\\x\n dy = y-a(i)\\y\n dt = Sign(dx)*dx + Sign(dy)*dy\n If dt > dist ; no update\n Continue\n ElseIf dt < dist ; an new 'owner' is found\n dist = dt\n Plot(x,y,a(i)\\FillColour)\n Else ; dt = dist\n Plot(x,y,RGBA(0,0,0,0)) ; no clear 'owner', make the pixel transparent\n EndIf\n Next\n Next\n Next\n For i=0 To ArraySize(a())\n Circle(a(i)\\x, a(i)\\y, 1, a(i)\\Colour)\n Next\n StopDrawing()\n EndIf\n ProcedureReturn img\nEndProcedure\n\n; Main code\nDefine img, x, y, file$\nDim V.VCoo(0)\nx = 640: y = 480\nIf Not GenRandomPoints(V(), x, y, 150): End: EndIf\nimg = MakeVoronoiDiagram(V(), x, y)\nIf img And OpenWindow(0, 0, 0, x, y, \"Voronoi Diagram in PureBasic\", #PB_Window_SystemMenu)\n ImageGadget(0, 0, 0, x, y, ImageID(img))\n Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow\nEndIf\n\nUsePNGImageEncoder()\nfile$ = SaveFileRequester(\"Save Image?\", \"Voronoi_Diagram_in_PureBasic.png\", \"PNG|*.png\", 0)\nIf file$ <> \"\"\n SaveImage(img, file$, #PB_ImagePlugin_PNG)\nEndIf\n", "language": "PureBasic" }, { "code": "from PIL import Image\nimport random\nimport math\n\ndef generate_voronoi_diagram(width, height, num_cells):\n\timage = Image.new(\"RGB\", (width, height))\n\tputpixel = image.putpixel\n\timgx, imgy = image.size\n\tnx = []\n\tny = []\n\tnr = []\n\tng = []\n\tnb = []\n\tfor i in range(num_cells):\n\t\tnx.append(random.randrange(imgx))\n\t\tny.append(random.randrange(imgy))\n\t\tnr.append(random.randrange(256))\n\t\tng.append(random.randrange(256))\n\t\tnb.append(random.randrange(256))\n\tfor y in range(imgy):\n\t\tfor x in range(imgx):\n\t\t\tdmin = math.hypot(imgx-1, imgy-1)\n\t\t\tj = -1\n\t\t\tfor i in range(num_cells):\n\t\t\t\td = math.hypot(nx[i]-x, ny[i]-y)\n\t\t\t\tif d < dmin:\n\t\t\t\t\tdmin = d\n\t\t\t\t\tj = i\n\t\t\tputpixel((x, y), (nr[j], ng[j], nb[j]))\n\timage.save(\"VoronoiDiagram.png\", \"PNG\")\n image.show()\n\t\ngenerate_voronoi_diagram(500, 500, 25)\n", "language": "Python" }, { "code": "import numpy as np\nfrom PIL import Image\nfrom scipy.spatial import KDTree\n\ndef generate_voronoi_diagram(X, Y, num_cells):\n # Random colors and points\n colors = np.random.randint((256, 256, 256), size=(num_cells, 3), dtype=np.uint8)\n points = np.random.randint((Y, X), size=(num_cells, 2))\n\n # Construct a list of all possible (y,x) coordinates\n idx = np.indices((Y, X))\n coords = np.moveaxis(idx, 0, -1).reshape((-1, 2))\n\n # Find the closest point to each coordinate\n _d, labels = KDTree(points).query(coords)\n labels = labels.reshape((Y, X))\n\n # Export an RGB image\n rgb = colors[labels]\n img = Image.fromarray(rgb, mode='RGB')\n img.save('VoronoiDiagram.png', 'PNG')\n img.show()\n return rgb\n", "language": "Python" }, { "code": "_Title \"Voronoi Diagram\"\n\nDim As Integer pnt, px, py, i, x, y, adjct, sy, ly\nDim As Double st\n\n'=====================================================================\n' Changes number of points and screen size here\n'=====================================================================\npnt = 100\npx = 512\npy = 512\n'=====================================================================\nScreen _NewImage(px, py, 32)\nRandomize Timer\n\nDim Shared As Integer pax(pnt), pay(pnt), indx(px, py)\nDim Shared As Long dSqr(px, py)\nDim As Long col(pnt)\n\nFor i = 1 To pnt\n pax(i) = Int(Rnd * px)\n pay(i) = Int(Rnd * py)\n col(i) = _RGB(Rnd * 256, Rnd * 256, Rnd * 256)\nNext\nst = Timer\nFor x = 0 To px - 1\n For y = 0 To py - 1\n dSqr(x, y) = (pax(1) - x) * (pax(1) - x) + (pay(1) - y) * (pay(1) - y)\n indx(x, y) = 1\n Next\nNext\n\nFor i = 2 To pnt\n ly = py - 1\n For x = pax(i) To 0 Step -1\n If (scan(i, x, ly)) = 0 Then Exit For\n Next x\n For x = pax(i) + 1 To px - 1\n If (scan(i, x, ly)) = 0 Then Exit For\n Next\nNext\n\nFor x = 0 To px - 1\n For y = 0 To py - 1\n sy = y\n adjct = indx(x, y)\n For y = y + 1 To py\n If indx(x, y) <> adjct Then y = y - 1: Exit For\n Next\n Line (x, sy)-(x, y + 1), col(adjct)\n Next\nNext\n\nSleep\nSystem\n\nFunction scan (site As Integer, x As Integer, ly As Integer)\n Dim As Integer ty\n Dim As Long delt2, dsq\n delt2 = (pax(site) - x) * (pax(site) - x)\n For ty = 0 To ly\n dsq = (pay(site) - ty) * (pay(site) - ty) + delt2\n If dsq <= dSqr(x, ty) Then\n dSqr(x, ty) = dsq\n indx(x, ty) = site\n scan = 1\n End If\n Next\nEnd Function\n", "language": "QB64" }, { "code": "## HF#1 Random Hex color\nrandHclr <- function() {\n m=255;r=g=b=0;\n r <- sample(0:m, 1, replace=TRUE);\n g <- sample(0:m, 1, replace=TRUE);\n b <- sample(0:m, 1, replace=TRUE);\n return(rgb(r,g,b,maxColorValue=m));\n}\n## HF#2 Metrics: Euclidean, Manhattan and Minkovski\nMetric <- function(x, y, mt) {\n if(mt==1) {return(sqrt(x*x + y*y))}\n if(mt==2) {return(abs(x) + abs(y))}\n if(mt==3) {return((abs(x)^3 + abs(y)^3)^0.33333)}\n}\n\n## Plotting Voronoi diagram. aev 3/12/17\n## ns - number of sites, fn - file name, ttl - plot title.\n## mt - type of metric: 1 - Euclidean, 2 - Manhattan, 3 - Minkovski.\npVoronoiD <- function(ns, fn=\"\", ttl=\"\",mt=1) {\n cat(\" *** START VD:\", date(), \"\\n\");\n if(mt<1||mt>3) {mt=1}; mts=\"\"; if(mt>1) {mts=paste0(\", mt - \",mt)};\n m=640; i=j=k=m1=m-2; x=y=d=dm=0;\n if(fn==\"\") {pf=paste0(\"VDR\", mt, ns, \".png\")} else {pf=paste0(fn, \".png\")};\n if(ttl==\"\") {ttl=paste0(\"Voronoi diagram, sites - \", ns, mts)};\n cat(\" *** Plot file -\", pf, \"title:\", ttl, \"\\n\");\n plot(NA, xlim=c(0,m), ylim=c(0,m), xlab=\"\", ylab=\"\", main=ttl);\n X=numeric(ns); Y=numeric(ns); C=numeric(ns);\n for(i in 1:ns) {\n X[i]=sample(0:m1, 1, replace=TRUE);\n Y[i]=sample(0:m1, 1, replace=TRUE);\n C[i]=randHclr();\n }\n for(i in 0:m1) {\n for(j in 0:m1) {\n dm=Metric(m1,m1,mt); k=-1;\n for(n in 1:ns) {\n d=Metric(X[n]-j,Y[n]-i, mt);\n if(d<dm) {dm=d; k=n;}\n }\n clr=C[k]; segments(j, i, j, i, col=clr);\n }\n }\n points(X, Y, pch = 19, col = \"black\", bg = \"white\")\n dev.copy(png, filename=pf, width=m, height=m);\n dev.off(); graphics.off();\n cat(\" *** END VD:\",date(),\"\\n\");\n}\n## Executing:\npVoronoiD(150) ## Euclidean metric\npVoronoiD(10,\"\",\"\",2) ## Manhattan metric\npVoronoiD(10,\"\",\"\",3) ## Minkovski metric\n", "language": "R" }, { "code": "#lang racket\n\n(require plot)\n\n;; Performs clustering of points in a grid\n;; using the nearest neigbour approach and shows\n;; clusters in different colors\n(define (plot-Voronoi-diagram point-list)\n (define pts\n (for*/list ([x (in-range 0 1 0.005)]\n [y (in-range 0 1 0.005)])\n (vector x y)))\n\n (define clusters (clusterize pts point-list))\n\n (plot\n (append\n (for/list ([r (in-list clusters)] [i (in-naturals)])\n (points (rest r) #:color i #:sym 'fullcircle1))\n (list (points point-list #:sym 'fullcircle5 #:fill-color 'white)))))\n\n;; Divides the set of points into clusters\n;; using given centroids\n(define (clusterize data centroids)\n (for*/fold ([res (map list centroids)]) ([x (in-list data)])\n (define c (argmin (curryr (metric) x) centroids))\n (dict-set res c (cons x (dict-ref res c)))))\n", "language": "Racket" }, { "code": "(define (euclidean-distance a b)\n (for/sum ([x (in-vector a)] [y (in-vector b)])\n (sqr (- x y))))\n\n(define (manhattan-distance a b)\n (for/sum ([x (in-vector a)] [y (in-vector b)])\n (abs (- x y))))\n\n(define metric (make-parameter euclidean-distance))\n", "language": "Racket" }, { "code": ";; Plots the Voronoi diagram as a contour plot of\n;; the classification function built for a set of points\n(define (plot-Voronoi-diagram2 point-list)\n (define n (length point-list))\n (define F (classification-function point-list))\n (plot\n (list\n (contour-intervals (compose F vector) 0 1 0 1\n #:samples 300\n #:levels n\n #:colors (range n)\n #:contour-styles '(solid)\n #:alphas '(1))\n (points point-list #:sym 'fullcircle3))))\n\n;; For a set of centroids returns a function\n;; which finds the index of the centroid nearest\n;; to a given point\n(define (classification-function centroids)\n (define tbl\n (for/hash ([p (in-list centroids)] [i (in-naturals)])\n (values p i)))\n (λ (x)\n (hash-ref tbl (argmin (curry (metric) x) centroids))))\n", "language": "Racket" }, { "code": "(define pts\n (for/list ([i 50]) (vector (random) (random))))\n\n(display (plot-Voronoi-diagram pts))\n\n(display (plot-Voronoi-diagram2 pts))\n\n(parameterize ([metric manhattan-distance])\n (display (plot-Voronoi-diagram2 pts)))\n\n;; Using the classification function it is possible to plot Voronoi diagram in 3D.\n(define pts3d (for/list ([i 7]) (vector (random) (random) (random))))\n(plot3d (list\n (isosurfaces3d (compose (classification-function pts3d) vector)\n 0 1 0 1 0 1\n #:line-styles '(transparent)\n #:samples 100\n #:colors (range 7)\n #:alphas '(1))\n (points3d pts3d #:sym 'fullcircle3)))\n", "language": "Racket" }, { "code": "use Image::PNG::Portable;\n\nmy @bars = '▁▂▃▅▆▇▇▆▅▃▂▁'.comb;\n\nmy %type = ( # Voronoi diagram type distance calculation\n 'Taxicab' => sub ($px, $py, $x, $y) { ($px - $x).abs + ($py - $y).abs },\n 'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)² + ($py - $y)² },\n 'Minkowski' => sub ($px, $py, $x, $y) { ($px - $x)³.abs + ($py - $y)³.abs },\n);\n\nmy $width = 400;\nmy $height = 400;\nmy $dots = 30;\n\nmy @domains = map { Hash.new(\n 'x' => (5..$width-5).roll,\n 'y' => (5..$height-5).roll,\n 'rgb' => [(64..255).roll xx 3]\n) }, ^$dots;\n\nfor %type.keys -> $type {\n print \"\\nGenerating $type diagram... \", ' ' x @bars;\n my $img = voronoi(@domains, :w($width), :h($height), :$type);\n @domains.map: *.&dot($img);\n $img.write: \"Voronoi-{$type}-perl6.png\";\n}\n\nsub voronoi (@domains, :$w, :$h, :$type) {\n my $png = Image::PNG::Portable.new: :width($w), :height($h);\n (^$w).race.map: -> $x {\n print \"\\b\" x 2+@bars, @bars.=rotate(1).join , ' ';\n for ^$h -> $y {\n my ($, $i) = min @domains.map: { %type{$type}(%($_)<x>, %($_)<y>, $x, $y), $++ };\n $png.set: $x, $y, |@domains[$i]<rgb>\n }\n }\n $png\n}\n\nsub dot (%h, $png, $radius = 3) {\n for (%h<x> X+ -$radius .. $radius) X (%h<y> X+ -$radius .. $radius) -> ($x, $y) {\n $png.set($x, $y, 0, 0, 0) if ( %h<x> - $x + (%h<y> - $y) * i ).abs <= $radius;\n }\n}\n", "language": "Raku" }, { "code": "Red [\n\tSource: https://github.com/vazub/rosetta-red\n\tTabs: 4\n\tNeeds: 'View\n]\n\ncomment {\n\tThis is a naive and therefore inefficient approach. For production-related tasks,\n\ta proper full implementation of Fortune's algorithm should be preferred.\n}\n\ncanvas: 500x500\nnum-points: 50\ndiagram-l1: make image! canvas\ndiagram-l2: make image! canvas\n\ndistance: function [\n\t\"Find Taxicab (d1) and Euclidean (d2) distances between two points\"\n\tpt1 [pair!]\n\tpt2 [pair!]\n][\n\td1: (absolute (pt1/x - pt2/x)) + absolute (pt1/y - pt2/y)\n\td2: square-root ((pt1/x - pt2/x) ** 2 + ((pt1/y - pt2/y) ** 2))\n\treduce [d1 d2]\n]\n\n;-- Generate random origin points with respective region colors\npoints: collect [\n\trandom/seed now/time/precise\n\tloop num-points [\n\t\tkeep random canvas\n\t\tkeep random white\n\t]\n]\n\n;-- Color each pixel, based on region it belongs to\nrepeat y canvas/y [\n\trepeat x canvas/x [\n\t\tcoord: as-pair x y\n\t\tmin-dist: distance 1x1 canvas\n\t\tcolor-l1: color-l2: none\n\t\tforeach [point color] points [\n\t\t\td: distance point coord\n\t\t\tif d/1 < min-dist/1 [min-dist/1: d/1 color-l1: color]\n\t\t\tif d/2 < min-dist/2 [min-dist/2: d/2 color-l2: color]\n\t\t]\n\t\tpoke diagram-l1 coord color-l1\n\t\tpoke diagram-l2 coord color-l2\n\t]\n]\n\n;-- Draw origin points for regions\nforeach [point color] points [\n\tdraw diagram-l1 compose [circle (point) 1]\n\tdraw diagram-l2 compose [circle (point) 1]\n]\n\n;-- Put results on screen\nview [\n\ttitle \"Voronoi Diagram\"\n\timage diagram-l1 image diagram-l2\n]\n", "language": "Red" }, { "code": "let n_sites = 60\n\nlet size_x = 640\nlet size_y = 480\n\nlet rand_int_range = (a, b) => a + Random.int(b - a + 1)\n\nlet dist_euclidean = (x, y) => { (x * x + y * y) }\nlet dist_minkowski = (x, y) => { (x * x * x + y * y * y) }\nlet dist_taxicab = (x, y) => { abs(x) + abs(y) }\n\nlet dist_f = dist_euclidean\nlet dist_f = dist_minkowski\nlet dist_f = dist_taxicab\n\nlet nearest_site = (site, x, y) => {\n let ret = ref(0)\n let dist = ref(0)\n Js.Array2.forEachi(site, ((sx, sy), k) => {\n let d = dist_f((x - sx), (y - sy))\n if (k == 0 || d < dist.contents) {\n dist.contents = d\n ret.contents = k\n }\n })\n ret.contents\n}\n\nlet gen_map = (site, rgb) => {\n let nearest = Belt.Array.make((size_x * size_y), 0)\n let buf = Belt.Array.make((3 * size_x * size_y), 0)\n\n for y in 0 to size_y - 1 {\n for x in 0 to size_x - 1 {\n nearest[y * size_x + x] = nearest_site(site, x, y)\n }\n }\n\n for i in 0 to (size_y * size_x) - 1 {\n let j = i * 3\n let (r, g, b) = rgb[nearest[i]]\n buf[j+0] = r\n buf[j+1] = g\n buf[j+2] = b\n }\n\n Printf.printf(\"P3\\n%d %d\\n255\\n\", size_x, size_y)\n Js.Array2.forEach(buf, (d) => Printf.printf(\"%d\\n\", d))\n}\n\n{\n Random.self_init ();\n let site =\n Belt.Array.makeBy(n_sites, (i) => {\n (Random.int(size_x),\n Random.int(size_y))\n })\n\n let rgb =\n Belt.Array.makeBy(n_sites, (i) => {\n (rand_int_range( 50, 120),\n rand_int_range( 80, 180),\n rand_int_range(140, 240))\n })\n gen_map(site, rgb)\n}\n", "language": "ReScript" }, { "code": "# Project : Voronoi diagram\n\nload \"guilib.ring\"\nload \"stdlib.ring\"\npaint = null\n\nnew qapp\n {\n spots\t= 100\n leftside = 400\n rightside = 400\n\n locx = list(spots)\n locy = list(spots)\n rgb = newlist(spots,3)\n seal = newlist(leftside, rightside)\n reach = newlist(leftside, rightside)\n\n win1 = new qwidget() {\n setwindowtitle(\"Voronoi diagram\")\n setgeometry(100,100,800,600)\n label1 = new qlabel(win1) {\n setgeometry(10,10,800,600)\n settext(\"\")\n }\n new qpushbutton(win1) {\n setgeometry(150,550,100,30)\n settext(\"draw\")\n setclickevent(\"draw()\")\n }\n show()\n }\n exec()\n }\n\nfunc draw\n p1 = new qpicture()\n color = new qcolor() {\n setrgb(0,0,255,255)\n }\n pen = new qpen() {\n setcolor(color)\n setwidth(1)\n }\n paint = new qpainter() {\n begin(p1)\n setpen(pen)\n\n for i =1 to spots\n locx[i] = floor(leftside * randomf())\n locy[i] = floor(rightside * randomf())\n rgb[i][1] = floor(256 * randomf())\n rgb[i][2] = floor(256 * randomf())\n rgb[i][3] = floor(256 * randomf())\n next\n for x = 1 to leftside\n for y = 1 to rightside\n reach[x][y] = pow((locx[1] - x),2) + pow((locy[1] - y),2)\n seal[x][y] = 1\n next\n next\n for i = 2 to spots\n for x = locx[i] to 0 step -1\t\t\n if not (chkpos(i,x,1, rightside-1))\n exit\n ok\n next\n for x = locx[i] + 1 to leftside - 1\t\t\n if not (chkpos(i, x, 1, rightside-1))\n exit\n ok\n next\n next\n for x = 1 to leftside\n for y = 1 to rightside\n \t c1 = rgb[seal[x][y]][1]\n \t c2 = rgb[seal[x][y]][2]\n\t c3 = rgb[seal[x][y]][3]\n color = new qcolor() { setrgb(c1,c2,c3,255) }\n pen = new qpen() { setcolor(color) setwidth(10) }\n setpen(pen)\n starty = y\n nearest = seal[x][y]\n for y = (y + 1) to rightside\n if seal[x][y] != nearest\n y = y - 1\n exit\n ok\n next\n paint.drawline(x,starty,x,y + 1)\n next\n next\n endpaint()\n }\n label1 { setpicture(p1) show() }\n return\n\nfunc chkpos(site,x,starty,endy)\n chkpos = 0\n dxsqr = 0\n\tdxsqr = pow((locx[site]- x),2)\n\tfor y = starty to endy\n\t dsqr = pow((locy[site] - y),2) + dxsqr\n if x <= leftside and y <= leftside and x > 0 and y > 0\n\t if dsqr <= reach[x][y]\n\t\treach[x][y]\t= dsqr\n\t\tseal[x][y] = site\n\t\tchkpos = 1\n ok\n\t ok\n\tnext\n return chkpos\n\nfunc randomf()\n decimals(10)\n str = \"0.\"\n for i = 1 to 10\n nr = random(9)\n str = str + string(nr)\n next\n return number(str)\n", "language": "Ring" }, { "code": "# frozen_string_literal: true\n\nrequire_relative 'raster_graphics'\n\nclass ColourPixel < Pixel\n def initialize(x, y, colour)\n @colour = colour\n super x, y\n end\n attr_accessor :colour\n\n def distance_to(px, py)\n Math.hypot(px - x, py - y)\n end\nend\n\nwidth = 300\nheight = 200\nnpoints = 20\npixmap = Pixmap.new(width, height)\n\n@bases = npoints.times.collect do |_i|\n ColourPixel.new(\n 3 + rand(width - 6), 3 + rand(height - 6), # provide a margin to draw a circle\n RGBColour.new(rand(256), rand(256), rand(256))\n )\nend\n\npixmap.each_pixel do |x, y|\n nearest = @bases.min_by { |base| base.distance_to(x, y) }\n pixmap[x, y] = nearest.colour\nend\n\[email protected] do |base|\n pixmap[base.x, base.y] = RGBColour::BLACK\n pixmap.draw_circle(base, 2, RGBColour::BLACK)\nend\n\npixmap.save_as_png('voronoi_rb.png')\n", "language": "Ruby" }, { "code": "# frozen_string_literal: true\n\nTile = Struct.new(:x, :y, :color) do\n def sq_dist(a, b)\n (x - a)**2 + (y - b)**2\n end\nend\n\nattr_reader :tiles\n\ndef settings\n size 500, 500\nend\n\ndef setup\n sketch_title 'Voronoi Diagram'\n load_pixels\n color_mode(HSB, 1.0)\n @tiles = generate_tiles(30)\n draw_voronoi\n update_pixels\n draw_voronoi_centers\nend\n\ndef generate_tiles(num)\n (0..num).map { Tile.new(rand(width), rand(height), color(rand, 1.0, 1.0)) }\nend\n\ndef draw_voronoi\n grid(width, height) do |x, y|\n closest = tiles.min_by { |tile| tile.sq_dist(x, y) }\n pixels[x + y * width] = closest.color\n end\nend\n\ndef draw_voronoi_centers\n tiles.each do |center|\n no_stroke\n fill 0\n ellipse(center.x, center.y, 4, 4)\n end\nend\n", "language": "Ruby" }, { "code": "graphic #g, 400,400\n#g flush()\nspots\t\t= 100\nleftSide\t= 400\nrightSide\t= 400\n\ndim locX(spots)\ndim locY(spots)\ndim rgb(spots,3)\ndim seal(leftSide, rightSide)\ndim reach(leftSide, rightSide)\n\nfor i =1 to spots\n locX(i)\t= int(leftSide * rnd(1))\n locY(i)\t= int(rightSide * rnd(1))\n rgb(i,1)\t= int(256 * rnd(1))\n rgb(i,2)\t= int(256 * rnd(1))\n rgb(i,3)\t= int(256 * rnd(1))\n #g color(rgb(i,1),rgb(i,2),rgb(i,3))\n #g set(locX(i),locY(i))\nnext i\n#g size(1)\n' find reach to the first site\nfor x = 0 to leftSide - 1\n for y = 0 to rightSide - 1\n reach(x, y) = (locX(1) - x) ^ 2 + (locY(1) - y) ^ 2\n seal(x, y) = 1\n next y\nnext x\n#g color(\"darkblue\")\n\n' spots other than 1st spot\nfor i = 2 to spots\n for x = locX(i) to 0 step -1\t\t' looking left\n if not(chkPos(i,x,0, rightSide - 1)) then exit for\n next x\n for x = locX(i) + 1 to leftSide - 1\t\t' looking right\n if not(chkPos(i, x, 0, rightSide - 1)) then exit for\n next x\nnext i\n\nfor x = 0 to leftSide - 1\n for y = 0 to rightSide - 1\n\tc1\t= rgb(seal(x, y),1)\n\tc2\t= rgb(seal(x, y),2)\n\tc3\t= rgb(seal(x, y),3)\n #g color(c1,c2,c3)\n startY\t= y\n nearest\t= seal(x, y)\n for y = y + 1 to rightSide\n if seal(x, y) <> nearest then y = y - 1 : exit for\n next y\n #g line(x,startY,x,y + 1)\n next y\nnext x\n\n#g color(\"black\")\n#g size(4)\nfor i =1 to spots\n #g set(locX(i),locY(i))\nnext i\nrender #g\nend\n\nfunction chkPos(site, x, startY, endY)\n\tdxSqr = (locX(site) - x) ^ 2\n\tfor y = startY to endY\n\t\tdSqr = (locY(site) - y) ^ 2 + dxSqr\n\t\tif dSqr <= reach(x, y) then\n\t\t\treach(x,y)\t= dSqr\n\t\t\tseal(x,y)\t= site\n\t\t\tchkPos\t\t= 1\n\t\tend if\n\tnext y\nend function\n", "language": "Run-BASIC" }, { "code": "extern crate piston;\nextern crate opengl_graphics;\nextern crate graphics;\nextern crate touch_visualizer;\n\n#[cfg(feature = \"include_sdl2\")]\nextern crate sdl2_window;\n\nextern crate getopts;\nextern crate voronoi;\nextern crate rand;\n\nuse touch_visualizer::TouchVisualizer;\nuse opengl_graphics::{ GlGraphics, OpenGL };\nuse graphics::{ Context, Graphics };\nuse piston::window::{ Window, WindowSettings };\nuse piston::input::*;\nuse piston::event_loop::*;\n#[cfg(feature = \"include_sdl2\")]\nuse sdl2_window::Sdl2Window as AppWindow;\nuse voronoi::{voronoi, Point, make_polygons};\nuse rand::Rng;\n\nstatic DEFAULT_WINDOW_HEIGHT: u32 = 600;\nstatic DEFAULT_WINDOW_WIDTH: u32 = 600;\n\nstruct Settings {\n lines_only: bool,\n random_count: usize\n}\n\nfn main() {\n let args: Vec<String> = std::env::args().collect();\n let mut opts = getopts::Options::new();\n opts.optflag(\"l\", \"lines_only\", \"Don't color polygons, just outline them\");\n opts.optopt(\"r\", \"random_count\", \"On keypress \\\"R\\\", put this many random points on-screen\", \"RANDOMCOUNT\");\n let matches = opts.parse(&args[1..]).expect(\"Failed to parse args\");\n\n let settings = Settings{\n lines_only: matches.opt_present(\"l\"),\n random_count: match matches.opt_str(\"r\") {\n None => { 50 },\n Some(s) => { s.parse().expect(\"Random count of bad format\") }\n }\n };\n\n event_loop(&settings);\n\n}\n\nfn random_point() -> [f64; 2] {\n [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)]\n}\n\nfn random_color() -> [f32; 4] {\n [rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0]\n}\n\nfn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) {\n dots.clear();\n colors.clear();\n\n for _ in 0..num {\n dots.push(random_point());\n colors.push(random_color());\n }\n}\n\nfn event_loop(settings: &Settings) {\n let opengl = OpenGL::V3_2;\n let mut window: AppWindow = WindowSettings::new(\"Interactive Voronoi\", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH])\n .exit_on_esc(true).opengl(opengl).build().unwrap();\n\n let ref mut gl = GlGraphics::new(opengl);\n let mut touch_visualizer = TouchVisualizer::new();\n let mut events = Events::new(EventSettings::new().lazy(true));\n let mut dots = Vec::new();\n let mut colors = Vec::new();\n\n let mut mx = 0.0;\n let mut my = 0.0;\n\n while let Some(e) = events.next(&mut window) {\n touch_visualizer.event(window.size(), &e);\n if let Some(button) = e.release_args() {\n match button {\n Button::Keyboard(key) => {\n if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); }\n if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); }\n }\n Button::Mouse(_) => {\n dots.push([mx, my]);\n colors.push(random_color());\n },\n _ => ()\n }\n };\n e.mouse_cursor(|x, y| {\n mx = x;\n my = y;\n });\n if let Some(args) = e.render_args() {\n gl.draw(args.viewport(), |c, g| {\n graphics::clear([1.0; 4], g);\n let mut vor_pts = Vec::new();\n for d in &dots {\n vor_pts.push(Point::new(d[0], d[1]));\n }\n if vor_pts.len() > 0 {\n let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64);\n let vor_polys = make_polygons(&vor_diagram);\n for (i, poly) in vor_polys.iter().enumerate() {\n if settings.lines_only {\n draw_lines_in_polygon(poly, &c, g);\n } else {\n draw_polygon(poly, &c, g, colors[i]);\n }\n }\n }\n for d in &dots {\n draw_ellipse(&d, &c, g);\n }\n });\n }\n }\n\n}\n\nfn draw_lines_in_polygon<G: Graphics>(\n poly: &Vec<Point>,\n c: &Context,\n g: &mut G,\n)\n{\n let color = [0.0, 0.0, 1.0, 1.0];\n\n for i in 0..poly.len()-1 {\n graphics::line(\n color,\n 2.0,\n [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()],\n c.transform,\n g\n )\n }\n}\n\nfn draw_polygon<G: Graphics>(\n poly: &Vec<Point>,\n c: &Context,\n g: &mut G,\n color: [f32; 4]\n) {\n let mut polygon_points: Vec<[f64; 2]> = Vec::new();\n\n for p in poly {\n polygon_points.push([p.x.into(), p.y.into()]);\n }\n\n graphics::polygon(\n color,\n polygon_points.as_slice(),\n c.transform,\n g\n )\n}\n\nfn draw_ellipse<G: Graphics>(\n cursor: &[f64; 2],\n c: &Context,\n g: &mut G,\n) {\n let color = [0.0, 0.0, 0.0, 1.0];\n graphics::ellipse(\n color,\n graphics::ellipse::circle(cursor[0], cursor[1], 4.0),\n c.transform,\n g\n );\n}\n", "language": "Rust" }, { "code": "import java.awt.geom.Ellipse2D\nimport java.awt.image.BufferedImage\nimport java.awt.{Color, Graphics, Graphics2D}\n\nimport scala.math.sqrt\n\nobject Voronoi extends App {\n private val (cells, dim) = (100, 1000)\n private val rand = new scala.util.Random\n private val color = Vector.fill(cells)(rand.nextInt(0x1000000))\n private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB)\n private val g: Graphics2D = image.createGraphics()\n private val px = Vector.fill(cells)(rand.nextInt(dim))\n private val py = Vector.fill(cells)(rand.nextInt(dim))\n\n for (x <- 0 until dim;\n y <- 0 until dim) {\n var n = 0\n\n def distance(x1: Int, x2: Int, y1: Int, y2: Int) =\n sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble) // Euclidian\n\n for (i <- px.indices\n if distance(px(i), x, py(i), y) < distance(px(n), x, py(n), y))\n n = i\n image.setRGB(x, y, color(n))\n }\n\n g.setColor(Color.BLACK)\n for (i <- px.indices) g.fill(new Ellipse2D.Double(px(i) - 2.5, py(i) - 2.5, 5, 5))\n\n new javax.swing.JFrame(\"Voronoi Diagram\") {\n override def paint(g: Graphics): Unit = {g.drawImage(image, 0, 0, this); ()}\n\n setBounds(0, 0, dim, dim)\n setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)\n setLocationRelativeTo(null)\n setResizable(false)\n setVisible(true)\n }\n\n}\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"draw.s7i\";\n include \"keybd.s7i\";\n\nconst type: point is new struct\n var integer: xPos is 0;\n var integer: yPos is 0;\n var color: col is black;\n end struct;\n\nconst proc: generateVoronoiDiagram (in integer: width, in integer: height, in integer: numCells) is func\n local\n var array point: points is 0 times point.value;\n var integer: index is 0;\n var integer: x is 0;\n var integer: y is 0;\n var integer: distSquare is 0;\n var integer: minDistSquare is 0;\n var integer: indexOfNearest is 0;\n begin\n screen(width, height);\n points := numCells times point.value;\n for index range 1 to numCells do\n points[index].xPos := rand(0, width);\n points[index].yPos := rand(0, height);\n points[index].col := color(rand(0, 65535), rand(0, 65535), rand(0, 65535));\n end for;\n for y range 0 to height do\n for x range 0 to width do\n minDistSquare := width ** 2 + height ** 2;\n for index range 1 to numCells do\n distSquare := (points[index].xPos - x) ** 2 + (points[index].yPos - y) ** 2;\n if distSquare < minDistSquare then\n minDistSquare := distSquare;\n indexOfNearest := index;\n end if;\n end for;\n point(x, y, points[indexOfNearest].col);\n end for;\n end for;\n for index range 1 to numCells do\n line(points[index].xPos - 2, points[index].yPos, 4, 0, black);\n line(points[index].xPos, points[index].yPos - 2, 0, 4, black);\n end for;\n end func;\n\nconst proc: main is func\n begin\n generateVoronoiDiagram(500, 500, 25);\n KEYBOARD := GRAPH_KEYBOARD;\n readln(KEYBOARD);\n end func;\n", "language": "Seed7" }, { "code": "require('Imager')\n\nfunc generate_voronoi_diagram(width, height, num_cells) {\n var img = %O<Imager>.new(xsize => width, ysize => height)\n var (nx,ny,nr,ng,nb) = 5.of { [] }...\n\n for i in (^num_cells) {\n nx << rand(^width)\n ny << rand(^height)\n nr << rand(^256)\n ng << rand(^256)\n nb << rand(^256)\n }\n\n for y=(^height), x=(^width) {\n var j = (^num_cells -> min_by {|i| hypot(nx[i]-x, ny[i]-y) })\n img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]])\n }\n return img\n}\n\nvar img = generate_voronoi_diagram(500, 500, 25)\nimg.write(file => 'VoronoiDiagram.png')\n", "language": "Sidef" }, { "code": "package require Tk\nproc r to {expr {int(rand()*$to)}}; # Simple helper\n\nproc voronoi {photo pointCount} {\n for {set i 0} {$i < $pointCount} {incr i} {\n\tlappend points [r [image width $photo]] [r [image height $photo]]\n }\n foreach {x y} $points {\n\tlappend colors [format \"#%02x%02x%02x\" [r 256] [r 256] [r 256]]\n }\n set initd [expr {[image width $photo] + [image height $photo]}]\n for {set i 0} {$i < [image width $photo]} {incr i} {\n\tfor {set j 0} {$j < [image height $photo]} {incr j} {\n\t set color black\n\t set d $initd\n\t foreach {x y} $points c $colors {\n\t\tset h [expr {hypot($x-$i,$y-$j)}]\n\t\t### Other interesting metrics\n\t\t#set h [expr {abs($x-$i)+abs($y-$j)}]\n\t\t#set h [expr {(abs($x-$i)**3+abs($y-$j)**3)**0.3}]\n\t\tif {$d > $h} {set d $h;set color $c}\n\t }\n\t $photo put $color -to $i $j\n\t}\n\t# To display while generating, uncomment this line and the other one so commented\n\t#if {$i%4==0} {update idletasks}\n }\n}\n\n# Generate a 600x400 Voronoi diagram with 60 random points\nimage create photo demo -width 600 -height 400\npack [label .l -image demo]\n# To display while generating, uncomment this line and the other one so commented\n#update\nvoronoi demo 60\n", "language": "Tcl" }, { "code": "import \"graphics\" for Canvas, Color\nimport \"dome\" for Window\nimport \"random\" for Random\n\nclass Game {\n static init() {\n Window.title = \"Voronoi diagram\"\n var cells = 70\n var size = 700\n Window.resize(size, size)\n Canvas.resize(size, size)\n voronoi(cells, size)\n }\n\n static update() {}\n\n static draw(alpha) {}\n\n static distSq(x1, x2, y1, y2) { (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) }\n\n static voronoi(cells, size) {\n var r = Random.new()\n var px = List.filled(cells, 0)\n var py = List.filled(cells, 0)\n var cl = List.filled(cells, 0)\n for (i in 0...cells) {\n px[i] = r.int(size)\n py[i] = r.int(size)\n cl[i] = Color.rgb(r.int(256), r.int(256), r.int(256))\n }\n for (x in 0...size) {\n for (y in 0...size) {\n var n = 0\n for (i in 0...cells) {\n if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i\n }\n Canvas.pset(x, y, cl[n])\n }\n }\n for (i in 0...cells) {\n Canvas.circlefill(px[i], py[i], 2, Color.black)\n }\n }\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\n\ndef N = 15; \\number of sites\nint SiteX(N), SiteY(N), \\coordinates of sites\n Dist2, MinDist2, MinI, \\distance squared, and minimums\n X, Y, I;\n[SetVid($13); \\set 320x200x8 graphics\nfor I:= 0 to N-1 do \\create a number of randomly placed sites\n [SiteX(I):= Ran(160); SiteY(I):= Ran(100)];\nfor Y:= 0 to 100-1 do \\generate Voronoi diagram\n for X:= 0 to 160-1 do \\for all points...\n [MinDist2:= -1>>1; \\find closest site\n for I:= 0 to N-1 do\n [Dist2:= sq(X-SiteX(I)) + sq(Y-SiteY(I));\n if Dist2 < MinDist2 then\n [MinDist2:= Dist2; MinI:= I];\n ];\n if MinDist2 then Point(X, Y, MinI+1); \\leave center black\n ];\nI:= ChIn(1); \\wait for keystroke\nSetVid($03); \\restore normal text screen\n]\n", "language": "XPL0" }, { "code": "clear screen\n\nsites = 200\nxEdge = 600\nyEdge = 400\n\nopen window xEdge, yEdge\n\ndim townX(sites), townY(sites), col$(sites)\n\nfor i =1 to sites\n townX(i) =int(xEdge *ran(1))\n townY(i) =int(yEdge *ran(1))\n col$(i) = str$(int(256 * ran(1))) + \", \" + str$(int(256 * ran(1))) + \", \" + str$(int(256 * ran(1)))\n color col$(i)\n fill circle townX(i), townY(i), 2\nnext i\n\ndim nearestIndex(xEdge, yEdge)\ndim dist(xEdge, yEdge)\n\n//fill distance table with distances from the first site\nfor x = 0 to xEdge - 1\n for y = 0 to yEdge - 1\n dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2\n nearestIndex(x, y) = 1\n next y\nnext x\n\ncolor 0,0,255\n//for other towns\nfor i = 2 to sites\n //display some progress\n //print at(0,20) \"computing: \", (i/sites*100) using \"###.#\", \" %\"\n\n //look left\n for x = townX(i) to 0 step -1\n if not(checkRow(i, x,0, yEdge - 1)) break\n next x\n //look right\n for x = townX(i) + 1 to xEdge - 1\n if not(checkRow(i, x, 0, yEdge - 1)) break\n next x\nnext i\n\nfor x = 0 to xEdge - 1\n for y =0 to yEdge - 1\n \tcolor col$(nearestIndex(x, y))\n startY = y\n nearest = nearestIndex(x, y)\n for y = y + 1 to yEdge\n if nearestIndex(x, y) <> nearest then y = y - 1 : break : end if\n next y\n line x, startY, x, y + 1\n next y\nnext x\n\ncolor 0,0,0\nfor i =1 to sites\n fill circle townX( i), townY( i), 2\nnext i\nprint peek(\"millisrunning\"), \" ms\"\n\nsub checkRow(site, x, startY, endY)\n local dxSquared, y, check\n\t\n dxSquared = (townX(site) - x) ^ 2\n for y = startY to endY\n dSquared = (townY(site) - y) ^ 2 + dxSquared\n if dSquared <= dist(x, y) then\n dist(x, y) = dSquared\n nearestIndex(x, y) = site\n check = 1\n end if\n next y\n return check\nend sub\n", "language": "Yabasic" }, { "code": "width = 500 : height = 500\nopen window width, height\n\nexport sub hypot(a, b)\n return (sqrt(a^2+b^2))\nend sub\n\nsub generate_voronoi_diagram(width, height, num_cells)\n local nx(num_cells), ny(num_cells), nr(num_cells), ng(num_cells), nb(num_cells)\n\n for i = 1 to num_cells\n nx(i) = ran(width)\n ny(i) = ran(height)\n nr(i) = ran(256)\n ng(i) = ran(256)\n nb(i) = ran(256)\n next\n for y = 1 to height\n for x = 1 to width\n dmin = hypot(width-1, height-1)\n j = -1\n for i = 1 to num_cells\n d = hypot(nx(i)-x, ny(i)-y)\n if d < dmin dmin = d : j = i\n next\n color nr(j), ng(j), ng(j)\n dot x, y\n next\n next\n\nend sub\n\ngenerate_voronoi_diagram(width, height, 25)\n", "language": "Yabasic" }, { "code": "fcn generate_voronoi_diagram(width,height,num_cells){\n image,imgx,imgy:=PPM(width,height),width,height;\n nx:=num_cells.pump(List,(0).random.fp(imgx));\n ny:=num_cells.pump(List,(0).random.fp(imgy));\n nr:=num_cells.pump(List,(0).random.fp(256)); // red\n ng:=num_cells.pump(List,(0).random.fp(256)); // blue\n nb:=num_cells.pump(List,(0).random.fp(256)); // green\n\n foreach y,x in (imgy,imgx){\n dmin:=(imgx-1).toFloat().hypot(imgy-1);\n j:=-1;\n foreach i in (num_cells){\n d:=(nx[i] - x).toFloat().hypot(ny[i] - y);\n\t if(d<dmin) dmin,j = d,i\n }\n image[x,y]=(nr[j]*0xff00 + ng[j])*0xff00 + nb[j];\n }\n image\n}\n", "language": "Zkl" }, { "code": "generate_voronoi_diagram(500,500,25).write(File(\"VoronoiDiagram.ppm\",\"wb\"));\n", "language": "Zkl" } ]
Voronoi-diagram
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Wagstaff_primes\n", "language": "00-META" }, { "code": ";Definition\nA ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.\n\n;Example \n(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.\n\n;Task\nFind and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.\n\n;Stretch (requires arbitrary precision integers)\nFind and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for. \n\nWhen testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.\n\n;Note\nIt can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.\n\n;References\n\n* [[wp:Wagstaff prime|Wikipedia - Wagstaff prime]]\n* [[oeis:A000979|OEIS:A000979 - Wagstaff primes]]\n<br><br>\n", "language": "00-TASK" }, { "code": "BEGIN # find some Wagstaff primes: primes of the form ( 2^p + 1 ) / 3 #\n # where p is an odd prime #\n INT max wagstaff = 10; # number of Wagstaff primes to find #\n INT w count := 0; # numbdr of Wagstaff primes found so far #\n # sieve the primes up to 200, hopefully enough... #\n [ 0 : 200 ]BOOL primes;\n primes[ 0 ] := primes[ 1 ] := FALSE;\n primes[ 2 ] := TRUE;\n FOR i FROM 3 BY 2 TO UPB primes DO primes[ i ] := TRUE OD;\n FOR i FROM 4 BY 2 TO UPB primes DO primes[ i ] := FALSE OD;\n FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB primes ) DO\n IF primes[ i ] THEN\n FOR s FROM i * i BY i + i TO UPB primes DO primes[ s ] := FALSE OD\n FI\n OD;\n # attempt to find the Wagstaff primes #\n LONG INT power of 2 := 2; # 2^1 #\n FOR p FROM 3 BY 2 WHILE w count < max wagstaff DO\n power of 2 *:= 4;\n IF primes[ p ] THEN\n LONG INT w := ( power of 2 + 1 ) OVER 3;\n # check w is prime - trial division #\n BOOL is prime := TRUE;\n LONG INT n := 3;\n WHILE n * n <= w AND is prime DO\n is prime := w MOD n /= 0;\n n +:= 2\n OD;\n IF is prime THEN\n # have another Wagstaff prime #\n w count +:= 1;\n print( ( whole( w count, -2 )\n , \": \"\n , whole( p, -4 )\n , \": \"\n , whole( w, 0 )\n , newline\n )\n )\n FI\n FI\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "begin % find some Wagstaff primes: primes of the form ( 2^p + 1 ) / 3 %\n % where p is an odd prime %\n\n integer wCount;\n\n % returns true if d exactly divides v, false otherwise %\n logical procedure divides( long real value d, v ) ;\n begin\n long real q, p10;\n q := v / d;\n p10 := 1;\n while p10 * 10 < q do begin\n p10 := p10 * 10\n end while_p10_lt_q ;\n while p10 >= 1 do begin\n while q >= p10 do q := q - p10;\n p10 := p10 / 10\n end while_p10_ge_1 ;\n q = 0\n end divides ;\n\n % prints v as a 14 digit integer number %\n procedure printI14( long real value v ) ;\n begin\n integer iv;\n long real r;\n r := abs( v );\n if v < 0 then writeon( s_w := 0, \"-\" );\n iv := truncate( r / 1000000 );\n if iv < 1 then begin\n writeon( i_w := 8, s_w := 0, \" \", truncate( r ) )\n end\n else begin\n string(6) sValue;\n writeon( i_w := 8, s_w := 0, iv );\n iv := truncate( abs( r ) - ( iv * 1000000.0 ) );\n for sPos := 5 step -1 until 0 do begin\n sValue( sPos // 1 ) := code( ( iv rem 10 ) + decode( \"0\" ) );\n iv := iv div 10\n end for_sPos;\n writeon( s_w := 0, sValue )\n end if_iv_lt_1__\n end printI ;\n\n wCount := 0;\n % find the Wagstaff primes using long reals to hold the numbers, which %\n % accurately represent integers up to 2^53, so only consider primes < 53 %\n for p := 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 do begin\n long real w, powerOfTwo;\n logical isPrime;\n powerOfTwo := 1;\n for i := 1 until p do powerOfTwo := powerOfTwo * 2;\n w := ( powerOfTwo + 1 ) / 3;\n isPrime := not divides( 2, w );\n if isPrime then begin\n integer f, toNext;\n long real f2;\n f := 3;\n f2 := 9;\n toNext := 16;\n while isPrime and f2 <= w do begin\n isPrime := not divides( f, w );\n f := f + 2;\n f2 := f2 + toNext;\n toNext := toNext + 8\n end while_isPrime_and_f2_le_x\n end if_isPrime ;\n if isPrime then begin\n wCount := wCount + 1;\n write( i_w := 3, s_w := 0, wCount, \": \", p, \" \" );\n if p >= 32 then printI14( w )\n else begin\n integer iw;\n iw := truncate( w );\n writeon( i_w := 14, s_w := 0, iw )\n end of_p_ge_32__ ;\n if wCount >= 10 then goto done % stop at 10 Wagstaff primes %\n end if_isPrime\n end for_p ;\ndone:\nend.\n", "language": "ALGOL-W" }, { "code": "wagstaff?: function [e][\n and? -> prime? e -> prime? (1+2^e)/3\n]\n\nsummarize: function [n][\n n: ~\"|n|\"\n s: size n\n if s > 20 -> n: ((take n 10)++\"...\")++drop.times:s-10 n\n n ++ ~\" (|s| digits)\"\n]\n\nexponents: select.first:24 range.step:2 1 ∞ => wagstaff?\nloop.with:'i exponents 'x -> print [\n pad ~\"|i+1|:\" 3 pad ~\"|x| -\" 6 summarize (1+2^x)/3\n]\n", "language": "Arturo" }, { "code": "function isPrime(v)\n\tif v < 2 then return False\n\tif v mod 2 = 0 then return v = 2\n\tif v mod 3 = 0 then return v = 3\n\td = 5\n\twhile d * d <= v\n\t\tif v mod d = 0 then return False else d += 2\n\tend while\n\treturn True\nend function\n\nsubroutine Wagstaff(num)\n\tpri = 1\n\twcount = 0\n\twag = 0\n\twhile wcount < num\n\t\tpri += 2\n\t\tif isPrime(pri) then\n\t\t\twag = (2 ^ pri + 1) / 3\n\t\t\tif isPrime(wag) then\n\t\t\t\twcount += 1\n\t\t\t\tprint rjust(wcount,2); \": \"; rjust(pri,2); \" => \"; int(wag)\n\t\t\tend if\n\t\tend if\n\tend while\nend subroutine\n\ncall Wagstaff(9) #BASIC-256 does not allow larger numbers\nend\n", "language": "BASIC256" }, { "code": "#include <stdio.h>\n#include <string.h>\n#include <gmp.h>\n\nint main() {\n const int limit = 29;\n int count = 0;\n char tmp[40];\n mpz_t p, w;\n mpz_init_set_ui(p, 1);\n mpz_init(w);\n while (count < limit) {\n mpz_nextprime(p, p);\n mpz_set_ui(w, 1);\n unsigned long ulp = mpz_get_ui(p);\n mpz_mul_2exp(w, w, ulp);\n mpz_add_ui(w, w, 1);\n mpz_tdiv_q_ui(w, w, 3);\n if (mpz_probab_prime_p(w, 15) > 0) {\n ++count;\n char *ws = mpz_get_str(NULL, 10, w);\n size_t le = strlen(ws);\n if (le < 34) {\n strcpy(tmp, ws);\n } else {\n strncpy(tmp, ws, 15);\n strcpy(tmp + 15, \"...\");\n strncpy(tmp + 18, ws + le - 15, 16);\n }\n printf(\"%5lu: %s\", ulp, tmp);\n if (le >=34) printf( \" (%ld digits)\", le);\n printf(\"\\n\");\n }\n }\n return 0;\n}\n", "language": "C" }, { "code": "#include <gmpxx.h>\n#include <primesieve.hpp>\n\n#include <iostream>\n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t max_digits) {\n std::string str = num.get_str();\n size_t len = str.size();\n if (len > max_digits) {\n str.replace(max_digits / 2, len - max_digits, \"...\");\n str += \" (\";\n str += std::to_string(len);\n str += \" digits)\";\n }\n return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n const big_int one(1);\n primesieve::iterator pi;\n pi.next_prime();\n for (int i = 0; i < 24;) {\n uint64_t p = pi.next_prime();\n big_int n = ((one << p) + 1) / 3;\n if (is_probably_prime(n))\n std::cout << ++i << \": \" << p << \" - \" << to_string(n, 30) << '\\n';\n }\n}\n", "language": "C++" }, { "code": "'Craft Basic may only calculate up to 9\n\nlet n = 9\nlet p = 1\n\ndo\n\tlet p = p + 2\n\n\tif prime(p) then\n\n\t\tlet w = (2 ^ p + 1) / 3\n\n\t\tif prime(w) then\n\n\t\t\tlet c = c + 1\n\t\t\tprint tab, c, tab, p, tab, w\n\n\t\tendif\n\n\tendif\n\n\ttitle p\n\n\twait\n\nloop c < n\n", "language": "Craft-Basic" }, { "code": "procedure WagstaffPrimes(Memo: TMemo);\n{Finds Wagstaff primes up to 6^64}\nvar P,B,R: int64;\nvar Cnt: integer;\nbegin\n{B is int64 to force 64-bit arithmetic}\nP:=0; B:=1; Cnt:=0;\nMemo.Lines.Add(' #: P (2^P + 1)/3');\nwhile P<64 do\n\tbegin\n\tR:=((B shl P) + 1) div 3;\n\tif IsPrime(P) and IsPrime(R) then\n\t\tbegin\n\t\tInc(Cnt);\n\t\tMemo.Lines.Add(Format('%2d: %2d %24.0n',[Cnt,P,R+0.0]));\n\t\tend;\n\tInc(P);\n\tend;\nend;\n", "language": "Delphi" }, { "code": "func prime n .\n if n mod 2 = 0 and n > 2\n return 0\n .\n i = 3\n while i <= sqrt n\n if n mod i = 0\n return 0\n .\n i += 2\n .\n return 1\n.\npri = 1\nwhile nwag <> 10\n pri += 2\n if prime pri = 1\n wag = (pow 2 pri + 1) / 3\n if prime wag = 1\n nwag += 1\n print pri & \" => \" & wag\n .\n .\n.\n", "language": "EasyLang" }, { "code": "// Wagstaff primes. Nigel Galloway: September 15th., 2022\nlet isWagstaff n=let mutable g=(1I+2I**n)/3I in if Open.Numeric.Primes.MillerRabin.IsProbablePrime &g then Some (n,g) else None\nprimes32()|>Seq.choose isWagstaff|>Seq.take 10|>Seq.iter(fun (n,g)->printfn $\"%d{n}->%A{g}\")\nprimes32()|>Seq.choose isWagstaff|>Seq.skip 10|>Seq,take 14|>Seq.iter(fun(n,_)->printf $\"%d{n} \"); printfn \"\"\n", "language": "F-Sharp" }, { "code": "Function isPrime(Byval num As Ulongint) As Boolean\n If num < 2 Then Return False\n If num Mod 2 = 0 Then Return num = 2\n If num Mod 3 = 0 Then Return num = 3\n Dim d As Uinteger = 5\n While d * d <= num\n If num Mod d = 0 Then Return False Else d += 2\n Wend\n Return True\nEnd Function\n\nSub Wagstaff(num As Ulongint)\n Dim As Ulongint pri = 1, wcount = 0, wag\n While wcount < num\n pri += 2\n If isPrime(pri) Then\n wag = (2 ^ pri + 1) / 3\n If isPrime(wag) Then\n wcount += 1\n Print Using \"###: ### => ##,###,###,###,###\"; wcount; pri; wag\n End If\n End If\n Wend\nEnd Sub\n\nWagstaff(10)\nSleep\n", "language": "FreeBASIC" }, { "code": "Use \"isprime.bas\"\n\nPublic Sub Main()\n\n Wagstaff(10)\n\nEnd\n\nSub Wagstaff(num As Long)\n\n Dim pri As Long = 1\n Dim wcount As Long = 0\n Dim wag As Long\n\n While wcount < num\n pri = pri + 2\n If isPrime(pri) Then\n wag = (2 ^ pri + 1) / 3\n If isPrime(wag) Then\n wcount += 1\n Print Format$(Str(wcount), \"###\"); \": \"; Format$(Str(pri), \"###\"); \" => \"; Int(wag)\n End If\n End If\n Wend\n\nEnd Sub\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n big \"github.com/ncw/gmp\"\n \"rcu\"\n)\n\nfunc main() {\n const limit = 29\n count := 0\n p := 1\n one := big.NewInt(1)\n three := big.NewInt(3)\n w := new(big.Int)\n for count < limit {\n for {\n p += 2\n if rcu.IsPrime(p) {\n break\n }\n }\n w.SetUint64(1)\n w.Lsh(w, uint(p))\n w.Add(w, one)\n w.Quo(w, three)\n if w.ProbablyPrime(15) {\n count++\n ws := w.String()\n le := len(ws)\n if le >= 34 {\n ws = ws[0:15] + \"...\" + ws[le-15:]\n }\n fmt.Printf(\"%5d: %s\", p, ws)\n if le >= 34 {\n fmt.Printf(\" (%d digits)\", le)\n }\n println()\n }\n }\n}\n", "language": "Go" }, { "code": " (,.f)p:I.1 p:(f=.3%~1+2x^])p:i.60\n 3 3\n 5 11\n 7 43\n 11 683\n 13 2731\n 17 43691\n 19 174763\n 23 2796203\n 31 715827883\n 43 2932031007403\n 61 768614336404564651\n 79 201487636602438195784363\n101 845100400152152934331135470251\n127 56713727820156410577229101238628035243\n167 62357403192785191176690552862561408838653121833643\n191 1046183622564446793972631570534611069350392574077339085483\n199 267823007376498379256993682056860433753700498963798805883563\n", "language": "J" }, { "code": "{{\n T0=. 6!:1''\n f=. 3%~1+2x^]\n c=. 0\n echo 'count power seconds'\n for_p. p:i.1e4 do.\n if. 1 p: f p do.\n c=. c+1\n echo 5 6 8j3\":c, p, (6!:1'')-T0\n if. 24 <: c do. return. end.\n end.\n end.\n}}_\ncount power seconds\n 1 3 0.004\n 2 5 0.006\n 3 7 0.008\n 4 11 0.013\n 5 13 0.018\n 6 17 0.021\n 7 19 0.025\n 8 23 0.028\n 9 31 0.030\n 10 43 0.033\n 11 61 0.035\n 12 79 0.039\n 13 101 0.044\n 14 127 0.052\n 15 167 0.062\n 16 191 0.075\n 17 199 0.089\n 18 313 0.120\n 19 347 0.167\n 20 701 0.436\n 21 1709 4.140\n 22 2617 16.035\n 23 3539 45.089\n 24 5807 181.280\n", "language": "J" }, { "code": "import java.math.BigInteger;\n\npublic class Main {\n public static void main(String[] args) {\n BigInteger d = new BigInteger(\"3\"), a;\n int lmt = 25, sl, c = 0;\n for (int i = 3; i < 5808; ) {\n a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);\n if (a.isProbablePrime(1)) {\n System.out.printf(\"%2d %4d \", ++c, i);\n String s = a.toString(); sl = s.length();\n if (sl < lmt) System.out.println(a);\n else System.out.println(s.substring(0, 11) + \"..\" + s.substring(sl - 11, sl) + \" \" + sl + \" digits\");\n }\n i = BigInteger.valueOf(i).nextProbablePrime().intValue();\n }\n }\n}\n", "language": "Java" }, { "code": "using Primes\n\nfunction wagstaffpair(p::Integer)\n isodd(p) || return (false, nothing)\n isprime(p) || return (false, nothing)\n\n m = (2^big(p) + 1) ÷ 3\n\n isprime(m) || return (false, nothing)\n\n return (true, m)\nend\n\nfunction findn_wagstaff_pairs(n_to_find::T) where T <: Integer\n pairs = Tuple{T, BigInt}[]\n count = 0\n i = 2\n while count < n_to_find\n iswag, m = wagstaffpair(i)\n iswag && push!(pairs, (i, m))\n count += iswag\n i += 1\n end\n return pairs\nend\n\nfunction println_wagstaff(pair; max_digit_display::Integer=20)\n p, m = pair\n mstr = string(m)\n\n if length(mstr) > max_digit_display\n umiddle = cld(max_digit_display, 2)\n lmiddle = fld(max_digit_display, 2)\n mstr = join((mstr[1:umiddle], \"...\", mstr[end-lmiddle+1:end],\n \" ($(length(mstr)) digits)\"))\n end\n\n println(\"p = $p, m = $mstr\")\nend\n\nforeach(println_wagstaff, findn_wagstaff_pairs(24))\n", "language": "Julia" }, { "code": "import std/strformat\nimport integers\n\nfunc compress(str: string; size: int): string =\n if str.len <= 2 * size: str\n else: &\"{str[0..<size]}...{str[^size..^1]} ({str.len} digits)\"\n\necho \"First 24 Wagstaff primes:\"\nlet One = newInteger(1)\nvar count = 0\nvar p = 3\nwhile count < 24:\n if p.isPrime:\n let n = (One shl p + 1) div 3\n if n.isPrime:\n inc count\n echo &\"{p:4}: {compress($n, 15)}\"\n inc p, 2\n", "language": "Nim" }, { "code": "let is_prime n =\n let rec test x =\n let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)\n in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5\n\nlet is_wagstaff n =\n let w = succ (1 lsl n) / 3 in\n if is_prime n && is_prime w then Some (n, w) else None\n\nlet () =\n let show (p, w) = Printf.printf \"%u -> %u%!\\n\" p w in\n Seq.(ints 3 |> filter_map is_wagstaff |> take 11 |> iter show)\n", "language": "OCaml" }, { "code": "\\\\ compiler: gp2c option: gp2c-run -g wprp.gp\n\n\n/* wprp(p): input odd prime p > 5 . */\n/* returns 1 if (2^p+1)/3 is a Wagstaff probable prime. */\nwprp(p) = {\n\n /* trial division up to a reasonable depth (time ratio tdiv/llr ≈ 0.2) */\n my(l=log(p), ld=log(l));\n forprimestep(q = 1, sqr(ld)^(l/log(2))\\4, p+p,\n if(Mod(2,q)^p == -1, return)\n );\n\n /* From R. & H. LIFCHITZ July 2000 */\n /* see: http://primenumbers.net/Documents/TestNP.pdf */\n /* if (2^p+1)/3 is prime ==> 25^2^(p-1) ≡ 25 (mod 2^p+1) */\n /* Lucas-Lehmer-Riesel test with fast modular reduction. */\n my(s=25, m=2^p-1);\n for(i = 2, p,\n s = sqr(s);\n s = bitand(s,m) - s>>p\n );\n s==25\n}; /* end wprp */\n\n\n/* get exponents of Wagstaff prps in range [a,b] */\nwprprun(a, b) = {\n my(t=0, c=0, thr=default(nbthreads));\n a = max(a,3);\n gettime();\n if(a <= 5,\n if(a == 3, c++; p = 3; printf(\"#%d\\tW%d\\t%2dmin, %2d,%03d ms\\n\", c, p, t\\60000%60, t\\1000%60, t%1000));\n c++; p = 5; printf(\"#%d\\tW%d\\t%2dmin, %2d,%03d ms\\n\", c, p, t\\60000%60, t\\1000%60, t%1000);\n a = 7\n );\n parforprime(p= a, b, wprp(p), d, /* wprp(p) -> d copy from parallel world into real world. */\n if(d,\n t += gettime()\\thr;\n c++;\n printf(\"#%d\\tW%d\\t%2dmin, %2d,%03d ms\\n\", c, p, t\\60000%60, t\\1000%60, t%1000)\n )\n )\n}; /* end wprprun */\n\n\n/* if running wprp as script */\n\\\\ export(wprp);\n\n\nwprprun(2, 42737)\n", "language": "PARI-GP" }, { "code": "use v5.36;\nuse bigint;\nuse ntheory 'is_prime';\n\nsub abbr ($d) { my $l = length $d; $l < 61 ? $d : substr($d,0,30) . '..' . substr($d,-30) . \" ($l digits)\" }\n\nmy($p,@W) = 2;\nuntil (@W == 30) {\n next unless 0 != ++$p % 2;\n push @W, $p if is_prime($p) and is_prime((2**$p + 1)/3)\n}\n\nprintf \"%2d: %5d - %s\\n\", $_+1, $W[$_], abbr( (2**$W[$_] + 1) / 3) for 0..$#W;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">isWagstaff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bLenOnly</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">mpz_ui_pow_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_add_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">assert</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_fdiv_q_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">mpz_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #7060A8;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bLenOnly</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">mpz_sizeinbase</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #7060A8;\">mpz_get_str</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">comma_fill</span><span style=\"color: #0000FF;\">:=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)):</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">wagstaff</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wagstaff</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">10</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pdx</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">isWagstaff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">wagstaff</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">}}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">pdx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"First 10 Wagstaff primes for the values of 'p' shown:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">papply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"%2d: %s\\n\"</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">wagstaff</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\nTook %s\\n\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Wagstaff primes that we can find in 5 seconds:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()<</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">5</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_prime</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pdx</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">isWagstaff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">integer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%5d (%,d digits, %s)\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">elapsed</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">pdx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n<!--\n", "language": "Phix" }, { "code": "\"\"\" Rosetta code Wagstaff_primes task \"\"\"\n\nfrom sympy import isprime\n\ndef wagstaff(N):\n \"\"\" find first N Wagstaff primes \"\"\"\n pri, wcount = 1, 0\n while wcount < N:\n pri += 2\n if isprime(pri):\n wag = (2**pri + 1) // 3\n if isprime(wag):\n wcount += 1\n print(f'{wcount: 3}: {pri: 5} => ',\n f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')\n\n\nwagstaff(24)\n", "language": "Python" }, { "code": " [ bit 1+ 3 / ] is wagstaff ( n --> n )\n\n [] 3 from\n [ 2 incr\n index prime while\n index wagstaff prime while\n index join\n dup size 24 = if end ]\n 10 split swap\n witheach\n [ dup say \"p = \" echo\n wagstaff\n say \", w(p) = \" echo cr ]\n witheach\n [ say \"p = \" echo cr ]\n", "language": "Quackery" }, { "code": "# First 20\n\nmy @wagstaff = (^∞).grep: { .is-prime && ((1 + 1 +< $_)/3).is-prime };\n\nsay ++$ ~ \": $_ - {(1 + 1 +< $_)/3}\" for @wagstaff[^20];\n\nsay .fmt(\"\\nTotal elapsed seconds: (%.2f)\\n\") given (my $elapsed = now) - INIT now;\n\n# However many I have patience for\n\nmy atomicint $count = 20;\n\nhyper for @wagstaff[20] .. * {\n next unless .is-prime;\n say ++⚛$count ~ \": $_ ({sprintf \"%.2f\", now - $elapsed})\" and $elapsed = now if is-prime (1 + 1 +< $_)/3;\n}\n", "language": "Raku" }, { "code": "require 'prime'\nrequire 'gmp'\n\nwagstaffs = Enumerator.new do |y|\n odd_primes = Prime.each\n odd_primes.next #skip 2\n loop do\n p = odd_primes.next\n candidate = (2 ** p + 1)/3\n y << [p, candidate] unless GMP::Z.new(candidate).probab_prime?.zero?\n end\nend\n\n10.times{puts \"%5d - %s\" % wagstaffs.next}\n14.times{puts \"%5d\" % wagstaffs.next.first}\n", "language": "Ruby" }, { "code": "import \"./math\" for Int\nimport \"./gmp\" for Mpz\nimport \"./fmt\" for Fmt\n\nvar isWagstaff = Fn.new { |p|\n var w = (2.pow(p) + 1) / 3 // always integral\n if (!Int.isPrime(w)) return [false, null]\n return [true, [p, w]]\n}\n\nvar isBigWagstaff = Fn.new { |p|\n var w = Mpz.one.lsh(p).add(1).div(3)\n return w.probPrime(15) > 0\n}\n\nvar start = System.clock\nvar p = 1\nvar wagstaff = []\nwhile (wagstaff.count < 10) {\n while (true) {\n p = p + 2\n if (Int.isPrime(p)) break\n }\n var res = isWagstaff.call(p)\n if (res[0]) wagstaff.add(res[1])\n}\nSystem.print(\"First 10 Wagstaff primes for the values of 'p' shown:\")\nfor (i in 0..9) Fmt.print(\"$2d: $d\", wagstaff[i][0], wagstaff[i][1])\nSystem.print(\"\\nTook %(System.clock - start) seconds\")\n\nvar limit = 19\nvar count = 0\nSystem.print(\"\\nValues of 'p' for the next %(limit) Wagstaff primes and\")\nSystem.print(\"overall time taken to reach them to higher second:\")\nwhile (count < limit) {\n while (true) {\n p = p + 2\n if (Int.isPrime(p)) break\n }\n if (isBigWagstaff.call(p)) {\n Fmt.print(\"$5d ($3d secs)\", p, (System.clock - start).ceil)\n count = count + 1\n }\n}\n", "language": "Wren" }, { "code": "func IsPrime(N); \\Return 'true' if N is prime\nreal N; int I;\n[if N <= 2. then return N = 2.;\nif Mod(N, 2.) = 0. then \\even\\ return false;\nfor I:= 3 to fix(sqrt(N)) do\n [if Mod(N, float(I)) = 0. then return false;\n I:= I+1;\n ];\nreturn true;\n];\n\nreal P, Q; int C;\n[P:= 2.; C:= 0;\nFormat(1, 0);\nrepeat if IsPrime(P) then\n [Q:= Pow(2., P) + 1.;\n if Mod(Q, 3.) = 0. and IsPrime(Q/3.) then\n [Text(0, \"(2^^\");\n RlOut(0, P);\n Text(0, \" + 1)/3 = \");\n RlOut(0, Q/3.);\n CrLf(0);\n C:= C+1;\n ];\n ];\n P:= P+1.;\nuntil C >= 10;\n]\n", "language": "XPL0" } ]
Wagstaff-primes
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Walk_a_directory/Non-recursively\nnote: File System Operations\n", "language": "00-META" }, { "code": ";Task:\nWalk a given directory and print the ''names'' of files matching a given pattern. \n\n(How is \"pattern\" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)\n\n\n'''Note:''' This task is for non-recursive methods. &nbsp; These tasks should read a ''single directory'', not an entire directory tree. \n\n'''Note:''' Please be careful when running any code presented here.\n\n\n;Related task:\n* &nbsp; [[Walk Directory Tree]] &nbsp; (read entire directory tree). \n<br><br>\n\n", "language": "00-TASK" }, { "code": "L(filename) fs:list_dir(‘/foo/bar’)\n I filename.ends_with(‘.mp3’)\n print(filename)\n", "language": "11l" }, { "code": ";\n; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham\n;\n\nexecBase equ 4\n\n;\n; from exec includes\n;\n_LVOOpenLibrary equ -552\n_LVOCloseLibrary equ -414\n_LVOAllocVec equ -684\n_LVOFreeVec equ -690\n\nMEMF_ANY equ 0\n\n;\n; from dos includes\n;\n_LVOVPrintf equ -954\n_LVOExamine equ -102\n_LVOExNext equ -108\n_LVOLock equ -84\n_LVOUnLock equ -90\n_LVOParsePatternNoCase equ -966\n_LVOMatchPatternNoCase equ -972\n\nACCESS_READ equ -2\n rsset 0\nfib_DiskKey rs.l 1\nfib_DirEntryType rs.l 1\nfib_FileName rs.b 108\nfib_Protection rs.l 1\nfib_EntryType rs.l 1\nfib_Size rs.l 1\nfib_NumBlocks rs.l 1\nfib_DateStamp rs.b 12\nfib_Comment rs.b 80\nfib_OwnerUID rs.w 1\nfib_OwnerGID rs.w 1\nfib_Reserved rs.b 32\nfib_SIZEOF rs.b 0\n\n;\n; main\n;\n\nstart\n move.l execBase,a6\n\n; open dos.library\n\n lea dosName,a1\n moveq #37,d0\n jsr _LVOOpenLibrary(a6)\n move.l d0,dosBase\n beq exit\n\n; allocate memory for file info block\n\n move.l #fib_SIZEOF,d0\n move.l #MEMF_ANY,d1\n jsr _LVOAllocVec(a6)\n move.l d0,fib\n beq exit\n\n; get directory lock\n\n move.l dosBase,a6\n\n move.l #pathString,d1\n move.l #ACCESS_READ,d2\n jsr _LVOLock(a6)\n move.l d0,lock\n beq exit\n\n; examine directory for ExNext\n\n move.l lock,d1\n move.l fib,d2\n jsr _LVOExamine(a6)\n tst.w d0\n beq exit\n\n; parse pattern string\n\n move.l #patternString,d1\n move.l #patternParsed,d2\n move.l #sizeof_patternString*2+2,d3\n jsr _LVOParsePatternNoCase(a6)\n tst.l d0\n blt exit\n\n; get some pointers for use in the loop\n\n lea printfArgs,a2\n move.l fib,a3\n lea fib_FileName(a3),a3\n\n.loop\n\n; get next directory entry\n\n move.l lock,d1\n move.l fib,d2\n jsr _LVOExNext(a6)\n tst.w d0\n beq exit\n\n; match pattern\n\n move.l #patternParsed,d1\n move.l a3,d2\n jsr _LVOMatchPatternNoCase(a6)\n\n; if match then print file name\n\n tst.l d0\n beq .nomatch\n\n move.l a3,(a2)\n move.l #formatString,d1\n move.l #printfArgs,d2\n jsr _LVOVPrintf(a6)\n\n.nomatch\n bra .loop\n\n; cleanup and exit\n\nexit\n move.l dosBase,a6\n move.l lock,d1\n jsr _LVOUnLock(a6)\n\n move.l execBase,a6\n move.l fib,a1\n tst.l a1\n beq .l1\n jsr _LVOFreeVec(a6)\n.l1\n move.l dosBase,a1\n jsr _LVOCloseLibrary(a6)\n rts\n\n section data,data_p\n;\n; variables\n;\ndosBase\n dc.l 0\n\nlock\n dc.l 0\n\nfib\n dc.l 0\n\nprintfArgs\n dc.l 0\n;\n; strings\n;\ndosName\n dc.b \"dos.library\",0\n\npathString\n dc.b \"ram:\",0\n\nformatString\n dc.b \"%s\",10,0\n\npatternString\n dc.b \"#?\",0\npatternString_end\nsizeof_patternString=patternString_end-patternString\n\npatternParsed\n dcb.b sizeof_patternString*2+2\n", "language": "68000-Assembly" }, { "code": "exit:\tequ\t0\t; CP/M syscall to exit\nputs:\tequ\t9\t; CP/M syscall to print a string\nsfirst:\tequ\t17\t; 'Find First' CP/M syscall\nsnext:\tequ\t18\t; 'Find Next' CP/M syscall\nFCB:\tequ\t5Ch\t; Location of FCB for file given on command line\n\torg\t100h\t\n\tlxi\td,FCB\t; CP/M parses the command line for us automatically\n\tmvi\tc,sfirst; and prepares an FCB which we can pass to SFIRST\n\tcall\t5\t; immediately.\n\tlxi\td,emsg\t; If SFIRST returns an error, there is no file,\n\tmvi\tc,puts\t; so we should print an error message.\nloop:\tinr\ta\t; A=FF = error\n\tjz\t5\n\tdcr\ta\t; If we _do_ have a file, the directory entry\n\trrc\t\t; is located at DTA (80h) + A * 32. 0<=A<=3.\n\trrc\t\t; Rotate right twice, moving low bits into high bits,\n\tstc\t\t; then finally rotate a 1 bit into the top bit.\n\trar\t\t; The effect is 000000AB -> 1AB00000.\n\tinr\ta\t; Finally the filename is at offset 1 in the dirent.\n\tmvi\th,0\t; Set HL = pointer to the filename\n\tmov\tl,a\t\n\tlxi\td,fname\t; The filename is stored as 'FILENAMEEXT', but let's\n\tmvi\tb,8\t; be nice and print 'FILENAME.EXT\\r\\n'.\n\tcall\tmemcpy\t; Copy filename (wihtout extension) into placeholder\n\tinx\td\t; Skip the '.' in the placeholder\n\tmvi\tb,3\t; Then copy the extension\n\tcall\tmemcpy\n\tlxi\td,fname\t; Then print the formatted filename\n\tmvi\tc,puts\n\tcall\t5\n\tlxi\td,FCB\t; Find the next file matching the pattern in the FCB\n\tmvi\tc,snext ; The result is the same as for SFIRST, so we can\n\tcall\t5\t; loop back here, except FF means no more files.\n\tmvi\tc,exit\t; Arrange for the error routine to instead exit cleanly\n\tjmp\tloop\nmemcpy:\tmov\ta,m\t; Copy B bytes from HL to DE\n\tstax\td\n\tinx\th\n\tinx\td\n\tdcr \tb\n\tjnz\tmemcpy\n\tret\t\nemsg:\tdb\t'Not Found$'\nfname:\tdb\t'XXXXXXXX.XXX',13,10,'$'\t; Filename placeholder\n", "language": "8080-Assembly" }, { "code": "\"*.c\" f:glob \\ puts an array of strings with the file names on the top of the stack\n", "language": "8th" }, { "code": "PROC GetFileName(CHAR ARRAY line,fname)\n BYTE i,len\n\n len=0\n i=3\n FOR i=3 TO 10\n DO\n IF line(i)=32 THEN EXIT FI\n len==+1\n fname(len)=line(i)\n OD\n len==+1\n fname(len)='.\n FOR i=11 TO 13\n DO\n IF line(i)=32 THEN EXIT FI\n len==+1\n fname(len)=line(i)\n OD\n fname(0)=len\nRETURN\n\nPROC Dir(CHAR ARRAY filter)\n CHAR ARRAY line(255),fname(255)\n BYTE dev=[1]\n\n PrintE(filter)\n Close(dev)\n Open(dev,filter,6)\n DO\n InputSD(dev,line)\n IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN\n EXIT\n FI\n GetFileName(line,fname)\n Put(32) PrintE(fname)\n OD\n Close(dev)\n PutE()\nRETURN\n\nPROC Main()\n Dir(\"D:*.*\")\n Dir(\"H1:X*.*\")\n Dir(\"H1:?????.ACT\")\n Dir(\"H1:??F*.*\")\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Directories; use Ada.Directories;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Walk_Directory\n (Directory : in String := \".\";\n Pattern : in String := \"\") -- empty pattern = all file names/subdirectory names\nis\n Search : Search_Type;\n Dir_Ent : Directory_Entry_Type;\nbegin\n Start_Search (Search, Directory, Pattern);\n\n while More_Entries (Search) loop\n Get_Next_Entry (Search, Dir_Ent);\n Put_Line (Simple_Name (Dir_Ent));\n end loop;\n\n End_Search (Search);\nend Walk_Directory;\n", "language": "Ada" }, { "code": "INT match=0, no match=1, out of memory error=2, other error=3;\n\n[]STRING directory = get directory(\".\");\nFOR file index TO UPB directory DO\n STRING file = directory[file index];\n IF grep in string(\"[Ss]ort*.[.]a68$\", file, NIL, NIL) = match THEN\n print((file, new line))\n FI\nOD\n", "language": "ALGOL-68" }, { "code": "tell application \"Finder\" to return name of every item in (startup disk)\n--> EXAMPLE RESULT: {\"Applications\", \"Developer\", \"Library\", \"System\", \"Users\"}\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to return name of every item in (path to documents folder from user domain) whose name ends with \"pdf\"\n--> EXAMPLE RESULT: {\"About Stacks.pdf\", \"Test.pdf\"}\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to return name of every item in (path to documents folder from user domain) whose name does not contain \"about\" and name ends with \"pdf\"\n--> RETURNS: {\"Test.pdf\"}\n", "language": "AppleScript" }, { "code": "tell application \"Finder\" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with \"pdf\"\n", "language": "AppleScript" }, { "code": "tell application \"System Events\" to return name of every item in documents folder whose name extension is \"pdf\"\n--> EXAMPLE RESULT: {\"ShellScripting.pdf\", \"RFC 4180 (CSV spec).pdf\", \"About Stacks.pdf\", \"AppleScriptLanguageGuide.pdf\", \"robinson_jeffers_2004_9.pdf\", \"DiskWarrior Manual.pdf\", \"RFC 2445 (iCalendar spec).pdf\", \"Artistic Orchestration.pdf\"}\n", "language": "AppleScript" }, { "code": "set docsFolderPath to POSIX path of (path to documents folder)\n-- By default, \"ls\" returns file names sorted by character code, so save the sorting until the end and do it case-insensitively.\nset shellCommandText to \"ls -f \" & quoted form of docsFolderPath & \" | grep -i '\\\\.pdf$' | sort -f\"\nreturn paragraphs of (do shell script shellCommandText)\n--> EXAMPLE RESULT: {\"About Stacks.pdf\", \"AppleScriptLanguageGuide.pdf\", \"Artistic Orchestration.pdf\", \"DiskWarrior Manual.pdf\", \"RFC 2445 (iCalendar spec).pdf\", \"RFC 4180 (CSV spec).pdf\", \"robinson_jeffers_2004_9.pdf\", \"ShellScripting.pdf\"}\n", "language": "AppleScript" }, { "code": "use AppleScript version \"2.4\" -- OS X 10.10 (Yosemite) or later\nuse framework \"Foundation\"\nuse scripting additions\n\nset docsFolderURL to current application's class \"NSURL\"'s fileURLWithPath:(POSIX path of (path to documents folder))\n-- Get NSURLs for the folder's visible contents.\ntell current application's class \"NSFileManager\"'s defaultManager() to ¬\n set visibleItems to its contentsOfDirectoryAtURL:(docsFolderURL) includingPropertiesForKeys:({}) ¬\n options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)\n-- Filter case-insensitively for those whose names have \".pdf\" extensions.\nset filter to current application's class \"NSPredicate\"'s predicateWithFormat:(\"pathExtension ==[c] 'pdf'\")\nset PDFs to visibleItems's filteredArrayUsingPredicate:(filter)\n-- Get the names of any matching items.\nset pdfNames to PDFs's valueForKey:(\"lastPathComponent\")\n-- Sort these case-insensitively and considering numerics.\nset pdfNames to pdfNames's sortedArrayUsingSelector:(\"localizedStandardCompare:\")\n-- Return the result as an AppleScript list of text.\nreturn pdfNames as list\n--> EXAMPLE RESULT: {\"About Stacks.pdf\", \"AppleScriptLanguageGuide.pdf\", \"Artistic Orchestration.pdf\", \"DiskWarrior Manual.pdf\", \"RFC 2445 (iCalendar spec).pdf\", \"RFC 4180 (CSV spec).pdf\", \"robinson_jeffers_2004_9.pdf\", \"ShellScripting.pdf\"}\n", "language": "AppleScript" }, { "code": "; list all files at current path\nprint list \".\"\n\n; get all files at given path\n; and select only the ones we want\n\n; just select the files with .md extension\nselect list \"some/path\"\n => [\".md\" = extract.extension]\n\n; just select the files that contain \"test\"\nselect list \"some/path\"\n => [in? \"test\"]\n", "language": "Arturo" }, { "code": "Loop, %A_WinDir%\\*.ini\n out .= A_LoopFileName \"`n\"\nMsgBox,% out\n", "language": "AutoHotkey" }, { "code": "PRINT WALK$(\".\", 1, \".+\", FALSE, NL$)\n", "language": "BaCon" }, { "code": "DECLARE SUB show (pattern AS STRING)\n\nshow \"*.*\"\n\nSUB show (pattern AS STRING)\n DIM f AS STRING\n f = DIR$(pattern)\n DO WHILE LEN(f)\n PRINT f\n f = DIR$\n LOOP\nEND SUB\n", "language": "BASIC" }, { "code": "call show (\"c:\\\")\nend\n\nsubroutine show (pattern$)\n\tf$ = dir(pattern$)\n\twhile length(f$)\n\t\tprint f$\n\t\tf$ = dir\n\tend while\nend subroutine\n", "language": "BASIC256" }, { "code": "dir /b \"%windir%\\system32\\*.exe\"\n", "language": "Batch-File" }, { "code": "@for /F \"tokens=*\" %%F in ('dir /b \"%windir%\\system32\\*.exe\"') do echo %%F\n", "language": "Batch-File" }, { "code": "for /F \"tokens=*\" %F in ('dir /b \"%windir%\\system32\\*.exe\"') do echo %F\n", "language": "Batch-File" }, { "code": " directory$ = \"C:\\Windows\\\"\n pattern$ = \"*.ini\"\n PROClistdir(directory$ + pattern$)\n END\n\n DEF PROClistdir(afsp$)\n LOCAL dir%, sh%, res%\n DIM dir% LOCAL 317\n SYS \"FindFirstFile\", afsp$, dir% TO sh%\n IF sh% <> -1 THEN\n REPEAT\n PRINT $$(dir%+44)\n SYS \"FindNextFile\", sh%, dir% TO res%\n UNTIL res% = 0\n SYS \"FindClose\", sh%\n ENDIF\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "#include <sys/types.h>\n#include <dirent.h>\n#include <regex.h>\n#include <stdio.h>\n\nenum {\n WALK_OK = 0,\n WALK_BADPATTERN,\n WALK_BADOPEN,\n};\n\nint walker(const char *dir, const char *pattern)\n{\n struct dirent *entry;\n regex_t reg;\n DIR *d;\n\n if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB))\n return WALK_BADPATTERN;\n if (!(d = opendir(dir)))\n return WALK_BADOPEN;\n while (entry = readdir(d))\n if (!regexec(&reg, entry->d_name, 0, NULL, 0))\n puts(entry->d_name);\n closedir(d);\n regfree(&reg);\n return WALK_OK;\n}\n\nint main()\n{\n walker(\".\", \".\\\\.c$\");\n return 0;\n}\n", "language": "C" }, { "code": "#include \"boost/filesystem.hpp\"\n#include \"boost/regex.hpp\"\n#include <iostream>\n\nusing namespace boost::filesystem;\n\nint main()\n{\n path current_dir(\".\");\n // list all files starting with a\n boost::regex pattern(\"a.*\");\n for (directory_iterator iter(current_dir), end;\n iter != end;\n ++iter)\n {\n boost::smatch match;\n std::string fn = iter->path().filename().string(); // must make local variable\n if (boost::regex_match( fn, match, pattern))\n {\n std::cout << match[0] << \"\\n\";\n }\n }\n}\n", "language": "C++" }, { "code": "#include <filesystem>\n#include <iostream>\n\nnamespace fs = std::filesystem;\n\nint main() {\n fs::path current_dir(\".\");\n // list all files containing an mp3 extension\n for (auto &file : fs::directory_iterator(current_dir)) {\n if (file.path().extension() == \".mp3\")\n std::cout << file.path().filename().string() << std::endl;\n }\n}\n", "language": "C++" }, { "code": "using System;\nusing System.IO;\n\nnamespace DirectoryWalk\n{\n class Program\n {\n static void Main(string[] args)\n {\n string[] filePaths = Directory.GetFiles(@\"c:\\MyDir\", \"a*\");\n foreach (string filename in filePaths)\n Console.WriteLine(filename);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(import java.nio.file.FileSystems)\n\n(defn match-files [f pattern]\n (.matches (.getPathMatcher (FileSystems/getDefault) (str \"glob:*\" pattern)) (.toPath f)))\n\n(defn walk-directory [dir pattern]\n (let [directory (clojure.java.io/file dir)]\n (map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))))\n", "language": "Clojure" }, { "code": "<cfdirectory action=\"list\" directory=\"C:\\temp\" filter=\"*.html\" name=\"dirListing\">\n<cfoutput query=\"dirListing\">\n #dirListing.name# (#dirListing.type#)<br>\n</cfoutput>\n", "language": "ColdFusion" }, { "code": "(defun walk-directory (directory pattern)\n (directory (merge-pathnames pattern directory)))\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio, std.file;\n\n dirEntries(\".\", \"*.*\", SpanMode.shallow).writeln;\n}\n", "language": "D" }, { "code": "$ loop:\n$ f = f$search( p1 )\n$ if f .eqs. \"\" then $ exit\n$ write sys$output f\n$ goto loop\n", "language": "DCL" }, { "code": "program Walk_a_directory;\n\n{$APPTYPE CONSOLE}\n{$R *.res}\n\nuses\n System.IOUtils;\n\nvar\n Files: TArray<string>;\n FileName, Directory: string;\n\nbegin\n Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to\n Files := TDirectory.GetFiles(Directory, '*.*');\n\n for FileName in Files do\n begin\n Writeln(FileName);\n end;\n\n Readln;\nend.\n", "language": "Delphi" }, { "code": "def walkDirectory(directory, pattern) {\n for name => file ? (name =~ rx`.*$pattern.*`) in directory {\n println(name)\n }\n}\n", "language": "E" }, { "code": "? walkDirectory(<file:~>, \"bash_\")\n.bash_history\n.bash_profile\n.bash_profile~\n", "language": "E" }, { "code": "import system'io;\nimport system'routines;\nimport extensions'routines;\n\npublic program()\n{\n var dir := Directory.assign(\"c:\\MyDir\");\n\n dir.getFiles(\"a.*\").forEach(printingLn);\n}\n", "language": "Elena" }, { "code": "# current directory\nIO.inspect File.ls!\n\ndir = \"/users/public\"\nIO.inspect File.ls!(dir)\n", "language": "Elixir" }, { "code": "(directory-files \"/some/dir/name\"\n nil ;; just the filenames, not full paths\n \"\\\\.c\\\\'\" ;; regexp\n t) ;; don't sort the filenames\n;;=> (\"foo.c\" \"bar.c\" ...)\n", "language": "Emacs-Lisp" }, { "code": "include file.e\n\nprocedure show(sequence pattern)\n sequence f\n f = dir(pattern)\n for i = 1 to length(f) do\n puts(1,f[i][D_NAME])\n puts(1,'\\n')\n end for\nend procedure\n\nshow(\"*.*\")\n", "language": "Euphoria" }, { "code": "System.IO.Directory.GetFiles(\"c:\\\\temp\", \"*.xml\")\n|> Array.iter (printfn \"%s\")\n", "language": "F-Sharp" }, { "code": "USING: globs io io.directories kernel regexp sequences ;\nIN: walk-directory-non-recursively\n\n: print-files ( path pattern -- )\n [ directory-files ] [ <glob> ] bi* [ matches? ] curry filter\n [ print ] each ;\n", "language": "Factor" }, { "code": "defer ls-filter ( name len -- ? )\n: ls-all 2drop true ;\n: ls-visible drop c@ [char] . <> ;\n\n: ls ( dir len -- )\n open-dir throw ( dirid )\n begin\n dup pad 256 rot read-dir throw\n while\n pad over ls-filter if\n cr pad swap type\n else drop then\n repeat\n drop close-dir throw ;\n\n\\ only show C language source and header files (*.c *.h)\n: c-file? ( str len -- ? )\n dup 3 < if 2drop false exit then\n + 1- dup c@\n dup [char] c <> swap [char] h <> and if drop false exit then\n 1- dup c@ [char] . <> if drop false exit then\n drop true ;\n' c-file? is ls-filter\n\ns\" .\" ls\n", "language": "Forth" }, { "code": "Sub show (pattern As String)\n Dim As String f = Dir$(pattern)\n While Len(f)\n Print f\n f = Dir$\n Wend\nEnd Sub\n\nshow \"*.*\"\nSleep\n", "language": "FreeBASIC" }, { "code": "for f = select[files[\".\"], {|f1| f1.getName[] =~ %r/\\.frink$/}]\n println[f.getName[]]\n", "language": "Frink" }, { "code": "include \"NSLog.incl\"\n\nvoid local fn EnumerateDirectoryAtURL( dirURL as CFURLRef )\n NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsPackageDescendants + ¬\n NSDirectoryEnumerationSkipsHiddenFiles + ¬\n NSDirectoryEnumerationSkipsSubdirectoryDescendants\n\n DirectoryEnumeratorRef enumerator = fn FileManagerEnumeratorAtURL( dirURL, NULL, options, NULL, NULL )\n CFURLRef url = fn EnumeratorNextObject( enumerator )\n while ( url )\n if ( fn StringIsEqual( fn URLPathExtension( url ), @\"fb\" ) )\n NSLog(@\"%@\",fn URLLastPathComponent( url ))\n end if\n url = fn EnumeratorNextObject( enumerator )\n wend\nend fn\n\nfn EnumerateDirectoryAtURL( fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) )\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\nDim sTemp As String\n\nFor Each sTemp In Dir(\"/etc\", \"*.d\")\n Print sTemp\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"path/filepath\"\n)\n\nfunc main() {\n fmt.Println(filepath.Glob(\"*.go\"))\n}\n", "language": "Go" }, { "code": "// *** print *.txt files in current directory\n new File('.').eachFileMatch(~/.*\\.txt/) {\n println it\n }\n\n // *** print *.txt files in /foo/bar\n new File('/foo/bar').eachFileMatch(~/.*\\.txt/) {\n println it\n }\n", "language": "Groovy" }, { "code": "use fmt;\nuse glob;\n\nexport fn main() void = {\n\tls(\"/etc/*.conf\");\n};\n\nfn ls(pattern: str) void = {\n\tlet gen = glob::glob(pattern, glob::flags::NONE);\n\tdefer glob::finish(&gen);\n\tfor (true) match (glob::next(&gen)) {\n\tcase void =>\n\t\tbreak;\n\tcase glob::failure =>\n\t\tcontinue;\n\tcase let s: str =>\n\t\tfmt::printfln(\"{}\", s)!;\n\t};\n};\n", "language": "Hare" }, { "code": "import System.Directory\nimport Text.Regex\nimport Data.Maybe\n\nwalk :: FilePath -> String -> IO ()\nwalk dir pattern = do\n filenames <- getDirectoryContents dir\n mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames\n\nmain = walk \".\" \".\\\\.hs$\"\n", "language": "Haskell" }, { "code": "CHARACTER dirtxt='dir.txt', filename*80\n\nSYSTEM(DIR='*.*', FIle=dirtxt) ! \"file names\", length, attrib, Created, LastWrite, LastAccess\nOPEN(FIle=dirtxt, Format='\"\",', LENgth=files) ! parses column 1 (\"file names\")\n\nDO nr = 1, files\n filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename\n ! write file names with extensions \"txt\", or \"hic\", or \"jpg\" (case insensitive) using RegEx option =128:\n IF( INDEX(filename, \"\\.txt|\\.hic|\\.jpg\", 128) ) WRITE() filename\nENDDO\n", "language": "HicEst" }, { "code": "procedure main()\nevery write(getdirs(\".\",\"icn\")) # writes out all directories from the current directory down\nend\n\nprocedure getdirs(s,pat) #: return a list of directories beneath the directory 's'\nlocal d,f\n\nif ( stat(s).mode ? =\"d\" ) & ( d := open(s) ) then {\n while f := read(d) do\n if find(pat,f) then\n suspend f\n close(d)\n }\nend\n", "language": "Icon" }, { "code": "f = file_search('*.txt', count=cc)\nif cc gt 0 then print,f\n", "language": "IDL" }, { "code": "require 'dir'\n0 dir '*.png'\n0 dir '/mydir/*.txt'\n", "language": "J" }, { "code": "File dir = new File(\"/foo/bar\");\n\nString[] contents = dir.list();\nfor (String file : contents)\n if (file.endsWith(\".mp3\"))\n System.out.println(file);\n", "language": "Java" }, { "code": "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\nvar dir = fso.GetFolder('test_folder');\n\nfunction walkDirectory(dir, re_pattern) {\n WScript.Echo(\"Files in \" + dir.name + \" matching '\" + re_pattern +\"':\");\n walkDirectoryFilter(dir.Files, re_pattern);\n\n WScript.Echo(\"Folders in \" + dir.name + \" matching '\" + re_pattern +\"':\");\n walkDirectoryFilter(dir.Subfolders, re_pattern);\n}\n\nfunction walkDirectoryFilter(items, re_pattern) {\n var e = new Enumerator(items);\n while (! e.atEnd()) {\n var item = e.item();\n if (item.name.match(re_pattern))\n WScript.Echo(item.name);\n e.moveNext();\n }\n}\n\nwalkDirectory(dir, '\\\\.txt$');\n", "language": "JavaScript" }, { "code": "for filename in readdir(\"/foo/bar\")\n if endswith(filename, \".mp3\")\n print(filename)\n end\nend\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.io.File\n\nfun walkDirectory(dirPath: String, pattern: Regex): List<String> {\n val d = File(dirPath)\n require(d.exists() && d.isDirectory())\n return d.list().filter { it.matches(pattern) }\n}\n\nfun main(args: Array<String>) {\n val r = Regex(\"\"\"^a.*\\.h$\"\"\") // get all C header files beginning with 'a'\n val files = walkDirectory(\"/usr/include\", r)\n for (file in files) println(file)\n}\n", "language": "Kotlin" }, { "code": "local(matchingfilenames = array)\n\ndir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}\n\n#matchingfilenames\n", "language": "Lasso" }, { "code": "-- Usage: printFiles(\"C:\\scripts\", \".ls\")\non printFiles (dir, fileType)\n i = 1\n sub = fileType.length -1\n repeat while TRUE\n fn = getNthFileNameInFolder(dir, i)\n if fn = EMPTY then exit repeat\n i = i+1\n if fn.length<fileType.length then next repeat\n if fn.char[fn.length-sub..fn.length]=fileType then put fn\n end repeat\nend\n", "language": "Lingo" }, { "code": "set the defaultFolder to the documents folder -- the documents folder is a \"specialFolderPath\"\nput the files into docfiles\nfilter docfiles with \"*.txt\"\nput docfiles\n", "language": "LiveCode" }, { "code": "require \"lfs\"\ndirectorypath = \".\" -- current working directory\nfor filename in lfs.dir(directorypath) do\n if filename:match(\"%.lua$\") then -- \"%.\" is an escaped \".\", \"$\" is end of string\n print(filename)\n end\nend\n", "language": "Lua" }, { "code": "-- Gets the output of given program as string\n-- Note that io.popen is not available on all platforms\nlocal function getOutput(prog)\n local file = assert(io.popen(prog, \"r\"))\n local output = assert(file:read(\"*a\"))\n file:close()\n return output\nend\n\n-- Iterates files in given directory\nlocal function files(directory, recursively)\n -- Use windows\" dir command\n local directory = directory:gsub(\"/\", \"\\\\\")\n local filenames = getOutput(string.format(\"dir %s %s/B/A:A\", directory, recursively and '/S' or ''))\n\n -- Function to be called in \"for filename in files(directory)\"\n return coroutine.wrap(function()\n for filename in filenames:gmatch(\"([^\\r\\n]+)\") do\n coroutine.yield(filename)\n end\n end)\nend\n\n-- Walk \"C:/Windows\" looking for executables\nlocal directory = \"C:/Windows\"\nlocal pattern = \".*%.exe$\" -- for finding executables\nfor filename in files(directory) do\n if filename:match(pattern) then\n print(filename)\n end\nend\n", "language": "Lua" }, { "code": "Module Show_Files_Standard {\n \\\\ we get more (include hidden too)\n Module InnerWay (folder_path$, pattern$){\n olddir$=dir$\n dir folder_path$\n \\\\ clear menu list\n Menu\n \\\\ + place export to menu, without showing\n \\\\ ! sort to name\n files ! + pattern$\n If MenuItems>0 then {\n For i=1 to MenuItems {\n Print Menu$(i)+\".exe\"\n }\n }\n dir olddir$\n }\n InnerWay \"C:\\Windows\",\"*.exe\"\n}\nShow_Files_Standard\n", "language": "M2000-Interpreter" }, { "code": "Module Show_Files {\n Function get_files$ (folder_path$) {\n \\\\ we get second argument using letter$ which pop from stack\n pattern$=lcase$(Letter$)\n Declare objfso \"Scripting.FileSystemObject\"\n Method objfso, \"GetFolder\", folder_path$ as fc\n With fc, \"files\" set files\n \\\\ from revision 13 - version 9.4\n With files, -4& as EnumFile\n With EnumFile, \"Name\" as name$\n Dim empty$()\n =empty$()\n Stack New {\n While EnumFile {\n If lcase$(name$) ~ pattern$ Then Data name$\n }\n \\\\ get stack values and fill an array\n =Array$([])\n }\n }\n Dim Name$()\n Name$()=get_files$(\"C:\\Windows\",\"*.exe\")\n m=each(Name$())\n While m {\n Print Array$(m)\n }\n}\nShow_Files\n", "language": "M2000-Interpreter" }, { "code": "FileNames[\"*\"]\nFileNames[\"*.png\", $RootDirectory]\n", "language": "Mathematica" }, { "code": "getFiles \"C:\\\\*.txt\"\n", "language": "MAXScript" }, { "code": "import Nanoquery.IO\n\nfor fname in new(File).listDir(\"/foo/bar\")\n\tif lower(new(File, fname).getExtension()) = \".mp3\"\n\t\tprintln filename\n\tend\nend\n", "language": "Nanoquery" }, { "code": "using System.Console;\nusing System.IO;\n\nmodule DirWalk\n{\n Main() : void\n {\n def files = Directory.GetFiles(@\"C:\\MyDir\"); // retrieves only files\n def files_subs = Directory.GetFileSystemEntries(@\"C:\\MyDir\"); // also retrieves (but does not enter) sub-directories\n // (like ls command)\n foreach (file in files) WriteLine(file);\n }\n}\n", "language": "Nemerle" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\nimport java.util.List\n\nrunSample(arg)\nreturn\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod getFileNames(dirname, pattern) public static returns List\n dir = File(dirname)\n contents = dir.list()\n fileNames = ArrayList()\n loop fname over contents\n if fname.matches(pattern) then do\n fileNames.add(fname)\n end\n end fname\n Collections.sort(fileNames)\n return fileNames\n\n-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmethod runSample(arg) private static\n parse arg dirname pattern\n if dirname = '' then dirname = System.getProperty('user.dir')\n if pattern = '' then pattern = '^RW.*\\\\.nrx$'\n\n fileNames = getFileNames(dirname, pattern)\n say 'Search of' dirname 'for files matching pattern \"'pattern'\" found' fileNames.size() 'files.'\n loop fn = 0 while fn < fileNames.size()\n say (fn + 1).right(5)':' fileNames.get(fn)\n end fn\n\n return\n", "language": "NetRexx" }, { "code": "import os\n\nfor file in walkFiles \"/foo/bar/*.mp3\":\n echo file\n", "language": "Nim" }, { "code": "use IO;\n\nbundle Default {\n class Test {\n function : Main(args : System.String[]) ~ Nil {\n dir := Directory->List(\"/src/code\");\n for(i := 0; i < dir->Size(); i += 1;) {\n if(dir[i]->EndsWith(\".obs\")) {\n dir[i]->PrintLine();\n };\n };\n }\n }\n}\n", "language": "Objeck" }, { "code": "NSString *dir = @\"/foo/bar\";\n\n// Pre-OS X 10.5\nNSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir];\n// OS X 10.5+\nNSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];\n\nfor (NSString *file in contents)\n if ([[file pathExtension] isEqualToString:@\"mp3\"])\n NSLog(@\"%@\", file);\n", "language": "Objective-C" }, { "code": "#load \"str.cma\"\nlet contents = Array.to_list (Sys.readdir \".\") in\nlet select pat str = Str.string_match (Str.regexp pat) str 0 in\nList.filter (select \".*\\\\.jpg\") contents\n", "language": "OCaml" }, { "code": "package main\n\nimport \"core:fmt\"\nimport \"core:path/filepath\"\n\nmain :: proc() {\n matches, _err := filepath.glob(\"*.odin\")\n for match in matches do fmt.println(match)\n}\n", "language": "Odin" }, { "code": "declare\n [Path] = {Module.link ['x-oz://system/os/Path.ozf']}\n [Regex] = {Module.link ['x-oz://contrib/regex']}\n\n Files = {Filter {Path.readdir \".\"} Path.isFile}\n Pattern = \".*\\\\.oz$\"\n MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \\= false end}\nin\n {ForAll MatchingFiles System.showInfo}\n", "language": "Oz" }, { "code": "{$H+}\n\nprogram Walk;\n\nuses SysUtils;\n\nvar Res: TSearchRec;\n Pattern, Path, Name: String;\n FileAttr: LongInt;\n Attr: Integer;\n\nbegin\n Write('File pattern: ');\n ReadLn(Pattern); { For example .\\*.pas }\n\n Attr := faAnyFile;\n if FindFirst(Pattern, Attr, Res) = 0 then\n begin\n Path := ExtractFileDir(Pattern);\n repeat\n Name := ConcatPaths([Path, Res.Name]);\n FileAttr := FileGetAttr(Name);\n if FileAttr and faDirectory = 0 then\n begin\n { Do something with file name }\n WriteLn(Name);\n end\n until FindNext(Res) <> 0;\n end;\n FindClose(Res);\nend.\n", "language": "Pascal" }, { "code": "use 5.010;\nopendir my $dh, '/home/foo/bar';\nsay for grep { /php$/ } readdir $dh;\nclosedir $dh;\n", "language": "Perl" }, { "code": "use 5.010; say while </home/foo/bar/*.php>;\n", "language": "Perl" }, { "code": "my @filenames = glob('/home/foo/bar/*.php');\n", "language": "Perl" }, { "code": "my $pattern = '*.c';\nmy @filenames = glob($pattern);\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">dir</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"*.txt\"</span><span style=\"color: #0000FF;\">))[</span><span style=\"color: #000000;\">D_NAME</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "$pattern = 'php';\n$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux\nwhile (false !== ($file = readdir($dh)))\n{\n if ($file != '.' and $file != '..')\n {\n if (preg_match(\"/$pattern/\", $file))\n {\n echo \"$file matches $pattern\\n\";\n }\n }\n}\nclosedir($dh);\n", "language": "PHP" }, { "code": "$pattern = 'php';\nforeach (scandir('/home/foo/bar') as $file)\n{\n if ($file != '.' and $file != '..')\n {\n if (preg_match(\"/$pattern/\", $file))\n {\n echo \"$file matches $pattern\\n\";\n }\n }\n}\n", "language": "PHP" }, { "code": "foreach (glob('/home/foo/bar/*.php') as $file){\n echo \"$file\\n\";\n}\n", "language": "PHP" }, { "code": "(for F (dir \"@src/\") # Iterate directory\n (when (match '`(chop \"[email protected]\") (chop F)) # Matches 's*.c'?\n (println F) ) ) # Yes: Print it\n", "language": "PicoLisp" }, { "code": "array(string) files = get_dir(\"/home/foo/bar\");\nforeach(files, string file)\n write(file + \"\\n\");\n", "language": "Pike" }, { "code": "lvars repp, fil;\n;;; create path repeater\nsys_file_match('*.p', '', false, 0) -> repp;\n;;; iterate over files\nwhile (repp() ->> fil) /= termin do\n ;;; print the file\n printf(fil, '%s\\n');\nendwhile;\n", "language": "Pop11" }, { "code": "Get-ChildItem *.txt -Name\nGet-ChildItem f* -Name\n", "language": "PowerShell" }, { "code": "Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' }\n", "language": "PowerShell" }, { "code": "Procedure walkDirectory(directory.s = \"\", pattern.s = \"\")\n Protected directoryID\n\n directoryID = ExamineDirectory(#PB_Any,directory,pattern)\n If directoryID\n While NextDirectoryEntry(directoryID)\n PrintN(DirectoryEntryName(directoryID))\n Wend\n FinishDirectory(directoryID)\n EndIf\nEndProcedure\n\nIf OpenConsole()\n walkDirectory()\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "import glob\nfor filename in glob.glob('/foo/bar/*.mp3'):\n print(filename)\n", "language": "Python" }, { "code": "import os\nfor filename in os.listdir('/foo/bar'):\n if filename.endswith('.mp3'):\n print(filename)\n", "language": "Python" }, { "code": "dir(\"/foo/bar\", \"mp3\")\n", "language": "R" }, { "code": "-> (for ([f (directory-list \"/tmp\")] #:when (regexp-match? \"\\\\.rkt$\" f))\n (displayln f))\n... *.rkt files ...\n", "language": "Racket" }, { "code": ".say for dir \".\", :test(/foo/);\n", "language": "Raku" }, { "code": "import IO;\npublic void Walk(loc a, str pattern){\n\tfor (entry <- listEntries(a))\n\t\tendsWith(entry, pattern) ? println(entry);\n}\n", "language": "Rascal" }, { "code": "'dir://.' open each as item\n item m/\\.txt$/ if \"%(item)s\\n\" print\n", "language": "Raven" }, { "code": "/*REXX program shows files in directory tree that match a given criteria*/\nparse arg xdir; if xdir='' then xdir='\\' /*Any DIR? Use default.*/\n@.=0 /*default in case ADDRESS fails. */\ntrace off /*suppress REXX err msg for fails*/\naddress system 'DIR' xdir '/b /s' with output stem @. /*issue DIR cmd.*/\nif rc\\==0 then do /*an error happened?*/\n say '***error!*** from DIR' xDIR /*indicate que pasa.*/\n say 'return code=' rc /*show the Ret Code.*/\n exit rc /*exit with the RC.*/\n end /* [↑] bad address.*/\n#[email protected] /*number of entries.*/\nif #==0 then #=' no ' /*use a word, ¬zero.*/\nsay center('directory ' xdir \" has \" # ' matching entries.',79,'─')\n\n do j=1 for #; say @.j; end /*show files that met criteria. */\n\nexit @.0+rc /*stick a fork in it, we're done.*/\n", "language": "REXX" }, { "code": "###---------------------------------------\n### Directory Tree Walk\n### Look for FileType for Music and Video\n\nfileType = [\".avi\", \".mp4\", \".mpg\", \".mkv\", \".mp3\", \".wmv\" ]\n\ndirList = []\nmusicList = []\n\n###---------------------------------------\n### Main\n\n ###-----------------------------------\n ### Start at this directory\n\n searchVideoMusic(\"C:\\Users\\Umberto\\\")\n\n see nl +\"Number of Music and Videos files: \" +len(musicList) +nl +nl\n see musicList\n See nl +\"Finished\" +nl\n\n###=======================================\n### Search for Video and Music files\n\nFunc searchVideoMusic(startDir)\n\n ChDir(startDir + \"Music\") ### <<<== add Music subpath C:\\Users\\Umberto\\Music\n listDir( CurrentDir() )\n\n ChDir(startDir + \"Videos\") ### <<<== add Videos subpath C:\\Users\\Umberto\\Videos\n listDir( CurrentDir() )\n\n for searchDir in dirList ### Search Directory List for Music and Videos files\n listDir(searchDir)\n next\n\n\n###==============================\n### Find Files in Directory\n\nFunc listDir(dirName)\n\n ChDir(dirName)\n Try\n ###-------------------------------------\n ### Get SubDirectories\n\n myListSub = Dir( CurrentDir() )\n Catch\n ###-------------------------------------\n ### Error, Couldn't open the directory\n\n See \"ListDir Catch! \" + CurrentDir() +\" --- \"+ cCatchError +nl\n return\n Done\n\n for x in myListSub\n if x[2]\n thisDir = x[1]\n\n if thisDir[1] = \".\"\n ### Do Nothing. Ignore dot.name\n\n else\n see nl +\"Dir: \" + CurrentDir() +\"\\\"+ thisDir + nl\n\n ###----------------------------------------\n ### Directory Walk add to directory list\n\n Add( dirList, (CurrentDir() +\"\\\"+ thisDir))\n ok\n else\n thisFile = x[1]\n\n ###-------------------------------\n ### Add Music or Video file type\n\n for thisType in fileType\n if ( substr(thisFile, thisType) ) ### <<<== Type of File from List\n see \" File: \" + thisFile + nl\n Add(musicList, (CurrentDir() +\"\\\"+ thisFile))\n ok\n next\n ok\n next\nreturn\n\n###===============================================\n", "language": "Ring" }, { "code": "# Files under this directory:\nDir.glob('*') { |file| puts file }\n\n# Files under path '/foo/bar':\nDir.glob( File.join('/foo/bar', '*') ) { |file| puts file }\n\n# As a method\ndef file_match(pattern=/\\.txt/, path='.')\n Dir[File.join(path,'*')].each do |file|\n puts file if file =~ pattern\n end\nend\n", "language": "Ruby" }, { "code": "files #g, DefaultDir$ + \"\\*.jpg\" ' find all jpg files\n\nif #g HASANSWER() then\n\tcount = #g rowcount()\t' get count of files\n\tfor i = 1 to count\n\tif #g hasanswer() then\t'retrieve info for next file\n\t\t#g nextfile$()\t'print name of file\n\t\tprint #g NAME$()\n\tend if\n\tnext\nend if\nwait\n", "language": "Run-BASIC" }, { "code": "extern crate docopt;\nextern crate regex;\nextern crate rustc_serialize;\n\nuse docopt::Docopt;\nuse regex::Regex;\n\nconst USAGE: &'static str = \"\nUsage: rosetta <pattern>\n\nWalks the directory tree starting with the current working directory and\nprint filenames matching <pattern>.\n\";\n\n#[derive(Debug, RustcDecodable)]\nstruct Args {\n arg_pattern: String,\n}\n\nfn main() {\n let args: Args = Docopt::new(USAGE)\n .and_then(|d| d.decode())\n .unwrap_or_else(|e| e.exit());\n\n let re = Regex::new(&args.arg_pattern).unwrap();\n let paths = std::fs::read_dir(\".\").unwrap();\n\n for path in paths {\n let path = path.unwrap().path();\n let path = path.to_str().unwrap();\n\n if re.is_match(path) {\n println!(\"{}\", path);\n }\n }\n}\n", "language": "Rust" }, { "code": "import java.io.File\n\nval dir = new File(\"/foo/bar\").list()\ndir.filter(file => file.endsWith(\".mp3\")).foreach(println)\n", "language": "Scala" }, { "code": "$ include \"seed7_05.s7i\";\n include \"osfiles.s7i\";\n\nconst proc: main is func\n local\n var string: fileName is \"\";\n begin\n for fileName range readDir(\".\") do\n if endsWith(fileName, \".sd7\") then\n writeln(fileName);\n end if;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "'*.p[lm]'.glob.each { |file| say file } # Perl files under this directory\n", "language": "Sidef" }, { "code": "func file_match(Block callback, pattern=/\\.txt\\z/, path=Dir.cwd) {\n path.open(\\var dir_h) || return nil\n dir_h.entries.each { |entry|\n if (entry.basename ~~ pattern) {\n callback(entry)\n }\n }\n}\n \nfile_match(\n path: %d'/tmp',\n pattern: /\\.p[lm]\\z/i,\n callback: { |file|\n say file;\n }\n)\n", "language": "Sidef" }, { "code": "(Directory name: 'a_directory')\n allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]\n", "language": "Smalltalk" }, { "code": "fun dirEntries path =\n let\n fun loop strm =\n case OS.FileSys.readDir strm of\n SOME name => name :: loop strm\n | NONE => []\n val strm = OS.FileSys.openDir path\n in\n loop strm before OS.FileSys.closeDir strm\n end\n", "language": "Standard-ML" }, { "code": "(print o concat o map (fn s => s ^ \"\\n\") o List.filter (String.isPrefix \".\") o dirEntries) \".\"\n", "language": "Standard-ML" }, { "code": "foreach filename [glob *.txt] {\n puts $filename\n}\n", "language": "Tcl" }, { "code": "set dir /foo/bar\nforeach filename [glob -directory $dir *.txt] {\n puts $filename\n ### Or, if you only want the local filename part...\n # puts [file tail $filename]\n}\n", "language": "Tcl" }, { "code": "needs shell\n\" .\" \" .\\\\.txt$\" dir.listByPattern\n", "language": "Toka" }, { "code": "$$ MODE TUSCRIPT\nfiles=FILE_NAMES (+,-std-)\nfileswtxt= FILTER_INDEX (files,\":*.txt:\",-)\ntxtfiles= SELECT (files,#fileswtxt)\n", "language": "TUSCRIPT" }, { "code": "(glob \"/etc/*.conf\")\n", "language": "TXR" }, { "code": "(\"/etc/adduser.conf\" \"/etc/apg.conf\" \"/etc/blkid.conf\" \"/etc/brltty.conf\"\n \"/etc/ca-certificates.conf\" \"/etc/colord.conf\" \"/etc/ddclient.conf\"\n \"/etc/debconf.conf\" \"/etc/deluser.conf\" \"/etc/dnsmasq.conf\" \"/etc/ffserver.conf\"\n \"/etc/fuse.conf\" \"/etc/gai.conf\" \"/etc/hdparm.conf\" \"/etc/host.conf\"\n \"/etc/insserv.conf\" \"/etc/irssi.conf\" \"/etc/kernel-img.conf\"\n \"/etc/kerneloops.conf\" \"/etc/knockd.conf\" \"/etc/ld.so.conf\" \"/etc/lftp.conf\"\n \"/etc/logrotate.conf\" \"/etc/ltrace.conf\" \"/etc/mke2fs.conf\" \"/etc/mtools.conf\"\n \"/etc/netscsid.conf\" \"/etc/nsswitch.conf\" \"/etc/ntp.conf\" \"/etc/pam.conf\"\n \"/etc/pnm2ppa.conf\" \"/etc/popularity-contest.conf\" \"/etc/resolv.conf\"\n \"/etc/rsyslog.conf\" \"/etc/sensors3.conf\" \"/etc/sysctl.conf\" \"/etc/ucf.conf\"\n \"/etc/updatedb.conf\" \"/etc/usb_modeswitch.conf\" \"/etc/wodim.conf\")\n", "language": "TXR" }, { "code": "(mappend [iff (op ends-with \".conf\") list] (get-lines (open-directory \"/etc\")))\n", "language": "TXR" }, { "code": "(\"ddclient.conf\" \"gai.conf\" \"ucf.conf\" \"kernel-img.conf\" \"ltrace.conf\"\n \"debconf.conf\" \"apg.conf\" \"adduser.conf\" \"mke2fs.conf\" \"colord.conf\"\n \"kerneloops.conf\" \"fuse.conf\" \"hdparm.conf\" \"irssi.conf\" \"host.conf\"\n \"ffserver.conf\" \"pam.conf\" \"sysctl.conf\" \"ld.so.conf\" \"dnsmasq.conf\"\n \"insserv.conf\" \"brltty.conf\" \"deluser.conf\" \"netscsid.conf\" \"nsswitch.conf\"\n \"mtools.conf\" \"wodim.conf\" \"updatedb.conf\" \"popularity-contest.conf\"\n \"knockd.conf\" \"ntp.conf\" \"sensors3.conf\" \"resolv.conf\" \"blkid.conf\"\n \"lftp.conf\" \"ca-certificates.conf\" \"usb_modeswitch.conf\" \"logrotate.conf\"\n \"rsyslog.conf\" \"pnm2ppa.conf\")\n", "language": "TXR" }, { "code": "ls -d *.c # *.c files in current directory\n(cd mydir && ls -d *.c) # *.c files in mydir\n", "language": "UNIX-Shell" }, { "code": "ls | grep '\\.c$'\n", "language": "UnixPipes" }, { "code": "Sub show_files(folder_path,pattern)\n\tSet objfso = CreateObject(\"Scripting.FileSystemObject\")\n\tFor Each file In objfso.GetFolder(folder_path).Files\n\t\tIf InStr(file.Name,pattern) Then\n\t\t\tWScript.StdOut.WriteLine file.Name\n\t\tEnd If\n\tNext\nEnd Sub\n\nCall show_files(\"C:\\Windows\",\".exe\")\n", "language": "VBScript" }, { "code": "'Using the OS pattern matching\nFor Each file In IO.Directory.GetFiles(\"\\temp\", \"*.txt\")\n Console.WriteLine(file)\nNext\n\n'Using VB's pattern matching and LINQ\nFor Each file In (From name In IO.Directory.GetFiles(\"\\temp\") Where name Like \"*.txt\")\n Console.WriteLine(file)\nNext\n\n'Using VB's pattern matching and dot-notation\nFor Each file In IO.Directory.GetFiles(\"\\temp\").Where(Function(f) f Like \"*.txt\")\n Console.WriteLine(file)\nNext\n", "language": "Visual-Basic-.NET" }, { "code": "import \"io\" for Directory\nimport \"./pattern\" for Pattern\n\nvar walk = Fn.new { |dir, pattern|\n if (!Directory.exists(dir)) Fiber.abort(\"Directory does not exist.\")\n var files = Directory.list(dir)\n return files.where { |f| pattern.isMatch(f) }\n}\n\n// get all C header files beginning with 'a' or 'b'\nvar p = Pattern.new(\"[a|b]+0^..h\", Pattern.whole)\nfor (f in walk.call(\"/usr/include\", p)) System.print(f)\n", "language": "Wren" }, { "code": "File.glob(\"*.zkl\") //--> list of matches\n", "language": "Zkl" } ]
Walk-a-directory-Non-recursively
[ { "code": "---\ncategory:\n- Cards\n- Games\nfrom: http://rosettacode.org/wiki/War_card_game\n", "language": "00-META" }, { "code": "War Card Game\n\nSimulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.\n\nReferences:\n\n:* Bicycle card company: [https://bicyclecards.com/how-to-play/war War game site]\n\n:* Wikipedia: [[wp:War_(card_game)|War (card game)]]\n\nRelated tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards for FreeCell]]\n* [[Poker hand_analyser]]\n* [[Go Fish]]\n\n\n", "language": "00-TASK" }, { "code": "UInt32 seed = 0\nF nonrandom(n)\n :seed = (1664525 * :seed + 1013904223) [&] FFFF'FFFF\n R Int(:seed >> 16) % n\n\nF nonrandom_shuffle(&x)\n L(i) (x.len - 1 .< 0).step(-1)\n V j = nonrandom(i + 1)\n swap(&x[i], &x[j])\n\nV SUITS = [‘♣’, ‘♦’, ‘♥’, ‘♠’]\nV FACES = [‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘J’, ‘Q’, ‘K’, ‘A’]\nV DECK = multiloop(FACES, SUITS, (f, s) -> f‘’s)\nV CARD_TO_RANK = Dict((0 .< DECK.len).map(i -> (:DECK[i], (i + 3) I/ 4)))\n\nT WarCardGame\n [String] deck1, deck2, pending\n\n F ()\n V deck = copy(:DECK)\n nonrandom_shuffle(&deck)\n .deck1 = deck[0.<26]\n .deck2 = deck[26..]\n\n F gameover()\n ‘ game over who won message ’\n I .deck2.empty\n I .deck1.empty\n print(\"\\nGame ends as a tie.\")\n E\n print(\"\\nPlayer 1 wins the game.\")\n E\n print(\"\\nPlayer 2 wins the game.\")\n R 0B\n\n F turn()\n ‘ one turn, may recurse on tie ’\n I .deck1.empty | .deck2.empty\n R .gameover()\n\n V card1 = .deck1.pop(0)\n V card2 = .deck2.pop(0)\n V (rank1, rank2) = (:CARD_TO_RANK[card1], :CARD_TO_RANK[card2])\n print(‘#<10#<10’.format(card1, card2), end' ‘’)\n I rank1 > rank2\n print(‘Player 1 takes the cards.’)\n .deck1.extend([card1, card2])\n .deck1.extend(.pending)\n .pending.clear()\n E I rank1 < rank2\n print(‘Player 2 takes the cards.’)\n .deck2.extend([card2, card1])\n .deck2.extend(.pending)\n .pending.clear()\n E\n print(‘Tie!’)\n I .deck1.empty | .deck2.empty\n R .gameover()\n\n V card3 = .deck1.pop(0)\n V card4 = .deck2.pop(0)\n .pending.extend([card1, card2, card3, card4])\n print(‘#<10#<10’.format(‘?’, ‘?’)‘Cards are face down.’)\n R .turn()\n\n R 1B\n\nV WG = WarCardGame()\nL WG.turn()\n L.continue\n", "language": "11l" }, { "code": " 100 R = RND (0): REM SEED\n 110 W = 1: REM BICYCLE RULE: ONLY ONE EXTRA CARD GIVEN UP IN WAR\n 120 P = 2: REM BICYCLE RULE: ONLY TWO PLAYERS\n 130 D = 1: REM BICYCLE RULE: ONLY ONE DECK OF CARDS\n 140 DIM D$(P),C$(P),G(P),L(P)\n 150 SUIT$ = \"CDHS\"\n 160 FACE$ = \"23456789TJQKA\"\n 170 M = LEN (SUIT$)\n 180 FOR I = 1 TO D: FOR S = 1 TO M: FOR F = 1 TO LEN (FACE$):P$ = P$ + CHR$ ((F - 1) * M + (S - 1)): NEXT F,S,I\n 190 TEXT : HOME : POKE 34,12\n REM DEAL TO PLAYERS\n 200 GOSUB 700\"SHUFFLE\n 210 E = INT (N / P)\n 220 FOR I = 1 TO P\n 230 D$(I) = MID$ (P$,(I - 1) * E + 1,E)\n 240 NEXT\n 250 P$ = MID$ (P$,(I - 1) * E + 1): REM WINNER OF THE FIRST PLAY KEEPS THESE REMAINING CARDS\n 260 P$ = \"\": REM REMOVE REMAINING CARDS FROM THE GAME\n REM PLAY\n 300 FOR T = 0 TO 1E38\n 310 GOSUB 400\"TURN\n 320 IF Q = 0 THEN NEXT T\n 330 PRINT \" IN \"T\" TURNS\": TEXT : VTAB 11: PRINT : CALL - 868: PRINT \"...\": VTAB 23\n 340 END\n\n REM TURN\n 400 PRINT : GOSUB 900\"IS GAME OVER?\n 410 IF Q THEN RETURN\n 420 U = 0: REM UTMOST CARD\n 430 C = 0: REM COUNT THE PLAYERS WITH THE UTMOST CARD\n 440 FOR I = 1 TO P\n 450 C$(I) = \"\" : IF NOT L(I) THEN C$(I) = MID$ (D$(I),1,1)\n 460 IF LEN (C$(I)) THEN GOSUB 800\"DRAW CARD\n 470 NEXT I\n 480 IF C = 1 GOTO 600\"WINNER TAKE CARDS\n 490 FOR I = 1 TO P:L(I) = G(I) < > U: NEXT I\n 500 PRINT \"WAR! \";\n 510 GOSUB 900\"IS GAME OVER?\n 520 IF Q THEN RETURN\n 530 C = 0\n 540 FOR I = 1 TO P:P$ = P$ + C$(I): NEXT I\n 550 FOR I = 1 TO P\n REM DOES NOT APPLY TO 2 PLAYER GAMES (BICYCLE RULE): Y MEANS IGNORE THE RULE THAT ONLY THE WINNERS PLACE CARD(S) FACE DOWN\n 560 IF Y OR NOT L(I) THEN FOR J = 1 TO W:C$ = MID$ (D$(I),1,1) :C = C + LEN(C$) : P$ = P$ + C$ :D$(I) = MID$ (D$(I),2): NEXT J\n 570 NEXT I\n 580 PRINT C\" CARDS PLACED FACE DOWN.\";\n 590 RETURN\n\n REM WINNER TAKE CARDS\n 600 FOR I = 1 TO P\n 610 L(I) = 0\n 620 P$ = P$ + C$(I)\n 630 NEXT I\n 640 PRINT \"PLAYER \"A\" TAKES \"LEN(P$);\n 650 IF NOT Z THEN GOSUB 710\"SHUFFLE\n 660 D$(A) = D$(A) + P$\n 670 P$ = \"\"\n 680 RETURN\n\n REM SHUFFLE\n 700 PRINT \"SHUFFLING \";\n 710 N = LEN (P$)\n 720 FOR I = 1 TO N\n 730 IF I - INT (I / 4) * 4 = 1 THEN PRINT \".\";\n 740 R = INT ( RND (1) * N + 1)\n 750 R$ = MID$ (P$,R,1) : C$ = MID$ (P$,I,1)\n 760 P$ = MID$ (P$,1,I - 1) + R$ + MID$ (P$,I + 1)\n 770 P$ = MID$ (P$,1,R - 1) + C$ + MID$ (P$,R + 1)\n 780 NEXT\n 790 RETURN\n\n REM DRAW CARD\n 800 G = ASC (C$(I))\n 810 G(I) = INT (G / M) + 1\n 820 PRINT MID$ (FACE$,G(I),1) MID$ (SUIT$,G - (G(I) - 1) * M + 1,1)\" \";\n 830 D$(I) = MID$ (D$(I),2)\n 840 C = C + (G(I) = U)\n 850 IF G(I) > U THEN U = G(I):C = 1:A = I\n 860 RETURN\n\n REM IS GAME OVER?\n 900 C = 0\n 910 FOR I = 1 TO P\n 920 IF LEN (D$(I)) THEN A = I:C = C + 1\n 930 NEXT I\n 940 IF C > 1 THEN RETURN\n REM GAME OVER - WHO WON MESSAGE\n 950 Q = 1\n 960 IF C THEN PRINT \"PLAYER \"A\" WINS THE GAME\";: RETURN\n 970 PRINT \"GAME ENDS AS A TIE\";: RETURN\n", "language": "Applesoft-BASIC" }, { "code": "CLEAR : R = RND ( - 58) : GOTO 110\n", "language": "Applesoft-BASIC" }, { "code": "suits := [\"♠\", \"♦\", \"♥\", \"♣\"]\nfaces := [2,3,4,5,6,7,8,9,10,\"J\",\"Q\",\"K\",\"A\"]\ndeck := [], p1 := [], p2 := []\nfor i, s in suits\n\tfor j, v in faces\n\t\tdeck.Push(v s)\ndeck := shuffle(deck)\ndeal := deal(deck, p1, p2)\np1 := deal.1, p2 := deal.2\n\nfor i, v in p2\n{\n\tif InStr(v, \"A\")\n\t\tp2[i] := p1[i], p1[i] := v\n\tif InStr(v, \"K\")\n\t\tp2[i] := p1[i], p1[i] := v\n\tif InStr(v, \"Q\")\n\t\tp2[i] := p1[i], p1[i] := v\n\tif InStr(v, \"J\")\n\t\tp2[i] := p1[i], p1[i] := v\n}\nMsgBox % war(p1, p2)\nreturn\nwar(p1, p2){\n\tJ:=11, Q:=11, K:=11, A:=12, stack := [], cntr := 0\n\toutput := \"------------------------------------------\"\n\t\t\t. \"`nRound# \t Deal\t \t\tWinner\tP1\tP1\"\n\t\t\t. \"`n------------------------------------------\"\n\t\t\t. \"`nround0 \t\t\t \t\t\t\t26\t26\"\n\n\twhile (p1.Count() && p2.Count()) {\n\t\tcntr++\n\t\tstack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1))\n\t\tr1:=SubStr(c1,1,-1)\t,r2:=SubStr(c2,1,-1)\n\t\tv1:=r1<11?r1:%r1%\t,v2:=r2<11?r2:%r2%\n\t\toutput .= \"`nround# \" cntr \"`t\" SubStr(c1 \" n\", 1, 4) \"vs \" SubStr(c2 \" \", 1, 4)\n\t\tif (v1 > v2){\n\t\t\tloop % stack.Count()\n\t\t\t\tp1.Push(stack.RemoveAt(1))\n\t\t\toutput .= \"`t`tP1 wins\"\n\t\t}\n\t\telse if (v1 < v2){\n\t\t\tloop % stack.Count()\n\t\t\t\tp2.Push(stack.RemoveAt(1))\n\t\t\toutput .= \"`t`tP2 wins\"\n\t\t}\n\t\tif (v1 = v2){\n\t\t\toutput .= \"`t`t**WAR**`t\" P1.Count() \"`t\" P2.Count()\n\t\t\tstack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1))\n\t\t\tif !(p1.Count() && p2.Count())\n\t\t\t\tbreak\n\t\t\toutput .= \"`nround# \" ++cntr \"`t(\" SubStr(c1 \" \", 1, 3) \") - (\" SubStr(c2 \" \", 1, 3) \")\"\n\t\t\toutput .= \"`tFace Dn\"\n\t\t}\n\t\toutput .= \"`t\" P1.Count() \"`t\" P2.Count()\n\t\tif !Mod(cntr, 20)\n\t\t{\n\t\t\tMsgBox % output\n\t\t\toutput := \"\"\n\t\t}\n\t}\n\toutput .= \"`n\" (P1.Count() ? \"P1 Wins\" : \"P2 Wins\")\n\toutput := StrReplace(output, \" )\", \") \")\n\toutput := StrReplace(output, \" -\", \" -\")\n\treturn output\n", "language": "AutoHotkey" }, { "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nclass war_game {\npublic:\n\twar_game() {\n\t\tfor ( char suit : SUITS ) {\n\t\t\tfor ( char pip : PIPS ) {\n\t\t\t\tdeck.emplace_back(card(suit, pip));\n\t\t\t}\n\t\t}\n\t\tstd::random_shuffle(deck.begin(), deck.end());\n\n\t\thandA = { deck.begin(), deck.begin() + 26 };\n\t\thandB = { deck.begin() + 26, deck.end() };\n\t}\n\n\tvoid next_turn() {\n\t\tcard cardA = handA.front(); handA.erase(handA.begin());\n\t\tcard cardB = handB.front(); handB.erase(handB.begin());\n\t\ttabledCards.emplace_back(cardA);\n\t\ttabledCards.emplace_back(cardB);\n\t\tint32_t rankA = getRank(cardA.pip);\n\t\tint32_t rankB = getRank(cardB.pip);\n\t\tstd::cout << cardA.pip << cardA.suit << \" \" << cardB.pip << cardB.suit << std::endl;\n\n\t\tif ( rankA > rankB ) {\n\t\t\tstd::cout << \" Player A takes the cards\" << std::endl;\n\t\t\tstd::random_shuffle(tabledCards.begin(), tabledCards.end());\n\t\t\thandA.insert(handA.end(), tabledCards.begin(), tabledCards.end());\n\t\t\ttabledCards.clear();\n\t\t} else if ( rankA < rankB ) {\n\t\t\tstd::cout << \" Player B takes the cards\" << std::endl;\n\t\t\tstd::random_shuffle(tabledCards.begin(), tabledCards.end());\n\t\t\thandB.insert(handB.end(), tabledCards.begin(), tabledCards.end());;\n\t\t\ttabledCards.clear();\n\t\t} else {\n\t\t\tstd::cout << \" War!\" << std::endl;\n\t\t\tif ( game_over() ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcard cardAA = handA.front(); handA.erase(handA.begin());\n\t\t\tcard cardBB = handB.front(); handB.erase(handB.begin());\n\t\t\ttabledCards.emplace_back(cardAA);\n\t\t\ttabledCards.emplace_back(cardBB);\n\t\t\tstd::cout << \"? ? Cards are face down\" << std::endl;\n\t\t\tif ( game_over() ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tnext_turn();\n\t\t}\n\t}\n\n\tbool game_over() const {\n\t\treturn handA.size() == 0 || handB.size() == 0;\n\t}\n\n\tvoid declare_winner() const {\n\t\tif ( handA.size() == 0 && handB.size() == 0 ) {\n\t\t\tstd::cout << \"The game ended in a tie\" << std::endl;\n\t\t} else if ( handA.size() == 0 ) {\n\t\t\tstd::cout << \"Player B has won the game\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"Player A has won the game\" << std::endl;\n\t\t}\n\t}\nprivate:\n\tclass card {\n\tpublic:\n\t\tcard(const char suit, const char pip) : suit(suit), pip(pip) {};\n\t\tchar suit, pip;\n\t};\n\n\tint32_t getRank(const char ch)\tconst {\n\t auto it = find(PIPS.begin(), PIPS.end(), ch);\n\t if ( it != PIPS.end() ) {\n\t return it - PIPS.begin();\n\t }\n\t return -1;\n\t}\n\n\tstd::vector<card> deck, handA, handB, tabledCards;\n\tinline static const std::vector<char> PIPS = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };\n\tinline static const std::vector<char> SUITS = { 'C', 'D', 'H', 'S' };\n};\n\nint main() {\n\twar_game wargame;\n srand((unsigned) time(NULL));\n\twhile ( ! wargame.game_over() ) {\n\t\twargame.next_turn();\n\t}\n\n\twargame.declare_winner();\n}\n", "language": "C++" }, { "code": "Dim Shared As Integer stack(1, 51) ' each player's stack of cards (52 maximum)\nDim Shared As Integer inx(1) ' index to last card (+1) for each stack\nDim Shared As Integer carta\n\nSub MoveCard(hacia As Integer, desde As Integer) ' Move top card desde stack to bottom of To stack\n Dim As Integer i\n carta = stack(desde, 0) ' take top carta from desde stack\n For i = 0 To inx(desde) - 2 ' shift remaining cards over\n stack(desde, i) = stack(desde, i + 1)\n Next i\n If inx(desde) > 0 Then inx(desde) -= 1 ' remove desde card from its stack\n stack(hacia, inx(hacia)) = carta ' add carta to bottom of To stack\n If inx(hacia) < 52 Then inx(hacia) += 1 ' remove desde card from its stack\nEnd Sub\n\nDim As String suit = \"HDCS \"\nDim As String rank = \"23456789TJQKA \"\nDim As Integer top ' index to compared cards, = stack top if not war\nDim As Integer deck(51) ' initial card deck (low 2 bits = suit)\nFor carta = 0 To 51 ' make a complete deck of cards\n deck(carta) = carta\nNext carta\nDim As Integer n, i, j, p, t\n\nRandomize Timer\nFor n = 0 To 10000 ' shuffle the deck by swapping random locations\n i = Int(Rnd * 52): j = Int(Rnd * 52)\n Swap deck(i), deck(j)\nNext n\nFor n = 0 To 51 ' deal deck into two stacks\n carta = deck(n)\n i = n \\ 2\n p = n Mod 2\n stack(p, i) = carta\nNext n\ninx(0) = 52 \\ 2: inx(1) = 52 \\ 2 ' set indexes to last card +1\n\nDo\n For p = 0 To 1 ' show both stacks of cards\n For i = 0 To inx(p) - 1\n carta = stack(p, i)\n Print Left(rank, carta Shr 2);\n Next i\n Print\n For i = 0 To inx(p) - 1\n carta = stack(p, i)\n Print Mid(suit, (carta And 3) + 1, 1);\n Next i\n Print\n Next p\n If inx(0) = 0 Or inx(1) = 0 Then Exit Do ' game over\n\n top = 0 ' compare card ranks (above 2-bit suits)\n Do\n If (stack(0, top) Shr 2) = (stack(1, top) Shr 2) Then\n Color 3 : Print \"War!\" : Print : Color 7\n top += 2 ' play a card down and a card up\n Elseif (stack(0, top) Shr 2) > (stack(1, top) Shr 2) Then\n For i = 0 To top ' move cards to stack 0\n MoveCard(0, 0): MoveCard(0, 1)\n Next i\n Exit Do\n Else\n For i = 0 To top ' move cards to stack 1\n MoveCard(1, 1): MoveCard(1, 0)\n Next i\n Exit Do\n End If\n Loop\n Sleep 1000, 1\n Print\nLoop\n\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nvar suits = []string{\"♣\", \"♦\", \"♥\", \"♠\"}\nvar faces = []string{\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"}\nvar cards = make([]string, 52)\nvar ranks = make([]int, 52)\n\nfunc init() {\n for i := 0; i < 52; i++ {\n cards[i] = fmt.Sprintf(\"%s%s\", faces[i%13], suits[i/13])\n ranks[i] = i % 13\n }\n}\n\nfunc war() {\n deck := make([]int, 52)\n for i := 0; i < 52; i++ {\n deck[i] = i\n }\n rand.Shuffle(52, func(i, j int) {\n deck[i], deck[j] = deck[j], deck[i]\n })\n hand1 := make([]int, 26, 52)\n hand2 := make([]int, 26, 52)\n for i := 0; i < 26; i++ {\n hand1[25-i] = deck[2*i]\n hand2[25-i] = deck[2*i+1]\n }\n for len(hand1) > 0 && len(hand2) > 0 {\n card1 := hand1[0]\n copy(hand1[0:], hand1[1:])\n hand1[len(hand1)-1] = 0\n hand1 = hand1[0 : len(hand1)-1]\n card2 := hand2[0]\n copy(hand2[0:], hand2[1:])\n hand2[len(hand2)-1] = 0\n hand2 = hand2[0 : len(hand2)-1]\n played1 := []int{card1}\n played2 := []int{card2}\n numPlayed := 2\n for {\n fmt.Printf(\"%s\\t%s\\t\", cards[card1], cards[card2])\n if ranks[card1] > ranks[card2] {\n hand1 = append(hand1, played1...)\n hand1 = append(hand1, played2...)\n fmt.Printf(\"Player 1 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand1))\n break\n } else if ranks[card1] < ranks[card2] {\n hand2 = append(hand2, played2...)\n hand2 = append(hand2, played1...)\n fmt.Printf(\"Player 2 takes the %d cards. Now has %d.\\n\", numPlayed, len(hand2))\n break\n } else {\n fmt.Println(\"War!\")\n if len(hand1) < 2 {\n fmt.Println(\"Player 1 has insufficient cards left.\")\n hand2 = append(hand2, played2...)\n hand2 = append(hand2, played1...)\n hand2 = append(hand2, hand1...)\n hand1 = hand1[0:0]\n break\n }\n if len(hand2) < 2 {\n fmt.Println(\"Player 2 has insufficient cards left.\")\n hand1 = append(hand1, played1...)\n hand1 = append(hand1, played2...)\n hand1 = append(hand1, hand2...)\n hand2 = hand2[0:0]\n break\n }\n fdCard1 := hand1[0] // face down card\n card1 = hand1[1] // face up card\n copy(hand1[0:], hand1[2:])\n hand1[len(hand1)-1] = 0\n hand1[len(hand1)-2] = 0\n hand1 = hand1[0 : len(hand1)-2]\n played1 = append(played1, fdCard1, card1)\n fdCard2 := hand2[0] // face down card\n card2 = hand2[1] // face up card\n copy(hand2[0:], hand2[2:])\n hand2[len(hand2)-1] = 0\n hand2[len(hand2)-2] = 0\n hand2 = hand2[0 : len(hand2)-2]\n played2 = append(played2, fdCard2, card2)\n numPlayed += 4\n fmt.Println(\"? \\t? \\tFace down cards.\")\n }\n }\n }\n if len(hand1) == 52 {\n fmt.Println(\"Player 1 wins the game!\")\n } else {\n fmt.Println(\"Player 2 wins the game!\")\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n war()\n}\n", "language": "Go" }, { "code": "DECK=: '2 3 4 5 6 7 8 9 10 J K Q A' (,' of ',])&.>/&cut '♣ ♦ ♥ ♠'\nrank=: DECK {{ {.\"1 ($m)#:(,m) i. y }}\nshuffle=: {~ ?~@#\ndeal=: _26 ]\\ shuffle@,@DECK\ncardwar=: {{\n TURNS=: 0\n 'P1 P2'=: <each deal''\n while. 0<P1 *&# P2 do. turn TURNS=: TURNS+1 end.\n after=. ' after ',TURNS,&\":' turn','s'#~1~:TURNS\n if. #P1 do. 'Player 1 wins', after\n elseif. #P2 do. 'Player 2 wins', after\n else. 'Tie',after end.\n}}\nplays=: {{ ((m)=: }.\".m)](echo n,~(m,' plays '),;'nothing'&[^:(0=#@]){.\".m)]({.\".m) }}\nturn=: {{\n c=. (b=. 'P2' plays''),(a =. 'P1' plays'')\n while. a =&rank b do.\n if. 0=P1 *&# P2 do. echo 'No more cards to draw' return. end.\n c=. c, (a=. 'P1' plays''),(b =. 'P2' plays''), 'P1' plays' face down', 'P2' plays' face down'\n end.\n ('P',\":1+a <&rank b) takes ({~ ?~@#)c-.a:\n}}\ntakes=: {{\n (m)=: (\".m),y\n echo m,' takes ',;(<' and ') _2}}.,(<', '),.y\n echo''\n}}\n", "language": "J" }, { "code": " cardwar''\nP1 plays 6 of ♦\nP2 plays 9 of ♥\nP2 takes 6 of ♦ and 9 of ♥\n\nP1 plays K of ♣\nP2 plays 6 of ♣\nP1 takes K of ♣ and 6 of ♣\n\nP1 plays A of ♦\nP2 plays A of ♥\nP2 plays 5 of ♠ face down\nP1 plays J of ♥ face down\nP2 plays 2 of ♣\nP1 plays J of ♦\nP1 takes A of ♥, J of ♥, A of ♦, 2 of ♣, 5 of ♠ and J of ♦\n\nP1 plays 7 of ♥\nP2 plays 10 of ♣\nP2 takes 10 of ♣ and 7 of ♥\n\n(... many lines deleted ...)\n\nP1 plays 2 of ♦\nP2 plays 5 of ♥\nP2 takes 2 of ♦ and 5 of ♥\n\nP1 plays K of ♥\nP2 plays 4 of ♥\nP1 takes 4 of ♥ and K of ♥\n\nP1 plays 3 of ♦\nP2 plays 3 of ♣\nP2 plays 2 of ♦ face down\nP1 plays 6 of ♠ face down\nP2 plays 5 of ♥\nP1 plays K of ♠\nP1 takes 6 of ♠, K of ♠, 5 of ♥, 3 of ♣, 3 of ♦ and 2 of ♦\n\nPlayer 1 wins after 86 turns\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic final class WarCardGame {\n\n\tpublic static void main(String[] args) {\n\t\tWarGame warGame = new WarGame();\n\t\t\n\t\twhile ( ! warGame.gameOver() ) {\n\t\t\twarGame.nextTurn();\n\t\t}\n\t\t\n\t\twarGame.declareWinner();\n\t}\t\n\t\n}\n\nfinal class WarGame {\n\t\n\tpublic WarGame() {\n\t\tdeck = new ArrayList<Card>(52);\t\n for ( Character suit : SUITS ) {\n for ( Character pip : PIPS ) {\n deck.add( new Card(suit, pip) );\n }\n }\n Collections.shuffle(deck);\n\n handA = new ArrayList<Card>(deck.subList(0, 26));\n handB = new ArrayList<Card>(deck.subList(26, 52));\n tabledCards = new ArrayList<Card>();\n\t}\n\t\n\tpublic void nextTurn() {\n\t\tCard cardA = handA.remove(0);\n\t\tCard cardB = handB.remove(0);\n\t\ttabledCards.add(cardA);\n\t\ttabledCards.add(cardB);\n\t\tint rankA = PIPS.indexOf(cardA.pip);\n\t\tint rankB = PIPS.indexOf(cardB.pip);\n\t\t\n\t\tSystem.out.print(cardA + \" \" + cardB);\n\t\tif ( rankA > rankB ) {\n System.out.println(\" Player A takes the cards\");\n Collections.shuffle(tabledCards);\n handA.addAll(tabledCards);\n tabledCards.clear();\n\t\t} else if ( rankA < rankB ) {\n System.out.println(\" Player B takes the cards\");\n Collections.shuffle(tabledCards);\n handB.addAll(tabledCards);\n tabledCards.clear();\n\t\t} else {\n\t System.out.println(\" War!\");\n if ( gameOver() ) {\n return;\n }\n\n Card cardAA = handA.remove(0);\n Card cardBB = handB.remove(0);\n tabledCards.add(cardAA);\n \t\ttabledCards.add(cardBB);\n \t\tSystem.out.println(\"? ? Cards are face down\"); \t\t\n \t\tif ( gameOver() ) {\n return;\n }\n \t\t\n nextTurn();\n\t\t}\n\t}\n\t\n\tpublic boolean gameOver() {\n\t\treturn handA.size() == 0 || handB.size() == 0;\n\t}\n\n public void declareWinner() { \t\n if ( handA.size() == 0 && handB.size() == 0 ) {\n \tSystem.out.println(\"The game ended in a tie\");\n } else if ( handA.size() == 0 ) {\n \tSystem.out.println(\"Player B has won the game\");\n } else {\n System.out.println(\"Player A has won the game\");\n }\n }\n\n private record Card(Character suit, Character pip) {\n \t\n \t@Override\n \tpublic String toString() {\n \t\treturn \"\" + pip + suit;\n \t}\n \t\n }\n\t\n\tprivate List<Card> deck, handA, handB, tabledCards;\n\t\n\tprivate static final List<Character> PIPS =\n\t\tArrays.asList( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );\n\tprivate static final List<Character> SUITS = List.of( 'C', 'D', 'H', 'S' );\n\t\n}\n", "language": "Java" }, { "code": "# https://bicyclecards.com/how-to-play/war/\n\nusing Random\n\nconst SUITS = [\"♣\", \"♦\", \"♥\", \"♠\"]\nconst FACES = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\", \"A\" ]\nconst DECK = vec([f * s for s in SUITS, f in FACES])\nconst rdict = Dict(DECK[i] => div(i + 3, 4) for i in eachindex(DECK))\n\ndeal2(deck) = begin d = shuffle(deck); d[1:2:51], d[2:2:52] end\n\nfunction turn!(d1, d2, pending)\n (isempty(d1) || isempty(d2)) && return false\n c1, c2 = popfirst!(d1), popfirst!(d2)\n r1, r2 = rdict[c1], rdict[c2]\n print(rpad(c1, 10), rpad(c2, 10))\n if r1 > r2\n println(\"Player 1 takes the cards.\")\n push!(d1, c1, c2, pending...)\n empty!(pending)\n elseif r1 < r2\n println(\"Player 2 takes the cards.\")\n push!(d2, c2, c1, pending...)\n empty!(pending)\n else # r1 == r2\n println(\"Tie!\")\n (isempty(d1) || isempty(d2)) && return false\n c3, c4 = popfirst!(d1), popfirst!(d2)\n println(rpad(\"?\", 10), rpad(\"?\", 10), \"Cards are face down.\")\n return turn!(d1, d2, push!(pending, c1, c2, c3, c4))\n end\n return true\nend\n\nfunction warcardgame()\n deck1, deck2 = deal2(DECK)\n while turn!(deck1, deck2, []) end\n if isempty(deck2)\n if isempty(deck1)\n println(\"Game ends as a tie.\")\n else\n println(\"Player 1 wins the game.\")\n end\n else\n println(\"Player 2 wins the game.\")\n end\nend\n\nwarcardgame()\n", "language": "Julia" }, { "code": "-- main.lua\nfunction newGame ()\n\t-- new deck\n\tlocal deck = {}\n\tfor iSuit = 1, #CardSuits do\n\t\tfor iRank = 1, #CardRanks do\n\t\t\tlocal card = {\n\t\t\t\tiSuit = iSuit,\n\t\t\t\tiRank = iRank,\n\t\t\t\tsuit = CardSuits[iSuit],\n\t\t\t\trank = iRank,\n\t\t\t\tname = CardRanks[iRank] .. CardSuits[iSuit]\n\t\t\t}\n\t\t\tlocal i = math.random (#deck + 1)\n\t\t\ttable.insert (deck, i, card)\n\t\tend\n\tend\n\t\n\t-- new deal\n\tPlayers = {\n\t\t{index = 1, cards = {}},\n\t\t{index = 2, cards = {}},\n\t}\n\tfor i = 1, #deck/#Players do\n\t\tfor iPlayer = 1, #Players do\n\t\t\ttable.insert (Players[iPlayer].cards, table.remove(deck))\n\t\tend\n\tend\n\tWarCards = {}\n\tTurn = 1\n\tStatistics = {}\nend\n\nfunction getHigherCard (cardA, cardB)\n\tif cardA.rank > cardB.rank then\n\t\treturn cardA, 1\n\telseif cardA.rank < cardB.rank then\n\t\treturn cardB, 2\n\telse\n\t\treturn nil\n\tend\nend\n\nfunction love.load()\n\t-- there is no card suits in the standard font\n\tCardSuits = {\"@\", \"#\", \"$\", \"%\"}\n\tCardRanks = {\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"V\", \"Q\", \"K\", \"A\"}\n\t\n\tnewGame ()\nend\n\nfunction love.draw()\n\tfor iPlayer = 1, #Players do\n\t\tlocal player = Players[iPlayer]\n\t\tlove.graphics.print ('Player '..player.index, 50*(iPlayer-1), 0)\n\t\tfor iCard, card in ipairs (player.cards) do\n\t\t\tlove.graphics.print (card.name, 50*(iPlayer-1), 14*iCard)\n\t\tend\n\tend\n\tfor i = 1, math.min(40, #Statistics) do\n\t\tlocal str = Statistics[i]\n\t\tlove.graphics.print (str, 150, 20+(i-1)*14)\n\tend\n\t\nend\n\nfunction makeTurn ()\n\tlocal card1 = table.remove (Players[1].cards)\n\tlocal card2 = table.remove (Players[2].cards)\n\tif card1 and card2 then\n\t\ttable.insert (WarCards, 1, card1)\n\t\ttable.insert (WarCards, math.random (1, 2), card2)\n\t\tlocal winCard, index = getHigherCard (card1, card2)\n\t\tif winCard then\n\t\t\ttable.insert (Statistics, 1, Turn .. '\tPlayer ' .. index .. ' get ' .. #WarCards .. ' cards: ' .. card1.name .. ' vs ' .. card2.name)\n\t\t\t\n\t\t\tfor iCard = #WarCards, 1, -1 do\n\t\t\t\ttable.insert (Players[index].cards, 1, table.remove (WarCards))\n\t\t\tend\n\t\telseif (#Players[1].cards > 0) and (#Players[2].cards > 0) then\n\t\t-- start war\n\t\t\ttable.insert (Statistics, 1, Turn .. '\tWar: ' .. card1.name .. ' vs ' .. card2.name)\n\t\t\ttable.insert (WarCards, table.remove (Players[1].cards))\n\t\t\ttable.insert (WarCards, table.remove (Players[2].cards))\n\t\telse\n\t\t\tlocal index = 2\n\t\t\tif #Players[1].cards == 0 then index = 1 end\n\t\t\ttable.insert (Statistics, 1, Turn .. '\tPlayer ' .. index .. ' has no cards for this war.')\n--\t\t\tGameOver = true\n\t\tend\n\t\tTurn = Turn + 1\n\telseif GameOver then\n\t\tGameOver = false\n\t\tnewGame ()\n\telse\n\t\tlocal index = 2\n\t\tif #Players[1].cards > #Players[2].cards then index = 1 end\n\t\ttable.insert (Statistics, 1, Turn .. '\tPlayer ' .. index .. ' wins the game!')\n\t\tGameOver = true\n\tend\nend\n\nfunction love.keypressed(key, scancode, isrepeat)\n\tif false then\n\telseif key == \"space\" then\n\t\tmakeTurn ()\n\telseif scancode == \"n\" then\n\t\tGameOver = false\n\t\tnewGame ()\n\telseif scancode == \"q\" then\n\t\tlocal lastTurn = Turn\n\t\twhile not (GameOver or (Turn > lastTurn + 10000-1)) do\n\t\t\tmakeTurn ()\n\t\tend\n\telseif key == \"escape\" then\n\t\tlove.event.quit()\n\tend\n\tif #Statistics > 40 then\n\t\tlocal i = #Statistics, 40, -1 do\n\t\t\ttable.remove (Statistics, i)\n\t\tend\n\tend\nend\n\nfunction love.mousepressed( x, y, button, istouch, presses )\n\tif button == 1 then -- left mouse button\n\t\tmakeTurn ()\n\telseif button == 2 then -- right mouse button\n\tend\nend\n", "language": "Lua" }, { "code": "import strformat\nimport playing_cards\n\nconst\n None = -1\n Player1 = 0\n Player2 = 1\n\ntype Player = range[None..Player2]\n\nconst PlayerNames: array[Player1..Player2, string] = [\"Player 1\", \"Player 2\"]\n\n#---------------------------------------------------------------------------------------------------\n\nproc `<`(a, b: Card): bool =\n ## Compare two cards by their rank, Ace being the greatest.\n if a.rank == Ace: false\n elif b.rank == Ace: true\n else: a.rank < b.rank\n\n#---------------------------------------------------------------------------------------------------\n\nproc displayRound(round: int; hands: openArray[Hand]; card1, card2: string; text: string) =\n ## Display text for a round.\n stdout.write &\"Round {round:<4} \"\n stdout.write &\"Cards: {hands[Player1].len:>2}/{hands[Player2].len:<2} \"\n stdout.write &\"{card1:>3} {card2:>3} \"\n echo text\n\n#---------------------------------------------------------------------------------------------------\n\nproc outOfCards(player: Player) =\n ## Display a message when a player has run out of cards.\n echo &\"{PlayerNames[player]} has run out of cards.\"\n\n#---------------------------------------------------------------------------------------------------\n\nproc doRound(hands: var openArray[Hand]; num: Positive) =\n ## Execute a round.\n\n var stack1, stack2: seq[Card]\n var winner: Player = None\n\n while winner == None:\n let card1 = hands[Player1].draw()\n let card2 = hands[Player2].draw()\n stack1.add card1\n stack2.add card2\n if card1.rank != card2.rank:\n winner = if card1 < card2: Player2 else: Player1\n displayRound(num, hands, $card1, $card2, &\"{PlayerNames[winner]} takes the cards.\")\n else:\n # There is a war.\n displayRound(num, hands, $card1, $card2, \"This is a war.\")\n if hands[Player1].len == 0:\n winner = Player2\n elif hands[Player2].len == 0:\n winner = Player1\n else:\n # Add a hidden card on stacks.\n stack1.add hands[Player1].draw()\n stack2.add hands[Player2].draw()\n displayRound(num, hands, \" ?\", \" ?\", \"Cards are face down.\")\n # Check if each player has enough cards to continue the war.\n if hands[Player1].len == 0:\n Player1.outOfCards()\n winner = Player2\n elif hands[Player2].len == 0:\n Player2.outOfCards()\n winner = Player1\n\n # Update hands.\n var stack = stack1 & stack2\n stack.shuffle()\n hands[winner] = stack & hands[winner]\n\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nvar deck = initDeck()\ndeck.shuffle()\n\nvar hands = deck.deal(2, 26)\nvar num = 0\nwhile true:\n inc num\n hands.doRound(num)\n if hands[Player1].len == 0:\n echo \"Player 2 wins this game.\"\n break\n if hands[Player2].len == 0:\n echo \"Player 1 wins this game.\"\n break\n", "language": "Nim" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/War_Card_Game\nuse warnings;\nuse List::Util qw( shuffle );\n\nmy %rank;\n@rank{ 2 .. 9, qw(t j q k a) } = 1 .. 13; # for winner\nlocal $_ = join '', shuffle\n map { my $f = $_; map $f.$_, qw( S H C D ) } 2 .. 9, qw( a t j q k );\nsubstr $_, 52, 0, \"\\n\"; # split deck into two parts\nmy $war = '';\nmy $cnt = 0;\n$cnt++ while print( /(.*)\\n(.*)/ && \"one: $1\\ntwo: $2\\n\\n\" ),\n s/^((.).)(.*)\\n((?!\\2)(.).)(.*)$/ my $win = $war; $war = ''; # capture\n $rank{$2} > $rank{$5} ? \"$3$1$4$win\\n$6\" : \"$3\\n$6$4$1$win\" /e\n ||\n s/^(.{4})(.*)\\n(.{4})(.*)$/ print \"WAR!!!\\n\\n\"; $war .= \"$1$3\";\n \"$2\\n$4\" /e; # tie means war\nprint \"player '\", /^.{10}/ ? 'one' : 'two', \"' wins in $cnt moves\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">deck</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">hand1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">deck</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">26</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">hand2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">deck</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">27</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">52</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">pending</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">pop1</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">hand1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">hand1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">hand1</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">pop2</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]}</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">13</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"23456789TJQKA\"</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #008000;\">\"SHDC\"</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hand1</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Game ends as a tie.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Player 2 wins the game.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Player 1 wins the game.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pop1</span><span style=\"color: #0000FF;\">(),</span>\n <span style=\"color: #000000;\">c2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pop2</span><span style=\"color: #0000FF;\">(),</span>\n <span style=\"color: #000000;\">r1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">r2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">show</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">r1</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">r2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Player 1 takes the cards.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">hand1</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">pending</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pending</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">r1</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">r2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Player 2 takes the cards.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">hand2</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">pending</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">pending</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000080;font-style:italic;\">-- r1==r2</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Tie!\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hand1</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hand2</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">pending</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c1</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">pop1</span><span style=\"color: #0000FF;\">()&</span><span style=\"color: #000000;\">pop2</span><span style=\"color: #0000FF;\">())</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"?? ?? Cards are face down.\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n<!--\n", "language": "Phix" }, { "code": "\"\"\" https://bicyclecards.com/how-to-play/war/ \"\"\"\n\nfrom numpy.random import shuffle\n\nSUITS = ['♣', '♦', '♥', '♠']\nFACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\nDECK = [f + s for f in FACES for s in SUITS]\nCARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))\n\n\nclass WarCardGame:\n \"\"\" card game War \"\"\"\n def __init__(self):\n deck = DECK.copy()\n shuffle(deck)\n self.deck1, self.deck2 = deck[:26], deck[26:]\n self.pending = []\n\n def turn(self):\n \"\"\" one turn, may recurse on tie \"\"\"\n if len(self.deck1) == 0 or len(self.deck2) == 0:\n return self.gameover()\n\n card1, card2 = self.deck1.pop(0), self.deck2.pop(0)\n rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]\n print(\"{:10}{:10}\".format(card1, card2), end='')\n if rank1 > rank2:\n print('Player 1 takes the cards.')\n self.deck1.extend([card1, card2])\n self.deck1.extend(self.pending)\n self.pending = []\n elif rank1 < rank2:\n print('Player 2 takes the cards.')\n self.deck2.extend([card2, card1])\n self.deck2.extend(self.pending)\n self.pending = []\n else: # rank1 == rank2\n print('Tie!')\n if len(self.deck1) == 0 or len(self.deck2) == 0:\n return self.gameover()\n\n card3, card4 = self.deck1.pop(0), self.deck2.pop(0)\n self.pending.extend([card1, card2, card3, card4])\n print(\"{:10}{:10}\".format(\"?\", \"?\"), 'Cards are face down.', sep='')\n return self.turn()\n\n return True\n\n def gameover(self):\n \"\"\" game over who won message \"\"\"\n if len(self.deck2) == 0:\n if len(self.deck1) == 0:\n print('\\nGame ends as a tie.')\n else:\n print('\\nPlayer 1 wins the game.')\n else:\n print('\\nPlayer 2 wins the game.')\n\n return False\n\n\nif __name__ == '__main__':\n WG = WarCardGame()\n while WG.turn():\n continue\n", "language": "Python" }, { "code": "#lang racket\n\n(define current-battle-length (make-parameter 3))\n\n(define cards (string->list (string-append \"🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂭🂮🂡\" \"🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂽🂾🂱\"\n \"🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃍🃎🃁\" \"🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃝🃞🃑\")))\n\n(define face (curry hash-ref (for/hash ((c cards) (i (in-naturals))) (values c (+ 2 (modulo i 13))))))\n\n(define (print-draw-result turn-number d1 c1 d2 c2 → (pending null))\n (printf \"#~a\\t~a ~a ~a\\t~a|~a|~a~%\" turn-number c1 → c2 (length d1) (length pending)(length d2)))\n\n(define (turn d1 d2 (n 1) (pending null) (battle 0))\n (match* (d1 d2)\n [('() '()) \"Game ends in a tie!\"]\n [(_ '()) \"Player 1 wins.\"]\n [('() _) \"Player 2 wins.\"]\n [((list c3 d1- ...) (list c4 d2- ...))\n #:when (positive? battle)\n (define pending+ (list* c3 c4 pending))\n (print-draw-result n d1- \"🂠\" d2- \"🂠\" \"?\" pending+)\n (turn d1- d2- (add1 n) pending+ (sub1 battle))]\n [((list (and c1 (app face r)) d1- ...) (list (and c2 (app face r)) d2- ...))\n (define pending+ (list* c1 c2 pending))\n (print-draw-result n d1- c1 d2- c2 #\\= pending+)\n (turn d1- d2- (add1 n) pending+ (current-battle-length))]\n [((list (and c1 (app face r1)) d1- ...) (list (and c2 (app face r2)) d2- ...))\n (define spoils (shuffle (list* c1 c2 pending)))\n (define p1-win? (> r1 r2))\n (define d1+ (if p1-win? (append d1- spoils) d1-))\n (define d2+ (if p1-win? d2- (append d2- spoils)))\n (print-draw-result n d1+ c1 d2+ c2 (if p1-win? \"←\" \"→\"))\n (turn d1+ d2+ (add1 n))]))\n\n(define (war-card-game)\n (call-with-values (λ () (split-at (shuffle cards) (quotient (length cards) 2)))\n turn))\n\n(displayln (war-card-game))\n", "language": "Racket" }, { "code": "unit sub MAIN (:$war where 2..4 = 4, :$sleep = .1);\n\nmy %c = ( # convenience hash of ANSI colors\n red => \"\\e[38;2;255;10;0m\",\n blue => \"\\e[38;2;05;10;200m\",\n black => \"\\e[38;2;0;0;0m\"\n);\n\nmy @cards = flat (flat\n <🂢 🂣 🂤 🂥 🂦 🂧 🂨 🂩 🂪 🂫 🂭 🂮 🂡\n 🃒 🃓 🃔 🃕 🃖 🃗 🃘 🃙 🃚 🃛 🃝 🃞 🃑>.map({ \"{%c<black>}$_\" }),\n <🂲 🂳 🂴 🂵 🂶 🂷 🂸 🂹 🂺 🂻 🂽 🂾 🂱\n 🃂 🃃 🃄 🃅 🃆 🃇 🃈 🃉 🃊 🃋 🃍 🃎 🃁>.map({ \"{%c<red>}$_\" })\n).batch(13).map({ .flat Z 2..14 })».map: { .[1] but .[0] };\n\nmy $back = \"{%c<blue>}🂠\";\nmy @won = <👈 👉>;\n\nsub shuffle (@cards) { @cards.pick: * }\nsub deal (@cards) { [@cards[0,*+2 … *], @cards[1,*+2 … *]] }\n\nmy ($rows, $cols) = qx/stty size/.words».Int; # get the terminal size\nnote \"Terminal is only $cols characters wide, needs to be at least 80, 120 or more recommended.\"\n and exit if $cols < 80;\n\nsub clean-up {\n reset-scroll-region;\n show-cursor;\n print-at $rows, 1, '';\n print \"\\e[0m\";\n exit(0)\n}\n\nsignal(SIGINT).tap: { clean-up() }\n\nmy @index = ($cols div 2 - 5, $cols div 2 + 4);\nmy @player = (deal shuffle @cards)».Array;\nmy $lose = False;\n\nsub take (@player, Int $cards) {\n if +@player >= $cards {\n return @player.splice(0, $cards);\n }\n else {\n $lose = True;\n return @player.splice(0, +@player);\n }\n}\n\nuse Terminal::ANSI;\n\nclear-screen;\nhide-cursor;\n# Set background color\nprint \"\\e[H\\e[J\\e[48;2;245;245;245m\", ' ' xx $rows * $cols + 1;\n\n# Add header\nprint-at 1, $cols div 2 - 1, \"{%c<red>}WAR!\";\nprint-at 2, 1, '━' x $cols;\n\nmy $row = 3;\nmy $height = $rows - $row - 2;\nset-scroll-region($row, $height);\n\n# footer\nprint-at $height + 1, 1, '━' x $cols;\n\nmy $round = 0;\nmy @round;\n\nloop {\n @round = [@player[0].&take(1)], [@player[1].&take(1)] unless +@round;\n print-at $row, $cols div 2, \"{%c<red>}┃\";\n print-at $row, @index[0], @round[0;0] // ' ';\n print-at $row, @index[1], @round[1;0] // ' ';\n if $lose {\n if @player[0] < @player[1] {\n print-at $row, $cols div 2 + 1, @won[1] unless +@round[1] == 1;\n print-at $height + 3, $cols div 2 - 10, \"{%c<red>} Player 1 is out of cards \"\n } else {\n print-at $row, $cols div 2 - 2, @won[0] unless +@round[0] == 1;\n print-at $height + 3, $cols div 2 - 10, \"{%c<red>} Player 2 is out of cards \"\n }\n\n }\n if (@round[0].tail // 0) > (@round[1].tail // 0) {\n print-at $row, $cols div 2 - 2, @won[0];\n @player[0].append: flat (|@round[0],|@round[1]).pick: *;\n @round = ();\n }\n elsif (@round[0].tail // 0) < (@round[1].tail // 0) {\n print-at $row, $cols div 2 + 1, @won[1];\n @player[1].append: flat (|@round[0],|@round[1]).pick: *;\n @round = ();\n }\n else {\n @round[0].append: @player[0].&take($war);\n @round[1].append: @player[1].&take($war);\n print-at $row, @index[0] - $_ * 2, ($_ %% $war) ?? @round[0; $_] !! $back for ^@round[0];\n print-at $row, @index[1] + $_ * 2, ($_ %% $war) ?? @round[1; $_] !! $back for ^@round[1];\n next\n }\n last if $lose;\n print-at $height + 2, $cols div 2 - 4, \"{%c<blue>} Round {++$round} \";\n print-at $height + 2, $cols div 2 - 40, \"{%c<blue>} Player 1: {+@player[0]} cards \";\n print-at $height + 2, $cols div 2 + 21, \"{%c<blue>} Player 2: {+@player[1]} cards \";\n sleep $sleep if +$sleep;\n if $row >= $height { scroll-up } else { ++$row }\n}\n\n# game over\nprint-at $height + 2, $cols div 2 - 40, \"{%c<blue>} Player 1: {+@player[0] ?? '52' !! \"{%c<red>}0\"}{%c<blue>} cards \";\nprint-at $height + 2, $cols div 2 + 20, \"{%c<blue>} Player 2: {+@player[1] ?? '52' !! \"{%c<red>}0\"}{%c<blue>} cards \";\nclean-up;\n", "language": "Raku" }, { "code": "import \"random\" for Random\nimport \"./queue\" for Deque\n\nvar rand = Random.new()\nvar suits = [\"♣\", \"♦\", \"♥\", \"♠\"]\nvar faces = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\" ]\nvar cards = List.filled(52, null)\nfor (i in 0..51) cards[i] = \"%(faces[i%13])%(suits[(i/13).floor])\"\nvar ranks = List.filled(52, 0)\nfor (i in 0..51) ranks[i] = i % 13\n\nvar war = Fn.new {\n var deck = List.filled(52, 0)\n for (i in 0..51) deck[i] = i\n rand.shuffle(deck)\n var hand1 = Deque.new()\n var hand2 = Deque.new()\n for (i in 0..25) {\n hand1.pushFront(deck[2*i])\n hand2.pushFront(deck[2*i+1])\n }\n while (hand1.count > 0 && hand2.count > 0) {\n var card1 = hand1.popFront()\n var card2 = hand2.popFront()\n var played1 = [card1]\n var played2 = [card2]\n var numPlayed = 2\n while (true) {\n System.write(\"%(cards[card1])\\t%(cards[card2])\\t\")\n if (ranks[card1] > ranks[card2]) {\n hand1.pushAllBack(played1)\n hand1.pushAllBack(played2)\n System.print(\"Player 1 takes the %(numPlayed) cards. Now has %(hand1.count).\")\n break\n } else if (ranks[card1] < ranks[card2]) {\n hand2.pushAllBack(played2)\n hand2.pushAllBack(played1)\n System.print(\"Player 2 takes the %(numPlayed) cards. Now has %(hand2.count).\")\n break\n } else {\n System.print(\"War!\")\n if (hand1.count < 2) {\n System.print(\"Player 1 has insufficient cards left.\")\n hand2.pushAllBack(played2)\n hand2.pushAllBack(played1)\n hand2.pushAllBack(hand1)\n hand1.clear()\n break\n }\n if (hand2.count < 2) {\n System.print(\"Player 2 has insufficient cards left.\")\n hand1.pushAllBack(played1)\n hand1.pushAllBack(played2)\n hand1.pushAllBack(hand2)\n hand2.clear()\n break\n }\n played1.add(hand1.popFront()) // face down card\n card1 = hand1.popFront() // face up card\n played1.add(card1)\n played2.add(hand2.popFront()) // face down card\n card2 = hand2.popFront() // face up card\n played2.add(card2)\n numPlayed = numPlayed + 4\n System.print(\"? \\t? \\tFace down cards.\")\n }\n }\n }\n if (hand1.count == 52) {\n System.print(\"Player 1 wins the game!\")\n } else {\n System.print(\"Player 2 wins the game!\")\n }\n}\n\nwar.call()\n", "language": "Wren" }, { "code": "char Deck(52), \\initial card deck (low 2 bits = suit)\n Stack(2, 52); \\each player's stack of cards (52 maximum)\nint Inx(2), \\index to last card (+1) for each stack\n Top, \\index to compared cards, = stack top if not war\n Card, N, I, J, P, T;\nchar Suit, Rank;\n\nproc MoveCard(To, From); \\Move top card From Stack to bottom of To Stack\nint To, From;\nint Card, I;\n[Card:= Stack(From, 0); \\take top Card from From Stack\nfor I:= 0 to Inx(From)-2 do \\shift remaining cards over\n Stack(From, I):= Stack(From, I+1);\nif Inx(From) > 0 then \\remove From card from its Stack\n Inx(From):= Inx(From)-1;\nStack(To, Inx(To)):= Card; \\add Card to bottom of To Stack\nif Inx(To) < 52 then \\remove From card from its Stack\n Inx(To):= Inx(To)+1;\n];\n\n[\\\\Suit:= \"^C^D^E^F \"; \\IBM OEM card symbols aren't displayable on RC\nSuit:= \"HDCS \";\nRank:= \"23456789TJQKA \"; \\T = 10\nfor Card:= 0 to 52-1 do \\make a complete deck of cards\n Deck(Card):= Card;\nfor N:= 0 to 10_000 do \\shuffle the deck by swapping random locations\n [I:= Ran(52); J:= Ran(52);\n T:= Deck(I); Deck(I):= Deck(J); Deck(J):= T;\n ];\nfor N:= 0 to 52-1 do \\deal deck into two stacks\n [Card:= Deck(N);\n I:= N/2;\n P:= rem(0);\n Stack(P, I):= Card;\n ];\nInx(0):= 52/2; Inx(1):= 52/2; \\set indexes to last card +1\n\nloop [for P:= 0 to 1 do \\show both stacks of cards\n [for I:= 0 to Inx(P)-1 do\n [Card:= Stack(P, I); ChOut(0, Rank(Card>>2))];\n CrLf(0);\n for I:= 0 to Inx(P)-1 do\n [Card:= Stack(P, I); ChOut(0, Suit(Card&3))];\n CrLf(0);\n ];\n if Inx(0)=0 or Inx(1)=0 then quit; \\game over\n\n Top:= 0; \\compare card ranks (above 2-bit suits)\n loop [if Stack(0, Top)>>2 = Stack(1, Top)>>2 then\n [Text(0, \"War!\"); CrLf(0);\n Top:= Top+2; \\play a card down and a card up\n ]\n else if Stack(0, Top)>>2 > Stack(1, Top)>>2 then\n [for I:= 0 to Top do \\move cards to Stack 0\n [MoveCard(0, 0); MoveCard(0, 1)];\n quit;\n ]\n else [for I:= 0 to Top do \\move cards to Stack 1\n [MoveCard(1, 1); MoveCard(1, 0)];\n quit;\n ];\n ];\n T:= ChIn(1); \\wait for keystroke (no key echo)\n CrLf(0);\n ];\n]\n]\n", "language": "XPL0" } ]
War-card-game
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Wasteful,_equidigital_and_frugal_numbers\n", "language": "00-META" }, { "code": ";Definitions\nLet '''n''' be a positive integer and '''l(n)''' be the number of its digits in base '''b'''.\n\nExpress '''n''' as the product of its prime factors raised to the appropriate powers. Let '''D(n)''' be the total number of its base '''b''' digits in all its prime factors and in all their exponents that are greater than 1.\n\nThen '''n''' is defined to be:\n\n1. a [[wp:Extravagant_number|'''wasteful''' (or '''extravagant''')]] number if l(n) '''<''' D(n); or\n\n2. an [[wp:Equidigital_number|'''equidigital''']] number if l(n) '''=''' D(n); or\n\n3. a [[wp:Frugal_number|'''frugal''' (or '''economical''')]] number if l(n) '''>''' D(n)\n\nin base '''b'''.\n\nBy convention, the number '''1''' is considered to be an '''equidigital''' number in '''any''' base even though it has no prime factors.\n\nFor the avoidance of any doubt, the number '''0''' is not a positive integer (and arguably not a [[wp:Natural_number|''natural number'']] either) and so is excluded from all 3 categories.\n\nAn '''economical''' number is sometimes defined as being one for which l(n) '''>=''' D(n) though this usage won't be followed here.\n\n\n;Examples\n\nIn base 10, the number 30 has a prime factorization of 2 x 3 x 5. The total number of digits is 3 (all exponents being 1) which is more than the 2 digits 30 has. So 30 is wasteful in base 10.\n\nIn base 10, the number 49 has a prime factorization of 7². The total number of digits, including those of the exponent, is 2 which is the same as the 2 digits 49 has. So 49 is equidigital in base 10.\n\nIn base 10, the number 125 has a prime factorization of 5³. The total number of digits, including those of the exponent, is 2 which is less than the 3 digits 125 has. So 125 is frugal in base 10.\n\nIn base 2, the number 100000 (32 decimal) has a prime factorization of 10^101 (2^5 decimal). The total number of binary digits, including those of the exponent, is 5 which is less than the 6 binary digits 100000 has. So 32 is frugal in base 2 (but equidigital in base 10).\n\n\n;Task\n\nCompute and show here the first '''50''' and the '''10,000th''' number in base '''10''' for each of the three categories of number defined above.\n\nAlso compute and show how many numbers less than '''1,000,000''' fall into each of the three categories.\n\n\n;Bonus\nDo the same for base '''11''', but show the results in base '''10'''.\n\n\n; References\n* [[oeis: A046760|OEIS: A046760 - Wasteful numbers]]\n* [[oeis: A046758|OEIS: A046758 - Equidigital numbers]]\n* [[oeis: A046759|OEIS: A046759 - Economical numbers]]\n<br><br>\n", "language": "00-TASK" }, { "code": "#include <algorithm>\n#include <cstdint>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nenum Category { WASTEFUL, EQUIDIGITAL, FRUGAL };\nconst std::vector<Category> categories = { Category::WASTEFUL, Category::EQUIDIGITAL, Category::FRUGAL };\n\nstruct Count {\n\tuint32_t lower_count;\n\tuint32_t upper_count;\n};\n\nstd::vector<std::unordered_map<uint32_t,uint32_t>> factors;\n\nstd::string to_string(const Category& category) {\n\tstd::string result;\n\tswitch ( category ) {\n\t\tcase Category::WASTEFUL : result = \"wasteful\"; break;\n\t\tcase Category::EQUIDIGITAL : result = \"equidigital\"; break;\n\t\tcase Category::FRUGAL : result = \"frugal\"; break;\n\t}\n\treturn result;\n}\n\n/**\n * Return the number of digits in the given number written in the given base\n */\nuint32_t digit_count(uint32_t number, const uint32_t& base) {\n\tuint32_t result = 0;\n\twhile ( number != 0 ) {\n\t\tresult++;\n\t\tnumber /= base;\n\t}\n\treturn result;\n}\n\n/**\n * Return the total number of digits used in the prime factorisation\n * of the given number written in the given base\n */\nuint32_t factor_count(const uint32_t& number, const uint32_t& base) {\n\tuint32_t result = 0;\n\tfor ( const auto& [key, value] : factors[number] ) {\n\t\tresult += digit_count(key, base);\n\t\tif ( value > 1 ) {\n\t\t\tresult += digit_count(value, base);\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Return the category of the given number written in the given base\n */\nCategory category(const uint32_t& number, const uint32_t& base) {\n\tconst uint32_t digit = digit_count(number, base);\n\tconst uint32_t factor = factor_count(number, base);\n\treturn ( digit < factor ) ? Category::WASTEFUL :\n\t\t ( digit > factor ) ? Category::FRUGAL : Category::EQUIDIGITAL;\n}\n\n/**\n * Factorise the numbers from 1 (inclusive) to limit (exclusive)\n */\nvoid create_factors(const uint32_t& limit) {\n\tfactors.assign(limit, std::unordered_map<uint32_t, uint32_t>());\n\tfactors[1].emplace(1, 1);\n\n\tfor ( uint32_t n = 1; n < limit; ++n ) {\n\t\tif ( factors[n].empty() ) {\n\t\t\tuint64_t n_copy = n;\n\t\t\twhile ( n_copy < limit ) {\n\t\t\t\tfor ( uint64_t i = n_copy; i < limit; i += n_copy ) {\n\t\t\t\t\tif ( factors[i].find(n) == factors[i].end() ) {\n\t\t\t\t\t\tfactors[i].emplace(n, 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfactors[i][n]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tn_copy *= n;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n\tcreate_factors(2'700'000);\n\n\tconst uint32_t tiny_limit = 50;\n\tconst uint32_t lower_limit = 10'000;\n\tconst uint32_t upper_limit = 1'000'000;\n\n\tfor ( uint32_t base : { 10, 11 } ) {\n\t\tstd::unordered_map<Category, Count> counts = { { Category::WASTEFUL, Count(0, 0) },\n\t\t\t{ Category::EQUIDIGITAL, Count(0, 0) }, { Category::FRUGAL, Count(0,0) } };\n\n\t\tstd::unordered_map<Category, std::vector<uint32_t>> lists = { { Category::WASTEFUL, std::vector<uint32_t>() },\n\t\t\t{ Category::EQUIDIGITAL, std::vector<uint32_t>() }, { Category::FRUGAL, std::vector<uint32_t>() } };\n\n\t\tuint32_t number = 1;\n\t\tstd::cout << \"FOR BASE \" << base << \":\" << std::endl << std::endl;\n\t\twhile ( std::any_of(counts.begin(), counts.end(),\n\t\t\t\t[](const std::pair<Category, Count>& pair) { return pair.second.lower_count < lower_limit; }) ) {\n\t\t\tCategory cat = category(number, base);\n\t\t\tif ( counts[cat].lower_count < tiny_limit || counts[cat].lower_count == lower_limit - 1 ) {\n\t\t\t\tlists[cat].emplace_back(number);\n\t\t\t}\n\t\t\tcounts[cat].lower_count++;\n\t\t\tif ( number < upper_limit ) {\n\t\t\t\tcounts[cat].upper_count++;\n\t\t\t}\n\t\t\tnumber++;\n\t\t}\n\n\t\tfor ( const Category& category : categories ) {\n\t\t\tstd::cout << \"First \" << tiny_limit << \" \" + to_string(category) << \" numbers:\" << std::endl;\n\t\t\tfor ( uint32_t i = 0; i < tiny_limit; ++i ) {\n\t\t\t\tstd::cout << std::setw(4) << lists[category][i] << ( i % 10 == 9 ? \"\\n\" : \" \" );\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::cout << lower_limit << \"th \" << to_string(category) << \" number: \"\n\t\t\t\t\t << lists[category][tiny_limit] << std::endl << std::endl;\n\t\t}\n\n\t\tstd::cout << \"For natural numbers less than \" << upper_limit << \", the breakdown is as follows:\" << std::endl;\n\t\tstd::cout << \" Wasteful numbers : \" << counts[Category::WASTEFUL].upper_count << std::endl;\n\t\tstd::cout << \" Equidigital numbers : \" << counts[Category::EQUIDIGITAL].upper_count << std::endl;\n\t\tstd::cout << \" Frugal numbers : \" << counts[Category::FRUGAL].upper_count << std::endl << std::endl;\n\t}\n}\n", "language": "C++" }, { "code": "// Frugal, equidigital, and wasteful numbers. Nigel Galloway: July 26th., 2022\nlet rec fG n g=match g/10L with 0L->n+1 |g->fG(n+1) g\nlet fN(g:int64)=Open.Numeric.Primes.Extensions.PrimeExtensions.PrimeFactors g|>Seq.skip 1|>Seq.countBy id|>Seq.sumBy(fun(n,g)->fG 0 n + if g<2 then 0 else fG 0 g)\nlet Frugal,Equidigital,Wasteful=let FEW n=Seq.initInfinite((+)2)|>Seq.filter(fun g->n(fG 0 g)(fN g)) in ((\"Frugal\",FEW(>)),(\"Equidigital\",seq{yield 1; yield! FEW(=)}),(\"Wasteful\",FEW(<)))\n[Frugal;Equidigital;Wasteful]|>List.iter(fun(n,g)->printf $\"%s{n}: 10 thousandth is %d{Seq.item 9999 g}; There are %d{Seq.length (g|>Seq.takeWhile((>)1000000))} < 1 million\\n First 50: \"; g|>Seq.take 50|>Seq.iter(printf \"%d \"); printfn \"\")\n", "language": "F-Sharp" }, { "code": "I=: #@(#.inv)\"0\nD=: [ +/@:I __ -.&1@,@q: ]\ntyp=: ~:&1@] * *@(I-D)\"0 NB. _1: wasteful, 0: equidigital, 1: frugal\n", "language": "J" }, { "code": " (9999&{, 50&{.)1+I._1=b10 NB. wasteful\n14346 4 6 8 9 12 18 20 22 24 26 28 30 33 34 36 38 39 40 42 44 45 46 48 50 51 52 54 55 56 57 58 60 62 63 65 66 68 69 70 72 74 75 76 77 78 80 82 84 85 86\n (9999&{, 50&{.)1+I. 0=b10 NB. equidigital\n33769 1 2 3 5 7 10 11 13 14 15 16 17 19 21 23 25 27 29 31 32 35 37 41 43 47 49 53 59 61 64 67 71 73 79 81 83 89 97 101 103 105 106 107 109 111 112 113 115 118 119\n (9999&{, 50&{.)1+I. 1=b10 NB. frugal\n1953125 125 128 243 256 343 512 625 729 1024 1029 1215 1250 1280 1331 1369 1458 1536 1681 1701 1715 1792 1849 1875 2048 2187 2197 2209 2401 2560 2809 3125 3481 3584 3645 3721 4096 4374 4375 4489 4802 4913 5041 5103 5329 6241 6250 6561 6859 6889 7203\n +/1e6>1+I._1=b10 NB. wasteful\n831231\n +/1e6>1+I. 0=b10 NB. equidigital\n165645\n +/1e6>1+I. 1=b10 NB. frugal\n3123\n", "language": "J" }, { "code": " (9999&{, 50&{.)1+I._1=b11 NB. wasteful\n12890 4 6 8 9 10 12 18 20 22 24 26 28 30 33 34 36 38 39 40 42 44 45 46 48 50 51 52 54 55 56 57 58 60 62 63 65 66 68 69 70 72 74 75 76 77 78 80 82 84 85\n (9999&{, 50&{.)1+I. 0=b11 NB. equidigital\n33203 1 2 3 5 7 11 13 14 15 16 17 19 21 23 25 27 29 31 32 35 37 41 43 47 49 53 59 61 64 67 71 73 79 81 83 89 97 101 103 107 109 113 121 122 123 127 129 131 133 134\n (9999&{, 50&{.)1+I. 1=b11 NB. frugal\n2659171 125 128 243 256 343 512 625 729 1024 1331 1369 1458 1536 1681 1701 1715 1792 1849 1875 2048 2187 2197 2209 2401 2560 2809 3072 3125 3481 3584 3645 3721 4096 4374 4375 4489 4802 4913 5041 5103 5120 5329 6241 6250 6561 6859 6889 7168 7203 7921\n +/1e6>1+I._1=b11 NB. wasteful\n795861\n +/1e6>1+I. 0=b11 NB. equidigital\n200710\n +/1e6>1+I. 1=b11 NB. frugal\n3428\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\npublic final class WastefulEquidigitalAndFrugalNumbers {\n\n\tpublic static void main(String[] args) {\n\t\tcreateFactors(2_700_000);\n\t\t\n\t\tfinal int tinyLimit = 50;\n\t\tfinal int lowerLimit = 10_000;\n\t\tfinal int upperLimit = 1_000_000;\t\t\n\t\t\n\t\tfor ( int base : List.of( 10, 11 ) ) {\t\t\t\t\n\t\t\tMap<Category, Count> counts = Arrays.stream(Category.values())\n\t\t\t\t.collect(Collectors.toMap( Function.identity(), value -> new Count(0, 0) ));\n\t\t\tMap<Category, List<Integer>> lists = Arrays.stream(Category.values())\n\t\t\t\t.collect(Collectors.toMap( Function.identity(), value -> new ArrayList<Integer>() ));\t\t\n\t\t\t\n\t\t int number = 1;\n\t\t System.out.println(\"FOR BASE \" + base + \":\" + System.lineSeparator());\n\t\t while ( counts.values().stream().anyMatch( count -> count.lowerCount < lowerLimit ) ) {\n\t\t \tCategory category = category(number, base);\n\t\t \tCount count = counts.get(category);\n\t\t \tif ( count.lowerCount < tinyLimit || count.lowerCount == lowerLimit - 1 ) {\n\t\t \t\tlists.get(category).add(number);\n\t\t \t}\n\t\t \tcount.lowerCount += 1;\n\t\t \tif ( number < upperLimit ) {\n\t\t \t\tcount.upperCount += 1;\n\t\t \t}\n\t\t \tnumber += 1;\t\t \t\n\t\t }\t\t\n\t\t\n\t\t\tfor ( Category category : Category.values() ) {\n\t\t\t\tSystem.out.println(\"First \" + tinyLimit + \" \" + category + \" numbers:\");\n\t\t\t\tfor ( int i = 0; i < tinyLimit; i++ ) {\n\t\t\t\t\tSystem.out.print(String.format(\"%4d%s\", lists.get(category).get(i), (i % 10 == 9 ? \"\\n\" : \" \")));\n\t\t\t\t}\n\t\t\t System.out.println();\t\t\n\t\t\t System.out.println(lowerLimit + \"th \" + category + \" number: \" + lists.get(category).get(tinyLimit));\n\t\t\t System.out.println();\n\t\t\t}\n\t\t\t\n\t\t System.out.println(\"For natural numbers less than \" + upperLimit + \", the breakdown is as follows:\");\t\t\n\t\t System.out.println(\" Wasteful numbers : \" + counts.get(Category.Wasteful).upperCount);\n\t\t System.out.println(\" Equidigital numbers : \" + counts.get(Category.Equidigital).upperCount);\n\t\t System.out.println(\" Frugal numbers : \" + counts.get(Category.Frugal).upperCount);\n\t\t System.out.println();\t\n\t\t}\n\t}\t\n\t\n\tprivate enum Category { Wasteful, Equidigital, Frugal }\n\t\n\t/**\n\t * Factorise the numbers from 1 (inclusive) to limit (exclusive)\n\t */\n\tprivate static void createFactors(int limit) {\n\t\tfactors = IntStream.rangeClosed(0, limit).boxed()\n\t\t\t.map( integer -> new HashMap<Integer, Integer>() ).collect(Collectors.toList());\n\t\tfactors.get(1).put(1, 1);\n\t\t\n\t\tfor ( int n = 1; n < limit; n++ ) {\n\t\t\tif ( factors.get(n).isEmpty() ) {\n\t\t\t\tlong nCopy = n;\n\t\t\t\twhile ( nCopy < limit ) {\n\t\t\t\t\tfor ( long i = nCopy; i < limit; i += nCopy ) {\n\t\t\t\t\t\tfactors.get((int) i).merge(n, 1, Integer::sum);\n\t\t\t\t\t}\n\t\t\t\t\tnCopy *= n;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Return the number of digits in the given number written in the given base\n\t */\n\tprivate static int digitCount(int number, int base) {\n\t\tint result = 0;\n\t\twhile ( number != 0 ) {\n\t\t result += 1;\n\t\t number /= base;\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Return the total number of digits used in the prime factorisation\n\t * of the given number written in the given base\n\t */\n\tprivate static int factorCount(int number, int base) {\n\t\tint result = 0;\n\t\tfor ( Map.Entry<Integer, Integer> entry : factors.get(number).entrySet() ) {\n\t\t\tresult += digitCount(entry.getKey(), base);\n\t\t\tif ( entry.getValue() > 1 ) {\n\t\t\t\tresult += digitCount(entry.getValue(), base);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Return the category of the given number written in the given base\n\t */\n\tprivate static Category category(int number, int base) {\n\t\tfinal int digitCount = digitCount(number, base);\n\t\tfinal int factorCount = factorCount(number, base);\n\t\treturn ( digitCount < factorCount ) ? Category.Wasteful :\n\t\t\t ( digitCount > factorCount ) ? Category.Frugal : Category.Equidigital;\t\n\t}\n\t\n\tprivate static class Count {\n\t\t\n\t\tpublic Count(int aLowerCount, int aUpperCount) {\n\t\t\tlowerCount = aLowerCount; upperCount = aUpperCount;\n\t\t}\n\t\t\n\t\tprivate int lowerCount, upperCount;\n\t\t\n\t}\n\t\n\tprivate static List<Map<Integer, Integer>> factors;\n\n}\n", "language": "Java" }, { "code": "using Primes\n\n\"\"\"\n function wastefulness(n, base = 10)\n\ncalculate d1: the number of digits in base `base` required to write the factor expansion of\n`n`, ie 12 -> 2^2 * 3^2 is 4 digits, 7 -> 7 is 1 digit, 20 -> 5 * 2^2 is 3 digits\n\ncalculate d2: the number of digits in base `base` to represent `n` itself\n\nreturn -1 if frugal (d1 > d2), 0 if equidigital (d1 == d2), 1 if wasteful (d1 > d2)\n\"\"\"\nfunction wastefulness(n::Integer, base = 10)\n @assert n > 0\n return n == 1 ? 0 :\n sign(sum(p -> ndigits(p[1], base=base) +\n (p[2] == 1 ? 0 : ndigits(p[2], base=base)),\n factor(n).pe) -\n ndigits(n, base=base))\nend\n\nfor b in [10, 11]\n w50, e50, f50 = Int[], Int[], Int[]\n w10k, e10k, f10k, wcount, ecount, fcount, wm, em, fm = 0, 0, 0, 0, 0, 0, 0, 0, 0\n for n in 1:10_000_000\n sgn = wastefulness(n, b)\n if sgn < 0\n fcount < 50 && push!(f50, n)\n fcount += 1\n fcount == 10000 &&(f10k = n)\n n < 1_000_000 && (fm += 1)\n elseif sgn == 0\n ecount < 50 && push!(e50, n)\n ecount += 1\n ecount == 10000 && (e10k = n)\n n < 1_000_000 && (em += 1)\n else # sgn > 0\n wcount < 50 && push!(w50, n)\n wcount += 1\n wcount == 10000 && (w10k = n)\n n < 1_000_000 && (wm += 1)\n end\n if f10k > 0\n println(\"FOR BASE $b:\\n\")\n println(\"First 50 Wasteful numbers:\")\n foreach(p -> print(rpad(p[2], 5), p[1] % 10 == 0 ? \"\\n\" : \"\"), pairs(w50))\n println(\"\\nFirst 50 Equidigital numbers:\")\n foreach(p -> print(rpad(p[2], 5), p[1] % 10 == 0 ? \"\\n\" : \"\"), pairs(e50))\n println(\"\\nFirst 50 Frugal numbers:\")\n foreach(p -> print(rpad(p[2], 5), p[1] % 10 == 0 ? \"\\n\" : \"\"), pairs(f50))\n println(\"\\n10,000th Wasteful number : $w10k\")\n println(\"10,000th Equidigital number : $e10k\")\n println(\"10,000th Frugal number : $f10k\")\n println(\"\\nFor natural numbers < 1 million, the breakdown is as follows:\")\n println(\" Wasteful numbers : $wm\")\n println(\" Equidigital numbers : $em\")\n println(\" Frugal numbers : $fm\\n\\n\")\n break\n end\n end\nend\n", "language": "Julia" }, { "code": "ClearAll[FactorIntegerDigits, ID, Stats]\nFactorIntegerDigits[n_] := Module[{},\n fi = FactorInteger[n];\n fi[[All, 1]] //= Map[IntegerLength];\n fi[[All, 2]] //= Map[If[# == 1, 0, IntegerLength[#]] &];\n Total[Flatten[fi]]\n ]\nStats[l_List] := Module[{},\n Print[\"10000: \", l[[10^4]]];\n Print[\"First 50: \", l[[;; 50]]];\n Print[\"Below 10^6: \", Length[Select[l, LessThan[10^6]]]];\n ]\nID[n_] := {IntegerLength[n], FactorIntegerDigits[n]}\nbla = {#, ID[#]} & /@ Range[2000000];\nwasteful = Select[bla, #[[2, 1]] < #[[2, 2]] &][[All, 1]];\nequidigital = Select[bla, #[[2, 1]] == #[[2, 2]] &][[All, 1]];\nfrugal = Select[bla, #[[2, 1]] > #[[2, 2]] &][[All, 1]];\nPrint[\"Wasteful\"]\nStats[wasteful]\n\nPrint[\"Equidigital\"]\nStats[equidigital]\n\nPrint[\"Frugal\"]\nStats[frugal]\n", "language": "Mathematica" }, { "code": "import std/[sequtils, strformat, tables]\n\n# Sieve to find the decomposition in prime factors.\nconst N = 2_700_000\nvar factors: array[1..N, CountTable[int]]\nfactors[1].inc(1)\n\nfor n in 2..N:\n if factors[n].len == 0: # \"n\" is prime.\n var m = n # Powers of \"n\"\n while m <= N:\n for k in countup(m, N, m):\n factors[k].inc(n)\n m *= n\n\ntype Category {.pure.} = enum Wasteful = \"wasteful\"\n Equidigital = \"equidigital\"\n Frugal = \"frugal\"\n\nfunc digitCount(n, base: Positive): int =\n ## Return the number of digits of the representation of \"n\" in given base.\n var n = n.Natural\n while n != 0:\n inc result\n n = n div base\n\nproc d(n, base: Positive): int =\n ## Compute \"D(n)\" in given base.\n for (p, e) in factors[n].pairs:\n inc result, p.digitCount(base)\n if e > 1: inc result, e.digitCount(base)\n\nproc category(n, base: Positive): Category =\n ## Return the category of \"n\" in given base.\n let i = n.digitCount(base)\n let d = d(n, base)\n result = if i < d: Wasteful elif i > d: Frugal else: Equidigital\n\n\nconst N1 = 50\nconst N2 = 10_000\nconst Limit = 1_000_000\n\nfor base in [10, 11]:\n\n var counts1: array[Category, int] # Total counts.\n var counts2: array[Category, int] # Counts for n < Limit.\n var numbers1: array[Category, array[1..N1, int]] # First N1 numbers in each category.\n var numbers2: array[Category, int] # Number at position N2 in each category.\n\n echo &\"For base {base}.\"\n echo \"===========\\n\"\n var n = 1\n while true:\n if n == Limit:\n counts2 = counts1\n let cat = n.category(base)\n inc counts1[cat]\n let c = counts1[cat]\n if c <= N1:\n numbers1[cat][c] = n\n elif c == N2:\n numbers2[cat] = n\n inc n\n if allIt(counts1, it >= N2) and n >= Limit: break\n\n for cat in Category.low..Category.high:\n echo &\"First {N1} {cat} numbers:\"\n for i, n in numbers1[cat]:\n stdout.write &\"{n:4}\"\n stdout.write if i mod 10 == 0: '\\n' else: ' '\n echo &\"\\nThe {N2}th {cat} number is {numbers2[cat]}.\\n\"\n\n echo &\"Among numbers less than {Limit}, there are:\"\n for cat in Category.low..Category.high:\n echo &\"- {counts2[cat]} {cat} numbers.\"\n echo '\\n'\n", "language": "Nim" }, { "code": "use v5.36;\nuse experimental 'for_list';\nuse ntheory <factor todigitstring>;\nuse List::Util <sum max min pairmap>;\n\nsub table ($c, @V) { my $t = $c * (my $w = 6); ( sprintf( ('%'.$w.'d')x@V, @V) ) =~ s/.{1,$t}\\K/\\n/gr }\n\nsub bag (@v) { my %h; $h{$_}++ for @v; %h }\n\nfor my $base (10, 11) {\n my(@F,@E,@W,$n,$totals);\n do {\n my %F = bag factor ++$n;\n my $s = sum pairmap { length(todigitstring($a,$base)) + ($b > 1 ? length(todigitstring($b,$base)) : 0) } %F;\n my $l = length todigitstring($n,$base);\n if ($n == 1 or $l == $s) { push @E, $n }\n elsif ( $l < $s) { push @W, $n }\n else { push @F, $n }\n } until 10000 < min scalar @F, scalar @E, scalar @W;\n\n say \"In base $base:\";\n for my ($type, $values) ('Wasteful', \\@W, 'Equidigital', \\@E, 'Frugal', \\@F) {\n say \"\\n$type numbers:\";\n say table 10, @$values[0..49];\n say \"10,000th: $$values[9999]\";\n $totals .= sprintf \"%11s: %d\\n\", $type, scalar grep { $_ < 1_000_000 } @$values\n }\n say \"\\nOf the positive integers up to one million:\\n$totals\";\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">analyze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">prime_factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">digits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">pq</span> <span style=\"color: #008080;\">in</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pq</span>\n <span style=\"color: #000000;\">digits</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%a\"</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">}}))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">digits</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%a\"</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">}}))</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- -1/0/+1 =&gt; 1/2/3 for wasteful/equidigital/frugal:</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">compare</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%a\"</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">}})),</span> <span style=\"color: #000000;\">digits</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n FOR BASE %d:\n\n First 50 Wasteful numbers:\n %s\n First 50 Equidigital numbers:\n %s\n First 50 Frugal numbers:\n %s\n 10,000th Wasteful number : %d\n 10,000th Equidigital number : %d\n 10,000th Frugal number : %d\n\n For natural numbers &lt; 1 million, the breakdown is as follows:\n Wasteful numbers : %6d\n Equidigital numbers : %6d\n Frugal numbers : %6d\n\n \"\"\"</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">in</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">11</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">wef</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{}},</span>\n <span style=\"color: #000000;\">w10k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">c2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">10000</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">wdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">analyze</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wef</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">])<</span><span style=\"color: #000000;\">50</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">wef</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">9999</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">w10k</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1e6</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">wdx</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()></span><span style=\"color: #000000;\">t1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">progress</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"working %d...\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">progress</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">w3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">wef</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #008000;\">\"%4d\"</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">w3</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">w10k</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">c2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "use Prime::Factor;\nuse Lingua::EN::Numbers;\n\nmy %cache;\n\nsub factor-char-sum ($n, $base = 10) { sum $n.&prime-factors.Bag.map: { .key.base($base).chars + (.value > 1 ?? .value.base($base).chars !! 0) } }\n\nsub economical ($n, $base = 10) { ($n > 1) && $n.base($base).chars > (%cache{$base}[$n] //= factor-char-sum $n, $base) }\nsub equidigital ($n, $base = 10) { ($n == 1) || $n.base($base).chars == (%cache{$base}[$n] //= factor-char-sum $n, $base) }\nsub extravagant ($n, $base = 10) { $n.base($base).chars < (%cache{$base}[$n] //= factor-char-sum $n, $base) }\n\n\nfor 10, 11 -> $base {\n %cache{$base}[3e6] = Any; # preallocate to avoid concurrency issues\n say \"\\nIn Base $base:\";\n for &extravagant, &equidigital, &economical -> &sub {\n say \"\\nFirst 50 {&sub.name} numbers:\";\n say (^∞).grep( {.&sub($base)} )[^50].batch(10)».&comma».fmt(\"%6s\").join: \"\\n\";\n say \"10,000th: \" ~ (^∞).hyper(:2000batch).grep( {.&sub($base)} )[9999].&comma;\n }\n\n my $upto = 1e6.Int;\n my atomicint ($extravagant, $equidigital, $economical);\n say \"\\nOf the positive integers up to {$upto.&cardinal}:\";\n (1..^$upto).race(:5000batch).map: { .&extravagant($base) ?? ++⚛$extravagant !! .&equidigital($base) ?? ++⚛$equidigital !! ++⚛$economical };\n say \" Extravagant: {comma $extravagant}\\n Equidigital: {comma $equidigital}\\n Economical: {comma $economical}\";\n %cache{$base} = Empty;\n}\n", "language": "Raku" }, { "code": "require 'prime'\n\n[10,11].each do |base|\n res = Hash.new{|h, k| h[k] = [] }\n puts \"\\nBase: #{base}\"\n\n (1..).each do |n|\n pd = n.prime_division\n pd = pd.map{|pr| pr.pop if pr.last == 1; pr}\n pd = [1] if n == 1\n selector = n.digits(base).size <=> pd.flatten.sum{|m| m.digits(base).size} # -1,0,1\n res[[:Equidigital, :Frugal, :Wasteful][selector]] << n\n break if res.values.all?{|v| v.size >= 10000}\n end\n\n res.each do |k, v|\n puts \"#{k}:\"\n puts \"10000th: #{v[9999]}; count: #{v.count{|n| n < 1_000_000}}\"\n p v.first(50)\n end\nend\n", "language": "Ruby" }, { "code": "import \"./math\" for Int\nimport \"./seq\" for Lst\nimport \"./fmt\" for Fmt\n\nvar analyze = Fn.new { |n, b|\n var factors = Int.primeFactors(n)\n var indivs = Lst.individuals(factors)\n var digits = 0\n for (indiv in indivs) {\n digits = digits + Int.digits(indiv[0], b).count\n if (indiv[1] > 1) digits = digits + Int.digits(indiv[1], b).count\n }\n return [Int.digits(n, b).count, digits]\n}\n\nfor (b in [10, 11]) {\n var w = []\n var e = [1]\n var f = []\n var wc = 0\n var ec = 1\n var fc = 0\n var wc2 = 0\n var ec2 = 1\n var fc2 = 0\n var n = 2\n System.print(\"FOR BASE %(b):\\n\")\n while (fc < 10000 || ec < 10000 || wc < 10000) {\n var r = analyze.call(n, b)\n if (r[0] < r[1]) {\n if (w.count < 50 || wc == 9999) w.add(n)\n wc = wc + 1\n if (n < 1e6) wc2 = wc2 + 1\n } else if (r[0] == r[1]) {\n if (e.count < 50 || ec == 9999) e.add(n)\n ec = ec + 1\n if (n < 1e6) ec2 = ec2 + 1\n } else {\n if (f.count < 50 || fc == 9999) f.add(n)\n fc = fc + 1\n if (n < 1e6) fc2 = fc2 + 1\n }\n n = n + 1\n }\n System.print(\"First 50 Wasteful numbers:\")\n Fmt.tprint(\"$4d\", w[0..49], 10)\n System.print()\n System.print(\"First 50 Equidigital numbers:\")\n Fmt.tprint(\"$4d\", e[0..49], 10)\n System.print()\n System.print(\"First 50 Frugal numbers:\")\n Fmt.tprint(\"$4d\", f[0..49], 10)\n System.print()\n System.print(\"10,000th Wasteful number : %(w[50])\")\n System.print(\"10,000th Equidigital number : %(e[50])\")\n System.print(\"10,000th Frugal number : %(f[50])\")\n System.print()\n System.print(\"For natural numbers < 1 million, the breakdown is as follows:\")\n Fmt.print(\" Wasteful numbers : $6d\", wc2)\n Fmt.print(\" Equidigital numbers : $6d\", ec2)\n Fmt.print(\" Frugal numbers : $6d\", fc2)\n System.print()\n}\n", "language": "Wren" } ]
Wasteful-equidigital-and-frugal-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Water_collected_between_towers\n", "language": "00-META" }, { "code": ";Task:\nIn a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n<pre>9 ██ 9 ██ \n8 ██ 8 ██ \n7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██ \n6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██ \n5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████ \n4 ██ ██ ████████ 4 ██≈≈██≈≈████████ \n3 ██████ ████████ 3 ██████≈≈████████ \n2 ████████████████ ██ 2 ████████████████≈≈██\n1 ████████████████████ 1 ████████████████████</pre>\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n<pre> [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]</pre>\n\n\nSee, also:\n\n* [https://youtu.be/ftcIcn8AmSY?t=536 Four Solutions to a Trivial Problem] – a Google Tech Talk by Guy Steele\n* [http://stackoverflow.com/questions/24414700/amazon-water-collected-between-towers/ Water collected between towers] on Stack Overflow, from which the example above is taken)\n* [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d An interesting Haskell solution], using the Tardis monad, by [https://gist.github.com/paf31 Phil Freeman] in a [https://gist.github.com/paf31/9d84ecf6a6a9b69cdb597a390f25764d Github gist].\n\n\n<br>\n\n", "language": "00-TASK" }, { "code": "F water_collected(tower)\n V l = tower.len\n V highest_left = [0] [+] (1 .< l).map(n -> max(@tower[0 .< n]))\n V highest_right = (1 .< l).map(n -> max(@tower[n .< @l])) [+] [0]\n V water_level = (0 .< l).map(n -> max(min(@highest_left[n], @highest_right[n]) - @tower[n], 0))\n print(‘highest_left: ’highest_left)\n print(‘highest_right: ’highest_right)\n print(‘water_level: ’water_level)\n print(‘tower_level: ’tower)\n print(‘total_water: ’sum(water_level))\n print(‘’)\n R sum(water_level)\n\nV towers = [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\nprint(towers.map(tower -> water_collected(tower)))\n", "language": "11l" }, { "code": "\torg\t100h\n\tjmp\tdemo\n\t;;;\tCalculate the amount of water a row of towers will hold\n\t;;;\tNote: this will destroy the input array.\n\t;;;\tInput: DE = tower array, BC = length of array\n\t;;;\tOutput: A = amount of water\nwater:\txra\ta\t; Start with no water\n\tsta\tw_out+1\nwscanr:\tmov\th,d\t; HL = right edge\n\tmov\tl,e\n\tdad\tb\nwscrlp:\tdcx\th\n\tcall\tcmp16\t; Reached beginning?\n\tjnc\tw_out\t; Then stop\n\tmov\ta,m\t; Otherwise, if current tower is zero\n\tora\ta\n\tjz\twscrlp\t; Then keep scanning\n\tpush\tb\t; Keep length\n\tpush\td\t; Keep array begin\n\tmvi\tb,0\t; No blocks yet\n\txchg\t\t; HL = left scanning edge, DE = right\nwscanl:\tmov\ta,m\t; Get current column\n\tora\ta\t; Is zero?\n\tjz\twunit\t; Then see if an unit of water must be added\n\tdcr\tm\t; Otherwise, decrease column\n\tinr\tb\t; Increase blocks\n\tjmp\twnext\nwunit:\tmov\ta,b\t; Any blocks?\n\tora\ta\n\tjz\twnext\n\tlda\tw_out+1\t; If so, add water\n\tinr\ta\n\tsta\tw_out+1\nwnext:\tinx\th\t; Next column\n\tcall\tcmp16\n\tjnc\twscanl\t; Until right edge reached\n\tmov\ta,b\n\tcmc\t\t; Check if more than 1 block left\n\trar\n\tora\ta\n\tpop \td\t; Restore array begin\n\tpop\tb\t; and length\n\tjnz\twscanr\t; If more than 1 block, keep scanning\nw_out:\tmvi\ta,0\t; Load water into A\n\tret \t\n\t;;;\t16-bit compare DE to HL\ncmp16:\tmov\ta,d\n\tcmp\th\n\trnz\n\tmov\ta,e\n\tcmp \tl\n\tret\n\t;;;\tCalculate and print the amount of water for each input\ndemo:\tlxi\th,series\nload:\tmov\te,m\t; Load pointer\n\tinx\th\n\tmov\td,m\n\tinx\th\n\tmov\tc,m\t; Load length\n\tinx\th\n\tmov\tb,m\n\tinx\th\n\tmov\ta,d\t; If pointer is zero,\n\tora\te\n\trz\t\t; stop.\n\tpush \th\t; Otherwise, save the series pointer\n\tcall\twater\t; Calculate amount of water\n\tcall\tprinta\t; Output amount of water\n\tpop\th\t; Restore series pointer\n\tjmp\tload\t; Load next example\n\t;;;\tPrint A as integer value\nprinta:\tlxi\td,num\t; Pointer to number string\n\tmvi\tc,10\t; Divisor\ndigit:\tmvi\tb,-1\t; Quotient\ndloop:\tinr\tb\t; Divide (by trial subtraction)\n\tsub\tc\n\tjnc\tdloop\n\tadi\t'0'+10\t; ASCII digit from remainder\n\tdcx\td\t; Store ASCII digit\n\tstax\td\n\tmov\ta,b\t; Continue with quotient\n\tana\ta\t; If not zero\n\tjnz\tdigit\n\tmvi\tc,9\t; 9 = CP/M print string syscall\n\tjmp\t5\t; Print number string\n\tdb\t'***'\t; Output number placeholder\nnum:\tdb\t' $'\n\t;;;\tSeries\nt1:\tdb\t1,5,3,7,2\nt2:\tdb\t5,3,7,2,6,4,5,9,1,2\nt3:\tdb\t2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\nt4: \tdb\t5,5,5,5\nt5:\tdb\t5,6,7,8\nt6: \tdb\t8,7,7,6\nt7:\tdb \t6,7,10,7,6\nt_end:\tequ\t$\n\t;;;\tLengths and pointers\nseries:\tdw\tt1,t2-t1\n\tdw\tt2,t3-t2\n\tdw\tt3,t4-t3\n\tdw\tt4,t5-t4\n\tdw\tt5,t6-t5\n\tdw\tt6,t7-t6\n\tdw\tt7,t_end-t7\n\tdw\t0\n", "language": "8080-Assembly" }, { "code": "\tcpu\t8086\n\torg\t100h\nsection\t.text\n\tjmp\tdemo\n\t;;;\tCalculate the amount of water a row of towers will hold\n\t;;;\tNote: this will destroy the input array.\n\t;;;\tInput: DX = tower array, CX = length of array\n\t;;;\tOutput: AX = amount of water\t\nwater:\txor\tax,ax\t\t; Amount of water starts at zero\t\n\txor\tbx,bx\t\t; BH = zero, BL = block count\n.scanr:\tmov\tdi,dx\t\t; DI = right edge of towers\n\tadd\tdi,cx\n.rloop:\tdec\tdi\n\tcmp\tdi,dx\t\t; Reached beginning?\n\tjl\t.out\t\t; Then calculation is done.\n\tcmp\tbh,[di]\t\t; Otherwise, if the tower is zero,\n\tje\t.rloop\t\t; Keep scanning\n\txor\tbl,bl\t\t; Set block count to zero\n\tmov\tsi,dx\t\t; SI = left scanning edge\n.scanl:\tcmp\tbh,[si]\t\t; Is the column empty?\n\tje\t.unit\t\t; Then see whether to add an unit of water\n\tdec\tbyte [si]\t; Otherwise, remove block from tower\n\tinc\tbx\t\t; And count it\n\tjmp\t.next\n.unit:\ttest\tbl,bl\t\t; Any blocks?\n\tjz\t.next\t\t\n\tinc\tax\t\t; If so, add unit of water\n.next:\tinc\tsi\t\t; Scan rightward\n\tcmp\tsi,di\t\t; Reached the right edge?\n\tjbe\t.scanl\t\t; If not, keep going\n\tshr\tbl,1\t\t; If more than 1 block,\n\tjnz\t.scanr\t\t; Keep going\n.out:\tret\n\t;;;\tCalculate and print the amount of water for each input\ndemo:\tmov\tsi,series\n.loop:\tlodsw\t\t\t; Load pointer\n\ttest\tax,ax\t\t; If 0,\n\tjz\t.done\t\t; we're done.\n\txchg\tax,dx\n\tlodsw\t\t\t; Load length\n\txchg\tax,cx\n\tpush\tsi\t\t; Keep array pointer\n\tcall\twater\t\t; Calculate amount of water\n\tcall\tprax\t\t; Print AX\n\tpop\tsi\t\t; Restore array pointer\n\tjmp \t.loop\n.done:\tret\n\t;;;\tPrint AX as number\nprax:\tmov\tbx,num\t\t; Pointer to end of number string\n\tmov\tcx,10 \t\t; Divisor\n.dgt:\txor\tdx,dx\t\t; Divide by 10\n\tdiv\tcx\n\tadd\tdl,'0'\t\t; Add ASCII 0 to remainder\n\tdec\tbx\t\t; Store digit\n\tmov\t[bx],dl\n\ttest\tax,ax\t\t; If number not zero yet\n\tjnz\t.dgt\t\t; Find rest of digits\n\tmov\tdx,bx\t\t; Print number string\n\tmov\tah,9\n\tint\t21h\n\tret\nsection\t.data\n\tdb\t'*****'\t\t; Output number placeholder\nnum:\tdb\t' $'\n\t;;;\tSeries\nt1:\tdb\t1,5,3,7,2\nt2:\tdb\t5,3,7,2,6,4,5,9,1,2\nt3:\tdb\t2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\nt4: \tdb\t5,5,5,5\nt5:\tdb\t5,6,7,8\nt6: \tdb\t8,7,7,6\nt7:\tdb \t6,7,10,7,6\nt_end:\tequ\t$\n\t;;;\tLengths and pointers\nseries:\tdw\tt1,t2-t1\n\tdw\tt2,t3-t2\n\tdw\tt3,t4-t3\n\tdw\tt4,t5-t4\n\tdw\tt5,t6-t5\n\tdw\tt6,t7-t6\n\tdw\tt7,t_end-t7\n\tdw\t0\n", "language": "8086-Assembly" }, { "code": "PROC PrintArray(BYTE ARRAY a BYTE len)\n BYTE i\n\n Put('[)\n FOR i=0 TO len-1\n DO\n IF i>0 THEN\n Put(32)\n FI\n PrintB(a(i))\n OD\n Put('])\nRETURN\n\nBYTE FUNC Max(BYTE ARRAY a BYTE start,stop)\n BYTE i,res\n\n res=0\n FOR i=start TO stop\n DO\n IF a(i)>res THEN\n res=a(i)\n FI\n OD\nRETURN (res)\n\nBYTE FUNC CalcWater(BYTE ARRAY a BYTE len)\n BYTE water,i,maxL,maxR,lev\n\n IF len<3 THEN\n RETURN (0)\n FI\n water=0\n FOR i=1 TO len-2\n DO\n maxL=Max(a,0,i-1)\n maxR=Max(a,i+1,len-1)\n IF maxL<maxR THEN\n lev=maxL\n ELSE\n lev=maxR\n FI\n IF a(i)<lev THEN\n water==+lev-a(i)\n FI\n OD\nRETURN (water)\n\nPROC Test(BYTE ARRAY a BYTE len)\n BYTE water\n\n water=CalcWater(a,len)\n PrintArray(a,len)\n PrintF(\" holds %B water units%E%E\",water)\nRETURN\n\nPROC Main()\n DEFINE COUNT=\"7\"\n BYTE ARRAY\n a1=[1 5 3 7 2],\n a2=[5 3 7 2 6 4 5 9 1 2],\n a3=[2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1],\n a4=[5 5 5 5],\n a5=[5 6 7 8],\n a6=[8 7 7 6],\n a7=[6 7 10 7 6]\n\n Test(a1,5)\n Test(a2,10)\n Test(a3,16)\n Test(a4,4)\n Test(a5,4)\n Test(a6,4)\n Test(a7,5)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\n\nprocedure Water_Collected is\n\n type Bar_Index is new Positive;\n type Natural_Array is array (Bar_Index range <>) of Natural;\n\n subtype Bar_Array is Natural_Array;\n subtype Water_Array is Natural_Array;\n\n function Flood (Bars : Bar_Array; Forward : Boolean) return Water_Array is\n R : Water_Array (Bars'Range);\n H : Natural := 0;\n begin\n if Forward then\n for A in R'Range loop\n H := Natural'Max (H, Bars (A));\n R (A) := H - Bars (A);\n end loop;\n else\n for A in reverse R'Range loop\n H := Natural'Max (H, Bars (A));\n R (A) := H - Bars (A);\n end loop;\n end if;\n return R;\n end Flood;\n\n function Fold (Left, Right : Water_Array) return Water_Array is\n R : Water_Array (Left'Range);\n begin\n for A in R'Range loop\n R (A) := Natural'Min (Left (A), Right (A));\n end loop;\n return R;\n end Fold;\n\n function Fill (Bars : Bar_Array) return Water_Array\n is (Fold (Flood (Bars, Forward => True),\n Flood (Bars, Forward => False)));\n\n function Sum_Of (Bars : Natural_Array) return Natural is\n Sum : Natural := 0;\n begin\n for Bar of Bars loop\n Sum := Sum + Bar;\n end loop;\n return Sum;\n end Sum_Of;\n\n procedure Show (Bars : Bar_Array) is\n use Ada.Text_IO;\n Water : constant Water_Array := Fill (Bars);\n begin\n Put (\"The series: [\");\n for Bar of Bars loop\n Put (Bar'Image);\n Put (\" \");\n end loop;\n Put (\"] holds \");\n Put (Sum_Of (Water)'Image);\n Put (\" units of water.\");\n New_Line;\n end Show;\n\nbegin\n Show ((1, 5, 3, 7, 2));\n Show ((5, 3, 7, 2, 6, 4, 5, 9, 1, 2));\n Show ((2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1));\n Show ((5, 5, 5, 5));\n Show ((5, 6, 7, 8));\n Show ((8, 7, 7, 6));\n Show ((6, 7, 10, 7, 6));\nend Water_Collected;\n", "language": "Ada" }, { "code": "--------------- WATER COLLECTED BETWEEN TOWERS -------------\n\n-- waterCollected :: [Int] -> Int\non waterCollected(xs)\n set leftWalls to scanl1(my max, xs)\n set rightWalls to scanr1(my max, xs)\n\n set waterLevels to zipWith(my min, leftWalls, rightWalls)\n\n -- positive :: Num a => a -> Bool\n script positive\n on |λ|(x)\n x > 0\n end |λ|\n end script\n\n -- minus :: Num a => a -> a -> a\n script minus\n on |λ|(a, b)\n a - b\n end |λ|\n end script\n\n sum(filter(positive, zipWith(minus, waterLevels, xs)))\nend waterCollected\n\n\n---------------------------- TEST --------------------------\non run\n map(waterCollected, ¬\n [[1, 5, 3, 7, 2], ¬\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], ¬\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], ¬\n [5, 5, 5, 5], ¬\n [5, 6, 7, 8], ¬\n [8, 7, 7, 6], ¬\n [6, 7, 10, 7, 6]])\n\n --> {2, 14, 35, 0, 0, 0, 0}\nend run\n\n\n--------------------- GENERIC FUNCTIONS --------------------\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- init :: [a] -> [a]\non init(xs)\n if length of xs > 1 then\n items 1 thru -2 of xs\n else\n {}\n end if\nend init\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- max :: Ord a => a -> a -> a\non max(x, y)\n if x > y then\n x\n else\n y\n end if\nend max\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- scanl :: (b -> a -> b) -> b -> [a] -> [b]\non scanl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n set lst to {startValue}\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n set end of lst to v\n end repeat\n return lst\n end tell\nend scanl\n\n-- scanl1 :: (a -> a -> a) -> [a] -> [a]\non scanl1(f, xs)\n if length of xs > 0 then\n scanl(f, item 1 of xs, items 2 thru -1 of xs)\n else\n {}\n end if\nend scanl1\n\n-- scanr :: (b -> a -> b) -> b -> [a] -> [b]\non scanr(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n set lst to {startValue}\n repeat with i from lng to 1 by -1\n set v to |λ|(v, item i of xs, i, xs)\n set end of lst to v\n end repeat\n return reverse of lst\n end tell\nend scanr\n\n-- scanr1 :: (a -> a -> a) -> [a] -> [a]\non scanr1(f, xs)\n if length of xs > 0 then\n scanr(f, item -1 of xs, items 1 thru -2 of xs)\n else\n {}\n end if\nend scanr1\n\n-- sum :: Num a => [a] -> a\non sum(xs)\n script add\n on |λ|(a, b)\n a + b\n end |λ|\n end script\n\n foldl(add, 0, xs)\nend sum\n\n-- tail :: [a] -> [a]\non tail(xs)\n if length of xs > 1 then\n items 2 thru -1 of xs\n else\n {}\n end if\nend tail\n\n-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\non zipWith(f, xs, ys)\n set lng to min(length of xs, length of ys)\n set lst to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, item i of ys)\n end repeat\n return lst\n end tell\nend zipWith\n", "language": "AppleScript" }, { "code": "{2, 14, 35, 0, 0, 0, 0}\n", "language": "AppleScript" }, { "code": "cmax: function => [\n m: neg ∞\n map & 'x -> m:<=max @[m x]\n]\n\nvmin: $ => [map couple & & => min]\n\nvsub: $ => [map couple & & 'p -> p\\0 - p\\1]\n\nwater: function [a][\n sum vsub vmin reverse cmax reverse a cmax a a\n]\n\nloop [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n] 'a -> print [a \"->\" water a]\n", "language": "Arturo" }, { "code": "WCBT(oTwr){\n\ttopL := Max(oTwr*), l := num := 0, barCh := lbarCh := \"\", oLvl := []\n\twhile (++l <= topL)\n\t\tfor t, h in oTwr\n\t\t\toLvl[l,t] := h ? \"██\" : \"≈≈\" , oTwr[t] := oTwr[t]>0 ? oTwr[t]-1 : 0\n\tfor l, obj in oLvl{\n\t\twhile (oLvl[l, A_Index] = \"≈≈\")\n\t\t\toLvl[l, A_Index] := \" \"\n\t\twhile (oLvl[l, obj.Count() +1 - A_Index] = \"≈≈\")\n\t\t\toLvl[l, obj.Count() +1 - A_Index] := \" \"\n\t\tfor t, v in obj\n\t\t\tlbarCh .= StrReplace(v, \"≈≈\", \"≈≈\", n), num += n\n\t\tbarCh := lbarCh \"`n\" barCh, lbarCh := \"\"\n\t}\n\treturn [num, barCh]\n}\n", "language": "AutoHotkey" }, { "code": "data := [[1, 5, 3, 7, 2]\n\t,[5, 3, 7, 2, 6, 4, 5, 9, 1, 2]\n\t,[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1]\n\t,[5, 5, 5, 5]\n\t,[5, 6, 7, 8]\n\t,[8, 7, 7, 6]\n\t,[6, 7, 10, 7, 6]]\n\nresult := \"\"\nfor i, oTwr in data{\n\tinp := \"\"\n\tfor i, h in oTwr\n\t\tinp .= h \", \"\n\tinp := \"[\" Trim(inp, \", \") \"]\"\n\tx := WCBT(oTwr)\n\tresult .= \"Chart \" inp \" has \" x.1 \" water units`n\" x.2 \"------------------------`n\"\n}\nMsgBox % result\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f WATER_COLLECTED_BETWEEN_TOWERS.AWK [-v debug={0|1}]\nBEGIN {\n wcbt(\"1,5,3,7,2\")\n wcbt(\"5,3,7,2,6,4,5,9,1,2\")\n wcbt(\"2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\")\n wcbt(\"5,5,5,5\")\n wcbt(\"5,6,7,8\")\n wcbt(\"8,7,7,6\")\n wcbt(\"6,7,10,7,6\")\n exit(0)\n}\nfunction wcbt(str, ans,hl,hr,i,n,tower) {\n n = split(str,tower,\",\")\n for (i=n; i>=0; i--) { # scan right to left\n hr[i] = max(tower[i],(i<n)?hr[i+1]:0)\n }\n for (i=0; i<=n; i++) { # scan left to right\n hl[i] = max(tower[i],(i!=0)?hl[i-1]:0)\n ans += min(hl[i],hr[i]) - tower[i]\n }\n printf(\"%4d : %s\\n\",ans,str)\n if (debug == 1) {\n for (i=1; i<=n; i++) { printf(\"%-4s\",tower[i]) } ; print(\"tower\")\n for (i=1; i<=n; i++) { printf(\"%-4s\",hl[i]) } ; print(\"l-r\")\n for (i=1; i<=n; i++) { printf(\"%-4s\",hr[i]) } ; print(\"r-l\")\n for (i=1; i<=n; i++) { printf(\"%-4s\",min(hl[i],hr[i])) } ; print(\"min\")\n for (i=1; i<=n; i++) { printf(\"%-4s\",min(hl[i],hr[i])-tower[i]) } ; print(\"sum\\n\")\n }\n}\nfunction max(x,y) { return((x > y) ? x : y) }\nfunction min(x,y) { return((x < y) ? x : y) }\n", "language": "AWK" }, { "code": "#include<stdlib.h>\n#include<stdio.h>\n\nint getWater(int* arr,int start,int end,int cutoff){\n\tint i, sum = 0;\n\t\n\tfor(i=start;i<=end;i++)\n\t\tsum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);\n\t\n\treturn sum;\n}\n\nint netWater(int* arr,int size){\n\tint i, j, ref1, ref2, marker, markerSet = 0,sum = 0;\n\t\n\tif(size<3)\n\t\treturn 0;\n\n\tfor(i=0;i<size-1;i++){\n\t\tstart:if(i!=size-2 && arr[i]>arr[i+1]){\n\t\t\t\tref1 = i;\n\t\t\t\t\n\t\t\t\tfor(j=ref1+1;j<size;j++){\n\t\t\t\t\tif(arr[j]>=arr[ref1]){\n\t\t\t\t\t\tref2 = j;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum += getWater(arr,ref1+1,ref2-1,ref1);\n\n\t\t\t\t\t\ti = ref2;\n\t\t\t\t\t\t\n\t\t\t\t\t\tgoto start;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){\n\t\t\t\t\t\tmarker = j+1;\n\t\t\t\t\t\tmarkerSet = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(markerSet==1){\n\t\t\t\t\tsum += getWater(arr,ref1+1,marker-1,marker);\n\n\t\t\t\t\ti = marker;\n\t\t\t\t\t\n\t\t\t\t\tmarkerSet = 0;\n\t\t\t\t\t\n\t\t\t\t\tgoto start;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\treturn sum;\n}\n\nint main(int argC,char* argV[])\n{\n\tint *arr,i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage : %s <followed by space separated series of integers>\");\n\telse{\n\t\tarr = (int*)malloc((argC-1)*sizeof(int));\n\t\t\n\t\tfor(i=1;i<argC;i++)\n\t\t\tarr[i-1] = atoi(argV[i]);\n\n\t\tprintf(\"Water collected : %d\",netWater(arr,argC-1));\n\t}\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector<int> b) {\n auto water = 0;\n const auto rows = *std::max_element(std::begin(b), std::end(b));\n const auto cols = std::size(b);\n std::vector<std::vector<int>> g(rows);\n for (auto& r : g) {\n for (auto i = 0; i < cols; ++i) {\n r.push_back(EMPTY);\n }\n }\n for (auto c = 0; c < cols; ++c) {\n for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n g[r][c] = WALL;\n }\n }\n for (auto c = 0; c < cols - 1; ++c) {\n auto start_row = rows - b[c];\n while (start_row < rows) {\n if (g[start_row][c] == EMPTY) break;\n auto c2 = c + 1;\n bool hitWall = false;\n while (c2 < cols) {\n if (g[start_row][c2] == WALL) {\n hitWall = true;\n break;\n }\n ++c2;\n }\n if (hitWall) {\n for (auto i = c + 1; i < c2; ++i) {\n g[start_row][i] = WATER;\n ++water;\n }\n }\n ++start_row;\n }\n }\n return water;\n}\n\nint main() {\n std::vector<std::vector<int>> b = {\n { 1, 5, 3, 7, 2 },\n { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n { 5, 5, 5, 5 },\n { 5, 6, 7, 8 },\n { 8, 7, 7, 6 },\n { 6, 7, 10, 7, 6 }\n };\n for (const auto v : b) {\n auto water = fill(v);\n std::cout << water << \" water drops.\" << std::endl;\n }\n std::cin.ignore();\n std::cin.get();\n return 0;\n}\n", "language": "C++" }, { "code": "class Program\n{\n static void Main(string[] args)\n {\n int[][] wta = {\n new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },\n new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};\n string blk, lf = \"\\n\", tb = \"██\", wr = \"≈≈\", mt = \" \";\n for (int i = 0; i < wta.Length; i++)\n {\n int bpf; blk = \"\"; do\n {\n string floor = \"\"; bpf = 0; for (int j = 0; j < wta[i].Length; j++)\n {\n if (wta[i][j] > 0)\n { floor += tb; wta[i][j] -= 1; bpf += 1; }\n else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);\n }\n if (bpf > 0) blk = floor + lf + blk;\n } while (bpf > 0);\n while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);\n while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);\n if (args.Length > 0) System.Console.Write(\"\\n{0}\", blk);\n System.Console.WriteLine(\"Block {0} retains {1,2} water units.\",\n i + 1, (blk.Length - blk.Replace(wr, \"\").Length) / 2);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "Block 1 retains 2 water units.\nBlock 2 retains 14 water units.\nBlock 3 retains 35 water units.\nBlock 4 retains 0 water units.\nBlock 5 retains 0 water units.\nBlock 6 retains 0 water units.\nBlock 7 retains 0 water units.\n", "language": "C-sharp" }, { "code": "class Program\n{\n// Variable names key:\n// i Iterator (of the tower block array).\n// tba Tower block array.\n// tea Tower elevation array.\n// rht Right hand tower column number (position).\n// wu Water units (count).\n// bof Blocks on floor (count).\n// col Column number in elevation array (position).\n\n static void Main(string[] args)\n {\n int i = 1; int[][] tba = {new int[] { 1, 5, 3, 7, 2 },\n new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },\n new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};\n foreach (int[] tea in tba)\n {\n int rht, wu = 0, bof; do\n {\n for (rht = tea.Length - 1; rht >= 0; rht--)\n if (tea[rht] > 0) break;\n if (rht < 0) break;\n bof = 0; for (int col = 0; col <= rht; col++)\n {\n if (tea[col] > 0) { tea[col] -= 1; bof += 1; }\n else if (bof > 0) wu++;\n }\n if (bof < 2) break;\n } while (true);\n System.Console.WriteLine(string.Format(\"Block {0} {1} water units.\",\n i++, wu == 0 ? \"does not hold any\" : \"holds \" + wu.ToString()));\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defn trapped-water [towers]\n (let [maxes #(reductions max %) ; the seq of increasing max values found in the input seq\n maxl (maxes towers) ; the seq of max heights to the left of each tower\n maxr (reverse (maxes (reverse towers))) ; the seq of max heights to the right of each tower\n mins (map min maxl maxr)] ; minimum highest surrounding tower per position\n (reduce + (map - mins towers)))) ; sum up the trapped water per position\n", "language": "Clojure" }, { "code": ";; in the following, # is a tower block and ~ is trapped water:\n;;\n;; 10|\n;; 9| #\n;; 8| #\n;; 7| # ~ ~ ~ ~ #\n;; 6| # ~ # ~ ~ #\n;; 5| # ~ # ~ # ~ # #\n;; 4| # ~ # ~ # # # #\n;; 3| # # # ~ # # # #\n;; 2| # # # # # # # # ~ #\n;; 1| # # # # # # # # # #\n;; ---+---------------------\n;; 5 3 7 2 6 4 5 9 1 2\n(trapped-water [5 3 7 2 6 4 5 9 1 2]) ;; 14\n", "language": "Clojure" }, { "code": "max = proc [T: type] (a,b: T) returns (T)\n where T has lt: proctype (T,T) returns (bool)\n if a<b then return(b)\n else return(a)\n end\nend max\n\n% based on: https://stackoverflow.com/a/42821623\nwater = proc (towers: sequence[int]) returns (int)\n si = sequence[int]\n\n w: int := 0\n left: int := 1\n right: int := si$size(towers)\n max_left: int := si$bottom(towers)\n max_right: int := si$top(towers)\n\n while left <= right do\n if towers[left] <= towers[right] then\n max_left := max[int](towers[left], max_left)\n w := w + max[int](max_left - towers[left], 0)\n left := left + 1\n else\n max_right := max[int](towers[right], max_right)\n w := w + max[int](max_right - towers[right], 0)\n right := right - 1\n end\n end\n return(w)\nend water\n\nstart_up = proc ()\n si = sequence[int]\n ssi = sequence[si]\n\n po: stream := stream$primary_output()\n\n tests: ssi := ssi$[\n si$[1, 5, 3, 7, 2],\n si$[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n si$[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n si$[5, 5, 5, 5],\n si$[5, 6, 7, 8],\n si$[8, 7, 7, 6],\n si$[6, 7, 10, 7, 6]\n ]\n\n for test: si in ssi$elements(tests) do\n stream$puts(po, int$unparse(water(test)) || \" \")\n end\nend start_up\n", "language": "CLU" }, { "code": "include \"cowgol.coh\";\ninclude \"argv.coh\";\n\n# Count the amount of water in a given array\nsub water(towers: [uint8], length: intptr): (units: uint8) is\n units := 0;\n loop\n var right := towers + length;\n loop\n right := @prev right;\n if right < towers or [right] != 0 then\n break;\n end if;\n end loop;\n if right < towers then break; end if;\n\n var blocks: uint8 := 0;\n var col := towers;\n while col <= right loop\n if [col] != 0 then\n [col] := [col] - 1;\n blocks := blocks + 1;\n elseif blocks != 0 then\n units := units + 1;\n end if;\n col := @next col;\n end loop;\n if blocks < 2 then\n break;\n end if;\n end loop;\nend sub;\n\n# Read list from the command line and print the answer\nArgvInit();\nvar towers: uint8[256];\nvar count: @indexof towers := 0;\nvar n32: int32;\nloop\n var argmt := ArgvNext();\n if argmt == 0 as [uint8] then\n break;\n end if;\n (n32, argmt) := AToI(argmt);\n towers[count] := n32 as uint8;\n count := count + 1;\nend loop;\n\nif count == 0 then\n print(\"enter towers on command line\\n\");\n ExitWithError();\nend if;\n\nprint_i8(water(&towers[0], count as intptr));\nprint_nl();\n", "language": "Cowgol" }, { "code": "import std.stdio;\n\nvoid main() {\n int i = 1;\n int[][] tba = [\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ]\n ];\n\n foreach (tea; tba) {\n int rht, wu, bof;\n do {\n for (rht = tea.length - 1; rht >= 0; rht--) {\n if (tea[rht] > 0) {\n break;\n }\n }\n\n if (rht < 0) {\n break;\n }\n\n bof = 0;\n for (int col = 0; col <= rht; col++) {\n if (tea[col] > 0) {\n tea[col] -= 1; bof += 1;\n } else if (bof > 0) {\n wu++;\n }\n }\n if (bof < 2) {\n break;\n }\n } while (true);\n\n write(\"Block \", i++);\n if (wu == 0) {\n write(\" does not hold any\");\n } else {\n write(\" holds \", wu);\n }\n writeln(\" water units.\");\n }\n}\n", "language": "D" }, { "code": "var Towers1: array [0..4] of integer = (1, 5, 3, 7, 2);\nvar Towers2: array [0..9] of integer = (5, 3, 7, 2, 6, 4, 5, 9, 1, 2);\nvar Towers3: array [0..15] of integer = (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1);\nvar Towers4: array [0..3] of integer = (5, 5, 5, 5);\nvar Towers5: array [0..3] of integer = (5, 6, 7, 8);\nvar Towers6: array [0..3] of integer = (8, 7, 7, 6);\nvar Towers7: array [0..4] of integer = (6, 7, 10, 7, 6);\n\n\ntype TMatrix = array of array of boolean;\n\nfunction ArrayToMatrix(Towers: array of integer): TMatrix;\n{Convert Tower Array to Matrix for analysis}\nvar Max,I,X,Y: integer;\nbegin\nMax:=0;\nfor I:=0 to High(Towers) do if Towers[I]>=Max then Max:=Towers[I];\nSetLength(Result,Length(Towers),Max);\nfor Y:=0 to High(Result[0]) do\n for X:=0 to High(Result) do Result[X,Y]:=Towers[X]>(Max-Y);\nend;\n\n\nprocedure DisplayMatrix(Memo: TMemo; Matrix: TMatrix);\n{Display a matrix}\nvar X,Y: integer;\nvar S: string;\nbegin\nfor Y:=0 to High(Matrix[0]) do\n\tbegin\n\tS:='[';\n\tfor X:=0 to High(Matrix) do\n\t\tbegin\n\t\tif Matrix[X,Y] then S:=S+'#'\n\t\telse S:=S+' ';\n\t\tend;\n\tS:=S+']';\n\tMemo.Lines.Add(S);\n\tend;\nend;\n\n\nfunction GetWaterStorage(Matrix: TMatrix): integer;\n{Analyze matrix to get water storage amount}\nvar X,Y,Cnt: integer;\nvar Inside: boolean;\nbegin\nResult:=0;\n{Scan each row of matrix to see if it is storing water}\nfor Y:=0 to High(Matrix[0]) do\n\tbegin\n\tInside:=False;\n\tCnt:=0;\n \tfor X:=0 to High(Matrix) do\n\t\tbegin\n\t\t{Test if this is a tower}\n\t\tif Matrix[X,Y] then\n\t\t\tbegin\n\t\t\t{if so, we may be inside trough}\n\t\t\tInside:=True;\n\t\t\t{If Cnt>0 there was a previous tower}\n\t\t\t{And we've impounded water }\n\t\t\tResult:=Result+Cnt;\n\t\t\t{Start new count with new tower}\n\t\t\tCnt:=0;\n\t\t\tend\n\t\telse if Inside then Inc(Cnt);\t{Count potential impounded water}\n\t\tend;\n\tend;\nend;\n\n\nprocedure ShowWaterLevels(Memo: TMemo; Towers: array of integer);\n{Analyze the water storage of towers and display result}\nvar Water: integer;\nvar Matrix: TMatrix;\nbegin\nMatrix:=ArrayToMatrix(Towers);\nDisplayMatrix(Memo,Matrix);\nWater:=GetWaterStorage(Matrix);\nMemo.Lines.Add('Storage: '+IntToStr(Water)+CRLF);\nend;\n\n\nprocedure WaterLevel(Memo: TMemo);\nbegin\nShowWaterLevels(Memo,Towers1);\nShowWaterLevels(Memo,Towers2);\nShowWaterLevels(Memo,Towers3);\nShowWaterLevels(Memo,Towers4);\nShowWaterLevels(Memo,Towers5);\nShowWaterLevels(Memo,Towers6);\nShowWaterLevels(Memo,Towers7);\nend;\n", "language": "Delphi" }, { "code": "proc water h[] . .\n n = len h[]\n len left[] n\n len right[] n\n for i = 1 to n\n max = higher max h[i]\n left[i] = max\n .\n max = 0\n for i = n downto 1\n max = higher max h[i]\n right[i] = max\n .\n for i = 1 to n\n sum += (lower left[i] right[i]) - h[i]\n .\n print sum\n.\nrepeat\n s$ = input\n until s$ = \"\"\n water number strsplit s$ \" \"\n.\n#\ninput_data\n1 5 3 7 2\n5 3 7 2 6 4 5 9 1 2\n2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1\n5 5 5 5\n5 6 7 8\n8 7 7 6\n6 7 10 7 6\n", "language": "EasyLang" }, { "code": "-module(watertowers).\n-export([towers/1, demo/0]).\n\ntowers(List) -> element(2, tower(List, 0)).\n\ntower([], _) -> {0,0};\ntower([H|T], MaxLPrev) ->\n MaxL = max(MaxLPrev, H),\n {MaxR, WaterAcc} = tower(T, MaxL),\n {max(MaxR,H), WaterAcc+max(0, min(MaxR,MaxL)-H)}.\n\ndemo() ->\n Cases = [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]],\n [io:format(\"~p -> ~p~n\", [Case, towers(Case)]) || Case <- Cases],\n ok.\n", "language": "Erlang" }, { "code": "(*\nA solution I'd show to Euclid !!!!.\nNigel Galloway May 4th., 2017\n*)\nlet solve n =\n let (n,_)::(i,e)::g = n|>List.sortBy(fun n->(-(snd n)))\n let rec fn i g e l =\n match e with\n | (n,e)::t when n < i -> fn n g t (l+(i-n-1)*e)\n | (n,e)::t when n > g -> fn i n t (l+(n-g-1)*e)\n | (n,t)::e -> fn i g e (l-t)\n | _ -> l\n fn (min n i) (max n i) g (e*(abs(n-i)-1))\n", "language": "F-Sharp" }, { "code": "USING: formatting kernel math.statistics math.vectors sequences ;\n\n: area ( seq -- n )\n [ cum-max ] [ <reversed> cum-max reverse vmin ] [ v- sum ] tri ;\n\n{\n { 1 5 3 7 2 }\n { 5 3 7 2 6 4 5 9 1 2 }\n { 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 }\n { 5 5 5 5 }\n { 5 6 7 8 }\n { 8 7 7 6 }\n { 6 7 10 7 6 }\n} [ dup area \"%[%d, %] -> %d\\n\" printf ] each\n", "language": "Factor" }, { "code": "type tower\n hght as uinteger\n posi as uinteger\nend type\n\nsub shellsort( a() as tower )\n 'quick and dirty shellsort, not the focus of this exercise\n dim as uinteger gap = ubound(a), i, j, n=ubound(a)\n dim as tower temp\n do\n gap = int(gap / 2.2)\n if gap=0 then gap=1\n for i=gap to n\n temp = a(i)\n j=i\n while j>=gap andalso a(j-gap).hght < temp.hght\n a(j) = a(j - gap)\n j -= gap\n wend\n a(j) = temp\n next i\n loop until gap = 1\nend sub\n\n'heights of towers in each city prefixed by the number of towers\ndata 5, 1, 5, 3, 7, 2\ndata 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2\ndata 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1\ndata 4, 5, 5, 5, 5\ndata 4, 5, 6, 7, 8\ndata 4, 8, 7, 7, 6\ndata 5, 6, 7, 10, 7, 6\n\ndim as uinteger i, n, j, first, last, water\ndim as tower manhattan(0 to 1)\nfor i = 1 to 7\n read n\n redim manhattan( 0 to n-1 )\n for j = 0 to n-1\n read manhattan(j).hght\n manhattan(j).posi = j\n next j\n shellsort( manhattan() )\n if manhattan(0).posi < manhattan(1).posi then\n first = manhattan(0).posi\n last = manhattan(1).posi\n else\n first = manhattan(1).posi\n last = manhattan(0).posi\n end if\n water = manhattan(1).hght * (last-first-1)\n for j = 2 to n-1\n if first<manhattan(j).posi and manhattan(j).posi<last then water -= manhattan(j).hght\n if manhattan(j).posi < first then\n water += manhattan(j).hght * (first-manhattan(j).posi-1)\n first = manhattan(j).posi\n end if\n if manhattan(j).posi > last then\n water += manhattan(j).hght * (manhattan(j).posi-last-1)\n last = manhattan(j).posi\n end if\n next j\n print using \"City configuration ## collected #### units of water.\"; i; water\nnext i\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc maxl(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := 0; i < len(hm);i++{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc maxr(hm []int ) []int{\n\tres := make([]int,len(hm))\n\tmax := 1\n\tfor i := len(hm) - 1 ; i >= 0;i--{\n\t\tif(hm[i] > max){\n\t\t\tmax = hm[i]\n\t\t}\n\t\tres[i] = max;\n\t}\n\treturn res\n}\nfunc min(a,b []int) []int {\n\tres := make([]int,len(a))\n\tfor i := 0; i < len(a);i++{\n\t\tif a[i] >= b[i]{\n\t\t\tres[i] = b[i]\n\t\t}else {\n\t\t\tres[i] = a[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc diff(hm, min []int) []int {\n\tres := make([]int,len(hm))\n\tfor i := 0; i < len(hm);i++{\n\t\tif min[i] > hm[i]{\n\t\t\tres[i] = min[i] - hm[i]\n\t\t}\n\t}\n\treturn res\n}\nfunc sum(a []int) int {\n\tres := 0\n\tfor i := 0; i < len(a);i++{\n\t\tres += a[i]\n\t}\n\treturn res\n}\n\nfunc waterCollected(hm []int) int {\n\tmaxr := maxr(hm)\n\tmaxl := maxl(hm)\n\tmin := min(maxr,maxl)\n\tdiff := diff(hm,min)\n\tsum := sum(diff)\n\treturn sum\n}\n\n\nfunc main() {\n\tfmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))\n\tfmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))\n\tfmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))\n\tfmt.Println(waterCollected([]int{5, 5, 5, 5}))\n\tfmt.Println(waterCollected([]int{5, 6, 7, 8}))\n\tfmt.Println(waterCollected([]int{8, 7, 7, 6}))\n\tfmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))\n}\n", "language": "Go" }, { "code": "Integer waterBetweenTowers(List<Integer> towers) {\n // iterate over the vertical axis. There the amount of water each row can hold is\n // the number of empty spots, minus the empty spots at the beginning and end\n return (1..towers.max()).collect { height ->\n // create a string representing the row, '#' for tower material and ' ' for air\n // use .trim() to remove spaces at beginning and end and then count remaining spaces\n towers.collect({ it >= height ? \"#\" : \" \" }).join(\"\").trim().count(\" \")\n }.sum()\n}\n\ntasks = [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n]\n\ntasks.each {\n println \"$it => total water: ${waterBetweenTowers it}\"\n}\n", "language": "Groovy" }, { "code": "10 DEFINT A-Z: DIM T(20): K=0\n20 K=K+1: READ N: IF N=0 THEN END\n30 FOR I=0 TO N-1: READ T(I): NEXT\n40 W=0\n50 FOR R=N-1 TO 0 STEP -1: IF T(R)=0 THEN NEXT ELSE IF R=0 THEN 110\n60 B=0\n70 FOR C=0 TO R\n80 IF T(C)>0 THEN T(C)=T(C)-1: B=B+1 ELSE IF B>0 THEN W=W+1\n90 NEXT\n100 IF B>1 THEN 50\n110 PRINT \"Block\";K;\"holds\";W;\"water units.\"\n120 GOTO 20\n130 DATA 5, 1,5,3,7,2\n140 DATA 10, 5,3,7,2,6,4,5,9,1,2\n150 DATA 16, 2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\n160 DATA 4, 5,5,5,5\n170 DATA 4, 5,6,7,8\n180 DATA 4, 8,7,7,6\n190 DATA 5, 6,7,10,7,6\n200 DATA 0\n", "language": "GW-BASIC" }, { "code": "import Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Unboxed as V\n\nwaterCollected :: Vector Int -> Int\nwaterCollected =\n V.sum . -- Sum of the water depths over each of\n V.filter (> 0) . -- the columns that are covered by some water.\n (V.zipWith (-) =<< -- Where coverages are differences between:\n (V.zipWith min . -- the lower water level in each case of:\n V.scanl1 max <*> -- highest wall to left, and\n V.scanr1 max)) -- highest wall to right.\n\nmain :: IO ()\nmain =\n mapM_\n (print . waterCollected . V.fromList)\n [ [1, 5, 3, 7, 2]\n , [5, 3, 7, 2, 6, 4, 5, 9, 1, 2]\n , [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1]\n , [5, 5, 5, 5]\n , [5, 6, 7, 8]\n , [8, 7, 7, 6]\n , [6, 7, 10, 7, 6]\n ]\n", "language": "Haskell" }, { "code": "import Data.List (replicate, transpose)\n\n-------------- WATER COLLECTED BETWEEN TOWERS ------------\n\ntowerPools :: [Int] -> [(Int, Int)]\ntowerPools =\n zipWith min . scanl1 max <*> scanr1 max\n >>= zipWith ((<*>) (,) . (-))\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n mapM_\n (putStrLn . display . towerPools)\n [ [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n ]\n\n------------------------- DIAGRAMS -----------------------\n\ndisplay :: [(Int, Int)] -> String\ndisplay = (<>) . showTowers <*> (('\\n' :) . showLegend)\n\nshowTowers :: [(Int, Int)] -> String\nshowTowers xs =\n let upper = maximum (fst <$> xs)\n in '\\n' :\n ( unlines\n . transpose\n . fmap\n ( \\(x, d) ->\n concat $\n replicate (upper - (x + d)) \" \"\n <> replicate d \"x\"\n <> replicate x \"█\"\n )\n )\n xs\n\nshowLegend :: [(Int, Int)] -> String\nshowLegend =\n ((<>) . show . fmap fst)\n <*> ((\" -> \" <>) . show . foldr ((+) . snd) 0)\n", "language": "Haskell" }, { "code": "collectLevels =: >./\\ <. >./\\. NB. collect levels after filling\nwaterLevels=: collectLevels - ] NB. water levels for each tower\ncollectedWater=: +/@waterLevels NB. sum the units of water collected\nprintTowers =: ' ' , [: |.@|: '#~' #~ ] ,. waterLevels NB. print a nice graph of towers and water\n", "language": "J" }, { "code": " collectedWater 5 3 7 2 6 4 5 9 1 2\n14\n printTowers 5 3 7 2 6 4 5 9 1 2\n\n #\n #\n #~~~~#\n #~#~~#\n#~#~#~##\n#~#~####\n###~####\n########~#\n##########\n\nNB. Test cases\n TestTowers =: <@\".;._2 noun define\n1 5 3 7 2\n5 3 7 2 6 4 5 9 1 2\n2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1\n5 5 5 5\n5 6 7 8\n8 7 7 6\n6 7 10 7 6\n)\n TestResults =: 2 14 35 0 0 0 0\n TestResults -: collectedWater &> TestTowers NB. check tests\n1\n", "language": "J" }, { "code": "public class WaterBetweenTowers {\n public static void main(String[] args) {\n int i = 1;\n int[][] tba = new int[][]{\n new int[]{1, 5, 3, 7, 2},\n new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n new int[]{5, 5, 5, 5},\n new int[]{5, 6, 7, 8},\n new int[]{8, 7, 7, 6},\n new int[]{6, 7, 10, 7, 6}\n };\n\n for (int[] tea : tba) {\n int rht, wu = 0, bof;\n do {\n for (rht = tea.length - 1; rht >= 0; rht--) {\n if (tea[rht] > 0) {\n break;\n }\n }\n\n if (rht < 0) {\n break;\n }\n\n bof = 0;\n for (int col = 0; col <= rht; col++) {\n if (tea[col] > 0) {\n tea[col]--;\n bof += 1;\n } else if (bof > 0) {\n wu++;\n }\n }\n if (bof < 2) {\n break;\n }\n } while (true);\n\n System.out.printf(\"Block %d\", i++);\n if (wu == 0) {\n System.out.print(\" does not hold any\");\n } else {\n System.out.printf(\" holds %d\", wu);\n }\n System.out.println(\" water units.\");\n }\n }\n}\n", "language": "Java" }, { "code": "(function () {\n 'use strict';\n\n // waterCollected :: [Int] -> Int\n var waterCollected = function (xs) {\n return sum( // water above each bar\n zipWith(function (a, b) {\n return a - b; // difference between water level and bar\n },\n zipWith(min, // lower of two flanking walls\n scanl1(max, xs), // highest walls to left\n scanr1(max, xs) // highest walls to right\n ),\n xs // tops of bars\n )\n .filter(function (x) {\n return x > 0; // only bars with water above them\n })\n );\n };\n\n // GENERIC FUNCTIONS ----------------------------------------\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n var zipWith = function (f, xs, ys) {\n var ny = ys.length;\n return (xs.length <= ny ? xs : xs.slice(0, ny))\n .map(function (x, i) {\n return f(x, ys[i]);\n });\n };\n\n // scanl1 is a variant of scanl that has no starting value argument\n // scanl1 :: (a -> a -> a) -> [a] -> [a]\n var scanl1 = function (f, xs) {\n return xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : [];\n };\n\n // scanr1 is a variant of scanr that has no starting value argument\n // scanr1 :: (a -> a -> a) -> [a] -> [a]\n var scanr1 = function (f, xs) {\n return xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : [];\n };\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n var scanl = function (f, startValue, xs) {\n var lst = [startValue];\n return xs.reduce(function (a, x) {\n var v = f(a, x);\n return lst.push(v), v;\n }, startValue), lst;\n };\n\n // scanr :: (b -> a -> b) -> b -> [a] -> [b]\n var scanr = function (f, startValue, xs) {\n var lst = [startValue];\n return xs.reduceRight(function (a, x) {\n var v = f(a, x);\n return lst.push(v), v;\n }, startValue), lst.reverse();\n };\n\n // sum :: (Num a) => [a] -> a\n var sum = function (xs) {\n return xs.reduce(function (a, x) {\n return a + x;\n }, 0);\n };\n\n // max :: Ord a => a -> a -> a\n var max = function (a, b) {\n return a > b ? a : b;\n };\n\n // min :: Ord a => a -> a -> a\n var min = function (a, b) {\n return b < a ? b : a;\n };\n\n // TEST ---------------------------------------------------\n return [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n ].map(waterCollected);\n\n //--> [2, 14, 35, 0, 0, 0, 0]\n})();\n", "language": "JavaScript" }, { "code": "[2, 14, 35, 0, 0, 0, 0]\n", "language": "JavaScript" }, { "code": "(() => {\n \"use strict\";\n\n // --------- WATER COLLECTED BETWEEN TOWERS ----------\n\n // waterCollected :: [Int] -> Int\n const waterCollected = xs =>\n sum(filter(lt(0))(\n zipWith(subtract)(xs)(\n zipWith(min)(\n scanl1(max)(xs)\n )(\n scanr1(max)(xs)\n )\n )\n ));\n\n\n // ---------------------- TEST -----------------------\n const main = () => [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n ].map(waterCollected);\n\n\n // --------------------- GENERIC ---------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: \"Tuple\",\n \"0\": a,\n \"1\": b,\n length: 2\n });\n\n\n // filter :: (a -> Bool) -> [a] -> [a]\n const filter = p =>\n // The elements of xs which match\n // the predicate p.\n xs => [...xs].filter(p);\n\n\n // lt (<) :: Ord a => a -> a -> Bool\n const lt = a =>\n b => a < b;\n\n\n // max :: Ord a => a -> a -> a\n const max = a =>\n // b if its greater than a,\n // otherwise a.\n b => a > b ? a : b;\n\n\n // min :: Ord a => a -> a -> a\n const min = a =>\n b => b < a ? b : a;\n\n\n // scanl :: (b -> a -> b) -> b -> [a] -> [b]\n const scanl = f => startValue => xs =>\n xs.reduce((a, x) => {\n const v = f(a[0])(x);\n\n return Tuple(v)(a[1].concat(v));\n }, Tuple(startValue)([startValue]))[1];\n\n\n // scanl1 :: (a -> a -> a) -> [a] -> [a]\n const scanl1 = f =>\n // scanl1 is a variant of scanl that\n // has no starting value argument.\n xs => xs.length > 0 ? (\n scanl(f)(\n xs[0]\n )(xs.slice(1))\n ) : [];\n\n\n // scanr :: (a -> b -> b) -> b -> [a] -> [b]\n const scanr = f =>\n startValue => xs => xs.reduceRight(\n (a, x) => {\n const v = f(x)(a[0]);\n\n return Tuple(v)([v].concat(a[1]));\n }, Tuple(startValue)([startValue])\n )[1];\n\n\n // scanr1 :: (a -> a -> a) -> [a] -> [a]\n const scanr1 = f =>\n // scanr1 is a variant of scanr that has no\n // seed-value argument, and assumes that\n // xs is not empty.\n xs => xs.length > 0 ? (\n scanr(f)(\n xs.slice(-1)[0]\n )(xs.slice(0, -1))\n ) : [];\n\n\n // subtract :: Num -> Num -> Num\n const subtract = x =>\n y => y - x;\n\n\n // sum :: [Num] -> Num\n const sum = xs =>\n // The numeric sum of all values in xs.\n xs.reduce((a, x) => a + x, 0);\n\n\n // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\n const zipWith = f =>\n // A list constructed by zipping with a\n // custom function, rather than with the\n // default tuple constructor.\n xs => ys => xs.map(\n (x, i) => f(x)(ys[i])\n ).slice(\n 0, Math.min(xs.length, ys.length)\n );\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "[2, 14, 35, 0, 0, 0, 0]\n", "language": "JavaScript" }, { "code": "def waterCollected:\n . as $tower\n | ($tower|length) as $n\n | ([0] + [range(1;$n) | ($tower[0:.] | max) ]) as $highLeft\n | ( [range(1;$n) | ($tower[.:$n] | max) ] + [0]) as $highRight\n | [ range(0;$n) | [ ([$highLeft[.], $highRight[.] ]| min) - $tower[.], 0 ] | max]\n | add ;\n\ndef towers: [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n];\n\ntowers[]\n| \"\\(waterCollected) from \\(.)\"\n", "language": "Jq" }, { "code": "using Printf\n\nfunction watercollected(towers::Vector{Int})\n high_lft = vcat(0, accumulate(max, towers[1:end-1]))\n high_rgt = vcat(reverse(accumulate(max, towers[end:-1:2])), 0)\n waterlvl = max.(min.(high_lft, high_rgt) .- towers, 0)\n return waterlvl\nend\n\nfunction towerprint(towers, levels)\n ctowers = copy(towers)\n clevels = copy(levels)\n hmax = maximum(towers)\n ntow = length(towers)\n for h in hmax:-1:1\n @printf(\"%2i |\", h)\n for j in 1:ntow\n if ctowers[j] + clevels[j] ≥ h\n if clevels[j] > 0\n cell = \"≈≈\"\n clevels[j] -= 1\n else\n cell = \"NN\"\n ctowers[j] -= 1\n end\n else\n cell = \" \"\n end\n print(cell)\n end\n println(\"|\")\n end\n\n\n println(\" \" * join(lpad(t, 2) for t in levels) * \": Water lvl\")\n println(\" \" * join(lpad(t, 2) for t in towers) * \": Tower lvl\")\nend\n\nfor towers in [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]]\n towerprint(towers, watercollected(towers))\n println()\nend\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nfun waterCollected(tower: IntArray): Int {\n val n = tower.size\n val highLeft = listOf(0) + (1 until n).map { tower.slice(0 until it).max()!! }\n val highRight = (1 until n).map { tower.slice(it until n).max()!! } + 0\n return (0 until n).map { maxOf(minOf(highLeft[it], highRight[it]) - tower[it], 0) }.sum()\n}\n\nfun main(args: Array<String>) {\n val towers = listOf(\n intArrayOf(1, 5, 3, 7, 2),\n intArrayOf(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),\n intArrayOf(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),\n intArrayOf(5, 5, 5, 5),\n intArrayOf(5, 6, 7, 8),\n intArrayOf(8, 7, 7, 6),\n intArrayOf(6, 7, 10, 7, 6)\n )\n for (tower in towers) {\n println(\"${\"%2d\".format(waterCollected(tower))} from ${tower.contentToString()}\")\n }\n}\n", "language": "Kotlin" }, { "code": "function waterCollected(i,tower)\n local length = 0\n for _ in pairs(tower) do\n length = length + 1\n end\n\n local wu = 0\n repeat\n local rht = length - 1\n while rht >= 0 do\n if tower[rht + 1] > 0 then\n break\n end\n rht = rht - 1\n end\n if rht < 0 then\n break\n end\n\n local bof = 0\n local col = 0\n while col <= rht do\n if tower[col + 1] > 0 then\n tower[col + 1] = tower[col + 1] - 1\n bof = bof + 1\n elseif bof > 0 then\n wu = wu + 1\n end\n col = col + 1\n end\n if bof < 2 then\n break\n end\n until false\n if wu == 0 then\n print(string.format(\"Block %d does not hold any water.\", i))\n else\n print(string.format(\"Block %d holds %d water units.\", i, wu))\n end\nend\n\nfunction main()\n local towers = {\n {1, 5, 3, 7, 2},\n {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n {5, 5, 5, 5},\n {5, 6, 7, 8},\n {8, 7, 7, 6},\n {6, 7, 10, 7, 6}\n }\n\n for i,tbl in pairs(towers) do\n waterCollected(i,tbl)\n end\nend\n\nmain()\n", "language": "Lua" }, { "code": "Module Water {\n Flush ' empty stack\n Data (1, 5, 3, 7, 2)\n Data (5, 3, 7, 2, 6, 4, 5, 9, 1, 2)\n Data (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)\n Data (5, 5, 5, 5), (5, 6, 7, 8),(8, 7, 7, 6)\n Data (6, 7, 10, 7, 6)\n bars=stack.size ' mark stack frame\n Dim bar()\n for bar=1 to bars\n bar()=Array ' pop an array from stack\n acc=0\n For i=1 to len(bar())-2\n level1=bar(i)\n level2=level1\n m=each(bar(), i+1, 1)\n while m\n if array(m)>level1 then level1=array(m)\n End While\n n=each(bar(), i+1, -1)\n while n\n if array(n)>level2 then level2=array(n)\n End While\n acc+=max.data(min(level1, level2)-bar(i), 0)\n Next i\n Data acc ' push to end value\n Next bar\n finalwater=[] ' is a stack object\n Print finalwater\n}\nWater\n", "language": "M2000-Interpreter" }, { "code": "", "language": "M2000-Interpreter" }, { "code": "Module Water3 {\n Flush ' empty stack\n Data (1, 5, 3, 7, 2)\n Data (5, 3, 7, 2, 6, 4, 5, 9, 1, 2)\n Data (2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)\n Data (5, 5, 5, 5), (5, 6, 7, 8),(8, 7, 7, 6)\n Data (6, 7, 10, 7, 6)\n bars=stack.size ' mark stack frame\n Dim bar()\n for bar=1 to bars\n bar()=Array ' pop an array from stack\n acc=0\n n=len(bar())-1\n dim hl(n+1), hr(n+1)\n For i=n to 0\n hr(i)=max.data(bar(i), if(i<n->hr(i+1), 0))\n Next i\n For i=0 to n\n hl(i)=max.data(bar(i), if(i>0->hl(i-1), 0))\n acc+=min.data(hl(i), hr(i))-bar(i)\n Next i\n Data acc ' push to end value\n Next bar\n finalwater=[] ' is a stack object\n Print finalwater\n}\nWater3\n", "language": "M2000-Interpreter" }, { "code": "ClearAll[waterbetween]\nwaterbetween[h_List] := Module[{mi, ma, ch},\n {mi, ma} = MinMax[h];\n Sum[\n ch = h - i;\n Count[\n Flatten@\n Position[\n ch, _?Negative], _?(Between[\n MinMax[Position[ch, _?NonNegative]]])]\n ,\n {i, mi + 1, ma}\n ]\n ]\nh = {{1, 5, 3, 7, 2}, {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, {2, 6, 3, 5, 2,\n 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, {5, 5, 5, 5}, {5, 6, 7, 8}, {8,\n 7, 7, 6}, {6, 7, 10, 7, 6}};\nwaterbetween /@ h\n", "language": "Mathematica" }, { "code": "10 REM Water collected between towers\n20 MXN=19\n30 REM Heights of towers in each city\n40 REM prefixed by the number of towers\n50 DATA 5,1,5,3,7,2\n60 DATA 10,5,3,7,2,6,4,5,9,1,2\n70 DATA 16,2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\n80 DATA 4,5,5,5,5\n90 DATA 4,5,6,7,8\n100 DATA 4,8,7,7,6\n110 DATA 5,6,7,10,7,6\n120 DIM A(MXN,1)\n130 FOR I=1 TO 7\n140 READ N\n150 FOR J=0 TO N-1\n160 READ A(J,0)\n170 A(J,1)=J\n180 NEXT J\n190 GOSUB 390\n200 IF A(0,1)>=A(1,1) THEN 220\n210 FRST=A(0,1):LST=A(1,1):GOTO 230\n220 FRST=A(1,1):LST=A(0,1)\n230 WTR=A(1,0)*(LST-FRST-1)\n240 FOR J=2 TO N-1\n250 IF FRST>=A(J,1) OR A(J,1)>=LST THEN 270\n260 WTR=WTR-A(J,0)\n270 IF A(J,1)>=FRST THEN 300\n280 WTR=WTR+A(J,0)*(FRST-A(J,1)-1)\n290 FRST=A(J,1)\n300 IF A(J,1)<=LST THEN 330\n310 WTR=WTR+A(J,0)*(A(J,1)-LST-1)\n320 LST=A(J,1)\n330 NEXT J\n340 PRINT \"Bar chart\";I;\"collected\";\n350 PRINT WTR;\"units of water.\"\n360 NEXT I\n370 END\n380 REM ** ShellSort\n390 GAP=N-1\n400 GAP=INT(GAP/2.2)\n410 IF GAP=0 THEN GAP=1\n420 FOR K=GAP TO N-1\n430 TH=A(K,0):TP=A(K,1)\n440 L=K\n450 IF L<GAP THEN 500\n460 IF A(L-GAP,0)>=TH THEN 500\n470 A(L,0)=A(L-GAP,0):A(L,1)=A(L-GAP,1)\n480 L=L-GAP\n490 GOTO 450\n500 A(L,0)=TH:A(L,1)=TP\n510 NEXT K\n520 IF GAP<>1 THEN 400\n530 RETURN\n", "language": "Nascom-BASIC" }, { "code": "import math, sequtils, sugar\n\nproc water(barChart: seq[int], isLeftPeak = false, isRightPeak = false): int =\n if len(barChart) <= 2:\n return\n if isLeftPeak and isRightPeak:\n return sum(barChart[1..^2].map(x=>min(barChart[0], barChart[^1])-x))\n var i: int\n if isLeftPeak:\n i = maxIndex(barChart[1..^1])+1\n else:\n i = maxIndex(barChart[0..^2])\n return water(barChart[0..i], isLeftPeak, true)+water(barChart[i..^1], true, isRightPeak)\n\nconst barCharts = [\n @[1, 5, 3, 7, 2],\n @[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n @[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n @[5, 5, 5, 5],\n @[5, 6, 7, 8],\n @[8, 7, 7, 6],\n @[6, 7, 10, 7, 6]]\nconst waterUnits = barCharts.map(chart=>water(chart, false, false))\necho(waterUnits)\n", "language": "Nim" }, { "code": "program RainInFlatland;\n\n{$IFDEF FPC} // Free Pascal\n {$MODE Delphi}\n{$ELSE} // Delphi\n {$APPTYPE CONSOLE}\n{$ENDIF}\n\nuses SysUtils;\ntype THeight = integer;\n// Heights could be f.p., but some changes to the code would be needed:\n// (1) the inc function isn't available for f.p. values,\n// (2) the print-out would need extra formatting.\n\n{------------------------------------------------------------------------------\nFind highest tower; if there are 2 or more equal highest, choose any.\nThen fill troughs so that on going towards the highest tower, from the\n left-hand or right-hand end, there are no steps down.\nAmount of filling required equals amount of water collected.\n}\nfunction FillTroughs( const h : array of THeight) : THeight;\nvar\n m, i, i_max : integer;\n h_max : THeight;\nbegin\n result := 0;\n m := High( h); // highest index, 0-based; there are m + 1 towers\n if (m <= 1) then exit; // result = 0 if <= 2 towers\n\n // Find highest tower and its index in the array.\n h_max := h[0];\n i_max := 0;\n for i := 1 to m do begin\n if h[i] > h_max then begin\n h_max := h[i];\n i_max := i;\n end;\n end;\n // Fill troughs from left-hand end to highest tower\n h_max := h[0];\n for i := 1 to i_max - 1 do begin\n if h[i] < h_max then inc( result, h_max - h[i])\n else h_max := h[i];\n end;\n // Fill troughs from right-hand end to highest tower\n h_max := h[m];\n for i := m - 1 downto i_max + 1 do begin\n if h[i] < h_max then inc( result, h_max - h[i])\n else h_max := h[i];\n end;\nend;\n\n{-------------------------------------------------------------------------\nWrapper for the above: finds amount of water, and prints input and result.\n}\nprocedure CalcAndPrint( h : array of THeight);\nvar\n water : THeight;\n j : integer;\nbegin\n water := FillTroughs( h);\n Write( water:5, ' <-- [');\n for j := 0 to High( h) do begin\n Write( h[j]);\n if j < High(h) then Write(', ') else WriteLn(']');\n end;\nend;\n\n{---------------------------------------------------------------------------\nMain routine.\n}\nbegin\n CalcAndPrint([1,5,3,7,2]);\n CalcAndPrint([5,3,7,2,6,4,5,9,1,2]);\n CalcAndPrint([2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1]);\n CalcAndPrint([5,5,5,5]);\n CalcAndPrint([5,6,7,8]);\n CalcAndPrint([8,7,7,6]);\n CalcAndPrint([6,7,10,7,6]);\nend.\n", "language": "Pascal" }, { "code": "use Modern::Perl;\nuse List::Util qw{ min max sum };\n\nsub water_collected {\n my @t = map { { TOWER => $_, LEFT => 0, RIGHT => 0, LEVEL => 0 } } @_;\n\n my ( $l, $r ) = ( 0, 0 );\n $_->{LEFT} = ( $l = max( $l, $_->{TOWER} ) ) for @t;\n $_->{RIGHT} = ( $r = max( $r, $_->{TOWER} ) ) for reverse @t;\n $_->{LEVEL} = min( $_->{LEFT}, $_->{RIGHT} ) for @t;\n\n return sum map { $_->{LEVEL} > 0 ? $_->{LEVEL} - $_->{TOWER} : 0 } @t;\n}\n\nsay join ' ', map { water_collected( @{$_} ) } (\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ],\n);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">collect_water</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]),</span>\n <span style=\"color: #000000;\">rm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$]),</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rm</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">tests</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">ti</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tests</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%35s : %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">collect_water</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ti</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">collect_water</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">left_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">right_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[$]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">left_height</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">right_height</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">left_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">left_max</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">left_height</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">left_max</span>\n <span style=\"color: #000000;\">right_max</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">right_max</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">right_height</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">right_max</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mins</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">left_height</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">right_height</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">diffs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mins</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">diffs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.2\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (bugfix in p2js.js/$sidii(), 20/4/22)</span>\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">print_water</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">towers</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">' '</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">towers</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'#'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]),</span>\n <span style=\"color: #000000;\">rm</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$]),</span>\n <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lm</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rm</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">heights</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">towers</span><span style=\"color: #0000FF;\">[-</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'~'</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\\ncollected:%d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">towers</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">print_water</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\ndef collect_water\n 0 var res\n len 1 - 2 swap 2 tolist\n for\n var i\n 1 i 1 - slice max >ps\n len i - 1 + i swap slice max >ps\n i get ps> ps> min swap -\n 0 max res + var res\n endfor\n drop\n res\nenddef\n\n( ( 1 5 3 7 2 )\n ( 5 3 7 2 6 4 5 9 1 2 )\n ( 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 )\n ( 5 5 5 5 )\n ( 5 6 7 8 )\n ( 8 7 7 6 )\n ( 6 7 10 7 6 ) )\n\nlen for\n get dup print \" : \" print collect_water ?\nendfor\n", "language": "Phixmonti" }, { "code": "(de water (Lst)\n (sum\n '((A)\n (cnt\n nT\n (clip (mapcar '((B) (>= B A)) Lst)) ) )\n (range 1 (apply max Lst)) ) )\n(println\n (mapcar\n water\n (quote\n (1 5 3 7 2)\n (5 3 7 2 6 4 5 9 1 2)\n (2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1)\n (5 5 5 5)\n (5 6 7 8)\n (8 7 7 6)\n (6 7 10 7 6) ) ) )\n", "language": "PicoLisp" }, { "code": "def water_collected(tower):\n N = len(tower)\n highest_left = [0] + [max(tower[:n]) for n in range(1,N)]\n highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]\n water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)\n for n in range(N)]\n print(\"highest_left: \", highest_left)\n print(\"highest_right: \", highest_right)\n print(\"water_level: \", water_level)\n print(\"tower_level: \", tower)\n print(\"total_water: \", sum(water_level))\n print(\"\")\n return sum(water_level)\n\ntowers = [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n[water_collected(tower) for tower in towers]\n", "language": "Python" }, { "code": "'''Water collected between towers'''\n\nfrom itertools import accumulate\nfrom functools import reduce\nfrom operator import add\n\n\n# ---------------------- TOWER POOLS -----------------------\n\n# towerPools :: [Int] -> [(Int, Int)]\ndef towerPools(towers):\n '''Tower heights with water depths.\n '''\n def towerAndWater(level, tower):\n return tower, level - tower\n\n waterlevels = map(\n min,\n accumulate(towers, max),\n reversed(list(\n accumulate(reversed(towers), max)\n )),\n )\n return list(map(towerAndWater, waterlevels, towers))\n\n\n# ------------------------ DIAGRAMS ------------------------\n\n# showTowers :: [(Int, Int)] -> String\ndef showTowers(xs):\n '''Diagrammatic representation.\n '''\n upper = max(xs, key=fst)[0]\n\n def row(xd):\n return ' ' * (upper - add(*xd)) + (\n snd(xd) * 'x' + '██' * fst(xd)\n )\n return unlines([\n ''.join(x) for x in zip(*map(row, xs))\n ])\n\n\n# showLegend :: (Int, Int)] -> String\ndef showLegend(xs):\n '''String display of tower heights and\n total sum of trapped water units.\n '''\n towers, depths = zip(*xs)\n return showList(towers) + (\n ' -> ' + str(sum(depths))\n )\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Water collected in various flooded bar charts.'''\n def diagram(xs):\n return showTowers(xs) + '\\n\\n' + (\n showLegend(xs) + '\\n\\n'\n )\n\n print(unlines(\n map(compose(diagram, towerPools), [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n ])\n ))\n\n\n# ------------------------ GENERIC -------------------------\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n return lambda x: f(g(x))\n return reduce(go, fs, lambda x: x)\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string formed by the intercalation\n of a list of strings with the newline character.\n '''\n return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ $ \"turtleduck.qky\" loadfile ] now!\n\n [ dup 0 = iff drop done\n dup 2 times\n [ 20 * 1 walk\n 1 4 turn\n 20 1 walk\n 1 4 turn ] ] is bar ( [ --> )\n\n [ tuck size unrot\n -1 4 turn\n witheach\n [ dup\n ' [ 158 151 147 ]\n dup colour\n fill bar\n dup 20 * 1 fly\n dip\n [ behead\n ' [ 162 197 208 ]\n dup colour\n fill bar ]\n -20 * 1 fly\n 1 4 turn\n 20 1 fly\n -1 4 turn ]\n drop\n 1 4 turn\n -20 * 1 fly ] is chart ( [ [ --> )\n\n [ [] 0 rot witheach\n [ max dup dip join ]\n drop ] is rightmax ( [ --> [ )\n\n [ reverse\n rightmax\n reverse ] is leftmax ( [ --> [ )\n\n [ [] unrot\n witheach\n [ over i^ peek\n min swap dip join ]\n drop ] is mins ( [ --> [ )\n\n [ [] unrot\n witheach\n [ over i^ peek\n - swap dip join ]\n drop ] is diffs ( [ --> [ )\n\n [ 0 swap witheach + ] is sum ( [ --> n )\n\n [ dup 2dup rightmax\n swap leftmax\n mins diffs chart ] is task1 ( [ --> )\n\n [ dup dup rightmax\n swap leftmax\n mins diffs sum ] is task2 ( [ --> )\n\n turtle\n 10 frames\n -540 1 fly\n\n ' [ [ 1 5 3 7 2 ]\n [ 5 3 7 2 6 4 5 9 1 2 ]\n [ 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 ]\n [ 5 5 5 5 ]\n [ 5 6 7 8 ]\n [ 8 7 7 6 ]\n [ 6 7 10 7 6 ] ]\n dup\n witheach\n [ dup size swap\n task1\n 1+ 20 * 1 fly ]\n witheach\n [ task2 echo sp ]\n 1 frames\n", "language": "Quackery" }, { "code": "' Water collected between towers\nDECLARE SUB ShellSort (A() AS ANY)\nTYPE TTowerRec\n Hght AS INTEGER\n Posi AS INTEGER\nEND TYPE\n\n'heights of towers in each city prefixed by the number of towers\nDATA 5, 1, 5, 3, 7, 2\nDATA 10, 5, 3, 7, 2, 6, 4, 5, 9, 1, 2\nDATA 16, 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1\nDATA 4, 5, 5, 5, 5\nDATA 4, 5, 6, 7, 8\nDATA 4, 8, 7, 7, 6\nDATA 5, 6, 7, 10, 7, 6\n\nREM $DYNAMIC\nDIM Manhattan(0 TO 1) AS TTowerRec\nFOR I% = 1 TO 7\n READ N%\n ERASE Manhattan\n REDIM Manhattan(0 TO N% - 1) AS TTowerRec\n FOR J% = 0 TO N% - 1\n READ Manhattan(J%).Hght\n Manhattan(J%).Posi = J%\n NEXT J%\n ShellSort Manhattan()\n IF Manhattan(0).Posi < Manhattan(1).Posi THEN\n First% = Manhattan(0).Posi\n Last% = Manhattan(1).Posi\n ELSE\n First% = Manhattan(1).Posi\n Last% = Manhattan(0).Posi\n END IF\n Water% = Manhattan(1).Hght * (Last% - First% - 1)\n FOR J% = 2 TO N% - 1\n IF First% < Manhattan(J%).Posi AND Manhattan(J%).Posi < Last% THEN Water% = Water% - Manhattan(J%).Hght\n IF Manhattan(J%).Posi < First% THEN\n Water% = Water% + Manhattan(J%).Hght * (First% - Manhattan(J%).Posi - 1)\n First% = Manhattan(J%).Posi\n END IF\n IF Manhattan(J%).Posi > Last% THEN\n Water% = Water% + Manhattan(J%).Hght * (Manhattan(J%).Posi - Last% - 1)\n Last% = Manhattan(J%).Posi\n END IF\n NEXT J%\n PRINT USING \"City configuration ## collected #### units of water.\"; I%; Water%\nNEXT I%\nEND\n\nREM $STATIC\nSUB ShellSort (A() AS TTowerRec)\n 'quick and dirty shellsort, not the focus of this exercise\n Gap% = UBOUND(A): N% = UBOUND(A)\n DIM Temp AS TTowerRec\n DO\n Gap% = INT(Gap% / 2.2)\n IF Gap% = 0 THEN Gap% = 1\n FOR I% = Gap% TO N%\n Temp = A(I%)\n J% = I%\n ' Simulated WHILE J% >= Gap% ANDALSO A(J% - Gap%).Hght < Temp.Hght\n DO\n IF J% < Gap% THEN EXIT DO\n IF A(J% - Gap%).Hght >= Temp.Hght THEN EXIT DO\n A(J%) = A(J% - Gap%)\n J% = J% - Gap%\n LOOP\n A(J%) = Temp\n NEXT I%\n LOOP UNTIL Gap% = 1\nEND SUB\n", "language": "QuickBASIC" }, { "code": "#lang racket/base\n(require racket/match)\n\n(define (water-collected-between-towers towers)\n (define (build-tallest-left/rev-list t mx/l rv)\n (match t\n [(list) rv]\n [(cons a d)\n (define new-mx/l (max a mx/l))\n (build-tallest-left/rev-list d new-mx/l (cons mx/l rv))]))\n\n (define (collect-from-right t tallest/l mx/r rv)\n (match t\n [(list) rv]\n [(cons a d)\n (define new-mx/r (max a mx/r))\n (define new-rv (+ rv (max (- (min new-mx/r (car tallest/l)) a) 0)))\n (collect-from-right d (cdr tallest/l) new-mx/r new-rv)]))\n\n (define reversed-left-list (build-tallest-left/rev-list towers 0 null))\n (collect-from-right (reverse towers) reversed-left-list 0 0))\n\n(module+ test\n (require rackunit)\n (check-equal?\n (let ((towerss\n '[[1 5 3 7 2]\n [5 3 7 2 6 4 5 9 1 2]\n [2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1]\n [5 5 5 5]\n [5 6 7 8]\n [8 7 7 6]\n [6 7 10 7 6]]))\n (map water-collected-between-towers towerss))\n (list 2 14 35 0 0 0 0)))\n", "language": "Racket" }, { "code": "sub max_l ( @a ) { [\\max] @a }\nsub max_r ( @a ) { ([\\max] @a.reverse).reverse }\n\nsub water_collected ( @towers ) {\n return 0 if @towers <= 2;\n\n my @levels = max_l(@towers) »min« max_r(@towers);\n\n return ( @levels »-« @towers ).grep( * > 0 ).sum;\n}\n\nsay map &water_collected,\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ],\n;\n", "language": "Raku" }, { "code": "/* REXX */\nCall bars '1 5 3 7 2'\nCall bars '5 3 7 2 6 4 5 9 1 2'\nCall bars '2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1'\nCall bars '5 5 5 5'\nCall bars '5 6 7 8'\nCall bars '8 7 7 6'\nCall bars '6 7 10 7 6'\nExit\nbars:\nParse Arg bars\nbar.0=words(bars)\nhigh=0\nbox.=' '\nDo i=1 To words(bars)\n bar.i=word(bars,i)\n high=max(high,bar.i)\n Do j=1 To bar.i\n box.i.j='x'\n End\n End\nm=1\nw=0\nDo Forever\n Do i=m+1 To bar.0\n If bar.i>bar.m Then\n Leave\n End\n If i>bar.0 Then Leave\n n=i\n Do i=m+1 To n-1\n w=w+bar.m-bar.i\n Do j=bar.i+1 To bar.m\n box.i.j='*'\n End\n End\n m=n\n End\nm=bar.0\nDo Forever\n Do i=bar.0 To 1 By -1\n If bar.i>bar.m Then\n Leave\n End\n If i<1 Then Leave\n n=i\n Do i=m-1 To n+1 By -1\n w=w+bar.m-bar.i\n Do j=bar.i+1 To bar.m\n box.i.j='*'\n End\n End\n m=n\n End\nSay bars '->' w\nCall show\nReturn\nshow:\nDo j=high To 1 By -1\n ol=''\n Do i=1 To bar.0\n ol=ol box.i.j\n End\n Say ol\n End\nReturn\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the amount of rainwater collected between towers.*/\n call tower 1 5 3 7 2\n call tower 5 3 7 2 6 4 5 9 1 2\n call tower 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1\n call tower 5 5 5 5\n call tower 5 6 7 8\n call tower 8 7 7 6\n call tower 6 7 10 7 6\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntower: procedure; arg y; #=words(y); t.=0; L.=0 /*the T. array holds the tower heights.*/\n do j=1 for #; t.j= word(y, j) /*construct the towers, */\n _= j-1; L.j= max(t._, L._) /* \" \" left─most tallest tower*/\n end /*j*/\n R.=0\n do b=# by -1 for #; _= b+1; R.b= max(t._, R._) /*right─most tallest tower*/\n end /*b*/\n w.=0 /*rainwater collected.*/\n do f=1 for #; if t.f>=L.f | t.f>=R.f then iterate /*rain between towers?*/\n w.f= min(L.f, R.f) - t.f; w.00= w.00 + w.f /*rainwater collected.*/\n end /*f*/\n say right(w.00, 9) 'units of rainwater collected for: ' y /*display water units.*/\n return\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the amount of rainwater collected between towers.*/\n call tower 1 5 3 7 2\n call tower 5 3 7 2 6 4 5 9 1 2\n call tower 2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1\n call tower 5 5 5 5\n call tower 5 6 7 8\n call tower 8 7 7 6\n call tower 6 7 10 7 6\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ntower: procedure; arg y; #= words(y); t.=0; L.=0 /*the T. array holds the tower heights.*/\n do j=1 for #; t.j=word(y,j); _=j-1 /*construct the towers; max height. */\n L.j=max(t._, L._); t.0=max(t.0, t.j) /*left-most tallest tower; build scale.*/\n end /*j*/\n R.=0\n do b=# by -1 for #; _= b+1; R.b= max(t._, R._) /*right-most tallest tower*/\n end /*b*/\n w.=0 /*rainwater collected.*/\n do f=1 for #; if t.f>=L.f | t.f>=R.f then iterate /*rain between towers?*/\n w.f= min(L.f, R.f) - t.f; w.00= w.00 + w.f /*rainwater collected.*/\n end /*f*/\n if w.00==0 then w.00= 'no' /*pretty up wording for \"no rainwater\".*/\n ratio= 2 /*used to maintain a good aspect ratio.*/\n p.= /*P. stores plot versions of towers. */\n do c=0 to #; cc= c * ratio /*construct the plot+scale for display.*/\n do h=1 for t.c+w.c; glyph= '█' /*maybe show a floor of some tower(s). */\n if h>t.c then glyph= '≈' /* \" \" rainwater between towers. */\n if c==0 then p.h= overlay(right(h, 9) , p.h, 1 ) /*tower scale*/\n else p.h= overlay(copies(glyph,ratio) , p.h, 10+cc) /*build tower*/\n end /*h*/\n end /*c*/\n p.1= overlay(w.00 'units of rainwater collected', p.1, 15*ratio+#) /*append text*/\n do z=t.0 by -1 to 0; say p.z /*display various tower floors & water.*/\n end /*z*/\n return\n", "language": "REXX" }, { "code": "def a(array)\nn=array.length\nleft={}\nright={}\nleft[0]=array[0]\ni=1\nloop do\n break if i >=n\nleft[i]=[left[i-1],array[i]].max\n i += 1\nend\nright[n-1]=array[n-1]\ni=n-2\nloop do\nbreak if i<0\n right[i]=[right[i+1],array[i]].max\ni-=1\nend\ni=0\nwater=0\nloop do\nbreak if i>=n\nwater+=[left[i],right[i]].min-array[i]\ni+=1\nend\nputs water\nend\n\na([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ])\na([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ])\na([ 5, 5, 5, 5 ])\na([ 5, 6, 7, 8 ])\na([ 8, 7, 7, 6 ])\na([ 6, 7, 10, 7, 6 ])\nreturn\n", "language": "Ruby" }, { "code": "use std::cmp::min;\n\nfn getfill(pattern: &[usize]) -> usize {\n let mut total = 0;\n for (idx, val) in pattern.iter().enumerate() {\n let l_peak = pattern[..idx].iter().max();\n let r_peak = pattern[idx + 1..].iter().max();\n if l_peak.is_some() && r_peak.is_some() {\n let peak = min(l_peak.unwrap(), r_peak.unwrap());\n if peak > val {\n total += peak - val;\n }\n }\n }\n total\n}\n\nfn main() {\n let patterns = vec![\n vec![1, 5, 3, 7, 2],\n vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n vec![5, 5, 5, 5],\n vec![5, 6, 7, 8],\n vec![8, 7, 7, 6],\n vec![6, 7, 10, 7, 6],\n ];\n\n for pattern in patterns {\n println!(\"pattern: {:?}, fill: {}\", &pattern, getfill(&pattern));\n }\n}\n", "language": "Rust" }, { "code": "import scala.collection.parallel.CollectionConverters.VectorIsParallelizable\n\n// Program to find maximum amount of water\n// that can be trapped within given set of bars.\nobject TrappedWater extends App {\n private val barLines = List(\n Vector(1, 5, 3, 7, 2),\n Vector(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),\n Vector(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),\n Vector(5, 5, 5, 5),\n Vector(5, 6, 7, 8),\n Vector(8, 7, 7, 6),\n Vector(6, 7, 10, 7, 6)).zipWithIndex\n\n // Method for maximum amount of water\n private def sqBoxWater(barHeights: Vector[Int]): Int = {\n def maxOfLeft = barHeights.par.scanLeft(0)(math.max).tail\n def maxOfRight = barHeights.par.scanRight(0)(math.max).init\n\n def waterlevels = maxOfLeft.zip(maxOfRight)\n .map { case (maxL, maxR) => math.min(maxL, maxR) }\n\n waterlevels.zip(barHeights).map { case (level, towerHeight) => level - towerHeight }.sum\n }\n\n barLines.foreach(barSet =>\n println(s\"Block ${barSet._2 + 1} could hold max. ${sqBoxWater(barSet._1)} units.\"))\n\n}\n", "language": "Scala" }, { "code": "(import (scheme base)\n (scheme write))\n\n(define (total-collected chart)\n (define (highest-left vals curr)\n (if (null? vals)\n (list curr)\n (cons curr\n (highest-left (cdr vals) (max (car vals) curr)))))\n (define (highest-right vals curr)\n (reverse (highest-left (reverse vals) curr)))\n ;\n (if (< (length chart) 3) ; catch the end cases\n 0\n (apply +\n (map (lambda (l c r)\n (if (or (<= l c)\n (<= r c))\n 0\n (- (min l r) c)))\n (highest-left chart 0)\n chart\n (highest-right chart 0)))))\n\n(for-each\n (lambda (chart)\n (display chart) (display \" -> \") (display (total-collected chart)) (newline))\n '((1 5 3 7 2)\n (5 3 7 2 6 4 5 9 1 2)\n (2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1)\n (5 5 5 5)\n (5 6 7 8)\n (8 7 7 6)\n (6 7 10 7 6)))\n", "language": "Scheme" }, { "code": "func max_l(Array a, m = a[0]) {\n gather { a.each {|e| take(m = max(m, e)) } }\n}\n\nfunc max_r(Array a) {\n max_l(a.flip).flip\n}\n\nfunc water_collected(Array towers) {\n var levels = (max_l(towers) »min« max_r(towers))\n (levels »-« towers).grep{ _ > 0 }.sum\n}\n\n[\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ],\n].map { water_collected(_) }.say\n", "language": "Sidef" }, { "code": "// Based on this answer from Stack Overflow:\n// https://stackoverflow.com/a/42821623\n\nfunc waterCollected(_ heights: [Int]) -> Int {\n guard heights.count > 0 else {\n return 0\n }\n var water = 0\n var left = 0, right = heights.count - 1\n var maxLeft = heights[left], maxRight = heights[right]\n\n while left < right {\n if heights[left] <= heights[right] {\n maxLeft = max(heights[left], maxLeft)\n water += maxLeft - heights[left]\n left += 1\n } else {\n maxRight = max(heights[right], maxRight)\n water += maxRight - heights[right]\n right -= 1\n }\n }\n return water\n}\n\nfor heights in [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]] {\n print(\"water collected = \\(waterCollected(heights))\")\n}\n", "language": "Swift" }, { "code": "templates histogramWater\n $ -> \\( @: 0\"1\";\n [$... -> ($)\"1\"-> { leftMax: $ -> #, value: ($)\"1\" } ] !\n when <$@..> do @: $; $ !\n otherwise $@ !\n \\) -> \\( @: { rightMax: 0\"1\", sum: 0\"1\" };\n $(last..1:-1)... -> #\n [email protected] !\n when <{ value: <[email protected]..> }> do @.rightMax: $.value;\n when <{ value: <$.leftMax..> }> do !VOID\n when <{ leftMax: <[email protected]>}> do @.sum: [email protected] + $.leftMax - $.value;\n otherwise @.sum: [email protected] + [email protected] - $.value;\n \\) !\nend histogramWater\n\n[[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]... -> '$ -> histogramWater; water in $;$#10;' -> !OUT::write\n", "language": "Tailspin" }, { "code": "namespace path {::tcl::mathfunc ::tcl::mathop}\n\nproc flood {ground} {\n set lefts [\n set d 0\n lmap g $ground {\n set d [max $d $g]\n }\n ]\n set ground [lreverse $ground]\n set rights [\n set d 0\n lmap g $ground {\n set d [max $d $g]\n }\n ]\n set rights [lreverse $rights]\n set ground [lreverse $ground]\n set water [lmap l $lefts r $rights {min $l $r}]\n set depths [lmap g $ground w $water {- $w $g}]\n + {*}$depths\n}\n\nforeach p {\n {5 3 7 2 6 4 5 9 1 2}\n {1 5 3 7 2}\n {5 3 7 2 6 4 5 9 1 2}\n {2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1}\n {5 5 5 5}\n {5 6 7 8}\n {8 7 7 6}\n {6 7 10 7 6}\n} {\n puts [flood $p]:\\t$p\n}\n", "language": "Tcl" }, { "code": "' Convert tower block data into a string representation, then manipulate that.\nModule Module1\n Sub Main(Args() As String)\n Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.\n Dim wta As Integer()() = { ' Water tower array (input data).\n New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n Dim blk As String, ' String representation of a block of towers.\n lf As String = vbLf, ' Line feed to separate floors in a block of towers.\n tb = \"██\", wr = \"≈≈\", mt = \" \" ' Tower Block, Water Retained, eMpTy space.\n For i As Integer = 0 To wta.Length - 1\n Dim bpf As Integer ' Count of tower blocks found per floor.\n blk = \"\"\n Do\n bpf = 0 : Dim floor As String = \"\" ' String representation of each floor.\n For j As Integer = 0 To wta(i).Length - 1\n If wta(i)(j) > 0 Then ' Tower block detected, add block to floor,\n floor &= tb : wta(i)(j) -= 1 : bpf += 1 ' reduce tower by one.\n Else ' Empty space detected, fill when not first or last column.\n floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)\n End If\n Next\n If bpf > 0 Then blk = floor & lf & blk ' Add floors until blocks are gone.\n Loop Until bpf = 0 ' No tower blocks left, so terminate.\n ' Erode potential water retention cells from left and right.\n While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While\n While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While\n ' Optionaly show towers w/ water marks.\n If shoTow Then Console.Write(\"{0}{1}\", lf, blk)\n ' Subtract the amount of non-water mark characters from the total char amount.\n Console.Write(\"Block {0} retains {1,2} water units.{2}\", i + 1,\n (blk.Length - blk.Replace(wr, \"\").Length) \\ 2, lf)\n Next\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "Block 1 retains 2 water units.\nBlock 2 retains 14 water units.\nBlock 3 retains 35 water units.\nBlock 4 retains 0 water units.\nBlock 5 retains 0 water units.\nBlock 6 retains 0 water units.\nBlock 7 retains 0 water units.\n", "language": "Visual-Basic-.NET" }, { "code": " ██\n ██\n ██≈≈██\n ██≈≈██\n ██████\n ████████\n██████████\nBlock 1 retains 2 water units.\n\n ██\n ██\n ██≈≈≈≈≈≈≈≈██\n ██≈≈██≈≈≈≈██\n██≈≈██≈≈██≈≈████\n██≈≈██≈≈████████\n██████≈≈████████\n████████████████≈≈██\n████████████████████\nBlock 2 retains 14 water units.\n\n ██\n ██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██\n ██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██\n ██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████\n ██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████\n ██████≈≈██≈≈██≈≈≈≈██████████\n████████████≈≈████████████████\n████████████████████████████████\nBlock 3 retains 35 water units.\n\n████████\n████████\n████████\n████████\n████████\nBlock 4 retains 0 water units.\n\n ██\n ████\n ██████\n████████\n████████\n████████\n████████\n████████\nBlock 5 retains 0 water units.\n\n██\n██████\n████████\n████████\n████████\n████████\n████████\n████████\nBlock 6 retains 0 water units.\n\n ██\n ██\n ██\n ██████\n██████████\n██████████\n██████████\n██████████\n██████████\n██████████\nBlock 7 retains 0 water units.\n", "language": "Visual-Basic-.NET" }, { "code": "Module Module1\n ''' <summary>\n ''' wide - Widens the aspect ratio of a linefeed separated string.\n ''' </summary>\n ''' <param name=\"src\">A string representing a block of towers.</param>\n ''' <param name=\"margin\">Optional padding for area to the left.</param>\n ''' <returns>A double-wide version of the string.</returns>\n Function wide(src As String, Optional margin As String = \"\") As String\n Dim res As String = margin : For Each ch As Char In src\n res += If(ch < \" \", ch & margin, ch + ch) : Next : Return res\n End Function\n\n ''' <summary>\n ''' cntChar - Counts characters, also custom formats the output.\n ''' </summary>\n ''' <param name=\"src\">The string to count characters in.</param>\n ''' <param name=\"ch\">The character to be counted.</param>\n ''' <param name=\"verb\">Verb to include in format. Expecting \"hold\",\n ''' but can work with \"retain\" or \"have\".</param>\n ''' <returns>The count of chars found in a string, and formats a verb.</returns>\n Function cntChar(src As String, ch As Char, verb As String) As String\n Dim cnt As Integer = 0\n For Each c As Char In src : cnt += If(c = ch, 1, 0) : Next\n Return If(cnt = 0, \"does not \" & verb & \" any\",\n verb.Substring(0, If(verb = \"have\", 2, 4)) & \"s \" & cnt.ToString())\n End Function\n\n ''' <summary>\n ''' report - Produces a report of the number of rain units found in\n ''' a block of towers, optionally showing the towers.\n ''' Autoincrements the blkID for each report.\n ''' </summary>\n ''' <param name=\"tea\">An int array with tower elevations.</param>\n ''' <param name=\"blkID\">An int of the block of towers ID.</param>\n ''' <param name=\"verb\">The verb to use in the description.\n ''' Defaults to \"has / have\".</param>\n ''' <param name=\"showIt\">When true, the report includes a string representation\n ''' of the block of towers.</param>\n ''' <returns>A string containing the amount of rain units, optionally preceeded by\n ''' a string representation of the towers holding any water.</returns>\n Function report(tea As Integer(), ' Tower elevation array.\n ByRef blkID As Integer, ' Block ID for the description.\n Optional verb As String = \"have\", ' Verb to use in the description.\n Optional showIt As Boolean = False) As String ' Show representaion.\n Dim block As String = \"\", ' The block of towers.\n lf As String = vbLf, ' The separator between floors.\n rTwrPos As Integer ' The position of the rightmost tower of this floor.\n Do\n For rTwrPos = tea.Length - 1 To 0 Step -1 ' Determine the rightmost tower\n If tea(rTwrPos) > 0 Then Exit For ' postition on this floor.\n Next\n If rTwrPos < 0 Then Exit Do ' When no towers remain, exit the do loop.\n ' init the floor to a space filled Char array, as wide as the block of towers.\n Dim floor As Char() = New String(\" \", tea.Length).ToCharArray()\n Dim bpf As Integer = 0 ' The count of blocks found per floor.\n For column As Integer = 0 To rTwrPos ' Scan from left to right.\n If tea(column) > 0 Then ' If a tower exists here,\n floor(column) = \"█\" ' mark the floor with a block,\n tea(column) -= 1 ' drop the tower elevation by one,\n bpf += 1 ' and advance the block count.\n ElseIf bpf > 0 Then ' Otherwise, see if a tower is present to the left.\n floor(column) = \"≈\" ' OK to fill with water.\n End If\n Next\n If bpf > If(showIt, 0, 1) Then ' Continue the building only when needed.\n ' If not showing blocks, discontinue building when a single tower remains.\n ' build tower blocks string with each floor added to top.\n block = New String(floor) & If(block = \"\", \"\", lf) & block\n Else\n Exit Do ' Ran out of towers, so exit the do loop.\n End If\n Loop While True ' Depending on previous break statements to terminate the do loop.\n blkID += 1 ' increment block ID counter.\n ' format report and return it.\n Return If(showIt, String.Format(vbLf & \"{0}\", wide(block, \" \")), \"\") &\n String.Format(\" Block {0} {1} water units.\", blkID, cntChar(block, \"≈\", verb))\n End Function\n\n ''' <summary>\n ''' Main routine.\n '''\n ''' With one command line parameter, it shows tower blocks,\n ''' with no command line parameters, it shows a plain report\n '''</summary>\n Sub Main()\n Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 ' Show towers.\n Dim blkCntr As Integer = 0 ' Block ID for reports.\n Dim verb As String = \"hold\" ' \"retain\" or \"have\" can be used instead of \"hold\".\n Dim tea As Integer()() = {New Integer() {1, 5, 3, 7, 2}, ' Tower elevation data.\n New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},\n New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}\n For Each block As Integer() In tea\n ' Produce report for each block of towers.\n Console.WriteLine(report(block, blkCntr, verb, shoTow))\n Next\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": " Block 1 holds 2 water units.\n Block 2 holds 14 water units.\n Block 3 holds 35 water units.\n Block 4 does not hold any water units.\n Block 5 does not hold any water units.\n Block 6 does not hold any water units.\n Block 7 does not hold any water units.\n", "language": "Visual-Basic-.NET" }, { "code": " ██\n ██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██\n ██≈≈≈≈≈≈██≈≈≈≈≈≈≈≈≈≈≈≈≈≈██\n ██≈≈██≈≈██≈≈≈≈≈≈≈≈██≈≈████\n ██≈≈██≈≈██≈≈██≈≈≈≈██≈≈██████\n ██████≈≈██≈≈██≈≈≈≈██████████\n ████████████≈≈████████████████\n ████████████████████████████████ Block 3 holds 35 water units.\n\n ████████\n ████████\n ████████\n ████████\n ████████ Block 4 does not hold any water units.\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./math\" for Math, Nums\nimport \"./fmt\" for Fmt\n\nvar waterCollected = Fn.new { |tower|\n var n = tower.count\n var highLeft = [0] + (1...n).map { |i| Nums.max(tower[0...i]) }.toList\n var highRight = (1...n).map { |i| Nums.max(tower[i...n]) }.toList + [0]\n var t = (0...n).map { |i| Math.max(Math.min(highLeft[i], highRight[i]) - tower[i], 0) }\n return Nums.sum(t)\n}\n\nvar towers = [\n [1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]\n]\nfor (tower in towers) Fmt.print(\"$2d from $n\", waterCollected.call(tower), tower)\n", "language": "Wren" }, { "code": "func WaterCollected(Array, Width); \\Return amount of water collected\nint Array, Width, Height, I, Row, Col, Left, Right, Water;\n[Water:= 0; Height:= 0;\nfor I:= 0 to Width-1 do \\find max height\n if Array(I) > Height then Height:= Array(I);\nfor Row:= 2 to Height do\n for Col:= 1 to Width-2 do \\(zero-based)\n if Row > Array(Col) then \\empty location\n [Left:= false; Right:= false; \\check for barriers\n for I:= 0 to Width-1 do\n if Array(I) >= Row then \\have barrier\n [if I < Col then Left:= true;\n if I > Col then Right:= true;\n ];\n if Left & Right then Water:= Water+1;\n ];\nreturn Water;\n];\n\nint Towers, I;\n[Towers:=[[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6],\n [0]]; \\for determining sub-array lengths\nfor I:= 0 to 7-1 do\n [IntOut( 0, WaterCollected(Towers(I), (Towers(I+1)-Towers(I))/4) );\n ChOut(0, ^ );\n ];\n]\n", "language": "XPL0" }, { "code": "data 7\ndata \"1,5,3,7,2\", \"5,3,7,2,6,4,5,9,1,2\", \"2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1\"\ndata \"5,5,5,5\", \"5,6,7,8\", \"8,7,7,6\", \"6,7,10,7,6\"\n\nread n\n\nfor i = 1 to n\n\tread n$\n\twcbt(n$)\nnext i\n\nsub wcbt(s$)\n\tlocal tower$(1), hr(1), hl(1), n, i, ans, k\n\t\n\tn = token(s$, tower$(), \",\")\n\n\tredim hr(n)\n\tredim hl(n)\n\tfor i = n to 1 step -1\n\t\tif i < n then\n\t\t\tk = hr(i + 1)\n\t\telse\n\t\t\tk = 0\n\t\tend if\n\t\thr(i) = max(val(tower$(i)), k)\n\tnext i\n\tfor i = 1 to n\n\t\tif i then\n\t\t\tk = hl(i - 1)\n\t\telse\n\t\t\tk = 0\n\t\tend if\n\t\thl(i) = max(val(tower$(i)), k)\n\t\tans = ans + min(hl(i), hr(i)) - val(tower$(i))\n\tnext i\n\tprint ans,\" \",n$\nend sub\n", "language": "Yabasic" }, { "code": "fcn waterCollected(walls){\n // compile max wall heights from left to right and right to left\n // then each pair is left/right wall of that cell.\n // Then the min of each wall pair == water height for that cell\n scanl(walls,(0).max) // scan to right, f is max(0,a,b)\n .zipWith((0).MAX.min, // f is MAX.min(a,b) == min(a,b)\n scanl(walls.reverse(),(0).max).reverse()) // right to left\n // now subtract the wall height from the water level and add 'em up\n .zipWith('-,walls).filter('>(0)).sum(0);\n}\nfcn scanl(xs,f,i=0){ // aka reduce but save list of results\n xs.reduce('wrap(s,x,a){ s=f(s,x); a.append(s); s },i,ss:=List());\n ss\n} // scanl((1,5,3,7,2),max,0) --> (1,5,5,7,7)\n", "language": "Zkl" }, { "code": "T( T(1, 5, 3, 7, 2), T(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),\n T(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),\n T(5, 5, 5, 5), T(5, 6, 7, 8),T(8, 7, 7, 6),\n T(6, 7, 10, 7, 6) )\n.pump(List, waterCollected).println();\n", "language": "Zkl" } ]
Water-collected-between-towers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Weird_numbers\n", "language": "00-META" }, { "code": "In number theory, a [[wp:weird number|weird number]] is a natural number that is [[wp:abundant number|abundant]] but ''not'' [[wp:semiperfect number|semiperfect]] (and therefore not [[wp:perfect number|perfect]] either).\n\nIn other words, the sum of the [[wp:Divisor#Further_notions_and_facts|proper divisors]] of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: &nbsp; &nbsp; '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* [[Abundant,_deficient_and_perfect_number_classifications|Abundant, deficient and perfect number classifications]]\n:* [[Proper_divisors|Proper divisors]]\n\n\n;See also:\n:* [[oeis:A006037|OEIS: A006037 weird numbers]]\n:* [[wp:weird number|Wikipedia: weird number]]\n:* [http://mathworld.wolfram.com/WeirdNumber.html MathWorld: weird number]\n<br>\n\n", "language": "00-TASK" }, { "code": "F divisors(n)\n V divs = [1]\n [Int] divs2\n V i = 2\n L i * i <= n\n I n % i == 0\n V j = n I/ i\n divs [+]= i\n I i != j\n divs2 [+]= j\n i++\n R divs2 [+] reversed(divs)\n\nF abundant(n, divs)\n R sum(divs) > n\n\nF semiperfect(n, divs) -> Bool\n I !divs.empty\n V h = divs[0]\n V t = divs[1..]\n I n < h\n R semiperfect(n, t)\n E\n R n == h | semiperfect(n - h, t) | semiperfect(n, t)\n E\n R 0B\n\nF sieve(limit)\n V w = [0B] * limit\n L(i) (2 .< limit).step(2)\n I w[i]\n L.continue\n V divs = divisors(i)\n I !abundant(i, divs)\n w[i] = 1B\n E I semiperfect(i, divs)\n L(j) (i .< limit).step(i)\n w[j] = 1B\n R w\n\nV w = sieve(17'000)\nV count = 0\nprint(‘The first 25 weird numbers:’)\nL(n) (2..).step(2)\n I !w[n]\n print(n, end' ‘ ’)\n count++\n I count == 25\n L.break\n", "language": "11l" }, { "code": "BEGIN # find wierd numbers - abundant but not semiperfect numbers - translation of Go #\n # returns the divisors of n in descending order #\n PROC divisors = ( INT n )[]INT:\n BEGIN\n INT max divs = 2 * ENTIER sqrt( n );\n [ 1 : max divs ]INT divs;\n [ 1 : max divs ]INT divs2;\n INT d pos := 0, d2 pos := 0;\n divs[ d pos +:= 1 ] := 1;\n FOR i FROM 2 WHILE i * i <= n DO\n IF n MOD i = 0 THEN\n INT j = n OVER i;\n divs[ d pos +:= 1 ] := i;\n IF i /= j THEN divs2[ d2 pos +:= 1 ] := j FI\n FI\n OD;\n FOR i FROM d pos BY -1 WHILE i > 0 DO\n divs2[ d2 pos +:= 1 ] := divs[ i ]\n OD;\n divs2[ 1 : d2 pos ]\n END # divisors # ;\n # returns TRUE if n with divisors divs, is abundant, FALSE otherwise #\n PROC abundant = ( INT n, []INT divs )BOOL:\n BEGIN\n INT sum := 0;\n FOR i FROM LWB divs TO UPB divs DO sum +:= divs[ i ] OD;\n sum > n\n END # abundant # ;\n # returns TRUE if n with divisors divs, is semiperfect, FALSE otherwise #\n PROC semiperfect = ( INT n, []INT divs, INT lb, ub )BOOL:\n IF ub < lb\n THEN FALSE\n ELIF INT h = divs[ lb ];\n n < h\n THEN semiperfect( n, divs, lb + 1, ub )\n ELIF n = h\n THEN TRUE\n ELIF semiperfect( n - h, divs, lb + 1, ub )\n THEN TRUE\n ELSE semiperfect( n, divs, lb + 1, ub )\n FI # semiperfect # ;\n # returns a sieve where FALSE = abundant and not semiperfect #\n PROC sieve = ( INT limit )[]BOOL:\n BEGIN # Only interested in even numbers >= 2 #\n [ 1 : limit ]BOOL w; FOR i FROM 1 TO limit DO w[ i ] := FALSE OD;\n FOR i FROM 2 BY 2 TO limit DO\n IF NOT w[ i ] THEN\n []INT divs = divisors( i );\n IF NOT abundant( i, divs ) THEN\n w[ i ] := TRUE\n ELIF semiperfect( i, divs, LWB divs, UPB divs ) THEN\n FOR j FROM i BY i TO limit DO w[ j ] := TRUE OD\n FI\n FI\n OD;\n w\n END # sieve # ;\n BEGIN # task #\n []BOOL w = sieve( 17 000 );\n INT count := 0;\n INT max = 25;\n print( ( \"The first 25 weird numbers are:\", newline ) );\n FOR n FROM 2 BY 2 WHILE count < max DO\n IF NOT w[ n ] THEN\n print( ( whole( n, 0 ), \" \" ) );\n count +:= 1\n FI\n OD;\n print( ( newline ) )\n END\nEND\n", "language": "ALGOL-68" }, { "code": "on run\n take(25, weirds())\n -- Gets there, but takes about 6 seconds on this system,\n -- (logging intermediates through the Messages channel, for the impatient :-)\nend run\n\n\n-- weirds :: Gen [Int]\non weirds()\n script\n property x : 1\n property v : 0\n on |λ|()\n repeat until isWeird(x)\n set x to 1 + x\n end repeat\n set v to x\n log v\n set x to 1 + x\n return v\n end |λ|\n end script\nend weirds\n\n-- isWeird :: Int -> Bool\non isWeird(n)\n set ds to descProperDivisors(n)\n set d to sum(ds) - n\n 0 < d and not hasSum(d, ds)\nend isWeird\n\n-- hasSum :: Int -> [Int] -> Bool\non hasSum(n, xs)\n if {} ≠ xs then\n set h to item 1 of xs\n set t to rest of xs\n if n < h then\n hasSum(n, t)\n else\n n = h or hasSum(n - h, t) or hasSum(n, t)\n end if\n else\n false\n end if\nend hasSum\n\n-- GENERIC ------------------------------------------------\n\n-- descProperDivisors :: Int -> [Int]\non descProperDivisors(n)\n if n = 1 then\n {1}\n else\n set realRoot to n ^ (1 / 2)\n set intRoot to realRoot as integer\n set blnPerfect to intRoot = realRoot\n\n -- isFactor :: Int -> Bool\n script isFactor\n on |λ|(x)\n n mod x = 0\n end |λ|\n end script\n\n -- Factors up to square root of n,\n set lows to filter(isFactor, enumFromTo(1, intRoot))\n\n -- and cofactors of these beyond the square root,\n\n -- integerQuotient :: Int -> Int\n script integerQuotient\n on |λ|(x)\n (n / x) as integer\n end |λ|\n end script\n\n set t to rest of lows\n if blnPerfect then\n set xs to t\n else\n set xs to lows\n end if\n map(integerQuotient, t) & (reverse of xs)\n end if\nend descProperDivisors\n\n-- enumFromTo :: (Int, Int) -> [Int]\non enumFromTo(m, n)\n if m ≤ n then\n set lst to {}\n repeat with i from m to n\n set end of lst to i\n end repeat\n return lst\n else\n return {}\n end if\nend enumFromTo\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- sum :: [Num] -> Num\non sum(xs)\n script add\n on |λ|(a, b)\n a + b\n end |λ|\n end script\n\n foldl(add, 0, xs)\nend sum\n\n-- take :: Int -> Gen [a] -> [a]\non take(n, xs)\n set ys to {}\n repeat with i from 1 to n\n set v to xs's |λ|()\n if missing value is v then\n return ys\n else\n set end of ys to v\n end if\n end repeat\n return ys\nend take\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n", "language": "AppleScript" }, { "code": "-- Sum n's proper divisors.\non aliquotSum(n)\n if (n < 2) then return 0\n set sum to 1\n set sqrt to n ^ 0.5\n set limit to sqrt div 1\n if (limit = sqrt) then\n set sum to sum + limit\n set limit to limit - 1\n end if\n repeat with i from 2 to limit\n if (n mod i is 0) then set sum to sum + i + n div i\n end repeat\n\n return sum\nend aliquotSum\n\n-- Return n's proper divisors.\non properDivisors(n)\n set output to {}\n\n if (n > 1) then\n set sqrt to n ^ 0.5\n set limit to sqrt div 1\n if (limit = sqrt) then\n set end of output to limit\n set limit to limit - 1\n end if\n repeat with i from limit to 2 by -1\n if (n mod i is 0) then\n set beginning of output to i\n set end of output to n div i\n end if\n end repeat\n set beginning of output to 1\n end if\n\n return output\nend properDivisors\n\n-- Does a subset of the given list of numbers add up to the target value?\non subsetOf:numberList sumsTo:target\n script o\n property lst : numberList\n property someNegatives : false\n\n on ssp(target, i)\n repeat while (i > 1)\n set n to item i of my lst\n set i to i - 1\n if ((n = target) or (((n < target) or (someNegatives)) and (ssp(target - n, i)))) then return true\n end repeat\n return (target = beginning of my lst)\n end ssp\n end script\n -- The search can be more efficient if it's known the list contains no negatives.\n repeat with n in o's lst\n if (n < 0) then\n set o's someNegatives to true\n exit repeat\n end if\n end repeat\n\n return o's ssp(target, count o's lst)\nend subsetOf:sumsTo:\n\n-- Is n a weird number?\non isWeird(n)\n -- Yes if its aliquot sum's greater than it and no subset of its proper divisors adds up to it.\n -- Using aliquotSum() to get the divisor sum and then calling properDivisors() too if a list's actually\n -- needed is generally faster than calling properDivisors() in the first place and summing the result.\n set sum to aliquotSum(n)\n if (sum > n) then\n set divisors to properDivisors(n)\n -- Check that no subset sums to the smaller (usually the latter) of n and sum - n.\n tell (sum - n) to if (it < n) then set n to it\n return (not (my subsetOf:divisors sumsTo:n))\n else\n return false\n end if\nend isWeird\n\n-- Task code:\non weirdNumbers(target)\n script o\n property weirds : {}\n end script\n\n set n to 2\n set counter to 0\n repeat until (counter = target)\n if (isWeird(n)) then\n set end of o's weirds to n\n set counter to counter + 1\n end if\n set n to n + 1\n end repeat\n\n return o's weirds\nend weirdNumbers\n\nweirdNumbers(25)\n", "language": "AppleScript" }, { "code": "{70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570, 10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, 13790, 13930, 14770, 15610, 15890, 16030, 16310}\n", "language": "AppleScript" }, { "code": "#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"stdbool.h\"\n#include \"string.h\"\n\nstruct int_a {\n int *ptr;\n size_t size;\n};\n\nstruct int_a divisors(int n) {\n int *divs, *divs2, *out;\n int i, j, c1 = 0, c2 = 0;\n struct int_a array;\n\n divs = malloc(n * sizeof(int) / 2);\n divs2 = malloc(n * sizeof(int) / 2);\n divs[c1++] = 1;\n\n for (i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n j = n / i;\n divs[c1++] = i;\n if (i != j) {\n divs2[c2++] = j;\n }\n }\n }\n\n out = malloc((c1 + c2) * sizeof(int));\n for (int i = 0; i < c2; i++) {\n out[i] = divs2[i];\n }\n for (int i = 0; i < c1; i++) {\n out[c2 + i] = divs[c1 - i - 1];\n }\n array.ptr = out;\n array.size = c1 + c2;\n\n free(divs);\n free(divs2);\n return array;\n}\n\nbool abundant(int n, struct int_a divs) {\n int sum = 0;\n int i;\n for (i = 0; i < divs.size; i++) {\n sum += divs.ptr[i];\n }\n return sum > n;\n}\n\nbool semiperfect(int n, struct int_a divs) {\n if (divs.size > 0) {\n int h = *divs.ptr;\n int *t = divs.ptr + 1;\n\n struct int_a ta;\n ta.ptr = t;\n ta.size = divs.size - 1;\n\n if (n < h) {\n return semiperfect(n, ta);\n } else {\n return n == h\n || semiperfect(n - h, ta)\n || semiperfect(n, ta);\n }\n } else {\n return false;\n }\n}\n\nbool *sieve(int limit) {\n bool *w = calloc(limit, sizeof(bool));\n struct int_a divs;\n int i, j;\n\n for (i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n divs = divisors(i);\n if (!abundant(i, divs)) {\n w[i] = true;\n } else if (semiperfect(i, divs)) {\n for (j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n\n free(divs.ptr);\n return w;\n}\n\nint main() {\n bool *w = sieve(17000);\n int count = 0;\n int max = 25;\n int n;\n\n printf(\"The first 25 weird numbers:\\n\");\n for (n = 2; count < max; n += 2) {\n if (!w[n]) {\n printf(\"%d \", n);\n count++;\n }\n }\n printf(\"\\n\");\n\n free(w);\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nstd::vector<int> divisors(int n) {\n std::vector<int> divs = { 1 };\n std::vector<int> divs2;\n\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int j = n / i;\n divs.push_back(i);\n if (i != j) {\n divs2.push_back(j);\n }\n }\n }\n\n std::copy(divs.cbegin(), divs.cend(), std::back_inserter(divs2));\n return divs2;\n}\n\nbool abundant(int n, const std::vector<int> &divs) {\n return std::accumulate(divs.cbegin(), divs.cend(), 0) > n;\n}\n\ntemplate<typename IT>\nbool semiperfect(int n, const IT &it, const IT &end) {\n if (it != end) {\n auto h = *it;\n auto t = std::next(it);\n if (n < h) {\n return semiperfect(n, t, end);\n } else {\n return n == h\n || semiperfect(n - h, t, end)\n || semiperfect(n, t, end);\n }\n } else {\n return false;\n }\n}\n\ntemplate<typename C>\nbool semiperfect(int n, const C &c) {\n return semiperfect(n, std::cbegin(c), std::cend(c));\n}\n\nstd::vector<bool> sieve(int limit) {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n std::vector<bool> w(limit);\n for (int i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n auto divs = divisors(i);\n if (!abundant(i, divs)) {\n w[i] = true;\n } else if (semiperfect(i, divs)) {\n for (int j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n return w;\n}\n\nint main() {\n auto w = sieve(17000);\n int count = 0;\n int max = 25;\n std::cout << \"The first 25 weird numbers:\";\n for (int n = 2; count < max; n += 2) {\n if (!w[n]) {\n std::cout << n << ' ';\n count++;\n }\n }\n std::cout << '\\n';\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace WeirdNumbers {\n class Program {\n static List<int> Divisors(int n) {\n List<int> divs = new List<int> { 1 };\n List<int> divs2 = new List<int>();\n\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int j = n / i;\n divs.Add(i);\n if (i != j) {\n divs2.Add(j);\n }\n }\n }\n\n divs.Reverse();\n divs2.AddRange(divs);\n return divs2;\n }\n\n static bool Abundant(int n, List<int> divs) {\n return divs.Sum() > n;\n }\n\n static bool Semiperfect(int n, List<int> divs) {\n if (divs.Count > 0) {\n var h = divs[0];\n var t = divs.Skip(1).ToList();\n if (n < h) {\n return Semiperfect(n, t);\n } else {\n return n == h\n || Semiperfect(n - h, t)\n || Semiperfect(n, t);\n }\n } else {\n return false;\n }\n }\n\n static List<bool> Sieve(int limit) {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n bool[] w = new bool[limit];\n for (int i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n var divs = Divisors(i);\n if (!Abundant(i, divs)) {\n w[i] = true;\n } else if (Semiperfect(i, divs)) {\n for (int j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n return w.ToList();\n }\n\n static void Main() {\n var w = Sieve(17_000);\n int count = 0;\n int max = 25;\n Console.WriteLine(\"The first 25 weird numbers:\");\n for (int n = 2; count < max; n += 2) {\n if (!w[n]) {\n Console.Write(\"{0} \", n);\n count++;\n }\n }\n Console.WriteLine();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "def divisors(n : Int32) : Array(Int32)\n divs = [1]\n divs2 = [] of Int32\n\n i = 2\n while i * i < n\n if n % i == 0\n j = n // i\n divs << i\n divs2 << j if i != j\n end\n\n i += 1\n end\n\n i = divs.size - 1\n\n # TODO: Use reverse\n while i >= 0\n divs2 << divs[i]\n i -= 1\n end\n\n divs2\nend\n\ndef abundant(n : Int32, divs : Array(Int32)) : Bool\n divs.sum > n\nend\n\ndef semiperfect(n : Int32, divs : Array(Int32)) : Bool\n if divs.size > 0\n h = divs[0]\n t = divs[1..]\n\n return n < h ? semiperfect(n, t) : n == h || semiperfect(n - h, t) || semiperfect(n, t)\n end\n\n return false\nend\n\ndef sieve(limit : Int32) : Array(Bool)\n # false denotes abundant and not semi-perfect.\n # Only interested in even numbers >= 2\n\n w = Array(Bool).new(limit, false) # An array filled with 'false'\n\n i = 2\n while i < limit\n if !w[i]\n divs = divisors i\n\n if !abundant(i, divs)\n w[i] = true\n elsif semiperfect(i, divs)\n j = i\n while j < limit\n w[j] = true\n j += i\n end\n end\n end\n\n i += 2\n end\n\n w\nend\n\ndef main\n w = sieve 17000\n count = 0\n max = 25\n\n print \"The first 25 weird numbers are: \"\n\n n = 2\n while count < max\n if !w[n]\n print \"#{n} \"\n count += 1\n end\n\n n += 2\n end\n\n puts \"\\n\"\nend\n\nrequire \"benchmark\"\nputs Benchmark.measure { main }\n", "language": "Crystal" }, { "code": "import std.algorithm;\nimport std.array;\nimport std.stdio;\n\nint[] divisors(int n) {\n int[] divs = [1];\n int[] divs2;\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int j = n / i;\n divs ~= i;\n if (i != j) {\n divs2 ~= j;\n }\n }\n }\n divs2 ~= divs.reverse;\n return divs2;\n}\n\nbool abundant(int n, int[] divs) {\n return divs.sum() > n;\n}\n\nbool semiperfect(int n, int[] divs) {\n // This algorithm is O(2^N) for N == divs.length when number is not semiperfect.\n // Comparing with (divs.sum < n) instead (divs.length==0) removes unnecessary\n // recursive binary tree branches.\n auto s = divs.sum;\n if(s == n)\n return true;\n else if ( s<n )\n return false;\n else {\n auto h = divs[0];\n auto t = divs[1..$];\n if (n < h) {\n return semiperfect(n, t);\n } else {\n return n == h\n // Supossin h is part of the sum\n || semiperfect(n - h, t)\n // Supossin h is not part of the sum\n || semiperfect(n, t);\n }\n }\n}\n\nbool[] sieve(int limit) {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n auto w = uninitializedArray!(bool[])(limit);\n w[] = false;\n for (int i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n auto divs = divisors(i);\n if (!abundant(i, divs)) {\n w[i] = true;\n } else if (semiperfect(i, divs)) {\n for (int j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n return w;\n}\n\nvoid main() {\n auto w = sieve(17_000);\n int count = 0;\n int max = 25;\n writeln(\"The first 25 weird numbers:\");\n for (int n = 2; count < max; n += 2) {\n if (!w[n]) {\n write(n, ' ');\n count++;\n }\n }\n writeln;\n}\n", "language": "D" }, { "code": "let divisors n = [1..n/2] |> List.filter (fun x->n % x = 0)\n\nlet abundant (n:int) divs = Seq.sum(divs) > n\n\nlet rec semiperfect (n:int) (divs:List<int>) =\n if divs.Length > 0 then\n let h = divs.Head\n let t = divs.Tail\n if n < h then\n semiperfect n t\n else\n n = h || (semiperfect (n - h) t) || (semiperfect n t)\n else false\n\nlet weird n =\n let d = divisors n\n if abundant n d then\n not(semiperfect n d)\n else\n false\n\n[<EntryPoint>]\nlet main _ =\n let mutable i = 1\n let mutable count = 0\n while (count < 25) do\n if (weird i) then\n count <- count + 1\n printf \"%d -> %d\\n\" count i\n i <- i + 1\n\n 0 // return an integer exit code\n", "language": "F-Sharp" }, { "code": "USING: combinators.short-circuit io kernel lists lists.lazy\nlocals math math.primes.factors prettyprint sequences ;\nIN: rosetta-code.weird-numbers\n\n:: has-sum? ( n seq -- ? )\n seq [ f ] [\n unclip-slice :> ( xs x )\n n x < [ n xs has-sum? ] [\n {\n [ n x = ]\n [ n x - xs has-sum? ]\n [ n xs has-sum? ]\n } 0||\n ] if\n ] if-empty ;\n\n: weird? ( n -- ? )\n dup divisors but-last reverse\n { [ sum < ] [ has-sum? not ] } 2&& ;\n\n: weirds ( -- list ) 1 lfrom [ weird? ] lfilter ;\n\n: weird-numbers-demo ( -- )\n \"First 25 weird numbers:\" print\n 25 weirds ltake list>array . ;\n\nMAIN: weird-numbers-demo\n", "language": "Factor" }, { "code": "Function GetFactors(n As Long,r() As Long) As Long\n Redim r(0)\n r(0)=1\n Dim As Long count,acc\n For z As Long=2 To n\\2\n If n Mod z=0 Then\n count+=1:redim preserve r(0 to count)\n r(count)=z\n acc+=z\n End If\n Next z\n Return 1+acc\nEnd Function\n\nsub sumcombinations(arr() As Long,n As Long,r As Long,index As Long,_data() As Long,i As Long,Byref ans As Long,ref As Long)\n Dim As Long acc\n If index=r Then\n For j As Long=0 To r-1\n acc+=_data(j)\n If acc=ref Then ans=1:Return\n If acc>ref then return\n Next j\n Return\n End If\n If i>=n Or ans<>0 Then Return\n _data(index) = arr(i)\n sumcombinations(arr(),n,r,index + 1,_data(),i+1,ans,ref)\n sumcombinations(arr(),n,r,index,_data(),i+1,ans,ref)\nEnd sub\n\nFunction IsWeird(u() As Long,num As Long) As Long\n Redim As Long d()\n Dim As Long ans\n For r As Long=2 To Ubound(u)\n Redim d(r)\n ans=0\n sumcombinations(u(),Ubound(u)+1,r,0,d(),0,ans,num)\n If ans =1 Then Return 0\n Next r\n Return 1\nEnd Function\n\nRedim As Long u()\nDim As Long SumFactors,number=2,count\nDo\n number+=2\n SumFactors=GetFactors(number,u())\n If SumFactors>number Then\n If IsWeird(u(),number) Then Print number;\" \";:count+=1\n End If\nLoop Until count=25\nPrint\nPrint \"first 25 done\"\nSleep\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc divisors(n int) []int {\n divs := []int{1}\n divs2 := []int{}\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n divs = append(divs, i)\n if i != j {\n divs2 = append(divs2, j)\n }\n }\n }\n for i := len(divs) - 1; i >= 0; i-- {\n divs2 = append(divs2, divs[i])\n }\n return divs2\n}\n\nfunc abundant(n int, divs []int) bool {\n sum := 0\n for _, div := range divs {\n sum += div\n }\n return sum > n\n}\n\nfunc semiperfect(n int, divs []int) bool {\n le := len(divs)\n if le > 0 {\n h := divs[0]\n t := divs[1:]\n if n < h {\n return semiperfect(n, t)\n } else {\n return n == h || semiperfect(n-h, t) || semiperfect(n, t)\n }\n } else {\n return false\n }\n}\n\nfunc sieve(limit int) []bool {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n w := make([]bool, limit)\n for i := 2; i < limit; i += 2 {\n if w[i] {\n continue\n }\n divs := divisors(i)\n if !abundant(i, divs) {\n w[i] = true\n } else if semiperfect(i, divs) {\n for j := i; j < limit; j += i {\n w[j] = true\n }\n }\n }\n return w\n}\n\nfunc main() {\n w := sieve(17000)\n count := 0\n const max = 25\n fmt.Println(\"The first 25 weird numbers are:\")\n for n := 2; count < max; n += 2 {\n if !w[n] {\n fmt.Printf(\"%d \", n)\n count++\n }\n }\n fmt.Println()\n}\n", "language": "Go" }, { "code": "weirds :: [Int]\nweirds = filter abundantNotSemiperfect [1 ..]\n\nabundantNotSemiperfect :: Int -> Bool\nabundantNotSemiperfect n =\n let ds = descProperDivisors n\n d = sum ds - n\n in 0 < d && not (hasSum d ds)\n\nhasSum :: Int -> [Int] -> Bool\nhasSum _ [] = False\nhasSum n (x:xs)\n | n < x = hasSum n xs\n | otherwise = (n == x) || hasSum (n - x) xs || hasSum n xs\n\ndescProperDivisors\n :: Integral a\n => a -> [a]\ndescProperDivisors n =\n let root = (floor . sqrt) (fromIntegral n :: Double)\n lows = filter ((0 ==) . rem n) [root,root - 1 .. 1]\n factors\n | n == root ^ 2 = tail lows\n | otherwise = lows\n in tail $ reverse (quot n <$> lows) ++ factors\n\nmain :: IO ()\nmain =\n (putStrLn . unlines) $\n zipWith (\\i x -> show i ++ (\" -> \" ++ show x)) [1 ..] (take 25 weirds)\n", "language": "Haskell" }, { "code": "factor=: [: }: [: , [: */&> [: { [: <@(^ i.@>:)/\"1 [: |: __&q:\n\nclassify=: 3 : 0\n weird =: perfect =: deficient =: abundant =: i. 0\n a=: (i. -. 0 , deficient =: 1 , i.&.:(p:inv)) y NB. a are potential semi-perfect numbers\n for_n. a do.\n if. n e. a do.\n factors=. factor n\n sf =. +/ factors\n if. sf < n do.\n deficient =: deficient , n\n else.\n if. n < sf do.\n abundant=: abundant , n\n else.\n perfect =: perfect , n\n a =: a -. (2+i.)@<.&.(%&n) y NB. remove multiples of perfect numbers\n continue.\n end.\n NB. compute sums of subsets to detect semiperfection\n NB. the following algorithm correctly finds weird numbers less than 20000\n NB. remove large terms necessary for the sum to reduce the Catalan tally of sets\n factors =. /:~ factors NB. ascending sort\n NB. if the sum of the length one outfixes is less n then the factor is required in the semiperfect set.\n i_required =. n (1 i.~ (>(1+/\\.]))) factors\n target =. n - +/ i_required }. factors\n t =. i_required {. factors\n NB. work in chunks of 2^16 to reduce memory requirement\n sp =. target e. ; (,:~2^16) <@([: +/\"1 t #~ (_ ,(#t)) {. #:);.3 i. 2 ^ # t\n if. sp do.\n a =: a -. (2+i.)@<.&.(%&n) y NB. remove multiples of semi perfect numbers\n else.\n weird =: weird , n\n a =: a -. n\n end.\n end.\n end.\n end.\n a =: a -. deficient\n weird\n)\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class WeirdNumbers {\n\n public static void main(String[] args) {\n int n = 2;\n // n += 2 : No odd weird numbers < 10^21\n for ( int count = 1 ; count <= 25 ; n += 2 ) {\n if ( isWeird(n) ) {\n System.out.printf(\"w(%d) = %d%n\", count, n);\n count++;\n }\n }\n }\n\n private static boolean isWeird(int n) {\n List<Integer> properDivisors = getProperDivisors(n);\n return isAbundant(properDivisors, n) && ! isSemiPerfect(properDivisors, n);\n }\n\n private static boolean isAbundant(List<Integer> divisors, int n) {\n int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n return divisorSum > n;\n }\n\n // Use Dynamic Programming\n private static boolean isSemiPerfect(List<Integer> divisors, int sum) {\n int size = divisors.size();\n\n // The value of subset[i][j] will be true if there is a subset of divisors[0..j-1] with sum equal to i\n boolean subset[][] = new boolean[sum+1][size+1];\n\n // If sum is 0, then answer is true\n for (int i = 0; i <= size; i++) {\n subset[0][i] = true;\n }\n\n // If sum is not 0 and set is empty, then answer is false\n for (int i = 1; i <= sum; i++) {\n subset[i][0] = false;\n }\n\n // Fill the subset table in bottom up manner\n for ( int i = 1 ; i <= sum ; i++ ) {\n for ( int j = 1 ; j <= size ; j++ ) {\n subset[i][j] = subset[i][j-1];\n int test = divisors.get(j-1);\n if ( i >= test ) {\n subset[i][j] = subset[i][j] || subset[i - test][j-1];\n }\n }\n }\n\n return subset[sum][size];\n }\n\n private static final List<Integer> getProperDivisors(int number) {\n List<Integer> divisors = new ArrayList<Integer>();\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 1 ; i <= sqrt ; i++ ) {\n if ( number % i == 0 ) {\n divisors.add(i);\n int div = number / i;\n if ( div != i && div != number ) {\n divisors.add(div);\n }\n }\n }\n return divisors;\n }\n\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // main :: IO ()\n const main = () =>\n take(25, weirds());\n\n\n // weirds :: Gen [Int]\n function* weirds() {\n let\n x = 1,\n i = 1;\n while (true) {\n x = until(isWeird, succ, x)\n console.log(i.toString() + ' -> ' + x)\n yield x;\n x = 1 + x;\n i = 1 + i;\n }\n }\n\n\n // isWeird :: Int -> Bool\n const isWeird = n => {\n const\n ds = descProperDivisors(n),\n d = sum(ds) - n;\n return 0 < d && !hasSum(d, ds)\n };\n\n // hasSum :: Int -> [Int] -> Bool\n const hasSum = (n, xs) => {\n const go = (n, xs) =>\n 0 < xs.length ? (() => {\n const\n h = xs[0],\n t = xs.slice(1);\n return n < h ? (\n go(n, t)\n ) : (\n n == h || hasSum(n - h, t) || hasSum(n, t)\n );\n })() : false;\n return go(n, xs);\n };\n\n\n // descProperDivisors :: Int -> [Int]\n const descProperDivisors = n => {\n const\n rRoot = Math.sqrt(n),\n intRoot = Math.floor(rRoot),\n blnPerfect = rRoot === intRoot,\n lows = enumFromThenTo(intRoot, intRoot - 1, 1)\n .filter(x => (n % x) === 0);\n return (\n reverse(lows)\n .slice(1)\n .map(x => n / x)\n ).concat((blnPerfect ? tail : id)(lows))\n };\n\n\n // GENERIC FUNCTIONS ----------------------------\n\n\n // enumFromThenTo :: Int -> Int -> Int -> [Int]\n const enumFromThenTo = (x1, x2, y) => {\n const d = x2 - x1;\n return Array.from({\n length: Math.floor(y - x2) / d + 2\n }, (_, i) => x1 + (d * i));\n };\n\n // id :: a -> a\n const id = x => x;\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // succ :: Enum a => a -> a\n const succ = x => 1 + x;\n\n // sum :: [Num] -> Num\n const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = (n, xs) =>\n 'GeneratorFunction' !== xs.constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# unordered\ndef proper_divisors:\n . as $n\n | if $n > 1 then 1,\n ( range(2; 1 + (sqrt|floor)) as $i\n | if ($n % $i) == 0 then $i,\n (($n / $i) | if . == $i then empty else . end)\n else empty\n\t end)\n else empty\n end;\n\n# Is n semiperfect given that divs are the proper divisors\ndef semiperfect(n; divs):\n (divs|length) as $le\n | if $le == 0 then false\n else divs[0] as $h\n | if n == $h then true\n elif $le == 1 then false\n else divs[1:] as $t\n | if n < $h then semiperfect(n; $t)\n else semiperfect(n-$h; $t) or semiperfect(n; $t)\n\tend\n end\n end ;\n\ndef sieve(limit):\n # 'false' denotes abundant and not semi-perfect.\n # Only interested in even numbers >= 2\n (reduce range(6; limit; 6) as $j ([]; .[$j] = true)) # eliminates multiples of 3\n | reduce range(2; limit; 2) as $i (.;\n if (.[$i]|not)\n then [$i|proper_divisors] as $divs\n | ($divs | add) as $sum\n | if $sum <= $i\n then .[$i] = true\n elif (semiperfect($sum-$i; $divs))\n then reduce range($i; limit; $i) as $j (.; .[$j] = true)\n else .\n end\n\telse .\n\tend) ;\n\n# Print up to $max weird numbers based on the given sieve size, $limit.\ndef task($limit; $max):\n sieve($limit) as $w\n | def weirds:\n range(2; $w|length; 2) | select($w[.]|not);\n\n # collect into an array for ease of counting\n [limit($max; weirds)]\n | \"The first \\(length) weird numbers are:\", . ;\n\n# The parameters should be set on the command line:\ntask($sieve; $limit)\n", "language": "Jq" }, { "code": "using Primes\n\nfunction nosuchsum(revsorted, num)\n if sum(revsorted) < num\n return true\n end\n for (i, n) in enumerate(revsorted)\n if n > num\n continue\n elseif n == num\n return false\n elseif !nosuchsum(revsorted[i+1:end], num - n)\n return false\n end\n end\n true\nend\n\nfunction isweird(n)\n if n < 70 || isodd(n)\n return false\n else\n f = [one(n)]\n for (p, x) in factor(n)\n f = reduce(vcat, [f*p^i for i in 1:x], init=f)\n end\n pop!(f)\n return sum(f) > n && nosuchsum(sort(f, rev=true), n)\n end\nend\n\nfunction testweird(N)\n println(\"The first $N weird numbers are: \")\n count, n = 0, 69\n while count < N\n if isweird(n)\n count += 1\n print(\"$n \")\n end\n n += 1\n end\nend\n\ntestweird(25)\n", "language": "Julia" }, { "code": "// Version 1.3.21\n\nfun divisors(n: Int): List<Int> {\n val divs = mutableListOf(1)\n val divs2 = mutableListOf<Int>()\n var i = 2\n while (i * i <= n) {\n if (n % i == 0) {\n val j = n / i\n divs.add(i)\n if (i != j) divs2.add(j)\n }\n i++\n }\n divs2.addAll(divs.asReversed())\n return divs2\n}\n\nfun abundant(n: Int, divs: List<Int>) = divs.sum() > n\n\nfun semiperfect(n: Int, divs: List<Int>): Boolean {\n if (divs.size > 0) {\n val h = divs[0]\n val t = divs.subList(1, divs.size)\n if (n < h) {\n return semiperfect(n, t)\n } else {\n return n == h || semiperfect(n-h, t) || semiperfect(n, t)\n }\n } else {\n return false\n }\n}\n\nfun sieve(limit: Int): BooleanArray {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n val w = BooleanArray(limit)\n for (i in 2 until limit step 2) {\n if (w[i]) continue\n val divs = divisors(i)\n if (!abundant(i, divs)) {\n w[i] = true\n } else if (semiperfect(i, divs)) {\n for (j in i until limit step i) w[j] = true\n }\n }\n return w\n}\n\nfun main() {\n val w = sieve(17000)\n var count = 0\n val max = 25\n println(\"The first 25 weird numbers are:\")\n var n = 2\n while (count < max) {\n if (!w[n]) {\n print(\"$n \")\n count++\n }\n n += 2\n }\n println()\n}\n", "language": "Kotlin" }, { "code": "function make(n, d)\n local a = {}\n for i=1,n do\n table.insert(a, d)\n end\n return a\nend\n\nfunction reverse(t)\n local n = #t\n local i = 1\n while i < n do\n t[i],t[n] = t[n],t[i]\n i = i + 1\n n = n - 1\n end\nend\n\nfunction tail(list)\n return { select(2, unpack(list)) }\nend\n\nfunction divisors(n)\n local divs = {}\n table.insert(divs, 1)\n\n local divs2 = {}\n\n local i = 2\n while i * i <= n do\n if n % i == 0 then\n local j = n / i\n table.insert(divs, i)\n if i ~= j then\n table.insert(divs2, j)\n end\n end\n i = i + 1\n end\n\n reverse(divs)\n for i,v in pairs(divs) do\n table.insert(divs2, v)\n end\n return divs2\nend\n\nfunction abundant(n, divs)\n local sum = 0\n for i,v in pairs(divs) do\n sum = sum + v\n end\n return sum > n\nend\n\nfunction semiPerfect(n, divs)\n if #divs > 0 then\n local h = divs[1]\n local t = tail(divs)\n if n < h then\n return semiPerfect(n, t)\n else\n return n == h\n or semiPerfect(n - h, t)\n or semiPerfect(n, t)\n end\n else\n return false\n end\nend\n\nfunction sieve(limit)\n -- false denotes abundant and not semi-perfect.\n -- Only interested in even numbers >= 2\n local w = make(limit, false)\n local i = 2\n while i < limit do\n if not w[i] then\n local divs = divisors(i)\n if not abundant(i, divs) then\n w[i] = true\n elseif semiPerfect(i, divs) then\n local j = i\n while j < limit do\n w[j] = true\n j = j + i\n end\n end\n end\n i = i + 1\n end\n return w\nend\n\nfunction main()\n local w = sieve(17000)\n local count = 0\n local max = 25\n print(\"The first 25 weird numbers:\")\n local n = 2\n while count < max do\n if not w[n] then\n io.write(n, ' ')\n count = count + 1\n end\n n = n + 2\n end\n print()\nend\n\nmain()\n", "language": "Lua" }, { "code": "ClearAll[WeirdNumberQ, HasSumQ]\nHasSumQ[n_Integer, xs_List] := HasSumHelperQ[n, ReverseSort[xs]]\nHasSumHelperQ[n_Integer, xs_List] := Module[{h, t},\n If[Length[xs] > 0,\n h = First[xs];\n t = Drop[xs, 1];\n If[n < h,\n HasSumHelperQ[n, t]\n ,\n n == h \\[Or] HasSumHelperQ[n - h, t] \\[Or] HasSumHelperQ[n, t]\n ]\n ,\n False\n ]\n ]\nWeirdNumberQ[n_Integer] := Module[{divs},\n divs = Most[Divisors[n]];\n If[Total[divs] > n,\n ! HasSumQ[n, divs]\n ,\n False\n ]\n ]\nr = {};\nn = 0;\nWhile[\n Length[r] < 25,\n If[WeirdNumberQ[++n], AppendTo[r, n]]\n ]\nPrint[r]\n", "language": "Mathematica" }, { "code": "import algorithm, math, strutils\n\nfunc divisors(n: int): seq[int] =\n var smallDivs = @[1]\n for i in 2..sqrt(n.toFloat).int:\n if n mod i == 0:\n let j = n div i\n smallDivs.add i\n if i != j: result.add j\n result.add reversed(smallDivs)\n\nfunc abundant(n: int; divs: seq[int]): bool {.inline.}=\n sum(divs) > n\n\nfunc semiperfect(n: int; divs: seq[int]): bool =\n if divs.len > 0:\n let h = divs[0]\n let t = divs[1..^1]\n result = if n < h: semiperfect(n, t)\n else: n == h or semiperfect(n - h, t) or semiperfect(n, t)\n\nfunc sieve(limit: int): seq[bool] =\n # False denotes abundant and not semi-perfect.\n # Only interested in even numbers >= 2.\n result.setLen(limit)\n for i in countup(2, limit - 1, 2):\n if result[i]: continue\n let divs = divisors(i)\n if not abundant(i, divs):\n result[i] = true\n elif semiperfect(i, divs):\n for j in countup(i, limit - 1, i):\n result[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 if not w[n]: list.add n\n inc n, 2\necho list.join(\" \")\n", "language": "Nim" }, { "code": "use strict;\nuse feature 'say';\n\nuse List::Util 'sum';\nuse POSIX 'floor';\nuse Algorithm::Combinatorics 'subsets';\nuse ntheory <is_prime divisors>;\n\nsub abundant {\n my($x) = @_;\n my $s = sum( my @l = is_prime($x) ? 1 : grep { $x != $_ } divisors($x) );\n $s > $x ? ($s, sort { $b <=> $a } @l) : ();\n}\n\nmy(@weird,$n);\nwhile () {\n $n++;\n my ($sum, @div) = abundant($n);\n next unless $sum; # Weird number must be abundant, skip it if it isn't.\n next if $sum / $n > 1.1; # There aren't any weird numbers with a sum:number ratio greater than 1.08 or so.\n\n if ($n >= 10430 and (! int $n%70) and is_prime(int $n/70)) {\n # It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird\n } else {\n my $next;\n my $l = shift @div;\n my $iter = subsets(\\@div);\n while (my $s = $iter->next) {\n ++$next and last if sum(@$s) == $n - $l;\n }\n next if $next;\n }\n push @weird, $n;\n last if @weird == 25;\n}\n\nsay \"The first 25 weird numbers:\\n\" . join ' ', @weird;\n", "language": "Perl" }, { "code": "use 5.010;\nuse strict;\nuse ntheory qw(vecsum divisors divisor_sum);\n\nsub is_pseudoperfect {\n my ($n, $d, $s, $m) = @_;\n\n $d //= do { my @d = divisors($n); pop(@d); \\@d };\n $s //= vecsum(@$d);\n $m //= $#$d;\n\n return 0 if $m < 0;\n\n while ($d->[$m] > $n) {\n $s -= $d->[$m--];\n }\n\n return 1 if ($n == $s or $d->[$m] == $n);\n\n is_pseudoperfect($n-$d->[$m], $d, $s-$d->[$m], $m - 1) ||\n is_pseudoperfect($n, $d, $s-$d->[$m], $m - 1);\n}\n\nsub is_weird {\n my ($n) = @_;\n divisor_sum($n) > 2*$n and not is_pseudoperfect($n);\n}\n\nmy @weird;\nfor (my $k = 1 ; @weird < 25 ; ++$k) {\n push(@weird, $k) if is_weird($k);\n}\n\nsay \"The first 25 weird numbers:\\n@weird\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">abundant</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #000000;\">n</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">semiperfect</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">];</span> <span style=\"color: #000000;\">divs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">h</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">h</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">semiperfect</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">semiperfect</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">sieve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- true denotes abundant and not semi-perfect.\n -- only interested in even numbers &gt;= 2</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">wierd</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">6</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">6</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- eliminate multiples of 3</span>\n <span style=\"color: #000000;\">wierd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">wierd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">divs</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">factors</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">abundant</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">wierd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">semiperfect</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">divs</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">wierd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">wierd</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #000080;font-style:italic;\">--constant MAX = 25, sieve_limit = 16313 </span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">MAX</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">50</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">sieve_limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">26533</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">wierd</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">sieve</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sieve_limit</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">sieve_limit</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">wierd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">MAX</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">shorten</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"weird numbers\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">))})</span>\n<!--\n", "language": "Phix" }, { "code": "'''Weird numbers'''\n\nfrom itertools import chain, count, islice, repeat\nfrom functools import reduce\nfrom math import sqrt\nfrom time import time\n\n\n# weirds :: Gen [Int]\ndef weirds():\n '''Non-finite stream of weird numbers.\n (Abundant, but not semi-perfect)\n OEIS: A006037\n '''\n def go(n):\n ds = descPropDivs(n)\n d = sum(ds) - n\n return [n] if 0 < d and not hasSum(d, ds) else []\n return concatMap(go)(count(1))\n\n\n# hasSum :: Int -> [Int] -> Bool\ndef hasSum(n, xs):\n '''Does any subset of xs sum to n ?\n (Assuming xs to be sorted in descending\n order of magnitude)'''\n def go(n, xs):\n if xs:\n h, t = xs[0], xs[1:]\n if n < h: # Head too big. Forget it. Tail ?\n return go(n, t)\n else:\n # The head IS the target ?\n # Or the tail contains a sum for the\n # DIFFERENCE between the head and the target ?\n # Or the tail contains some OTHER sum for the target ?\n return n == h or go(n - h, t) or go(n, t)\n else:\n return False\n return go(n, xs)\n\n\n# descPropDivs :: Int -> [Int]\ndef descPropDivs(n):\n '''Descending positive divisors of n,\n excluding n itself.'''\n root = sqrt(n)\n intRoot = int(root)\n blnSqr = root == intRoot\n lows = [x for x in range(1, 1 + intRoot) if 0 == n % x]\n return [\n n // x for x in (\n lows[1:-1] if blnSqr else lows[1:]\n )\n ] + list(reversed(lows))\n\n\n# --------------------------TEST---------------------------\n\n# main :: IO ()\ndef main():\n '''Test'''\n\n start = time()\n n = 50\n xs = take(n)(weirds())\n\n print(\n (tabulated('First ' + str(n) + ' weird numbers:\\n')(\n lambda i: str(1 + i)\n )(str)(5)(\n index(xs)\n )(range(0, n)))\n )\n print(\n '\\nApprox computation time: ' +\n str(int(1000 * (time() - start))) + ' ms'\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n,\n subdividing the contents of xs.\n Where the length of xs is not evenly divible,\n the final list will be shorter than n.'''\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list or string over which a function f\n has been mapped.\n The list monad can be derived by using an (a -> [b])\n function which wraps its output in a list (using an\n empty list to represent computational failure).\n '''\n return lambda xs: chain.from_iterable(map(f, xs))\n\n\n# index (!!) :: [a] -> Int -> a\ndef index(xs):\n '''Item at given (zero-based) index.'''\n return lambda n: None if 0 > n else (\n xs[n] if (\n hasattr(xs, \"__getitem__\")\n ) else next(islice(xs, n, None))\n )\n\n\n# paddedMatrix :: a -> [[a]] -> [[a]]\ndef paddedMatrix(v):\n ''''A list of rows padded to equal length\n (where needed) with instances of the value v.'''\n def go(rows):\n return paddedRows(\n len(max(rows, key=len))\n )(v)(rows)\n return lambda rows: go(rows) if rows else []\n\n\n# paddedRows :: Int -> a -> [[a]] -[[a]]\ndef paddedRows(n):\n '''A list of rows padded (but never truncated)\n to length n with copies of value v.'''\n def go(v, xs):\n def pad(x):\n d = n - len(x)\n return (x + list(repeat(v, d))) if 0 < d else x\n return list(map(pad, xs))\n return lambda v: lambda xs: go(v, xs) if xs else []\n\n\n# showColumns :: Int -> [String] -> String\ndef showColumns(n):\n '''A column-wrapped string\n derived from a list of rows.'''\n def go(xs):\n def fit(col):\n w = len(max(col, key=len))\n\n def pad(x):\n return x.ljust(4 + w, ' ')\n return ''.join(map(pad, col))\n\n q, r = divmod(len(xs), n)\n return unlines(map(\n fit,\n transpose(paddedMatrix('')(\n chunksOf(q + int(bool(r)))(\n xs\n )\n ))\n ))\n return lambda xs: go(xs)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value. For numeric types, (1 +).'''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\n# tabulated :: String -> (a -> String) ->\n# (b -> String) ->\n# Int ->\n# (a -> b) -> [a] -> String\ndef tabulated(s):\n '''Heading -> x display function -> fx display function ->\n number of columns -> f -> value list -> tabular string.'''\n def go(xShow, fxShow, intCols, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + showColumns(intCols)([\n xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda nCols: (\n lambda f: lambda xs: go(\n xShow, fxShow, nCols, f, xs\n )\n )\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# transpose :: Matrix a -> Matrix a\ndef transpose(m):\n '''The rows and columns of the argument transposed.\n (The matrix containers and rows can be lists or tuples).'''\n if m:\n inner = type(m[0])\n z = zip(*m)\n return (type(m))(\n map(inner, z) if tuple != inner else z\n )\n else:\n return m\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.'''\n def go(f, x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return lambda f: lambda x: go(f, x)\n\n\n# MAIN ----------------------------------------------------\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ stack ] is target ( --> s )\n [ stack ] is success ( --> s )\n [ stack ] is makeable ( --> s )\n\n [ bit makeable take\n 2dup & 0 !=\n dip [ | makeable put ] ] is made ( n --> b )\n\n [ ' [ 0 ] swap\n dup target put\n properdivisors\n 0 over witheach +\n target share > not iff\n [ target release\n 2drop false ] done\n true success put\n 0 makeable put\n witheach\n [ over witheach\n [ over dip\n [ +\n dup target share = iff\n [ false success replace\n drop conclude ] done\n dup target share < iff\n [ dup made not iff\n join else drop ]\n else drop ] ]\n success share not if conclude\n drop ]\n drop\n target release\n makeable release\n success take ] is weird ( n --> b )\n\n [] 0\n [ 1+\n dup weird if\n [ tuck join swap ]\n over size 25 = until ]\n drop\n echo\n", "language": "Quackery" }, { "code": "#lang racket\n\n(require math/number-theory)\n\n(define (abundant? n proper-divisors)\n (> (apply + proper-divisors) n))\n\n(define (semi-perfect? n proper-divisors)\n (let recur ((ds proper-divisors) (n n))\n (or (zero? n)\n (and (positive? n)\n (pair? ds)\n (or (recur (cdr ds) n)\n (recur (cdr ds) (- n (car ds))))))))\n\n(define (weird? n)\n (let ((proper-divisors (drop-right (divisors n) 1))) ;; divisors includes n\n (and (abundant? n proper-divisors) (not (semi-perfect? n proper-divisors)))))\n\n(module+ main\n (let recur ((i 0) (n 1) (acc null))\n (cond [(= i 25) (reverse acc)]\n [(weird? n) (recur (add1 i) (add1 n) (cons n acc))]\n [else (recur i (add1 n) acc)])))\n\n(module+ test\n (require rackunit)\n (check-true (weird? 70))\n (check-false (weird? 12)))\n", "language": "Racket" }, { "code": "sub abundant (\\x) {\n my @l = x.is-prime ?? 1 !! flat\n 1, (2 .. x.sqrt.floor).map: -> \\d {\n my \\y = x div d;\n next if y * d !== x;\n d !== y ?? (d, y) !! d\n };\n (my $s = @l.sum) > x ?? ($s, |@l.sort(-*)) !! ();\n}\n\nmy @weird = (2, 4, {|($_ + 4, $_ + 6)} ... *).map: -> $n {\n my ($sum, @div) = $n.&abundant;\n next unless $sum; # Weird number must be abundant, skip it if it isn't.\n next if $sum / $n > 1.1; # There aren't any weird numbers with a sum:number ratio greater than 1.08 or so.\n if $n >= 10430 and ($n %% 70) and ($n div 70).is-prime {\n # It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird\n } else {\n my $next;\n my $l = @div.shift;\n ++$next and last if $_.sum == $n - $l for @div.combinations;\n next if $next;\n }\n $n\n}\n\nput \"The first 25 weird numbers:\\n\", @weird[^25];\n", "language": "Raku" }, { "code": "/*REXX program finds and displays N weird numbers in a vertical format (with index).*/\nparse arg n cols . /*obtain optional arguments from the CL*/\nif n=='' | n==\",\" then n= 25 /*Not specified? Then use the default.*/\nif cols=='' | cols==\",\" then cols= 10 /* \" \" \" \" \" \" */\nw= 10 /*width of a number in any column. */\nif cols>0 then say ' index │'center(' weird numbers', 1 + cols*(w+1) )\nif cols>0 then say '───────┼'center(\"\" , 1 + cols*(w+1), '─')\nidx= 1; $= /*index for the output list; $: 1 line*/\nweirds= 0 /*the count of weird numbers (so far).*/\n do j=2 by 2 until weirds==n /*examine even integers 'til have 'nuff*/\n if \\weird(j) then iterate /*Not a weird number? Then skip it. */\n weirds= weirds + 1 /*bump the count of weird numbers. */\n c= commas(j) /*maybe add commas to the number. */\n $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/\n if weirds//cols\\==0 then iterate /*have we populated a line of output? */\n say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */\n idx= idx + cols /*bump the index count for the output*/\n end /*j*/\n\nif $\\=='' then say center(idx, 7)\"│\" substr($, 2) /*possible display residual output.*/\nif cols>0 then say '───────┴'center(\"\" , 1 + cols*(w+1), '─')\nsay\nsay 'Found ' commas(weirds) ' weird numbers'\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg _; do ic=length(_)-3 to 1 by -3; _=insert(',', _, ic); end; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nDaS: procedure; parse arg x 1 z 1,b; a= 1 /*get X,Z,B (the 1st arg); init A list.*/\n r= 0; q= 1 /* [↓] ══integer square root══ ___ */\n do while q<=z; q=q*4; end /*R: an integer which will be √ X */\n do while q>1; q=q%4; _= z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end\n end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/\n sig= a /*initialize the sigma so far. ___ */\n do j=2 to r - (r*r==x) /*divide by some integers up to √ X */\n if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α and ß. */\n sig= sig +j +x%j /*bump the sigma (the sum of divisors).*/\n end\n end /*j*/ /* [↑] % is the REXX integer division*/\n /* [↓] adjust for a square. ___*/\n if j*j==x then return sig+j a j b /*Was X a square? If so, add √ X */\n return sig a b /*return the divisors (both lists). */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nweird: procedure; parse arg x . /*obtain a # to be tested for weirdness*/\n if x<70 | x//3==0 then return 0 /*test if X is too low or multiple of 3*/\n parse value DaS(x) with sigma divs /*obtain sigma and the proper divisors.*/\n if sigma<=x then return 0 /*X isn't abundant (sigma too small).*/\n #= words(divs) /*count the number of divisors for X. */\n if #<3 then return 0 /*Not enough divisors? \" \" */\n if #>15 then return 0 /*number of divs > 15? It's not weird.*/\n a.= /*initialize the A. stemmed array.*/\n do i=1 for #; _= word(divs, i) /*obtain one of the divisors of X. */\n @.i= _; a._= . /*assign proper divs──►@ array; also id*/\n end /*i*/\n df= sigma - x /*calculate difference between Σ and X.*/\n if a.df==. then return 0 /*Any divisor is equal to DF? Not weird*/\n c= 0 /*zero combo counter; calc. power of 2.*/\n do p=1 for 2**#-2; c= c + 1 /*convert P──►binary with leading zeros*/\n yy.c= strip( x2b( d2x(p) ), 'L', 0) /*store this particular combination. */\n end /*p*/\n /* [↓] decreasing partitions is faster*/\n do part=c by -1 for c; s= 0 /*test of a partition add to the arg X.*/\n _= yy.part; L= length(_) /*obtain one method of partitioning. */\n do cp=L by -1 for L /*obtain a sum of a partition. */\n if substr(_,cp,1) then do; s= s + @.cp /*1 bit? Then add ──►S*/\n if s==x then return 0 /*Sum equal? Not weird*/\n if s==df then return 0 /*Sum = DF? \" \" */\n if s>x then iterate /*Sum too big? Try next*/\n end\n end /*cp*/\n end /*part*/; return 1 /*no sum equal to X, so X is weird.*/\n", "language": "REXX" }, { "code": "/*REXX program finds and displays N weird numbers in a vertical format (with index).*/\nparse arg n cols . /*obtain optional arguments from the CL*/\nif n=='' | n==\",\" then n= 400 /*Not specified? Then use the default.*/\nif cols=='' | cols==\",\" then cols= 10 /* \" \" \" \" \" \" */\nw= 10 /*width of a number in any column. */\ncall genP /*generate primes just past Hp. */\nif cols>0 then say ' index │'center(' weird numbers', 1 + cols*(w+1) )\nif cols>0 then say '───────┼'center(\"\" , 1 + cols*(w+1), '─')\nweirds= 0; !!.= 0 /*the count of weird numbers (so far).*/\nidx= 1; $= /*index for the output list; $: 1 line*/\n do j=2 by 2 until weirds==n /*examine even integers 'til have 'nuff*/\n if \\weird(j) then iterate /*Not a weird number? Then skip it. */\n weirds= weirds + 1 /*bump the count of weird numbers. */\n do a=1 for # until _>hp; if @.a<sigma+j then iterate; _= j*@.a; !!._= 1\n end /*a*/\n c= commas(j) /*maybe add commas to the number. */\n $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/\n if weirds//cols\\==0 then iterate /*have we populated a line of output? */\n say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */\n idx= idx + cols /*bump the index count for the output*/\n end /*j*/\n\nif $\\=='' then say center(idx, 7)\"│\" substr($, 2) /*possible display residual output.*/\nif cols>0 then say '───────┴'center(\"\" , 1 + cols*(w+1), '─')\nsay\nsay 'Found ' commas(weirds) ' weird numbers'\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg _; do ic=length(_)-3 to 1 by -3; _=insert(',', _, ic); end; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nDaS: procedure; parse arg x 1 z 1,b; a= 1 /*get X,Z,B (the 1st arg); init A list.*/\n r= 0; q= 1 /* [↓] ══integer square root══ ___ */\n do while q<=z; q=q*4; end /*R: an integer which will be √ X */\n do while q>1; q=q%4; _= z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end\n end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/\n sig = a /*initialize the sigma so far. ___ */\n do j=2 to r - (r*r==x) /*divide by some integers up to √ X */\n if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α & ß. */\n sig= sig +j +x%j /*bump the sigma (the sum of Pdivisors)*/\n end\n end /*j*/ /* [↑] % is the REXX integer division*/\n /* [↓] adjust for a square. ___*/\n if j*j==x then return sig+j a j b /*Was X a square? If so, add √ X */\n return sig a b /*return the divisors (both lists). */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngenP: hp= 1000 * n /*high Prime limit; define 2 low primes*/\n @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */\n #=5; s.#= @.# **2 /*number of primes so far; prime². */\n /* [↓] generate more primes ≤ high.*/\n do j=@.#+2 by 2 for max(0, hp%2-@.#%2-1) /*find odd primes from here on. */\n parse var j '' -1 _; if _==5 then iterate /*J divisible by 5? (right dig)*/\n if j// 3==0 then iterate /*\" \" \" 3? */\n if j// 7==0 then iterate /*\" \" \" 7? */\n /* [↑] the above five lines saves time*/\n do k=5 while s.k<=j /* [↓] divide by the known odd primes.*/\n if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */\n end /*k*/ /* [↑] only process numbers ≤ √ J */\n #= #+1; @.#= j; s.#= j*j /*bump # of Ps; assign next P; P²; P# */\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nweird: procedure expose !!. sigma; parse arg x /*obtain a # to be tested for weirdness*/\n if x<70 | x//3==0 then return 0 /*test if X is too low or multiple of 3*/\n if !!.x then return 1 /*Is this a prime*previous #? Found one*/\n parse value DaS(x) with sigma divs /*obtain sigma and the proper divisors.*/\n if sigma<=x then return 0 /*X isn't abundant (sigma too small).*/\n #= words(divs) /*count the number of divisors for X. */\n if #<3 then return 0 /*Not enough divisors? \" \" */\n if #>15 then return 0 /*number of divs > 15? It's not weird.*/\n a.= /*initialize the A. stemmed array.*/\n do i=1 for #; _= word(divs, i) /*obtain one of the divisors of X. */\n @.i= _; a._= . /*assign proper divs──►@ array; also id*/\n end /*i*/\n df= sigma - x /*calculate difference between Σ and X.*/\n if a.df==. then return 0 /*Any divisor is equal to DF? Not weird*/\n c= 0; u= 2**# /*zero combo counter; calc. power of 2.*/\n do p=1 for u-2; c= c + 1 /*convert P──►binary with leading zeros*/\n yy.c= strip( x2b( d2x(p) ), 'L', 0) /*store this particular combination. */\n end /*p*/\n /* [↓] decreasing partitions is faster*/\n do part=c by -1 for c; s= 0 /*test of a partition add to the arg X.*/\n _= yy.part; L= length(_) /*obtain one method of partitioning. */\n do cp=L by -1 for L /*obtain a sum of a partition. */\n if substr(_,cp,1) then do; s= s + @.cp /*1 bit? Then add ──►S*/\n if s==x then return 0 /*Sum equal? Not weird*/\n if s==df then return 0 /*Sum = DF? \" \" */\n if s>x then iterate /*Sum too big? Try next*/\n end\n end /*cp*/\n end /*part*/\n return 1 /*no sum equal to X, so X is weird.*/\n", "language": "REXX" }, { "code": "def divisors(n)\n divs = [1]\n divs2 = []\n\n i = 2\n while i * i <= n\n if n % i == 0 then\n j = (n / i).to_i\n divs.append(i)\n if i != j then\n divs2.append(j)\n end\n end\n\n i = i + 1\n end\n\n divs2 += divs.reverse\n return divs2\nend\n\ndef abundant(n, divs)\n return divs.sum > n\nend\n\ndef semiperfect(n, divs)\n if divs.length > 0 then\n h = divs[0]\n t = divs[1..-1]\n if n < h then\n return semiperfect(n, t)\n else\n return n == h || semiperfect(n - h, t) || semiperfect(n, t)\n end\n else\n return false\n end\nend\n\ndef sieve(limit)\n w = Array.new(limit, false)\n i = 2\n while i < limit\n if not w[i] then\n divs = divisors(i)\n if not abundant(i, divs) then\n w[i] = true\n elsif semiperfect(i, divs) then\n j = i\n while j < limit\n w[j] = true\n j = j + i\n end\n end\n end\n i = i + 2\n end\n return w\nend\n\ndef main\n w = sieve(17000)\n count = 0\n max = 25\n print \"The first %d weird numbers:\\n\" % [max]\n n = 2\n while count < max\n if not w[n] then\n print n, \" \"\n count = count + 1\n end\n n = n + 2\n end\n print \"\\n\"\nend\n\nmain()\n", "language": "Ruby" }, { "code": "func is_pseudoperfect(n, d = n.divisors.first(-1), s = d.sum, m = d.end) {\n\n return false if (m < 0)\n\n while (d[m] > n) {\n s -= d[m--]\n }\n\n return true if (n == s)\n return true if (d[m] == n)\n\n __FUNC__(n-d[m], d, s-d[m], m-1) || __FUNC__(n, d, s-d[m], m-1)\n}\n\nfunc is_weird(n) {\n (n.sigma > 2*n) && !is_pseudoperfect(n)\n}\n\nvar w = (1..Inf -> lazy.grep(is_weird).first(25))\nsay \"The first 25 weird numbers:\\n#{w.join(' ')}\"\n", "language": "Sidef" }, { "code": "fn divisors(n int) []int {\n mut divs := [1]\n mut divs2 := []int{}\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n divs << i\n if i != j {\n divs2 << j\n }\n }\n }\n for i := divs.len - 1; i >= 0; i-- {\n divs2 << divs[i]\n }\n return divs2\n}\n\nfn abundant(n int, divs []int) bool {\n mut sum := 0\n for div in divs {\n sum += div\n }\n return sum > n\n}\n\nfn semiperfect(n int, divs []int) bool {\n le := divs.len\n if le > 0 {\n h := divs[0]\n t := divs[1..]\n if n < h {\n return semiperfect(n, t)\n } else {\n return n == h || semiperfect(n-h, t) || semiperfect(n, t)\n }\n } else {\n return false\n }\n}\n\nfn sieve(limit int) []bool {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n mut w := []bool{len: limit}\n for i := 2; i < limit; i += 2 {\n if w[i] {\n continue\n }\n divs := divisors(i)\n if !abundant(i, divs) {\n w[i] = true\n } else if semiperfect(i, divs) {\n for j := i; j < limit; j += i {\n w[j] = true\n }\n }\n }\n return w\n}\n\nfn main() {\n w := sieve(17000)\n mut count := 0\n max := 25\n println(\"The first 25 weird numbers are:\")\n for n := 2; count < max; n += 2 {\n if !w[n] {\n print(\"$n \")\n count++\n }\n }\n println('')\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n\n Dim resu As New List(Of Integer)\n\n Function TestAbundant(n As Integer, ByRef divs As List(Of Integer)) As Boolean\n divs = New List(Of Integer)\n Dim sum As Integer = -n : For i As Integer = Math.Sqrt(n) To 1 Step -1\n If n Mod i = 0 Then divs.Add(i) : Dim j As Integer = n / i : divs.Insert(0, j) : sum += i + j\n Next : divs(0) = sum - divs(0) : Return divs(0) > 0\n End Function\n\n Function subList(src As List(Of Integer), Optional first As Integer = Integer.MinValue) As List(Of Integer)\n subList = src.ToList : subList.RemoveAt(1)\n End Function\n\n Function semiperfect(divs As List(Of Integer)) As Boolean\n If divs.Count < 2 Then Return False\n Select Case divs.First.CompareTo(divs(1))\n Case 0 : Return True\n Case -1 : Return semiperfect(subList(divs))\n Case 1 : Dim t As List(Of Integer) = subList(divs) : t(0) -= divs(1)\n If semiperfect(t) Then Return True Else t(0) = divs.First : Return semiperfect(t)\n End Select : Return False ' execution can't get here, just for compiler warning\n End Function\n\n Function Since(et As TimeSpan) As String ' big ugly routine to prettify the elasped time\n If et > New TimeSpan(2000000) Then\n Dim s As String = \" \" & et.ToString(), p As Integer = s.IndexOf(\":\"), q As Integer = s.IndexOf(\".\")\n If q < p Then s = s.Insert(q, \"Days\") : s = s.Replace(\"Days.\", \"Days, \")\n p = s.IndexOf(\":\") : s = s.Insert(p, \"h\") : s = s.Replace(\"h:\", \"h \")\n p = s.IndexOf(\":\") : s = s.Insert(p, \"m\") : s = s.Replace(\"m:\", \"m \")\n s = s.Replace(\" 0\", \" \").Replace(\" 0h\", \" \").Replace(\" 0m\", \" \") & \"s\"\n Return s.TrimStart()\n Else\n If et > New TimeSpan(1500) Then\n Return et.TotalMilliseconds.ToString() & \"ms\"\n Else\n If et > New TimeSpan(15) Then\n Return (et.TotalMilliseconds * 1000.0).ToString() & \"µs\"\n Else\n Return (et.TotalMilliseconds * 1000000.0).ToString() & \"ns\"\n End If\n End If\n End If\n End Function\n\n Sub Main(args As String())\n Dim sw As New Stopwatch, st As Integer = 2, stp As Integer = 1020, count As Integer = 0\n Dim max As Integer = 25, halted As Boolean = False\n If args.Length > 0 Then _\n Dim t As Integer = Integer.MaxValue : If Integer.TryParse(args(0), t) Then max = If(t > 0, t, Integer.MaxValue)\n If max = Integer.MaxValue Then\n Console.WriteLine(\"Calculating weird numbers, press a key to halt.\")\n stp *= 10\n Else\n Console.WriteLine(\"The first {0} weird numbers:\", max)\n End If\n If max < 25 Then stp = 140\n sw.Start()\n Do : Parallel.ForEach(Enumerable.Range(st, stp),\n Sub(n)\n Dim divs As List(Of Integer) = Nothing\n If TestAbundant(n, divs) AndAlso Not semiperfect(divs) Then\n SyncLock resu : resu.Add(n) : End SyncLock\n End If\n End Sub)\n If resu.Count > 0 Then\n resu.Sort()\n If count + resu.Count > max Then\n resu = resu.Take(max - count).ToList\n End If\n Console.Write(String.Join(\" \", resu) & \" \")\n count += resu.Count : resu.Clear()\n End If\n If Console.KeyAvailable Then Console.ReadKey() : halted = True : Exit Do\n st += stp\n Loop Until count >= max\n sw.Stop()\n If max < Integer.MaxValue Then\n Console.WriteLine(vbLf & \"Computation time was {0}.\", Since(sw.Elapsed))\n If halted Then Console.WriteLine(\"Halted at number {0}.\", count)\n Else\n Console.WriteLine(vbLf & \"Computation time was {0} for the first {1} weird numbers.\", Since(sw.Elapsed), count)\n End If\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./math\" for Int, Nums\nimport \"./iterate\" for Stepped\n\nvar semiperfect // recursive\nsemiperfect = Fn.new { |n, divs|\n var le = divs.count\n if (le == 0) return false\n var h = divs[0]\n if (n == h) return true\n if (le == 1) return false\n var t = divs[1..-1]\n if (n < h) return semiperfect.call(n, t)\n return semiperfect.call(n-h, t) || semiperfect.call(n, t)\n}\n\nvar sieve = Fn.new { |limit|\n // 'false' denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n var w = List.filled(limit, false)\n for (j in Stepped.new(6...limit, 6)) w[j] = true // eliminate multiples of 3\n for (i in Stepped.new(2...limit, 2)) {\n if (!w[i]) {\n var divs = Int.properDivisors(i)\n var sum = Nums.sum(divs)\n if (sum <= i) {\n w[i] = true\n } else if (semiperfect.call(sum-i, divs)) {\n for (j in Stepped.new(i...limit, i)) w[j] = true\n }\n }\n }\n return w\n}\n\nvar start = System.clock\nvar limit = 16313\nvar w = sieve.call(limit)\nvar count = 0\nvar max = 25\nSystem.print(\"The first 25 weird numbers are:\")\nvar n = 2\nwhile (count < max) {\n if (!w[n]) {\n System.write(\"%(n) \")\n count = count + 1\n }\n n = n + 2\n}\nSystem.print()\nSystem.print(\"\\nTook %(((System.clock-start)*1000).round) milliseconds\")\n", "language": "Wren" }, { "code": "def SizeOfInt = 4;\ndef \\IntA\\ Ptr, Size;\nint Array(2);\n\nfunc Divisors(N); \\Returns a list of proper divisors for N\nint N;\nint Divs, Divs2, Out;\nint I, J, C1, C2;\n[C1:= 0; C2:= 0;\nDivs:= MAlloc(N * SizeOfInt / 2);\nDivs2:= MAlloc(N * SizeOfInt / 2);\nDivs(C1):= 1; C1:= C1+1;\nI:= 2;\nwhile I*I <= N do\n [if rem(N/I) = 0 then\n [J:= N/I;\n Divs(C1):= I; C1:= C1+1;\n if I # J then\n [Divs2(C2):= J; C2:= C2+1];\n ];\n I:= I+1;\n ];\nOut:= MAlloc((C1+C2) * SizeOfInt);\nfor I:= 0 to C2-1 do\n Out(I):= Divs2(I);\nfor I:= 0 to C1-1 do\n Out(C2+I):= Divs(C1-I-1);\nArray(Ptr):= Out;\nArray(Size):= C1 + C2;\nRelease(Divs);\nRelease(Divs2);\nreturn Array;\n];\n\nfunc Abundant(N, Divs); \\Returns 'true' if N is abundant\nint N, Divs;\nint Sum, I;\n[Sum:= 0;\nfor I:= 0 to Divs(Size)-1 do\n Sum:= Sum + Divs(Ptr,I);\nreturn Sum > N;\n];\n\nfunc Semiperfect(N, Divs); \\Returns 'true' if N is semiperfect\nint N, Divs;\nint H, T, TA(2);\n[if Divs(Size) > 0 then\n [H:= Divs(Ptr,0);\n T:= Divs(Ptr)+SizeOfInt;\n TA(Ptr):= T;\n TA(Size):= Divs(Size)-1;\n if N < H then\n return Semiperfect(N, TA)\n else return N = H or Semiperfect(N-H, TA) or Semiperfect(N, TA);\n ]\nelse return false;\n];\n\nfunc Sieve(Limit); \\Return array of weird number indexes set 'false'\nint Limit; \\i.e. non-abundant and non-semiperfect\nint W, Divs(2), I, J;\n[W:= MAlloc(Limit * SizeOfInt);\nfor I:= 0 to Limit-1 do W(I):= 0; \\for safety\nI:= 2;\nwhile I < Limit do\n [if W(I) = 0 then\n [Divs:= Divisors(I);\n if not Abundant(I, Divs) then\n W(I):= true\n else if Semiperfect(I, Divs) then\n [J:= I;\n while J < Limit do\n [W(J):= true;\n J:= J+I;\n ];\n ];\n ];\n I:= I+2;\n ];\nRelease(Divs(Ptr));\nreturn W;\n];\n\nint W, Count, Max, N;\n[W:= Sieve(17000);\nCount:= 0;\nMax:= 25;\nText(0, \"The first 25 weird numbers:^m^j\");\nN:= 2;\nwhile Count < Max do\n [if not W(N) then\n [IntOut(0, N); ChOut(0, ^ );\n Count:= Count+1;\n ];\n N:= N+2;\n ];\nCrLf(0);\nRelease(W);\n]\n", "language": "XPL0" }, { "code": "fcn properDivs(n){\n if(n==1) return(T);\n ( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )\n .pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })\n}\nfcn abundant(n,divs){ divs.sum(0) > n }\nfcn semiperfect(n,divs){\n if(divs){\n h,t := divs[0], divs[1,*];\n if(n<h) return(semiperfect(n,t));\n return((n==h) or semiperfect(n - h, t) or semiperfect(n, t));\n }\n False\n}\nfcn sieve(limit){\n // False denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n w:=List.createLong(limit,False);\n foreach i in ([2..limit - 1, 2]){\n if(w[i]) continue;\n divs:=properDivs(i);\n if(not abundant(i,divs)) w[i]=True;\n else if(semiperfect(i,divs))\n\t { foreach j in ([i..limit - 1, i]){ w[j]=True; } }\n }\n w\n}\n", "language": "Zkl" }, { "code": "w,count,max := sieve(17_000), 0, 25;\nprintln(\"The first 25 weird numbers are:\");\nforeach n in ([2..* ,2]){\n if(not w[n]){ print(\"%d \".fmt(n)); count+=1; }\n if(count>=max) break;\n}\nprintln();\n", "language": "Zkl" } ]
Weird-numbers
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Wieferich_primes\nnote: Prime Numbers\n", "language": "00-META" }, { "code": "<br>\nIn number theory, a '''Wieferich prime''' is a prime number ''' ''p'' ''' such that ''' ''p<sup>2</sup>'' ''' evenly divides ''' ''2<sup>(p − 1)</sup> − 1'' '''.\n\n\nIt is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified.\n\n\n;Task \n\n* Write a routine (function procedure, whatever) to find Wieferich primes.\n\n* Use that routine to identify and display all of the Wieferich primes less than 5000.\n\n\n;See also\n\n;* [[oeis:A001220|OEIS A001220 - Wieferich primes]]\n<br>\n\n", "language": "00-TASK" }, { "code": "with Ada.Text_IO;\n\nprocedure Wieferich_Primes is\n\n function Is_Prime (V : Positive) return Boolean is\n D : Positive := 5;\n begin\n if V < 2 then return False; end if;\n if V mod 2 = 0 then return V = 2; end if;\n if V mod 3 = 0 then return V = 3; end if;\n while D * D <= V loop\n if V mod D = 0 then\n return False;\n end if;\n D := D + 2;\n end loop;\n return True;\n end Is_Prime;\n\n function Is_Wieferich (N : Positive) return Boolean is\n Q : Natural := 1;\n begin\n if not Is_Prime (N) then\n return False;\n end if;\n for P in 2 .. N loop\n Q := (2 * Q) mod N**2;\n end loop;\n return Q = 1;\n end Is_Wieferich;\n\nbegin\n\n Ada.Text_IO.Put_Line (\"Wieferich primes below 5000:\");\n for N in 1 .. 4999 loop\n if Is_Wieferich (N) then\n Ada.Text_IO.Put_Line (N'Image);\n end if;\n end loop;\n\nend Wieferich_Primes;\n", "language": "Ada" }, { "code": "BEGIN # find Wierferich Primes: primes p where p^2 evenly divides 2^(p-1)-1 #\n\n INT max number = 5 000; # maximum number we will consider #\n # set precision of LONG LONG INT - p^5000 has over 1500 digits #\n PR precision 1600 PR\n PR read \"primes.incl.a68\" PR # include prime utlities #\n # get a list of primes up to max number #\n []INT prime = EXTRACTPRIMESUPTO max number\n FROMPRIMESIEVE PRIMESIEVE max number;\n\n # find the primes #\n INT p pos := LWB prime;\n LONG LONG INT two to p minus 1 := 1;\n INT power := 0;\n INT w count := 0;\n WHILE w count < 2 DO\n INT p = prime[ p pos ];\n WHILE power < ( p - 1 ) DO\n two to p minus 1 *:= 2;\n power +:= 1\n OD;\n IF ( two to p minus 1 - 1 ) MOD ( p * p ) = 0 THEN\n print( ( \" \", whole( p, 0 ) ) );\n w count +:= 1\n FI;\n p pos +:= 1\n OD\nEND\n", "language": "ALGOL-68" }, { "code": " ⎕CY 'dfns' ⍝ import dfns namespace\n ⍝ pco ← prime finder\n ⍝ nats ← natural number arithmetic (uses strings)\n ⍝ Get all Wieferich primes below n:\n wief←{{⍵/⍨{(,'0')≡(×⍨⍵)|nats 1 -nats⍨ 2 *nats ⍵-1}¨⍵}⍸1 pco⍳⍵}\n wief 5000\n1093 3511\n", "language": "APL" }, { "code": "wieferich?: function [n][\n and? -> prime? n\n -> zero? (dec 2 ^ n-1) % n ^ 2\n]\n\nprint [\"Wieferich primes less than 5000:\" select 1..5000 => wieferich?]\n", "language": "Arturo" }, { "code": "# syntax: GAWK -f WIEFERICH_PRIMES.AWK\n# converted from FreeBASIC\nBEGIN {\n start = 1\n stop = 4999\n for (i=start; i<=stop; i++) {\n if (is_wieferich_prime(i)) {\n printf(\"%d\\n\",i)\n count++\n }\n }\n printf(\"Wieferich primes %d-%d: %d\\n\",start,stop,count)\n exit(0)\n}\nfunction is_prime(n, d) {\n d = 5\n if (n < 2) { return(0) }\n if (n % 2 == 0) { return(n == 2) }\n if (n % 3 == 0) { return(n == 3) }\n while (d*d <= n) {\n if (n % d == 0) { return(0) }\n d += 2\n if (n % d == 0) { return(0) }\n d += 4\n }\n return(1)\n}\nfunction is_wieferich_prime(p, p2,q) {\n if (!is_prime(p)) { return(0) }\n q = 1\n p2 = p^2\n while (p > 1) {\n q = (2*q) % p2\n p--\n }\n return(q == 1)\n}\n", "language": "AWK" }, { "code": "print \"Wieferich primes less than 5000: \"\nfor i = 1 to 5000\n if isWeiferich(i) then print i\nnext i\nend\n\nfunction isWeiferich(p)\n if not isPrime(p) then return False\n q = 1\n p2 = p ^ 2\n while p > 1\n q = (2 * q) mod p2\n p -= 1\n end while\n if q = 1 then return True else return False\nend function\n\nfunction isPrime(v)\n if v < 2 then return False\n if v mod 2 = 0 then return v = 2\n if v mod 3 = 0 then return v = 3\n d = 5\n while d * d <= v\n if v mod d = 0 then return False else d += 2\n end while\n return True\nend function\n", "language": "BASIC256" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdint.h>\n\n#define LIMIT 5000\nstatic bool PRIMES[LIMIT];\n\nstatic void prime_sieve() {\n uint64_t p;\n int i;\n\n PRIMES[0] = false;\n PRIMES[1] = false;\n for (i = 2; i < LIMIT; i++) {\n PRIMES[i] = true;\n }\n\n for (i = 4; i < LIMIT; i += 2) {\n PRIMES[i] = false;\n }\n\n for (p = 3;; p += 2) {\n uint64_t q = p * p;\n if (q >= LIMIT) {\n break;\n }\n if (PRIMES[p]) {\n uint64_t inc = 2 * p;\n for (; q < LIMIT; q += inc) {\n PRIMES[q] = false;\n }\n }\n }\n}\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n uint64_t result = 1;\n\n if (mod == 1) {\n return 0;\n }\n\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1) {\n result = (result * base) % mod;\n }\n base = (base * base) % mod;\n }\n return result;\n}\n\nvoid wieferich_primes() {\n uint64_t p;\n\n for (p = 2; p < LIMIT; ++p) {\n if (PRIMES[p] && modpow(2, p - 1, p * p) == 1) {\n printf(\"%lld\\n\", p);\n }\n }\n}\n\nint main() {\n prime_sieve();\n\n printf(\"Wieferich primes less than %d:\\n\", LIMIT);\n wieferich_primes();\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <cstdint>\n#include <iostream>\n#include <vector>\n\nstd::vector<bool> prime_sieve(uint64_t limit) {\n std::vector<bool> sieve(limit, true);\n if (limit > 0)\n sieve[0] = false;\n if (limit > 1)\n sieve[1] = false;\n for (uint64_t i = 4; i < limit; i += 2)\n sieve[i] = false;\n for (uint64_t p = 3; ; p += 2) {\n uint64_t q = p * p;\n if (q >= limit)\n break;\n if (sieve[p]) {\n uint64_t inc = 2 * p;\n for (; q < limit; q += inc)\n sieve[q] = false;\n }\n }\n return sieve;\n}\n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n if (mod == 1)\n return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1)\n result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nstd::vector<uint64_t> wieferich_primes(uint64_t limit) {\n std::vector<uint64_t> result;\n std::vector<bool> sieve(prime_sieve(limit));\n for (uint64_t p = 2; p < limit; ++p)\n if (sieve[p] && modpow(2, p - 1, p * p) == 1)\n result.push_back(p);\n return result;\n}\n\nint main() {\n const uint64_t limit = 5000;\n std::cout << \"Wieferich primes less than \" << limit << \":\\n\";\n for (uint64_t p : wieferich_primes(limit))\n std::cout << p << '\\n';\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace WieferichPrimes {\n class Program {\n static long ModPow(long @base, long exp, long mod) {\n if (mod == 1) {\n return 0;\n }\n\n long result = 1;\n @base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1) {\n result = (result * @base) % mod;\n }\n @base = (@base * @base) % mod;\n }\n return result;\n }\n\n static bool[] PrimeSieve(int limit) {\n bool[] sieve = Enumerable.Repeat(true, limit).ToArray();\n\n if (limit > 0) {\n sieve[0] = false;\n }\n if (limit > 1) {\n sieve[1] = false;\n }\n\n for (int i = 4; i < limit; i += 2) {\n sieve[i] = false;\n }\n\n for (int p = 3; ; p += 2) {\n int q = p * p;\n if (q >= limit) {\n break;\n }\n if (sieve[p]) {\n int inc = 2 * p;\n for (; q < limit; q += inc) {\n sieve[q] = false;\n }\n }\n }\n\n return sieve;\n }\n\n static List<int> WiefreichPrimes(int limit) {\n bool[] sieve = PrimeSieve(limit);\n List<int> result = new List<int>();\n for (int p = 2; p < limit; p++) {\n if (sieve[p] && ModPow(2, p - 1, p * p) == 1) {\n result.Add(p);\n }\n }\n return result;\n }\n\n static void Main() {\n const int limit = 5000;\n Console.WriteLine(\"Wieferich primes less that {0}:\", limit);\n foreach (int p in WiefreichPrimes(limit)) {\n Console.WriteLine(p);\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "fastfunc isprim num .\n i = 2\n while i <= sqrt num\n if num mod i = 0\n return 0\n .\n i += 1\n .\n return 1\n.\nfunc wieferich p .\n if isprim p = 0\n return 0\n .\n q = 1\n p2 = p * p\n while p > 1\n q = (2 * q) mod p2\n p -= 1\n .\n if q = 1\n return 1\n .\n.\nprint \"Wieferich primes less than 5000: \"\nfor i = 2 to 5000\n if wieferich i = 1\n print i\n .\n.\n", "language": "EasyLang" }, { "code": "// Weiferich primes: Nigel Galloway. June 2nd., 2021\nprimes32()|>Seq.takeWhile((>)5000)|>Seq.filter(fun n->(2I**(n-1)-1I)%(bigint(n*n))=0I)|>Seq.iter(printfn \"%d\")\n", "language": "F-Sharp" }, { "code": "USING: io kernel math math.functions math.primes prettyprint\nsequences ;\n\n\"Wieferich primes less than 5000:\" print\n5000 primes-upto [ [ 1 - 2^ 1 - ] [ sq divisor? ] bi ] filter .\n", "language": "Factor" }, { "code": "Func Iswief(p)=Isprime(p)*Divides(p^2, 2^(p-1)-1).\nfor i=2 to 5000 do if Iswief(i) then !!i fi od\n", "language": "Fermat" }, { "code": ": prime? ( n -- ? ) here + c@ 0= ;\n: notprime! ( n -- ) here + 1 swap c! ;\n\n: prime_sieve { n -- }\n here n erase\n 0 notprime!\n 1 notprime!\n n 4 > if\n n 4 do i notprime! 2 +loop\n then\n 3\n begin\n dup dup * n <\n while\n dup prime? if\n n over dup * do\n i notprime!\n dup 2* +loop\n then\n 2 +\n repeat\n drop ;\n\n: modpow { c b a -- a^b mod c }\n c 1 = if 0 exit then\n 1\n a c mod to a\n begin\n b 0>\n while\n b 1 and 1 = if\n a * c mod\n then\n a a * c mod to a\n b 2/ to b\n repeat ;\n\n: wieferich_prime? { p -- ? }\n p prime? if\n p p * p 1- 2 modpow 1 =\n else\n false\n then ;\n\n: wieferich_primes { n -- }\n .\" Wieferich primes less than \" n 1 .r .\" :\" cr\n n prime_sieve\n n 0 do\n i wieferich_prime? if\n i 1 .r cr\n then\n loop ;\n\n5000 wieferich_primes\nbye\n", "language": "Forth" }, { "code": "#include \"isprime.bas\"\n\nfunction iswief( byval p as uinteger ) as boolean\n if not isprime(p) then return 0\n dim as integer q = 1, p2 = p^2\n while p>1\n q=(2*q) mod p2\n p = p - 1\n wend\n if q=1 then return 1 else return 0\nend function\n\nfor i as uinteger = 1 to 5000\n if iswief(i) then print i\nnext i\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"rcu\"\n)\n\nfunc main() {\n primes := rcu.Primes(5000)\n zero := new(big.Int)\n one := big.NewInt(1)\n num := new(big.Int)\n fmt.Println(\"Wieferich primes < 5,000:\")\n for _, p := range primes {\n num.Set(one)\n num.Lsh(num, uint(p-1))\n num.Sub(num, one)\n den := big.NewInt(int64(p * p))\n if num.Rem(num, den).Cmp(zero) == 0 {\n fmt.Println(rcu.Commatize(p))\n }\n }\n}\n", "language": "Go" }, { "code": "isPrime :: Integer -> Bool\nisPrime n\n |n == 2 = True\n |n == 1 = False\n |otherwise = null $ filter (\\i -> mod n i == 0 ) [2 .. root]\n where\n root :: Integer\n root = toInteger $ floor $ sqrt $ fromIntegral n\n\nisWieferichPrime :: Integer -> Bool\nisWieferichPrime n = isPrime n && mod ( 2 ^ ( n - 1 ) - 1 ) ( n ^ 2 ) == 0\n\nsolution :: [Integer]\nsolution = filter isWieferichPrime [2 .. 5000]\n\nmain :: IO ( )\nmain = do\n putStrLn \"Wieferich primes less than 5000:\"\n print solution\n", "language": "Haskell" }, { "code": " I.(1&p: * 0=*: | _1+2x^<:) i.5000\n1093 3511\n", "language": "J" }, { "code": " p: I. (0=*:|_1+2x^<:) I.1 p: i.5000\n1093 3511\n", "language": "J" }, { "code": "import java.util.*;\n\npublic class WieferichPrimes {\n public static void main(String[] args) {\n final int limit = 5000;\n System.out.printf(\"Wieferich primes less than %d:\\n\", limit);\n for (Integer p : wieferichPrimes(limit))\n System.out.println(p);\n }\n\n private static boolean[] primeSieve(int limit) {\n boolean[] sieve = new boolean[limit];\n Arrays.fill(sieve, true);\n if (limit > 0)\n sieve[0] = false;\n if (limit > 1)\n sieve[1] = false;\n for (int i = 4; i < limit; i += 2)\n sieve[i] = false;\n for (int p = 3; ; p += 2) {\n int q = p * p;\n if (q >= limit)\n break;\n if (sieve[p]) {\n int inc = 2 * p;\n for (; q < limit; q += inc)\n sieve[q] = false;\n }\n }\n return sieve;\n }\n\n private static long modpow(long base, long exp, long mod) {\n if (mod == 1)\n return 0;\n long result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1)\n result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n }\n\n private static List<Integer> wieferichPrimes(int limit) {\n boolean[] sieve = primeSieve(limit);\n List<Integer> result = new ArrayList<>();\n for (int p = 2; p < limit; ++p) {\n if (sieve[p] && modpow(2, p - 1, p * p) == 1)\n result.add(p);\n }\n return result;\n }\n}\n", "language": "Java" }, { "code": "def is_prime:\n . as $n\n | if ($n < 2) then false\n elif ($n % 2 == 0) then $n == 2\n elif ($n % 3 == 0) then $n == 3\n elif ($n % 5 == 0) then $n == 5\n elif ($n % 7 == 0) then $n == 7\n elif ($n % 11 == 0) then $n == 11\n elif ($n % 13 == 0) then $n == 13\n elif ($n % 17 == 0) then $n == 17\n elif ($n % 19 == 0) then $n == 19\n else {i:23}\n | until( (.i * .i) > $n or ($n % .i == 0); .i += 2)\n | .i * .i > $n\n end;\n\n# Emit an array of primes less than `.`\ndef primes:\n if . < 2 then []\n else\n [2] + [range(3; .; 2) | select(is_prime)]\n end;\n\n# for the sake of infinite-precision integer arithmetic\ndef power($b): . as $a | reduce range(0; $b) as $i (1; .*$a);\n", "language": "Jq" }, { "code": "# Input: the limit\ndef wieferich:\n primes[]\n | . as $p\n | select( ( (2|power($p-1)) - 1) % (.*.) == 0);\n\n5000 | wieferich\n", "language": "Jq" }, { "code": "using Primes\n\nprintln(filter(p -> (big\"2\"^(p - 1) - 1) % p^2 == 0, primes(5000))) # [1093, 3511]\n", "language": "Julia" }, { "code": "ClearAll[WieferichPrimeQ]\nWieferichPrimeQ[n_Integer] := PrimeQ[n] && Divisible[2^(n - 1) - 1, n^2]\nSelect[Range[5000], WieferichPrimeQ]\n", "language": "Mathematica" }, { "code": "import math\nimport bignum\n\nfunc isPrime(n: Positive): bool =\n if n mod 2 == 0: return n == 2\n if n mod 3 == 0: return n == 3\n var d = 5\n while d <= sqrt(n.toFloat).int:\n if n mod d == 0: return false\n inc d, 2\n if n mod d == 0: return false\n inc d, 4\n result = true\n\necho \"Wieferich primes less than 5000:\"\nlet two = newInt(2)\nfor p in 2u..<5000:\n if p.isPrime:\n if exp(two, p - 1, p * p) == 1: # Modular exponentiation.\n echo p\n", "language": "Nim" }, { "code": "iswief(p)=if(isprime(p)&&(2^(p-1)-1)%p^2==0,1,0)\nfor(N=1,5000,if(iswief(N),print(N)))\n", "language": "PARI-GP" }, { "code": "use feature 'say';\nuse ntheory qw(is_prime powmod);\n\nsay 'Wieferich primes less than 5000: ' . join ', ', grep { is_prime($_) and powmod(2, $_-1, $_*$_) == 1 } 1..5000;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">weiferich</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">p2pm1m1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">mpz_ui_pow_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p2pm1m1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_sub_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p2pm1m1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p2pm1m1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">mpz_fdiv_q_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p2pm1m1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p2pm1m1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Weiferich primes less than 5000: %V\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">get_primes_le</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">weiferich</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">base</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">modulus</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">weiferich</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_set_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">modulus</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">mpz_powm_ui</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">base</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">modulus</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">mpz_cmp_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Weiferich primes less than 5000: %V\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">get_primes_le</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">5000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">weiferich</span><span style=\"color: #0000FF;\">)})</span>\n<!--\n", "language": "Phix" }, { "code": "(de **Mod (X Y N)\n (let M 1\n (loop\n (when (bit? 1 Y)\n (setq M (% (* M X) N)) )\n (T (=0 (setq Y (>> 1 Y)))\n M )\n (setq X (% (* X X) N)) ) ) )\n(let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)))\n (until (> D 5000)\n (and\n (=1 (**Mod 2 (dec D) (* D D)))\n (println D) )\n (inc 'D (++ L)) ) )\n", "language": "PicoLisp" }, { "code": "Procedure.i isPrime(n)\n Protected k\n\n If n = 2 : ProcedureReturn #True\n ElseIf n <= 1 Or n % 2 = 0 : ProcedureReturn #False\n Else\n For k = 3 To Int(Sqr(n)) Step 2\n If n % k = 0\n ProcedureReturn #False\n EndIf\n Next\n EndIf\n\n ProcedureReturn #True\nEndProcedure\n\nProcedure.i isWeiferich(p)\n Protected q, p2\n\n If Not isPrime(p) : ProcedureReturn #False : EndIf\n q = 1\n p2 = Pow(p, 2)\n While p > 1\n q = (2*q) % p2\n p - 1\n Wend\n If q = 1\n ProcedureReturn #True\n Else\n ProcedureReturn #False\n EndIf\nEndProcedure\n\nOpenConsole()\nPrintN(\"Wieferich primes less than 5000: \")\nFor i = 2 To 5000\n If isWeiferich(i)\n PrintN(Str(i))\n EndIf\nNext i\nInput()\nCloseConsole()\n", "language": "PureBasic" }, { "code": "# Wieferich-Primzahlen\nMAX: int = 5_000\n\n# Berechnet a^n mod m\ndef pow_mod(a: int, n: int, m: int) -> int:\n assert n >= 0 and m != 0, \"pow_mod(a, n, m), n >= 0, m <> 0\"\n res: int = 1\n a %= m\n while n > 0:\n if n%2:\n res = (res*a)%m\n n -= 1\n else:\n a = (a*a)%m\n n //= 2\n return res%m\n\ndef is_prime(n: int) -> bool:\n for i in range(2, int(n**0.5) + 1):\n if n%i == 0:\n return False\n return True\n\ndef is_wieferich(p: int) -> True:\n if is_prime(p) == False:\n return False\n if pow_mod(2, p - 1, p*p) == 1:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n print(f\"Wieferich primes less than {MAX}:\")\n for i in range(2, MAX + 1):\n if is_wieferich(i):\n print(i)\n", "language": "Python" }, { "code": " 5000 eratosthenes\n\n [ dup isprime iff\n [ dup 1 - bit 1 -\n swap dup * mod\n 0 = ]\n else [ drop false ] ] is wieferich ( n --> b )\n\n 5000 times [ i^ wieferich if [ i^ echo cr ] ]\n", "language": "Quackery" }, { "code": "#lang typed/racket\n(require math/number-theory)\n\n(: wieferich-prime? (-> Positive-Integer Boolean))\n\n(define (wieferich-prime? p)\n (and (prime? p)\n (divides? (* p p) (sub1 (expt 2 (sub1 p))))))\n\n(module+ main\n (define wieferich-primes<5000\n (for/list : (Listof Integer) ((p (sequence-filter wieferich-prime?\n (in-range 1 5000))))\n p))\n wieferich-primes<5000)\n", "language": "Racket" }, { "code": "put \"Wieferich primes less than 5000: \", join ', ', ^5000 .grep: { .is-prime and not ( exp($_-1, 2) - 1 ) % .² };\n", "language": "Raku" }, { "code": "/*REXX program finds and displays Wieferich primes which are under a specified limit N*/\nparse arg n . /*obtain optional argument from the CL.*/\nif n=='' | n==\",\" then n= 5000 /*Not specified? Then use the default.*/\nnumeric digits 3000 /*bump # of dec. digs for calculation. */\nnumeric digits max(9, length(2**n) ) /*calculate # of decimal digits needed.*/\ncall genP /*build array of semaphores for primes.*/\n title= ' Wieferich primes that are < ' commas(n) /*title for the output.*/\nw= length(title) + 2 /*width of field for the primes listed.*/\nsay ' index │'center(title, w) /*display the title for the output. */\nsay '───────┼'center(\"\" , w, '─') /* \" a sep \" \" \" */\nfound= 0 /*initialize number of Wieferich primes*/\n do j=1 to #; p= @.j /*search for Wieferich primes in range.*/\n if (2**(p-1)-1)//p**2\\==0 then iterate /*P**2 not evenly divide 2**(P-1) - 1?*/ /* ◄■■■■■■■ the filter.*/\n found= found + 1 /*bump the counter of Wieferich primes.*/\n say center(found, 7)'│' center(commas(p), w) /*display the Wieferich prime.*/\n end /*j*/\n\nsay '───────┴'center(\"\" , w, '─'); say /*display a foot sep for the output. */\nsay 'Found ' commas(found) title /* \" \" summary \" \" \" */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncommas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngenP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes (index-1). */\n !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* \" \" \" \" (semaphores).*/\n #= 5; sq.#= @.# ** 2 /*number of primes so far; prime². */\n do j=@.#+2 by 2 to n-1; parse var j '' -1 _ /*get right decimal digit of J.*/\n if _==5 then iterate /*J ÷ by 5? Yes, skip.*/\n if j//3==0 then iterate; if j//7==0 then iterate /*\" \" \" 3? J ÷ by 7? */\n do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/\n if j//@.k==0 then iterate j /*Is J ÷ a P? Then not prime. ___ */\n end /*k*/ /* [↑] only process numbers ≤ √ J */\n #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # Ps; assign next P; P sqare; P.*/\n end /*j*/; return\n", "language": "REXX" }, { "code": "require \"prime\"\n\nputs Prime.each(5000).select{|p| 2.pow(p-1 ,p*p) == 1 }\n", "language": "Ruby" }, { "code": "print \"Wieferich primes less than 5000: \"\nfor i = 1 to 5000\n if isWeiferich(i) then print i\nnext i\nend\n\nfunction isPrime(n)\nif n < 2 then isPrime = 0 : goto [exit]\nif n = 2 then isPrime = 1 : goto [exit]\nif n mod 2 = 0 then isPrime = 0 : goto [exit]\nisPrime = 1\nfor i = 3 to int(n^.5) step 2\n if n mod i = 0 then isPrime = 0 : goto [exit]\nnext i\n[exit]\nend function\n\nfunction isWeiferich(p)\n if isPrime(p) = 0 then isWeiferich = 0 : goto [exit]\n q = 1\n p2 = p^2\n while p > 1\n q = (2*q) mod p2\n p = p - 1\n wend\n if q = 1 then\n isWeiferich = 1 : goto [exit]\n else\n isWeiferich = 0 : goto [exit]\n end if\n[exit]\nend function\n", "language": "Run-BASIC" }, { "code": "// [dependencies]\n// primal = \"0.3\"\n// mod_exp = \"1.0\"\n\nfn wieferich_primes(limit: usize) -> impl std::iter::Iterator<Item = usize> {\n primal::Primes::all()\n .take_while(move |x| *x < limit)\n .filter(|x| mod_exp::mod_exp(2, *x - 1, *x * *x) == 1)\n}\n\nfn main() {\n let limit = 5000;\n println!(\"Wieferich primes less than {}:\", limit);\n for p in wieferich_primes(limit) {\n println!(\"{}\", p);\n }\n}\n", "language": "Rust" }, { "code": "func is_wieferich_prime(p, base=2) {\n powmod(base, p-1, p**2) == 1\n}\n\nsay (\"Wieferich primes less than 5000: \", 5000.primes.grep(is_wieferich_prime))\n", "language": "Sidef" }, { "code": "func primeSieve(limit: Int) -> [Bool] {\n guard limit > 0 else {\n return []\n }\n var sieve = Array(repeating: true, count: limit)\n sieve[0] = false\n if limit > 1 {\n sieve[1] = false\n }\n if limit > 4 {\n for i in stride(from: 4, to: limit, by: 2) {\n sieve[i] = false\n }\n }\n var p = 3\n while true {\n var q = p * p\n if q >= limit {\n break\n }\n if sieve[p] {\n let inc = 2 * p\n while q < limit {\n sieve[q] = false\n q += inc\n }\n }\n p += 2\n }\n return sieve\n}\n\nfunc modpow(base: Int, exponent: Int, mod: Int) -> Int {\n if mod == 1 {\n return 0\n }\n var result = 1\n var exp = exponent\n var b = base\n b %= mod\n while exp > 0 {\n if (exp & 1) == 1 {\n result = (result * b) % mod\n }\n b = (b * b) % mod\n exp >>= 1\n }\n return result\n}\n\nfunc wieferichPrimes(limit: Int) -> [Int] {\n let sieve = primeSieve(limit: limit)\n var result: [Int] = []\n for p in 2..<limit {\n if sieve[p] && modpow(base: 2, exponent: p - 1, mod: p * p) == 1 {\n result.append(p)\n }\n }\n return result\n}\n\nlet limit = 5000\nprint(\"Wieferich primes less than \\(limit):\")\nfor p in wieferichPrimes(limit: limit) {\n print(p)\n}\n", "language": "Swift" }, { "code": "import \"./math\" for Int\nimport \"./big\" for BigInt\n\nvar primes = Int.primeSieve(5000)\nSystem.print(\"Wieferich primes < 5000:\")\nfor (p in primes) {\n var num = (BigInt.one << (p - 1)) - 1\n var den = p * p\n if (num % den == 0) System.print(p)\n}\n", "language": "Wren" }, { "code": "print \"Wieferich primes less than 5000: \"\nfor i = 2 to 5000\n if isWeiferich(i) print i\nnext i\nend\n\nsub isWeiferich(p)\n if not isPrime(p) return False\n q = 1\n p2 = p ^ 2\n while p > 1\n q = mod((2*q), p2)\n p = p - 1\n wend\n if q = 1 then return True else return False : fi\nend sub\n\nsub isPrime(v)\n if v < 2 return False\n if mod(v, 2) = 0 return v = 2\n if mod(v, 3) = 0 return v = 3\n d = 5\n while d * d <= v\n if mod(v, d) = 0 then return False else d = d + 2 : fi\n wend\n return True\nend sub\n", "language": "Yabasic" } ]
Wieferich-primes
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Wilson_primes_of_order_n\nnote: Prime Numbers\n", "language": "00-META" }, { "code": ";Definition\n\nA [https://en.wikipedia.org/wiki/Wilson_prime Wilson prime of order '''n'''] is a prime number &nbsp; '''p''' &nbsp; such that &nbsp; '''p<sup>2</sup>''' &nbsp; exactly divides:\n <big> '''(n − 1)! <small>&times;</small> (p − n)! − (− 1)<sup>n</sup>''' </big>\n\n\nIf &nbsp; '''n''' &nbsp; is &nbsp; '''1''', &nbsp; the latter formula reduces to the more familiar: &nbsp; '''(p - n)! + 1''' &nbsp; where the only known examples for &nbsp; '''p''' &nbsp; are &nbsp; '''5''', &nbsp; '''13''', &nbsp; and &nbsp; '''563'''.\n\n\n;Task\n\nCalculate and show on this page the Wilson primes, if any, for orders '''n = 1 to 11 inclusive''' and for primes '''p < 18''' &nbsp; or, \n<br>if your language supports ''big integers'', for '''p < 11,000'''.\n \n\n;Related task\n:* [[Primality by Wilson's theorem]]\n\n\n", "language": "00-TASK" }, { "code": "BEGIN # find Wilson primes of order n, primes such that: #\n # ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 #\n PR read \"primes.incl.a68\" PR # include prime utilities #\n []BOOL primes = PRIMESIEVE 11 000; # sieve the primes to 11 500 #\n # returns TRUE if p is an nth order Wilson prime #\n PROC is wilson = ( INT n, p )BOOL:\n IF p < n THEN FALSE\n ELSE\n LONG INT p2 = p * p;\n LONG INT prod := 1;\n FOR i TO n - 1 DO # prod := ( n - 1 )! MOD p2 #\n prod := ( prod * i ) MOD p2\n OD;\n FOR i TO p - n DO # prod := ( ( p - n )! * ( n - 1 )! ) MOD p2 #\n prod := ( prod * i ) MOD p2\n OD;\n 0 = ( p2 + prod + IF ODD n THEN 1 ELSE -1 FI ) MOD p2\n FI # is wilson # ;\n # find the Wilson primes #\n print( ( \" n: Wilson primes\", newline ) );\n print( ( \"-----------------\", newline ) );\n FOR n TO 11 DO\n print( ( whole( n, -2 ), \":\" ) );\n IF is wilson( n, 2 ) THEN print( ( \" 2\" ) ) FI;\n FOR p FROM 3 BY 2 TO UPB primes DO\n IF primes[ p ] THEN\n IF is wilson( n, p ) THEN print( ( \" \", whole( p, 0 ) ) ) FI\n FI\n OD;\n print( ( newline ) )\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "100 home\n110 print \"n: Wilson primes\"\n120 print \"--------------------\"\n130 for n = 1 to 11\n140 print n;chr$(9);\n150 for p = 2 to 18\n160 gosub 240\n170 if pt = 0 then goto 200\n180 gosub 340\n190 if wnpt = 1 then print p,\n200 next p\n210 print\n220 next n\n230 end\n240 rem tests if the number P is prime\n250 rem result is stored in PT\n260 pt = 1\n270 if p = 2 then return\n280 if p * 2 - int(p / 2) = 0 then pt = 0 : return\n290 j = 3\n300 if j*j > p then return\n310 if p * j - int(p / j) = 0 then pt = 0 : return\n320 j = j+2\n330 goto 300\n340 rem tests if the prime p is a Wilson prime of order n\n350 rem make sure it actually is prime first\n360 rem result is stored in wnpt\n370 wnpt = 0\n380 if p = 2 and n = 2 then wnpt = 1 : return\n390 if n > p then wnpt = 0 : return\n400 prod = 1 : p2 = p*p\n410 for i = 1 to n-1\n420 prod = (prod*i) : gosub 500\n430 next i\n440 for i = 1 to p-n\n450 prod = (prod*i) : gosub 500\n460 next i\n470 prod = (p2+prod-(-1)^n) : gosub 500\n480 if prod = 0 then wnpt = 1 : return\n490 wnpt = 0 : return\n500 rem prod mod p2 fails if prod > 32767 so brew our own modulus function\n510 prod = prod-int(prod/p2)*p2\n520 return\n", "language": "Applesoft-BASIC" }, { "code": "function isPrime(v)\n\tif v <= 1 then return False\n\tfor i = 2 To int(sqr(v))\n\t\tif v % i = 0 then return False\n\tnext i\n\treturn True\nend function\n\nfunction isWilson(n, p)\n\tif p < n then return false\n\tprod = 1\n\tp2 = p*p #p^2\n\tfor i = 1 to n-1\n\t\tprod = (prod*i) mod p2\n\tnext i\n\tfor i = 1 to p-n\n\t\tprod = (prod*i) mod p2\n\tnext i\n\tprod = (p2 + prod - (-1)**n) mod p2\n\tif prod = 0 then return true else return false\nend function\n\nprint \" n: Wilson primes\"\nprint \"----------------------\"\nfor n = 1 to 11\n\tprint n;\" : \";\n\tfor p = 3 to 10499 step 2\n\t\tif isPrime(p) and isWilson(n, p) then print p; \" \";\n\tnext p\n\tprint\nnext n\nend\n", "language": "BASIC256" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <gmp.h>\n\nbool *sieve(int limit) {\n int i, p;\n limit++;\n // True denotes composite, false denotes prime.\n bool *c = calloc(limit, sizeof(bool)); // all false by default\n c[0] = true;\n c[1] = true;\n for (i = 4; i < limit; i += 2) c[i] = true;\n p = 3; // Start from 3.\n while (true) {\n int p2 = p * p;\n if (p2 >= limit) break;\n for (i = p2; i < limit; i += 2 * p) c[i] = true;\n while (true) {\n p += 2;\n if (!c[p]) break;\n }\n }\n return c;\n}\n\nint main() {\n const int limit = 11000;\n int i, j, n, pc = 0;\n unsigned long p;\n bool *c = sieve(limit);\n for (i = 0; i < limit; ++i) {\n if (!c[i]) ++pc;\n }\n unsigned long *primes = (unsigned long *)malloc(pc * sizeof(unsigned long));\n for (i = 0, j = 0; i < limit; ++i) {\n if (!c[i]) primes[j++] = i;\n }\n mpz_t *facts = (mpz_t *)malloc(limit *sizeof(mpz_t));\n for (i = 0; i < limit; ++i) mpz_init(facts[i]);\n mpz_set_ui(facts[0], 1);\n for (i = 1; i < limit; ++i) mpz_mul_ui(facts[i], facts[i-1], i);\n mpz_t f, sign;\n mpz_init(f);\n mpz_init_set_ui(sign, 1);\n printf(\" n: Wilson primes\\n\");\n printf(\"--------------------\\n\");\n for (n = 1; n < 12; ++n) {\n printf(\"%2d: \", n);\n mpz_neg(sign, sign);\n for (i = 0; i < pc; ++i) {\n p = primes[i];\n if (p < n) continue;\n mpz_mul(f, facts[n-1], facts[p-n]);\n mpz_sub(f, f, sign);\n if (mpz_divisible_ui_p(f, p*p)) printf(\"%ld \", p);\n }\n printf(\"\\n\");\n }\n free(c);\n free(primes);\n for (i = 0; i < limit; ++i) mpz_clear(facts[i]);\n free(facts);\n return 0;\n}\n", "language": "C" }, { "code": "#include <iomanip>\n#include <iostream>\n#include <vector>\n#include <gmpxx.h>\n\nstd::vector<int> generate_primes(int limit) {\n std::vector<bool> sieve(limit >> 1, true);\n for (int p = 3, s = 9; s < limit; p += 2) {\n if (sieve[p >> 1]) {\n for (int q = s; q < limit; q += p << 1)\n sieve[q >> 1] = false;\n }\n s += (p + 1) << 2;\n }\n std::vector<int> primes;\n if (limit > 2)\n primes.push_back(2);\n for (int i = 1; i < sieve.size(); ++i) {\n if (sieve[i])\n primes.push_back((i << 1) + 1);\n }\n return primes;\n}\n\nint main() {\n using big_int = mpz_class;\n const int limit = 11000;\n std::vector<big_int> f{1};\n f.reserve(limit);\n big_int factorial = 1;\n for (int i = 1; i < limit; ++i) {\n factorial *= i;\n f.push_back(factorial);\n }\n std::vector<int> primes = generate_primes(limit);\n std::cout << \" n | Wilson primes\\n--------------------\\n\";\n for (int n = 1, s = -1; n <= 11; ++n, s = -s) {\n std::cout << std::setw(2) << n << \" |\";\n for (int p : primes) {\n if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)\n std::cout << ' ' << p;\n }\n std::cout << '\\n';\n }\n}\n", "language": "C++" }, { "code": "100 cls\n110 print \"n: Wilson primes\"\n120 print \"--------------------\"\n130 for n = 1 to 11\n140 print n;chr$(9);\n150 for p = 2 to 18\n160 gosub 240\n170 if pt = 0 then goto 200\n180 gosub 340\n190 if wnpt = 1 then print p,\n200 next p\n210 print\n220 next n\n230 end\n240 rem tests if the number P is prime\n250 rem result is stored in PT\n260 pt = 1\n270 if p = 2 then return\n280 if p mod 2 = 0 then pt = 0 : return\n290 j = 3\n300 if j*j > p then return\n310 if p mod j = 0 then pt = 0 : return\n320 j = j+2\n330 goto 300\n340 rem tests if the prime p is a Wilson prime of order n\n350 rem make sure it actually is prime first\n360 rem result is stored in wnpt\n370 wnpt = 0\n380 if p = 2 and n = 2 then wnpt = 1 : return\n390 if n > p then wnpt = 0 : return\n400 prod = 1 : p2 = p*p\n410 for i = 1 to n-1\n420 prod = (prod*i) : gosub 500\n430 next i\n440 for i = 1 to p-n\n450 prod = (prod*i) : gosub 500\n460 next i\n470 prod = (p2+prod-(-1)^n) : gosub 500\n480 if prod = 0 then wnpt = 1 : return\n490 wnpt = 0 : return\n500 rem prod mod p2 fails if prod > 32767 so brew our own modulus function\n510 prod = prod-int(prod/p2)*p2\n520 return\n", "language": "Chipmunk-Basic" }, { "code": "func isprim num .\n i = 2\n while i <= sqrt num\n if num mod i = 0\n return 0\n .\n i += 1\n .\n return 1\n.\nfunc is_wilson n p .\n if p < n\n return 0\n .\n prod = 1\n p2 = p * p\n for i = 1 to n - 1\n prod = prod * i mod p2\n .\n for i = 1 to p - n\n prod = prod * i mod p2\n .\n prod = (p2 + prod - pow -1 n) mod p2\n if prod = 0\n return 1\n .\n return 0\n.\nprint \"n: Wilson primes\"\nprint \"-----------------\"\nfor n = 1 to 11\n write n & \" \"\n for p = 3 step 2 to 10099\n if isprim p = 1 and is_wilson n p = 1\n write p & \" \"\n .\n .\n print \"\"\n.\n", "language": "EasyLang" }, { "code": "// Wilson primes. Nigel Galloway: July 31st., 2021\nlet rec fN g=function n when n<2I->g |n->fN(n*g)(n-1I)\nlet fG (n:int)(p:int)=let g,p=bigint n,bigint p in (((fN 1I (g-1I))*(fN 1I (p-g))-(-1I)**n)%(p*p))=0I\n[1..11]|>List.iter(fun n->printf \"%2d -> \" n; let fG=fG n in pCache|>Seq.skipWhile((>)n)|>Seq.takeWhile((>)11000)|>Seq.filter fG|>Seq.iter(printf \"%d \"); printfn \"\")\n", "language": "F-Sharp" }, { "code": "USING: formatting infix io kernel literals math math.functions\nmath.primes math.ranges prettyprint sequences sequences.extras ;\n\n<< CONSTANT: limit 11,000 >>\n\nCONSTANT: primes $[ limit primes-upto ]\n\nCONSTANT: factorials\n $[ limit [1,b] 1 [ * ] accumulate* 1 prefix ]\n\n: factorial ( n -- n! ) factorials nth ; inline\n\nINFIX:: fn ( p n -- m )\n factorial(n-1) * factorial(p-n) - -1**n ;\n\n: wilson? ( p n -- ? ) [ fn ] keepd sq divisor? ; inline\n\n: order ( n -- seq )\n primes swap [ [ < ] curry drop-while ] keep\n [ wilson? ] curry filter ;\n\n: order. ( n -- )\n dup \"%2d: \" printf order [ pprint bl ] each nl ;\n\n\" n: Wilson primes\\n--------------------\" print\n11 [1,b] [ order. ] each\n", "language": "Factor" }, { "code": "#include \"isprime.bas\"\n\nfunction is_wilson( n as uinteger, p as uinteger ) as boolean\n 'tests if p^2 divides (n-1)!(p-n)! - (-1)^n\n 'does NOT test the primality of p; do that first before you call this!\n 'using mods no big nums are required\n if p<n then return false\n dim as uinteger prod = 1, i, p2 = p^2\n for i = 1 to n-1\n prod = (prod*i) mod p2\n next i\n for i = 1 to p-n\n prod = (prod*i) mod p2\n next i\n prod = (p2 + prod - (-1)^n) mod p2\n if prod = 0 then return true else return false\nend function\n\nprint \"n: Wilson primes\"\nprint \"--------------------\"\nfor n as uinteger = 1 to 11\n print using \"## \";n;\n for p as uinteger = 3 to 10099 step 2\n if isprime(p) andalso is_wilson(n, p) then print p;\" \";\n next p\n print\nnext n\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"rcu\"\n)\n\nfunc main() {\n const LIMIT = 11000\n primes := rcu.Primes(LIMIT)\n facts := make([]*big.Int, LIMIT)\n facts[0] = big.NewInt(1)\n for i := int64(1); i < LIMIT; i++ {\n facts[i] = new(big.Int)\n facts[i].Mul(facts[i-1], big.NewInt(i))\n }\n sign := int64(1)\n f := new(big.Int)\n zero := new(big.Int)\n fmt.Println(\" n: Wilson primes\")\n fmt.Println(\"--------------------\")\n for n := 1; n < 12; n++ {\n fmt.Printf(\"%2d: \", n)\n sign = -sign\n for _, p := range primes {\n if p < n {\n continue\n }\n f.Mul(facts[n-1], facts[p-n])\n f.Sub(f, big.NewInt(sign))\n p2 := int64(p * p)\n bp2 := big.NewInt(p2)\n if f.Rem(f, bp2).Cmp(zero) == 0 {\n fmt.Printf(\"%d \", p)\n }\n }\n fmt.Println()\n }\n}\n", "language": "Go" }, { "code": "10 PRINT \"n: Wilson primes\"\n20 PRINT \"--------------------\"\n30 FOR N = 1 TO 11\n40 PRINT USING \"##\";N;\n50 FOR P=2 TO 18\n60 GOSUB 140\n70 IF PT=0 THEN GOTO 100\n80 GOSUB 230\n90 IF WNPT=1 THEN PRINT P;\n100 NEXT P\n110 PRINT\n120 NEXT N\n130 END\n140 REM tests if the number P is prime\n150 REM result is stored in PT\n160 PT = 1\n170 IF P=2 THEN RETURN\n175 IF P MOD 2 = 0 THEN PT=0:RETURN\n180 J=3\n190 IF J*J>P THEN RETURN\n200 IF P MOD J = 0 THEN PT = 0: RETURN\n210 J = J + 2\n220 GOTO 190\n230 REM tests if the prime P is a Wilson prime of order N\n240 REM make sure it actually is prime first\n250 REM RESULT is stored in WNPT\n260 WNPT=0\n270 IF P=2 AND N=2 THEN WNPT = 1: RETURN\n280 IF N>P THEN WNPT=0: RETURN\n290 PROD# = 1 : P2 = P*P\n300 FOR I = 1 TO N-1\n310 PROD# = (PROD#*I) : GOSUB 3000\n320 NEXT I\n330 FOR I = 1 TO P-N\n340 PROD# = (PROD#*I) : GOSUB 3000\n350 NEXT I\n360 PROD# = (P2+PROD#-(-1)^N) : GOSUB 3000\n370 IF PROD# = 0 THEN WNPT = 1: RETURN\n380 WNPT = 0: RETURN\n3000 REM PROD# MOD P2 fails if PROD#>32767 so brew our own modulus function\n3010 PROD# = PROD# - INT(PROD#/P2)*P2\n3020 RETURN\n", "language": "GW-BASIC" }, { "code": " wilson=. 0 = (*:@] | _1&^@[ -~ -~ *&! <:@[)^:<:\n\n (>: i. 11x) ([ ;\"0 wilson\"0/ <@# ]) i.&.(p:inv) 11000\n┌──┬───────────────┐\n│1 │5 13 563 │\n├──┼───────────────┤\n│2 │2 3 11 107 4931│\n├──┼───────────────┤\n│3 │7 │\n├──┼───────────────┤\n│4 │10429 │\n├──┼───────────────┤\n│5 │5 7 47 │\n├──┼───────────────┤\n│6 │11 │\n├──┼───────────────┤\n│7 │17 │\n├──┼───────────────┤\n│8 │ │\n├──┼───────────────┤\n│9 │541 │\n├──┼───────────────┤\n│10│11 1109 │\n├──┼───────────────┤\n│11│17 2713 │\n└──┴───────────────┘\n", "language": "J" }, { "code": "import java.math.BigInteger;\nimport java.util.*;\n\npublic class WilsonPrimes {\n public static void main(String[] args) {\n final int limit = 11000;\n BigInteger[] f = new BigInteger[limit];\n f[0] = BigInteger.ONE;\n BigInteger factorial = BigInteger.ONE;\n for (int i = 1; i < limit; ++i) {\n factorial = factorial.multiply(BigInteger.valueOf(i));\n f[i] = factorial;\n }\n List<Integer> primes = generatePrimes(limit);\n System.out.printf(\" n | Wilson primes\\n--------------------\\n\");\n BigInteger s = BigInteger.valueOf(-1);\n for (int n = 1; n <= 11; ++n) {\n System.out.printf(\"%2d |\", n);\n for (int p : primes) {\n if (p >= n && f[n - 1].multiply(f[p - n]).subtract(s)\n .mod(BigInteger.valueOf(p * p))\n .equals(BigInteger.ZERO))\n System.out.printf(\" %d\", p);\n }\n s = s.negate();\n System.out.println();\n }\n }\n\n private static List<Integer> generatePrimes(int limit) {\n boolean[] sieve = new boolean[limit >> 1];\n Arrays.fill(sieve, true);\n for (int p = 3, s = 9; s < limit; p += 2) {\n if (sieve[p >> 1]) {\n for (int q = s; q < limit; q += p << 1)\n sieve[q >> 1] = false;\n }\n s += (p + 1) << 2;\n }\n List<Integer> primes = new ArrayList<>();\n if (limit > 2)\n primes.add(2);\n for (int i = 1; i < sieve.length; ++i) {\n if (sieve[i])\n primes.add((i << 1) + 1);\n }\n return primes;\n }\n}\n", "language": "Java" }, { "code": "def emit_until(cond; stream): label $out | stream | if cond then break $out else . end;\n\n# For 0 <= $n <= ., factorials[$n] is $n !\ndef factorials:\n reduce range(1; .+1) as $n ([1];\n .[$n] = $n * .[$n-1]);\n\ndef lpad($len): tostring | ($len - length) as $l | (\" \" * $l)[:$l] + .;\n\ndef primes: 2, (range(3; infinite; 2) | select(is_prime));\n", "language": "Jq" }, { "code": "# Input: the limit of $p\ndef wilson_primes:\n def sgn: if . % 2 == 0 then 1 else -1 end;\n\n . as $limit\n | factorials as $facts\n | \" n: Wilson primes\\n--------------------\",\n (range(1;12) as $n\n | \"\\($n|lpad(2)) : \\(\n [emit_until( . >= $limit; primes)\n | select(. as $p\n | $p >= $n and\n (($facts[$n - 1] * $facts[$p - $n] - ($n|sgn))\n % ($p*$p) == 0 )) ])\" );\n\n11000 | wilson_primes\n", "language": "Jq" }, { "code": "using Primes\n\nfunction wilsonprimes(limit = 11000)\n sgn, facts = 1, accumulate(*, 1:limit, init = big\"1\")\n println(\" n: Wilson primes\\n--------------------\")\n for n in 1:11\n print(lpad(n, 2), \": \")\n sgn = -sgn\n for p in primes(limit)\n if p > n && (facts[n < 2 ? 1 : n - 1] * facts[p - n] - sgn) % p^2 == 0\n print(\"$p \")\n end\n end\n println()\n end\nend\n\nwilsonprimes()\n", "language": "Julia" }, { "code": "ClearAll[WilsonPrime]\nWilsonPrime[n_Integer] := Module[{primes, out},\n primes = Prime[Range[PrimePi[11000]]];\n out = Reap@Do[\n If[Divisible[((n - 1)!) ((p - n)!) - (-1)^n, p^2], Sow[p]]\n ,\n {p, primes}\n ];\n First[out[[2]], {}]\n ]\nDo[\n Print[WilsonPrime[n]]\n ,\n {n, 1, 11}\n]\n", "language": "Mathematica" }, { "code": "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 primes.add p.toInt\n p = p.nextPrime()\n\n# Build list of factorials.\nvar facts: array[Limit, Int]\nfacts[0] = newInt(1)\nfor i in 1..<Limit:\n facts[i] = facts[i - 1] * i\n\nvar sign = 1\necho \" n: Wilson primes\"\necho \"—————————————————\"\nfor n in 1..11:\n sign = -sign\n var wilson: seq[int]\n for p in primes:\n if p < n: continue\n let f = facts[n - 1] * facts[p - n] - sign\n if f mod (p * p) == 0:\n wilson.add p\n echo &\"{n:2}: \", wilson.join(\" \")\n", "language": "Nim" }, { "code": "default(\"parisizemax\", \"1024M\");\n\n\n\\\\ Define the function wilsonprimes with a default limit of 11000\nwilsonprimes(limit) = {\n \\\\ Set the default limit if not specified\n my(limit = if(limit, limit, 11000));\n \\\\ Precompute factorial values up to the limit to save time\n my(facts = vector(limit, i, i!));\n \\\\ Sign variable for adjustment in the formula\n my(sgn = 1);\n print(\" n: Wilson primes\\n--------------------\");\n \\\\ Loop over the specified range (1 to 11 in the original code)\n for(n = 1, 11,\n print1(Str(\" \", n, \": \"));\n sgn = -sgn; \\\\ Toggle the sign\n \\\\ Loop over all primes up to the limit\n forprime(p = 2, limit,\n \\\\ Check the Wilson prime condition modified for PARI/GP\n index=1;\n if(n<2,index=1,index=n-1);\n if(p > n && Mod(facts[index] * facts[p - n] - sgn, p^2) == 0,\n print1(Str(p, \" \"));\n )\n );\n print1(\"\\n\");\n );\n}\n\n\\\\ Execute the function with the default limit\nwilsonprimes();\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse ntheory <primes factorial>;\n\nmy @primes = @{primes( 10500 )};\n\nfor my $n (1..11) {\n printf \"%3d: %s\\n\", $n, join ' ', grep { $_ >= $n && 0 == (factorial($n-1) * factorial($_-$n) - (-1)**$n) % $_**2 } @primes\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">11000</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">mpfr</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">mpz</span> <span style=\"color: #000000;\">f</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_init</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">primes</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_primes_le</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">facts</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mpz_inits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">limit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (nb 0!==1!, same slot)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">limit</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #7060A8;\">mpz_mul_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">facts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">facts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">sgn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" n: Wilson primes\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"--------------------\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">11</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: \"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">sgn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">sgn</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">primes</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">primes</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">mpz_mul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">facts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)],</span><span style=\"color: #000000;\">facts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">max</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)])</span>\n <span style=\"color: #7060A8;\">mpz_sub_si</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sgn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mpz_divisible_ui_p</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d \"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "main:-\n wilson_primes(11000).\n\nwilson_primes(Limit):-\n writeln(' n | Wilson primes\\n---------------------'),\n make_factorials(Limit),\n find_prime_numbers(Limit),\n wilson_primes(1, 12, -1).\n\nwilson_primes(N, N, _):-!.\nwilson_primes(N, M, S):-\n wilson_primes(N, S),\n S1 is -S,\n N1 is N + 1,\n wilson_primes(N1, M, S1).\n\nwilson_primes(N, S):-\n writef('%3r |', [N]),\n N1 is N - 1,\n factorial(N1, F1),\n is_prime(P),\n P >= N,\n PN is P - N,\n factorial(PN, F2),\n 0 is (F1 * F2 - S) mod (P * P),\n writef(' %w', [P]),\n fail.\nwilson_primes(_, _):-\n nl.\n\nmake_factorials(N):-\n retractall(factorial(_, _)),\n make_factorials(N, 0, 1).\n\nmake_factorials(N, N, F):-\n assert(factorial(N, F)),\n !.\nmake_factorials(N, M, F):-\n assert(factorial(M, F)),\n M1 is M + 1,\n F1 is F * M1,\n make_factorials(N, M1, F1).\n", "language": "Prolog" }, { "code": ":- module(prime_numbers, [find_prime_numbers/1, is_prime/1]).\n:- dynamic is_prime/1.\n\nfind_prime_numbers(N):-\n retractall(is_prime(_)),\n assertz(is_prime(2)),\n init_sieve(N, 3),\n sieve(N, 3).\n\ninit_sieve(N, P):-\n P > N,\n !.\ninit_sieve(N, P):-\n assertz(is_prime(P)),\n Q is P + 2,\n init_sieve(N, Q).\n\nsieve(N, P):-\n P * P > N,\n !.\nsieve(N, P):-\n is_prime(P),\n !,\n S is P * P,\n cross_out(S, N, P),\n Q is P + 2,\n sieve(N, Q).\nsieve(N, P):-\n Q is P + 2,\n sieve(N, Q).\n\ncross_out(S, N, _):-\n S > N,\n !.\ncross_out(S, N, P):-\n retract(is_prime(S)),\n !,\n Q is S + 2 * P,\n cross_out(Q, N, P).\ncross_out(S, N, P):-\n Q is S + 2 * P,\n cross_out(Q, N, P).\n", "language": "Prolog" }, { "code": "# wilson_prime.py by xing216\ndef sieve(n):\n multiples = []\n for i in range(2, n+1):\n if i not in multiples:\n yield i\n for j in range(i*i, n+1, i):\n multiples.append(j)\ndef intListToString(list):\n return \" \".join([str(i) for i in list])\nlimit = 11000\nprimes = list(sieve(limit))\nfacs = [1]\nfor i in range(1,limit):\n facs.append(facs[-1]*i)\nsign = 1\nprint(\" n: Wilson primes\")\nprint(\"—————————————————\")\n\nfor n in range(1,12):\n sign = -sign\n wilson = []\n for p in primes:\n if p < n: continue\n f = facs[n-1] * facs[p-n] - sign\n if f % p**2 == 0: wilson.append(p)\n print(f\"{n:2d}: {intListToString(wilson)}\")\n", "language": "Python" }, { "code": "FUNCTION isPrime (ValorEval)\n IF ValorEval < 2 THEN isPrime = False\n IF ValorEval MOD 2 = 0 THEN isPrime = 2\n IF ValorEval MOD 3 = 0 THEN isPrime = 3\n d = 5\n WHILE d * d <= ValorEval\n IF ValorEval MOD d = 0 THEN isPrime = False ELSE d = d + 2\n WEND\n isPrime = True\nEND FUNCTION\n\nFUNCTION isWilson (n, p)\n IF p < n THEN isWilson = False\n prod = 1\n p2 = p ^ 2\n FOR i = 1 TO n - 1\n prod = (prod * i) MOD p2\n NEXT i\n FOR i = 1 TO p - n\n prod = (prod * i) MOD p2\n NEXT i\n prod = (p2 + prod - (-1) ^ n) MOD p2\n IF prod = 0 THEN isWilson = True ELSE isWilson = False\nEND FUNCTION\n\nPRINT \" n: Wilson primes\"\nPRINT \"----------------------\"\nFOR n = 1 TO 11\n PRINT USING \"##: \"; n;\n FOR p = 3 TO 10099 STEP 2\n If isPrime(p) AND isWilson(n, p) Then Print p; \" \";\n NEXT p\n PRINT\nNEXT n\nEND\n", "language": "QBasic" }, { "code": "#lang racket\n\n(require math/number-theory)\n\n(define ((wilson-prime? n) p)\n (and (>= p n)\n (prime? p)\n (divides? (sqr p)\n (- (* (factorial (- n 1))\n (factorial (- p n)))\n (expt -1 n)))))\n\n(define primes<11000 (filter prime? (range 1 11000)))\n\n(for ((n (in-range 1 (add1 11))))\n (printf \"~a: ~a~%\" n (filter (wilson-prime? n) primes<11000)))\n", "language": "Racket" }, { "code": "# Factorial\nsub postfix:<!> (Int $n) { (constant f = 1, |[\\×] 1..*)[$n] }\n\n# Invisible times\nsub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };\n\n# Prime the iterator for thread safety\nsink 11000!;\n\nmy @primes = ^1.1e4 .grep: *.is-prime;\n\nsay\n' n: Wilson primes\n────────────────────';\n\n.say for (1..40).hyper(:1batch).map: -> \\𝒏 {\n sprintf \"%3d: %s\", 𝒏, @primes.grep( -> \\𝒑 { (𝒑 ≥ 𝒏) && ((𝒏 - 1)!⁢(𝒑 - 𝒏)! - (-1) ** 𝒏) %% 𝒑² } ).Str\n}\n", "language": "Raku" }, { "code": "/*REXX program finds and displays Wilson primes: a prime P such that P**2 divides:*/\n/*────────────────── (n-1)! * (P-n)! - (-1)**n where n is 1 ──◄ 11, and P < 18.*/\nparse arg oLO oHI hip . /*obtain optional argument from the CL.*/\nif oLO=='' | oLO==\",\" then oLO= 1 /*Not specified? Then use the default.*/\nif oHI=='' | oHI==\",\" then oHI= 11 /* \" \" \" \" \" \" */\nif hip=='' | hip==\",\" then hip= 11000 /* \" \" \" \" \" \" */\ncall genP /*build array of semaphores for primes.*/\n!!.= . /*define the default for factorials. */\nbignum= !(hip) /*calculate a ginormous factorial prod.*/\nparse value bignum 'E0' with ex 'E' ex . /*obtain possible exponent of factorial*/\nnumeric digits (max(9, ex+2) ) /*calculate max # of dec. digits needed*/\ncall facts hip /*go & calculate a number of factorials*/\ntitle= ' Wilson primes P of order ' oLO \" ──► \" oHI', where P < ' commas(hip)\nw= length(title) + 1 /*width of columns of possible numbers.*/\nsay ' order │'center(title, w )\nsay '───────┼'center(\"\" , w, '─')\n do n=oLO to oHI; nf= !(n-1) /*precalculate a factorial product. */\n z= -1**n /* \" \" plus or minus (+1│-1).*/\n if n==1 then lim= 103 /*limit to known primes for 1st order. */\n else lim= # /* \" \" all \" \" orders ≥ 2.*/\n $= /*$: a line (output) of Wilson primes.*/\n do j=1 for lim; p= @.j /*search through some generated primes.*/\n if (nf*!(p-n)-z)//sq.j\\==0 then iterate /*expression ~ q.j ? No, then skip it.*/ /* ◄■■■■■■■ the filter.*/\n $= $ ' ' commas(p) /*add a commatized prime ──► $ list.*/\n end /*p*/\n\n if $=='' then $= ' (none found within the range specified)'\n say center(n, 7)'│' substr($, 2) /*display what Wilson primes we found. */\n end /*n*/\nsay '───────┴'center(\"\" , w, '─')\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\n!: arg x; if !!.x\\==. then return !!.x; a=1; do f=1 for x; a=a*f; end; return a\ncommas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?\nfacts: !!.= 1; x= 1; do f=1 for hip; x= x * f; !!.f= x; end; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngenP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */\n !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* \" \" \" \" semaphores. */\n sq.1=4; sq.2=9; sq.3= 25; sq.4= 49; #= 5; sq.#= @.#**2 /*squares of low primes.*/\n do j=@.#+2 by 2 for max(0, hip%2-@.#%2-1) /*find odd primes from here on. */\n parse var j '' -1 _; if _==5 then iterate /*J ÷ 5? (right digit).*/\n if j//3==0 then iterate; if j//7==0 then iterate /*\" \" 3? Is J ÷ by 7? */\n do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/\n if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */\n end /*k*/ /* [↑] only process numbers ≤ √ J */\n #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */\n end /*j*/; return\n", "language": "REXX" }, { "code": "require \"prime\"\n\nmodule Modulo\n refine Integer do\n def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }\n end\nend\n\nusing Modulo\nprimes = Prime.each(11000).to_a\n\n(1..11).each do |n|\n res = primes.select do |pr|\n prpr = pr*pr\n ((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)**n) % (prpr) == 0\n end\n puts \"#{n.to_s.rjust(2)}: #{res.inspect}\"\nend\n", "language": "Ruby" }, { "code": "// [dependencies]\n// rug = \"1.13.0\"\n\nuse rug::Integer;\n\nfn generate_primes(limit: usize) -> Vec<usize> {\n let mut sieve = vec![true; limit >> 1];\n let mut p = 3;\n let mut sq = p * p;\n while sq < limit {\n if sieve[p >> 1] {\n let mut q = sq;\n while q < limit {\n sieve[q >> 1] = false;\n q += p << 1;\n }\n }\n sq += (p + 1) << 2;\n p += 2;\n }\n let mut primes = Vec::new();\n if limit > 2 {\n primes.push(2);\n }\n for i in 1..sieve.len() {\n if sieve[i] {\n primes.push((i << 1) + 1);\n }\n }\n primes\n}\n\nfn factorials(limit: usize) -> Vec<Integer> {\n let mut f = vec![Integer::from(1)];\n let mut factorial = Integer::from(1);\n f.reserve(limit);\n for i in 1..limit {\n factorial *= i as u64;\n f.push(factorial.clone());\n }\n f\n}\n\nfn main() {\n let limit = 11000;\n let f = factorials(limit);\n let primes = generate_primes(limit);\n println!(\" n | Wilson primes\\n--------------------\");\n let mut s = -1;\n for n in 1..=11 {\n print!(\"{:2} |\", n);\n for p in &primes {\n if *p >= n {\n let mut num = Integer::from(&f[n - 1] * &f[*p - n]);\n num -= s;\n if num % ((p * p) as u64) == 0 {\n print!(\" {}\", p);\n }\n }\n }\n println!();\n s = -s;\n }\n}\n", "language": "Rust" }, { "code": "func is_wilson_prime(p, n = 1) {\n var m = p*p\n (factorialmod(n-1, m) * factorialmod(p-n, m) - (-1)**n) % m == 0\n}\n\nvar primes = 1.1e4.primes\n\nsay \" n: Wilson primes\\n────────────────────\"\n\nfor n in (1..11) {\n printf(\"%3d: %s\\n\", n, primes.grep {|p| is_wilson_prime(p, n) })\n}\n", "language": "Sidef" }, { "code": "Option Strict On\nOption Explicit On\n\nModule WilsonPrimes\n\n Function isPrime(p As Integer) As Boolean\n If p < 2 Then Return False\n If p Mod 2 = 0 Then Return p = 2\n IF p Mod 3 = 0 Then Return p = 3\n Dim d As Integer = 5\n Do While d * d <= p\n If p Mod d = 0 Then\n Return False\n Else\n d = d + 2\n End If\n Loop\n Return True\n End Function\n\n Function isWilson(n As Integer, p As Integer) As Boolean\n If p < n Then Return False\n Dim prod As Long = 1\n Dim p2 As Long = p * p\n For i = 1 To n - 1\n prod = (prod * i) Mod p2\n Next i\n For i = 1 To p - n\n prod = (prod * i) Mod p2\n Next i\n prod = (p2 + prod - If(n Mod 2 = 0, 1, -1)) Mod p2\n Return prod = 0\n End Function\n\n Sub Main()\n Console.Out.WriteLine(\" n: Wilson primes\")\n Console.Out.WriteLine(\"----------------------\")\n For n = 1 To 11\n Console.Out.Write(n.ToString.PadLeft(2) & \": \")\n If isWilson(n, 2) Then Console.Out.Write(\"2 \")\n For p = 3 TO 10499 Step 2\n If isPrime(p) And isWilson(n, p) Then Console.Out.Write(p & \" \")\n Next p\n Console.Out.WriteLine()\n Next n\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./math\" for Int\nimport \"./big\" for BigInt\nimport \"./fmt\" for Fmt\n\nvar limit = 11000\nvar primes = Int.primeSieve(limit)\nvar facts = List.filled(limit, null)\nfacts[0] = BigInt.one\nfor (i in 1...11000) facts[i] = facts[i-1] * i\nvar sign = 1\nSystem.print(\" n: Wilson primes\")\nSystem.print(\"--------------------\")\nfor (n in 1..11) {\n Fmt.write(\"$2d: \", n)\n sign = -sign\n for (p in primes) {\n if (p < n) continue\n var f = facts[n-1] * facts[p-n] - sign\n if (f.isDivisibleBy(p*p)) Fmt.write(\"%(p) \", p)\n }\n System.print()\n}\n", "language": "Wren" }, { "code": "print \"n: Wilson primes\"\nprint \"---------------------\"\nfor n = 1 to 11\n print n, \":\",\n for p = 3 to 10099 step 2\n if isPrime(p) and isWilson(n, p) then print p, \" \", : fi\n next p\n print\nnext n\nend\n\nsub isPrime(v)\n if v < 2 then return False : fi\n if mod(v, 2) = 0 then return v = 2 : fi\n if mod(v, 3) = 0 then return v = 3 : fi\n d = 5\n while d * d <= v\n if mod(v, d) = 0 then return False else d = d + 2 : fi\n end while\n return True\nend sub\n\nsub isWilson(n, p)\n if p < n then return False : fi\n prod = 1\n\tp2 = p**2\n for i = 1 to n-1\n prod = mod((prod*i), p2)\n next i\n for i = 1 to p-n\n prod = mod((prod*i), p2)\n next i\n prod = mod((p2 + prod - (-1)**n), p2)\n if prod = 0 then return True else return False : fi\nend sub\n", "language": "Yabasic" } ]
Wilson-primes-of-order-n
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Window_creation/X11\nnote: GUI\nrequires:\n- Graphics\n", "language": "00-META" }, { "code": ";Task:\nCreate a simple '''X11''' application, &nbsp; using an '''X11''' protocol library such as Xlib or XCB, &nbsp; that draws a box and &nbsp; \"Hello World\" &nbsp; in a window. \n\nImplementations of this task should &nbsp; ''avoid using a toolkit'' &nbsp; as much as possible.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program creatFenX1164.s */\n/* link with gcc options -lX11 -L/usr/lpp/X11/lib */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n.equ ClientMessage, 33\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszRetourligne: .asciz \"\\n\"\nszMessErreur: .asciz \"Server X11 not found.\\n\"\nszMessErrfen: .asciz \"Error create X11 window.\\n\"\n\nszLibDW: .asciz \"WM_DELETE_WINDOW\" // message close window\n\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n.align 4\nqDisplay: .skip 8 // Display address\nqDefScreen: .skip 8 // Default screen address\nidentWin: .skip 8 // window ident\nwmDeleteMessage: .skip 16 // ident close message\nstEvent: .skip 400 // provisional size\n\nbuffer: .skip 500\n\n/**********************************************/\n/* -- Code section */\n/**********************************************/\n.text\n.global main // program entry\nmain:\n mov x0,#0 // open server X\n bl XOpenDisplay\n cmp x0,#0\n beq erreur\n // Ok return Display address\n ldr x1,qAdrqDisplay\n str x0,[x1] // store Display address for future use\n mov x28,x0 // and in register 28\n // load default screen\n ldr x2,[x0,#264] // at location 264\n ldr x1,qAdrqDefScreen\n str x2,[x1] //store default_screen\n mov x2,x0\n ldr x0,[x2,#232] // screen list\n\n //screen areas\n ldr x5,[x0,#+88] // white pixel\n ldr x3,[x0,#+96] // black pixel\n ldr x4,[x0,#+56] // bits par pixel\n ldr x1,[x0,#+16] // root windows\n // create window x11\n mov x0,x28 //display\n mov x2,#0 // position X\n mov x3,#0 // position Y\n mov x4,600 // weight\n mov x5,400 // height\n mov x6,0 // bordure ???\n ldr x7,0 // ?\n ldr x8,qBlanc // background\n str x8,[sp,-16]! // argument fot stack\n bl XCreateSimpleWindow\n add sp,sp,16 // for stack alignement\n cmp x0,#0 // error ?\n beq erreurF\n //mov x3,sp\n ldr x1,qAdridentWin\n str x0,[x1] // store window ident for future use\n mov x27,x0 // and in register 27\n\n // Correction of window closing error\n mov x0,x28 // Display address\n ldr x1,qAdrszLibDW // atom name address\n mov x2,#1 // False create atom if not exist\n bl XInternAtom\n cmp x0,#0\n ble erreurF\n ldr x1,qAdrwmDeleteMessage // address message\n str x0,[x1]\n mov x2,x1 // address atom create\n mov x0,x28 // display address\n mov x1,x27 // window ident\n mov x3,#1 // number of protocoles\n bl XSetWMProtocols\n cmp x0,#0\n ble erreurF\n\n // Display window\n mov x1,x27 // ident window\n mov x0,x28 // Display address\n bl XMapWindow\n\n1: // events loop\n mov x0,x28 // Display address\n ldr x1,qAdrstEvent // events structure address\n bl XNextEvent\n ldr x0,qAdrstEvent // events structure address\n ldr w0,[x0] // type in 4 fist bytes\n cmp w0,#ClientMessage // message for close window\n bne 1b // no -> loop\n\n ldr x0,qAdrstEvent // events structure address\n ldr x1,[x0,56] // location message code\n ldr x2,qAdrwmDeleteMessage // equal ?\n ldr x2,[x2]\n cmp x1,x2\n bne 1b // no loop\n\n mov x0,0 // end Ok\n b 100f\nerreurF: // error create window\n ldr x0,qAdrszMessErrfen\n bl affichageMess\n mov x0,1\n b 100f\nerreur: // error no server x11 active\n ldr x0,qAdrszMessErreur\n bl affichageMess\n mov x0,1\n100: // program standard end\n mov x8,EXIT\n svc 0\nqBlanc: .quad 0xF0F0F0F0\nqAdrqDisplay: .quad qDisplay\nqAdrqDefScreen: .quad qDefScreen\nqAdridentWin: .quad identWin\nqAdrstEvent: .quad stEvent\nqAdrszMessErrfen: .quad szMessErrfen\nqAdrszMessErreur: .quad szMessErreur\nqAdrwmDeleteMessage: .quad wmDeleteMessage\nqAdrszLibDW: .quad szLibDW\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "FILE window;\ndraw device (window, \"X\", \"600x400\");\nopen (window, \"Hello, World!\", stand draw channel);\n draw erase (window);\n draw move (window, 0.25, 0.5);\n draw colour (window, 1, 0, 0);\n draw text (window, \"c\", \"c\", \"hello world\");\n draw show (window);\n VOID (read char);\nclose (window)\n", "language": "ALGOL-68" }, { "code": "/* ARM assembly Raspberry PI */\n/* program windows1.s */\n\n/* compile with as */\n/* link with gcc and options -lX11 -L/usr/lpp/X11/lib */\n\n/********************************************/\n/*Constantes */\n/********************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n/* constantes X11 */\n.equ KeyPressed, 2\n.equ ButtonPress, 4\n.equ MotionNotify, 6\n.equ EnterNotify, 7\n.equ LeaveNotify, 8\n.equ Expose, 12\n.equ ClientMessage, 33\n.equ KeyPressMask, 1\n.equ ButtonPressMask, 4\n.equ ButtonReleaseMask, 8\n.equ ExposureMask, 1<<15\n.equ StructureNotifyMask, 1<<17\n.equ EnterWindowMask, 1<<4\n.equ LeaveWindowMask, 1<<5\n.equ ConfigureNotify, 22\n\n/*******************************************/\n/* DONNEES INITIALISEES */\n/*******************************************/\n.data\nszWindowName: .asciz \"Windows Raspberry\"\nszRetourligne: .asciz \"\\n\"\nszMessDebutPgm: .asciz \"Program start. \\n\"\nszMessErreur: .asciz \"Server X not found.\\n\"\nszMessErrfen: .asciz \"Can not create window.\\n\"\nszMessErreurX11: .asciz \"Error call function X11. \\n\"\nszMessErrGc: .asciz \"Can not create graphics context.\\n\"\nszTitreFenRed: .asciz \"Pi\"\nszTexte1: .asciz \"Hello world.\"\n.equ LGTEXTE1, . - szTexte1\nszTexte2: .asciz \"Press q for close window or clic X in system menu.\"\n.equ LGTEXTE2, . - szTexte2\nszLibDW: .asciz \"WM_DELETE_WINDOW\" @ special label for correct close error\n\n/*************************************************/\nszMessErr: .ascii\t\"Error code hexa : \"\nsHexa: .space 9,' '\n .ascii \" decimal : \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\n\n/*******************************************/\n/* DONNEES NON INITIALISEES */\n/*******************************************/\n.bss\n.align 4\nptDisplay: .skip 4 @ pointer display\nptEcranDef: .skip 4 @ pointer screen default\nptFenetre: .skip 4 @ pointer window\nptGC: .skip 4 @ pointer graphic context\nkey: .skip 4 @ key code\nwmDeleteMessage: .skip 8 @ ident close message\nevent: .skip 400 @ TODO event size ??\nPrpNomFenetre: .skip 100 @ window name proprety\nbuffer: .skip 500\niWhite: .skip 4 @ rgb code for white pixel\niBlack: .skip 4 @ rgb code for black pixel\n/**********************************************/\n/* -- Code section */\n/**********************************************/\n.text\n.global main\n\nmain: @ entry of program\n ldr r0,iAdrszMessDebutPgm @\n bl affichageMess @ display start message on console linux\n /* attention r6 pointer display*/\n /* attention r8 pointer graphic context */\n /* attention r9 ident window */\n /*****************************/\n /* OPEN SERVER X11 */\n /*****************************/\n mov r0,#0\n bl XOpenDisplay @ open X server\n cmp r0,#0 @ error ?\n beq erreurServeur\n ldr r1,iAdrptDisplay\n str r0,[r1] @ store display address\n mov r6,r0 @ and in register r6\n ldr r2,[r0,#+132] @ load default_screen\n ldr r1,iAdrptEcranDef\n str r2,[r1] @ store default_screen\n mov r2,r0\n ldr r0,[r2,#+140] @ load pointer screen list\n ldr r5,[r0,#+52] @ load value white pixel\n ldr r4,iAdrWhite @ and store in memory\n str r5,[r4]\n ldr r3,[r0,#+56] @ load value black pixel\n ldr r4,iAdrBlack @ and store in memory\n str r3,[r4]\n ldr r4,[r0,#+28] @ load bits par pixel\n ldr r1,[r0,#+8] @ load root windows\n /**************************/\n /* CREATE WINDOW */\n /**************************/\n mov r0,r6 @ address display\n mov r2,#0 @ window position X\n mov r3,#0 @ window position Y\n mov r8,#0 @ for stack alignement\n push {r8}\n push {r3} @ background = black pixel\n push {r5} @ border = white pixel\n mov r8,#2 @ border size\n push {r8}\n mov r8,#400 @ hauteur\n push {r8}\n mov r8,#600 @ largeur\n push {r8}\n bl XCreateSimpleWindow\n add sp,#24 @ stack alignement 6 push (4 bytes * 6)\n cmp r0,#0 @ error ?\n beq erreurF\n\n ldr r1,iAdrptFenetre\n str r0,[r1] @ store window address in memory\n mov r9,r0 @ and in register r9\n /*****************************/\n /* add window property */\n /*****************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iAdrszWindowName @ window name\n ldr r3,iAdrszTitreFenRed @ window name reduced\n mov r4,#0\n push {r4} @ parameters not use\n push {r4}\n push {r4}\n push {r4}\n bl XSetStandardProperties\n add sp,sp,#16 @ stack alignement for 4 push\n /**************************************/\n /* for correction window close error */\n /**************************************/\n mov r0,r6 @ display address\n ldr r1,iAdrszLibDW @ atom address\n mov r2,#1 @ False créate atom if not exists\n bl XInternAtom\n cmp r0,#0 @ error X11 ?\n ble erreurX11\n ldr r1,iAdrwmDeleteMessage @ recept address\n str r0,[r1]\n mov r2,r1 @ return address\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r3,#1 @ number of protocols\n bl XSetWMProtocols\n cmp r0,#0 @ error X11 ?\n ble erreurX11\n /**********************************/\n /* create graphic context */\n /**********************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,#0 @ not use for simply context\n mov r3,#0\n bl XCreateGC\n cmp r0,#0 @ error ?\n beq erreurGC\n ldr r1,iAdrptGC\n str r0,[r1] @ store address graphic context\n mov r8,r0 @ and in r8\n /****************************/\n /* modif window background */\n /****************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iGris1 @ background color\n bl XSetWindowBackground\n cmp r0,#0 @ error ?\n ble erreurX11\n /***************************/\n /* OUF!! window display */\n /***************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n bl XMapWindow\n /****************************/\n /* Write text in the window */\n /****************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,r8 @ address graphic context\n mov r3,#50 @ position x\n sub sp,#4 @ stack alignement\n mov r4,#LGTEXTE1 - 1 @ size string\n push {r4} @ on the stack\n ldr r4,iAdrszTexte1 @ string address\n push {r4}\n mov r4,#100 @ position y\n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement\n cmp r0,#0 @ error ?\n blt erreurX11\n /* write text 2 */\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,r8 @ address graphic context\n mov r3,#10 @ position x\n sub sp,#4 @ stack alignement\n mov r4,#LGTEXTE2 - 1 @ size string\n push {r4} @ on the stack\n ldr r4,iAdrszTexte2 @ string address\n push {r4}\n mov r4,#350 @ position y\n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement\n cmp r0,#0 @ error ?\n blt erreurX11\n /****************************/\n /* Autorisations */\n /****************************/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iFenetreMask @ autorisation mask\n bl XSelectInput\n cmp r0,#0 @ error ?\n ble erreurX11\n /****************************/\n /* Events loop */\n /****************************/\n1:\n mov r0,r6 @ display address\n ldr r1,iAdrevent @ events address\n bl XNextEvent @ event ?\n ldr r0,iAdrevent\n ldr r0,[r0] @ code event\n cmp r0,#KeyPressed @ key ?\n bne 2f\n ldr r0,iAdrevent @ yes read key in buffer\n ldr r1,iAdrbuffer\n mov r2,#255\n ldr r3,iAdrkey\n mov r4,#0\n push {r4} @ stack alignement\n push {r4}\n bl XLookupString\n add sp,#8 @ stack alignement 2 push\n cmp r0,#1 @ is character key ?\n bne 2f\n ldr r0,iAdrbuffer @ yes -> load first buffer character\n ldrb r0,[r0]\n cmp r0,#0x71 @ character q for quit\n beq 5f @ yes -> end\n b 4f\n2:\n /* */\n /* for example clic mouse button */\n /************************************/\n cmp r0,#ButtonPress @ clic mouse buton\n bne 3f\n ldr r0,iAdrevent\n ldr r1,[r0,#+32] @ position X mouse clic\n ldr r2,[r0,#+36] @ position Y\n @ etc for eventuel use\n b 4f\n3:\n cmp r0,#ClientMessage @ code for close window within error\n bne 4f\n ldr r0,iAdrevent\n ldr r1,[r0,#+28] @ code message address\n ldr r2,iAdrwmDeleteMessage @ equal code window créate ???\n ldr r2,[r2]\n cmp r1,r2\n beq 5f @ yes -> end window\n\n4: @ loop for other event\n b 1b\n /***********************************/\n /* Close window -> free ressources */\n /***********************************/\n5:\n mov r0,r6 @ display address\n ldr r1,iAdrptGC\n ldr r1,[r1] @ load context graphic address\n bl XFreeGC\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n bl XDestroyWindow\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address\n bl XCloseDisplay\n cmp r0,#0\n blt erreurX11\n mov r0,#0 @ return code OK\n b 100f\nerreurF: @ create error window but possible not necessary. Display error by server\n ldr r1,iAdrszMessErrfen\n bl displayError\n mov r0,#1 @ return error code\n b 100f\nerreurGC: @ error create graphic context\n ldr r1,iAdrszMessErrGc\n bl displayError\n mov r0,#1\n b 100f\nerreurX11: @ erreur X11\n ldr r1,iAdrszMessErreurX11\n bl displayError\n mov r0,#1\n b 100f\nerreurServeur: @ error no found X11 server see doc putty and Xming\n ldr r1,iAdrszMessErreur\n bl displayError\n mov r0,#1\n b 100f\n\n100: @ standard end of the program\n mov r7, #EXIT\n svc 0\niFenetreMask: .int KeyPressMask|ButtonPressMask|StructureNotifyMask\niGris1: .int 0xFFA0A0A0\niAdrWhite: .int iWhite\niAdrBlack: .int iBlack\niAdrptDisplay: .int ptDisplay\niAdrptEcranDef: .int ptEcranDef\niAdrptFenetre: .int ptFenetre\niAdrptGC: .int ptGC\niAdrevent: .int event\niAdrbuffer: .int buffer\niAdrkey: .int key\niAdrszLibDW: .int szLibDW\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessErreurX11: .int szMessErreurX11\niAdrszMessErrGc: .int szMessErrGc\niAdrszMessErreur: .int szMessErreur\niAdrszMessErrfen: .int szMessErrfen\niAdrszWindowName: .int szWindowName\niAdrszTitreFenRed: .int szTitreFenRed\niAdrszTexte1: .int szTexte1\niAdrszTexte2: .int szTexte2\niAdrPrpNomFenetre: .int PrpNomFenetre\niAdrwmDeleteMessage: .int wmDeleteMessage\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur registers */\n bx lr @ return\n/***************************************************/\n/* affichage message d erreur */\n/***************************************************/\n/* r0 contains error code r1 : message address */\ndisplayError:\n push {r0-r2,lr} @ save registers\n mov r2,r0 @ save error code\n mov r0,r1\n bl affichageMess\n mov r0,r2 @ error code\n ldr r1,iAdrsHexa\n bl conversion16 @ conversion hexa\n mov r0,r2 @ error code\n ldr r1,iAdrsDeci @ result address\n bl conversion10 @ conversion decimale\n ldr r0,iAdrszMessErr @ display error message\n bl affichageMess\n100:\n pop {r0-r2,lr} @ restaur registers\n bx lr @ return\niAdrszMessErr: .int szMessErr\niAdrsHexa: .int sHexa\niAdrsDeci: .int sDeci\n/******************************************************************/\n/* Converting a register to hexadecimal */\n/******************************************************************/\n/* r0 contains value and r1 address area */\nconversion16:\n push {r1-r4,lr} @ save registers\n mov r2,#28 @ start bit position\n mov r4,#0xF0000000 @ mask\n mov r3,r0 @ save entry value\n1: @ start loop\n and r0,r3,r4 @value register and mask\n lsr r0,r2 @ move right\n cmp r0,#10 @ compare value\n addlt r0,#48 @ <10 ->digit\t\n addge r0,#55 @ >10 ->letter A-F\n strb r0,[r1],#1 @ store digit on area and + 1 in area address\n lsr r4,#4 @ shift mask 4 positions\n subs r2,#4 @ counter bits - 4 <= zero ?\n bge 1b @ no -> loop\n\n100:\n pop {r1-r4,lr} @ restaur registers\n bx lr @return\n/******************************************************************/\n/* Converting a register to a decimal unsigned */\n/******************************************************************/\n/* r0 contains value and r1 address area */\n/* r0 return size of result (no zero final in area) */\n/* area size => 11 bytes */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers\n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0\n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length\n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres\n bx lr @return\n\n/***************************************************/\n/* division par 10 unsigned */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\n/* r1 remainder */\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)\n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5\n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function\niMagicNumber: \t.int 0xCCCCCCCD\n", "language": "ARM-Assembly" }, { "code": "'--- added a flush to exit cleanly\nPRAGMA LDFLAGS `pkg-config --cflags --libs x11`\nPRAGMA INCLUDE <X11/Xlib.h>\nPRAGMA INCLUDE <X11/Xutil.h>\n\nOPTION PARSE FALSE\n\n'---XLIB is so ugly\nALIAS XNextEvent TO EVENT\nALIAS XOpenDisplay TO DISPLAY\nALIAS DefaultScreen TO SCREEN\nALIAS XCreateSimpleWindow TO CREATE\nALIAS XCloseDisplay TO CLOSE_DISPLAY\nALIAS XSelectInput TO EVENT_TYPE\nALIAS XMapWindow TO MAP_EVENT\nALIAS XFillRectangle TO FILL_RECTANGLE\nALIAS XDrawString TO DRAW_STRING\nALIAS XFlush TO FLUSH\n\n\n'---pointer to X Display structure\nDECLARE d TYPE Display*\n\n'---pointer to the newly created window\t\t\n'DECLARE w TYPE WINDOW\n\n'---pointer to the XEvent\nDECLARE e TYPE XEvent\n\nDECLARE msg TYPE char*\n\n'--- number of screen to place the window on\nDECLARE s TYPE int\n\n\n\n msg = \"Hello, World!\"\n\n\n d = DISPLAY(NULL)\n IF d == NULL THEN\n\t EPRINT \"Cannot open display\" FORMAT \"%s%s\\n\"\n\t END\n END IF\n\n s = SCREEN(d)\n w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))\n\n EVENT_TYPE(d, w, ExposureMask | KeyPressMask)\n MAP_EVENT(d, w)\n\n WHILE (1)\n\t EVENT(d, &e)\n\t IF e.type == Expose THEN\n\t FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)\n\t DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))\n\t END IF\n\t IF e.type == KeyPress THEN\n\t BREAK\n\t END IF\n WEND\n FLUSH(d)\n CLOSE_DISPLAY(d)\n", "language": "BaCon" }, { "code": "#include <X11/Xlib.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main(void) {\n Display *d;\n Window w;\n XEvent e;\n const char *msg = \"Hello, World!\";\n int s;\n\n d = XOpenDisplay(NULL);\n if (d == NULL) {\n fprintf(stderr, \"Cannot open display\\n\");\n exit(1);\n }\n\n s = DefaultScreen(d);\n w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1,\n BlackPixel(d, s), WhitePixel(d, s));\n XSelectInput(d, w, ExposureMask | KeyPressMask);\n XMapWindow(d, w);\n\n while (1) {\n XNextEvent(d, &e);\n if (e.type == Expose) {\n XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);\n XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg));\n }\n if (e.type == KeyPress)\n break;\n }\n\n XCloseDisplay(d);\n return 0;\n}\n", "language": "C" }, { "code": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <xcb/xcb.h>\n\nint main ()\n{\n xcb_connection_t *c;\n xcb_screen_t *screen;\n xcb_drawable_t win;\n xcb_gcontext_t foreground;\n xcb_gcontext_t background;\n xcb_generic_event_t *e;\n uint32_t mask = 0;\n uint32_t values[2];\n\n char string[] = \"Hello, XCB!\";\n uint8_t string_len = strlen(string);\n\n xcb_rectangle_t rectangles[] = {\n {40, 40, 20, 20},\n };\n\n c = xcb_connect (NULL, NULL);\n\n /* get the first screen */\n screen = xcb_setup_roots_iterator (xcb_get_setup (c)).data;\n\n /* root window */\n win = screen->root;\n\n /* create black (foreground) graphic context */\n foreground = xcb_generate_id (c);\n mask = XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES;\n values[0] = screen->black_pixel;\n values[1] = 0;\n xcb_create_gc (c, foreground, win, mask, values);\n\n /* create white (background) graphic context */\n background = xcb_generate_id (c);\n mask = XCB_GC_BACKGROUND | XCB_GC_GRAPHICS_EXPOSURES;\n values[0] = screen->white_pixel;\n values[1] = 0;\n xcb_create_gc (c, background, win, mask, values);\n\n /* create the window */\n win = xcb_generate_id(c);\n mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;\n values[0] = screen->white_pixel;\n values[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS;\n xcb_create_window (c, /* connection */\n XCB_COPY_FROM_PARENT, /* depth */\n win, /* window Id */\n screen->root, /* parent window */\n 0, 0, /* x, y */\n 150, 150, /* width, height */\n 10, /* border_width */\n XCB_WINDOW_CLASS_INPUT_OUTPUT, /* class */\n screen->root_visual, /* visual */\n mask, values); /* masks */\n\n /* map the window on the screen */\n xcb_map_window (c, win);\n\n xcb_flush (c);\n\n while ((e = xcb_wait_for_event (c))) {\n switch (e->response_type & ~0x80) {\n case XCB_EXPOSE:\n xcb_poly_rectangle (c, win, foreground, 1, rectangles);\n xcb_image_text_8 (c, string_len, win, background, 20, 20, string);\n xcb_flush (c);\n break;\n case XCB_KEY_PRESS:\n goto endloop;\n }\n free (e);\n }\n endloop:\n\n return 0;\n}\n", "language": "C" }, { "code": " identification division.\n program-id. x11-hello.\n installation. cobc -x x11-hello.cob -lX11\n remarks. Use of private data is likely not cross platform.\n\n data division.\n working-storage section.\n 01 msg.\n 05 filler value z\"S'up, Earth?\".\n 01 msg-len usage binary-long value 12.\n\n 01 x-display usage pointer.\n 01 x-window usage binary-c-long.\n\n *> GnuCOBOL does not evaluate C macros, need to peek at opaque\n *> data from Xlib.h\n *> some padding is added, due to this comment in the header\n *> \"there is more to this structure, but it is private to Xlib\"\n 01 x-display-private based.\n 05 x-ext-data usage pointer sync.\n 05 private1 usage pointer.\n 05 x-fd usage binary-long.\n 05 private2 usage binary-long.\n 05 proto-major-version usage binary-long.\n 05 proto-minor-version usage binary-long.\n 05 vendor usage pointer sync.\n 05 private3 usage pointer.\n 05 private4 usage pointer.\n 05 private5 usage pointer.\n 05 private6 usage binary-long.\n 05 allocator usage program-pointer sync.\n 05 byte-order usage binary-long.\n 05 bitmap-unit usage binary-long.\n 05 bitmap-pad usage binary-long.\n 05 bitmap-bit-order usage binary-long.\n 05 nformats usage binary-long.\n 05 screen-format usage pointer sync.\n 05 private8 usage binary-long.\n 05 x-release usage binary-long.\n 05 private9 usage pointer sync.\n 05 private10 usage pointer sync.\n 05 qlen usage binary-long.\n 05 last-request-read usage binary-c-long unsigned sync.\n 05 request usage binary-c-long unsigned sync.\n 05 private11 usage pointer sync.\n 05 private12 usage pointer.\n 05 private13 usage pointer.\n 05 private14 usage pointer.\n 05 max-request-size usage binary-long unsigned.\n 05 x-db usage pointer sync.\n 05 private15 usage program-pointer sync.\n 05 display-name usage pointer.\n 05 default-screen usage binary-long.\n 05 nscreens usage binary-long.\n 05 screens usage pointer sync.\n 05 motion-buffer usage binary-c-long unsigned.\n 05 private16 usage binary-c-long unsigned.\n 05 min-keycode usage binary-long.\n 05 max-keycode usage binary-long.\n 05 private17 usage pointer sync.\n 05 private18 usage pointer.\n 05 private19 usage binary-long.\n 05 x-defaults usage pointer sync.\n 05 filler pic x(256).\n\n 01 x-screen-private based.\n 05 scr-ext-data usage pointer sync.\n 05 display-back usage pointer.\n 05 root usage binary-c-long.\n 05 x-width usage binary-long.\n 05 x-height usage binary-long.\n 05 m-width usage binary-long.\n 05 m-height usage binary-long.\n 05 x-ndepths usage binary-long.\n 05 depths usage pointer sync.\n 05 root-depth usage binary-long.\n 05 root-visual usage pointer sync.\n 05 default-gc usage pointer.\n 05 cmap usage pointer.\n 05 white-pixel usage binary-c-long unsigned sync.\n 05 black-pixel usage binary-c-long unsigned.\n 05 max-maps usage binary-long.\n 05 min-maps usage binary-long.\n 05 backing-store usage binary-long.\n 05 save_unders usage binary-char.\n 05 root-input-mask usage binary-c-long sync.\n 05 filler pic x(256).\n\n 01 event.\n 05 e-type usage binary-long.\n 05 filler pic x(188).\n 05 filler pic x(256).\n 01 Expose constant as 12.\n 01 KeyPress constant as 2.\n\n *> ExposureMask or-ed with KeyPressMask, from X.h\n 01 event-mask usage binary-c-long value 32769.\n\n *> make the box around the message wide enough for the font\n 01 x-char-struct.\n 05 lbearing usage binary-short.\n 05 rbearing usage binary-short.\n 05 string-width usage binary-short.\n 05 ascent usage binary-short.\n 05 descent usage binary-short.\n 05 attributes usage binary-short unsigned.\n 01 font-direction usage binary-long.\n 01 font-ascent usage binary-long.\n 01 font-descent usage binary-long.\n\n 01 XGContext usage binary-c-long.\n 01 box-width usage binary-long.\n 01 box-height usage binary-long.\n\n *> ***************************************************************\n procedure division.\n\n call \"XOpenDisplay\" using by reference null returning x-display\n on exception\n display function module-id \" Error: \"\n \"no XOpenDisplay linkage, requires libX11\"\n upon syserr\n stop run returning 1\n end-call\n if x-display equal null then\n display function module-id \" Error: \"\n \"XOpenDisplay returned null\" upon syserr\n stop run returning 1\n end-if\n set address of x-display-private to x-display\n\n if screens equal null then\n display function module-id \" Error: \"\n \"XOpenDisplay associated screen null\" upon syserr\n stop run returning 1\n end-if\n set address of x-screen-private to screens\n\n call \"XCreateSimpleWindow\" using\n by value x-display root 10 10 200 50 1\n black-pixel white-pixel\n returning x-window\n call \"XStoreName\" using\n by value x-display x-window by reference msg\n\n call \"XSelectInput\" using by value x-display x-window event-mask\n\n call \"XMapWindow\" using by value x-display x-window\n\n call \"XGContextFromGC\" using by value default-gc\n returning XGContext\n call \"XQueryTextExtents\" using by value x-display XGContext\n by reference msg by value msg-len\n by reference font-direction font-ascent font-descent\n x-char-struct\n compute box-width = string-width + 8\n compute box-height = font-ascent + font-descent + 8\n\n perform forever\n call \"XNextEvent\" using by value x-display by reference event\n if e-type equal Expose then\n call \"XDrawRectangle\" using\n by value x-display x-window default-gc 5 5\n box-width box-height\n call \"XDrawString\" using\n by value x-display x-window default-gc 10 20\n by reference msg by value msg-len\n end-if\n if e-type equal KeyPress then exit perform end-if\n end-perform\n\n call \"XCloseDisplay\" using by value x-display\n\n goback.\n end program x11-hello.\n", "language": "COBOL" }, { "code": ";;; Single-file/interactive setup; large applications should define an ASDF system instead\n\n(let* ((display (open-default-display))\n (screen (display-default-screen display))\n (root-window (screen-root screen))\n (black-pixel (screen-black-pixel screen))\n (white-pixel (screen-white-pixel screen))\n (window (create-window :parent root-window\n :x 10 :y 10\n :width 100 :height 100\n :background white-pixel\n :event-mask '(:exposure :key-press)))\n (gc (create-gcontext :drawable window\n :foreground black-pixel\n :background white-pixel)))\n (map-window window)\n (unwind-protect\n (event-case (display :discard-p t)\n (exposure ()\n (draw-rectangle window gc 20 20 10 10 t)\n (draw-glyphs window gc 10 50 \"Hello, World!\")\n nil #| continue receiving events |#)\n (key-press ()\n t #| non-nil result signals event-case to exit |#))\n (when window\n (destroy-window window))\n (when gc\n (free-gcontext gc))\n (close-display display)))\n", "language": "Common-Lisp" }, { "code": "warnings off\nrequire xlib.fs\n\n0 value \tX11-D \\ Display\n0 value\t\tX11-S \\ Screen\n0 value \tX11-root\n0 value \tX11-GC\n0 value \tX11-W \\ Window\n0 value \tX11-Black\n0 value X11-White\n9 value \tX11-Top\n0 value \tX11-Left\ncreate \t\tX11-ev 96 allot\n\nvariable \twm_delete\n\n: X11-D-S \tX11-D X11-S ;\n: X11-D-G X11-D X11-GC ;\n: X11-D-W \tX11-D X11-W ;\n: X11-D-W-G X11-D-W X11-GC ;\n\n: open-X11 ( -- )\n\tX11-D 0= if 0 XOpendisplay to X11-D\n\t\t X11-D 0= abort\" can't connect to X server\"\n\t\t X11-D XDefaultscreen to X11-S\n\t\t X11-D-S XRootwindow to X11-root\n\t\t X11-D-S XDefaultGC to X11-GC\n\t\t X11-D-S XBlackPixel to X11-Black\n\t\t X11-D-S XWhitePixel to X11-White\n\t\tthen\n\tX11-W 0= if X11-D X11-root X11-top X11-left 400 220 0 0 $808080 XCreateSimplewindow to X11-W\n\t\t X11-W 0= abort\" failed to create X11-window\"\n\t\t X11-D-W $28043 XSelectInput drop\n\t\t X11-D s\" WM_DELETE_WEINDOW\" 1 XInternAtom wm_delete !\n\t X11-D-W wm_delete 1 XSetWMProtocols drop\n\t\t X11-D-W XMapwindow drop\n\t\t X11-D XFlush drop\n\t\tthen ;\n\n: close-graphics ( -- )\n\tX11-W if X11-D-W XDestroywindow drop 0 to X11-W\n\t then\n X11-D if X11-D XClosedisplay 0 to X11-D\n\t then ;\n\n: foreground \t>r X11-D-G r> XSetForeground drop ;\n: background \t>r X11-D-G r> XSetBackground drop ;\n: keysym \tX11-ev 0 XLookupKeysym ;\n\n: ev-loop\n begin X11-D X11-ev XNextEvent throw\n\t X11-White foreground\n\t X11-Black background\n\t X11-D-W-G 100 100 s\" Hello World\" XDrawString drop\n\t X11-D-W-G 100 120 150 25 XDrawRectangle drop\n\t X11-D-W-G 110 135 s\" Press ESC to exit ...\" XDrawString drop\n\t case X11-ev @ $ffffffff and\n\t 3 of keysym XK_Escape = if exit then endof\n\t endcase\n\tagain ;\n\\ #### Test #####\n0 open-X11\nev-loop\nclose-graphics\nbye\n", "language": "Forth" }, { "code": "#include once \"X11/Xlib.bi\"\n\nDim As Display Ptr dpy\nDim As Window win\nDim As GC gc\nDim As XEvent ev\n\ndpy = XOpenDisplay(NULL)\nwin = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy), 0, 0, 400, 300, 0, 0, 0)\ngc = XCreateGC(dpy, win, 0, NULL)\nXSelectInput(dpy, win, ExposureMask Or KeyPressMask)\nXMapWindow(dpy, win)\n\nWhile XNextEvent(dpy, @ev) = 0\n If ev.type = Expose Then\n XDrawString(dpy, win, gc, 200, 150, \"Hello World\", 11)\n EndIf\nWend\n\nXCloseDisplay(dpy)\n", "language": "FreeBASIC" }, { "code": "package main\n\n// Copyright (c) 2013 Alex Kesling\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport (\n \"log\"\n \"github.com/jezek/xgb\"\n \"github.com/jezek/xgb/xproto\"\n)\n\nfunc main() {\n // Open the connection to the X server\n X, err := xgb.NewConn()\n if err != nil {\n log.Fatal(err)\n }\n\n // geometric objects\n points := []xproto.Point{\n {10, 10},\n {10, 20},\n {20, 10},\n {20, 20}};\n\n polyline := []xproto.Point{\n {50, 10},\n { 5, 20}, // rest of points are relative\n {25,-20},\n {10, 10}};\n\n segments := []xproto.Segment{\n {100, 10, 140, 30},\n {110, 25, 130, 60}};\n\n rectangles := []xproto.Rectangle{\n { 10, 50, 40, 20},\n { 80, 50, 10, 40}};\n\n arcs := []xproto.Arc{\n {10, 100, 60, 40, 0, 90 << 6},\n {90, 100, 55, 40, 0, 270 << 6}};\n\n setup := xproto.Setup(X)\n // Get the first screen\n screen := setup.DefaultScreen(X)\n\n // Create black (foreground) graphic context\n foreground, _ := xproto.NewGcontextId(X)\n mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)\n values := []uint32{screen.BlackPixel, 0}\n xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)\n\n // Ask for our window's Id\n win, _ := xproto.NewWindowId(X)\n winDrawable := xproto.Drawable(win)\n\n // Create the window\n mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)\n values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}\n xproto.CreateWindow(X, // Connection\n screen.RootDepth, // Depth\n win, // Window Id\n screen.Root, // Parent Window\n 0, 0, // x, y\n 150, 150, // width, height\n 10, // border_width\n xproto.WindowClassInputOutput, // class\n screen.RootVisual, // visual\n mask, values) // masks\n\n // Map the window on the screen\n xproto.MapWindow(X, win)\n\n for {\n evt, err := X.WaitForEvent()\n switch evt.(type) {\n case xproto.ExposeEvent:\n /* We draw the points */\n xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)\n\n /* We draw the polygonal line */\n xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)\n\n /* We draw the segments */\n xproto.PolySegment(X, winDrawable, foreground, segments)\n\n /* We draw the rectangles */\n xproto.PolyRectangle(X, winDrawable, foreground, rectangles)\n\n /* We draw the arcs */\n xproto.PolyArc(X, winDrawable, foreground, arcs)\n\n default:\n /* Unknown event type, ignore it */\n }\n\n if err != nil {\n log.Fatal(err)\n }\n }\n return\n}\n", "language": "Go" }, { "code": "import javax.swing.*\nimport java.awt.*\nimport java.awt.event.WindowAdapter\nimport java.awt.event.WindowEvent\nimport java.awt.geom.Rectangle2D\n\nclass WindowCreation extends JApplet implements Runnable {\n void paint(Graphics g) {\n (g as Graphics2D).with {\n setStroke(new BasicStroke(2.0f))\n drawString(\"Hello Groovy!\", 20, 20)\n setPaint(Color.blue)\n draw(new Rectangle2D.Double(10d, 50d, 30d, 30d))\n }\n }\n\n void run() {\n new JFrame(\"Groovy Window Demo\").with {\n addWindowListener(new WindowAdapter() {\n void windowClosing(WindowEvent e) {\n System.exit(0)\n }\n })\n\n getContentPane().add(\"Center\", new WindowCreation())\n pack()\n setSize(new Dimension(150, 150))\n setVisible(true)\n }\n }\n}\n", "language": "Groovy" }, { "code": "Start,Programs,Applications,Editors,Leafpad,Textbox,\nType:[openbox]Hello World[pling][closebox]\n", "language": "GUISS" }, { "code": "import Graphics.X11.Xlib\nimport Control.Concurrent (threadDelay)\n\nmain = do\n display <- openDisplay \"\"\n let defScr = defaultScreen display\n rw <- rootWindow display defScr\n\n xwin <- createSimpleWindow display rw\n 0 0 400 200 1\n (blackPixel display defScr)\n (whitePixel display defScr)\n\n setTextProperty display xwin \"Rosetta Code: X11 simple window\" wM_NAME\n\n mapWindow display xwin\n\n sync display False\n threadDelay (5000000)\n\n destroyWindow display xwin\n closeDisplay display\n", "language": "Haskell" }, { "code": "procedure main()\n W1 := open(\"X-Window\",\"g\",\"size=250,250\",\"bg=black\",\"fg=red\") | stop(\"unable to open window\")\n FillRectangle(W1,50,50,150,150)\n WDone(W1)\nend\n\nlink graphics\n", "language": "Icon" }, { "code": "import javax.swing.JFrame;\nimport javax.swing.SwingUtilities;\n\npublic class WindowExample {\n\n public static void main(String[] args) {\n Runnable runnable = new Runnable() {\n public void run() {\n\tcreateAndShow();\n }\n };\n SwingUtilities.invokeLater(runnable);\n }\n\t\n static void createAndShow() {\n JFrame frame = new JFrame(\"Hello World\");\n frame.setSize(640,480);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n}\n", "language": "Java" }, { "code": "import java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\nimport javax.swing.*;\n\npublic class WindowExample extends JApplet {\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n\n g2.setStroke(new BasicStroke(2.0f));\n g2.drawString(\"Hello java\", 20, 20);\n g2.setPaint(Color.blue);\n g2.draw(new Rectangle2D.Double(40, 40, 20, 20));\n }\n\n public static void main(String s[]) {\n JFrame f = new JFrame(\"ShapesDemo2D\");\n f.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent e) {System.exit(0);}\n });\n JApplet applet = new ShapesDemo2D();\n f.getContentPane().add(\"Center\", applet);\n f.pack();\n f.setSize(new Dimension(150, 150));\n f.setVisible(true);\n }\n}\n", "language": "Java" }, { "code": "using Xlib\n\nfunction x11demo()\n # Open connection to the server.\n dpy = XOpenDisplay(C_NULL)\n dpy == C_NULL && error(\"unable to open display\")\n scr = DefaultScreen(dpy)\n\n # Create a window.\n win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr), 10, 10, 300, 100, 1,\n BlackPixel(dpy, scr), WhitePixel(dpy, scr))\n\n # Select the kind of events we are interested in.\n XSelectInput(dpy, win, ExposureMask | KeyPressMask)\n\n # Show or in x11 terms map window.\n XMapWindow(dpy, win)\n\n # Run event loop.\n evt = Ref(XEvent())\n while true\n XNextEvent(dpy, evt)\n\n # Draw or redraw the window.\n if EventType(evt) == Expose\n XFillRectangle(dpy, win, DefaultGC(dpy, scr), 24, 24, 16, 16)\n XDrawString(dpy, win, DefaultGC(dpy, scr), 50, 50, \"Hello, World! Press any key to exit.\")\n end\n\n # Exit whenever a key is pressed.\n if EventType(evt) == KeyPress\n break\n end\n end\n\n # Shutdown server connection\n XCloseDisplay(dpy)\nend\n\nx11demo()\n", "language": "Julia" }, { "code": "// Kotlin Native v0.3\n\nimport kotlinx.cinterop.*\nimport Xlib.*\n\nfun main(args: Array<String>) {\n val msg = \"Hello, World!\"\n val d = XOpenDisplay(null)\n if (d == null) {\n println(\"Cannot open display\")\n return\n }\n\n val s = XDefaultScreen(d)\n val w = XCreateSimpleWindow(d, XRootWindow(d, s), 10, 10, 160, 160, 1,\n XBlackPixel(d, s), XWhitePixel(d, s))\n XSelectInput(d, w, ExposureMask or KeyPressMask)\n XMapWindow(d, w)\n val e = nativeHeap.alloc<XEvent>()\n\n while (true) {\n XNextEvent(d, e.ptr)\n if (e.type == Expose) {\n XFillRectangle(d, w, XDefaultGC(d, s), 55, 40, 50, 50)\n XDrawString(d, w, XDefaultGC(d, s), 45, 120, msg, msg.length)\n }\n else if (e.type == KeyPress) break\n }\n\n XCloseDisplay(d)\n nativeHeap.free(e)\n}\n", "language": "Kotlin" }, { "code": "\\\\ M2000 froms (windows) based on a flat, empty with no title bar, vb6 window and a user control.\n\\\\ title bar is a user control in M2000 form\n\\\\ On linux, wine application run M2000 interpreter traslating vb6 calls to window system.\nModule SquareAndText2Window {\n\tConst black=0, white=15\n\tDeclare form1 form\n\t\\\\ defaultwindow title is the name of variable,here is: form1\n\tRem With form1, \"Title\", \"A title for this window\"\n\tMethod form1,\"move\", 2000,3000,10000,8000 ' in twips\n\tlayer form1 {\n\t\tCls white\n\t\tFont \"Verdana\"\n\t\tRem Window 12 , 10000,8000; ' hide modr 13 using a REM before\n\t\tRem\n\t\tMode 12 ' 12 in pt\n\t\tCls white, 2 ' fill white, set third raw for top of scrolling frame\n\t\tPen black\n\t\tMove 1000,2000 ' absolute coordinated in twips - use Step for relative coordinates\n\t\t\\\\ polygon use relative coordinates in twips\n\t\tpolygon white, 1000,0,0,-1000,-1000,0,0,-1000\n\t\t\\\\ write text using graphic coordinates\n\t\tMove 1000, 3000 : Legend \"Hello World\", \"Arial\", 12\n\t\t\\\\ write text using layer as console (font Verdana)\n\t\tPrint @(15,5),\"Goodbye Wolrd\"\n\t\t\\\\ 9120 7920 if we use window 12,10000, 8000 (cut exactly for console use)\n\t\t\\\\ 10000 8000 if we use Mode 12\n\t\t\\\\ scale.y include window height (including header)\n\t\t\\\\ the layer extend bellow\n\t\tPrint scale.x, scale.y\n\t}\n\t\\\\ show form1 modal (continue to next line when we close the window)\n\tMethod form1,\"Show\", 1\n\t\\\\ closing meand hide in M2000\n\twait 1000 ' in msec\n\tMethod form1,\"move\", random(2000, 10000),random(3000, 8000)\n\t\\\\ now show again\n\tMethod form1,\"Show\", 1\n\t\\\\ now we close the form, releasing resources\n\tDeclare form1 Nothing\n}\nSquareAndText2Window\n", "language": "M2000-Interpreter" }, { "code": "Needs[\"GUIKit`\"]\n ref = GUIRun[Widget[\"Panel\", {\n Widget[\n \"ImageLabel\", {\"data\" ->\n Script[ExportString[Graphics[Rectangle[{0, 0}, {1, 1}]],\n \"GIF\"]]}],\n Widget[\"Label\", { \"text\" -> \"Hello World!\"}]}\n ]]\n", "language": "Mathematica" }, { "code": "import x11/[xlib,xutil,x]\n\nconst\n windowWidth = 1000\n windowHeight = 600\n borderWidth = 5\n eventMask = ButtonPressMask or KeyPressMask or ExposureMask\n\nvar\n display: PDisplay\n window: Window\n deleteMessage: Atom\n graphicsContext: GC\n\nproc init() =\n display = XOpenDisplay(nil)\n if display == nil:\n quit \"Failed to open display\"\n\n let\n screen = XDefaultScreen(display)\n rootWindow = XRootWindow(display, screen)\n foregroundColor = XBlackPixel(display, screen)\n backgroundColor = XWhitePixel(display, screen)\n\n window = XCreateSimpleWindow(display, rootWindow, -1, -1, windowWidth,\n windowHeight, borderWidth, foregroundColor, backgroundColor)\n\n discard XSetStandardProperties(display, window, \"X11 Example\", \"window\", 0,\n nil, 0, nil)\n\n discard XSelectInput(display, window, eventMask)\n discard XMapWindow(display, window)\n\n deleteMessage = XInternAtom(display, \"WM_DELETE_WINDOW\", false.XBool)\n discard XSetWMProtocols(display, window, deleteMessage.addr, 1)\n\n graphicsContext = XDefaultGC(display, screen)\n\n\nproc drawWindow() =\n const text = \"Hello, Nim programmers.\"\n discard XDrawString(display, window, graphicsContext, 10, 50, text, text.len)\n discard XFillRectangle(display, window, graphicsContext, 20, 20, 10, 10)\n\n\nproc mainLoop() =\n ## Process events until the quit event is received\n var event: XEvent\n while true:\n discard XNextEvent(display, event.addr)\n case event.theType\n of Expose:\n drawWindow()\n of ClientMessage:\n if cast[Atom](event.xclient.data.l[0]) == deleteMessage:\n break\n of KeyPress:\n let key = XLookupKeysym(cast[PXKeyEvent](event.addr), 0)\n if key != 0:\n echo \"Key \", key, \" pressed\"\n of ButtonPressMask:\n echo \"Mouse button \", event.xbutton.button, \" pressed at \",\n event.xbutton.x, \",\", event.xbutton.y\n else:\n discard\n\n\nproc main() =\n init()\n mainLoop()\n discard XDestroyWindow(display, window)\n discard XCloseDisplay(display)\n\n\nmain()\n", "language": "Nim" }, { "code": "open Xlib\n\nlet () =\n let d = xOpenDisplay \"\" in\n let s = xDefaultScreen d in\n let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 100 100 1\n (xBlackPixel d s) (xWhitePixel d s) in\n xSelectInput d w [ExposureMask; KeyPressMask];\n xMapWindow d w;\n\n let msg = \"Hello, World!\" in\n\n let rec main_loop() =\n match xEventType(xNextEventFun d) with\n | Expose ->\n xFillRectangle d w (xDefaultGC d s) 20 20 10 10;\n xDrawString d w (xDefaultGC d s) 10 50 msg;\n main_loop()\n | KeyPress -> () (* exit main loop *)\n | _ -> main_loop()\n in\n main_loop();\n xCloseDisplay d;\n;;\n", "language": "OCaml" }, { "code": "program xshowwindow;\n{$mode objfpc}{$H+}\n\nuses\n xlib, x, ctypes;\n\nprocedure ModalShowX11Window(AMsg: string);\nvar\n d: PDisplay;\n w: TWindow;\n e: TXEvent;\n msg: PChar;\n s: cint;\nbegin\n msg := PChar(AMsg);\n\n { open connection with the server }\n d := XOpenDisplay(nil);\n if (d = nil) then\n begin\n WriteLn('[ModalShowX11Window] Cannot open display');\n exit;\n end;\n s := DefaultScreen(d);\n\n { create window }\n w := XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 50, 1,\n BlackPixel(d, s), WhitePixel(d, s));\n\n { select kind of events we are interested in }\n XSelectInput(d, w, ExposureMask or KeyPressMask);\n\n { map (show) the window }\n XMapWindow(d, w);\n\n { event loop }\n while (True) do\n begin\n XNextEvent(d, @e);\n { draw or redraw the window }\n if (e._type = Expose) then\n begin\n XFillRectangle(d, w, DefaultGC(d, s), 0, 10, 100, 3);\n XFillRectangle(d, w, DefaultGC(d, s), 0, 30, 100, 3);\n XDrawString (d, w, DefaultGC(d, s), 5, 25, msg, strlen(msg));\n end;\n { exit on key press }\n if (e._type = KeyPress) then Break;\n end;\n\n { close connection to server }\n XCloseDisplay(d);\nend;\n\nbegin\n ModalShowX11Window('Hello, World!');\nend.\n", "language": "Pascal" }, { "code": "#!/usr/bin/perl -w\nuse strict;\nuse X11::Protocol;\n\nmy $X = X11::Protocol->new;\n\nmy $window = $X->new_rsrc;\n$X->CreateWindow ($window,\n $X->root, # parent window\n 'InputOutput', # class\n 0, # depth, copy from parent\n 0, # visual, copy from parent\n 0,0, # X,Y (window manager will override)\n 300,100, # width,height\n 0, # border width\n background_pixel => $X->black_pixel,\n event_mask => $X->pack_event_mask('Exposure',\n 'ButtonPress'),\n );\n\nmy $gc = $X->new_rsrc;\n$X->CreateGC ($gc, $window,\n foreground => $X->white_pixel);\n\n$X->{'event_handler'} = sub {\n my %event = @_;\n my $event_name = $event{'name'};\n\n if ($event_name eq 'Expose') {\n $X->PolyRectangle ($window, $gc, [ 10,10, # x,y top-left corner\n 30,20 ]); # width,height\n $X->PolyText8 ($window, $gc,\n 10, 55, # X,Y of text baseline\n [ 0, # delta X\n 'Hello ... click mouse button to exit.' ]);\n\n } elsif ($event_name eq 'ButtonPress') {\n exit 0;\n }\n};\n\n$X->MapWindow ($window);\nfor (;;) {\n $X->handle_input;\n}\n", "language": "Perl" }, { "code": "#!/usr/bin/picolisp /usr/lib/picolisp/lib.l\n\n(load \"@lib/misc.l\" \"@lib/gcc.l\")\n\n(gcc \"x11\" '(\"-lX11\") 'simpleWin)\n\n#include <X11/Xlib.h>\n\nany simpleWin(any ex) {\n any x = cdr(ex);\n int dx, dy;\n Display *disp;\n int scrn;\n Window win;\n XEvent ev;\n\n x = cdr(ex), dx = (int)evCnt(ex,x);\n x = cdr(x), dy = (int)evCnt(ex,x);\n x = evSym(cdr(x));\n if (disp = XOpenDisplay(NULL)) {\n char msg[bufSize(x)];\n\n bufString(x, msg);\n scrn = DefaultScreen(disp);\n win = XCreateSimpleWindow(disp, RootWindow(disp,scrn), 0, 0, dx, dy,\n 1, BlackPixel(disp,scrn), WhitePixel(disp,scrn) );\n XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask);\n XMapWindow(disp, win);\n for (;;) {\n XNextEvent(disp, &ev);\n switch (ev.type) {\n case Expose:\n XDrawRectangle(disp, win, DefaultGC(disp, scrn), 10, 10, dx-20, dy-20);\n XDrawString(disp, win, DefaultGC(disp, scrn), 30, 40, msg, strlen(msg));\n break;\n case KeyPress:\n case ButtonPress:\n XCloseDisplay(disp);\n return Nil;\n }\n }\n }\n return mkStr(\"Can't open Display\");\n}\n/**/\n\n(simpleWin 300 200 \"Hello World\")\n(bye)\n", "language": "PicoLisp" }, { "code": "from Xlib import X, display\n\nclass Window:\n def __init__(self, display, msg):\n self.display = display\n self.msg = msg\n\n self.screen = self.display.screen()\n self.window = self.screen.root.create_window(\n 10, 10, 100, 100, 1,\n self.screen.root_depth,\n background_pixel=self.screen.white_pixel,\n event_mask=X.ExposureMask | X.KeyPressMask,\n )\n self.gc = self.window.create_gc(\n foreground = self.screen.black_pixel,\n background = self.screen.white_pixel,\n )\n\n self.window.map()\n\n def loop(self):\n while True:\n e = self.display.next_event()\n\n if e.type == X.Expose:\n self.window.fill_rectangle(self.gc, 20, 20, 10, 10)\n self.window.draw_text(self.gc, 10, 50, self.msg)\n elif e.type == X.KeyPress:\n raise SystemExit\n\n\nif __name__ == \"__main__\":\n Window(display.Display(), \"Hello, World!\").loop()\n", "language": "Python" }, { "code": "import xcb\nfrom xcb.xproto import *\nimport xcb.render\n\ndef main():\n conn = xcb.connect()\n conn.render = conn(xcb.render.key)\n\n setup = conn.get_setup()\n root = setup.roots[0].root\n depth = setup.roots[0].root_depth\n visual = setup.roots[0].root_visual\n white = setup.roots[0].white_pixel\n\n window = conn.generate_id()\n conn.core.CreateWindow(depth, window, root,\n 0, 0, 640, 480, 0,\n WindowClass.InputOutput,\n visual,\n CW.BackPixel | CW.EventMask,\n [ white, EventMask.Exposure |\n EventMask.KeyPress ])\n\n conn.core.MapWindow(window)\n conn.flush()\n\n while True:\n event = conn.wait_for_event()\n\n if isinstance(event, ExposeEvent):\n color = (0, 0, 65535, 65535)\n rectangle = (20, 20, 40, 40)\n # TODO, fixme:\n # I haven't been able to find what I should put for the parameter \"op\"\n # conn.render.FillRectangles(op, window, color, 1, rectangle)\n conn.flush()\n\n elif isinstance(event, KeyPressEvent):\n break\n\n conn.disconnect()\n\nmain()\n", "language": "Python" }, { "code": "#lang racket/gui\n\n(define frame (new frame%\n [label \"Example\"]\n [width 300]\n [height 300]))\n(new canvas% [parent frame]\n [paint-callback\n (lambda (canvas dc)\n (send dc set-scale 3 3)\n (send dc set-text-foreground \"blue\")\n (send dc draw-text \"Don't Panic!\" 0 0))])\n(send frame show #t)\n", "language": "Racket" }, { "code": "use NativeCall;\n\nclass Display is repr('CStruct') {\n has int32 $!screen;\n has int32 $!window;\n }\nclass GC is repr('CStruct') {\n has int32 $!context;\n}\nclass XEvent is repr('CStruct') {\n has int32 $.type;\n method init { $!type = 0 }\n}\n\nsub XOpenDisplay(Str $name = ':0') returns Display is native('X11') { * }\nsub XDefaultScreen(Display $) returns int32 is native('X11') { * }\nsub XRootWindow(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XBlackPixel(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XWhitePixel(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XCreateSimpleWindow(\n Display $, int32 $parent_window, int32 $x, int32 $y,\n int32 $width, int32 $height, int32 $border_width,\n int32 $border, int32 $background\n) returns int32 is native('X11') { * }\nsub XMapWindow(Display $, int32 $window) is native('X11') { * }\nsub XSelectInput(Display $, int32 $window, int32 $mask) is native('X11') { * }\nsub XFillRectangle(\n Display $, int32 $window, GC $, int32 $x, int32 $y, int32 $width, int32 $height\n) is native('X11') { * }\nsub XDrawString(\n Display $, int32 $window, GC $, int32 $x, int32 $y, Str $, int32 $str_length\n) is native('X11') { * }\nsub XDefaultGC(Display $, int32 $screen) returns GC is native('X11') { * }\nsub XNextEvent(Display $, XEvent $e) is native('X11') { * }\nsub XCloseDisplay(Display $) is native('X11') { * }\n\nmy Display $display = XOpenDisplay()\n or die \"Can not open display\";\n\nmy int $screen = XDefaultScreen($display);\nmy int $window = XCreateSimpleWindow(\n $display,\n XRootWindow($display, $screen),\n 10, 10, 100, 100, 1,\n XBlackPixel($display, $screen), XWhitePixel($display, $screen)\n);\nXSelectInput($display, $window, 1 +< 15 +| 1);\nXMapWindow($display, $window);\n\nmy Str $msg = 'Hello, World!';\nmy XEvent $e .= new; $e.init;\nloop {\n XNextEvent($display, $e);\n if $e.type == 12 {\n\t XFillRectangle($display, $window, XDefaultGC($display, $screen), 20, 20, 10, 10);\n\t XDrawString($display, $window, XDefaultGC($display, $screen), 10, 50, $msg, my int $ = $msg.chars);\n }\n elsif $e.type == 2 {\n\t last;\n }\n}\nXCloseDisplay($display);\n", "language": "Raku" }, { "code": "import scala.swing.{ MainFrame, SimpleSwingApplication }\nimport scala.swing.Swing.pair2Dimension\n\nobject WindowExample extends SimpleSwingApplication {\n def top = new MainFrame {\n title = \"Hello!\"\n centerOnScreen\n preferredSize = ((200, 150))\n }\n}\n", "language": "Scala" }, { "code": "open XWindows ;\nval dp = XOpenDisplay \"\" ;\nval w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ;\nXMapWindow w;\nXFlush dp ;\nXDrawString w (DefaultGC dp) (XPoint {x=10,y=50}) \"Hello World!\" ;\nXFlush dp ;\n", "language": "Standard-ML" }, { "code": "package provide xlib 1\npackage require critcl\n\ncritcl::clibraries -L/usr/X11/lib -lX11\ncritcl::ccode {\n #include <X11/Xlib.h>\n static Display *d;\n static GC gc;\n}\n\n# Display connection functions\ncritcl::cproc XOpenDisplay {Tcl_Interp* interp char* name} ok {\n d = XOpenDisplay(name[0] ? name : NULL);\n if (d == NULL) {\n\tTcl_AppendResult(interp, \"cannot open display\", NULL);\n\treturn TCL_ERROR;\n }\n gc = DefaultGC(d, DefaultScreen(d));\n return TCL_OK;\n}\ncritcl::cproc XCloseDisplay {} void {\n XCloseDisplay(d);\n}\n\n# Basic window functions\ncritcl::cproc XCreateSimpleWindow {\n int x int y int width int height int events\n} int {\n int s = DefaultScreen(d);\n Window w = XCreateSimpleWindow(d, RootWindow(d,s), x, y, width, height, 0,\n\t BlackPixel(d,s), WhitePixel(d,s));\n XSelectInput(d, w, ExposureMask | events);\n return (int) w;\n}\ncritcl::cproc XDestroyWindow {int w} void {\n XDestroyWindow(d, (Window) w);\n}\ncritcl::cproc XMapWindow {int w} void {\n XMapWindow(d, (Window) w);\n}\ncritcl::cproc XUnmapWindow {int w} void {\n XUnmapWindow(d, (Window) w);\n}\n\n# Event receiver\ncritcl::cproc XNextEvent {Tcl_Interp* interp} char* {\n XEvent e;\n XNextEvent(d, &e);\n switch (e.type) {\n\tcase Expose:\treturn \"type expose\";\n\tcase KeyPress:\treturn \"type key\";\n\t/* etc. This is a cheap hack version. */\n\tdefault:\treturn \"type ?\";\n }\n}\n\n# Painting functions\ncritcl::cproc XFillRectangle {int w int x int y int width int height} void {\n XFillRectangle(d, (Window)w, gc, x, y, width, height);\n}\ncritcl::cproc XDrawString {int w int x int y Tcl_Obj* msg} void {\n int len;\n const char *str = Tcl_GetStringFromObj(msg, &len);\n XDrawString(d, (Window)w, gc, x, y, str, len);\n}\n", "language": "Tcl" }, { "code": "package require xlib\n\nXOpenDisplay {}\nset w [XCreateSimpleWindow 10 10 100 100 1]\nXMapWindow $w\nwhile {[lindex [XNextEvent] 0] == \"expose\"} {\n XFillRectangle $w 20 20 10 10\n XDrawString $w 10 50 \"Hello, World!\"\n}\nXDestroyWindow $w\nXCloseDisplay\n", "language": "Tcl" }, { "code": "package require TclOO\npackage provide x11 1\n\nnamespace eval ::x {\n namespace export {[a-z]*}\n namespace ensemble create\n variable mask\n array set mask {\n\tKeyPress\t1\n\tKeyRelease\t2\n\tButtonPress\t4\n\tButtonRelease\t8\n }\n\n proc display {script} {\n\tXOpenDisplay {}\n\tcatch {uplevel 1 $script} msg opts\n\tXCloseDisplay\n\treturn -options $opts $msg\n }\n proc eventloop {var handlers} {\n\tupvar 1 $var v\n\twhile 1 {\n\t set v [XNextEvent]\n\t uplevel 1 [list switch [dict get $v type] $handlers]\n\t}\n }\n\n oo::class create window {\n\tvariable w\n constructor {x y width height events} {\n\t set m 0\n\t variable ::x::mask\n\t foreach e $events {catch {incr m $mask($e)}}\n\t set w [XCreateSimpleWindow $x $y $width $height $m]\n\t}\n\tmethod map {} {\n\t XMapWindow $w\n\t}\n\tmethod unmap {} {\n\t XUnmapWindow $w\n\t}\n\tmethod fill {x y width height} {\n\t XFillRectangle $w $x $y $width $height\n\t}\n\tmethod text {x y string} {\n\t XDrawString $w $x $y $string\n\t}\n\tdestructor {\n\t XDestroyWindow $w\n\t}\n }\n}\n", "language": "Tcl" }, { "code": "package require x11\n\n# With a display connection open, create and map a window\nx display {\n set w [x window new 10 10 100 100 KeyPress]\n $w map\n\n x eventloop ev {\n\texpose {\n\t # Paint the window\n\t $w fill 20 20 10 10\n\t $w text 10 50 \"Hello, World!\"\n\t}\n\tkey {\n\t # Quit the event loop\n\t break\n\t}\n }\n\n $w destroy\n}\n", "language": "Tcl" }, { "code": "/* Window_creation_X11.wren */\n\nvar KeyPressMask = 1 << 0\nvar ExposureMask = 1 << 15\nvar KeyPress = 2\nvar Expose = 12\n\nforeign class XGC {\n construct default(display, screenNumber) {}\n}\n\nforeign class XEvent {\n construct new() {}\n\n foreign eventType\n}\n\nforeign class XDisplay {\n construct openDisplay(displayName) {}\n\n foreign defaultScreen()\n\n foreign rootWindow(screenNumber)\n\n foreign blackPixel(screenNumber)\n\n foreign whitePixel(screenNumber)\n\n foreign selectInput(w, eventMask)\n\n foreign mapWindow(w)\n\n foreign closeDisplay()\n\n foreign nextEvent(eventReturn)\n\n foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)\n\n foreign fillRectangle(d, gc, x, y, width, height)\n\n foreign drawString(d, gc, x, y, string, length)\n}\n\nvar xd = XDisplay.openDisplay(\"\")\nif (xd == 0) {\n System.print(\"Cannot open display.\")\n return\n}\nvar s = xd.defaultScreen()\nvar w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 100, 100, 1, xd.blackPixel(s), xd.whitePixel(s))\nxd.selectInput(w, ExposureMask | KeyPressMask)\nxd.mapWindow(w)\nvar msg = \"Hello, World!\"\nvar e = XEvent.new()\nwhile (true) {\n xd.nextEvent(e)\n var gc = XGC.default(xd, s)\n if (e.eventType == Expose) {\n xd.fillRectangle(w, gc, 20, 20, 10, 10)\n xd.drawString(w, gc, 10, 50, msg, msg.count)\n }\n if (e.eventType == KeyPress) break\n}\nxd.closeDisplay()\n", "language": "Wren" }, { "code": "/* gcc Window_creation_X11.c -o Window_creation_X11 -lX11 -lwren -lm */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <X11/Xlib.h>\n#include \"wren.h\"\n\n/* C <=> Wren interface functions */\n\nvoid C_displayAllocate(WrenVM* vm) {\n Display** pdisplay = (Display**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(Display*));\n const char *displayName = wrenGetSlotString(vm, 1);\n if (displayName == \"\") {\n *pdisplay = XOpenDisplay(NULL);\n } else {\n *pdisplay = XOpenDisplay(displayName);\n }\n}\n\nvoid C_gcAllocate(WrenVM* vm) {\n GC *pgc = (GC *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(GC));\n Display* display = *(Display**)wrenGetSlotForeign(vm, 1);\n int s = (int)wrenGetSlotDouble(vm, 2);\n *pgc = DefaultGC(display, s);\n}\n\nvoid C_eventAllocate(WrenVM* vm) {\n wrenSetSlotNewForeign(vm, 0, 0, sizeof(XEvent));\n}\n\nvoid C_eventType(WrenVM* vm) {\n XEvent e = *(XEvent *)wrenGetSlotForeign(vm, 0);\n wrenSetSlotDouble(vm, 0, (double)e.type);\n}\n\nvoid C_defaultScreen(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n int screenNumber = DefaultScreen(display);\n wrenSetSlotDouble(vm, 0, (double)screenNumber);\n}\n\nvoid C_rootWindow(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n int screenNumber = (int)wrenGetSlotDouble(vm, 1);\n Window w = RootWindow(display, screenNumber);\n wrenSetSlotDouble(vm, 0, (double)w);\n}\n\nvoid C_blackPixel(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n int screenNumber = (int)wrenGetSlotDouble(vm, 1);\n unsigned long p = BlackPixel(display, screenNumber);\n wrenSetSlotDouble(vm, 0, (double)p);\n}\n\nvoid C_whitePixel(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n int screenNumber = (int)wrenGetSlotDouble(vm, 1);\n unsigned long p = WhitePixel(display, screenNumber);\n wrenSetSlotDouble(vm, 0, (double)p);\n}\n\nvoid C_selectInput(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n Window w = (Window)wrenGetSlotDouble(vm, 1);\n long eventMask = (long)wrenGetSlotDouble(vm, 2);\n XSelectInput(display, w, eventMask);\n}\n\nvoid C_mapWindow(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n Window w = (Window)wrenGetSlotDouble(vm, 1);\n XMapWindow(display, w);\n}\n\nvoid C_closeDisplay(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n XCloseDisplay(display);\n}\n\nvoid C_nextEvent(WrenVM* vm) {\n Display* display = *(Display**)wrenGetSlotForeign(vm, 0);\n XEvent* pe = (XEvent*)wrenGetSlotForeign(vm, 1);\n XNextEvent(display, pe);\n}\n\nvoid C_createSimpleWindow(WrenVM* vm) {\n Display *display = *(Display**)wrenGetSlotForeign(vm, 0);\n Window parent = (Window)wrenGetSlotDouble(vm, 1);\n int x = (int)wrenGetSlotDouble(vm, 2);\n int y = (int)wrenGetSlotDouble(vm, 3);\n unsigned int width = (unsigned int)wrenGetSlotDouble(vm, 4);\n unsigned int height = (unsigned int)wrenGetSlotDouble(vm, 5);\n unsigned int borderWidth = (unsigned int)wrenGetSlotDouble(vm, 6);\n unsigned long border = (unsigned long)wrenGetSlotDouble(vm, 7);\n unsigned long background = (unsigned long)wrenGetSlotDouble(vm, 8);\n Window w = XCreateSimpleWindow(display, parent, x, y, width, height, borderWidth, border, background);\n wrenSetSlotDouble(vm, 0, (double)w);\n}\n\nvoid C_fillRectangle(WrenVM* vm) {\n Display *display = *(Display**)wrenGetSlotForeign(vm, 0);\n Drawable d = (Drawable)wrenGetSlotDouble(vm, 1);\n GC gc = *(GC *)wrenGetSlotForeign(vm, 2);\n int x = (int)wrenGetSlotDouble(vm, 3);\n int y = (int)wrenGetSlotDouble(vm, 4);\n unsigned int width = (unsigned int)wrenGetSlotDouble(vm, 5);\n unsigned int height = (unsigned int)wrenGetSlotDouble(vm, 6);\n XFillRectangle(display, d, gc, x, y, width, height);\n}\n\nvoid C_drawString(WrenVM* vm) {\n Display *display = *(Display**)wrenGetSlotForeign(vm, 0);\n Drawable d = (Drawable)wrenGetSlotDouble(vm, 1);\n GC gc = *(GC *)wrenGetSlotForeign(vm, 2);\n int x = (int)wrenGetSlotDouble(vm, 3);\n int y = (int)wrenGetSlotDouble(vm, 4);\n const char *string = wrenGetSlotString(vm, 5);\n int length = (int)wrenGetSlotDouble(vm, 6);\n XDrawString(display, d, gc, x, y, string, length);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n WrenForeignClassMethods methods;\n methods.finalize = NULL;\n if (strcmp(className, \"XDisplay\") == 0) {\n methods.allocate = C_displayAllocate;\n } else if (strcmp(className, \"XGC\") == 0) {\n methods.allocate = C_gcAllocate;\n } else if (strcmp(className, \"XEvent\") == 0) {\n methods.allocate = C_eventAllocate;\n } else {\n methods.allocate = NULL;\n }\n return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"XEvent\") == 0) {\n if (!isStatic && strcmp(signature, \"eventType\") == 0) return C_eventType;\n } else if (strcmp(className, \"XDisplay\") == 0) {\n if (!isStatic && strcmp(signature, \"defaultScreen()\") == 0) return C_defaultScreen;\n if (!isStatic && strcmp(signature, \"rootWindow(_)\") == 0) return C_rootWindow;\n if (!isStatic && strcmp(signature, \"blackPixel(_)\") == 0) return C_blackPixel;\n if (!isStatic && strcmp(signature, \"whitePixel(_)\") == 0) return C_whitePixel;\n if (!isStatic && strcmp(signature, \"selectInput(_,_)\") == 0) return C_selectInput;\n if (!isStatic && strcmp(signature, \"mapWindow(_)\") == 0) return C_mapWindow;\n if (!isStatic && strcmp(signature, \"closeDisplay()\") == 0) return C_closeDisplay;\n if (!isStatic && strcmp(signature, \"nextEvent(_)\") == 0) return C_nextEvent;\n if (!isStatic && strcmp(signature, \"createSimpleWindow(_,_,_,_,_,_,_,_)\") == 0) return C_createSimpleWindow;\n if (!isStatic && strcmp(signature, \"fillRectangle(_,_,_,_,_,_)\") == 0) return C_fillRectangle;\n if (!isStatic && strcmp(signature, \"drawString(_,_,_,_,_,_)\") == 0) return C_drawString;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignClassFn = &bindForeignClass;\n config.bindForeignMethodFn = &bindForeignMethod;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Window_creation_X11.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" }, { "code": "open window 300,200\n\ntext 150, 100, \"Hello World\"\n\nrectangle 10,10 to 90,90\nfill rectangle 40,40,60,60\n\nclear screen\n\ninkey$\nclose window\n", "language": "Yabasic" } ]
Window-creation-X11
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Window_management\nnote: GUI\n", "language": "00-META" }, { "code": "Treat windows or at least window identities as [[wp:First-class_object|first class objects]].\n\n* Store window identities in variables, compare them for equality.\n* Provide examples of performing some of the following:\n** hide, \n** show, \n** close, \n** minimize, \n** maximize, \n** move, &nbsp; &nbsp; and \n** resize a window. \n\n\nThe window of interest may or may not have been created by your program.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F1:: ;; when user hits the F1 key, do the following\nWinGetTitle, window, A ; get identity of active window into a variable\nWinMove, %window%, , 100, 100, 800, 800 ; move window to coordinates, 100, 100\n ; and change size to 800 x 800 pixels\nsleep, 2000\nWinHide, % window ; hide window\nTrayTip, hidden, window is hidden, 2\nsleep, 2000\nWinShow, % window ; show window again\nloop,\n{\n inputbox, name, what was the name of your window?\n if (name = window) ; compare window variables for equality\n {\n msgbox you got it\n break\n }\n; else try again\n}\nWinClose, % window\nreturn\n", "language": "AutoHotkey" }, { "code": " SWP_NOMOVE = 2\n SWP_NOZORDER = 4\n SW_MAXIMIZE = 3\n SW_MINIMIZE = 6\n SW_RESTORE = 9\n SW_HIDE = 0\n SW_SHOW = 5\n\n REM Store window handle in a variable:\n myWindowHandle% = @hwnd%\n\n PRINT \"Hiding the window in two seconds...\"\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_HIDE\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_SHOW\n PRINT \"Windows shown again.\"\n\n PRINT \"Minimizing the window in two seconds...\"\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_MINIMIZE\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_RESTORE\n PRINT \"Maximizing the window in two seconds...\"\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_MAXIMIZE\n WAIT 200\n SYS \"ShowWindow\", myWindowHandle%, SW_RESTORE\n PRINT \"Now restored to its normal size.\"\n\n PRINT \"Resizing the window in two seconds...\"\n WAIT 200\n SYS \"SetWindowPos\", myWindowHandle%, 0, 0, 0, 400, 200, \\\n \\ SWP_NOMOVE OR SWP_NOZORDER\n\n PRINT \"Closing the window in two seconds...\"\n WAIT 200\n QUIT\n", "language": "BBC-BASIC" }, { "code": "#include<windows.h>\n#include<unistd.h>\n#include<stdio.h>\n\nconst char g_szClassName[] = \"weirdWindow\";\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n switch(msg)\n {\n case WM_CLOSE:\n DestroyWindow(hwnd);\n break;\n case WM_DESTROY:\n PostQuitMessage(0);\n break;\n default:\n return DefWindowProc(hwnd, msg, wParam, lParam);\n }\n return 0;\n}\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n LPSTR lpCmdLine, int nCmdShow)\n{\n WNDCLASSEX wc;\n HWND hwnd[3];\n MSG Msg;\n\tint i,x=0,y=0;\n\tchar str[3][100];\n\tint maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);\n\t\n\tchar messages[15][180] = {\"Welcome to the Rosettacode Window C implementation.\",\n\t\"If you can see two blank windows just behind this message box, you are in luck.\",\n\t\"Let's get started....\",\n\t\"Yes, you will be seeing a lot of me :)\",\n\t\"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)\",\n\t\"Let's compare the windows for equality.\",\n\t\"Now let's hide Window 1.\",\n\t\"Now let's see Window 1 again.\",\n\t\"Let's close Window 2, bye, bye, Number 2 !\",\n\t\"Let's minimize Window 1.\",\n\t\"Now let's maximize Window 1.\",\n\t\"And finally we come to the fun part, watch Window 1 move !\",\n\t\"Let's double Window 1 in size for all the good work.\",\n\t\"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )\"};\n\n wc.cbSize = sizeof(WNDCLASSEX);\n wc.style = 0;\n wc.lpfnWndProc = WndProc;\n wc.cbClsExtra = 0;\n wc.cbWndExtra = 0;\n wc.hInstance = hInstance;\n wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);\n wc.lpszMenuName = NULL;\n wc.lpszClassName = g_szClassName;\n wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\n if(!RegisterClassEx(&wc))\n {\n MessageBox(NULL, \"Window Registration Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n return 0;\n }\n\n\tfor(i=0;i<2;i++){\n\t\t\n\t\tsprintf(str[i],\"Window Number %d\",i+1);\n\t\t\n\t\thwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);\n\t\t\n\t\tif(hwnd[i] == NULL)\n\t\t{\n\t\t\tMessageBox(NULL, \"Window Creation Failed!\", \"Error!\",MB_ICONEXCLAMATION | MB_OK);\n\t\t\treturn 0;\n\t\t}\n\n\t\tShowWindow(hwnd[i], nCmdShow);\n\t\tUpdateWindow(hwnd[i]);\n\t}\n\t\n\tfor(i=0;i<6;i++){\n\t\t\tMessageBox(NULL, messages[i], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\t\t\n\t}\n\t\n\tif(hwnd[0]==hwnd[1])\n\t\t\tMessageBox(NULL, \"Window 1 and 2 are equal.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\telse\n\t\t\tMessageBox(NULL, \"Nope, they are not.\", \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\t\n\tMessageBox(NULL, messages[6], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[7], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_SHOW);\n\t\n\tMessageBox(NULL, messages[8], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[1], SW_HIDE);\n\t\n\tMessageBox(NULL, messages[9], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MINIMIZE);\n\t\n\tMessageBox(NULL, messages[10], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_MAXIMIZE);\n\t\n\tMessageBox(NULL, messages[11], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tShowWindow(hwnd[0], SW_RESTORE);\n\t\n\twhile(x!=maxX/2||y!=maxY/2){\n\t\tif(x<maxX/2)\n\t\t\tx++;\n\t\tif(y<maxY/2)\n\t\t\ty++;\n\t\t\n\t\tMoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);\n\t\tsleep(10);\n\t}\n\t\n\tMessageBox(NULL, messages[12], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\t\n\tMoveWindow(hwnd[0],0,0,maxX, maxY,0);\n\t\n\tMessageBox(NULL, messages[13], \"Info\",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);\n\n while(GetMessage(&Msg, NULL, 0, 0) > 0)\n {\n TranslateMessage(&Msg);\n DispatchMessage(&Msg);\n }\n return Msg.wParam;\n}\n", "language": "C" }, { "code": "sWindow As New String[4]\n'________________________\nPublic Sub Form_Open()\n\nManipulate\n\nEnd\n'________________________\nPublic Sub Manipulate()\nDim siDelay As Short = 2\n\nMe.Show\nPrint \"Show\"\nWait siDelay\n\nsWindow[0] = Me.Width\nsWindow[1] = Me.Height\nsWindow[2] = Me.X\nsWindow[3] = Me.y\n\nMe.Hide\nPrint \"Hidden\"\nCompareWindow\nWait siDelay\n\nMe.Show\nPrint \"Show\"\nCompareWindow\nWait siDelay\n\nMe.Minimized = True\nPrint \"Minimized\"\nCompareWindow\nWait siDelay\n\nMe.Show\nPrint \"Show\"\nCompareWindow\nWait siDelay\n\nMe.Maximized = True\nPrint \"Maximized\"\nCompareWindow\nWait siDelay\n\nMe.Maximized = False\nPrint \"Not Maximized\"\nCompareWindow\nWait siDelay\n\nMe.Height = 200\nMe.Width = 300\nPrint \"Resized\"\nCompareWindow\nWait siDelay\n\nMe.x = 10\nMe.Y = 10\nPrint \"Moved\"\nCompareWindow\nWait siDelay\n\nMe.Close\n\nEnd\n'________________________\nPublic Sub CompareWindow()\nDim sNewWindow As New String[4]\nDim siCount As Short\nDim bMatch As Boolean = True\n\nsNewWindow[0] = Me.Width\nsNewWindow[1] = Me.Height\nsNewWindow[2] = Me.X\nsNewWindow[3] = Me.y\n\nFor siCount = 0 To 3\n If sWindow[siCount] <> sNewWindow[siCount] Then bMatch = False\nNext\n\nIf bMatch Then\n Print \"Windows identities match the original window size\"\nElse\n Print \"Windows identities DONOT match the original window size\"\nEnd If\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"github.com/gotk3/gotk3/gtk\"\n \"log\"\n \"time\"\n)\n\nfunc check(err error, msg string) {\n if err != nil {\n log.Fatal(msg, err)\n }\n}\n\nfunc main() {\n gtk.Init(nil)\n\n window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n check(err, \"Unable to create window:\")\n window.SetResizable(true)\n window.SetTitle(\"Window management\")\n window.SetBorderWidth(5)\n window.Connect(\"destroy\", func() {\n gtk.MainQuit()\n })\n\n stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)\n check(err, \"Unable to create stack box:\")\n\n bmax, err := gtk.ButtonNewWithLabel(\"Maximize\")\n check(err, \"Unable to create maximize button:\")\n bmax.Connect(\"clicked\", func() {\n window.Maximize()\n })\n\n bunmax, err := gtk.ButtonNewWithLabel(\"Unmaximize\")\n check(err, \"Unable to create unmaximize button:\")\n bunmax.Connect(\"clicked\", func() {\n window.Unmaximize()\n })\n\n bicon, err := gtk.ButtonNewWithLabel(\"Iconize\")\n check(err, \"Unable to create iconize button:\")\n bicon.Connect(\"clicked\", func() {\n window.Iconify()\n })\n\n bdeicon, err := gtk.ButtonNewWithLabel(\"Deiconize\")\n check(err, \"Unable to create deiconize button:\")\n bdeicon.Connect(\"clicked\", func() {\n window.Deiconify()\n })\n\n bhide, err := gtk.ButtonNewWithLabel(\"Hide\")\n check(err, \"Unable to create hide button:\")\n bhide.Connect(\"clicked\", func() {\n // not working on Ubuntu 16.04 but window 'dims' after a few seconds\n window.Hide()\n time.Sleep(10 * time.Second)\n window.Show()\n })\n\n bshow, err := gtk.ButtonNewWithLabel(\"Show\")\n check(err, \"Unable to create show button:\")\n bshow.Connect(\"clicked\", func() {\n window.Show()\n })\n\n bmove, err := gtk.ButtonNewWithLabel(\"Move\")\n check(err, \"Unable to create move button:\")\n isShifted := false\n bmove.Connect(\"clicked\", func() {\n w, h := window.GetSize()\n if isShifted {\n window.Move(w-10, h-10)\n } else {\n window.Move(w+10, h+10)\n }\n isShifted = !isShifted\n })\n\n bquit, err := gtk.ButtonNewWithLabel(\"Quit\")\n check(err, \"Unable to create quit button:\")\n bquit.Connect(\"clicked\", func() {\n window.Destroy()\n })\n\n stackbox.PackStart(bmax, true, true, 0)\n stackbox.PackStart(bunmax, true, true, 0)\n stackbox.PackStart(bicon, true, true, 0)\n stackbox.PackStart(bdeicon, true, true, 0)\n stackbox.PackStart(bhide, true, true, 0)\n stackbox.PackStart(bshow, true, true, 0)\n stackbox.PackStart(bmove, true, true, 0)\n stackbox.PackStart(bquit, true, true, 0)\n\n window.Add(stackbox)\n window.ShowAll()\n gtk.Main()\n}\n", "language": "Go" }, { "code": "CHARACTER title=\"Rosetta Window_management\"\nREAL :: w=-333, h=25, x=1, y=0.5 ! pixels < 0, relative window size 0...1, script character size > 1\n\n WINDOW(WINdowhandle=wh, Width=w, Height=h, X=x, Y=y, TItle=title) ! create, on return size/pos VARIABLES are set to script char\n WINDOW(WIN=wh, MINimize) ! minimize\n WINDOW(WIN=wh, SHowNormal) ! restore\n WINDOW(WIN=wh, X=31, Y=7+4) !<-- move upper left here (col 31, row 7 + ~4 rows for title, menus, toolbar. Script window in upper left screen)\n WINDOW(WIN=wh, MAXimize) ! maximize (hides the script window)\n WINDOW(Kill=wh) ! close\nEND\n", "language": "HicEst" }, { "code": "link graphics\n\nprocedure main()\n\n Delay := 3000\n\n W1 := open(\"Window 1\",\"g\",\"resize=on\",\"size=400,400\",\"pos=100,100\",\"bg=black\",\"fg=red\") |\n stop(\"Unable to open window 1\")\n W2 := open(\"Window 2\",\"g\",\"resize=on\",\"size=400,400\",\"pos=450,450\",\"bg=blue\",\"fg=yellow\") |\n stop(\"Unable to open window 2\")\n W3 := open(\"Window 3\",\"g\",\"resize=on\",\"size=400,400\",\"pos=600,150\",\"bg=orange\",\"fg=black\") |\n stop(\"Unable to open window 3\")\n WWrite(W3,\"Opened three windows\")\n\n WWrite(W3,\"Window 1&2 with rectangles\")\n every Wx := W1 | W2 | W3 do\n if Wx ~=== W3 then\n FillRectangle(Wx,50,50,100,100)\n\n delay(Delay)\n WWrite(W3,\"Window 1 rasied\")\n Raise(W1)\n\n delay(Delay)\n WWrite(W3,\"Window 2 hidden\")\n WAttrib(W2,\"canvas=hidden\")\n\n delay(Delay)\n WWrite(W3,\"Window 2 maximized\")\n WAttrib(W2,\"canvas=maximal\")\n Raise(W3)\n\n delay(Delay)\n WWrite(W3,\"Window 2 restored & resized\")\n WAttrib(W2,\"canvas=normal\")\n WAttrib(W2,\"size=600,600\")\n\n delay(Delay)\n WWrite(W3,\"Window 2 moved\")\n WAttrib(W2,\"posx=700\",\"posy=300\")\n\n delay(Delay)\n WWrite(W3,\"Window 2 minimized\")\n WAttrib(W2,\"canvas=iconic\")\n\n delay(Delay)\n WWrite(W3,\"Window 2 restored\")\n WAttrib(W2,\"canvas=normal\") # restore as maximal, possible bug\n\n delay(Delay)\n WWrite(W3,\"Enter Q or q here to quit\")\n WDone(W3)\nend\n", "language": "Icon" }, { "code": "import java.awt.BorderLayout;\nimport java.awt.EventQueue;\nimport java.awt.Frame;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.lang.reflect.InvocationTargetException;\nimport javax.swing.AbstractAction;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.border.EmptyBorder;\n\npublic class WindowController extends JFrame {\n // Create UI on correct thread\n public static void main( final String[] args ) {\n EventQueue.invokeLater( () -> new WindowController() );\n }\n\n private JComboBox<ControlledWindow> list;\n\n // Button class to call the right method\n private class ControlButton extends JButton {\n private ControlButton( final String name ) {\n super(\n new AbstractAction( name ) {\n public void actionPerformed( final ActionEvent e ) {\n try {\n WindowController.class.getMethod( \"do\" + name )\n .invoke ( WindowController.this );\n } catch ( final Exception x ) { // poor practice\n x.printStackTrace(); // also poor practice\n }\n }\n }\n );\n }\n }\n\n // UI for controlling windows\n public WindowController() {\n super( \"Controller\" );\n\n final JPanel main = new JPanel();\n final JPanel controls = new JPanel();\n\n setLocationByPlatform( true );\n setResizable( false );\n setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n setLayout( new BorderLayout( 3, 3 ) );\n getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n add( new JLabel( \"Add windows and control them.\" ), BorderLayout.NORTH );\n main.add( list = new JComboBox<>() );\n add( main, BorderLayout.CENTER );\n controls.setLayout( new GridLayout( 0, 1, 3, 3 ) );\n controls.add( new ControlButton( \"Add\" ) );\n controls.add( new ControlButton( \"Hide\" ) );\n controls.add( new ControlButton( \"Show\" ) );\n controls.add( new ControlButton( \"Close\" ) );\n controls.add( new ControlButton( \"Maximise\" ) );\n controls.add( new ControlButton( \"Minimise\" ) );\n controls.add( new ControlButton( \"Move\" ) );\n controls.add( new ControlButton( \"Resize\" ) );\n add( controls, BorderLayout.EAST );\n pack();\n setVisible( true );\n }\n\n // These are the windows we're controlling, but any JFrame would do\n private static class ControlledWindow extends JFrame {\n private int num;\n\n public ControlledWindow( final int num ) {\n super( Integer.toString( num ) );\n this.num = num;\n setLocationByPlatform( true );\n getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) );\n setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );\n add( new JLabel( \"I am window \" + num + \". Use the controller to control me.\" ) );\n pack();\n setVisible( true );\n }\n\n public String toString() {\n return \"Window \" + num;\n }\n }\n\n // Here comes the useful bit - window control code\n // Everything else was just to allow us to do this!\n\n public void doAdd() {\n list.addItem( new ControlledWindow( list.getItemCount () + 1 ) );\n pack();\n }\n\n public void doHide() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n window.setVisible( false );\n }\n\n public void doShow() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n window.setVisible( true );\n }\n\n public void doClose() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n window.dispose();\n }\n\n public void doMinimise() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n window.setState( Frame.ICONIFIED );\n }\n\n public void doMaximise() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n window.setExtendedState( Frame.MAXIMIZED_BOTH );\n }\n\n public void doMove() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n final int hPos = getInt( \"Horizontal position?\" );\n if ( -1 == hPos ) {\n return;\n }\n final int vPos = getInt( \"Vertical position?\" );\n if ( -1 == vPos ) {\n return;\n }\n window.setLocation ( hPos, vPos );\n }\n\n public void doResize() {\n final JFrame window = getWindow();\n if ( null == window ) {\n return;\n }\n final int width = getInt( \"Width?\" );\n if ( -1 == width ) {\n return;\n }\n final int height = getInt( \"Height?\" );\n if ( -1 == height ) {\n return;\n }\n window.setBounds ( window.getX(), window.getY(), width, height );\n }\n\n private JFrame getWindow() {\n final JFrame window = ( JFrame ) list.getSelectedItem();\n if ( null == window ) {\n JOptionPane.showMessageDialog( this, \"Add a window first\" );\n }\n return window;\n }\n\n private int getInt(final String prompt) {\n final String s = JOptionPane.showInputDialog( prompt );\n if ( null == s ) {\n return -1;\n }\n try {\n return Integer.parseInt( s );\n } catch ( final NumberFormatException x ) {\n JOptionPane.showMessageDialog( this, \"Not a number\" );\n return -1;\n }\n }\n}\n", "language": "Java" }, { "code": "using Gtk\n\nfunction controlwindow(win, lab)\n sleep(4)\n set_gtk_property!(lab, :label, \"Hiding...\")\n sleep(1)\n println(\"Hiding widow\")\n set_gtk_property!(win, :visible, false)\n sleep(5)\n set_gtk_property!(lab, :label, \"Showing...\")\n println(\"Showing window\")\n set_gtk_property!(win, :visible, true)\n sleep(5)\n set_gtk_property!(lab, :label, \"Resizing...\")\n println(\"Resizing window\")\n resize!(win, 300, 300)\n sleep(4)\n set_gtk_property!(lab, :label, \"Maximizing...\")\n println(\"Maximizing window\")\n sleep(1)\n maximize(win)\n set_gtk_property!(lab, :label, \"Closing...\")\n sleep(5)\n println(\"Closing window\")\n destroy(win)\n sleep(2)\n exit(0)\nend\n\nfunction runwindow()\n win = GtkWindow(\"Window Control Test\", 500, 30) |> (GtkFrame() |> (vbox = GtkBox(:v)))\n lab = GtkLabel(\"Window under external control\")\n push!(vbox, lab)\n @async(controlwindow(win, lab))\n\n cond = Condition()\n endit(w) = notify(cond)\n signal_connect(endit, win, :destroy)\n showall(win)\n wait(cond)\nend\n\nrunwindow()\n", "language": "Julia" }, { "code": "nb=NotebookCreate[]; (*Create a window and store in a variable*)\nnb===nb2 (*test for equality with another window object*)\nSetOptions[nb,Visible->False](*Hide*)\nSetOptions[nb,Visible->True](*Show*)\nNotebookClose[nb] (*Close*)\nSetOptions[nb,WindowMargins->{{x,Automatic},{y,Automatic}}](*Move to x,y screen position*)\nSetOptions[nb,WindowSize->{100,100}](*Resize*)\n", "language": "Mathematica" }, { "code": "import os\nimport gintro/[glib, gobject, gtk, gio]\nfrom gintro/gdk import processAllUpdates\n\ntype MyWindow = ref object of ApplicationWindow\n isShifted: bool\n\n#---------------------------------------------------------------------------------------------------\n\nproc wMaximize(button: Button; window: MyWindow) =\n window.maximize()\n\nproc wUnmaximize(button: Button; window: MyWindow) =\n window.unmaximize()\n\nproc wIconify(button: Button; window: MyWindow) =\n window.iconify()\n\nproc wDeiconify(button: Button; window: MyWindow) =\n window.deiconify()\n\nproc wHide(button: Button; window: MyWindow) =\n window.hide()\n processAllUpdates()\n os.sleep(2000)\n window.show()\n\nproc wShow(button: Button; window: MyWindow) =\n window.show()\n\nproc wMove(button: Button; window: MyWindow) =\n var x, y: int\n window.getPosition(x, y)\n if window.isShifted:\n window.move(x - 10, y - 10)\n else:\n window.move(x + 10, y + 10)\n window.isShifted = not window.isShifted\n\nproc wQuit(button: Button; window: MyWindow) =\n window.destroy()\n\n#---------------------------------------------------------------------------------------------------\n\nproc activate(app: Application) =\n ## Activate the application.\n\n let window = newApplicationWindow(MyWindow, app)\n window.setTitle(\"Window management\")\n\n let stackBox = newBox(Orientation.vertical, 10)\n stackBox.setHomogeneous(true)\n\n let\n bMax = newButton(\"maximize\")\n bUnmax = newButton(\"unmaximize\")\n bIcon = newButton(\"iconize\")\n bDeicon = newButton(\"deiconize\")\n bHide = newButton(\"hide\")\n bShow = newButton(\"show\")\n bMove = newButton(\"move\")\n bQuit = newButton(\"Quit\")\n\n for button in [bMax, bUnmax, bIcon, bDeicon, bHide, bShow, bMove, bQuit]:\n stackBox.add button\n\n window.setBorderWidth(5)\n window.add(stackBox)\n\n discard bMax.connect(\"clicked\", wMaximize, window)\n discard bUnmax.connect(\"clicked\", wUnmaximize, window)\n discard bIcon.connect(\"clicked\", wIconify, window)\n discard bDeicon.connect(\"clicked\", wDeiconify, window)\n discard bHide.connect(\"clicked\", wHide, window)\n discard bShow.connect(\"clicked\", wShow, window)\n discard bMove.connect(\"clicked\", wMove, window)\n discard bQuit.connect(\"clicked\", wQuit, window)\n\n window.showAll()\n\n#———————————————————————————————————————————————————————————————————————————————————————————————————\n\nlet app = newApplication(Application, \"Rosetta.Window.Management\")\ndiscard app.connect(\"activate\", activate)\ndiscard app.run()\n", "language": "Nim" }, { "code": "import os\nimport gdk2, glib2, gtk2\n\nproc thisDestroy(widget: PWidget; data: Pgpointer) {.cdecl.} =\n main_quit()\n\nproc thisMax(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().maximize()\n\nproc thisUnmax(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().unmaximize()\n\nproc thisIcon(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().iconify()\n\nproc thisDeicon(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().deiconify()\n\nproc thisHide(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().hide()\n window_process_all_updates()\n sleep(2000)\n widget.get_parent_window().show()\n\nproc thisShow(widget: PWidget; data: Pgpointer) {.cdecl.} =\n widget.get_parent_window().show()\n\nvar isShifted = false\n\nproc thisMove(widget: PWidget; data: Pgpointer) {.cdecl.} =\n var x, y: gint\n widget.get_parent_window().get_position(addr(x), addr(y))\n if isshifted:\n widget.get_parent_window().move(x - 10, y - 10)\n else:\n widget.get_parent_window().move(x + 10, y + 10)\n isShifted = not isShifted\n\n\nnim_init()\nlet window = window_new(gtk2.WINDOW_TOPLEVEL)\ndiscard window.allow_grow()\nwindow.set_title(\"Window management\")\nlet\n stackbox = vbox_new(true, 10)\n bMax = button_new(\"maximize\")\n bUnmax = button_new(\"unmaximize\")\n bIcon = button_new(\"iconize\")\n bDeicon = button_new(\"deiconize\")\n bHide = button_new(\"hide\")\n bShow = button_new(\"show\")\n bMove = button_new(\"move\")\n bQuit = button_new(\"Quit\")\n\nstackbox.pack_start(bMax, true, true, 0)\nstackbox.pack_start(bUnmax, true, true, 0)\nstackbox.pack_start(bIcon, true, true, 0)\nstackbox.pack_start(bDeicon, true, true, 0)\nstackbox.pack_start(bHide, true, true, 0)\nstackbox.pack_start(bShow, true, true, 0)\nstackbox.pack_start(bMove, true, true, 0)\nstackbox.pack_start(bQuit, true, true, 0)\nwindow.set_border_width(5)\nwindow.add(stackbox)\n\ndiscard window.signal_connect(\"destroy\", SIGNAL_FUNC(thisDestroy), nil)\ndiscard bIcon.signal_connect(\"clicked\", SIGNAL_FUNC(thisIcon), nil)\ndiscard bDeicon.signal_connect(\"clicked\", SIGNAL_FUNC(thisDeicon), nil)\ndiscard bMax.signal_connect(\"clicked\", SIGNAL_FUNC(thisMax), nil)\ndiscard bUnmax.signal_connect(\"clicked\", SIGNAL_FUNC(thisUnmax), nil)\ndiscard bHide.signal_connect(\"clicked\", SIGNAL_FUNC(thisHide), nil)\ndiscard bShow.signal_connect(\"clicked\", SIGNAL_FUNC(thisShow), nil)\ndiscard bMove.signal_connect(\"clicked\", SIGNAL_FUNC(thismove), nil)\ndiscard bQuit.signal_connect(\"clicked\", SIGNAL_FUNC(thisDestroy), nil)\nwindow.show_all()\nmain()\n", "language": "Nim" }, { "code": "import iup\n\n# assumes you have the iup .dll or .so installed\n\nproc toCB(fp: proc): ICallback =\n return cast[ICallback](fp)\n\ndiscard iup.open(nil,nil)\n\nvar btnRestore = button(\"restore\",\"\")\nvar btnFull = button(\"Full screen\",\"\")\nvar btnMin = button(\"minimize\",\"\")\nvar btnMax = button(\"maximize\",\"\")\nvar btnHide = button(\"Transparent\",\"\")\n#var btnHide = button(\"Hide (close)\",\"\")\nvar btnShow = button(\"Show\",\"\")\n\nvar hbox = Hbox(btnRestore, btnFull, btnMax, btnMin, btnShow, btnHide, nil)\nsetAttribute(hbox,\"MARGIN\", \"10x10\")\nsetAttribute(hbox,\"PADDING\", \"5x5\")\n\nvar dlg = Dialog(hbox)\n#SetAttribute(dlg, \"SIZE\", \"100x50\")\n\nproc doFull(ih:PIhandle): cint {.cdecl.} =\n setAttribute(dlg,\"FULLSCREEN\",\"YES\")\n return IUP_DEFAULT\n\nproc doMax(ih:PIhandle): cint {.cdecl.} =\n #setAttribute(dlg,\"FULLSCREEN\",\"YES\")\n setAttribute(dlg,\"PLACEMENT\",\"MAXIMIZED\")\n # this is a work-around to get the dialog minimised (on win platform)\n setAttribute(dlg,\"VISIBLE\",\"YES\")\n return IUP_DEFAULT\n\nproc doMin(ih:PIhandle): cint {.cdecl.} =\n setAttribute(dlg,\"PLACEMENT\",\"MINIMIZED\")\n # this is a work-around to get the dialog minimised (on win platform)\n setAttribute(dlg,\"VISIBLE\",\"YES\")\n return IUP_DEFAULT\n\nproc doRestore(ih:PIhandle): cint {.cdecl.} =\n setAttribute(dlg,\"OPACITY\",\"255\")\n setAttribute(dlg,\"FULLSCREEN\",\"NO\")\n setAttribute(dlg,\"PLACEMENT\",\"NORMAL\")\n setAttribute(dlg,\"VISIBLE\",\"YES\")\n return IUP_DEFAULT\n\nproc doHide(ih:PIhandle): cint {.cdecl.} =\n #setAttribute(dlg,\"VISIBLE\",\"NO\")\n setAttribute(dlg,\"OPACITY\",\"60\")\n return IUP_DEFAULT\n\nproc doShow(ih:PIhandle): cint {.cdecl.} =\n setAttribute(dlg,\"OPACITY\",\"255\")\n setAttribute(dlg,\"VISIBLE\",\"YES\")\n return IUP_DEFAULT\n\ndiscard setCallback(btnRestore,\"ACTION\", toCB(doRestore))\ndiscard setCallback(btnFull,\"ACTION\", toCB(doFull))\ndiscard setCallback(btnMax,\"ACTION\", toCB(doMax))\ndiscard setCallback(btnMin,\"ACTION\", toCB(doMin))\ndiscard setCallback(btnShow,\"ACTION\", toCB(doShow))\ndiscard setCallback(btnHide,\"ACTION\", toCB(doHide))\n\ndiscard dlg.show()\ndiscard mainloop()\niup.Close()\n", "language": "Nim" }, { "code": "declare\n [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}\n\n %% The messages that can be sent to the windows.\n WindowActions =\n [hide show close\n iconify deiconify\n maximize restore\n set(minsize:minsize(width:400 height:400))\n set(minsize:minsize(width:200 height:200))\n set(geometry:geometry(x:0 y:0))\n set(geometry:geometry(x:500 y:500))\n ]\n\n %% Two windows, still uninitialized.\n Windows = windows(window1:_\n window2:_)\n\n fun {CreateWindow}\n Message = {NewCell WindowActions.1}\n ReceiverName = {NewCell {Arity Windows}.1}\n fun {ButtonText}\n \"Send\"#\" \"#{ValueToString @Message}#\" to \"#@ReceiverName\n end\n Button\n Desc =\n td(title:\"Window Management\"\n lr(listbox(init:{Arity Windows}\n glue:nswe\n tdscrollbar:true\n actionh:proc {$ W}\n ReceiverName := {GetSelected W}\n {Button set(text:{ButtonText})}\n end\n )\n listbox(init:{Map WindowActions ValueToString}\n glue:nswe\n tdscrollbar:true\n actionh:proc {$ A}\n Message := {GetSelected A}\n {Button set(text:{ButtonText})}\n end\n )\n glue:nswe\n )\n button(text:{ButtonText}\n glue:we\n handle:Button\n action:proc {$}\n {Windows.@ReceiverName @Message}\n end\n )\n )\n Window = {Extend {QTk.build Desc}}\n in\n {Window show}\n Window\n end\n\n %% Adds two methods to a toplevel instance.\n %% For maximize and restore we have to interact directly with Tk\n %% because that functionality is not part of the QTk library.\n fun {Extend Toplevel}\n proc {$ A}\n case A of maximize then\n {Tk.send wm(state Toplevel zoomed)}\n [] restore then\n {Tk.send wm(state Toplevel normal)}\n else\n {Toplevel A}\n end\n end\n end\n\n %% Returns the current entry of a listbox\n %% as an Oz value.\n fun {GetSelected LB}\n Entries = {LB get($)}\n Index = {LB get(firstselection:$)}\n in\n {Compiler.virtualStringToValue {Nth Entries Index}}\n end\n\n fun {ValueToString V}\n {Value.toVirtualString V 100 100}\n end\nin\n {Record.forAll Windows CreateWindow}\n", "language": "Oz" }, { "code": "#!perl\nuse strict;\nuse warnings;\nuse Tk;\n\nmy $mw;\nmy $win;\nmy $lab;\n\n# How to open a window.\nsub openWin {\n\tif( $win ) {\n\t\t$win->deiconify;\n\t\t$win->wm('state', 'normal');\n\t} else {\n\t\teval { $win->destroy } if $win;\n\t\t$win = $mw->Toplevel;\n\t\t$win->Label(-text => \"This is the window being manipulated\")\n\t\t\t->pack(-fill => 'both', -expand => 1);\n\t\t$lab->configure(-text => \"The window object is:\\n$win\");\n\t}\n}\n\n# How to close a window\nsub closeWin {\n\treturn unless $win;\n\t$win->destroy;\n\t$lab->configure(-text => '');\n\tundef $win;\n}\n\n# How to minimize a window\nsub minimizeWin {\n\treturn unless $win;\n\t$win->iconify;\n}\n\n# How to maximize a window\nsub maximizeWin {\n\treturn unless $win;\n\t$win->wm('state', 'zoomed');\n\teval { $win->wmAttribute(-zoomed => 1) }; # Hack for X11\n}\n\n# How to move a window\nsub moveWin {\n\treturn unless $win;\n\tmy ($x, $y) = $win->geometry() =~ /\\+(\\d+)\\+(\\d+)\\z/ or die;\n\t$_ += 10 for $x, $y;\n\t$win->geometry(\"+$x+$y\");\n}\n\n# How to resize a window\nsub resizeWin {\n\treturn unless $win;\n\tmy ($w, $h) = $win->geometry() =~ /^(\\d+)x(\\d+)/ or die;\n\t$_ += 10 for $w, $h;\n\t$win->geometry($w . \"x\" . $h);\n}\n\n$mw = MainWindow->new;\nfor my $label0 ($mw->Label(-text => 'Window handle:')) {\n\t$lab = $mw->Label(-text => '');\n\t$label0->grid($lab);\n}\n\nmy @binit = ('Open/Restore' => \\&openWin, Close => \\&closeWin,\n\tMinimize => \\&minimizeWin, Maximize => \\&maximizeWin,\n\tMove => \\&moveWin, Resize => \\&resizeWin);\n\nwhile( my ($text, $callback) = splice @binit, 0, 2 ) {\n\t$mw->Button(-text => $text, -command => $callback)->grid('-');\n}\n\nMainLoop();\n\n__END__\n", "language": "Perl" }, { "code": "-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Window_management.exw</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doFull</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"FULLSCREEN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doMax</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PLACEMENT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MAXIMIZED\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- this is a work-around to get the dialog minimised (on win platform)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doMin</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PLACEMENT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MINIMIZED\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- this is a work-around to get the dialog minimised (on win platform)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doRestore</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"OPACITY\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"255\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"FULLSCREEN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PLACEMENT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"NORMAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YES\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doDim</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"OPACITY\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"60\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"OPACITY\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"255\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">doMove</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"SCREENPOSITION\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">shift</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"SHIFTKEY\"</span><span style=\"color: #0000FF;\">)?-</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShowXY</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">shift</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">shift</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">hbox</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"restore\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doRestore\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"full screen\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doFull\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"maximize\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doMax\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"minimize\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doMin\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"dim\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doDim\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"show\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doShow\"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"move\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"doMove\"</span><span style=\"color: #0000FF;\">))})</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hbox</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MARGIN\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"10x10\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hbox</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PADDING\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"5x5\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hbox</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"OPACITY\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"255\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #7060A8;\">IupShowXY</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">IUP_CENTER</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">IUP_CENTER</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "$ ersatz/pil +\n: (setq\n JFrame \"javax.swing.JFrame\"\n MAXIMIZED_BOTH (java (public JFrame 'MAXIMIZED_BOTH))\n ICONIFIED (java (public JFrame 'ICONIFIED))\n Win (java JFrame T \"Window\") )\n-> $JFrame\n\n# Compare for equality\n: (== Win Win)\n-> T\n\n# Set window visible\n(java Win 'setLocation 100 100)\n(java Win 'setSize 400 300)\n(java Win 'setVisible T)\n\n# Hide window\n(java Win 'hide)\n\n# Show again\n(java Win 'setVisible T)\n\n# Move window\n(java Win 'setLocation 200 200)\n\n# Iconify window\n(java Win 'setExtendedState\n (| (java (java Win 'getExtendedState)) ICONIFIED) )\n\n# De-conify window\n(java Win 'setExtendedState\n (& (java (java Win 'getExtendedState)) (x| (hex \"FFFFFFFF\") ICONIFIED)) )\n\n# Maximize window\n(java Win 'setExtendedState\n (| (java (java Win 'getExtendedState)) MAXIMIZED_BOTH) )\n\n# Close window\n(java Win 'dispose)\n", "language": "PicoLisp" }, { "code": ";- Create a linked list to store created windows.\nNewList Windows()\nDefine i, j, dh, dw, flags, err$, x, y\n\n;- Used sub-procedure to simplify the error handling\nProcedure HandleError(Result, Text.s,ErrorLine=0,ExitCode=0)\n If Not Result\n MessageRequester(\"Error\",Text)\n End ExitCode\n EndIf\n ProcedureReturn Result\nEndProcedure\n\n;- Window handling procedures\nProcedure Minimize(window)\n SetWindowState(window,#PB_Window_Minimize)\nEndProcedure\n\nProcedure Normalize(window)\n SetWindowState(window,#PB_Window_Normal)\nEndProcedure\n\n;- Get enviroment data\nHandleError(ExamineDesktops(), \"Failed to examine you Desktop.\")\ndh=HandleError(DesktopHeight(0),\"Could not retrieve DesktopHight\")/3\ndw=HandleError(DesktopWidth(0), \"Could not retrieve DesktopWidth\")/3\n\n;- Now, creating 9 windows\nflags=#PB_Window_SystemMenu\nerr$=\"Failed to open Window\"\nFor i=0 To 8\n j=HandleError(OpenWindow(#PB_Any,i*10,i*10+30,10,10,Str(i),flags),err$)\n SmartWindowRefresh(j, 1)\n AddElement(Windows())\n Windows()=j\nNext i\nDelay(1000)\n\n;- Call a sub-routine for each Window stored in the list.\nForEach Windows()\n Minimize(Windows())\nNext\nDelay(1000)\n;- and again\nForEach Windows()\n Normalize(Windows())\nNext\nDelay(1000)\n\n;- Spread them evenly\nForEach Windows()\n ResizeWindow(Windows(),x*dw,y*dh,dw-15,dh-35)\n x+1\n If x>2\n x=0: y+1\n EndIf\nNext\nDelay(2000)\n\nEnd\n", "language": "PureBasic" }, { "code": "from tkinter import *\nimport tkinter.messagebox\n\ndef maximise():\n\t\"\"\"get screenwidth and screenheight, and resize window to that size.\n\tAlso move to 0,0\"\"\"\n\troot.geometry(\"{}x{}+{}+{}\".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))\n\t\ndef minimise():\n\t\"\"\"Iconify window to the taskbar. When reopened, the window is\n\tunfortunately restored to its original state, NOT its most recent state.\"\"\"\n\troot.iconify()\n\t\ndef delete():\n\t\"\"\"create a modal dialog. If answer is \"OK\", quit the program\"\"\"\n\tif tkinter.messagebox.askokcancel(\"OK/Cancel\",\"Are you sure?\"):\n\t\troot.quit()\n\t\nroot = Tk()\n\nmx=Button(root,text=\"maximise\",command=maximise)\nmx.grid()\nmx.bind(maximise)\n\nmn=Button(root,text=\"minimise\",command=minimise)\nmn.grid()\nmn.bind(minimise)\n\n#catch exit events, including \"X\" on title bar.\nroot.protocol(\"WM_DELETE_WINDOW\",delete)\n\nmainloop()\n", "language": "Python" }, { "code": "#lang racket/gui\n\n(define (say . xs) (printf \">>> ~a\\n\" (apply ~a xs)) (flush-output))\n\n(define frame (new frame% [label \"Demo\"] [width 400] [height 400]))\n(say \"frame = \" frame) ; plain value\n\n(say 'Show) (send frame show #t) (sleep 1)\n(say 'Hide) (send frame show #f) (sleep 1)\n(say 'Show) (send frame show #t) (sleep 1)\n(say 'Minimize) (send frame iconize #t) (sleep 1)\n(say 'Restore) (send frame iconize #f) (sleep 1)\n(say 'Maximize) (send frame maximize #t) (sleep 1)\n(say 'Restore) (send frame maximize #f) (sleep 1)\n(say 'Move) (send frame move 100 100) (sleep 1)\n(say 'Resize) (send frame resize 100 100) (sleep 1)\n(say 'Close) (send frame show #f) (sleep 1) ; that's how we close a window\n", "language": "Racket" }, { "code": "use X11::libxdo;\n\nmy $xdo = Xdo.new;\n\nsay 'Visible windows:';\nprintf \"Class: %-21s ID#: %10d pid: %5d Name: %s\\n\", $_<class ID pid name>\n for $xdo.get-windows.sort(+*.key)».value;\nsleep 2;\n\nmy $id = $xdo.get-active-window;\n\nmy ($w, $h ) = $xdo.get-window-size( $id );\nmy ($wx, $wy) = $xdo.get-window-location( $id );\nmy ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );\n\n$xdo.move-window( $id, 150, 150 );\n\n$xdo.set-window-size( $id, 350, 350, 0 );\n\nsleep .25;\n\nfor flat 1 .. $dw - 350, $dw - 350, {$_ - 1} … 1 -> $mx { #\n my $my = (($mx / $dw * τ).sin * 500).abs.Int;\n $xdo.move-window( $id, $mx, $my );\n $xdo.activate-window($id);\n}\n\nsleep .25;\n\n$xdo.move-window( $id, 150, 150 );\n\nmy $dx = $dw - 300;\nmy $dy = $dh - 300;\n\n$xdo.set-window-size( $id, $dx, $dy, 0 );\n\nsleep .25;\n\nmy $s = -1;\n\nloop {\n $dx += $s * ($dw / 200).ceiling;\n $dy += $s * ($dh / 200).ceiling;\n $xdo.set-window-size( $id, $dx, $dy, 0 );\n $xdo.activate-window($id);\n sleep .005;\n $s *= -1 if $dy < 200;\n last if $dx >= $dw;\n}\n\nsleep .25;\n\n$xdo.set-window-size( $id, $w, $h, 0 );\n$xdo.move-window( $id, $wx, $wy );\n$xdo.activate-window($id);\n\nsleep .25;\n\n$xdo.minimize($id);\n$xdo.activate-window($id);\nsleep 1;\n$xdo.raise-window($id);\nsleep .25;\n", "language": "Raku" }, { "code": "Load \"guilib.ring\"\n\n/*\n +--------------------------------------------------------------------------\n + Program Name : ScreenDrawOnReSize.ring\n + Date : 2016.06.16\n + Author : Bert Mariani\n + Purpose : Re-Draw Chart after ReSize or move\n +--------------------------------------------------------------------------\n*/\n\n\n###-------------------------------\n### DRAW CHART size 1000 x 1000\n###\n\n###------------------------------\n\n### Window Size\n WinLeft = 80 ### 80 Window position on screen\n WinTop = 80 ### 80 Window position on screen\n WinWidth = 1000 ### 1000 Window Size - Horizontal-X WinWidth\n WinHeight = 750 ### 750 Window Size - Vertical-Y WinHeight\n WinRight = WinLeft + WinWidth ### 1080\n WinBottom = WinTop + WinHeight ### 830\n\n### Label Box Size\n BoxLeft = 40 ### Start corner Label1 Box Start Position inside WIN1\n BoxTop = 40 ### Start corner\n BoxWidth = WinWidth -80 ### End corner Label1 Box Size\n BoxHeight = WinHeight -80 ### End corner\n\n###----------------------------\n\n\nNew qapp {\n win1 = new qwidget() {\n\n ### Position and Size of WINDOW on the Screen\n setwindowtitle(\"DrawChart using QPainter\")\n setgeometry( WinLeft, WinTop, WinWidth, WinHeight)\n\n win1{ setwindowtitle(\"Initial Window Position: \" +\" L \" + WinLeft +\" T \" + WinTop +\" Width\" + width() +\" Height \" + height() ) }\n\n ### ReSizeEvent ... Call WhereAreWe function\n myfilter = new qallevents(win1)\n myfilter.setResizeEvent(\"WhereAreWe()\")\n installeventfilter(myfilter)\n\n ### Draw within this BOX\n label1 = new qlabel(win1) {\n setgeometry(BoxLeft, BoxTop, BoxWidth, BoxHeight)\n settext(\"We are Here\")\n }\n\n\n ### Button Position and Size ... Call DRAW function\n new qpushbutton(win1) {\n setgeometry( 30, 30, 80, 20)\n settext(\"Draw\")\n setclickevent(\"Draw()\")\n }\n\n ###---------------\n\n show()\n }\n\n exec()\n}\n\n\n###-----------------\n### FUNCTION Draw\n###-----------------\n\nFunc WhereAreWe\n Rec = win1.framegeometry()\n\n WinWidth = win1.width() ### 1000 Current Values\n WinHeight = win1.height() ### 750\n\n WinLeft = Rec.left() +8 ### <<< QT FIX because of Win Title\n WinTop = Rec.top() +30 ### <<< QT FIX because of Win Title\n WinRight = Rec.right()\n WinBottom = Rec.bottom()\n\n BoxWidth = WinWidth -80 ### 950\n BoxHeight = WinHeight -80 ### 700\n\n win1{ setwindowtitle(\"Window ReSize: Win \" + WinWidth + \"x\" + WinHeight + \" --- Box \" + BoxWidth + \"x\" + BoxHeight +\n \" --- LT \" + WinLeft + \"-\" + WinTop + \" --- RB \" + WinRight + \"-\" + WinBottom ) }\n\n See \"We Are Here - setResizeEvent - \"\n See \" Win \" + WinWidth + \"x\" + WinHeight + \" --- Box \" + BoxWidth + \"x\" + BoxHeight\n See \" --- LT \" + Winleft + \"-\" + WinTop + \" --- RB \" + WinRight + \"-\" + WinBottom +nl\n\n win1.setgeometry( WinLeft, WinTop, WinWidth, WinHeight )\n label1.setgeometry( BoxLeft, BoxTop, BoxWidth, BoxHeight )\n\n\nreturn\n\nFunc Draw\n\n win1{ setwindowtitle(\"Draw Position: Win \" + WinWidth + \"x\" + WinHeight + \" --- Box \" + BoxWidth + \"x\" + BoxHeight +\n \" --- LT \" + WinLeft + \"-\" + WinTop + \" --- RB \" + WinRight + \"-\" + WinBottom ) }\n\n See \"Draw Position: \" + WinWidth + \"x\" + WinHeight + \" --- Box \" + BoxWidth + \"x\" + BoxHeight +\n \" --- LT \" + WinLeft + \"-\" + WinTop + \" --- RB \" + WinRight + \"-\" + WinBottom + nl\n\n\n # ##-----------------------------\n ### PEN Colors\n\n p1 = new qpicture()\n\n colorBlue = new qcolor() { setrgb(0, 0,255,255) }\n penBlue = new qpen() { setcolor(colorBlue) setwidth(1) }\n\n\n ###-----------------------\n ### PAINT the Chart\n\n new qpainter() {\n begin(p1)\n setpen(penBlue)\n\n ###---------------------\n ### Draw Line Chart\n\n drawline( 1 , 1 , BoxWidth , 1 ) ### WinTop line horizonal\n drawline( 1 , 1 , 1 , BoxHeight ) ### WinLeft Line vetical\n\n drawline( 1 , BoxHeight , BoxWidth , BoxHeight ) ### Bottom Line horizontal\n drawline( BoxWidth , 1 , BoxWidth , BoxHeight ) ### WinRight Line vertical\n\n drawline( BoxWidth / 2 , 1 , BoxWidth / 2 , BoxHeight ) ### Central vertical\n drawline( 1 , BoxHeight / 2 , BoxWidth , BoxHeight / 2 ) ### Central horizontal\n\n\n ###--------------------------------------------------\n\n\n endpaint()\n }\n\n\n label1 { setpicture(p1) show() }\n\nreturn\n###--------------------------------------------\n", "language": "Ring" }, { "code": "package require Tk\n\n# How to open a window\nproc openWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n # Already existing; just reset\n wm deiconify $win\n wm state $win normal\n return\n }\n catch {destroy $win} ;# Squelch the old one\n set win [toplevel .t]\n pack [label $win.label -text \"This is the window being manipulated\"] \\\n -fill both -expand 1\n}\n# How to close a window\nproc closeWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n destroy $win\n }\n}\n# How to minimize a window\nproc minimizeWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n wm state $win iconic\n }\n}\n# How to maximize a window\nproc maximizeWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n wm state $win zoomed\n catch {wm attribute $win -zoomed 1} ;# Hack for X11\n }\n}\n# How to move a window\nproc moveWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n scan [wm geometry $win] \"%dx%d+%d+%d\" width height x y\n wm geometry $win +[incr x 10]+[incr y 10]\n }\n}\n# How to resize a window\nproc resizeWin {} {\n global win\n if {[info exists win] && [winfo exists $win]} {\n scan [wm geometry $win] \"%dx%d+%d+%d\" width height x y\n wm geometry $win [incr width 10]x[incr height 10]\n }\n}\n\ngrid [label .l -text \"Window handle:\"] [label .l2 -textvariable win]\ngrid [button .b1 -text \"Open/Reset\" -command openWin] -\ngrid [button .b2 -text \"Close\" -command closeWin] -\ngrid [button .b3 -text \"Minimize\" -command minimizeWin] -\ngrid [button .b4 -text \"Maximize\" -command maximizeWin] -\ngrid [button .b5 -text \"Move\" -command moveWin] -\ngrid [button .b6 -text \"Resize\" -command resizeWin] -\n", "language": "Tcl" }, { "code": "/* Window_management.wren */\n\nvar GTK_WINDOW_TOPLEVEL = 0\nvar GTK_ORIENTATION_VERTICAL = 1\nvar GTK_BUTTONBOX_CENTER = 5\n\nforeign class GtkWindow {\n construct new(type) {}\n\n foreign title=(title)\n foreign setDefaultSize(width, height)\n\n foreign add(widget)\n foreign connectDestroy()\n\n foreign showAll()\n foreign iconify()\n foreign deiconify()\n foreign maximize()\n foreign unmaximize()\n foreign move(x, y)\n foreign resize(width, height)\n foreign hide()\n foreign destroy()\n}\n\nforeign class GtkButtonBox {\n construct new(orientation) {}\n\n foreign spacing=(interval)\n foreign layout=(layoutStyle)\n\n foreign add(button)\n}\n\nforeign class GtkButton {\n construct newWithLabel(label) {}\n\n foreign connectClicked()\n}\n\nclass Gdk {\n foreign static flush()\n}\n\nclass C {\n foreign static sleep(secs)\n}\n\nvar Window = GtkWindow.new(GTK_WINDOW_TOPLEVEL)\nWindow.title = \"Window management\"\nWindow.setDefaultSize(400, 400)\nWindow.connectDestroy()\n\nclass GtkCallbacks {\n static btnClicked(label) {\n if (label == \"Minimize\") {\n Window.iconify()\n } else if (label == \"Unminimize\") {\n Window.deiconify()\n } else if (label == \"Maximize\") {\n Window.maximize()\n } else if (label == \"Unmaximize\") {\n Window.unmaximize()\n } else if (label == \"Move\") {\n Window.move(0, 0) // move to top left hand corner of display\n } else if (label == \"Resize\") {\n Window.resize(600, 600)\n } else if (label == \"Hide\") {\n Window.hide()\n Gdk.flush()\n C.sleep(5) // wait 5 seconds\n Window.showAll()\n } else if (label == \"Close\") {\n Window.destroy()\n }\n }\n}\n\nvar buttonBox = GtkButtonBox.new(GTK_ORIENTATION_VERTICAL)\nbuttonBox.spacing = 20\nbuttonBox.layout = GTK_BUTTONBOX_CENTER\nWindow.add(buttonBox)\n\nvar btnMin = GtkButton.newWithLabel(\"Minimize\")\nbtnMin.connectClicked()\nbuttonBox.add(btnMin)\n\nvar btnUnmin = GtkButton.newWithLabel(\"Unminimize\")\nbtnUnmin.connectClicked()\nbuttonBox.add(btnUnmin)\n\nvar btnMax = GtkButton.newWithLabel(\"Maximize\")\nbtnMax.connectClicked()\nbuttonBox.add(btnMax)\n\nvar btnUnmax = GtkButton.newWithLabel(\"Unmaximize\")\nbtnUnmax.connectClicked()\nbuttonBox.add(btnUnmax)\n\nvar btnMove = GtkButton.newWithLabel(\"Move\")\nbtnMove.connectClicked()\nbuttonBox.add(btnMove)\n\nvar btnResize = GtkButton.newWithLabel(\"Resize\")\nbtnResize.connectClicked()\nbuttonBox.add(btnResize)\n\nvar btnHide = GtkButton.newWithLabel(\"Hide\")\nbtnHide.connectClicked()\nbuttonBox.add(btnHide)\n\nvar btnClose = GtkButton.newWithLabel(\"Close\")\nbtnClose.connectClicked()\nbuttonBox.add(btnClose)\n\nWindow.showAll()\n", "language": "Wren" }, { "code": "/* gcc `pkg-config --cflags gtk+-3.0` -DGDK_VERSION_MIN_REQIRED=GDK_VERSION_3_2 Window_management.c -o Window_management `pkg-config --libs gtk+-3.0` -lwren -lm */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <gtk/gtk.h>\n#include <unistd.h>\n#include \"wren.h\"\n\n/* C <=> Wren interface functions */\n\nWrenVM *vm;\n\nstatic void btnClicked(GtkWidget *button, gpointer user_data) {\n const gchar *label = gtk_button_get_label(GTK_BUTTON(button));\n wrenEnsureSlots(vm, 2);\n wrenGetVariable(vm, \"main\", \"GtkCallbacks\", 0);\n WrenHandle *method = wrenMakeCallHandle(vm, \"btnClicked(_)\");\n wrenSetSlotString(vm, 1, (const char *)label);\n wrenCall(vm, method);\n wrenReleaseHandle(vm, method);\n}\n\nvoid C_gtkWindowAllocate(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenSetSlotNewForeign(vm, 0, 0, sizeof(GtkWidget*));\n GtkWindowType type = (GtkWindowType)wrenGetSlotDouble(vm, 1);\n *window = gtk_window_new(type);\n}\n\nvoid C_gtkButtonBoxAllocate(WrenVM* vm) {\n GtkWidget **buttonBox = (GtkWidget **)wrenSetSlotNewForeign(vm, 0, 0, sizeof(GtkWidget*));\n GtkOrientation orientation = (GtkOrientation)wrenGetSlotDouble(vm, 1);\n *buttonBox = gtk_button_box_new(orientation);\n}\n\nvoid C_gtkButtonAllocate(WrenVM* vm) {\n GtkWidget **button = (GtkWidget **)wrenSetSlotNewForeign(vm, 0, 0, sizeof(GtkWidget*));\n const gchar *label = (const gchar *)wrenGetSlotString(vm, 1);\n *button = gtk_button_new_with_label(label);\n}\n\nvoid C_setTitle(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n const gchar *title = (const gchar *)wrenGetSlotString(vm, 1);\n gtk_window_set_title(GTK_WINDOW(*window), title);\n}\n\nvoid C_setDefaultSize(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gint width = (gint)wrenGetSlotDouble(vm, 1);\n gint height = (gint)wrenGetSlotDouble(vm, 2);\n gtk_window_set_default_size(GTK_WINDOW(*window), width, height);\n}\n\nvoid C_add(WrenVM* vm) {\n GtkWidget **container = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n GtkWidget **widget = (GtkWidget **)wrenGetSlotForeign(vm, 1);\n gtk_container_add(GTK_CONTAINER(*container), *widget);\n}\n\nvoid C_connectDestroy(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n g_signal_connect(*window, \"destroy\", G_CALLBACK(gtk_main_quit), NULL);\n}\n\nvoid C_showAll(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_widget_show_all(*window);\n}\n\nvoid C_iconify(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_window_iconify(GTK_WINDOW(*window));\n}\n\nvoid C_deiconify(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_window_deiconify(GTK_WINDOW(*window));\n}\n\nvoid C_maximize(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_window_maximize(GTK_WINDOW(*window));\n}\n\nvoid C_unmaximize(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_window_unmaximize(GTK_WINDOW(*window));\n}\n\nvoid C_move(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gint x = (gint)wrenGetSlotDouble(vm, 1);\n gint y = (gint)wrenGetSlotDouble(vm, 2);\n gtk_window_move(GTK_WINDOW(*window), x, y);\n}\n\nvoid C_resize(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gint width = (gint)wrenGetSlotDouble(vm, 1);\n gint height = (gint)wrenGetSlotDouble(vm, 2);\n gtk_window_resize(GTK_WINDOW(*window), width, height);\n}\n\nvoid C_hide(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_widget_hide(*window);\n}\n\nvoid C_destroy(WrenVM* vm) {\n GtkWidget **window = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gtk_widget_destroy(*window);\n}\n\nvoid C_setSpacing(WrenVM* vm) {\n GtkWidget **buttonBox = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n gint spacing = (gint)wrenGetSlotDouble(vm, 1);\n gtk_box_set_spacing(GTK_BOX(*buttonBox), spacing);\n}\n\nvoid C_setLayout(WrenVM* vm) {\n GtkWidget **buttonBox = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n GtkButtonBoxStyle layoutStyle = (GtkButtonBoxStyle)wrenGetSlotDouble(vm, 1);\n gtk_button_box_set_layout(GTK_BUTTON_BOX(*buttonBox), layoutStyle);\n}\n\nvoid C_connectClicked(WrenVM* vm) {\n GtkWidget **button = (GtkWidget **)wrenGetSlotForeign(vm, 0);\n g_signal_connect(*button, \"clicked\", G_CALLBACK(btnClicked), NULL);\n}\n\nvoid C_flush(WrenVM* vm) {\n gdk_display_flush(gdk_display_get_default());\n}\n\nvoid C_sleep(WrenVM* vm) {\n unsigned int secs = (unsigned int)wrenGetSlotDouble(vm, 1);\n sleep(secs);\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n WrenForeignClassMethods methods;\n methods.allocate = NULL;\n methods.finalize = NULL;\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"GtkWindow\") == 0) {\n methods.allocate = C_gtkWindowAllocate;\n } else if (strcmp(className, \"GtkButtonBox\") == 0) {\n methods.allocate = C_gtkButtonBoxAllocate;\n } else if (strcmp(className, \"GtkButton\") == 0) {\n methods.allocate = C_gtkButtonAllocate;\n }\n }\n return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"GtkWindow\") == 0) {\n if (!isStatic && strcmp(signature, \"title=(_)\") == 0) return C_setTitle;\n if (!isStatic && strcmp(signature, \"setDefaultSize(_,_)\") == 0) return C_setDefaultSize;\n if (!isStatic && strcmp(signature, \"add(_)\") == 0) return C_add;\n if (!isStatic && strcmp(signature, \"connectDestroy()\") == 0) return C_connectDestroy;\n if (!isStatic && strcmp(signature, \"showAll()\") == 0) return C_showAll;\n if (!isStatic && strcmp(signature, \"iconify()\") == 0) return C_iconify;\n if (!isStatic && strcmp(signature, \"deiconify()\") == 0) return C_deiconify;\n if (!isStatic && strcmp(signature, \"maximize()\") == 0) return C_maximize;\n if (!isStatic && strcmp(signature, \"unmaximize()\") == 0) return C_unmaximize;\n if (!isStatic && strcmp(signature, \"move(_,_)\") == 0) return C_move;\n if (!isStatic && strcmp(signature, \"resize(_,_)\") == 0) return C_resize;\n if (!isStatic && strcmp(signature, \"hide()\") == 0) return C_hide;\n if (!isStatic && strcmp(signature, \"destroy()\") == 0) return C_destroy;\n } else if (strcmp(className, \"GtkButtonBox\") == 0) {\n if (!isStatic && strcmp(signature, \"spacing=(_)\") == 0) return C_setSpacing;\n if (!isStatic && strcmp(signature, \"layout=(_)\") == 0) return C_setLayout;\n if (!isStatic && strcmp(signature, \"add(_)\") == 0) return C_add;\n } else if (strcmp(className, \"GtkButton\") == 0) {\n if (!isStatic && strcmp(signature, \"connectClicked()\") == 0) return C_connectClicked;\n } else if (strcmp(className, \"Gdk\") == 0) {\n if (isStatic && strcmp(signature, \"flush()\") == 0) return C_flush;\n } else if (strcmp(className, \"C\") == 0) {\n if (isStatic && strcmp(signature, \"sleep(_)\") == 0) return C_sleep;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nint main(int argc, char **argv) {\n gtk_init(&argc, &argv);\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignClassFn = &bindForeignClass;\n config.bindForeignMethodFn = &bindForeignMethod;\n vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Window_management.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n gtk_main();\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" } ]
Window-management
[ { "code": "---\ncategory:\n- Cellular automata\nfrom: http://rosettacode.org/wiki/Wireworld\nnote: Games\n", "language": "00-META" }, { "code": "[[wp:Wireworld|Wireworld]] is a cellular automaton with some similarities to [[Conway's Game of Life]]. \n\nIt is capable of doing sophisticated computations with appropriate programs \n(it is actually [[wp:Turing-complete|Turing complete]]), \nand is much simpler to program for.\n\nA Wireworld arena consists of a Cartesian grid of cells, \neach of which can be in one of four states. \nAll cell transitions happen simultaneously. \n\nThe cell transition rules are this:\n::{| class=wikitable\n|-\n! Input State\n! Output State\n! Condition\n|-\n| <tt>empty</tt>\n| <tt>empty</tt>\n|\n|-\n| <tt>electron&nbsp;head&nbsp;</tt>\n| <tt>electron&nbsp;tail&nbsp;</tt>\n|\n|-\n| <tt>electron&nbsp;tail&nbsp;</tt>\n| <tt>conductor</tt>\n|\n|-\n| valign=top | <tt>conductor</tt>\n| valign=top | <tt>electron&nbsp;head&nbsp;</tt>\n| if 1 or 2 cells in the [[wp:Moore neighborhood|neighborhood]] of the cell are in the state “<tt>electron head</tt>”\n|-\n| <tt>conductor</tt>\n| <tt>conductor</tt>\n| otherwise\n|}\n\n\n;Task:\nCreate a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using \"<tt>H</tt>\" for an electron head, \"<tt>t</tt>\" for a tail, \"<tt>.</tt>\" for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:\n<pre>\ntH.........\n. .\n ...\n. .\nHt.. ......\n</pre>\nWhile text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V allstates = ‘Ht. ’\nV head = allstates[0]\nV tail = allstates[1]\nV conductor = allstates[2]\nV empty = allstates[3]\n\nV w =\n|‘tH.........\n . .\n ...\n . .\n Ht.. ......’\n\nT WW\n [[Char]] world\n Int w\n Int h\n F (world, w, h)\n .world = world\n .w = w\n .h = h\n\nF readfile(f)\n V world = f.map(row -> row.rtrim(Array[Char](\"\\r\\n\")))\n V height = world.len\n V width = max(world.map(row -> row.len))\n V nonrow = [‘ ’(‘ ’ * width)‘ ’]\n V world2 = nonrow [+] world.map(row -> ‘ ’String(row).ljust(@width)‘ ’) [+] nonrow\n V world3 = world2.map(row -> Array(row))\n R WW(world3, width, height)\n\nF newcell(currentworld, x, y)\n V istate = currentworld[y][x]\n assert(istate C :allstates, ‘Wireworld cell set to unknown value \"#.\"’.format(istate))\n V ostate = :empty\n I istate == :head\n ostate = :tail\n E I istate == :tail\n ostate = :conductor\n E I istate == :empty\n ostate = :empty\n E\n V n = sum([(-1, -1), (-1, +0), (-1, +1),\n (+0, -1), (+0, +1),\n (+1, -1), (+1, +0), (+1, +1)].map((dx, dy) -> Int(@currentworld[@y + dy][@x + dx] == :head)))\n ostate = I n C 1..2 {:head} E :conductor\n R ostate\n\nF nextgen(ww)\n V (world, width, height) = ww\n V newworld = copy(world)\n L(x) 1 .. width\n L(y) 1 .. height\n newworld[y][x] = newcell(world, x, y)\n R WW(newworld, width, height)\n\nF world2string(ww)\n R ww.world[1 .< (len)-1].map(row -> (row[1 .< (len)-1]).join(‘’).rtrim((‘ ’, \"\\t\", \"\\r\", \"\\n\"))).join(\"\\n\")\n\nV ww = readfile(w.split(\"\\n\"))\n\nL(gen) 10\n print((\"\\n#3 \".format(gen))‘’(‘=’ * (ww.w - 4))\"\\n\")\n print(world2string(ww))\n ww = nextgen(ww)\n", "language": "11l" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Wireworld is\n type Cell is (' ', 'H', 't', '.');\n type Board is array (Positive range <>, Positive range <>) of Cell;\n -- Perform one transition of the cellular automation\n procedure Wireworld (State : in out Board) is\n function \"abs\" (Left : Cell) return Natural is\n begin\n if Left = 'H' then\n return 1;\n else\n return 0;\n end if;\n end \"abs\";\n Above : array (State'Range (2)) of Cell := (others => ' ');\n Left : Cell := ' ';\n Current : Cell;\n begin\n for I in State'First (1) + 1..State'Last (1) - 1 loop\n for J in State'First (2) + 1..State'Last (2) - 1 loop\n Current := State (I, J);\n case Current is\n when ' ' =>\n null;\n when 'H' =>\n State (I, J) := 't';\n when 't' =>\n State (I, J) := '.';\n when '.' =>\n if abs Above ( J - 1) + abs Above ( J) + abs Above ( J + 1) +\n abs Left + abs State (I, J + 1) +\n abs State (I + 1, J - 1) + abs State (I + 1, J) + abs State (I + 1, J + 1)\n in 1..2 then\n State (I, J) := 'H';\n else\n State (I, J) := '.';\n end if;\n end case;\n Above (J - 1) := Left;\n Left := Current;\n end loop;\n end loop;\n end Wireworld;\n -- Print state of the automation\n procedure Put (State : Board) is\n begin\n for I in State'First (1) + 1..State'Last (1) - 1 loop\n for J in State'First (2) + 1..State'Last (2) - 1 loop\n case State (I, J) is\n when ' ' => Put (' ');\n when 'H' => Put ('H');\n when 't' => Put ('t');\n when '.' => Put ('.');\n end case;\n end loop;\n New_Line;\n end loop;\n end Put;\n Oscillator : Board := (\" \", \" tH \", \" . .... \", \" .. \", \" \");\nbegin\n for Step in 0..9 loop\n Put_Line (\"Step\" & Integer'Image (Step) & \" ---------\"); Put (Oscillator);\n Wireworld (Oscillator);\n end loop;\nend Test_Wireworld;\n", "language": "Ada" }, { "code": "CO\nWireworld implementation.\nCO\n\nPROC exception = ([]STRING args)VOID:(\n putf(stand error, ($\"Exception\"$, $\", \"g$, args, $l$));\n stop\n);\n\nPROC assertion error = (STRING message)VOID:exception((\"assertion error\", message));\n\nMODE CELL = CHAR;\nMODE WORLD = FLEX[0, 0]CELL;\nCELL head=\"H\", tail=\"t\", conductor=\".\", empty = \" \";\nSTRING all states := empty;\n\nBOOL wrap = FALSE; # is the world round? #\n\nSTRING nl := REPR 10;\n\nSTRING in string :=\n \"tH.........\"+nl+\n \". .\"+nl+\n \" ...\"+nl+\n \". .\"+nl+\n \"Ht.. ......\"+nl\n;\n\nOP +:= = (REF FLEX[]FLEX[]CELL lines, FLEX[]CELL line)VOID:(\n [UPB lines + 1]FLEX[0]CELL new lines;\n new lines[:UPB lines]:=lines;\n lines := new lines;\n lines[UPB lines]:=line\n);\n\nPROC read file = (REF FILE in file)WORLD: (\n # file > initial world configuration\" #\n FLEX[0]CELL line;\n FLEX[0]FLEX[0]CELL lines;\n INT upb x:=0, upb y := 0;\n BEGIN\n # on physical file end(in file, exit read line); #\n make term(in file, nl);\n FOR x TO 5 DO\n get(in file, (line, new line));\n upb x := x;\n IF UPB line > upb y THEN upb y := UPB line FI;\n lines +:= line\n OD;\n exit read line: SKIP\n END;\n [upb x, upb y]CELL out;\n FOR x TO UPB out DO\n out[x,]:=lines[x]+\" \"*(upb y-UPB lines[x])\n OD;\n out\n);\n\nPROC new cell = (WORLD current world, INT x, y)CELL: (\n CELL istate := current world[x, y];\n IF INT pos; char in string (istate, pos, all states); pos IS REF INT(NIL) THEN\n assertion error(\"Wireworld cell set to unknown value \"+istate) FI;\n IF istate = head THEN\n tail\n ELIF istate = tail THEN\n conductor\n ELIF istate = empty THEN\n empty\n ELSE # istate = conductor #\n [][]INT dxy list = ( (-1,-1), (-1,+0), (-1,+1),\n (+0,-1), (+0,+1),\n (+1,-1), (+1,+0), (+1,+1) );\n INT n := 0;\n FOR enum dxy TO UPB dxy list DO\n []INT dxy = dxy list[enum dxy];\n IF wrap THEN\n INT px = ( x + dxy[1] - 1 ) MOD 1 UPB current world + 1;\n INT py = ( y + dxy[2] - 1 ) MOD 2 UPB current world + 1;\n n +:= ABS (current world[px, py] = head)\n ELSE\n INT px = x + dxy[1];\n INT py = y + dxy[2];\n IF px >= 1 LWB current world AND px <= 1 UPB current world AND\n py >= 2 LWB current world AND py <= 2 UPB current world THEN\n n +:= ABS (current world[px, py] = head)\n FI\n FI\n OD;\n IF 1 <= n AND n <= 2 THEN head ELSE conductor FI\n FI\n);\n\nPROC next gen = (WORLD world)WORLD:(\n # compute next generation of wireworld #\n WORLD new world := world;\n FOR x TO 1 UPB world DO\n FOR y TO 2 UPB world DO\n new world[x,y] := new cell(world, x, y)\n OD\n OD;\n new world\n);\n\nPROC world2string = (WORLD world) STRING:(\n STRING out:=\"\";\n FOR x TO UPB world DO\n out +:= world[x,]+nl\n OD;\n out\n);\n\nFILE in file;\nassociate(in file, in string);\n\nWORLD ww := read file(in file);\nclose(in file);\n\nFOR gen TO 10 DO\n printf ( ($lg(-3)\" \"$, gen-1, $g$,\"=\"* (2 UPB ww-4), $l$));\n print ( world2string(ww) );\n ww := next gen(ww)\nOD\n", "language": "ALGOL-68" }, { "code": "#SingleInstance, Force\n#NoEnv\nSetBatchLines, -1\nFile := \"Wireworld.txt\"\nCellSize := 20\nCellSize2 := CellSize - 2\nC1 := 0xff000000\nC2 := 0xff0066ff\nC3 := 0xffd40055\nC4 := 0xffffcc00\n\nif (!FileExist(File)) {\n\tMsgBox, % \"File(\" File \") is not present.\"\n\tExitApp\n}\n\n; Uncomment if Gdip.ahk is not in your standard library\n; #Include, Gdip.ahk\nIf !pToken := Gdip_Startup(){\n\tMsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system.\n\tExitApp\n}\nOnExit, Exit\n\nA := [], Width := 0\nLoop, Read, % File\n{\n\tRow := A_Index\n\tLoop, Parse, A_LoopReadLine\n\t{\n\t\tif (A_Index > Width)\n\t\t\tWidth := A_Index\n\t\tif (A_LoopField = A_Space)\n\t\t\tcontinue\n\t\tA[Row, A_Index] := A_LoopField\n\t}\n}\n\nWidth := Width * CellSize + 2 * CellSize\n, Height := Row * CellSize + 2 * CellSize\n, Row := \"\"\n, TopLeftX := (A_ScreenWidth - Width) // 2\n, TopLeftY := (A_ScreenHeight - Height) // 2\n\nGui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs\nGui, 1: Show, NA\n\nhwnd1 := WinExist()\n, hbm := CreateDIBSection(Width, Height)\n, hdc := CreateCompatibleDC()\n, obm := SelectObject(hdc, hbm)\n, G := Gdip_GraphicsFromHDC(hdc)\n, Gdip_SetSmoothingMode(G, 4)\n\nLoop {\n\tpBrush := Gdip_BrushCreateSolid(C1)\n\t, Gdip_FillRectangle(G, pBrush, 0, 0, Width, Height)\n\t, Gdip_DeleteBrush(pBrush)\n\n\tfor RowNum, Row in A\n\t\tfor CellNum, Cell in Row\n\t\t\tC := Cell = \"H\" ? C2 : Cell = \"t\" ? C3 : C4\n\t\t\t, pBrush := Gdip_BrushCreateSolid(C)\n\t\t\t, Gdip_FillRectangle(G, pBrush, CellNum * CellSize + 1, RowNum * CellSize - 2, CellSize2, CellSize2)\n\t\t\t, Gdip_DeleteBrush(pBrush)\n\t\n\n\tUpdateLayeredWindow(hwnd1, hdc, TopLeftX, TopLeftY, Width, Height)\n\t, Gdip_GraphicsClear(G)\n\t, A := NextState(A)\n\tSleep, 600\n}\n\nNextState(A) {\n\tB := {}\n\tfor RowNum, Row in A {\n\t\tfor CellNum, Cell in Row {\n\t\t\tif (Cell = \"H\")\n\t\t\t\tB[RowNum, CellNum] := \"t\"\n\t\t\telse if (Cell = \"t\")\n\t\t\t\tB[RowNum, CellNum] := \".\"\n\t\t\telse if (Cell = \".\") {\n\t\t\t\tH_Count := 0\n\t\t\t\tLoop 3 {\n\t\t\t\t\tY := RowNum - 2 + A_Index\n\t\t\t\t\tLoop, 3 {\n\t\t\t\t\t\tX := CellNum - 2 + A_Index\n\t\t\t\t\t\tif (A[Y, X] = \"H\")\n\t\t\t\t\t\t\tH_Count++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (H_Count = 1 || H_Count = 2)\n\t\t\t\t\tB[RowNum, CellNum] := \"H\"\n\t\t\t\telse\n\t\t\t\t\tB[RowNum, CellNum] := \".\"\n\t\t\t}\n\t\t}\n\t}\n\treturn B\n}\n\np::Pause\n\nEsc::\nExit:\nGdip_Shutdown(pToken)\nExitApp\n", "language": "AutoHotkey" }, { "code": "$ww = \"\"\n$ww &= \"tH.........\" & @CR\n$ww &= \". . \" & @CR\n$ww &= \" ... \" & @CR\n$ww &= \". . \" & @CR\n$ww &= \"Ht.. ......\"\n$rows = StringSplit($ww, @CR)\n$cols = StringSplit($rows[1], \"\")\nGlobal $Wireworldarray[$rows[0]][$cols[0]]\nFor $I = 1 To $rows[0]\n\t$cols = StringSplit($rows[$I], \"\")\n\tFor $k = 1 To $cols[0]\n\t\t$Wireworldarray[$I - 1][$k - 1] = $cols[$k]\n\tNext\nNext\nWireworld($Wireworldarray)\nFunc Wireworld($array)\n\tLocal $labelarray = $array\n\tLocal $Top = 0, $Left = 0\n\t$hFui = GUICreate(\"Wireworld\", UBound($array, 2) * 25, UBound($array) * 25)\n\tFor $I = 0 To UBound($array) - 1\n\t\tFor $k = 0 To UBound($array, 2) - 1\n\t\t\tSwitch $array[$I][$k]\n\t\t\t\tCase \"t\" ; Tail\n\t\t\t\t\t$labelarray[$I][$k] = GUICtrlCreateButton(\"\", $Left, $Top, 25, 25)\n\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000)\n\t\t\t\tCase \"h\" ; Head\n\t\t\t\t\t$labelarray[$I][$k] = GUICtrlCreateButton(\"\", $Left, $Top, 25, 25)\n\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF)\n\t\t\t\tCase \".\" ; Conductor\n\t\t\t\t\t$labelarray[$I][$k] = GUICtrlCreateButton(\"\", $Left, $Top, 25, 25)\n\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00)\n\t\t\t\tCase \" \" ; Empty\n\t\t\t\t\t$labelarray[$I][$k] = GUICtrlCreateButton(\"\", $Left, $Top, 25, 25)\n\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0x000000)\n\t\t\tEndSwitch\n\t\t\t$Left += 25\n\t\tNext\n\t\t$Left = 0\n\t\t$Top += 25\n\tNext\n\tGUISetState()\n\tLocal $nextsteparray = $array\n\tWhile 1\n\t\t$msg = GUIGetMsg()\n\t\t$array = $nextsteparray\n\t\tSleep(250)\n\t\tFor $I = 0 To UBound($array) - 1\n\t\t\tFor $k = 0 To UBound($array, 2) - 1\n\t\t\t\tIf $array[$I][$k] = \" \" Then ContinueLoop\n\t\t\t\tIf $array[$I][$k] = \"h\" Then $nextsteparray[$I][$k] = \"t\"\n\t\t\t\tIf $array[$I][$k] = \"t\" Then $nextsteparray[$I][$k] = \".\"\n\t\t\t\tIf $array[$I][$k] = \".\" Then\n\t\t\t\t\t$counter = 0\n\t\t\t\t\tIf $I - 1 >= 0 Then ; Top\n\t\t\t\t\t\tIf $array[$I - 1][$k] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $k - 1 >= 0 Then ; left\n\t\t\t\t\t\tIf $array[$I][$k - 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $I + 1 <= UBound($array) - 1 Then ; Bottom\n\t\t\t\t\t\tIf $array[$I + 1][$k] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $k + 1 <= UBound($array, 2) - 1 Then ;Right\n\t\t\t\t\t\tIf $array[$I][$k + 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $I - 1 >= 0 And $k - 1 >= 0 Then ; left Top\n\t\t\t\t\t\tIf $array[$I - 1][$k - 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $I + 1 <= UBound($array) - 1 And $k + 1 <= UBound($array, 2) - 1 Then ; Right Bottom\n\t\t\t\t\t\tIf $array[$I + 1][$k + 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $I + 1 <= UBound($array) - 1 And $k - 1 >= 0 Then ;Left Bottom\n\t\t\t\t\t\tIf $array[$I + 1][$k - 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $I - 1 >= 0 And $k + 1 <= UBound($array, 2) - 1 Then ; Top Right\n\t\t\t\t\t\tIf $array[$I - 1][$k + 1] = \"h\" Then $counter += 1\n\t\t\t\t\tEndIf\n\t\t\t\t\tIf $counter = 1 Or $counter = 2 Then $nextsteparray[$I][$k] = \"h\"\n\t\t\t\tEndIf\n\t\t\tNext\n\t\tNext\n\t\tFor $I = 0 To UBound($nextsteparray) - 1\n\t\t\tFor $k = 0 To UBound($nextsteparray, 2) - 1\n\t\t\t\tSwitch $nextsteparray[$I][$k]\n\t\t\t\t\tCase \"t\" ; Tail\n\t\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000)\n\t\t\t\t\tCase \"h\" ; Head\n\t\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF)\n\t\t\t\t\tCase \".\" ; Conductor\n\t\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00)\n\t\t\t\t\tCase \" \" ; Empty\n\t\t\t\t\t\tGUICtrlSetBkColor($labelarray[$I][$k], 0x000000)\n\t\t\t\tEndSwitch\n\t\t\t\t$Left += 25\n\t\t\tNext\n\t\t\t$Left = 0\n\t\t\t$Top += 25\n\t\tNext\n\t\tIf $msg = -3 Then Exit\n\tWEnd\nEndFunc ;==>Wireworld\n", "language": "AutoIt" }, { "code": " Size% = 20\n DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1)\n\n VDU 23,22,Size%*8;Size%*8;64,64,16,0\n OFF\n\n DATA \"tH.........\"\n DATA \". . \"\n DATA \" ... \"\n DATA \". . \"\n DATA \"Ht.. ......\"\n\n FOR Y% = 12 TO 8 STEP -1\n READ A$\n FOR X% = 1 TO LEN(A$)\n P&(X%+4, Y%) = ASCMID$(A$, X%, 1) AND 15\n NEXT\n NEXT Y%\n\n COLOUR 8,0,0,255 : REM Electron head = blue\n COLOUR 4,255,0,0 : REM Electron tail = red\n COLOUR 14,255,200,0 : REM Conductor orange\n\n REPEAT\n FOR Y% = 1 TO Size%-2\n FOR X% = 1 TO Size%-2\n IF P&(X%,Y%)<>Q&(X%,Y%) GCOL P&(X%,Y%) : PLOT X%*16, Y%*16\n CASE P&(X%,Y%) OF\n WHEN 0: Q&(X%,Y%) = 0\n WHEN 8: Q&(X%,Y%) = 4\n WHEN 4: Q&(X%,Y%) = 14\n WHEN 14:\n T% = (P&(X%+1,Y%)=8) + (P&(X%+1,Y%+1)=8) + (P&(X%+1,Y%-1)=8) + \\\n \\ (P&(X%-1,Y%)=8) + (P&(X%-1,Y%+1)=8) + (P&(X%-1,Y%-1)=8) + \\\n \\ (P&(X%,Y%-1)=8) + (P&(X%,Y%+1)=8)\n IF T%=-1 OR T%=-2 THEN Q&(X%,Y%) = 8 ELSE Q&(X%,Y%) = 14\n ENDCASE\n NEXT\n NEXT Y%\n SWAP P&(), Q&()\n WAIT 50\n UNTIL FALSE\n", "language": "BBC-BASIC" }, { "code": "/* 2009-09-27 <[email protected]> */\n#define ANIMATE_VT100_POSIX\n#include <stdio.h>\n#include <string.h>\n#ifdef ANIMATE_VT100_POSIX\n#include <time.h>\n#endif\n\nchar world_7x14[2][512] = {\n {\n \"+-----------+\\n\"\n \"|tH.........|\\n\"\n \"|. . |\\n\"\n \"| ... |\\n\"\n \"|. . |\\n\"\n \"|Ht.. ......|\\n\"\n \"+-----------+\\n\"\n }\n};\n\nvoid next_world(const char *in, char *out, int w, int h)\n{\n int i;\n\n for (i = 0; i < w*h; i++) {\n switch (in[i]) {\n case ' ': out[i] = ' '; break;\n case 't': out[i] = '.'; break;\n case 'H': out[i] = 't'; break;\n case '.': {\n int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +\n (in[i-1] == 'H') + (in[i+1] == 'H') +\n (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');\n out[i] = (hc == 1 || hc == 2) ? 'H' : '.';\n break;\n }\n default:\n out[i] = in[i];\n }\n }\n out[i] = in[i];\n}\n\nint main()\n{\n int f;\n\n for (f = 0; ; f = 1 - f) {\n puts(world_7x14[f]);\n next_world(world_7x14[f], world_7x14[1-f], 14, 7);\n#ifdef ANIMATE_VT100_POSIX\n printf(\"\\x1b[%dA\", 8);\n printf(\"\\x1b[%dD\", 14);\n {\n static const struct timespec ts = { 0, 100000000 };\n nanosleep(&ts, 0);\n }\n#endif\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <ggi/ggi.h>\n#include <set>\n#include <map>\n#include <utility>\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <unistd.h> // for usleep\n\nenum cell_type { none, wire, head, tail };\n\n// *****************\n// * display class *\n// *****************\n\n// this is just a small wrapper for the ggi interface\n\nclass display\n{\npublic:\n display(int sizex, int sizey, int pixsizex, int pixsizey,\n ggi_color* colors);\n ~display()\n {\n ggiClose(visual);\n ggiExit();\n }\n\n void flush();\n bool keypressed() { return ggiKbhit(visual); }\n void clear();\n void putpixel(int x, int y, cell_type c);\nprivate:\n ggi_visual_t visual;\n int size_x, size_y;\n int pixel_size_x, pixel_size_y;\n ggi_pixel pixels[4];\n};\n\ndisplay::display(int sizex, int sizey, int pixsizex, int pixsizey,\n ggi_color* colors):\n pixel_size_x(pixsizex),\n pixel_size_y(pixsizey)\n{\n if (ggiInit() < 0)\n {\n std::cerr << \"couldn't open ggi\\n\";\n exit(1);\n }\n\n visual = ggiOpen(NULL);\n if (!visual)\n {\n ggiPanic(\"couldn't open visual\\n\");\n }\n\n ggi_mode mode;\n if (ggiCheckGraphMode(visual, sizex, sizey,\n GGI_AUTO, GGI_AUTO, GT_4BIT,\n &mode) != 0)\n {\n if (GT_DEPTH(mode.graphtype) < 2) // we need 4 colors!\n ggiPanic(\"low-color displays are not supported!\\n\");\n }\n if (ggiSetMode(visual, &mode) != 0)\n {\n ggiPanic(\"couldn't set graph mode\\n\");\n }\n ggiAddFlags(visual, GGIFLAG_ASYNC);\n\n size_x = mode.virt.x;\n size_y = mode.virt.y;\n\n for (int i = 0; i < 4; ++i)\n pixels[i] = ggiMapColor(visual, colors+i);\n}\n\nvoid display::flush()\n{\n // set the current display frame to the one we have drawn to\n ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));\n\n // flush the current visual\n ggiFlush(visual);\n\n // try to set a different frame for drawing (errors are ignored; if\n // setting the new frame fails, the current one will be drawn upon,\n // with the only adverse effect being some flickering).\n ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));\n}\n\nvoid display::clear()\n{\n ggiSetGCForeground(visual, pixels[0]);\n ggiDrawBox(visual, 0, 0, size_x, size_y);\n}\n\nvoid display::putpixel(int x, int y, cell_type cell)\n{\n // this draws a logical pixel (i.e. a rectangle of size pixel_size_x\n // times pixel_size_y), not a physical pixel\n ggiSetGCForeground(visual, pixels[cell]);\n ggiDrawBox(visual,\n x*pixel_size_x, y*pixel_size_y,\n pixel_size_x, pixel_size_y);\n}\n\n// *****************\n// * the wireworld *\n// *****************\n\n// initialized to an empty wireworld\nclass wireworld\n{\npublic:\n void set(int posx, int posy, cell_type type);\n void draw(display& destination);\n void step();\nprivate:\n typedef std::pair<int, int> position;\n typedef std::set<position> position_set;\n typedef position_set::iterator positer;\n position_set wires, heads, tails;\n};\n\nvoid wireworld::set(int posx, int posy, cell_type type)\n{\n position p(posx, posy);\n wires.erase(p);\n heads.erase(p);\n tails.erase(p);\n switch(type)\n {\n case head:\n heads.insert(p);\n break;\n case tail:\n tails.insert(p);\n break;\n case wire:\n wires.insert(p);\n break;\n }\n}\n\nvoid wireworld::draw(display& destination)\n{\n destination.clear();\n for (positer i = heads.begin(); i != heads.end(); ++i)\n destination.putpixel(i->first, i->second, head);\n for (positer i = tails.begin(); i != tails.end(); ++i)\n destination.putpixel(i->first, i->second, tail);\n for (positer i = wires.begin(); i != wires.end(); ++i)\n destination.putpixel(i->first, i->second, wire);\n destination.flush();\n}\n\nvoid wireworld::step()\n{\n std::map<position, int> new_heads;\n for (positer i = heads.begin(); i != heads.end(); ++i)\n for (int dx = -1; dx <= 1; ++dx)\n for (int dy = -1; dy <= 1; ++dy)\n {\n position pos(i->first + dx, i->second + dy);\n if (wires.count(pos))\n new_heads[pos]++;\n }\n wires.insert(tails.begin(), tails.end());\n tails.swap(heads);\n heads.clear();\n for (std::map<position, int>::iterator i = new_heads.begin();\n i != new_heads.end();\n ++i)\n {\n// std::cout << i->second;\n if (i->second < 3)\n {\n wires.erase(i->first);\n heads.insert(i->first);\n }\n }\n}\n\nggi_color colors[4] =\n {{ 0x0000, 0x0000, 0x0000 }, // background: black\n { 0x8000, 0x8000, 0x8000 }, // wire: white\n { 0xffff, 0xffff, 0x0000 }, // electron head: yellow\n { 0xffff, 0x0000, 0x0000 }}; // electron tail: red\n\nint main(int argc, char* argv[])\n{\n int display_x = 800;\n int display_y = 600;\n int pixel_x = 5;\n int pixel_y = 5;\n\n if (argc < 2)\n {\n std::cerr << \"No file name given!\\n\";\n return 1;\n }\n\n // assume that the first argument is the name of a file to parse\n std::ifstream f(argv[1]);\n wireworld w;\n std::string line;\n int line_number = 0;\n while (std::getline(f, line))\n {\n for (int col = 0; col < line.size(); ++col)\n {\n switch (line[col])\n {\n case 'h': case 'H':\n w.set(col, line_number, head);\n break;\n case 't': case 'T':\n w.set(col, line_number, tail);\n break;\n case 'w': case 'W': case '.':\n w.set(col, line_number, wire);\n break;\n default:\n std::cerr << \"unrecognized character: \" << line[col] << \"\\n\";\n return 1;\n case ' ':\n ; // no need to explicitly set this, so do nothing\n }\n }\n ++line_number;\n }\n\n display d(display_x, display_y, pixel_x, pixel_y, colors);\n\n w.draw(d);\n\n while (!d.keypressed())\n {\n usleep(100000);\n w.step();\n w.draw(d);\n }\n std::cout << std::endl;\n}\n", "language": "C++" }, { "code": "abstract class Cell(shared Character char) of emptyCell | head | tail | conductor {\n\n shared Cell output({Cell*} neighbors) =>\n switch (this)\n case (emptyCell) emptyCell\n case (head) tail\n case (tail) conductor\n case (conductor) (neighbors.count(head.equals) in 1..2 then head else conductor);\n\n string => char.string;\n}\n\nobject emptyCell extends Cell(' ') {}\n\nobject head extends Cell('H') {}\n\nobject tail extends Cell('t') {}\n\nobject conductor extends Cell('.') {}\n\nMap<Character,Cell> cellsByChar = map { for (cell in `Cell`.caseValues) cell.char->cell };\n\nclass Wireworld(String data) {\n\n value lines = data.lines;\n\n value width = max(lines*.size);\n value height = lines.size;\n\n function toIndex(Integer x, Integer y) => x + y * width;\n\n variable value currentState = Array.ofSize(width * height, emptyCell);\n variable value nextState = Array.ofSize(width * height, emptyCell);\n\n for (j->line in lines.indexed) {\n for (i->char in line.indexed) {\n currentState[toIndex(i, j)] = cellsByChar[char] else emptyCell;\n }\n }\n\n value emptyGrid = Array.ofSize(width * height, emptyCell);\n void clear(Array<Cell> cells) => emptyGrid.copyTo(cells);\n\n shared void update() {\n clear(nextState);\n for(j in 0:height) {\n for(i in 0:width) {\n if(exists cell = currentState[toIndex(i, j)]) {\n value nextCell = cell.output(neighborhood(currentState, i, j));\n nextState[toIndex(i, j)] = nextCell;\n }\n }\n }\n value temp = currentState;\n currentState = nextState;\n nextState = temp;\n }\n\n shared void display() {\n for (row in currentState.partition(width)) {\n print(\"\".join(row));\n }\n }\n\n shared {Cell*} neighborhood(Array<Cell> grid, Integer x, Integer y) => {\n for (j in y - 1..y + 1)\n for (i in x - 1..x + 1)\n if(i in 0:width && j in 0:height)\n grid[toIndex(i, j)]\n }.coalesced;\n\n}\n\nshared void run() {\n value data = \"tH.........\n . .\n ...\n . .\n Ht.. ......\";\n\n value world = Wireworld(data);\n\n variable value generation = 0;\n\n void display() {\n print(\"generation: ``generation``\");\n world.display();\n }\n\n display();\n\n while (true) {\n if (exists input = process.readLine(), input.lowercased == \"q\") {\n return;\n }\n world.update();\n generation++;\n display();\n\n }\n}\n", "language": "Ceylon" }, { "code": "(defun electron-neighbors (wireworld row col)\n (destructuring-bind (rows cols) (array-dimensions wireworld)\n (loop for off-row from (max 0 (1- row)) to (min (1- rows) (1+ row)) sum\n (loop for off-col from (max 0 (1- col)) to (min (1- cols) (1+ col)) count\n (and (not (and (= off-row row) (= off-col col)))\n (eq 'electron-head (aref wireworld off-row off-col)))))))\n\n(defun wireworld-next-generation (wireworld)\n (destructuring-bind (rows cols) (array-dimensions wireworld)\n (let ((backing (make-array (list rows cols))))\n (do ((c 0 (if (= c (1- cols)) 0 (1+ c)))\n (r 0 (if (= c (1- cols)) (1+ r) r)))\n ((= r rows))\n (setf (aref backing r c) (aref wireworld r c)))\n (do ((c 0 (if (= c (1- cols)) 0 (1+ c)))\n (r 0 (if (= c (1- cols)) (1+ r) r)))\n ((= r rows))\n (setf (aref wireworld r c)\n (case (aref backing r c)\n (electron-head 'electron-tail)\n (electron-tail 'conductor)\n (conductor (case (electron-neighbors backing r c)\n ((1 2) 'electron-head)\n (otherwise 'conductor)))\n (otherwise nil)))))))\n\n(defun print-wireworld (wireworld)\n (destructuring-bind (rows cols) (array-dimensions wireworld)\n (do ((r 0 (1+ r)))\n ((= r rows))\n (do ((c 0 (1+ c)))\n ((= c cols))\n (format t \"~C\" (case (aref wireworld r c)\n (electron-head #\\H)\n (electron-tail #\\t)\n (conductor #\\.)\n (otherwise #\\Space))))\n (format t \"~&\"))))\n\n(defun wireworld-show-gens (wireworld n)\n (dotimes (m n)\n (terpri)\n (wireworld-next-generation wireworld)\n (print-wireworld wireworld)))\n\n(defun ww-char-to-symbol (char)\n (ecase char\n (#\\Space 'nil)\n (#\\. 'conductor)\n (#\\t 'electron-tail)\n (#\\H 'electron-head)))\n\n(defun make-wireworld (image)\n \"Make a wireworld grid from a list of strings (rows) of equal length\n(columns), each character being ' ', '.', 'H', or 't'.\"\n (make-array (list (length image) (length (first image)))\n :initial-contents\n (mapcar (lambda (s) (map 'list #'ww-char-to-symbol s)) image)))\n\n(defun make-rosetta-wireworld ()\n (make-wireworld '(\"tH.........\"\n \". . \"\n \" ... \"\n \". . \"\n \"Ht.. ......\")))\n", "language": "Common-Lisp" }, { "code": "import std.stdio, std.algorithm;\n\nvoid wireworldStep(char[][] W1, char[][] W2) pure nothrow @safe @nogc {\n foreach (immutable r; 1 .. W1.length - 1)\n foreach (immutable c; 1 .. W1[0].length - 1)\n switch (W1[r][c]) {\n case 'H': W2[r][c] = 't'; break;\n case 't': W2[r][c] = '.'; break;\n case '.':\n int nH = 0;\n foreach (sr; -1 .. 2)\n foreach (sc; -1 .. 2)\n nH += W1[r + sr][c + sc] == 'H';\n W2[r][c] = (nH == 1 || nH == 2) ? 'H' : '.';\n break;\n default:\n }\n}\n\nvoid main() {\n auto world = [\" \".dup,\n \" tH \".dup,\n \" . .... \".dup,\n \" .. \".dup,\n \" \".dup];\n\n char[][] world2;\n foreach (row; world)\n world2 ~= row.dup;\n\n foreach (immutable step; 0 .. 7) {\n writefln(\"\\nStep %d: ------------\", step);\n foreach (row; world[1 .. $ - 1])\n row[1 .. $ - 1].writeln;\n wireworldStep(world, world2);\n swap(world, world2);\n }\n}\n", "language": "D" }, { "code": "program Wireworld;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils,\n System.IOUtils;\n\nvar\n rows, cols: Integer;\n rx, cx: Integer;\n mn: TArray<Integer>;\n\nprocedure Print(grid: TArray<byte>);\nbegin\n writeln(string.Create('_', cols * 2), #10);\n\n for var r := 1 to rows do\n begin\n for var c := 1 to cols do\n begin\n if grid[r * cx + c] = 0 then\n write(' ')\n else\n write(' ', chr(grid[r * cx + c]));\n end;\n writeln;\n end;\nend;\n\nprocedure Step(var dst: TArray<byte>; src: TArray<byte>);\nbegin\n for var r := 1 to rows do\n begin\n for var c := 1 to cols do\n begin\n var x := r * cx + c;\n dst[x] := src[x];\n\n case chr(dst[x]) of\n 'H':\n dst[x] := ord('t');\n 't':\n dst[x] := ord('.');\n '.':\n begin\n var nn := 0;\n for var n in mn do\n if src[x + n] = ord('H') then\n inc(nn);\n if (nn = 1) or (nn = 2) then\n dst[x] := ord('H');\n end;\n end;\n end;\n end;\nend;\n\nprocedure Main();\nconst\n CONFIG_FILE = 'ww.config';\nbegin\n\n if not FileExists(CONFIG_FILE) then\n begin\n Writeln(CONFIG_FILE, ' not exist');\n exit;\n end;\n\n var srcRows := TFile.ReadAllLines(CONFIG_FILE);\n\n rows := length(srcRows);\n\n cols := 0;\n for var r in srcRows do\n begin\n if Length(r) > cols then\n cols := length(r);\n end;\n\n rx := rows + 2;\n cx := cols + 2;\n\n mn := [-cx - 1, -cx, -cx + 1, -1, 1, cx - 1, cx, cx + 1];\n\n var _odd: TArray<byte>;\n var _even: TArray<byte>;\n\n SetLength(_odd, rx * cx);\n SetLength(_even, rx * cx);\n\n FillChar(_odd[0], rx * cx, 0);\n FillChar(_even[0], rx * cx, 0);\n\n for var i := 0 to High(srcRows) do\n begin\n var r := srcRows[i];\n\n var offset := (i + 1) * cx + 1;\n for var j := 1 to length(r) do\n _odd[offset + j - 1] := ord(r[j]);\n end;\n\n while True do\n begin\n print(_odd);\n step(_even, _odd);\n Readln;\n\n print(_even);\n step(_odd, _even);\n Readln;\n end;\nend;\n\nbegin\n Main;\n\n {$IFNDEF UNIX} readln; {$ENDIF}\nend.\n", "language": "Delphi" }, { "code": "sys topleft\nglobal m[] nc .\nbackground 777\n#\nproc show . .\n clear\n scale = 100 / nc\n sz = scale * 0.95\n for i to len m[]\n x = (i - 1) mod nc\n y = (i - 1) div nc\n move x * scale y * scale\n if m[i] = 0\n color 000\n elif m[i] = 1\n color 980\n elif m[i] = 2\n color 338\n else\n color 833\n .\n rect sz sz\n .\n.\nproc read . .\n s$ = input\n nc = len s$ + 2\n for i to nc\n m[] &= 0\n .\n repeat\n m[] &= 0\n for c$ in strchars s$\n if c$ = \".\"\n m[] &= 1\n elif c$ = \"H\"\n m[] &= 2\n elif c$ = \"t\"\n m[] &= 3\n else\n m[] &= 0\n .\n .\n for i to nc - len s$ - 1\n m[] &= 0\n .\n s$ = input\n until s$ = \"\"\n .\n for i to nc\n m[] &= 0\n .\n.\nread\n#\nlen mn[] len m[]\n#\nproc update . .\n for i to len m[]\n if m[i] = 2\n mn[i] = 3\n elif m[i] = 3\n mn[i] = 1\n elif m[i] = 1\n s = 0\n for dx = -1 to 1\n for dy = -1 to 1\n ix = i + dy * nc + dx\n s += if m[ix] = 2\n .\n .\n if s = 2 or s = 1\n mn[i] = 2\n else\n mn[i] = 1\n .\n .\n .\n swap mn[] m[]\n.\non timer\n update\n show\n timer 0.5\n.\nshow\ntimer 0.5\n#\ninput_data\ntH.........\n. .\n ...\n. .\nHt.. ......\n", "language": "EasyLang" }, { "code": "import system'routines;\nimport extensions;\nimport cellular;\n\nconst string sample =\n\" tH......\n. ......\n ...Ht... .\n ....\n . .....\n ....\n ......tH .\n. ......\n ...Ht...\";\n\nconst string conductorLabel = \".\";\nconst string headLabel = \"H\";\nconst string tailLabel = \"t\";\nconst string emptyLabel = \" \";\n\nconst int empty = 0;\nconst int conductor = 1;\nconst int electronHead = 2;\nconst int electronTail = 3;\n\nwireWorldRuleSet = new RuleSet\n{\n int proceed(Space s, int x, int y)\n {\n int cell := s.at(x, y);\n\n cell =>\n conductor\n {\n int number := s.LiveCell(x, y, electronHead);\n if (number == 1 || number == 2)\n {\n ^ electronHead\n }\n else\n {\n ^ conductor\n }\n }\n electronHead\n {\n ^ electronTail\n }\n electronTail\n {\n ^ conductor\n }\n !{\n ^ cell\n }\n }\n};\n\nsealed class Model\n{\n Space theSpace;\n\n constructor load(string stateString, int maxX, int maxY)\n {\n var strings := stateString.splitBy(newLineConstant).selectBy::(s => s.toArray()).toArray();\n\n theSpace := IntMatrixSpace.allocate(maxX, maxY, RuleSet\n {\n int proceed(Space s, int x, int y)\n {\n int retVal := 0;\n if (x < strings.Length)\n {\n var l := strings[x];\n if (y < l.Length)\n {\n (l[y]) =>\n conductorLabel { retVal := conductor }\n headLabel { retVal := electronHead }\n tailLabel { retVal := electronTail }\n emptyLabel { retVal := empty }\n }\n else\n {\n retVal := empty\n }\n }\n else\n {\n retVal := empty\n };\n\n ^ retVal\n }\n })\n }\n\n run()\n {\n theSpace.update(wireWorldRuleSet)\n }\n\n print()\n {\n int columns := theSpace.Columns;\n int rows := theSpace.Rows;\n\n int i := 0;\n int j := 0;\n while (i < rows)\n {\n j := 0;\n\n while (j < columns)\n {\n var label := emptyLabel;\n int cell := theSpace.at(i, j);\n\n cell =>\n conductor { label := conductorLabel }\n electronHead { label := headLabel }\n electronTail { label := tailLabel };\n\n console.write(label);\n\n j := j + 1\n };\n\n i := i + 1;\n console.writeLine()\n }\n }\n}\n\npublic program()\n{\n Model model := Model.load(sample,10,30);\n for(int i := 0; i < 10; i += 1)\n {\n console.printLineFormatted(\"Iteration {0}\",i);\n model.print().run()\n }\n}\n", "language": "Elena" }, { "code": "defmodule Wireworld do\n @empty \" \"\n @head \"H\"\n @tail \"t\"\n @conductor \".\"\n @neighbours (for x<- -1..1, y <- -1..1, do: {x,y}) -- [{0,0}]\n\n def set_up(string) do\n lines = String.split(string, \"\\n\", trim: true)\n grid = Enum.with_index(lines)\n |> Enum.flat_map(fn {line,i} ->\n String.codepoints(line)\n |> Enum.with_index\n |> Enum.map(fn {char,j} -> {{i, j}, char} end)\n end)\n |> Enum.into(Map.new)\n width = Enum.map(lines, fn line -> String.length(line) end) |> Enum.max\n height = length(lines)\n {grid, width, height}\n end\n\n # to string\n defp to_s(grid, width, height) do\n Enum.map_join(0..height-1, fn i ->\n Enum.map_join(0..width-1, fn j -> Map.get(grid, {i,j}, @empty) end) <> \"\\n\"\n end)\n end\n\n # transition all cells simultaneously\n defp transition(grid) do\n Enum.into(grid, Map.new, fn {{x, y}, state} ->\n {{x, y}, transition_cell(grid, state, x, y)}\n end)\n end\n\n # how to transition a single cell\n defp transition_cell(grid, current, x, y) do\n case current do\n @empty -> @empty\n @head -> @tail\n @tail -> @conductor\n _ -> if neighbours_with_state(grid, x, y) in 1..2, do: @head, else: @conductor\n end\n end\n\n # given a position in the grid, find the neighbour cells with a particular state\n def neighbours_with_state(grid, x, y) do\n Enum.count(@neighbours, fn {dx,dy} -> Map.get(grid, {x+dx, y+dy}) == @head end)\n end\n\n # run a simulation up to a limit of transitions, or until a recurring\n # pattern is found\n # This will print text to the console\n def run(string, iterations\\\\25) do\n {grid, width, height} = set_up(string)\n Enum.reduce(0..iterations, {grid, %{}}, fn count,{grd, seen} ->\n IO.puts \"Generation : #{count}\"\n IO.puts to_s(grd, width, height)\n\n if seen[grd] do\n IO.puts \"I've seen this grid before... after #{count} iterations\"\n exit(:normal)\n else\n {transition(grd), Map.put(seen, grd, count)}\n end\n end)\n IO.puts \"ran through #{iterations} iterations\"\n end\nend\n\n# this is the \"2 Clock generators and an XOR gate\" example from the wikipedia page\ntext = \"\"\"\n ......tH\n. ......\n ...Ht... .\n ....\n . .....\n ....\n tH...... .\n. ......\n ...Ht...\n\"\"\"\n\nWireworld.run(text)\n", "language": "Elixir" }, { "code": "// Wireworld. Nigel Galloway: January 22nd., 2024\ntype Cell= |E |T |H |C\nlet n=array2D [[T;H;C;C;C;C;C;C;C;C;C];\n [C;E;E;E;C;E;E;E;E;E;E];\n [E;E;E;C;C;C;E;E;E;E;E];\n [C;E;E;E;C;E;E;E;E;E;E];\n [H;T;C;C;E;C;C;C;C;C;C]]\nlet fG n g=match n|>Seq.sumBy(fun n->match Array2D.get g (fst n) (snd n) with H->1 |_->0) with 1 |2->H |_->C\nlet fX i=i|>Array2D.mapi(fun n g->function |E->E |H->T |T->C |C->fG (Seq.allPairs [max 0 (n-1)..min (n+1) (Array2D.length1 i-1)] [max 0 (g-1)..min (g+1) (Array2D.length2 i-1)]) i)\nSeq.unfold(fun n->Some(n,fX n))n|>Seq.take 15|>Seq.iteri(fun n g->printfn \"%d:\\n%A\\n\" n g)\n", "language": "F-Sharp" }, { "code": "16 constant w\n 8 constant h\n\n: rows w * 2* ;\n1 rows constant row\nh rows constant size\n\ncreate world size allot\nworld value old\nold w + value new\n\n: init world size erase ;\n: age new old to new to old ;\n\n: foreachrow ( xt -- )\n size 0 do I over execute row +loop drop ;\n\n0 constant EMPTY\n1 constant HEAD\n2 constant TAIL\n3 constant WIRE\ncreate cstate bl c, char H c, char t c, char . c,\n\n: showrow ( i -- ) cr\n old + w over + swap do I c@ cstate + c@ emit loop ;\n: show ['] showrow foreachrow ;\n\n\n: line ( row addr len -- )\n bounds do\n i c@\n case\n bl of EMPTY over c! endof\n 'H of HEAD over c! endof\n 't of TAIL over c! endof\n '. of WIRE over c! endof\n endcase\n 1+\n loop drop ;\n\n: load ( filename -- )\n r/o open-file throw\n init old row + 1+ ( file row )\n begin over pad 80 rot read-line throw\n while over pad rot line\n row +\n repeat\n 2drop close-file throw\n show cr ;\n\n\n: +head ( sum i -- sum )\n old + c@ HEAD = if 1+ then ;\n: conductor ( i WIRE -- i HEAD|WIRE )\n drop 0\n over 1- row - +head\n over row - +head\n over 1+ row - +head\n over 1- +head\n over 1+ +head\n over 1- row + +head\n over row + +head\n over 1+ row + +head\n 1 3 within if HEAD else WIRE then ;\n\n\\ before: empty head tail wire\n\ncreate transition ' noop , ' 1+ , ' 1+ , ' conductor ,\n\n\\ after: empty tail wire head|wire\n\n: new-state ( i -- )\n dup old + c@\n dup cells transition + @ execute\n swap new + c! ;\n\n: newrow ( i -- )\n w over + swap do I new-state loop ;\n: gen ['] newrow foreachrow age ;\n\n: wireworld begin gen 0 0 at-xy show key? until ;\n", "language": "Forth" }, { "code": "program Wireworld\n implicit none\n\n integer, parameter :: max_generations = 12\n integer :: nrows = 0, ncols = 0, maxcols = 0\n integer :: gen, ierr = 0\n integer :: i, j\n character(1), allocatable :: cells(:,:)\n character(10) :: form, sub\n character(80) :: buff\n\n! open input file\n open(unit=8, file=\"wwinput.txt\")\n\n! find numbers of rows and columns in data\n do\n read(8, \"(a)\", iostat=ierr) buff\n if(ierr /= 0) exit\n nrows = nrows + 1\n ncols = len_trim(buff)\n if(ncols > maxcols) maxcols = ncols\n end do\n\n! allcate enough space to hold the data\n allocate(cells(0:nrows+1, 0:maxcols+1))\n cells = \" \"\n\n! load data\n rewind(8)\n do i = 1, nrows\n read(8, \"(a)\", iostat=ierr) buff\n if(ierr /= 0) exit\n do j = 1, maxcols\n cells(i, j) = buff(j:j)\n end do\n end do\n close(8)\n\n! calculate format string for write statement\n write(sub, \"(i8)\") maxcols\n form = \"(\" // trim(adjustl(sub)) // \"a1)\"\n\n do gen = 0, max_generations\n write(*, \"(/a, i0)\") \"Generation \", gen\n do i = 1, nrows\n write(*, form) cells(i, 1:maxcols)\n end do\n call nextgen(cells)\n end do\n deallocate(cells)\n\n contains\n\n subroutine Nextgen(cells)\n character, intent(in out) :: cells(0:,0:)\n character :: buffer(0:size(cells, 1)-1, 0:size(cells, 2)-1)\n integer :: i, j, h\n\n buffer = cells ! Store current status\n do i = 1, size(cells, 1)-2\n do j = 1, size(cells, 2)-2\n select case (buffer(i, j))\n case(\" \")\n ! no Change\n\n case(\"H\")\n ! If a head change to tail\n cells(i, j) = \"t\"\n\n case(\"t\")\n ! if a tail change to conductor\n cells(i, j) = \".\"\n\n case (\".\")\n ! Count number of electron heads in surrounding eight cells.\n ! We can ignore that fact that we count the centre cell as\n ! well because we already know it contains a conductor.\n ! If surrounded by 1 or 2 heads change to a head\n h = sum(count(buffer(i-1:i+1, j-1:j+1) == \"H\", 1))\n if(h == 1 .or. h == 2) cells(i, j) = \"H\"\n end select\n end do\n end do\n end subroutine Nextgen\nend program Wireworld\n", "language": "Fortran" }, { "code": "#define MAXX 319\n#define MAXY 199\n\nenum state\n E=0, C=8, H=9, T=4 'doubles as colours: black, grey, bright blue, red\nend enum\n\ndim as uinteger world(0 to 1, 0 to MAXX, 0 to MAXY), active = 0, buffer = 1\ndim as double rate = 1./3. 'seconds per frame\ndim as double tick\ndim as uinteger x, y\n\nfunction turn_on( world() as unsigned integer, x as uinteger, y as uinteger, a as uinteger ) as boolean\n dim as ubyte n = 0\n dim as integer qx, qy\n for qx = -1 to 1\n for qy = -1 to 1\n if qx=0 andalso qy=0 then continue for\n if world(a,(x+qx+MAXX+1) mod (MAXX+1), (y+qy+MAXY+1) mod (MAXY+1))=H then n=n+1 'handles wrap-around\n next qy\n next qx\n if n=1 then return true\n if n=2 then return true\n return false\nend function\n\n'generate sample map\n\nfor x=20 to 30\n world(active, x, 20) = C\n world(active, x, 24) = C\nnext x\nworld(active, 24, 24 ) = E\nworld(active, 20, 21 ) = C\nworld(active, 20, 23 ) = C\nworld(active, 24, 21 ) = C\nworld(active, 23, 22 ) = C\nworld(active, 24, 22 ) = C\nworld(active, 25, 22 ) = C\nworld(active, 24, 23 ) = C\nworld(active, 20, 20 ) = T\nworld(active, 21, 20 ) = H\nworld(active, 21, 24 ) = T\nworld(active, 20, 24 ) = H\n\nscreen 12\n\ndo\n tick = timer\n for x = 0 to 319\n for y = 0 to 199\n pset (x,y), world(active, x, y)\n if world(active,x,y) = E then world(buffer,x,y) = E 'empty cells stay empty\n if world(active,x,y) = H then world(buffer,x,y) = T 'electron heads turn into electron tails\n if world(active,x,y) = T then world(buffer,x,y) = C 'electron tails revert to conductors\n if world(active,x,y) = C then\n if turn_on(world(),x,y,active) then\n world(buffer,x,y) = H 'maybe electron heads spread\n else\n world(buffer,x,y) = C 'otherwise condutor remains conductor\n end if\n end if\n next y\n next x\n while tick + rate > timer\n wend\n cls\n buffer = 1 - buffer\n active = 1 - buffer\nloop\n", "language": "FreeBASIC" }, { "code": "//Create event\n/*\nWireworld first declares constants and then reads a wireworld from a textfile.\nIn order to implement wireworld in GML a single array is used.\nTo make it behave properly, there need to be states that are 'in-between' two states:\n0 = empty\n1 = conductor from previous state\n2 = electronhead from previous state\n5 = electronhead that was a conductor in the previous state\n3 = electrontail from previous state\n4 = electrontail that was a head in the previous state\n*/\nempty = 0;\nconduc = 1;\neHead = 2;\neTail = 3;\neHead_to_eTail = 4;\ncoduc_to_eHead = 5;\nworking = true;//not currently used, but setting it to false stops wireworld. (can be used to pause)\ntoroidalMode = false;\nfactor = 3;//this is used for the display. 3 means a single pixel is multiplied by three in size.\n\nvar tempx,tempy ,fileid, tempstring, gridid, listid, maxwidth, stringlength;\ntempx = 0;\ntempy = 0;\ntempstring = \"\";\nmaxwidth = 0;\n\n//the next piece of code loads the textfile containing a wireworld.\n//the program will not work correctly if there is no textfile.\nif file_exists(\"WW.txt\")\n{\nfileid = file_text_open_read(\"WW.txt\");\ngridid = ds_grid_create(0,0);\nlistid = ds_list_create();\n while !file_text_eof(fileid)\n {\n tempstring = file_text_read_string(fileid);\n stringlength = string_length(tempstring);\n ds_list_add(listid,stringlength);\n if maxwidth < stringlength\n {\n ds_grid_resize(gridid,stringlength,ds_grid_height(gridid) + 1)\n maxwidth = stringlength\n }\n else\n {\n ds_grid_resize(gridid,maxwidth,ds_grid_height(gridid) + 1)\n }\n\n for (i = 1; i <= stringlength; i +=1)\n {\n switch (string_char_at(tempstring,i))\n {\n case ' ': ds_grid_set(gridid,tempx,tempy,empty); break;\n case '.': ds_grid_set(gridid,tempx,tempy,conduc); break;\n case 'H': ds_grid_set(gridid,tempx,tempy,eHead); break;\n case 't': ds_grid_set(gridid,tempx,tempy,eTail); break;\n default: break;\n }\n tempx += 1;\n }\n file_text_readln(fileid);\n tempy += 1;\n tempx = 0;\n }\nfile_text_close(fileid);\n//fill the 'open' parts of the grid\ntempy = 0;\n repeat(ds_list_size(listid))\n {\n tempx = ds_list_find_value(listid,tempy);\n repeat(maxwidth - tempx)\n {\n ds_grid_set(gridid,tempx,tempy,empty);\n tempx += 1;\n }\n tempy += 1;\n }\nboardwidth = ds_grid_width(gridid);\nboardheight = ds_grid_height(gridid);\n//the contents of the grid are put in a array, because arrays are faster.\n//the grid was needed because arrays cannot be resized properly.\ntempx = 0;\ntempy = 0;\n repeat(boardheight)\n {\n repeat(boardwidth)\n {\n board[tempx,tempy] = ds_grid_get(gridid,tempx,tempy);\n tempx += 1;\n }\n tempy += 1;\n tempx = 0;\n }\n//the following code clears memory\nds_grid_destroy(gridid);\nds_list_destroy(listid);\n}\n", "language": "GML" }, { "code": "//Step event\n/*\nThis step event executes each 1/speed seconds.\nIt checks everything on the board using an x and a y through two repeat loops.\nThe variables westN,northN,eastN,southN, resemble the space left, up, right and down respectively,\nseen from the current x & y.\n1 -> 5 (conductor is changing to head)\n2 -> 4 (head is changing to tail)\n3 -> 1 (tail became conductor)\n*/\n\nvar tempx,tempy,assignhold,westN,northN,eastN,southN,neighbouringHeads,T;\ntempx = 0;\ntempy = 0;\nwestN = 0;\nnorthN = 0;\neastN = 0;\nsouthN = 0;\nneighbouringHeads = 0;\nT = 0;\n\nif working = 1\n{\n repeat(boardheight)\n {\n repeat(boardwidth)\n {\n switch board[tempx,tempy]\n {\n case empty: assignhold = empty; break;\n case conduc:\n neighbouringHeads = 0;\n if toroidalMode = true //this is disabled, but otherwise lets wireworld behave toroidal.\n {\n if tempx=0\n {\n westN = boardwidth -1;\n }\n else\n {\n westN = tempx-1;\n }\n if tempy=0\n {\n northN = boardheight -1;\n }\n else\n {\n northN = tempy-1;\n }\n if tempx=boardwidth -1\n {\n eastN = 0;\n }\n else\n {\n eastN = tempx+1;\n }\n if tempy=boardheight -1\n {\n southN = 0;\n }\n else\n {\n southN = tempy+1;\n }\n\n T=board[westN,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[tempx,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[eastN,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[westN,tempy];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[eastN,tempy];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[westN,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[tempx,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n T=board[eastN,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n else//this is the default mode that works for the provided example.\n {//the next code checks whether coordinates fall outside the array borders.\n //and counts all the neighbouring electronheads.\n if tempx=0\n {\n westN = -1;\n }\n else\n {\n westN = tempx - 1;\n T=board[westN,tempy];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if tempy=0\n {\n northN = -1;\n }\n else\n {\n northN = tempy - 1;\n T=board[tempx,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if tempx = boardwidth -1\n {\n eastN = -1;\n }\n else\n {\n eastN = tempx + 1;\n T=board[eastN,tempy];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if tempy = boardheight -1\n {\n southN = -1;\n }\n else\n {\n southN = tempy + 1;\n T=board[tempx,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n\n if westN != -1 and northN != -1\n {\n T=board[westN,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if eastN != -1 and northN != -1\n {\n T=board[eastN,northN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if westN != -1 and southN != -1\n {\n T=board[westN,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n if eastN != -1 and southN != -1\n {\n T=board[eastN,southN];\n if T=eHead or T=eHead_to_eTail\n {\n neighbouringHeads += 1;\n }\n }\n }\n if neighbouringHeads = 1 or neighbouringHeads = 2\n {\n assignhold = coduc_to_eHead;\n }\n else\n {\n assignhold = conduc;\n }\n break;\n\n case eHead: assignhold = eHead_to_eTail; break;\n case eTail: assignhold = conduc; break;\n default: break;\n }\n board[tempx,tempy] = assignhold;\n tempx += 1;\n }\n tempy += 1;\n tempx = 0;\n }\n}\n", "language": "GML" }, { "code": "//Draw event\n/*\nThis event occurs whenever the screen is refreshed.\nIt checks everything on the board using an x and a y through two repeat loops and draws it.\nIt is an important step, because all board values are changed to the normal versions:\n5 -> 2 (conductor changed to head)\n4 -> 3 (head changed to tail)\n*/\n//draw sprites and text first\n\n//now draw wireworld\nvar tempx,tempy;\ntempx = 0;\ntempy = 0;\n\nrepeat(boardheight)\n{\n repeat(boardwidth)\n {\n switch board[tempx,tempy]\n {\n case empty:\n //draw_point_color(tempx,tempy,c_black);\n draw_set_color(c_black);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n break;\n case conduc:\n //draw_point_color(tempx,tempy,c_yellow);\n draw_set_color(c_yellow);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n break;\n case eHead:\n //draw_point_color(tempx,tempy,c_red);\n draw_set_color(c_blue);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n draw_rectangle_color(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,c_red,c_red,c_red,c_red,false);\n break;\n case eTail:\n //draw_point_color(tempx,tempy,c_blue);\n draw_set_color(c_red);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n break;\n case coduc_to_eHead:\n //draw_point_color(tempx,tempy,c_red);\n draw_set_color(c_blue);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n board[tempx,tempy] = eHead;\n break;\n case eHead_to_eTail:\n //draw_point_color(tempx,tempy,c_blue);\n draw_set_color(c_red);\n draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);\n board[tempx,tempy] = eTail;\n break;\n default: break;\n }\n tempx += 1\n }\ntempy += 1;\ntempx = 0;\n}\ndraw_set_color(c_black);\n", "language": "GML" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"io/ioutil\"\n \"strings\"\n)\n\nvar rows, cols int // extent of input configuration\nvar rx, cx int // grid extent (includes border)\nvar mn []int // offsets of moore neighborhood\n\nfunc main() {\n // read input configuration from file\n src, err := ioutil.ReadFile(\"ww.config\")\n if err != nil {\n fmt.Println(err)\n return\n }\n srcRows := bytes.Split(src, []byte{'\\n'})\n\n // compute package variables\n rows = len(srcRows)\n for _, r := range srcRows {\n if len(r) > cols {\n cols = len(r)\n }\n }\n rx, cx = rows+2, cols+2\n mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}\n\n // allocate two grids and copy input into first grid\n odd := make([]byte, rx*cx)\n even := make([]byte, rx*cx)\n for ri, r := range srcRows {\n copy(odd[(ri+1)*cx+1:], r)\n }\n\n // run\n for {\n print(odd)\n step(even, odd)\n fmt.Scanln()\n\n print(even)\n step(odd, even)\n fmt.Scanln()\n }\n}\n\nfunc print(grid []byte) {\n fmt.Println(strings.Repeat(\"__\", cols))\n fmt.Println()\n for r := 1; r <= rows; r++ {\n for c := 1; c <= cols; c++ {\n if grid[r*cx+c] == 0 {\n fmt.Print(\" \")\n } else {\n fmt.Printf(\" %c\", grid[r*cx+c])\n }\n }\n fmt.Println()\n }\n}\n\nfunc step(dst, src []byte) {\n for r := 1; r <= rows; r++ {\n for c := 1; c <= cols; c++ {\n x := r*cx + c\n dst[x] = src[x]\n switch dst[x] {\n case 'H':\n dst[x] = 't'\n case 't':\n dst[x] = '.'\n case '.':\n var nn int\n for _, n := range mn {\n if src[x+n] == 'H' {\n nn++\n }\n }\n if nn == 1 || nn == 2 {\n dst[x] = 'H'\n }\n }\n }\n }\n}\n", "language": "Go" }, { "code": "import Data.List\nimport Control.Monad\nimport Control.Arrow\nimport Data.Maybe\n\nstates=\" Ht.\"\nshiftS=\" t..\"\n\nborden bc xs = bs: (map (\\x -> bc:(x++[bc])) xs) ++ [bs]\n where r = length $ head xs\n bs = replicate (r+2) bc\n\ntake3x3 = ap ((.). taken. length) (taken. length. head) `ap` borden '*'\n where taken n = transpose. map (take n.map (take 3)).map tails\n\nnwState xs | e =='.' && noH>0 && noH<3 = 'H'\n | otherwise = shiftS !! (fromJust $ elemIndex e states)\n where e = xs!!1!!1\n noH = length $ filter (=='H') $ concat xs\n\nrunCircuit = iterate (map(map nwState).take3x3)\n", "language": "Haskell" }, { "code": "oscillator= [\" tH \",\n \". ....\",\n \" .. \"\n ]\n\nexample = mapM_ (mapM_ putStrLn) .map (borden ' ').take 9 $ runCircuit oscillator\n", "language": "Haskell" }, { "code": "link graphics\n\n$define EDGE -1\n$define EMPTY 0\n$define HEAD 1\n$define TAIL 2\n$define COND 3\n\nglobal Colours,Width,Height,World,oldWorld\n\nprocedure main() # wire world modified from forestfire\n\n Height := 400 # Window height\n Width := 400 # Window width\n Rounds := 500 # max Rounds\n Delay := 5 # Runout Delay\n\n setup_world(read_world())\n every round := 1 to Rounds do {\n show_world()\n if \\runout then\n delay(Delay)\n else\n case Event() of {\n \"q\" : break # q = quit\n \"r\" : runout := 1 # r = run w/o stepping\n \"s\" : WriteImage(\"Wireworld-\"||round) # save\n }\n evolve_world()\n }\n WDone()\nend\n\nprocedure read_world() #: for demo in place of reading\n return [ \"tH.........\",\n \". .\",\n \" ...\",\n \". .\",\n \"Ht.. ......\"]\nend\n\nprocedure setup_world(L) #: setup the world\n\n Colours := table() # define colours\n Colours[EDGE] := \"grey\"\n Colours[EMPTY] := \"black\"\n Colours[HEAD] := \"blue\"\n Colours[TAIL] := \"red\"\n Colours[COND] := \"yellow\"\n\n States := table()\n States[\"t\"] := TAIL\n States[\"H\"] := HEAD\n States[\" \"] := EMPTY\n States[\".\"] := COND\n\n WOpen(\"label=Wireworld\", \"bg=black\",\n \"size=\" || Width+2 || \",\" || Height+2) | # add for border\n stop(\"Unable to open Window\")\n every !(World := list(Height)) := list(Width,EMPTY) # default\n every ( World[1,1 to Width] | World[Height,1 to Width] |\n World[1 to Height,1] | World[1 to Height,Width] ) := EDGE\n\n every r := 1 to *L & c := 1 to *L[r] do { # setup read in program\n World[r+1, c+1] := States[L[r,c]]\n }\nend\n\nprocedure show_world() #: show World - drawn changes only\n every r := 2 to *World-1 & c := 2 to *World[r]-1 do\n if /oldWorld | oldWorld[r,c] ~= World[r,c] then {\n WAttrib(\"fg=\" || Colours[tr := World[r,c]])\n DrawPoint(r,c)\n }\nend\n\nprocedure evolve_world() #: evolve world\n old := oldWorld := list(*World) # freeze copy\n every old[i := 1 to *World] := copy(World[i]) # deep copy\n\n every r := 2 to *World-1 & c := 2 to *World[r]-1 do\n World[r,c] := case old[r,c] of { # apply rules\n # EMPTY : EMPTY\n HEAD : TAIL\n TAIL : COND\n COND : {\n i := 0\n every HEAD = ( old[r-1,c-1 to c+1] | old[r,c-1|c+1] | old[r+1,c-1 to c+1] ) do i +:= 1\n if i := 1 | 2 then HEAD\n }\n }\nend\n", "language": "Icon" }, { "code": "circ0=:}: ] ;. _1 LF, 0 : 0\ntH........\n. .\n ...\n. .\nHt.. .....\n)\n", "language": "J" }, { "code": "board=: ' ' ,.~ ' ' ,. ' ' , ' ' ,~ ]\n\nnwS=: 3 : 0\n e=. (<1 1){y\n if. ('.'=e)*. e.&1 2 +/'H'=,y do. 'H' return. end.\n ' t..' {~ ' Ht.' i. e\n)\n", "language": "J" }, { "code": " process=: (3 3 nwS;. _3 board)^:\n(<10) process circuit\n", "language": "J" }, { "code": "require'viewmat'\nviewmat\"2 ' .tH'i. (<10) process circ0\n", "language": "J" }, { "code": "var ctx, sizeW, sizeH, scl = 10, map, tmp;\nfunction getNeighbour( i, j ) {\n var ii, jj, c = 0;\n for( var b = -1; b < 2; b++ ) {\n for( var a = -1; a < 2; a++ ) {\n ii = i + a; jj = j + b;\n if( ii < 0 || ii >= sizeW || jj < 0 || jj >= sizeH ) continue;\n if( map[ii][jj] == 1 ) c++;\n }\n }\n return ( c == 1 || c == 2 );\n}\nfunction simulate() {\n drawWorld();\n for( var j = 0; j < sizeH; j++ ) {\n for( var i = 0; i < sizeW; i++ ) {\n switch( map[i][j] ) {\n case 0: tmp[i][j] = 0; break;\n case 1: tmp[i][j] = 2; break;\n case 2: tmp[i][j] = 3; break;\n case 3:\n if( getNeighbour( i, j ) ) tmp[i][j] = 1;\n else tmp[i][j] = 3;\n break;\n }\n }\n }\n [tmp, map] = [map, tmp];\n setTimeout( simulate, 200 );\n}\nfunction drawWorld() {\n ctx.fillStyle = \"#000\"; ctx.fillRect( 0, 0, sizeW * scl, sizeH * scl );\n for( var j = 0; j < sizeH; j++ ) {\n for( var i = 0; i < sizeW; i++ ) {\n switch( map[i][j] ) {\n case 0: continue;\n case 1: ctx.fillStyle = \"#03f\"; break;\n case 2: ctx.fillStyle = \"#f30\"; break;\n case 3: ctx.fillStyle = \"#ff3\"; break;\n }\n ctx.fillRect( i, j, 1, 1 );\n }\n }\n}\nfunction openFile( event ) {\n var input = event.target;\n var reader = new FileReader();\n reader.onload = function() {\n createWorld( reader.result );\n };\n reader.readAsText(input.files[0]);\n}\nfunction createWorld( txt ) {\n var l = txt.split( \"\\n\" );\n sizeW = parseInt( l[0] );\n sizeH = parseInt( l[1] );\n map = new Array( sizeW );\n tmp = new Array( sizeW );\n for( var i = 0; i < sizeW; i++ ) {\n map[i] = new Array( sizeH );\n tmp[i] = new Array( sizeH );\n for( var j = 0; j < sizeH; j++ ) {\n map[i][j] = tmp[i][j] = 0;\n }\n }\n var t;\n for( var j = 0; j < sizeH; j++ ) {\n for( var i = 0; i < sizeW; i++ ) {\n switch( l[j + 2][i] ) {\n case \" \": t = 0; break;\n case \"H\": t = 1; break;\n case \"t\": t = 2; break;\n case \".\": t = 3; break;\n }\n map[i][j] = t;\n }\n }\n init();\n}\nfunction init() {\n var canvas = document.createElement( \"canvas\" );\n canvas.width = sizeW * scl;\n canvas.height = sizeH * scl;\n ctx = canvas.getContext( \"2d\" );\n ctx.scale( scl, scl );\n document.body.appendChild( canvas );\n simulate();\n}\n", "language": "JavaScript" }, { "code": "def lines: split(\"\\n\")|length;\n\ndef cols: split(\"\\n\")[0]|length + 1; # allow for the newline\n\n# Is there an \"H\" at [x,y] relative to position i, assuming the width is w?\n# Input is an array; 72 is \"H\"\ndef isH(x; y; i; w): if .[i+ w*y + x] == 72 then 1 else 0 end;\n\ndef neighborhood(i;w):\n isH(-1; -1; i; w) + isH(0; -1; i; w) + isH(1; -1; i; w) +\n isH(-1; 0; i; w) + isH(1; 0; i; w) +\n isH(-1; 1; i; w) + isH(0; 1; i; w) + isH(1; 1; i; w) ;\n\n# The basic rules:\n# Input: a world\n# Output: the next state of .[i]\ndef evolve(i; width) :\n # \"Ht. \" | explode => [ 72, 116, 46, 32 ]\n .[i] as $c\n | if $c == 32 then $c # \" \" => \" \"\n elif $c == 116 then 46 # \"t\" => \".\"\n elif $c == 72 then 116 # \"H\" => \"t\"\n elif $c == 46 then # \".\"\n # updates are \"simultaneous\" i.e. relative to $world\n neighborhood(i; width) as $sum\n | (if [1,2]|index($sum) then 72 else . end) # \"H\"\n else $c\n end ;\n\n# [world, lines, cols] | next(w) => [world, lines, cols]\ndef next:\n .[0] as $world | .[1] as $lines | .[2] as $w\n | reduce range(0; $world|length) as $i\n ($world;\n $world | evolve($i; $w) as $next\n | if .[$i] == $next then . else .[$i] = $next end )\n | [., $lines, $w] ; #\n", "language": "Jq" }, { "code": "# \"clear screen\":\ndef cls: \"\\u001b[2J\";\n\n# Input: an integer; 1000 ~ 1 sec\ndef spin:\n reduce range(1; 500 * .) as $i\n (0; . + ($i|cos)*($i|cos) + ($i|sin)*($i|sin) )\n | \"\" ;\n\n# Animate n steps;\n# if \"sleep\" is non-negative then cls and\n# sleep about \"sleep\" ms between frames.\ndef animate(n; sleep):\n if n == 0 then empty\n else (if sleep >= 0 then cls else \"\" end),\n (.[0]|implode), n, \"\\n\",\n (sleep|spin),\n ( next|animate(n-1; sleep) )\n end ;\n\n# Input: a string representing the initial state\ndef animation(n; sleep):\n [ explode, lines, cols] | animate(n; sleep) ;\n\n# Input: a string representing the initial state\ndef frames(n): animation(n; -1);#\n", "language": "Jq" }, { "code": "def world11:\n\"+-----------+\\n\" +\n\"|tH.........|\\n\" +\n\"|. . |\\n\" +\n\"| ... |\\n\" +\n\"|. . |\\n\" +\n\"|Ht.. ......|\\n\" +\n\"+-----------+\\n\" ;\n\ndef world9:\n\" \\n\" +\n\" tH \\n\" +\n\" . .... \\n\" +\n\" .. \\n\" +\n\" \\n\" ;\n", "language": "Jq" }, { "code": "# Ten-step animation with about 1 sec between frames\nworld9 | animation(10; 1000)\n", "language": "Jq" }, { "code": "# Ten frames in sequence:\nworld11 | frames(10)\n", "language": "Jq" }, { "code": "function surround2D(b, i, j)\n h, w = size(b)\n [b[x,y] for x in i-1:i+1, y in j-1:j+1 if (0 < x <= h && 0 < y <= w)]\nend\n\nsurroundhas1or2(b, i, j) = 0 < sum(map(x->Char(x)=='H', surround2D(b, i, j))) <= 2 ? 'H' : '.'\n\nfunction boardstep!(currentboard, nextboard)\n x, y = size(currentboard)\n for j in 1:y, i in 1:x\n ch = Char(currentboard[i, j])\n if ch == ' '\n continue\n else\n nextboard[i, j] = (ch == 'H') ? 't' : (ch == 't' ? '.' :\n surroundhas1or2(currentboard, i, j))\n end\n end\nend\n\nconst b1 = \" \" *\n \" tH \" *\n \" . .... \" *\n \" .. \" *\n \" \"\nconst mat = reshape(map(x->UInt8(x[1]), split(b1, \"\")), (9, 5))'\nconst mat2 = copy(mat)\n\nfunction printboard(mat)\n for i in 1:size(mat)[1]\n println(\"\\t\", join([Char(c) for c in mat[i,:]], \"\"))\n end\nend\n\nprintln(\"Starting Wireworld board:\")\nprintboard(mat)\nfor step in 1:8\n boardstep!(mat, mat2)\n println(\" Step $step:\")\n printboard(mat2)\n mat .= mat2\nend\n", "language": "Julia" }, { "code": "WindowWidth = 840\nWindowHeight = 600\n\ndim p$( 40, 25), q$( 40, 25)\n\nempty$ = \" \" ' white\ntail$ = \"t\" ' yellow\nhead$ = \"H\" ' black\nconductor$ = \".\" ' red\n\njScr = 0\n\nnomainwin\n\nmenu #m, \"File\", \"Load\", [load], \"Quit\", [quit]\n\nopen \"wire world\" for graphics_nf_nsb as #m\n #m \"trapclose [quit]\"\n 'timer 1000, [tmr]\n wait\n\nend\n\n[quit]\n close #m\n end\n\n[load]\n 'timer 0\n filedialog \"Open WireWorld File\", \"*.ww\", file$\n open file$ for input as #in\n y =0\n while not( eof( #in))\n line input #in, lijn$\n ' print \"|\"; lijn$; \"|\"\n for x =0 to len( lijn$) -1\n p$( x, y) =mid$( lijn$, x +1, 1)\n\n select case p$( x, y)\n case \" \"\n clr$ =\"white\"\n case \"t\"\n clr$ =\"yellow\"\n case \"H\"\n clr$ =\"black\"\n case \".\"\n clr$ =\"red\"\n end select\n\n #m \"goto \" ; 4 +x *20; \" \"; 4 +y *20\n #m \"backcolor \"; clr$\n #m \"down\"\n #m \"boxfilled \"; 4 +x *20 +19; \" \"; 4 +y *20 +19\n #m \"up ; flush\"\n next x\n y =y +1\n wend\n close #in\n 'notice \"Ready to run.\"\n timer 1000, [tmr]\n wait\n\n[tmr]\n timer 0\n scan\n\n for x =0 to 40 ' copy temp array /current array\n for y =0 to 25\n q$( x, y) =p$( x, y)\n next y\n next x\n\n for y =0 to 25\n for x =0 to 40\n select case q$( x, y)\n case head$ ' heads ( black) become tails ( yellow)\n p$( x, y ) =tail$\n clr$ =\"yellow\"\n\n case tail$ ' tails ( yellow) become conductors ( red)\n p$( x, y ) =conductor$\n clr$ =\"red\"\n\n case conductor$ '\n hCnt =0\n\n xL =x -1: if xL < 0 then xL =40 ' wrap-round edges at all four sides\n xR =x +1: if xR >40 then xR = 0\n yA =y -1: if yA < 0 then yA =25\n yB =y +1: if yB >40 then yB = 0\n\n if q$( xL, y ) =head$ then hCnt =hCnt +1 ' Moore environment- 6 neighbours\n if q$( xL, yA) =head$ then hCnt =hCnt +1 ' count all neighbours currently heads\n if q$( xL, yB) =head$ then hCnt =hCnt +1\n\n if q$( xR, y ) =head$ then hCnt =hCnt +1\n if q$( xR, yA) =head$ then hCnt =hCnt +1\n if q$( xR, yB) =head$ then hCnt =hCnt +1\n\n if q$( x, yA) =head$ then hCnt =hCnt +1\n if q$( x, yB) =head$ then hCnt =hCnt +1\n\n if ( hCnt =1) or ( hCnt =2) then ' conductor ( red) becomes head ( yellow) in this case only\n p$( x, y ) =head$ ' otherwise stays conductor ( red).\n clr$ =\"black\"\n else\n p$( x, y ) =conductor$\n clr$ =\"red\"\n end if\n\n case else\n clr$ =\"white\"\n end select\n\n #m \"goto \" ; 4 +x *20; \" \"; 4 +y *20\n #m \"backcolor \"; clr$\n #m \"down\"\n #m \"boxfilled \"; 4 +x *20 +19; \" \"; 4 +y *20 +19\n #m \"up\"\n next x\n next y\n #m \"flush\"\n #m \"getbmp scr 0 0 400 300\"\n\n 'bmpsave \"scr\", \"R:\\scrJHF\" +right$( \"000\" +str$( jScr), 3) +\".bmp\"\n jScr =jScr+1\n if jScr >20 then wait\n timer 1000, [tmr]\nwait\n", "language": "Liberty-BASIC" }, { "code": "to wireworld :filename :speed ;speed in n times per second, approximated\nMake \"speed 60/:speed\nwireworldread :filename\nMake \"bufferfield (mdarray (list :height :width) 0)\nfor [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :bufferfield mditem (list :i :j) :field]]\npu ht\nMake \"gen 0\nwhile [\"true] [ ;The user will have to halt it :P\n ;clean\n seth 90\n setxy 0 20\n ;label :gen\n sety 0\n for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :field mditem (list :i :j) :bufferfield]]\n for [i 0 :height-1] [\n for [j 0 :width-1] [\n if (mditem (list :i :j) :field)=[] [setpixel [255 255 255]] ;blank\n if (mditem (list :i :j) :field)=1 [setpixel [0 0 0] if wn :j :i 2 [mdsetitem (list :i :j) :bufferfield 2]] ;wire\n if (mditem (list :i :j) :field)=2 [setpixel [0 0 255] mdsetitem (list :i :j) :bufferfield 3] ;head\n if (mditem (list :i :j) :field)=3 [setpixel [255 0 0] mdsetitem (list :i :j) :bufferfield 1] ;tail\n setx xcor+1\n ]\n setxy 0 ycor-1\n ]\n Make \"gen :gen+1\n wait :speed\n]\nend\n\nto wireworldread :filename\nlocal [line]\nopenread :filename\nsetread :filename\nMake \"width 0\nMake \"height 0\n; first pass, take dimensions\nwhile [not eofp] [\n Make \"line readword\n if (count :line)>:width [Make \"width count :line]\n Make \"height :height+1\n]\n; second pass, load data\nsetreadpos 0\nMake \"field (mdarray (list :height :width) 0)\nfor [i 0 :height-1] [\n Make \"line readword\n foreach :line [\n if ?=char 32 [mdsetitem (list :i #-1) :field []]\n if ?=\". [mdsetitem (list :i #-1) :field 1]\n if ?=\"H [mdsetitem (list :i #-1) :field 2]\n if ?=\"t [mdsetitem (list :i #-1) :field 3]\n ]\n]\nsetread []\nclose :filename\nend\n\nto wn :x :y :thing ;WireNeighbourhood\nMake \"neighbours 0\nif (mditem (list :y-1 :x) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y-1 :x+1) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y :x+1) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y+1 :x+1) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y+1 :x) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y+1 :x-1) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y :x-1) :field)=:thing [Make \"neighbours :neighbours+1]\nif (mditem (list :y-1 :x-1) :field)=:thing [Make \"neighbours :neighbours+1]\nifelse OR :neighbours=1 :neighbours=2 [op \"true] [op \"false]\nend\n", "language": "Logo" }, { "code": "local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'},\n {'.', ' ', ' ', ' ', '.'},\n {' ', ' ', ' ', '.', '.', '.'},\n {'.', ' ', ' ', ' ', '.'},\n {'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}}\n\nfunction step(map)\n local next = {}\n for i = 1, #map do\n next[i] = {}\n for j = 1, #map[i] do\n next[i][j] = map[i][j]\n if map[i][j] == \"H\" then\n next[i][j] = \"t\"\n elseif map[i][j] == \"t\" then\n next[i][j] = \".\"\n elseif map[i][j] == \".\" then\n local count = \t((map[i-1] or {})[j-1] == \"H\" and 1 or 0) +\n ((map[i-1] or {})[j] == \"H\" and 1 or 0) +\n ((map[i-1] or {})[j+1] == \"H\" and 1 or 0) +\n ((map[i] or {})[j-1] == \"H\" and 1 or 0) +\n ((map[i] or {})[j+1] == \"H\" and 1 or 0) +\n ((map[i+1] or {})[j-1] == \"H\" and 1 or 0) +\n ((map[i+1] or {})[j] == \"H\" and 1 or 0) +\n ((map[i+1] or {})[j+1] == \"H\" and 1 or 0)\n if count == 1 or count == 2 then\n next[i][j] = \"H\"\n else\n next[i][j] = \".\"\n end\n end\n end\n end\n return next\nend\n\nif not not love then\n local time, frameTime, size = 0, 0.25, 20\n local colors = {[\".\"] = {255, 200, 0},\n [\"t\"] = {255, 0, 0},\n [\"H\"] = {0, 0, 255}}\n function love.update(dt)\n time = time + dt\n if time > frameTime then\n time = time - frameTime\n map = step(map)\n end\n end\n\n function love.draw()\n for i = 1, #map do\n for j = 1, #map[i] do\n love.graphics.setColor(colors[map[i][j]] or {0, 0, 0})\n love.graphics.rectangle(\"fill\", j*size, i*size, size, size)\n end\n end\n end\nelse\n for iter = 1, 10 do\n print(\"\\nstep \"..iter..\"\\n\")\n for i = 1, #map do\n for j = 1, #map[i] do\n io.write(map[i][j])\n end\n io.write(\"\\n\")\n end\n map = step(map)\n end\nend\n", "language": "Lua" }, { "code": "DynamicModule[{data =\n ArrayPad[PadRight[Characters /@ StringSplit[\"tH.........\n . .\n ...\n . .\n Ht.. ......\", \"\\n\"]] /. {\" \" -> 0, \"t\" -> 2, \"H\" -> 1,\n \".\" -> 3}, 1]},\n Dynamic@ArrayPlot[\n data = CellularAutomaton[{{{_, _, _}, {_, 0, _}, {_, _, _}} ->\n 0, {{_, _, _}, {_, 1, _}, {_, _, _}} ->\n 2, {{_, _, _}, {_, 2, _}, {_, _, _}} ->\n 3, {{a_, b_, c_}, {d_, 3, e_}, {f_, g_, h_}} :>\n Switch[Count[{a, b, c, d, e, f, g, h}, 1], 1, 1, 2, 1, _, 3]},\n data], ColorRules -> {1 -> Yellow, 2 -> Red}]]\n", "language": "Mathematica" }, { "code": "colors = [color.black, color.yellow, color.aqua, color.red]\ndeltas = [[-1,-1], [-1,0], [-1,1],\n [ 0,-1], [ 0,1],\n [ 1,-1], [ 1,0], [ 1,1]]\n\ndisplayGrid = function(grid, td)\n\tfor y in range(0, grid.len - 1)\n\t\tfor x in range(0, grid[0].len - 1)\n\t\t\ttd.setCell x,y, grid[y][x]\n\t\tend for\n\tend for\nend function\n\nbuildGrid = function(s)\n\tlines = s.split(char(13))\n\tnRows = lines.len\n\tnCols = 0\n\tfor line in lines\n\t\tif line.len > nCols then nCols = line.len\n\tend for\n\t\n\tgrid = []\n\temptyRow = []\n\tfor c in range(1,nCols)\n\t\temptyRow.push(0)\n\tend for\n\t\n\tfor line in lines\n\t\trow = emptyRow[:]\n\t\tfor i in range(0, line.len - 1)\n\t\t\trow[i] = \" .Ht\".indexOf(line[i])\n\t\tend for\n\t\tgrid.push(row)\n\tend for\n\treturn grid\nend function\n\ngetNewState = function(td, x, y)\n\tcellState = td.cell(x, y)\n\tif cellState == 3 then\n\t\treturn 1\n\telse if cellState == 2 then\n\t\treturn 3\n\telse if cellState == 1 then\n\t\tsum = 0\n\t\tfor delta in deltas\n\t\t\tx1 = x + delta[0]\n\t\t\ty1 = y + delta[1]\n\t\t\tif td.cell(x1, y1) == 2 then sum += 1\n\t\tend for\n\t\tif sum == 1 or sum == 2 then\n\t\t\treturn 2\n\t\telse\n\t\t\treturn 1\n\t\tend if\n\tend if\n\treturn cellState\nend function\n\nclear\n\nwireWorldProgram = \"tH.........\" + char(13)\nwireWorldProgram += \". .\" + char(13)\nwireWorldProgram += \" ...\" + char(13)\nwireWorldProgram += \". .\" + char(13)\nwireWorldProgram += \"Ht.. ......\"\ngrid = buildGrid(wireWorldProgram)\n\n// Prepare a tile display\n// Generate image used for the tiles from the colors defined above.\nimg = Image.create(colors.len, 1);\nfor i in range(0, colors.len - 1)\n\timg.setPixel(i, 0, colors[i])\nend for\n\ncols = grid[0].len\nrows = grid.len\ndisplay(4).mode = displayMode.tile\ntd = display(4)\ncSize = 25\ntd.cellSize = cSize // size of cells on screen\ntd.scrollX = -(960 - cols * (cSize + 1)) / 2\ntd.scrollY = -(640 - rows * (cSize + 1)) / 2\ntd.extent = [cols, rows]\ntd.overlap = -1 // adds a small gap between cells\ntd.tileSet = img; td.tileSetTileSize = 1\ntd.clear 0\n\nwhile true\n\tdisplayGrid(grid, td)\n\tfor y in range(0, rows - 1)\n\t\tfor x in range(0, cols - 1)\n\t\t\tgrid[y][x] = getNewState(td, x, y)\n\t\tend for\n\tend for\n\twait 0.5\nend while\n", "language": "MiniScript" }, { "code": "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 for i, c in s:\n o[i] = case c\n of ' ': ' '\n of 't': '.'\n of 'H': 't'\n of '.':\n if (isH(-1, -1) + isH(0, -1) + isH(1, -1) +\n isH(-1, 0) + isH(1, 0) +\n isH(-1, 1) + isH(0, 1) + isH(1, 1)\n ) in 1..2: 'H' else: '.'\n else: c\n\nwhile true:\n echo world\n stdout.write \"\\x1b[\",h,\"A\"\n stdout.write \"\\x1b[\",w,\"D\"\n sleep 100\n\n world2.next(world, w)\n swap world, world2\n", "language": "Nim" }, { "code": "let w = [|\n \" ......tH \";\n \" . ...... \";\n \" ...Ht... . \";\n \" .... \";\n \" . ..... \";\n \" .... \";\n \" tH...... . \";\n \" . ...... \";\n \" ...Ht... \";\n |]\n\nlet is_head w x y =\n try if w.(x).[y] = 'H' then 1 else 0\n with _ -> 0\n\nlet neighborhood_heads w x y =\n let n = ref 0 in\n for _x = pred x to succ x do\n for _y = pred y to succ y do\n n := !n + (is_head w _x _y)\n done;\n done;\n (!n)\n\nlet step w =\n let n = Array.init (Array.length w) (fun i -> String.copy w.(i)) in\n let width = Array.length w\n and height = String.length w.(0)\n in\n for x = 0 to pred width do\n for y = 0 to pred height do\n n.(x).[y] <- (\n match w.(x).[y] with\n | ' ' -> ' '\n | 'H' -> 't'\n | 't' -> '.'\n | '.' ->\n (match neighborhood_heads w x y with\n | 1 | 2 -> 'H'\n | _ -> '.')\n | _ -> assert false)\n done;\n done;\n (n)\n\nlet print = (Array.iter print_endline)\n\nlet () =\n let rec aux w =\n Unix.sleep 1;\n let n = step w in\n print n;\n aux n\n in\n aux w\n", "language": "OCaml" }, { "code": "declare\n Rules =\n [rule(& & )\n rule(&H &t)\n rule(&t &.)\n rule(&. &H when:fun {$ Neighbours}\n fun {IsHead X} X == &H end\n Hs = {Filter Neighbours IsHead}\n Len = {Length Hs}\n in\n Len == 1 orelse Len == 2\n end)\n rule(&. &.)]\n\n Init = [\"tH.........\"\n \". . \"\n \" ... \"\n \". . \"\n \"Ht.. ......\"]\n\n MaxGen = 100\n\n %% G(i) -> G(i+1)\n fun {Evolve Gi}\n fun {Get X#Y}\n Row = {CondSelect Gi Y unit}\n in\n {CondSelect Row X & } %% cells beyond boundaries are empty\n end\n fun {GetNeighbors X Y}\n {Map [X-1#Y-1 X#Y-1 X+1#Y-1\n X-1#Y X+1#Y\n X-1#Y+1 X#Y+1 X+1#Y+1]\n Get}\n end\n in\n {Record.mapInd Gi\n fun {$ Y Row}\n {Record.mapInd Row\n fun {$ X C}\n for Rule in Rules return:Return do\n if C == Rule.1 then\n\t\t When = {CondSelect Rule when {Const true}}\n\t\tin\n\t\t if {When {GetNeighbors X Y}} then\n\t\t {Return Rule.2}\n\t\t end\n\t\tend\n\t end\n end}\n end}\n end\n\n %% Create an arena from a list of strings.\n fun {ReadArena LinesList}\n {List.toTuple '#'\n {Map LinesList\n fun {$ Line}\n {List.toTuple row Line}\n end}}\n end\n\n %% Converts an arena to a virtual string\n fun {ShowArena G}\n {Record.map G\n fun {$ L} {Record.toList L}#\"\\n\" end}\n end\n\n %% helpers\n fun lazy {Iterate F V} V|{Iterate F {F V}} end\n fun {Const X} fun {$ _} X end end\n\n %% prepare GUI\n [QTk]={Module.link [\"x-oz://system/wp/QTk.ozf\"]}\n GenDisplay\n Field\n GUI = td(label(handle:GenDisplay)\n label(handle:Field font:{QTk.newFont font(family:'Courier')})\n )\n {{QTk.build GUI} show}\n\n G0 = {ReadArena Init}\n Gn = {Iterate Evolve G0}\nin\n for\n Gi in Gn\n I in 0..MaxGen\n do\n {GenDisplay set(text:\"Gen. \"#I)}\n {Field set(text:{ShowArena Gi})}\n {Delay 500}\n end\n", "language": "Oz" }, { "code": "\\\\ 0 = conductor, 1 = tail, 2 = head, 3 = empty\nwireworldStep(M)={\n\tmy(sz=matsize(M),t);\n\tmatrix(sz[1],sz[2],x,y,\n\t\tt=M[x,y];\n\t\tif(t,\n\t\t\t[0,1,3][t]\n\t\t,\n\t\t\tt=sum(i=max(x-1,1),min(x+1,sz[1]),\n\t\t\t\tsum(j=max(y-1,1),min(y+1,sz[2]),\n\t\t\t\t\tM[i,j]==2\n\t\t\t\t)\n\t\t\t);\n\t\t\tif(t==1|t==2,2,3)\n\t\t)\n\t)\n};\nanimate(M)={\n\twhile(1,display(M=wireworldStep(M)))\n};\ndisplay(M)={\n\tmy(sz=matsize(M),t);\n\tfor(i=1,sz[1],\n\t\tfor(j=1,sz[2],\n\t\t\tt=M[i,j];\n\t\t\tprint1([\".\",\"t\",\"H\",\" \"][t+1])\n\t\t);\n\t\tprint\n\t)\n};\nanimate(read(\"wireworld.gp\"))\n", "language": "PARI-GP" }, { "code": "my @f = ([],(map {chomp;['',( split // ),'']} <>),[]);\n\nfor (1 .. 10) {\n\tprint join \"\", map {\"@$_\\n\"} @f;\n\tmy @a = ([]);\n\tfor my $y (1 .. $#f-1) {\n\t\tmy $r = $f[$y];\n\t\tmy $rr = [''];\n\t\tfor my $x (1 .. $#$r-1) {\n\t\t\tmy $c = $r->[$x];\n\t\t\tpush @$rr,\n\t\t\t\t$c eq 'H' ? 't' :\n\t\t\t\t$c eq 't' ? '.' :\n\t\t\t\t$c eq '.' ? (join('', map {\"@{$f[$_]}[$x-1 .. $x+1]\"=~/H/g} ($y-1 .. $y+1)) =~ /^H{1,2}$/ ? 'H' : '.') :\n\t\t\t\t$c;\n\t\t}\n\t\tpush @$rr, '';\n\t\tpush @a, $rr;\n\t}\n\t@f = (@a,[]);\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Wireworld.exw\n -- ==========================\n --\n -- Invoke with file to read, or let it read the one below (if compiled assumes source is in the same directory)\n --\n -- Note that tabs in description files are not supported - where necessary spaces can be replaced with _ chars.\n -- (tab chars in text files should technically always represent (to-next) 8 spaces, but not many editors respect\n -- that, and instead assume the file will only ever be read by the same program/with matching settings. &lt;/rant&gt;)\n -- (see also demo\\edix\\src\\tabs.e\\ExpandTabs() for what you'd need if you knew what the tab chars really meant.)\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">default_description</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n tH.........\n .___.\n ___...\n .___.\n Ht.. ......\n \"\"\"</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">counts</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">longest</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">valid_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" _.tH\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'\\t'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- as above</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"error: tab char on line %d\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">abort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">load_desc</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">text</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">default_description</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">filename</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">command_line</span><span style=\"color: #0000FF;\">()[$],</span><span style=\"color: #008000;\">\".exe\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\".exw\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">fn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">open</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">filename</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"r\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"error opening %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">filename</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">abort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">get_text</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">GT_LF_STRIPPED</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">close</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">lines</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">valid_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">lines</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">longest</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">line</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">text</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">valid_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">lines</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">longest</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">longest</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">line</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">counts</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">dxy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #0000FF;\">{+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">set_counts</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">'.'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dxy</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">dxy</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">'H'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">count</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">count</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Wireworld\"</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timer</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/(</span><span style=\"color: #000000;\">longest</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">dy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasClear</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">set_counts</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">colour</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" _\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">colour</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_BLACK</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'.'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">colour</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_YELLOW</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">counts</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'H'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'H'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">colour</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_BLUE</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'t'</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">'t'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">colour</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_RED</span>\n <span style=\"color: #000000;\">lines</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'.'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">colour</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasBox</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupUpdate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_IGNORE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">load_desc</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RASTERSIZE=300x180\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"%s\"`</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">})</span>\n\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "$desc = 'tH.........\n. .\n ........\n. .\nHt.. ......\n\n ..\ntH.... .......\n ..\n\n ..\ntH..... ......\n ..';\n\n$steps = 30;\n\n//fill in the world with the cells\n$world = array(array());\n$row = 0;\n$col = 0;\nforeach(str_split($desc) as $i){\n switch($i){\n case \"\\n\":\n $row++;\n //if($col > $width) $width = $col;\n $col = 0;\n $world[] = array();\n break;\n case '.':\n $world[$row][$col] = 1;//conductor\n $col++;\n break;\n case 'H':\n $world[$row][$col] = 2;//head\n $col++;\n break;\n case 't':\n $world[$row][$col] = 3;//tail\n $col++;\n break;\n default:\n $world[$row][$col] = 0;//insulator/air\n $col++;\n break;\n };\n};\nfunction draw_world($world){\n foreach($world as $rowc){\n foreach($rowc as $cell){\n switch($cell){\n case 0:\n echo ' ';\n break;\n case 1:\n echo '.';\n break;\n case 2:\n echo 'H';\n break;\n case 3:\n echo 't';\n };\n };\n echo \"\\n\";\n };\n //var_export($world);\n};\necho \"Original world:\\n\";\ndraw_world($world);\nfor($i = 0; $i < $steps; $i++){\n $old_world = $world; //backup to look up where was an electron head\n foreach($world as $row => &$rowc){\n foreach($rowc as $col => &$cell){\n switch($cell){\n case 2:\n $cell = 3;\n break;\n case 3:\n $cell = 1;\n break;\n case 1:\n $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;\n $neigh_heads += (int) @$old_world[$row - 1][$col] == 2;\n $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;\n $neigh_heads += (int) @$old_world[$row][$col - 1] == 2;\n $neigh_heads += (int) @$old_world[$row][$col + 1] == 2;\n $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;\n $neigh_heads += (int) @$old_world[$row + 1][$col] == 2;\n if($neigh_heads == 1 || $neigh_heads == 2){\n $cell = 2;\n };\n };\n };\n unset($cell); //just to be safe\n };\n unset($rowc); //just to be safe\n echo \"\\nStep \" . ($i + 1) . \":\\n\";\n draw_world($world);\n};\n", "language": "PHP" }, { "code": "(load \"@lib/simul.l\")\n\n(let\n (Data (in \"wire.data\" (make (while (line) (link @))))\n Grid (grid (length (car Data)) (length Data)) )\n (mapc\n '((G D) (mapc put G '(val .) D))\n Grid\n (apply mapcar (flip Data) list) )\n (loop\n (disp Grid T\n '((This) (pack \" \" (: val) \" \")) )\n (wait 1000)\n (for Col Grid\n (for This Col\n (case (=: next (: val))\n (\"H\" (=: next \"t\"))\n (\"t\" (=: next \".\"))\n (\".\"\n (when\n (>=\n 2\n (cnt # Count neighbors\n '((Dir) (= \"H\" (get (Dir This) 'val)))\n (quote\n west east south north\n ((X) (south (west X)))\n ((X) (north (west X)))\n ((X) (south (east X)))\n ((X) (north (east X))) ) )\n 1 )\n (=: next \"H\") ) ) ) ) )\n (for Col Grid # Update\n (for This Col\n (=: val (: next)) ) )\n (prinl) ) )\n", "language": "PicoLisp" }, { "code": "Enumeration\n #Empty\n #Electron_head\n #Electron_tail\n #Conductor\nEndEnumeration\n\n#Delay=100\n#XSize=23\n#YSize=12\n\nProcedure Limit(n, min, max)\n If n<min\n n=min\n ElseIf n>max\n n=max\n EndIf\n ProcedureReturn n\nEndProcedure\n\nProcedure Moore_neighborhood(Array World(2),x,y)\n Protected cnt=0, i, j\n For i=Limit(x-1, 0, #XSize) To Limit(x+1, 0, #XSize)\n For j=Limit(y-1, 0, #YSize) To Limit(y+1, 0, #YSize)\n If World(i,j)=#Electron_head\n cnt+1\n EndIf\n Next\n Next\n ProcedureReturn cnt\nEndProcedure\n\nProcedure PresentWireWorld(Array World(2))\n Protected x,y\n ;ClearConsole()\n For y=0 To #YSize\n For x=0 To #XSize\n ConsoleLocate(x,y)\n Select World(x,y)\n Case #Electron_head\n ConsoleColor(12,0): Print(\"#\")\n Case #Electron_tail\n ConsoleColor(4,0): Print(\"#\")\n Case #Conductor\n ConsoleColor(6,0): Print(\"#\")\n Default\n ConsoleColor(15,0): Print(\" \")\n EndSelect\n Next\n PrintN(\"\")\n Next\nEndProcedure\n\nProcedure UpdateWireWorld(Array World(2))\n Dim NewArray(#XSize,#YSize)\n Protected i, j\n For i=0 To #XSize\n For j=0 To #YSize\n Select World(i,j)\n Case #Electron_head\n NewArray(i,j)=#Electron_tail\n Case #Electron_tail\n NewArray(i,j)=#Conductor\n Case #Conductor\n Define m=Moore_neighborhood(World(),i,j)\n If m=1 Or m=2\n NewArray(i,j)=#Electron_head\n Else\n NewArray(i,j)=#Conductor\n EndIf\n Default ; e.g. should be Empty\n NewArray(i,j)=#Empty\n EndSelect\n Next\n Next\n CopyArray(NewArray(),World())\nEndProcedure\n\nIf OpenConsole()\n EnableGraphicalConsole(#True)\n ConsoleTitle(\"XOR() WireWorld\")\n ;- Set up the WireWorld\n Dim WW.i(#XSize,#YSize)\n Define x, y\n Restore StartWW\n For y=0 To #YSize\n For x=0 To #XSize\n Read.i WW(x,y)\n Next\n Next\n\n ;- Start the WireWorld simulation\n Repeat\n PresentWireWorld(WW())\n UpdateWireWorld(WW())\n Delay(#Delay)\n ForEver\nEndIf\n\nDataSection\n StartWW:\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n Data.i 0,0,0,3,3,3,3,2,1,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0\n Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0\n Data.i 0,0,0,2,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,3,3,3,3,3\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0\n Data.i 0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0\n Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0\n Data.i 0,0,0,2,3,3,3,3,1,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nEndDataSection\n", "language": "PureBasic" }, { "code": "CompilerIf #PB_Compiler_Unicode\n CompilerError \"The file handling in this small program is only in ASCII.\"\nCompilerEndIf\n\nEnumeration\n #Empty\n #Electron_head\n #Electron_tail\n #Conductor\n #COL_Empty = $000000\n #COL_Electron_head = $5100FE\n #COL_Electron_tail = $6A3595\n #COL_Conductor = $62C4FF\n #WW_Window = 0\n #WW_IGadget = 0\n #WW_Timer = 0\n #WW_Image = 0\nEndEnumeration\n\n#Delay=100\nGlobal XSize, YSize\n\nProcedure Limit(n, min, max)\n If n<min: n=min\n ElseIf n>max: n=max\n EndIf\n ProcedureReturn n\nEndProcedure\n\nProcedure Moore_neighborhood(Array World(2),x,y)\n Protected cnt=0, i, j\n For i=Limit(x-1, 0, XSize) To Limit(x+1, 0, XSize)\n For j=Limit(y-1, 0, YSize) To Limit(y+1, 0, YSize)\n If World(i,j)=#Electron_head\n cnt+1\n EndIf\n Next\n Next\n ProcedureReturn cnt\nEndProcedure\n\nProcedure PresentWireWorld(Array World(2))\n Protected x,y\n StartDrawing(ImageOutput(#WW_Image))\n For y=0 To YSize-1\n For x=0 To XSize-1\n Select World(x,y)\n Case #Electron_head\n Plot(x,y,#COL_Electron_head)\n Case #Electron_tail\n Plot(x,y,#COL_Electron_tail)\n Case #Conductor\n Plot(x,y,#COL_Conductor)\n Default\n Plot(x,y,#COL_Empty)\n EndSelect\n Next\n Next\n StopDrawing()\n ImageGadget(#WW_IGadget,0,0,XSize,YSize,ImageID(#WW_Image))\nEndProcedure\n\nProcedure UpdateWireWorld(Array World(2))\n Dim NewArray(XSize,YSize)\n Protected i, j\n For i=0 To XSize\n For j=0 To YSize\n Select World(i,j)\n Case #Electron_head\n NewArray(i,j)=#Electron_tail\n Case #Electron_tail\n NewArray(i,j)=#Conductor\n Case #Conductor\n Define m=Moore_neighborhood(World(),i,j)\n If m=1 Or m=2\n NewArray(i,j)=#Electron_head\n Else\n NewArray(i,j)=#Conductor\n EndIf\n Default ; e.g. should be Empty\n NewArray(i,j)=#Empty\n EndSelect\n Next\n Next\n CopyArray(NewArray(),World())\nEndProcedure\n\nProcedure LoadDataFromFile(File$,Array A(2))\n Define Line$, x, y, *c.Character\n If OpenFile(0,File$)\n ;\n ; Count non-commented lines & length of the first line, e.g. get Array(x,y)\n While Not Eof(0)\n Line$=Trim(ReadString(0))\n *c=@Line$\n If Not PeekC(*c)=';'\n y+1\n If Not x\n While PeekC(*c)>='0' And PeekC(*c)<='3'\n x+1: *c+1\n Wend\n EndIf\n EndIf\n Wend\n XSize=x: YSize=y\n Dim A(XSize,YSize)\n ;\n ; Read in the Wire-World\n y=0\n FileSeek(0,0)\n While Not Eof(0)\n Line$=Trim(ReadString(0))\n *c=@Line$\n If Not PeekC(*c)=';'\n x=0\n While x<XSize\n A(x,y)=PeekC(*c)-'0'\n x+1: *c+1\n Wend\n y+1\n EndIf\n Wend\n CloseFile(0)\n EndIf\nEndProcedure\n\n#Title=\"WireWorld, PureBasic\"\nIf OpenWindow(#WW_Window,0,0,XSize,YSize,#Title,#PB_Window_SystemMenu)\n Dim WW.i(0,0)\n Define Pattern$ = \"Text (*.txt)|*.txt\", Pattern = 0\n Define DefFile$ = \"WireWorld.txt\", Event\n Define Title$ = \"Please choose file To load\"\n Define File$ = OpenFileRequester(Title$, DefFile$, Pattern$, Pattern)\n AddWindowTimer(#WW_Window,#WW_Timer,#Delay)\n LoadDataFromFile(File$,WW())\n ResizeWindow(#WW_Window,0,0,XSize,YSize)\n CreateImage(#WW_Image,XSize,YSize)\n Repeat\n Event=WaitWindowEvent()\n If Event=#PB_Event_Timer\n PresentWireWorld(WW())\n UpdateWireWorld (WW())\n EndIf\n Until Event=#PB_Event_CloseWindow\nEndIf\n", "language": "PureBasic" }, { "code": "'''\nWireworld implementation.\n'''\n\nfrom io import StringIO\nfrom collections import namedtuple\nfrom pprint import pprint as pp\nimport copy\n\nWW = namedtuple('WW', 'world, w, h')\nhead, tail, conductor, empty = allstates = 'Ht. '\n\n\ninfile = StringIO('''\\\ntH.........\n. .\n ...\n. .\nHt.. ......\\\n''')\n\ndef readfile(f):\n '''file > initial world configuration'''\n world = [row.rstrip('\\r\\n') for row in f]\n height = len(world)\n width = max(len(row) for row in world)\n # fill right and frame in empty cells\n nonrow = [ \" %*s \" % (-width, \"\") ]\n world = nonrow + \\\n [ \" %*s \" % (-width, row) for row in world ] + \\\n nonrow\n world = [list(row) for row in world]\n return WW(world, width, height)\n\ndef newcell(currentworld, x, y):\n istate = currentworld[y][x]\n assert istate in allstates, 'Wireworld cell set to unknown value \"%s\"' % istate\n if istate == head:\n ostate = tail\n elif istate == tail:\n ostate = conductor\n elif istate == empty:\n ostate = empty\n else: # istate == conductor\n n = sum( currentworld[y+dy][x+dx] == head\n for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),\n (+0,-1), (+0,+1),\n (+1,-1), (+1,+0), (+1,+1) ) )\n ostate = head if 1 <= n <= 2 else conductor\n return ostate\n\ndef nextgen(ww):\n 'compute next generation of wireworld'\n world, width, height = ww\n newworld = copy.deepcopy(world)\n for x in range(1, width+1):\n for y in range(1, height+1):\n newworld[y][x] = newcell(world, x, y)\n return WW(newworld, width, height)\n\ndef world2string(ww):\n return '\\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )\n\nww = readfile(infile)\ninfile.close()\n\nfor gen in range(10):\n print ( (\"\\n%3i \" % gen) + '=' * (ww.w-4) + '\\n' )\n print ( world2string(ww) )\n ww = nextgen(ww)\n", "language": "Python" }, { "code": "#lang racket\n(require 2htdp/universe)\n(require 2htdp/image)\n(require racket/fixnum)\n\n; see the forest fire task, from which this is derived...\n(define-struct wire-world (width height cells) #:prefab)\n\n(define state:_ 0)\n(define state:. 1)\n(define state:H 2)\n(define state:t 3)\n\n(define (char->state c)\n (case c\n ((#\\_ #\\space) state:_)\n ((#\\.) state:.)\n ((#\\H) state:H)\n ((#\\t) state:t)))\n\n(define (initial-world l)\n (let ((h (length l))\n (w (string-length (first l))))\n (make-wire-world w h\n (for*/fxvector\n #:length (* h w)\n ((row (in-list l))\n (cell (in-string row)))\n (char->state cell)))))\n\n(define initial-list\n '(\"tH.........\"\n \". . \"\n \" ... \"\n \". . \"\n \"Ht.. ......\"))\n\n(define-syntax-rule (count-neighbours-in-state ww wh wc r# c# state-to-match)\n (for/sum\n ((r (in-range (- r# 1) (+ r# 2)))\n #:when (< -1 r wh)\n (c (in-range (- c# 1) (+ c# 2)))\n #:when (< -1 c ww)\n ;; note, this will check cell at (r#, c#), too but it's not\n ;; worth checking that r=r# and c=c# each time in\n ;; this case, we know that (r#, c#) is a conductor:\n ; #:unless (and (= r# r) (= c# c))\n (i (in-value (+ (* r ww) c)))\n #:when (= state-to-match (fxvector-ref wc i)))\n 1))\n\n(define (cell-new-state ww wh wc row col)\n (let ((cell (fxvector-ref wc (+ col (* row ww)))))\n (cond\n ((= cell state:_) cell) ; empty -> empty\n ((= cell state:t) state:.) ; tail -> empty\n ((= cell state:H) state:t) ; head -> tail\n ((<= 1 (count-neighbours-in-state ww wh wc row col state:H) 2) state:H)\n (else cell))))\n\n(define (wire-world-tick world)\n (define ww (wire-world-width world))\n (define wh (wire-world-height world))\n (define wc (wire-world-cells world))\n\n (define (/w x) (quotient x ww))\n (define (%w x) (remainder x ww))\n\n (make-wire-world\n ww wh\n (for/fxvector\n #:length (* ww wh)\n ((cell (in-fxvector wc))\n (r# (sequence-map /w (in-naturals)))\n (c# (sequence-map %w (in-naturals))))\n (cell-new-state ww wh wc r# c#))))\n\n(define colour:_ (make-color 0 0 0)) ; black\n(define colour:. (make-color 128 128 128)) ; grey\n(define colour:H (make-color 128 255 255)) ; bright cyan\n(define colour:t (make-color 0 128 128)) ; dark cyan\n\n(define colour-vector (vector colour:_ colour:. colour:H colour:t))\n(define (cell-state->colour state) (vector-ref colour-vector state))\n\n(define render-scaling 20)\n(define (render-world W)\n (define ww (wire-world-width W))\n (define wh (wire-world-height W))\n (define wc (wire-world-cells W))\n (let* ((flat-state\n (for/list ((cell (in-fxvector wc)))\n (cell-state->colour cell))))\n (place-image (scale render-scaling (color-list->bitmap flat-state ww wh))\n (* ww (/ render-scaling 2))\n (* wh (/ render-scaling 2))\n (empty-scene (* render-scaling ww) (* render-scaling wh)))))\n\n(define (run-wire-world #:initial-state W)\n (big-bang\n (initial-world W) ;; initial state\n [on-tick wire-world-tick\n 1/8 ; tick time (seconds)\n ]\n [to-draw render-world]))\n\n(run-wire-world #:initial-state initial-list)\n", "language": "Racket" }, { "code": "class Wireworld {\n has @.line;\n method height returns Int { @!line.elems }\n method width returns Int { max @!line».chars }\n\n multi method new(@line) { samewith :@line }\n multi method new($str ) { samewith $str.lines }\n\n method gist { join \"\\n\", @.line }\n\n method !neighbors($i where ^$.height, $j where ^$.width)\n {\n my @i = grep ^$.height, $i «+« (-1, 0, 1);\n my @j = grep ^$.width, $j «+« (-1, 0, 1);\n gather for @i X @j -> (\\i, \\j) {\n next if [ i, j ] ~~ [ $i, $j ];\n take @!line[i].comb[j];\n }\n }\n method succ {\n my @succ;\n for ^$.height X ^$.width -> ($i, $j) {\n @succ[$i] ~=\n do given @.line[$i].comb[$j] {\n when 'H' { 't' }\n when 't' { '.' }\n when '.' {\n grep('H', self!neighbors($i, $j)) == 1|2 ?? 'H' !! '.'\n }\n default { ' ' }\n }\n }\n return self.new: @succ;\n }\n}\n\nmy %*SUB-MAIN-OPTS;\n%*SUB-MAIN-OPTS<named-anywhere> = True;\n\nmulti sub MAIN (\n IO() $filename,\n Numeric:D :$interval = 1/4,\n Bool :$stop-on-repeat,\n) {\n run-loop :$interval, :$stop-on-repeat, Wireworld.new: $filename.slurp;\n}\n\n#| run a built-in example\nmulti sub MAIN (\n Numeric:D :$interval = 1/4,\n Bool :$stop-on-repeat,\n) {\n run-loop\n :$interval,\n :$stop-on-repeat,\n Wireworld.new:\n\tQ:to/§/\n\ttH.........\n\t. .\n\t ...\n\t. .\n\tHt.. ......\n\t§\n}\n\nsub run-loop (\n Wireworld:D $initial,\n Real:D(Numeric) :$interval = 1/4,\n Bool :$stop-on-repeat\n){\n my %seen is SetHash;\n\n print \"\\e7\"; # save cursor position\n for $initial ...^ * eqv * { # generate a sequence (uses .succ)\n print \"\\e8\"; # restore cursor position\n .say;\n last if $stop-on-repeat and %seen{ .gist }++;\n sleep $interval;\n }\n}\n", "language": "Raku" }, { "code": "/*REXX program displays a wire world Cartesian grid of four─state cells. */\nparse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps\nif iFID=='' then iFID= \"WIREWORLD.TXT\" /*should default input file be used? */\n bla = 'BLANK' /*the \"name\" for a blank. */\ngenerations = p(generations 100 ) /*number generations that are allowed. */\n rows = p(rows 3 ) /*the number of cell rows. */\n cols = p(cols 3 ) /* \" \" \" \" columns. */\n bare = pickChar(bare bla ) /*character used to show an empty cell.*/\nclearScreen = p(clearScreen 0 ) /*1 means to clear the screen. */\n head = pickChar(head 'H' ) /*pick the character for the head. */\n tail = pickChar(tail 't' ) /* \" \" \" \" \" tail. */\n wire = pickChar(wire . ) /* \" \" \" \" \" wire. */\n reps = p(reps 2 ) /*stop program if there are 2 repeats.*/\nfents= max(cols, linesize() - 1) /*the fence width used after displaying*/\n#reps= 0; $.= bare; gens= abs(generations) /*at start, universe is new and barren.*/\n /* [↓] read the input file. */\n do r=1 while lines(iFID)\\==0 /*keep reading until the End─Of─File. */\n q= strip( linein(iFID), 'T') /*get a line from input file. */\n L= length(q); cols= max(cols, L) /*calculate maximum number of columns. */\n do c=1 for L; $.r.c= substr(q, c, 1) /*assign the cells for the R row. */\n end /*c*/\n end /*r*/\n!.= 0; signal on halt /*initial state of cells; handle halt.*/\nrows= r - 1; life= 0; call showCells /*display initial state of the cells. */\n /*watch cells evolve, 4 possible states*/\n do life=1 for gens; @.= bare /*perform for the number of generations*/\n do r=1 for rows /*process each of the rows. */\n do c=1 for cols; ?= $.r.c; ??= ? /* \" \" \" \" columns. */\n select /*determine the type of cell. */\n when ?==head then ??= tail\n when ?==tail then ??= wire\n when ?==wire then do; #= hood(); if #==1 | #==2 then ??= head; end\n otherwise nop\n end /*select*/\n @.r.c= ?? /*possible assign a cell a new state.*/\n end /*c*/\n end /*r*/\n\n call assign$ /*assign alternate cells ──► real world*/\n if generations>0 | life==gens then call showCells\n end /*life*/\n /*stop watching the universe (or life).*/\nhalt: if life-1\\==gens then say 'The ───Wireworld─── program was interrupted by user.'\ndone: exit 0 /*stick a fork in it, we are all done.*/\n/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/\n$: parse arg _row,_col; return $._row._col==head\nassign$: do r=1 for rows; do c=1 for cols; $.r.c= @.r.c; end; end; return\nhood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1)\np: return word(arg(1), 1) /*pick the 1st word in list.*/\npickChar: parse arg _ .;arg U .;L=length(_);if U==bla then _=' '; if L==3 then _=d2c(_);if L==2 then _=x2c(_);return _\nshowRows: _=; do r=1 for rows; z=; do c=1 for cols; z= z||$.r.c; end; z= strip(z,'T'); say z; _= _||z; end; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshowCells: if clearScreen then 'CLS' /*◄──change CLS for the host*/\n call showRows /*show rows in proper order.*/\n say right( copies('═', fents)life, fents) /*display a title for cells.*/\n if _=='' then signal done /*No life? Then stop run. */\n if !._ then #reps= #reps + 1 /*detected repeated pattern.*/\n !._= 1 /*it is now an extant state.*/\n if reps\\==0 & #reps<=reps then return /*so far, so good, no reps.*/\n say '\"Wireworld\" repeated itself' reps \"times, the program is stopping.\"\n signal done /*jump to this pgm's \"exit\".*/\n", "language": "REXX" }, { "code": "/* gnu assembler syntax */\nwireworld:\n/* unsigned int width (a0) */\n/* unsigned int height (a1) */\n/* char* grid (a2) */\n\n mv a4,a2\n\n li t4,'. /* conductor */\n li t5,'H /* head */\n li t6,'t /* tail */\n\n addi t2,a0,-1\n addi t3,a1,-1\n\n mv t1,zero\n.yloop: /* outer loop (y) */\n mv t0,zero\n.xloop: /* inner loop (x) */\n\n lb a5,0(a4)\n bgt a5,t4,.torh\n blt a5,t4,.empty\n\n/* conductor: */\n/* unsigned int head_count (a3) */\n/* char* test_ptr (a6) */\n/* char test (a7) */\n\n mv a3,zero\n sub a6,a4,a0\n addi a6,a6,-1\n\n0: beq t1,zero,1f /* bounds up */\n beq t0,zero,0f /* bounds left */\n lb a7,0(a6)\n bne a7,t6,0f\n addi a3,a3,1\n\n0: lb a7,1(a6)\n bne a7,t6,0f\n addi a3,a3,1\n\n0: beq t0,t2,0f /* bounds right */\n lb a7,2(a6)\n bne a7,t6,0f\n addi a3,a3,1\n\n0:1: add a6,a6,a0\n beq t0,zero,0f /* bounds left */\n lb a7,0(a6)\n bne a7,t6,0f\n addi a3,a3,1\n\n0: beq t0,t2,0f /* bounds right */\n lb a7,2(a6)\n bne a7,t5,0f\n addi a3,a3,1\n\n0: add a6,a6,a0\n\n beq t1,t3,1f /* bounds down */\n beq t0,zero,0f /* bounds left */\n lb a7,0(a6)\n bne a7,t5,0f\n addi a3,a3,1\n\n0: lb a7,1(a6)\n bne a7,t5,0f\n addi a3,a3,1\n\n0: beq t0,t2,0f /* bounds right */\n lb a7,2(a6)\n bne a7,t5,0f\n addi a3,a3,1\n\n0:1: beq a3,zero,.empty\n addi a3,a3,-2\n bgt a3,zero,.empty\n\n mv a5,t5 /* convert conductor to electron head */\n j .save\n\n.torh: beq a5,t6,.tail\n\n.head: mv a5,t6\n j .save\n\n.tail: mv a5,t4\n.save: sb a5,0(a4)\n.empty: /* do nothing */\n\n/* end x-loop */\n addi a4,a4,1\n addi t0,t0,1\n bne t0,a0,.xloop\n\n/* end y-loop */\n addi t1,t1,1\n bne t1,a1,.yloop\n\n ret\n", "language": "RISC-V-Assembly" }, { "code": "#include <stdio.h>\n#include <string.h>\n\nchar init[] = \" tH....tH \"\n \" . ...... \"\n \" ........ . \"\n \" .. .... .. .. .. \"\n \".. ... . ..tH....tH... .tH..... ....tH.. .tH.\"\n \" .. .... .. .. .. \"\n \" tH...... . \"\n \" . ....tH \"\n \" ...Ht... \";\nint width = 60;\nint height = 9;\n\nvoid wireworld(unsigned int, unsigned int, char *);\n\nint main() {\n char tmp[width + 1] = {};\n do {\n for (int i = 0; i < height; i++) {\n strncpy(tmp, init + i * width, width);\n puts(tmp);\n }\n wireworld(width, height, init);\n } while (getchar());\n\n return 0;\n}\n", "language": "RISC-V-Assembly" }, { "code": "use std::str::FromStr;\n\n#[derive(Debug, Copy, Clone, PartialEq)]\npub enum State {\n Empty,\n Conductor,\n ElectronTail,\n ElectronHead,\n}\n\nimpl State {\n fn next(&self, e_nearby: usize) -> State {\n match self {\n State::Empty => State::Empty,\n State::Conductor => {\n if e_nearby == 1 || e_nearby == 2 {\n State::ElectronHead\n } else {\n State::Conductor\n }\n }\n State::ElectronTail => State::Conductor,\n State::ElectronHead => State::ElectronTail,\n }\n }\n}\n\n#[derive(Debug, Clone, PartialEq)]\npub struct WireWorld {\n pub width: usize,\n pub height: usize,\n pub data: Vec<State>,\n}\n\nimpl WireWorld {\n pub fn new(width: usize, height: usize) -> Self {\n WireWorld {\n width,\n height,\n data: vec![State::Empty; width * height],\n }\n }\n\n pub fn get(&self, x: usize, y: usize) -> Option<State> {\n if x >= self.width || y >= self.height {\n None\n } else {\n self.data.get(y * self.width + x).copied()\n }\n }\n\n pub fn set(&mut self, x: usize, y: usize, state: State) {\n self.data[y * self.width + x] = state;\n }\n\n fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize\n where F: FnMut(State) -> bool\n {\n let (x, y) = (x as i32, y as i32);\n let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];\n\n neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()\n }\n\n pub fn next(&mut self) {\n let mut next_state = vec![];\n for y in 0..self.height {\n for x in 0..self.width {\n let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);\n next_state.push(self.get(x, y).unwrap().next(e_count));\n }\n }\n self.data = next_state;\n }\n}\n\nimpl FromStr for WireWorld {\n type Err = ();\n fn from_str(s: &str) -> Result<WireWorld, ()> {\n let s = s.trim();\n let height = s.lines().count();\n let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);\n let mut world = WireWorld::new(width, height);\n\n for (y, line) in s.lines().enumerate() {\n for (x, ch) in line.trim_end().chars().enumerate() {\n let state = match ch {\n '.' => State::Conductor,\n 't' => State::ElectronTail,\n 'H' => State::ElectronHead,\n _ => State::Empty,\n };\n world.set(x, y, state);\n }\n }\n Ok(world)\n }\n}\n", "language": "Rust" }, { "code": "use pixels::{Pixels, SurfaceTexture};\nuse winit::event::*;\nuse winit::event_loop::{ControlFlow, EventLoop};\nuse winit::window::WindowBuilder;\nuse std::{env, fs};\n\nmod wireworld;\nuse wireworld::{State, WireWorld};\n\nconst EMPTY_COLOR: [u8; 3] = [0x00, 0x00, 0x00];\nconst WIRE_COLOR: [u8; 3] = [0xFC, 0xF9, 0xF8];\nconst HEAD_COLOR: [u8; 3] = [0xFC, 0x00, 0x00];\nconst TAIL_COLOR: [u8; 3] = [0xFC, 0x99, 0x33];\n\nfn main() {\n let args: Vec<_> = env::args().collect();\n if args.len() < 2 {\n eprintln!(\"Error: No Input File\");\n std::process::exit(1);\n }\n\n let input_file = fs::read_to_string(&args[1]).unwrap();\n let mut world: WireWorld = input_file.parse().unwrap();\n\n let event_loop = EventLoop::new();\n let window = WindowBuilder::new()\n .with_title(format!(\"Wireworld - {}\", args[1]))\n .build(&event_loop).unwrap();\n let size = window.inner_size();\n let texture = SurfaceTexture::new(size.width, size.height, &window);\n let mut image_buffer = Pixels::new(world.width as u32, world.height as u32, texture).unwrap();\n\n event_loop.run(move |ev, _, flow| {\n match ev {\n Event::WindowEvent {\n event: WindowEvent::CloseRequested, ..\n } => {\n *flow = ControlFlow::Exit;\n }\n Event::WindowEvent {\n event: WindowEvent::KeyboardInput {\n input: KeyboardInput {\n state: ElementState::Pressed,\n virtual_keycode: Some(VirtualKeyCode::Space),\n ..\n }, ..\n }, ..\n } => {\n world.next();\n window.request_redraw();\n }\n Event::RedrawRequested(_) => {\n let frame = image_buffer.get_frame();\n for (pixel, state) in frame.chunks_exact_mut(4).zip(world.data.iter()) {\n let color = match state {\n State::Empty => EMPTY_COLOR,\n State::Conductor => WIRE_COLOR,\n State::ElectronTail => TAIL_COLOR,\n State::ElectronHead => HEAD_COLOR,\n };\n\n pixel[0] = color[0]; // R\n pixel[1] = color[1]; // G\n pixel[2] = color[2]; // B\n pixel[3] = 0xFF; // A\n }\n image_buffer.render().unwrap();\n }\n _ => {}\n }\n });\n}\n", "language": "Rust" }, { "code": "var f = [[], DATA.lines.map {['', .chars..., '']}..., []]\n\n10.times {\n say f.map { .join(\" \") + \"\\n\" }.join\n var a = [[]]\n for y in (1 ..^ f.end) {\n var r = f[y]\n var rr = ['']\n for x in (1 ..^ r.end) {\n var c = r[x]\n rr << (\n given(c) {\n when('H') { 't' }\n when('t') { '.' }\n when('.') { <. H>[[f[y-1 .. y+1]].map{.[x-1 .. x+1]}.count('H') ~~ [1,2]] }\n default { c }\n }\n )\n }\n rr << ''\n a << rr\n }\n f = [a..., []]\n}\n\n__DATA__\ntH.........\n. .\n ...\n. .\nHt.. ......\n", "language": "Sidef" }, { "code": "(* Maximilian Wuttke 12.04.2016 *)\n\ntype world = char vector vector\n\nfun getstate (w:world, (x, y)) = (Vector.sub (Vector.sub (w, y), x)) handle Subscript => #\" \"\n\nfun conductor (w:world, (x, y)) =\n\tlet\n\t val s = [getstate (w, (x-1, y-1)) = #\"H\", getstate (w, (x-1, y)) = #\"H\", getstate (w, (x-1, y+1)) = #\"H\",\n\t getstate (w, (x, y-1)) = #\"H\", getstate (w, (x, y+1)) = #\"H\",\n\t getstate (w, (x+1, y-1)) = #\"H\", getstate (w, (x+1, y)) = #\"H\", getstate (w, (x+1, y+1)) = #\"H\"]\n\t (* Count `true` in s *)\n\t val count = List.length (List.filter (fn x => x=true) s)\n\tin\n\t if count = 1 orelse count = 2 then #\"H\" else #\".\"\n\tend\n\nfun translate (w:world, (x, y)) =\n\tcase getstate (w, (x, y)) of\n\t #\" \" => #\" \"\n\t | #\"H\" => #\"t\"\n\t | #\"t\" => #\".\"\n\t | #\".\" => conductor (w, (x, y))\n\t | s => s\n\nfun next_world (w : world) = Vector.mapi (fn (y, row) => Vector.mapi (fn (x, _) => translate (w, (x, y))) row) w\n\n\n(* Test *)\n\n(* makes a list of strings into a world *)\nfun make_world (rows : string list) : world =\n\tVector.fromList (map (fn (row : string) => Vector.fromList (explode row)) rows)\n\n\n(* word_str reverses make_world *)\nfun vec_str (r:char vector) = implode (List.tabulate (Vector.length r, fn x => Vector.sub (r, x)))\nfun world_str (w:world) = List.tabulate (Vector.length w, fn y => vec_str (Vector.sub (w, y)))\nfun print_world (w:world) = (map (fn row_str => print (row_str ^ \"\\n\")) (world_str w); ())\n\nval test = make_world [\n\t\"tH.........\",\n\t\". . \",\n\t\" ... \",\n\t\". . \",\n\t\"Ht.. ......\"]\n", "language": "Standard-ML" }, { "code": "#import std\n\nrule = case~&l\\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?</`H! `.!}\n\nneighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*\n\nevolve \"n\" = @iNC ~&x+ rep\"n\" ^C\\~& rule**+ neighborhoods@h\n", "language": "Ursala" }, { "code": "diode =\n\n<\n ' .. ',\n 'tH....... .Ht',\n ' .. '>\n\n#show+\n\nexample = mat0 evolve13 diode\n", "language": "Ursala" }, { "code": "import \"./fmt\" for Fmt\nimport \"./ioutil\" for FileUtil, Stdin\n\nvar rows = 0 // extent of input configuration\nvar cols = 0 // \"\"\"\nvar rx = 0 // grid extent (includes border)\nvar cx = 0 // \"\"\"\nvar mn = [] // offsets of Moore neighborhood\n\nvar print = Fn.new { |grid|\n System.print(\"__\" * cols)\n System.print()\n for (r in 1..rows) {\n for (c in 1..cols) Fmt.write(\" $s\", grid[r*cx+c])\n System.print()\n }\n}\n\nvar step = Fn.new { |dst, src|\n for (r in 1..rows) {\n for (c in 1..cols) {\n var x = r*cx + c\n dst[x] = src[x]\n if (dst[x] == \"H\") {\n dst[x] = \"t\"\n } else if (dst[x] == \"t\") {\n dst[x] = \".\"\n } else if (dst[x] == \".\") {\n var nn = 0\n for (n in mn) {\n if (src[x+n] == \"H\") nn = nn + 1\n }\n if (nn == 1 || nn == 2) dst[x] = \"H\"\n }\n }\n }\n}\n\nvar srcRows = FileUtil.readLines(\"ww.config\")\nrows = srcRows.count\nfor (r in srcRows) {\n if (r.count > cols) cols = r.count\n}\nrx = rows + 2\ncx = cols + 2\nmn = [-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1]\n\n// allocate two grids and copy input into first grid\nvar odd = List.filled(rx*cx, \" \")\nvar even = List.filled(rx*cx, \" \")\n\nvar ri = 0\nfor (r in srcRows) {\n for (i in 0...r.count) {\n odd[(ri+1)*cx+1+i] = r[i]\n }\n ri = ri + 1\n}\n\n// run\nwhile (true) {\n print.call(odd)\n step.call(even, odd)\n Stdin.readLine() // wait for enter to be pressed\n\n print.call(even)\n step.call(odd, even)\n Stdin.readLine() // ditto\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\nchar New(53,40), Old(53,40);\n\nproc Block(X0, Y0, C); \\Display a colored block\nint X0, Y0, C; \\big (6x5) coordinates, char\nint X, Y;\n[case C of \\convert char to color\n ^H: C:= $9; \\blue\n ^t: C:= $C; \\red\n ^.: C:= $E \\yellow\nother C:= 0; \\black\nfor Y:= Y0*5 to Y0*5+4 do \\make square blocks by correcting aspect ratio\n for X:= X0*6 to X0*6+5 do \\ (6x5 = square)\n Point(X,Y,C);\n];\n\nint X, Y, C;\n[SetVid($13); \\set 320x200 graphics display\nfor Y:= 0 to 40-1 do \\initialize New with space (empty) characters\n for X:= 0 to 53-1 do\n New(X, Y):= ^ ;\nX:= 1; Y:= 1; \\read file from command line, skipping borders\nloop [C:= ChIn(1);\n case C of\n $0D: X:= 1; \\carriage return\n $0A: Y:= Y+1; \\line feed\n $1A: quit \\end of file\n other [New(X,Y):= C; X:= X+1];\n ];\nrepeat C:= Old; Old:= New; New:= C; \\swap arrays, by swapping their pointers\n for Y:= 1 to 39-1 do \\generate New array from Old\n for X:= 1 to 52-1 do \\ (skipping borders)\n [case Old(X,Y) of\n ^ : New(X,Y):= ^ ; \\copy empty to empty\n ^H: New(X,Y):= ^t; \\convert head to tail\n ^t: New(X,Y):= ^. \\convert tail to conductor\n other [C:= (Old(X-1,Y-1)=^H) + (Old(X+0,Y-1)=^H) + \\head count\n (Old(X+1,Y-1)=^H) + (Old(X-1,Y+0)=^H) + \\ in neigh-\n (Old(X+1,Y+0)=^H) + (Old(X-1,Y+1)=^H) + \\ boring\n (Old(X+0,Y+1)=^H) + (Old(X+1,Y+1)=^H); \\ cells\n New(X,Y):= if C=-1 or C=-2 then ^H else ^.; \\ (true=-1)\n ];\n Block(X, Y, New(X,Y)); \\display result\n ];\n Sound(0, 6, 1); \\delay about 1/3 second\nuntil KeyHit; \\keystroke terminates program\nSetVid(3); \\restore normal text mode\n]\n", "language": "XPL0" }, { "code": "open window 230,130\nbackcolor 0,0,0\nclear window\n\nlabel circuit\n\tDATA \" \"\n\tDATA \" tH......... \"\n\tDATA \" . . \"\n\tDATA \" ... \"\n\tDATA \" . . \"\n\tDATA \" Ht.. ...... \"\n\tDATA \" \"\n\tDATA \"\"\n\t\ndo\n\tread a$\n\tif a$ = \"\" break\n\tn = n + 1\n\tredim t$(n)\n\tt$(n) = a$+a$\nloop\n\nsize = len(t$(1))/2\nE2 = size\nfirst = true\nOrig = 0\nDest = E2\n\ndo\n for y = 2 to n-1\n for x = 2 to E2-1\n switch mid$(t$(y),x+Orig,1)\n case \" \": color 32,32,32 : mid$(t$(y),x+Dest,1) = \" \" : break\n case \"H\": color 0,0,255 : mid$(t$(y),x+Dest,1) = \"t\" : break\n case \"t\": color 255,0,0 : mid$(t$(y),x+Dest,1) = \".\" : break\n case \".\":\n color 255,200,0\n t = 0\n for y1 = y-1 to y+1\n \tfor x1 = x-1 to x+1 \t\t\n \t\tt = t + (\"H\" = mid$(t$(y1),x1+Orig,1))\n \tnext x1\n next y1\n if t=1 or t=2 then\n \tmid$(t$(y),x+Dest,1) = \"H\"\n else\n \tmid$(t$(y),x+Dest,1) = \".\"\n end if\n end switch\n fill circle x*16, y*16, 8\n next x\n print t$(y),\"=\"\n next y\n first = not first\n if first then\n \tOrig = 0 : Dest = E2\n else\n \tOrig = E2 : Dest = 0\n end if\n wait .5\nloop\n", "language": "Yabasic" } ]
Wireworld
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Word_ladder\n", "language": "00-META" }, { "code": "Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.\n\nOnly one letter may be changed at a time and the change must result in a word in [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt unixdict], the minimum number of intermediate words should be used.\n\nDemonstrate the following:\n\nA boy can be made into a man: boy -> bay -> ban -> man\n\nWith a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady\n\nA john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane \n\nA child can not be turned into an adult.\n\nOptional transpositions of your choice.\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F isOneAway(word1, word2)\n V result = 0B\n L(i) 0 .< word1.len\n I word1[i] != word2[i]\n I result\n R 0B\n E\n result = 1B\n R result\n\nDefaultDict[Int, [String]] words\n\nL(word) File(‘unixdict.txt’).read().split(\"\\n\")\n words[word.len] [+]= word\n\nF find_path(start, target)\n V lg = start.len\n assert(target.len == lg, ‘Source and destination must have same length.’)\n assert(start C :words[lg], ‘Source must exist in the dictionary.’)\n assert(target C :words[lg], ‘Destination must exist in the dictionary.’)\n\n V currPaths = [[start]]\n V pool = copy(:words[lg])\n\n L\n [[String]] newPaths\n [String] added\n L(candidate) pool\n L(path) currPaths\n I isOneAway(candidate, path.last)\n V newPath = path [+] [candidate]\n I candidate == target\n R newPath\n E\n newPaths.append(newPath)\n added.append(candidate)\n L.break\n\n I newPaths.empty\n L.break\n currPaths = move(newPaths)\n L(w) added\n pool.remove(w)\n\n R [String]()\n\nL(start, target) [(‘boy’, ‘man’), (‘girl’, ‘lady’), (‘john’, ‘jane’), (‘child’, ‘adult’), (‘cat’, ‘dog’), (‘lead’, ‘gold’), (‘white’, ‘black’), (‘bubble’, ‘tickle’)]\n V path = find_path(start, target)\n I path.empty\n print(‘No path from \"’start‘\" to \"’target‘\".’)\n E\n print(path.join(‘ -> ’))\n", "language": "11l" }, { "code": "# quick implementation of a stack of INT.\n real program starts after it.\n#\nMODE STACK = STRUCT (INT top, FLEX[1:0]INT data, INT increment);\n\nPROC makestack = (INT increment)STACK: (1, (), increment);\n\nPROC pop = (REF STACK s)INT: ( top OF s -:= 1; (data OF s)[top OF s] );\n\nPROC push = (REF STACK s, INT n)VOID:\n BEGIN\n IF top OF s > UPB data OF s THEN\n [ UPB data OF s + increment OF s ]INT tmp;\n tmp[1 : UPB data OF s] := data OF s;\n data OF s := tmp\n FI;\n (data OF s)[top OF s] := n;\n top OF s +:= 1\n END;\n\nPROC empty = (REF STACK s)BOOL: top OF s <= 1;\n\nPROC contents = (REF STACK s)[]INT: (data OF s)[:top OF s - 1];\n\n# start solution #\n\n[]STRING words = BEGIN # load dictionary file into array #\n FILE f;\n BOOL eof := FALSE;\n open(f, \"unixdict.txt\", stand in channel);\n on logical file end(f, (REF FILE f)BOOL: eof := TRUE);\n INT idx := 1;\n FLEX [1:0] STRING words;\n STRING word;\n WHILE NOT eof DO\n get(f, (word, newline));\n IF idx > UPB words THEN\n HEAP [1 : UPB words + 10000]STRING tmp;\n tmp[1 : UPB words] := words;\n words := tmp\n FI;\n words[idx] := word;\n idx +:= 1\n OD;\n words[1:idx-1]\n END;\n\nINT nwords = UPB words;\n\nINT max word length = (INT mwl := 0;\n FOR i TO UPB words DO\n IF mwl < UPB words[i] THEN mwl := UPB words[i] FI\n OD;\n mwl);\n\n[nwords]FLEX[0]INT neighbors;\n\n[max word length]BOOL precalculated by length;\n\nFOR i TO UPB precalculated by length DO precalculated by length[i] := FALSE OD;\n\n# precalculating neighbours takes time, but not doing it is even slower... #\nPROC precalculate neighbors = (INT word length)VOID:\n BEGIN\n [nwords]REF STACK stacks;\n FOR i TO UPB stacks DO stacks[i] := NIL OD;\n FOR i TO UPB words DO\n IF UPB words[i] = word length THEN\n IF REF STACK(stacks[i]) :=: NIL THEN stacks[i] := HEAP STACK := makestack(10) FI;\n FOR j FROM i + 1 TO UPB words DO\n IF UPB words[j] = word length THEN\n IF neighboring(words[i], words[j]) THEN\n push(stacks[i], j);\n IF REF STACK(stacks[j]) :=: NIL THEN stacks[j] := HEAP STACK := makestack(10) FI;\n push(stacks[j], i)\n FI\n FI\n OD\n FI\n OD;\n FOR i TO UPB neighbors DO\n IF REF STACK(stacks[i]) :/=: NIL THEN\n neighbors[i] := contents(stacks[i])\n FI\n OD;\n precalculated by length [word length] := TRUE\n END;\n\nPROC neighboring = (STRING a, b)BOOL: # do a & b differ in just 1 char? #\n BEGIN\n INT diff := 0;\n FOR i TO UPB a DO IF a[i] /= b[i] THEN diff +:= 1 FI OD;\n diff = 1\n END;\n\nPROC word ladder = (STRING from, STRING to)[]STRING:\n BEGIN\n IF UPB from /= UPB to THEN fail FI;\n INT word length = UPB from;\n IF word length < 1 OR word length > max word length THEN fail FI;\n IF from = to THEN fail FI;\n INT start := 0;\n INT destination := 0;\n FOR i TO UPB words DO\n IF UPB words[i] = word length THEN\n IF words[i] = from THEN start := i\n ELIF words[i] = to THEN destination := i\n FI\n FI\n OD;\n IF destination = 0 OR start = 0 THEN fail FI;\n IF NOT precalculated by length [word length] THEN\n precalculate neighbors(word length)\n FI;\n STACK stack := makestack(1000);\n [nwords]INT distance;\n [nwords]INT previous;\n FOR i TO nwords DO distance[i] := nwords+1; previous[i] := 0 OD;\n INT shortest := nwords+1;\n distance[start] := 0;\n push(stack, start);\n WHILE NOT empty(stack)\n DO\n INT curr := pop(stack);\n INT dist := distance[curr];\n IF dist < shortest - 1 THEN\n # find neighbors and add them to the stack #\n FOR i FROM UPB neighbors[curr] BY -1 TO 1 DO\n INT n = neighbors[curr][i];\n IF distance[n] > dist + 1 THEN\n distance[n] := dist + 1;\n previous[n] := curr;\n IF n = destination THEN\n shortest := dist + 1\n ELSE\n push(stack, n)\n FI\n FI\n OD;\n IF curr = destination THEN shortest := dist FI\n FI\n OD;\n INT length = distance[destination] + 1;\n IF length > nwords THEN fail FI;\n [length]STRING result;\n INT curr := destination;\n FOR i FROM length BY -1 TO 1\n DO\n result[i] := words[curr];\n curr := previous[curr]\n OD;\n result EXIT\n fail: LOC [0] STRING\n END;\n\n[][]STRING pairs = ((\"boy\", \"man\"), (\"bed\", \"cot\"),\n (\"old\", \"new\"), (\"dry\", \"wet\"),\n\n (\"girl\", \"lady\"), (\"john\", \"jane\"),\n (\"lead\", \"gold\"), (\"poor\", \"rich\"),\n (\"lamb\", \"stew\"), (\"kick\", \"goal\"),\n (\"cold\", \"warm\"), (\"nude\", \"clad\"),\n\n (\"child\", \"adult\"), (\"white\", \"black\"),\n (\"bread\", \"toast\"), (\"lager\", \"stout\"),\n (\"bride\", \"groom\"), (\"table\", \"chair\"),\n\n (\"bubble\", \"tickle\"));\n\nFOR i TO UPB pairs\nDO\n STRING from = pairs[i][1], to = pairs[i][2];\n []STRING ladder = word ladder(from, to);\n IF UPB ladder = 0\n THEN print((\"No solution for \"\"\" + from + \"\"\" -> \"\"\" + to + \"\"\"\", newline))\n ELSE FOR j TO UPB ladder DO print(((j > 1 | \"->\" | \"\"), ladder[j])) OD;\n print(newline)\n FI\nOD\n", "language": "ALGOL-68" }, { "code": "#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\nusing word_map = std::map<size_t, std::vector<std::string>>;\n\n// Returns true if strings s1 and s2 differ by one character.\nbool one_away(const std::string& s1, const std::string& s2) {\n if (s1.size() != s2.size())\n return false;\n bool result = false;\n for (size_t i = 0, n = s1.size(); i != n; ++i) {\n if (s1[i] != s2[i]) {\n if (result)\n return false;\n result = true;\n }\n }\n return result;\n}\n\n// Join a sequence of strings into a single string using the given separator.\ntemplate <typename iterator_type, typename separator_type>\nstd::string join(iterator_type begin, iterator_type end,\n separator_type separator) {\n std::string result;\n if (begin != end) {\n result += *begin++;\n for (; begin != end; ++begin) {\n result += separator;\n result += *begin;\n }\n }\n return result;\n}\n\n// If possible, print the shortest chain of single-character modifications that\n// leads from \"from\" to \"to\", with each intermediate step being a valid word.\n// This is an application of breadth-first search.\nbool word_ladder(const word_map& words, const std::string& from,\n const std::string& to) {\n auto w = words.find(from.size());\n if (w != words.end()) {\n auto poss = w->second;\n std::vector<std::vector<std::string>> queue{{from}};\n while (!queue.empty()) {\n auto curr = queue.front();\n queue.erase(queue.begin());\n for (auto i = poss.begin(); i != poss.end();) {\n if (!one_away(*i, curr.back())) {\n ++i;\n continue;\n }\n if (to == *i) {\n curr.push_back(to);\n std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n return true;\n }\n std::vector<std::string> temp(curr);\n temp.push_back(*i);\n queue.push_back(std::move(temp));\n i = poss.erase(i);\n }\n }\n }\n std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n return false;\n}\n\nint main() {\n word_map words;\n std::ifstream in(\"unixdict.txt\");\n if (!in) {\n std::cerr << \"Cannot open file unixdict.txt.\\n\";\n return EXIT_FAILURE;\n }\n std::string word;\n while (getline(in, word))\n words[word.size()].push_back(word);\n word_ladder(words, \"boy\", \"man\");\n word_ladder(words, \"girl\", \"lady\");\n word_ladder(words, \"john\", \"jane\");\n word_ladder(words, \"child\", \"adult\");\n word_ladder(words, \"cat\", \"dog\");\n word_ladder(words, \"lead\", \"gold\");\n word_ladder(words, \"white\", \"black\");\n word_ladder(words, \"bubble\", \"tickle\");\n return EXIT_SUCCESS;\n}\n", "language": "C++" }, { "code": "// Word ladder: Nigel Galloway. June 5th., 2021\nlet fG n g=n|>List.partition(fun n->2>Seq.fold2(fun z n g->z+if n=g then 0 else 1) 0 n g)\nlet wL n g=let dict=seq{use n=System.IO.File.OpenText(\"unixdict.txt\") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(Seq.length>>(=)(Seq.length n))|>List.ofSeq|>List.except [n]\n let (|Done|_|) n=n|>List.tryFind((=)g)\n let rec wL n g l=match n with h::t->let i,e=fG l (List.head h) in match i with Done i->Some((i::h)|>List.rev) |_->wL t ((i|>List.map(fun i->i::h))@g) e\n |_->match g with []->None |_->wL g [] l\n let i,e=fG dict n in match i with Done i->Some([n;g]) |_->wL(i|>List.map(fun g->[g;n])) [] e\n[(\"boy\",\"man\");(\"girl\",\"lady\");(\"john\",\"jane\");(\"child\",\"adult\")]|>List.iter(fun(n,g)->printfn \"%s\" (match wL n g with Some n->n|>String.concat \" -> \" |_->n+\" into \"+g+\" can't be done\"))\n", "language": "F-Sharp" }, { "code": "[(\"evil\",\"good\");(\"god\",\"man\")]|>List.iter(fun(n,g)->printfn \"%s\" (match wL n g with Some n->n|>String.concat \" -> \" |_->n+\" into \"+g+\" can't be done\"))\n", "language": "F-Sharp" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"strings\"\n)\n\nfunc contains(a []string, s string) bool {\n for _, e := range a {\n if e == s {\n return true\n }\n }\n return false\n}\n\nfunc oneAway(a, b string) bool {\n sum := 0\n for i := 0; i < len(a); i++ {\n if a[i] != b[i] {\n sum++\n }\n }\n return sum == 1\n}\n\nfunc wordLadder(words []string, a, b string) {\n l := len(a)\n var poss []string\n for _, word := range words {\n if len(word) == l {\n poss = append(poss, word)\n }\n }\n todo := [][]string{{a}}\n for len(todo) > 0 {\n curr := todo[0]\n todo = todo[1:]\n var next []string\n for _, word := range poss {\n if oneAway(word, curr[len(curr)-1]) {\n next = append(next, word)\n }\n }\n if contains(next, b) {\n curr = append(curr, b)\n fmt.Println(strings.Join(curr, \" -> \"))\n return\n }\n for i := len(poss) - 1; i >= 0; i-- {\n if contains(next, poss[i]) {\n copy(poss[i:], poss[i+1:])\n poss[len(poss)-1] = \"\"\n poss = poss[:len(poss)-1]\n }\n }\n for _, s := range next {\n temp := make([]string, len(curr))\n copy(temp, curr)\n temp = append(temp, s)\n todo = append(todo, temp)\n }\n }\n fmt.Println(a, \"into\", b, \"cannot be done.\")\n}\n\nfunc main() {\n b, err := ioutil.ReadFile(\"unixdict.txt\")\n if err != nil {\n log.Fatal(\"Error reading file\")\n }\n bwords := bytes.Fields(b)\n words := make([]string, len(bwords))\n for i, bword := range bwords {\n words[i] = string(bword)\n }\n pairs := [][]string{\n {\"boy\", \"man\"},\n {\"girl\", \"lady\"},\n {\"john\", \"jane\"},\n {\"child\", \"adult\"},\n }\n for _, pair := range pairs {\n wordLadder(words, pair[0], pair[1])\n }\n}\n", "language": "Go" }, { "code": "import System.IO (readFile)\nimport Control.Monad (foldM)\nimport Data.List (intercalate)\nimport qualified Data.Set as S\n\ndistance :: String -> String -> Int\ndistance s1 s2 = length $ filter not $ zipWith (==) s1 s2\n\nwordLadders :: [String] -> String -> String -> [[String]]\nwordLadders dict start end\n | length start /= length end = []\n | otherwise = [wordSpace] >>= expandFrom start >>= shrinkFrom end\n where\n\n wordSpace = S.fromList $ filter ((length start ==) . length) dict\n\n expandFrom s = go [[s]]\n where\n go (h:t) d\n | S.null d || S.null f = []\n | end `S.member` f = [h:t]\n | otherwise = go (S.elems f:h:t) (d S.\\\\ f)\n where\n f = foldr (\\w -> S.union (S.filter (oneStepAway w) d)) mempty h\n\n shrinkFrom = scanM (filter . oneStepAway)\n\n oneStepAway x = (1 ==) . distance x\n\n scanM f x = fmap snd . foldM g (x,[x])\n where g (b, r) a = (\\x -> (x, x:r)) <$> f b a\n\nwordLadder :: [String] -> String -> String -> [String]\nwordLadder d s e = case wordLadders d s e of\n [] -> []\n h:_ -> h\n\nshowChain [] = putStrLn \"No chain\"\nshowChain ch = putStrLn $ intercalate \" -> \" ch\n\nmain = do\n dict <- lines <$> readFile \"unixdict.txt\"\n showChain $ wordLadder dict \"boy\" \"man\"\n showChain $ wordLadder dict \"girl\" \"lady\"\n showChain $ wordLadder dict \"john\" \"jane\"\n showChain $ wordLadder dict \"alien\" \"drool\"\n showChain $ wordLadder dict \"child\" \"adult\"\n", "language": "Haskell" }, { "code": "wordLadders2 :: String -> String -> [String] -> [[String]]\nwordLadders2 start end dict\n | length start /= length end = []\n | otherwise = pure wordSpace >>= expand start end >>= shrink end\n where\n\n wordSpace = S.fromList $ filter ((length start ==) . length) dict\n\n expand s e d = tail . map S.elems <$> go [S.singleton s] [S.singleton e] d\n where\n go (hs:ts) (he:te) d\n | S.null d || S.null fs || S.null fe = []\n | not $ S.null f1 = [reverse (f1:te) ++ hs:ts]\n | not $ S.null f2 = [reverse (he:te) ++ f2:ts]\n | not $ S.null f3 = [reverse (he:te) ++ f3:hs:ts]\n | otherwise = go (fs:hs:ts) (fe:he:te) (d S.\\\\ hs S.\\\\ he)\n where\n fs = front hs\n fe = front he\n f1 = fs `S.intersection` he\n f2 = fe `S.intersection` hs\n f3 = fs `S.intersection` fe\n front = S.foldr (\\w -> S.union (S.filter (oneStepAway w) d)) mempty\n\n shrink = scanM (findM . oneStepAway)\n\n oneStepAway x = (1 ==) . distance x\n\n scanM f x = fmap snd . foldM g (x,[x])\n where g (b, r) a = (\\x -> (x, x:r)) <$> f b a\n\n findM p = msum . map (\\x -> if p x then pure x else mzero)\n", "language": "Haskell" }, { "code": "import AStar (findPath, Graph(..))\nimport qualified Data.Map as M\n\ndistance :: String -> String -> Int\ndistance s1 s2 = length $ filter not $ zipWith (==) s1 s2\n\nwordLadder :: [String] -> String -> String -> [String]\nwordLadder dict start end = findPath g distance start end\n where\n short_dict = filter ((length start ==) . length) dict\n g = Graph $ \\w -> M.fromList [ (x, 1)\n | x <- short_dict\n , distance w x == 1 ]\n", "language": "Haskell" }, { "code": "extend=: {{\n j=. {:y\n l=. <:{:$m\n <y,\"1 0 I.l=m+/ .=\"1 j{m\n}}\n\nwlad=: {{\n l=. #x assert. l=#y\n words=. >(#~ l=#@>) cutLF fread 'unixdict.txt'\n ix=. ,:words i.x assert. ix<#words\n iy=. ,:words i.y assert. iy<#words\n while. -. 1 e. ix e.&, iy do.\n if. 0 e. ix,&# iy do. EMPTY return. end.\n ix=. ; words extend\"1 ix\n if. -. 1 e. ix e.&, iy do.\n iy=. ; words extend\"1 iy\n end.\n end.\n iy=. |.\"1 iy\n r=. ix,&,iy\n for_jk.(ix,&#iy)#:I.,ix +./@e.\"1/ iy do.\n ixj=. ({.jk){ix\n iyk=. ({:jk){iy\n for_c. ixj ([-.-.) iyk do.\n path=. (ixj{.~ixj i.c) , iyk}.~ iyk i.c\n if. path <&# r do. r=. path end.\n end.\n end.\n }.,' ',.r{words\n}}\n", "language": "J" }, { "code": " 'boy' wlad 'man'\nboy bay ban man\n 'girl' wlad 'lady'\ngirl gill gall gale gaze laze lazy lady\n 'john' wlad 'jane'\njohn cohn conn cone cane jane\n 'child' wlad 'adult'\n 'cat' wlad 'dog'\ncat cot cog dog\n 'lead' wlad 'gold'\nlead load goad gold\n 'white' wlad 'black'\nwhite whine chine chink clink blink blank black\n 'bubble' wlad 'tickle'\nbubble babble gabble garble gargle gaggle giggle jiggle jingle tingle tinkle tickle\n", "language": "J" }, { "code": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.PriorityQueue;\nimport java.util.Set;\nimport java.util.stream.IntStream;\n\npublic class WordLadder {\n private static int distance(String s1, String s2) {\n assert s1.length() == s2.length();\n return (int) IntStream.range(0, s1.length())\n .filter(i -> s1.charAt(i) != s2.charAt(i))\n .count();\n }\n\n private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {\n wordLadder(words, fw, tw, 8);\n }\n\n private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {\n if (fw.length() != tw.length()) {\n throw new IllegalArgumentException(\"From word and to word must have the same length\");\n }\n\n Set<String> ws = words.get(fw.length());\n if (ws.contains(fw)) {\n List<String> primeList = new ArrayList<>();\n primeList.add(fw);\n\n PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {\n int cmp1 = Integer.compare(chain1.size(), chain2.size());\n if (cmp1 == 0) {\n String last1 = chain1.get(chain1.size() - 1);\n int d1 = distance(last1, tw);\n\n String last2 = chain2.get(chain2.size() - 1);\n int d2 = distance(last2, tw);\n\n return Integer.compare(d1, d2);\n }\n return cmp1;\n });\n queue.add(primeList);\n\n while (queue.size() > 0) {\n List<String> curr = queue.remove();\n if (curr.size() > limit) {\n continue;\n }\n\n String last = curr.get(curr.size() - 1);\n for (String word : ws) {\n if (distance(last, word) == 1) {\n if (word.equals(tw)) {\n curr.add(word);\n System.out.println(String.join(\" -> \", curr));\n return;\n }\n\n if (!curr.contains(word)) {\n List<String> cp = new ArrayList<>(curr);\n cp.add(word);\n queue.add(cp);\n }\n }\n }\n }\n }\n\n System.err.printf(\"Cannot turn `%s` into `%s`%n\", fw, tw);\n }\n\n public static void main(String[] args) throws IOException {\n Map<Integer, Set<String>> words = new HashMap<>();\n for (String line : Files.readAllLines(Path.of(\"unixdict.txt\"))) {\n Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);\n wl.add(line);\n }\n\n wordLadder(words, \"boy\", \"man\");\n wordLadder(words, \"girl\", \"lady\");\n wordLadder(words, \"john\", \"jane\");\n wordLadder(words, \"child\", \"adult\");\n wordLadder(words, \"cat\", \"dog\");\n wordLadder(words, \"lead\", \"gold\");\n wordLadder(words, \"white\", \"black\");\n wordLadder(words, \"bubble\", \"tickle\", 12);\n }\n}\n", "language": "Java" }, { "code": "import java.io.*;\nimport java.util.*;\n\npublic class WordLadder {\n public static void main(String[] args) {\n try {\n Map<Integer, List<String>> words = new HashMap<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(\"unixdict.txt\"))) {\n String line;\n while ((line = reader.readLine()) != null)\n words.computeIfAbsent(line.length(), k -> new ArrayList<String>()).add(line);\n }\n wordLadder(words, \"boy\", \"man\");\n wordLadder(words, \"girl\", \"lady\");\n wordLadder(words, \"john\", \"jane\");\n wordLadder(words, \"child\", \"adult\");\n wordLadder(words, \"cat\", \"dog\");\n wordLadder(words, \"lead\", \"gold\");\n wordLadder(words, \"white\", \"black\");\n wordLadder(words, \"bubble\", \"tickle\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n // Returns true if strings s1 and s2 differ by one character.\n private static boolean oneAway(String s1, String s2) {\n if (s1.length() != s2.length())\n return false;\n boolean result = false;\n for (int i = 0, n = s1.length(); i != n; ++i) {\n if (s1.charAt(i) != s2.charAt(i)) {\n if (result)\n return false;\n result = true;\n }\n }\n return result;\n }\n\n // If possible, print the shortest chain of single-character modifications that\n // leads from \"from\" to \"to\", with each intermediate step being a valid word.\n // This is an application of breadth-first search.\n private static void wordLadder(Map<Integer, List<String>> words, String from, String to) {\n List<String> w = words.get(from.length());\n if (w != null) {\n Deque<String> poss = new ArrayDeque<>(w);\n Deque<String> f = new ArrayDeque<String>();\n f.add(from);\n Deque<Deque<String>> queue = new ArrayDeque<>();\n queue.add(f);\n while (!queue.isEmpty()) {\n Deque<String> curr = queue.poll();\n for (Iterator<String> i = poss.iterator(); i.hasNext(); ) {\n String str = i.next();\n if (!oneAway(str, curr.getLast()))\n continue;\n if (to.equals(str)) {\n curr.add(to);\n System.out.println(String.join(\" -> \", curr));\n return;\n }\n Deque<String> temp = new ArrayDeque<>(curr);\n temp.add(str);\n queue.add(temp);\n i.remove();\n }\n }\n }\n System.out.printf(\"%s into %s cannot be done.\\n\", from, to);\n }\n}\n", "language": "Java" }, { "code": "def count(stream): reduce stream as $i (0; .+1);\n\ndef words: [inputs]; # one way to read the word list\n\ndef oneAway($a; $b):\n ($a|explode) as $ax\n | ($b|explode) as $bx\n | 1 == count(range(0; $a|length) | select($ax[.] != $bx[.]));\n\n# input: the word list\ndef wordLadder($a; $b):\n ($a|length) as $len\n | { poss: map(select(length == $len)), # the relevant words\n todo: [[$a]] # possible chains\n }\n | until ( ((.todo|length) == 0) or .solution;\n .curr = .todo[0]\n | .todo |= .[1:]\n\t| .curr[-1] as $c\n | (.poss | map(select( oneAway(.; $c) ))) as $next\n | if ($b | IN($next[]))\n then .curr += [$b]\n | .solution = (.curr|join(\" -> \"))\n else .poss = (.poss - $next)\n\t | .curr as $curr\n | .todo = (reduce range(0; $next|length) as $i (.todo;\n . + [$curr + [$next[$i] ]] ))\n end )\n | if .solution then .solution\n else \"There is no ladder from \\($a) to \\($b).\"\n end ;\n\ndef pairs:\n [\"boy\", \"man\"],\n [\"girl\", \"lady\"],\n [\"john\", \"jane\"],\n [\"child\", \"adult\"],\n [\"word\", \"play\"]\n;\n\nwords\n| pairs as $p\n| wordLadder($p[0]; $p[1])\n", "language": "Jq" }, { "code": "const dict = Set(split(read(\"unixdict.txt\", String), r\"\\s+\"))\n\nfunction targeted_mutations(str::AbstractString, target::AbstractString)\n working, tried = [[str]], Set{String}()\n while all(a -> a[end] != target, working)\n newworking = Vector{Vector{String}}()\n for arr in working\n s = arr[end]\n push!(tried, s)\n for j in 1:length(s), c in 'a':'z'\n w = s[1:j-1] * c * s[j+1:end]\n if w in dict && !(w in tried)\n push!(newworking, [arr; w])\n end\n end\n end\n isempty(newworking) && return [[\"This cannot be done.\"]]\n working = newworking\n end\n return filter(a -> a[end] == target, working)\nend\n\nprintln(\"boy to man: \", targeted_mutations(\"boy\", \"man\"))\nprintln(\"girl to lady: \", targeted_mutations(\"girl\", \"lady\"))\nprintln(\"john to jane: \", targeted_mutations(\"john\", \"jane\"))\nprintln(\"child to adult: \", targeted_mutations(\"child\", \"adult\"))\n", "language": "Julia" }, { "code": "db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[3]]]]];\nsel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];\ng=Graph[db,UndirectedEdge@@@sel];\nFindShortestPath[g,\"boy\",\"man\"]\n\ndb=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[4]]]]];\nsel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];\ng=Graph[db,UndirectedEdge@@@sel];\nFindShortestPath[g,\"girl\",\"lady\"]\nFindShortestPath[g,\"john\",\"jane\"]\n\ndb=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[5]]]]];\nsel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];\ng=Graph[db,UndirectedEdge@@@sel];\nFindShortestPath[g,\"child\",\"adult\"]\n", "language": "Mathematica" }, { "code": "import sets, strformat, strutils\n\n\nfunc isOneAway(word1, word2: string): bool =\n ## Return true if \"word1\" and \"word2\" has only one letter of difference.\n for i in 0..word1.high:\n if word1[i] != word2[i]:\n if result: return false # More than one letter of difference.\n else: 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 words[word.len].incl word\n\n\nproc path(start, target: string): seq[string] =\n ## Return a path from \"start\" to \"target\" or an empty list\n ## if there is no possible path.\n let lg = start.len\n doAssert target.len == lg, \"Source and destination must have same length.\"\n doAssert start in words[lg], \"Source must exist in the dictionary.\"\n doAssert target in words[lg], \"Destination must exist in the dictionary.\"\n\n var currPaths = @[@[start]] # Current list of paths found.\n var pool = words[lg] # List of possible words to use.\n\n while true:\n var newPaths: seq[seq[string]] # Next list of paths.\n var added: HashSet[string] # Set of words added during the round.\n for candidate in pool:\n for path in currPaths:\n if candidate.isOneAway(path[^1]):\n let newPath = path & candidate\n if candidate == target:\n # Found a path.\n return newPath\n else:\n # Not the target. Add a new path.\n newPaths.add newPath\n added.incl candidate\n break\n if newPaths.len == 0: break # No path.\n currPaths = move(newPaths) # Update list of paths.\n pool.excl added # Remove added words from pool.\n\n\nwhen isMainModule:\n for (start, target) in [(\"boy\", \"man\"), (\"girl\", \"lady\"), (\"john\", \"jane\"),\n (\"child\", \"adult\"), (\"cat\", \"dog\"), (\"lead\", \"gold\"),\n (\"white\", \"black\"), (\"bubble\", \"tickle\")]:\n let path = path(start, target)\n if path.len == 0:\n echo &\"No path from “{start}” to “{target}”.\"\n else:\n echo path.join(\" → \")\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\n\nmy %dict;\n\nopen my $handle, '<', 'unixdict.txt';\nwhile (my $word = <$handle>) {\n chomp($word);\n my $len = length $word;\n if (exists $dict{$len}) {\n push @{ $dict{ $len } }, $word;\n } else {\n my @words = ( $word );\n $dict{$len} = \\@words;\n }\n}\nclose $handle;\n\nsub distance {\n my $w1 = shift;\n my $w2 = shift;\n\n my $dist = 0;\n for my $i (0 .. length($w1) - 1) {\n my $c1 = substr($w1, $i, 1);\n my $c2 = substr($w2, $i, 1);\n if (not ($c1 eq $c2)) {\n $dist++;\n }\n }\n return $dist;\n}\n\nsub contains {\n my $aref = shift;\n my $needle = shift;\n\n for my $v (@$aref) {\n if ($v eq $needle) {\n return 1;\n }\n }\n\n return 0;\n}\n\nsub word_ladder {\n my $fw = shift;\n my $tw = shift;\n\n if (exists $dict{length $fw}) {\n my @poss = @{ $dict{length $fw} };\n my @queue = ([$fw]);\n while (scalar @queue > 0) {\n my $curr_ref = shift @queue;\n my $last = $curr_ref->[-1];\n\n my @next;\n for my $word (@poss) {\n if (distance($last, $word) == 1) {\n push @next, $word;\n }\n }\n\n if (contains(\\@next, $tw)) {\n push @$curr_ref, $tw;\n print join (' -> ', @$curr_ref), \"\\n\";\n return;\n }\n\n for my $word (@next) {\n for my $i (0 .. scalar @poss - 1) {\n if ($word eq $poss[$i]) {\n splice @poss, $i, 1;\n last;\n }\n }\n }\n\n for my $word (@next) {\n my @temp = @$curr_ref;\n push @temp, $word;\n\n push @queue, \\@temp;\n }\n }\n }\n\n print STDERR \"Cannot change $fw into $tw\\n\";\n}\n\nword_ladder('boy', 'man');\nword_ladder('girl', 'lady');\nword_ladder('john', 'jane');\nword_ladder('child', 'adult');\nword_ladder('cat', 'dog');\nword_ladder('lead', 'gold');\nword_ladder('white', 'black');\nword_ladder('bubble', 'tickle');\n", "language": "Perl" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\nmy %dict;\nopen my $handle, '<', 'ref/unixdict.txt';\nwhile (my $word = <$handle>) {\n chomp $word;\n my $l = length $word;\n if ($dict{$l}) { push @{ $dict{$l} }, $word }\n else { $dict{$l} = \\@{[$word]} }\n}\nclose $handle;\n\nsub distance {\n my($w1,$w2) = @_;\n my $d;\n substr($w1, $_, 1) eq substr($w2, $_, 1) or $d++ for 0 .. length($w1) - 1;\n return $d // 0;\n}\n\nsub contains {\n my($aref,$needle) = @_;\n $needle eq $_ and return 1 for @$aref;\n return 0;\n}\n\nsub word_ladder {\n my($fw,$tw) = @_;\n say 'Nothing like that in dictionary.' and return unless $dict{length $fw};\n\n my @poss = @{ $dict{length $fw} };\n my @queue = [$fw];\n while (@queue) {\n my $curr_ref = shift @queue;\n my $last = $curr_ref->[-1];\n\n my @next;\n distance($last, $_) == 1 and push @next, $_ for @poss;\n push(@$curr_ref, $tw) and say join ' -> ', @$curr_ref and return if contains \\@next, $tw;\n\n for my $word (@next) {\n $word eq $poss[$_] and splice(@poss, $_, 1) and last for 0 .. @poss - 1;\n }\n push @queue, \\@{[@{$curr_ref}, $_]} for @next;\n }\n\n say \"Cannot change $fw into $tw\";\n}\n\nword_ladder(split) for 'boy man', 'girl lady', 'john jane', 'child adult';\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">words</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unix_dict</span><span style=\"color: #0000FF;\">()</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">right_length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">one_away</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_ne</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">))=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">dca</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">word_ladder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">poss</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">right_length</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">todo</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">}},</span>\n <span style=\"color: #000000;\">curr</span> <span style=\"color: #000080;font-style:italic;\">-- aka todo[1], word chain starting from a</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">todo</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">curr</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">todo</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">todo</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">todo</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]}</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">next</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">poss</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">one_away</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">curr</span><span style=\"color: #0000FF;\">[$])</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">next</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">curr</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"-&gt;\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">poss</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">poss</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"out\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">next</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">todo</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">apply</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dca</span><span style=\"color: #0000FF;\">,{{</span><span style=\"color: #000000;\">curr</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">next</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s into %s cannot be done\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">word_ladder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"boy\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"man\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">word_ladder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"girl\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"lady\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">word_ladder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"john\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"jane\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">word_ladder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"child\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"adult\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "import os,sys,zlib,urllib.request\n\ndef h ( str,x=9 ):\n for c in str :\n x = ( x*33 + ord( c )) & 0xffffffffff\n return x\n\ndef cache ( func,*param ):\n n = 'cache_%x.bin'%abs( h( repr( param )))\n try : return eval( zlib.decompress( open( n,'rb' ).read()))\n except : pass\n s = func( *param )\n open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))\n return s\n\ndico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'\nread_url = lambda url : urllib.request.urlopen( url ).read()\nload_dico = lambda url : tuple( cache( read_url,url ).split( b'\\n'))\nisnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1\n\ndef build_map ( words ):\n map = [(w.decode('ascii'),[]) for w in words]\n for i1,(w1,n1) in enumerate( map ):\n for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):\n if isnext( w1,w2 ):\n n1.append( i2 )\n n2.append( i1 )\n return map\n\ndef find_path ( words,w1,w2 ):\n i = [w[0] for w in words].index( w1 )\n front,done,res = [i],{i:-1},[]\n while front :\n i = front.pop(0)\n word,next = words[i]\n for n in next :\n if n in done : continue\n done[n] = i\n if words[n][0] == w2 :\n while n >= 0 :\n res = [words[n][0]] + res\n n = done[n]\n return ' '.join( res )\n front.append( n )\n return '%s can not be turned into %s'%( w1,w2 )\n\nfor w in ('boy man','girl lady','john jane','alien drool','child adult'):\n print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))\n", "language": "Python" }, { "code": "#lang racket\n\n(define *unixdict* (delay (with-input-from-file \"../../data/unixdict.txt\"\n (compose list->set port->lines))))\n\n(define letters-as-strings (map string (string->list \"abcdefghijklmnopqrstuvwxyz\")))\n\n(define ((replace-for-c-at-i w i) c)\n (string-append (substring w 0 i) c (substring w (add1 i))))\n\n(define (candidates w)\n (for*/list (((i w_i) (in-parallel (string-length w) w))\n (r (in-value (replace-for-c-at-i w i)))\n (c letters-as-strings)\n #:unless (char=? w_i (string-ref c 0)))\n (r c)))\n\n(define (generate-candidates word.path-hash)\n (for*/hash (((w p) word.path-hash)\n (w′ (candidates w)))\n (values w′ (cons w p))))\n\n(define (hash-filter-keys keep-key? h)\n (for/hash (((k v) h) #:when (keep-key? k)) (values k v)))\n\n(define (Word-ladder src dest (words (force *unixdict*)))\n (let loop ((edge (hash src null)) (unused (set-remove words src)))\n (let ((cands (generate-candidates edge)))\n (if (hash-has-key? cands dest)\n (reverse (cons dest (hash-ref cands dest)))\n (let ((new-edge (hash-filter-keys (curry set-member? unused) cands)))\n (if (hash-empty? new-edge)\n `(no-path-between ,src ,dest)\n (loop new-edge (set-subtract unused (list->set (hash-keys new-edge))))))))))\n\n(module+ main\n (Word-ladder \"boy\" \"man\")\n (Word-ladder \"girl\" \"lady\")\n (Word-ladder \"john\" \"jane\")\n (Word-ladder \"alien\" \"drool\")\n (Word-ladder \"child\" \"adult\"))\n", "language": "Racket" }, { "code": "constant %dict = 'unixdict.txt'.IO.lines\n .classify(*.chars)\n .map({ .key => .value.Set });\n\nsub word_ladder ( Str $from, Str $to ) {\n die if $from.chars != $to.chars;\n\n my $sized_dict = %dict{$from.chars};\n\n my @workqueue = (($from,),);\n my $used = ($from => True).SetHash;\n while @workqueue {\n my @new_q;\n for @workqueue -> @words {\n my $last_word = @words.tail;\n my @new_tails = gather for 'a' .. 'z' -> $replacement_letter {\n for ^$last_word.chars -> $i {\n my $new_word = $last_word;\n $new_word.substr-rw($i, 1) = $replacement_letter;\n\n next unless $new_word ∈ $sized_dict\n and not $new_word ∈ $used;\n take $new_word;\n $used{$new_word} = True;\n\n return |@words, $new_word if $new_word eq $to;\n }\n }\n push @new_q, ( |@words, $_ ) for @new_tails;\n }\n @workqueue = @new_q;\n }\n}\nfor <boy man>, <girl lady>, <john jane>, <child adult> -> ($from, $to) {\n say word_ladder($from, $to)\n // \"$from into $to cannot be done\";\n}\n", "language": "Raku" }, { "code": "lower: procedure; parse arg a; @= 'abcdefghijklmnopqrstuvwxyz'; @u= @; upper @u\n return translate(a, @, @u)\n", "language": "REXX" }, { "code": "/*REXX program finds words (within an identified dict.) to solve a word ladder puzzle.*/\nparse arg base targ iFID . /*obtain optional arguments from the CL*/\nif base=='' | base==\",\" then base= 'boy' /*Not specified? Then use the default.*/\nif targ=='' | targ==\",\" then targ= 'man' /* \" \" \" \" \" \" */\nif iFID=='' | iFID==\",\" then iFID='unixdict.txt' /* \" \" \" \" \" \" */\nabc= 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet. */\nabcU= abc; upper abcU /* \" uppercase \" \" */\nbase= lower(base); targ= lower(targ) /*lowercase the BASE and also the TARG.*/\n L= length(base) /*length of the BASE (in characters). */\nif L<2 then call err 'base word is too small or missing' /*oops, too small*/\nif length(targ)\\==L then call msg , \"target word isn't the same length as the base word\"\ncall letters /*assign letters, faster than SUBSTR. */\n#= 0 /*# of words whose length matches BASE.*/\n@.= /*default value of any dictionary word.*/\n do recs=0 while lines(iFID)\\==0 /*read each word in the file (word=X).*/\n x= lower(strip( linein( iFID) ) ) /*pick off a word from the input line. */\n if length(x)\\==L then iterate /*Word not correct length? Then skip. */\n #= # + 1; @.x= 1 /*bump # words with length L; semaphore*/\n end /*recs*/ /* [↑] semaphore name is uppercased. */\n!.= 0\nsay copies('─', 30) recs \"words in the dictionary file: \" iFID\nsay copies('─', 30) # \"words in the dictionary file of length: \" L\nsay copies('─', 30) ' base word is: ' base\nsay copies('─', 30) 'target word is: ' targ\nrung= targ\n$= base\n do f=1 for m; call look; if result\\=='' then leave /*Found? Quit.*/\n end /*f*/\nsay\nif f>m then call msg 'no word ladder solution possible for ' base \" ──► \" targ\n\n do f-2; $= base; !.= 0 /*process all the rungs that were found*/\n do forever; call look; if result\\=='' then leave /*Found? Quit.*/\n end /*forever*/\n end /*f-2*/\ncall show words(rung)\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nmsg: say; if arg()==2 then say '***error*** ' arg(2); else say arg(1); say; exit 13\nshow: say 'a solution: ' base; do j=1 to arg(1); say left('',12) word(rung,j); end; return\nletters: do m=1 for length(abc); a.m= substr(abc, m, 1); end; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nlook: procedure expose @. !. a. $ abc base L rung targ search; rungs= word(rung, 1)\n $$=; rung#= words(rungs)\n do i=1 for words($); y= word($, i); !.y= 1\n do k=1 for L\n do n=1 for 26; z= overlay(a.n, y, k) /*change a letter*/\n if @.z=='' then iterate /*Is this not a word? Then skip it. */\n if !.z then iterate /* \" \" a repeat? \" \" \" */\n if z==rungs then rung= y rung /*prepend a word to the rung list. */\n if z==rungs & rung#>1 then return z /*short─circuit. */\n if z==targ then return z\n $$= $$ z /*append a possible ladder word to $$*/\n end /*n*/\n end /*k*/\n end /*i*/\n $= $$; return ''\n", "language": "REXX" }, { "code": "require \"set\"\n\nWords = File.open(\"unixdict.txt\").read.split(\"\\n\").\n group_by { |w| w.length }.map { |k, v| [k, Set.new(v)] }.\n to_h\n\ndef word_ladder(from, to)\n raise \"Length mismatch\" unless from.length == to.length\n sized_words = Words[from.length]\n work_queue = [[from]]\n used = Set.new [from]\n while work_queue.length > 0\n new_q = []\n work_queue.each do |words|\n last_word = words[-1]\n new_tails = Enumerator.new do |enum|\n (\"a\"..\"z\").each do |replacement_letter|\n last_word.length.times do |i|\n new_word = last_word.clone\n new_word[i] = replacement_letter\n next unless sized_words.include? new_word and\n not used.include? new_word\n enum.yield new_word\n used.add new_word\n return words + [new_word] if new_word == to\n end\n end\n end\n new_tails.each do |t|\n new_q.push(words + [t])\n end\n end\n work_queue = new_q\n end\nend\n\n[%w<boy man>, %w<girl lady>, %w<john jane>, %w<child adult>].each do |from, to|\n if ladder = word_ladder(from, to)\n puts ladder.join \" → \"\n else\n puts \"#{from} into #{to} cannot be done\"\n end\nend\n", "language": "Ruby" }, { "code": "import Foundation\n\nfunc oneAway(string1: [Character], string2: [Character]) -> Bool {\n if string1.count != string2.count {\n return false\n }\n var result = false\n var i = 0\n while i < string1.count {\n if string1[i] != string2[i] {\n if result {\n return false\n }\n result = true\n }\n i += 1\n }\n return result\n}\n\nfunc wordLadder(words: [[Character]], from: String, to: String) {\n let fromCh = Array(from)\n let toCh = Array(to)\n var poss = words.filter{$0.count == fromCh.count}\n var queue: [[[Character]]] = [[fromCh]]\n while !queue.isEmpty {\n var curr = queue[0]\n let last = curr[curr.count - 1]\n queue.removeFirst()\n let next = poss.filter{oneAway(string1: $0, string2: last)}\n if next.contains(toCh) {\n curr.append(toCh)\n print(curr.map{String($0)}.joined(separator: \" -> \"))\n return\n }\n poss.removeAll(where: {next.contains($0)})\n for str in next {\n var temp = curr\n temp.append(str)\n queue.append(temp)\n }\n }\n print(\"\\(from) into \\(to) cannot be done.\")\n}\n\ndo {\n let words = try String(contentsOfFile: \"unixdict.txt\", encoding: String.Encoding.ascii)\n .components(separatedBy: \"\\n\")\n .filter{!$0.isEmpty}\n .map{Array($0)}\n wordLadder(words: words, from: \"man\", to: \"boy\")\n wordLadder(words: words, from: \"girl\", to: \"lady\")\n wordLadder(words: words, from: \"john\", to: \"jane\")\n wordLadder(words: words, from: \"child\", to: \"adult\")\n wordLadder(words: words, from: \"cat\", to: \"dog\")\n wordLadder(words: words, from: \"lead\", to: \"gold\")\n wordLadder(words: words, from: \"white\", to: \"black\")\n wordLadder(words: words, from: \"bubble\", to: \"tickle\")\n} catch {\n print(error.localizedDescription)\n}\n", "language": "Swift" }, { "code": "import \"io\" for File\nimport \"./sort\" for Find\n\nvar words = File.read(\"unixdict.txt\").trim().split(\"\\n\")\n\nvar oneAway = Fn.new { |a, b|\n var sum = 0\n for (i in 0...a.count) if (a[i] != b[i]) sum = sum + 1\n return sum == 1\n}\n\nvar wordLadder = Fn.new { |a, b|\n var l = a.count\n var poss = words.where { |w| w.count == l }.toList\n var todo = [[a]]\n while (todo.count > 0) {\n var curr = todo[0]\n todo = todo[1..-1]\n var next = poss.where { |w| oneAway.call(w, curr[-1]) }.toList\n if (Find.first(next, b) != -1) {\n curr.add(b)\n System.print(curr.join(\" -> \"))\n return\n }\n poss = poss.where { |p| !next.contains(p) }.toList\n for (i in 0...next.count) {\n var temp = curr.toList\n temp.add(next[i])\n todo.add(temp)\n }\n }\n System.print(\"%(a) into %(b) cannot be done.\")\n}\n\nvar pairs = [\n [\"boy\", \"man\"],\n [\"girl\", \"lady\"],\n [\"john\", \"jane\"],\n [\"child\", \"adult\"]\n]\nfor (pair in pairs) wordLadder.call(pair[0], pair[1])\n", "language": "Wren" } ]
Word-ladder
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Word_search\n", "language": "00-META" }, { "code": "A [[wp:Word_search|word search]] puzzle typically consists of a grid of letters in which words are hidden.\n\nThere are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.\n\nThe words may overlap but are not allowed to zigzag, or wrap around.\n<br><br>\n;Task \nCreate a 10 by 10 word search and fill it using words from the [http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict]. Use only words that are longer than 2, and contain no non-alphabetic characters.\n\nThe cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. \n\nPack a minimum of 25 words into the grid.\n\nPrint the resulting grid and the solutions.\n<br><br>\n;Example\n\n<pre>\n 0 1 2 3 4 5 6 7 8 9\n\n0 n a y r y R e l m f \n1 y O r e t s g n a g \n2 t n e d i S k y h E \n3 n o t n c p c w t T \n4 a l s u u n T m a x \n5 r o k p a r i s h h \n6 a A c f p a e a c C \n7 u b u t t t O l u n \n8 g y h w a D h p m u \n9 m i r p E h o g a n \n\nparish (3,5)(8,5) gangster (9,1)(2,1)\npaucity (4,6)(4,0) guaranty (0,8)(0,1)\nprim (3,9)(0,9) huckster (2,8)(2,1)\nplasm (7,8)(7,4) fancy (3,6)(7,2)\nhogan (5,9)(9,9) nolo (1,2)(1,5)\nunder (3,4)(3,0) chatham (8,6)(8,0)\nate (4,8)(6,6) nun (9,7)(9,9)\nbutt (1,7)(4,7) hawk (9,5)(6,2)\nwhy (3,8)(1,8) ryan (3,0)(0,0)\nfay (9,0)(7,2) much (8,8)(8,5)\ntar (5,7)(5,5) elm (6,0)(8,0)\nmax (7,4)(9,4) pup (5,3)(3,5)\nmph (8,8)(6,8)\n</pre>\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "-V\n dirs = [[1, 0], [ 0, 1], [ 1, 1],\n [1, -1], [-1, 0],\n [0, -1], [-1, -1], [-1, 1]]\n n_rows = 10\n n_cols = 10\n grid_size = n_rows * n_cols\n min_words = 25\n\nT Grid\n num_attempts = 0\n [[String]] cells = [[‘’] * :n_cols] * :n_rows\n [String] solutions\n\nF read_words(filename)\n [String] words\n L(line) File(filename).read_lines()\n V s = line.lowercase()\n I re:‘^[a-z]{3,10}’.match(s)\n words.append(s)\n R words\n\nF place_message(Grid &grid; =msg)\n msg = msg.uppercase().replace(re:‘[^A-Z]’, ‘’)\n V message_len = msg.len\n I message_len C 0 <.< :grid_size\n V gap_size = :grid_size I/ message_len\n\n L(i) 0 .< message_len\n V pos = i * gap_size + random:(0 .. gap_size)\n grid.cells[pos I/ :n_cols][pos % :n_cols] = msg[i]\n\n R message_len\n R 0\n\nF try_location(Grid &grid; word, direction, pos)\n V r = pos I/ :n_cols\n V c = pos % :n_cols\n V length = word.len\n\n I (:dirs[direction][0] == 1 & (length + c) > :n_cols) |\n (:dirs[direction][0] == -1 & (length - 1) > c) |\n (:dirs[direction][1] == 1 & (length + r) > :n_rows) |\n (:dirs[direction][1] == -1 & (length - 1) > r)\n R 0\n\n V rr = r\n V cc = c\n V i = 0\n V overlaps = 0\n\n L i < length\n I grid.cells[rr][cc] != ‘’ & grid.cells[rr][cc] != word[i]\n R 0\n cc += :dirs[direction][0]\n rr += :dirs[direction][1]\n i++\n\n rr = r\n cc = c\n i = 0\n\n L i < length\n I grid.cells[rr][cc] == word[i]\n overlaps++\n E\n grid.cells[rr][cc] = word[i]\n\n I i < length - 1\n cc += :dirs[direction][0]\n rr += :dirs[direction][1]\n i++\n\n V letters_placed = length - overlaps\n I letters_placed > 0\n grid.solutions.append(‘#<10 (#.,#.)(#.,#.)’.format(word, c, r, cc, rr))\n\n R letters_placed\n\nF try_place_word(Grid &grid; word)\n V rand_dir = random:(0 .. :dirs.len)\n V rand_pos = random:(0 .. :grid_size)\n\n L(=direction) 0 .< :dirs.len\n direction = (direction + rand_dir) % :dirs.len\n\n L(=pos) 0 .< :grid_size\n pos = (pos + rand_pos) % :grid_size\n V letters_placed = try_location(&grid, word, direction, pos)\n I letters_placed > 0\n R letters_placed\n R 0\n\nF create_word_search(&words)\n V grid = Grid()\n V num_attempts = 0\n\n L num_attempts < 100\n num_attempts++\n random:shuffle(&words)\n grid = Grid()\n V message_len = place_message(&grid, ‘Rosetta Code’)\n V target = :grid_size - message_len\n V cells_filled = 0\n L(word) words\n cells_filled += try_place_word(&grid, word)\n I cells_filled == target\n I grid.solutions.len >= :min_words\n grid.num_attempts = num_attempts\n R grid\n E\n L.break\n R grid\n\nF print_result(grid)\n I grid.num_attempts == 0\n print(‘No grid to display’)\n R\n\n V size = grid.solutions.len\n\n print(‘Attempts: #.’.format(grid.num_attempts))\n print(‘Number of words: #.’.format(size))\n\n print(\"\\n 0 1 2 3 4 5 6 7 8 9\\n\")\n L(r) 0 .< :n_rows\n print(‘#. ’.format(r), end' ‘’)\n L(c) 0 .< :n_cols\n print(‘ #. ’.format(grid.cells[r][c]), end' ‘’)\n print()\n print()\n\n L(i) (0 .< size - 1).step(2)\n print(‘#. #.’.format(grid.solutions[i], grid.solutions[i + 1]))\n\n I size % 2 == 1\n print(grid.solutions[size - 1])\n\nprint_result(create_word_search(&read_words(‘unixdict.txt’)))\n", "language": "11l" }, { "code": "#include <iomanip>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <fstream>\n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n Cell() : val( 0 ), cntOverlap( 0 ) {}\n char val; int cntOverlap;\n};\nclass Word {\npublic:\n Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) :\n word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n std::string word;\n int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n void create( std::string& file ) {\n std::ifstream f( file.c_str(), std::ios_base::in );\n std::string word;\n while( f >> word ) {\n if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n dictionary.push_back( word );\n }\n f.close();\n std::random_shuffle( dictionary.begin(), dictionary.end() );\n buildPuzzle();\n }\n\n void printOut() {\n std::cout << \"\\t\";\n for( int x = 0; x < WID; x++ ) std::cout << x << \" \";\n std::cout << \"\\n\\n\";\n for( int y = 0; y < HEI; y++ ) {\n std::cout << y << \"\\t\";\n for( int x = 0; x < WID; x++ )\n std::cout << puzzle[x][y].val << \" \";\n std::cout << \"\\n\";\n }\n size_t wid1 = 0, wid2 = 0;\n for( size_t x = 0; x < used.size(); x++ ) {\n if( x & 1 ) {\n if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n } else {\n if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n }\n }\n std::cout << \"\\n\";\n std::vector<Word>::iterator w = used.begin();\n while( w != used.end() ) {\n std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\"\n << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n w++;\n if( w == used.end() ) break;\n std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\"\n << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n w++;\n }\n std::cout << \"\\n\\n\";\n }\nprivate:\n void addMsg() {\n std::string msg = \"ROSETTACODE\";\n int stp = 9, p = rand() % stp;\n for( size_t x = 0; x < msg.length(); x++ ) {\n puzzle[p % WID][p / HEI].val = msg.at( x );\n p += rand() % stp + 4;\n }\n }\n int getEmptySpaces() {\n int es = 0;\n for( int y = 0; y < HEI; y++ ) {\n for( int x = 0; x < WID; x++ ) {\n if( !puzzle[x][y].val ) es++;\n }\n }\n return es;\n }\n bool check( std::string word, int c, int r, int dc, int dr ) {\n for( size_t a = 0; a < word.length(); a++ ) {\n if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n c += dc; r += dr;\n }\n return true;\n }\n bool setWord( std::string word, int c, int r, int dc, int dr ) {\n if( !check( word, c, r, dc, dr ) ) return false;\n int sx = c, sy = r;\n for( size_t a = 0; a < word.length(); a++ ) {\n if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n else puzzle[c][r].cntOverlap++;\n c += dc; r += dr;\n }\n used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n return true;\n }\n bool add2Puzzle( std::string word ) {\n int x = rand() % WID, y = rand() % HEI,\n z = rand() % 8;\n for( int d = z; d < z + 8; d++ ) {\n switch( d % 8 ) {\n case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break;\n case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break;\n case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break;\n case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break;\n case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break;\n case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break;\n case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break;\n }\n }\n return false;\n }\n void clearWord() {\n if( used.size() ) {\n Word lastW = used.back();\n used.pop_back();\n\n for( size_t a = 0; a < lastW.word.length(); a++ ) {\n if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n puzzle[lastW.cols][lastW.rows].val = 0;\n }\n if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n puzzle[lastW.cols][lastW.rows].cntOverlap--;\n }\n lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n }\n }\n }\n void buildPuzzle() {\n addMsg();\n int es = 0, cnt = 0;\n size_t idx = 0;\n do {\n for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n\n if( add2Puzzle( *w ) ) {\n es = getEmptySpaces();\n if( !es && used.size() >= MIN_WORD_CNT )\n return;\n }\n }\n clearWord();\n std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n } while( ++cnt < 100 );\n }\n std::vector<Word> used;\n std::vector<std::string> dictionary;\n Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n unsigned s = unsigned( time( 0 ) );\n srand( s );\n words w; w.create( std::string( \"unixdict.txt\" ) );\n w.printOut();\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Wordseach\n{\n static class Program\n {\n readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n {0, -1}, {-1, -1}, {-1, 1}};\n\n class Grid\n {\n public char[,] Cells = new char[nRows, nCols];\n public List<string> Solutions = new List<string>();\n public int NumAttempts;\n }\n\n readonly static int nRows = 10;\n readonly static int nCols = 10;\n readonly static int gridSize = nRows * nCols;\n readonly static int minWords = 25;\n\n readonly static Random rand = new Random();\n\n static void Main(string[] args)\n {\n PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")));\n }\n\n private static List<string> ReadWords(string filename)\n {\n int maxLen = Math.Max(nRows, nCols);\n\n return System.IO.File.ReadAllLines(filename)\n .Select(s => s.Trim().ToLower())\n .Where(s => Regex.IsMatch(s, \"^[a-z]{3,\" + maxLen + \"}$\"))\n .ToList();\n }\n\n private static Grid CreateWordSearch(List<string> words)\n {\n int numAttempts = 0;\n\n while (++numAttempts < 100)\n {\n words.Shuffle();\n\n var grid = new Grid();\n int messageLen = PlaceMessage(grid, \"Rosetta Code\");\n int target = gridSize - messageLen;\n\n int cellsFilled = 0;\n foreach (var word in words)\n {\n cellsFilled += TryPlaceWord(grid, word);\n if (cellsFilled == target)\n {\n if (grid.Solutions.Count >= minWords)\n {\n grid.NumAttempts = numAttempts;\n return grid;\n }\n else break; // grid is full but we didn't pack enough words, start over\n }\n }\n }\n return null;\n }\n\n private static int TryPlaceWord(Grid grid, string word)\n {\n int randDir = rand.Next(dirs.GetLength(0));\n int randPos = rand.Next(gridSize);\n\n for (int dir = 0; dir < dirs.GetLength(0); dir++)\n {\n dir = (dir + randDir) % dirs.GetLength(0);\n\n for (int pos = 0; pos < gridSize; pos++)\n {\n pos = (pos + randPos) % gridSize;\n\n int lettersPlaced = TryLocation(grid, word, dir, pos);\n if (lettersPlaced > 0)\n return lettersPlaced;\n }\n }\n return 0;\n }\n\n private static int TryLocation(Grid grid, string word, int dir, int pos)\n {\n int r = pos / nCols;\n int c = pos % nCols;\n int len = word.Length;\n\n // check bounds\n if ((dirs[dir, 0] == 1 && (len + c) > nCols)\n || (dirs[dir, 0] == -1 && (len - 1) > c)\n || (dirs[dir, 1] == 1 && (len + r) > nRows)\n || (dirs[dir, 1] == -1 && (len - 1) > r))\n return 0;\n\n int rr, cc, i, overlaps = 0;\n\n // check cells\n for (i = 0, rr = r, cc = c; i < len; i++)\n {\n if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])\n {\n return 0;\n }\n\n cc += dirs[dir, 0];\n rr += dirs[dir, 1];\n }\n\n // place\n for (i = 0, rr = r, cc = c; i < len; i++)\n {\n if (grid.Cells[rr, cc] == word[i])\n overlaps++;\n else\n grid.Cells[rr, cc] = word[i];\n\n if (i < len - 1)\n {\n cc += dirs[dir, 0];\n rr += dirs[dir, 1];\n }\n }\n\n int lettersPlaced = len - overlaps;\n if (lettersPlaced > 0)\n {\n grid.Solutions.Add($\"{word,-10} ({c},{r})({cc},{rr})\");\n }\n\n return lettersPlaced;\n }\n\n private static int PlaceMessage(Grid grid, string msg)\n {\n msg = Regex.Replace(msg.ToUpper(), \"[^A-Z]\", \"\");\n\n int messageLen = msg.Length;\n if (messageLen > 0 && messageLen < gridSize)\n {\n int gapSize = gridSize / messageLen;\n\n for (int i = 0; i < messageLen; i++)\n {\n int pos = i * gapSize + rand.Next(gapSize);\n grid.Cells[pos / nCols, pos % nCols] = msg[i];\n }\n return messageLen;\n }\n return 0;\n }\n\n public static void Shuffle<T>(this IList<T> list)\n {\n int n = list.Count;\n while (n > 1)\n {\n n--;\n int k = rand.Next(n + 1);\n T value = list[k];\n list[k] = list[n];\n list[n] = value;\n }\n }\n\n private static void PrintResult(Grid grid)\n {\n if (grid == null || grid.NumAttempts == 0)\n {\n Console.WriteLine(\"No grid to display\");\n return;\n }\n int size = grid.Solutions.Count;\n\n Console.WriteLine(\"Attempts: \" + grid.NumAttempts);\n Console.WriteLine(\"Number of words: \" + size);\n\n Console.WriteLine(\"\\n 0 1 2 3 4 5 6 7 8 9\");\n for (int r = 0; r < nRows; r++)\n {\n Console.Write(\"\\n{0} \", r);\n for (int c = 0; c < nCols; c++)\n Console.Write(\" {0} \", grid.Cells[r, c]);\n }\n\n Console.WriteLine(\"\\n\");\n\n for (int i = 0; i < size - 1; i += 2)\n {\n Console.WriteLine(\"{0} {1}\", grid.Solutions[i],\n grid.Solutions[i + 1]);\n }\n if (size % 2 == 1)\n Console.WriteLine(grid.Solutions[size - 1]);\n\n Console.ReadLine();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.random : Random, uniform, randomShuffle;\nimport std.stdio;\n\nimmutable int[][] dirs = [\n [1, 0], [ 0, 1], [ 1, 1],\n [1, -1], [-1, 0],\n [0, -1], [-1, -1], [-1, 1]\n];\n\nenum nRows = 10;\nenum nCols = 10;\nenum gridSize = nRows * nCols;\nenum minWords = 25;\n\nauto rnd = Random();\n\nclass Grid {\n int numAttempts;\n char[nRows][nCols] cells;\n string[] solutions;\n\n this() {\n for(int row=0; row<nRows; ++row) {\n cells[row] = 0;\n }\n }\n}\n\nvoid main() {\n printResult(createWordSearch(readWords(\"unixdict.txt\")));\n}\n\nstring[] readWords(string filename) {\n import std.algorithm : all, max;\n import std.ascii : isAlpha;\n import std.string : chomp, toLower;\n\n auto maxlen = max(nRows, nCols);\n\n string[] words;\n auto source = File(filename);\n foreach(line; source.byLine) {\n chomp(line);\n if (line.length >= 3 && line.length <= maxlen) {\n if (all!isAlpha(line)) {\n words ~= line.toLower.idup;\n }\n }\n }\n\n return words;\n}\n\nGrid createWordSearch(string[] words) {\n Grid grid;\n int numAttempts;\n\n outer:\n while(++numAttempts < 100) {\n randomShuffle(words);\n\n grid = new Grid();\n int messageLen = placeMessage(grid, \"Rosetta Code\");\n int target = gridSize - messageLen;\n\n int cellsFilled;\n foreach (string word; words) {\n cellsFilled += tryPlaceWord(grid, word);\n if (cellsFilled == target) {\n if (grid.solutions.length >= minWords) {\n grid.numAttempts = numAttempts;\n break outer;\n } else break; // grid is full but we didn't pack enough words, start over\n }\n }\n }\n return grid;\n}\n\nint placeMessage(Grid grid, string msg) {\n import std.algorithm : filter;\n import std.ascii : isUpper;\n import std.conv : to;\n import std.string : toUpper;\n\n msg = to!string(msg.toUpper.filter!isUpper);\n\n if (msg.length > 0 && msg.length < gridSize) {\n int gapSize = gridSize / msg.length;\n\n for (int i=0; i<msg.length; i++) {\n int pos = i * gapSize + uniform(0, gapSize, rnd);\n grid.cells[pos / nCols][pos % nCols] = msg[i];\n }\n return msg.length;\n }\n return 0;\n}\n\nint tryPlaceWord(Grid grid, string word) {\n int randDir = uniform(0, dirs.length, rnd);\n int randPos = uniform(0, gridSize, rnd);\n\n for (int dir=0; dir<dirs.length; dir++) {\n dir = (dir + randDir) % dirs.length;\n\n for (int pos=0; pos<gridSize; pos++) {\n pos = (pos + randPos) % gridSize;\n\n int lettersPlaced = tryLocation(grid, word, dir, pos);\n if (lettersPlaced > 0) {\n return lettersPlaced;\n }\n }\n }\n return 0;\n}\n\nint tryLocation(Grid grid, string word, int dir, int pos) {\n import std.format;\n\n int r = pos / nCols;\n int c = pos % nCols;\n int len = word.length;\n\n // check bounds\n if ((dirs[dir][0] == 1 && (len + c) > nCols)\n || (dirs[dir][0] == -1 && (len - 1) > c)\n || (dirs[dir][1] == 1 && (len + r) > nRows)\n || (dirs[dir][1] == -1 && (len - 1) > r)) {\n return 0;\n }\n\n int i, rr, cc, overlaps = 0;\n\n // check cells\n for (i=0, rr=r, cc=c; i<len; i++) {\n if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word[i]) {\n return 0;\n }\n cc += dirs[dir][0];\n rr += dirs[dir][1];\n }\n\n // place\n for (i=0, rr=r, cc=c; i<len; i++) {\n if (grid.cells[rr][cc] == word[i]) {\n overlaps++;\n } else {\n grid.cells[rr][cc] = word[i];\n }\n\n if (i < len - 1) {\n cc += dirs[dir][0];\n rr += dirs[dir][1];\n }\n }\n\n int lettersPlaced = len - overlaps;\n if (lettersPlaced > 0) {\n grid.solutions ~= format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr);\n }\n\n return lettersPlaced;\n}\n\nvoid printResult(Grid grid) {\n if (grid is null || grid.numAttempts == 0) {\n writeln(\"No grid to display\");\n return;\n }\n int size = grid.solutions.length;\n\n writeln(\"Attempts: \", grid.numAttempts);\n writeln(\"Number of words: \", size);\n\n writeln(\"\\n 0 1 2 3 4 5 6 7 8 9\");\n for (int r=0; r<nRows; r++) {\n writef(\"\\n%d \", r);\n for (int c=0; c<nCols; c++) {\n writef(\" %c \", grid.cells[r][c]);\n }\n }\n\n writeln;\n writeln;\n\n for (int i=0; i<size-1; i+=2) {\n writef(\"%s %s\\n\", grid.solutions[i], grid.solutions[i + 1]);\n }\n if (size % 2 == 1) {\n writeln(grid.solutions[size - 1]);\n }\n}\n", "language": "D" }, { "code": "Randomize Timer ' OK getting a good puzzle every time\n\n#Macro TrmSS (n)\n LTrim(Str(n))\n#EndMacro\n\n'overhauled\nDim Shared As ULong LengthLimit(3 To 10) 'reset in Initialize, track and limit longer words\n\n'LoadWords opens file of words and sets\nDim Shared As ULong NWORDS 'set in LoadWords, number of words with length: > 2 and < 11 and just letters\n\n' word file words (shuffled) to be fit into puzzle and index position\nDim Shared As String WORDSSS(1 To 24945), CWORDSSS(1 To 24945)\nDim Shared As ULong WORDSINDEX 'the file has 24945 words but many are unsuitable\n\n'words placed in Letters grid, word itself (WSS) x, y head (WX, WY) and direction (WD), WI is the index to all these\nDim Shared As String WSS(1 To 100)\nDim Shared As ULong WX(1 To 100), WY(1 To 100), WD(1 To 100), WI\n\n' letters grid and direction arrays\nDim Shared As String LSS(0 To 9, 0 To 9)\nDim Shared As Long DX(0 To 7), DY(0 To 7)\nDX(0) = 1: DY(0) = 0\nDX(1) = 1: DY(1) = 1\nDX(2) = 0: DY(2) = 1\nDX(3) = -1: DY(3) = 1\nDX(4) = -1: DY(4) = 0\nDX(5) = -1: DY(5) = -1\nDX(6) = 0: DY(6) = -1\nDX(7) = 1: DY(7) = -1\n\n'to store all the words found embedded in the grid LSS()\nDim Shared As String ALLSS(1 To 200)\nDim Shared As ULong AllX(1 To 200), AllY(1 To 200), AllD(1 To 200) 'to store all the words found embedded in the grid LSS()\nDim Shared As ULong ALLindex\n\n' signal successful fill of puzzle\nDim Shared FILLED As Boolean\nDim Shared As ULong try = 1\n\nSub LoadWords\n Dim As String wdSS\n Dim As ULong i, m, ff = FreeFile\n Dim ok As Boolean\n\n Open \"unixdict.txt\" For Input As #ff\n If Err > 0 Then\n Print !\"\\n unixdict.txt not found, program will end\"\n Sleep 5000\n End\n End If\n While Eof(1) = 0\n Input #ff, wdSS\n If Len(wdSS) > 2 And Len(wdSS) < 11 Then\n ok = TRUE\n For m = 1 To Len(wdSS)\n If Asc(wdSS, m) < 97 Or Asc(wdSS, m) > 122 Then ok = FALSE: Exit For\n Next\n If ok Then i += 1: WORDSSS(i) = wdSS: CWORDSSS(i) = wdSS\n End If\n Wend\n Close #ff\n NWORDS = i\nEnd Sub\n\nSub Shuffle\n Dim As ULong i, r\n For i = NWORDS To 2 Step -1\n r = Int(Rnd * i) + 1\n Swap WORDSSS(i), WORDSSS(r)\n Next\nEnd Sub\n\nSub Initialize\n Dim As ULong r, c'', x, y, d\n Dim As String wdSS\n\n FILLED = FALSE\n For r = 0 To 9\n For c = 0 To 9\n LSS(c, r) = \" \"\n Next\n Next\n\n 'reset word arrays by resetting the word index back to zero\n WI = 0\n\n 'fun stuff for me but doubt others would like that much fun!\n 'pluggin \"basic\", 0, 0, 2\n 'pluggin \"plus\", 1, 0, 0\n\n 'to assure the spreading of ROSETTA CODE\n LSS(Int(Rnd * 5) + 5, 0) = \"R\": LSS(Int(Rnd * 9) + 1, 1) = \"O\"\n LSS(Int(Rnd * 9) + 1, 2) = \"S\": LSS(Int(Rnd * 9) + 1, 3) = \"E\"\n LSS(1, 4) = \"T\": LSS(9, 4) = \"T\": LSS(Int(10 * Rnd), 5) = \"A\"\n LSS(Int(10 * Rnd), 6) = \"C\": LSS(Int(10 * Rnd), 7) = \"O\"\n LSS(Int(10 * Rnd), 8) = \"D\": LSS(Int(10 * Rnd), 9) = \"E\"\n\n 'reset limits\n LengthLimit(3) = 200\n LengthLimit(4) = 6\n LengthLimit(5) = 3\n LengthLimit(6) = 2\n LengthLimit(7) = 1\n LengthLimit(8) = 0\n LengthLimit(9) = 0\n LengthLimit(10) = 0\n\n 'reset word order\n Shuffle\nEnd Sub\n\n'for fun plug-in of words\nSub pluggin (wdSS As String, x As Long, y As Long, d As Long)\n\n For i As ULong = 0 To Len(wdSS) - 1\n LSS(x + i * DX(d), y + i * DY(d)) = Mid(wdSS, i + 1, 1)\n Next\n WI += WI\n WSS(WI) = wdSS: WX(WI) = x: WY(WI) = y: WD(WI) = d\nEnd Sub\n\n' Function TrmSS (n As Integer) As String\n' TrmSS = RTrim(LTrim(Str(n)))\n' End Function\n\n'used in PlaceWord\nFunction CountSpaces () As ULong\n Dim As ULong x, y, count\n\n For y = 0 To 9\n For x = 0 To 9\n If LSS(x, y) = \" \" Then count += 1\n Next\n Next\n CountSpaces = count\nEnd Function\n\nSub ShowPuzzle\n Dim As ULong i, x, y\n 'Dim As String wateSS\n\n Cls\n Print \" 0 1 2 3 4 5 6 7 8 9\"\n Locate 3, 1\n For i = 0 To 9\n Print TrmSS(i)\n Next\n For y = 0 To 9\n For x = 0 To 9\n Locate y + 3, 2 * x + 5: Print LSS(x, y)\n Next\n Next\n For i = 1 To WI\n If i < 21 Then\n Locate i + 1, 30: Print TrmSS(i); \" \"; WSS(i)\n ElseIf i < 41 Then\n Locate i - 20 + 1, 45: Print TrmSS(i); \" \"; WSS(i)\n ElseIf i < 61 Then\n Locate i - 40 + 1, 60: Print TrmSS(i); \" \"; WSS(i)\n End If\n Next\n Locate 18, 1: Print \"Spaces left:\"; CountSpaces\n Locate 19, 1: Print NWORDS\n Locate 20, 1: Print Space(16)\n If WORDSINDEX Then Locate 20, 1: Print TrmSS(WORDSINDEX); \" \"; WORDSSS(WORDSINDEX)\n 'LOCATE 15, 1: INPUT \"OK, press enter... \"; wateSS\nEnd Sub\n\n'used in PlaceWord\nFunction Match (word As String, template As String) As Long\n Dim i As ULong\n Dim c As String\n Match = 0\n If Len(word) <> Len(template) Then Exit Function\n For i = 1 To Len(template)\n If Asc(template, i) <> 32 And (Asc(word, i) <> Asc(template, i)) Then Exit Function\n Next\n Match = -1\nEnd Function\n\n'heart of puzzle builder\nSub PlaceWord\n ' place the words randomly in the grid\n ' start at random spot and work forward or back 100 times = all the squares\n ' for each open square try the 8 directions for placing the word\n ' even if word fits Rossetta Challenge task requires leaving 11 openings to insert ROSETTA CODE,\n ' exactly 11 spaces needs to be left, if/when this occurs FILLED will be set true to signal finished to main loop\n ' if place a word update LSS, WI, WSS(WI), WX(WI), WY(WI), WD(WI)\n\n Dim As String wdSS, templateSS\n Dim As Long rdir\n Dim As ULong wLen, spot, testNum\n Dim As ULong x, y, d, dNum, rdd, i, j\n\n Dim As Boolean b1, b2\n\n wdSS = WORDSSS(WORDSINDEX) ' the right side is all shared\n ' skip too many long words\n If LengthLimit(Len(wdSS)) Then LengthLimit(Len(wdSS)) += 1 Else Exit Sub 'skip long ones\n wLen = Len(wdSS) - 1 ' from the spot there are this many letters to check\n spot = Int(Rnd * 100) ' a random spot on grid\n testNum = 1 ' when this hits 100 we've tested all possible spots on grid\n If Rnd < .5 Then rdir = -1 Else rdir = 1 ' go forward or back from spot for next test\n While testNum < 101\n y = spot \\ 10\n x = spot Mod 10\n If LSS(x, y) = Mid(wdSS, 1, 1) Or LSS(x, y) = \" \" Then\n d = Int(8 * Rnd)\n If Rnd < .5 Then rdd = -1 Else rdd = 1\n dNum = 1\n While dNum < 9\n 'will wdSS fit? from at x, y\n templateSS = \"\"\n b1 = wLen * DX(d) + x >= 0 And wLen * DX(d) + x <= 9\n b2 = wLen * DY(d) + y >= 0 And wLen * DY(d) + y <= 9\n If b1 And b2 Then 'build the template of letters and spaces from Letter grid\n For i = 0 To wLen\n templateSS += LSS(x + i * DX(d), y + i * DY(d))\n Next\n If Match(wdSS, templateSS) Then 'the word will fit but does it fill anything?\n For j = 1 To Len(templateSS)\n If Asc(templateSS, j) = 32 Then 'yes a space to fill\n For i = 0 To wLen\n LSS(x + i * DX(d), y + i * DY(d)) = Mid(wdSS, i + 1, 1)\n Next\n WI += 1\n WSS(WI) = wdSS: WX(WI) = x: WY(WI) = y: WD(WI) = d\n ShowPuzzle\n If CountSpaces = 0 Then FILLED = TRUE\n Exit Sub 'get out now that word is loaded\n End If\n Next\n 'if still here keep looking\n End If\n End If\n d = (d + 8 + rdd) Mod 8\n dNum += 1\n Wend\n End If\n spot = (spot + 100 + rdir) Mod 100\n testNum += 1\n Wend\nEnd Sub\n\nSub FindAllWords\n Dim As String wdSS, templateSS, wateSS\n Dim As ULong wLen, x, y, d, j\n Dim As Boolean b1, b2\n\n For i As ULong = 1 To NWORDS\n wdSS = CWORDSSS(i)\n wLen = Len(wdSS) - 1\n For y = 0 To 9\n For x = 0 To 9\n If LSS(x, y) = Mid(wdSS, 1, 1) Then\n For d = 0 To 7\n b1 = wLen * DX(d) + x >= 0 And wLen * DX(d) + x <= 9\n b2 = wLen * DY(d) + y >= 0 And wLen * DY(d) + y <= 9\n If b1 And b2 Then 'build the template of letters and spaces from Letter grid\n templateSS = \"\"\n For j = 0 To wLen\n templateSS += LSS(x + j * DX(d), y + j * DY(d))\n Next\n If templateSS = wdSS Then 'found a word\n 'store it\n ALLindex += 1\n ALLSS(ALLindex) = wdSS: AllX(ALLindex) = x: AllY(ALLindex) = y: AllD(ALLindex) = d\n 'report it\n Locate 22, 1: Print Space(50)\n Locate 22, 1: Print \"Found: \"; wdSS; \" (\"; TrmSS(x); \", \"; TrmSS(y); \") >>>---> \"; TrmSS(d);\n Input \" Press enter...\", wateSS\n End If\n End If\n Next\n End If\n Next\n Next\n Next\nEnd Sub\n\nSub FilePuzzle\n Dim As ULong i, r, c, ff = FreeFile\n Dim As String bSS\n\n Open \"WS Puzzle.txt\" For Output As #ff\n Print #ff, \" 0 1 2 3 4 5 6 7 8 9\"\n Print #ff,\n For r = 0 To 9\n bSS = TrmSS(r) + \" \"\n For c = 0 To 9\n bSS += LSS(c, r) + \" \"\n Next\n Print #ff, bSS\n Next\n Print #ff,\n Print #ff, \"Directions >>>---> 0 = East, 1 = SE, 2 = South, 3 = SW, 4 = West, 5 = NW, 6 = North, 7 = NE\"\n Print #ff,\n Print #ff, \" These are the items from unixdict.txt used to build the puzzle:\"\n Print #ff,\n For i = 1 To WI Step 2\n Print #ff, Right(Space(7) + TrmSS(i), 7); \") \"; Right(Space(7) + WSS(i), 10); \" (\"; TrmSS(WX(i)); \", \"; TrmSS(WY(i)); \") >>>---> \"; TrmSS(WD(i));\n If i + 1 <= WI Then\n Print #ff, Right(Space(7) + TrmSS(i + 1), 7); \") \"; Right(Space(7) + WSS(i + 1), 10); \" (\"; TrmSS(WX(i + 1)); \", \"; TrmSS(WY(i + 1)); \") >>>---> \"; TrmSS(WD(i + 1))\n Else\n Print #ff,\n End If\n Next\n Print #ff,\n Print #ff, \" These are the items from unixdict.txt found embedded in the puzzle:\"\n Print #ff,\n For i = 1 To ALLindex Step 2\n Print #ff, Right(Space(7) + TrmSS(i), 7); \") \"; Right(Space(7) + ALLSS(i), 10); \" (\"; TrmSS(AllX(i)); \", \"; TrmSS(AllY(i)); \") >>>---> \"; TrmSS(AllD(i));\n If i + 1 <= ALLindex Then\n Print #ff, Right(Space(7) + TrmSS(i + 1), 7); \") \"; Right(Space(7) + ALLSS(i + 1), 10); \" (\"; TrmSS(AllX(i + 1)); \", \"; TrmSS(AllY(i + 1)); \") >>>---> \"; TrmSS(AllD(i + 1))\n Else\n Print #ff, \"\"\n End If\n Next\n Print #ff,\n Print #ff, \"On try #\" + TrmSS(try) + \" a successful puzzle was built and filed.\"\n Close #ff\nEnd Sub\n\n\nLoadWords 'this sets NWORDS count to work with\n\nWhile try < 11\n Initialize\n ShowPuzzle\n For WORDSINDEX = 1 To NWORDS\n PlaceWord\n ' ShowPuzzle\n If FILLED Then Exit For\n Next\n If Not filled And WI > 24 Then ' we have 25 or more words\n For y As ULong = 0 To 9 ' fill spaces with random letters\n For x As ULong = 0 To 9\n If LSS(x, y) = \" \" Then LSS(x, y) = Chr(Int(Rnd * 26) + 1 + 96)\n Next\n Next\n filled = TRUE\n ShowPuzzle\n End If\n If FILLED And WI > 24 Then\n FindAllWords\n FilePuzzle\n Locate 23, 1: Print \"On try #\"; TrmSS(try); \" a successful puzzle was built and filed.\"\n Exit While\n Else\n try += 1\n End If\nWend\n\nIf Not FILLED Then Locate 23, 1: Print \"Sorry, 10 tries and no success.\"\n\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"math/rand\"\n \"os\"\n \"regexp\"\n \"strings\"\n \"time\"\n)\n\nvar dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}\n\nconst (\n nRows = 10\n nCols = nRows\n gridSize = nRows * nCols\n minWords = 25\n)\n\nvar (\n re1 = regexp.MustCompile(fmt.Sprintf(\"^[a-z]{3,%d}$\", nRows))\n re2 = regexp.MustCompile(\"[^A-Z]\")\n)\n\ntype grid struct {\n numAttempts int\n cells [nRows][nCols]byte\n solutions []string\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc readWords(fileName string) []string {\n file, err := os.Open(fileName)\n check(err)\n defer file.Close()\n var words []string\n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n if re1.MatchString(word) {\n words = append(words, word)\n }\n }\n check(scanner.Err())\n return words\n}\n\nfunc createWordSearch(words []string) *grid {\n var gr *grid\nouter:\n for i := 1; i < 100; i++ {\n gr = new(grid)\n messageLen := gr.placeMessage(\"Rosetta Code\")\n target := gridSize - messageLen\n cellsFilled := 0\n rand.Shuffle(len(words), func(i, j int) {\n words[i], words[j] = words[j], words[i]\n })\n for _, word := range words {\n cellsFilled += gr.tryPlaceWord(word)\n if cellsFilled == target {\n if len(gr.solutions) >= minWords {\n gr.numAttempts = i\n break outer\n } else { // grid is full but we didn't pack enough words, start over\n break\n }\n }\n }\n }\n return gr\n}\n\nfunc (gr *grid) placeMessage(msg string) int {\n msg = strings.ToUpper(msg)\n msg = re2.ReplaceAllLiteralString(msg, \"\")\n messageLen := len(msg)\n if messageLen > 0 && messageLen < gridSize {\n gapSize := gridSize / messageLen\n for i := 0; i < messageLen; i++ {\n pos := i*gapSize + rand.Intn(gapSize)\n gr.cells[pos/nCols][pos%nCols] = msg[i]\n }\n return messageLen\n }\n return 0\n}\n\nfunc (gr *grid) tryPlaceWord(word string) int {\n randDir := rand.Intn(len(dirs))\n randPos := rand.Intn(gridSize)\n for dir := 0; dir < len(dirs); dir++ {\n dir = (dir + randDir) % len(dirs)\n for pos := 0; pos < gridSize; pos++ {\n pos = (pos + randPos) % gridSize\n lettersPlaced := gr.tryLocation(word, dir, pos)\n if lettersPlaced > 0 {\n return lettersPlaced\n }\n }\n }\n return 0\n}\n\nfunc (gr *grid) tryLocation(word string, dir, pos int) int {\n r := pos / nCols\n c := pos % nCols\n le := len(word)\n\n // check bounds\n if (dirs[dir][0] == 1 && (le+c) > nCols) ||\n (dirs[dir][0] == -1 && (le-1) > c) ||\n (dirs[dir][1] == 1 && (le+r) > nRows) ||\n (dirs[dir][1] == -1 && (le-1) > r) {\n return 0\n }\n overlaps := 0\n\n // check cells\n rr := r\n cc := c\n for i := 0; i < le; i++ {\n if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {\n return 0\n }\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n\n // place\n rr = r\n cc = c\n for i := 0; i < le; i++ {\n if gr.cells[rr][cc] == word[i] {\n overlaps++\n } else {\n gr.cells[rr][cc] = word[i]\n }\n if i < le-1 {\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n }\n\n lettersPlaced := le - overlaps\n if lettersPlaced > 0 {\n sol := fmt.Sprintf(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr)\n gr.solutions = append(gr.solutions, sol)\n }\n return lettersPlaced\n}\n\nfunc printResult(gr *grid) {\n if gr.numAttempts == 0 {\n fmt.Println(\"No grid to display\")\n return\n }\n size := len(gr.solutions)\n fmt.Println(\"Attempts:\", gr.numAttempts)\n fmt.Println(\"Number of words:\", size)\n fmt.Println(\"\\n 0 1 2 3 4 5 6 7 8 9\")\n for r := 0; r < nRows; r++ {\n fmt.Printf(\"\\n%d \", r)\n for c := 0; c < nCols; c++ {\n fmt.Printf(\" %c \", gr.cells[r][c])\n }\n }\n fmt.Println(\"\\n\")\n for i := 0; i < size-1; i += 2 {\n fmt.Printf(\"%s %s\\n\", gr.solutions[i], gr.solutions[i+1])\n }\n if size%2 == 1 {\n fmt.Println(gr.solutions[size-1])\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n unixDictPath := \"/usr/share/dict/words\"\n printResult(createWordSearch(readWords(unixDictPath)))\n}\n", "language": "Go" }, { "code": "require'web/gethttp'\n\nunixdict=:verb define\n if. _1 -: fread 'unixdict.txt' do.\n (gethttp 'http://www.puzzlers.org/pub/wordlists/unixdict.txt') fwrite 'unixdict.txt'\n end.\n fread 'unixdict.txt'\n)\n\nwords=:verb define\n (#~ 1 - 0&e.@e.&'abcdefghijklmnopqrstuvwxyz'@>) (#~ [: (2&< * 10&>:) #@>) <;._2 unixdict''\n)\n\ndirs=: 10#.0 0-.~>,{,~<i:1\nlims=: _10+,\"2 +/&>/\"1 (0~:i:4)#>,{,~<<\"1]1 10 1 +i.\"0]10*i:_1\ndnms=: ;:'nw north ne west east sw south se'\n\ngenpuz=:verb define\n words=. words''\n fill=. 'ROSETTACODE'\n grid=. ,10 10$' '\n inds=. ,i.10 10\n patience=. -:#words\n key=. i.0 0\n inuse=. i.0 2\n while. (26>#key)+.0<cap=. (+/' '=grid)-#fill do.\n word=. >({~ ?@#) words\n dir=. ?@#dirs\n offs=. (inds#~(#word)<:inds{dir{lims)+/(i.#word)*/dir{dirs\n cool=. ' '=offs{grid\n sel=. */\"1 cool+.(offs{grid)=\"1 word\n offs=. (sel*cap>:+/\"1 cool)#offs\n if. (#offs) do.\n off=. ({~ ?@#) offs\n loc=. ({.off),dir\n if. -. loc e. inuse do.\n inuse=. inuse,loc\n grid=. word off} grid\n patience=. patience+1\n key=. /:~ key,' ',(10{.word),(3\":1+10 10#:{.off),' ',dir{::dnms\n end.\n else. NB. grr...\n if. 0 > patience=. patience-1 do.\n inuse=.i.0 2\n key=.i.0 0\n grid=. ,10 10$' '\n patience=. -:#words\n end.\n end.\n end.\n puz=. (_23{.\":i.10),' ',1j1#\"1(\":i.10 1),.' ',.10 10$fill (I.grid=' ')} grid\n puz,' ',1 1}._1 _1}.\":((</.~ <.) i.@# * 3%#)key\n)\n", "language": "J" }, { "code": " genpuz''\n 0 1 2 3 4 5 6 7 8 9\n\n0 y R p y r f O a p S\n1 l o l s i f c c e a\n2 l n v z i e n r n l\n3 o p z s t e E i n l\n4 h l s a v e r d a o\n5 e a t a g r e e d y\n6 m e m a g T f T A C\n7 a y e r s p f z a p\n8 O e c n a w o l l a\n9 e s o p o r p c D E\n\n acetate 1 8 sw │ gam 7 5 west │ pol 1 3 sw\n acrid 1 8 south│ holly 5 1 north│ propose 10 7 west\n agreed 6 4 east │ massif 7 1 ne │ rsvp 1 5 sw\n allowance 9 10 west │ neva 3 7 sw │ sao 8 5 south\n alloy 2 10 south│ offer 9 7 north│ save 5 3 east\n arm 9 5 nw │ only 4 1 ne │ sop 10 2 east\n ayers 8 1 east │ pap 10 4 ne │ tee 4 5 se\n cop 10 8 nw │ paz 8 10 west │ wan 9 6 west\n fizzle 1 6 sw │ penna 1 9 south│\n", "language": "J" }, { "code": "import java.io.*;\nimport static java.lang.String.format;\nimport java.util.*;\n\npublic class WordSearch {\n static class Grid {\n int numAttempts;\n char[][] cells = new char[nRows][nCols];\n List<String> solutions = new ArrayList<>();\n }\n\n final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},\n {0, -1}, {-1, -1}, {-1, 1}};\n\n final static int nRows = 10;\n final static int nCols = 10;\n final static int gridSize = nRows * nCols;\n final static int minWords = 25;\n\n final static Random rand = new Random();\n\n public static void main(String[] args) {\n printResult(createWordSearch(readWords(\"unixdict.txt\")));\n }\n\n static List<String> readWords(String filename) {\n int maxLen = Math.max(nRows, nCols);\n\n List<String> words = new ArrayList<>();\n try (Scanner sc = new Scanner(new FileReader(filename))) {\n while (sc.hasNext()) {\n String s = sc.next().trim().toLowerCase();\n if (s.matches(\"^[a-z]{3,\" + maxLen + \"}$\"))\n words.add(s);\n }\n } catch (FileNotFoundException e) {\n System.out.println(e);\n }\n return words;\n }\n\n static Grid createWordSearch(List<String> words) {\n Grid grid = null;\n int numAttempts = 0;\n\n outer:\n while (++numAttempts < 100) {\n Collections.shuffle(words);\n\n grid = new Grid();\n int messageLen = placeMessage(grid, \"Rosetta Code\");\n int target = gridSize - messageLen;\n\n int cellsFilled = 0;\n for (String word : words) {\n cellsFilled += tryPlaceWord(grid, word);\n if (cellsFilled == target) {\n if (grid.solutions.size() >= minWords) {\n grid.numAttempts = numAttempts;\n break outer;\n } else break; // grid is full but we didn't pack enough words, start over\n }\n }\n }\n\n return grid;\n }\n\n static int placeMessage(Grid grid, String msg) {\n msg = msg.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n\n int messageLen = msg.length();\n if (messageLen > 0 && messageLen < gridSize) {\n int gapSize = gridSize / messageLen;\n\n for (int i = 0; i < messageLen; i++) {\n int pos = i * gapSize + rand.nextInt(gapSize);\n grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);\n }\n return messageLen;\n }\n return 0;\n }\n\n static int tryPlaceWord(Grid grid, String word) {\n int randDir = rand.nextInt(dirs.length);\n int randPos = rand.nextInt(gridSize);\n\n for (int dir = 0; dir < dirs.length; dir++) {\n dir = (dir + randDir) % dirs.length;\n\n for (int pos = 0; pos < gridSize; pos++) {\n pos = (pos + randPos) % gridSize;\n\n int lettersPlaced = tryLocation(grid, word, dir, pos);\n if (lettersPlaced > 0)\n return lettersPlaced;\n }\n }\n return 0;\n }\n\n static int tryLocation(Grid grid, String word, int dir, int pos) {\n\n int r = pos / nCols;\n int c = pos % nCols;\n int len = word.length();\n\n // check bounds\n if ((dirs[dir][0] == 1 && (len + c) > nCols)\n || (dirs[dir][0] == -1 && (len - 1) > c)\n || (dirs[dir][1] == 1 && (len + r) > nRows)\n || (dirs[dir][1] == -1 && (len - 1) > r))\n return 0;\n\n int rr, cc, i, overlaps = 0;\n\n // check cells\n for (i = 0, rr = r, cc = c; i < len; i++) {\n if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))\n return 0;\n cc += dirs[dir][0];\n rr += dirs[dir][1];\n }\n\n // place\n for (i = 0, rr = r, cc = c; i < len; i++) {\n if (grid.cells[rr][cc] == word.charAt(i))\n overlaps++;\n else\n grid.cells[rr][cc] = word.charAt(i);\n\n if (i < len - 1) {\n cc += dirs[dir][0];\n rr += dirs[dir][1];\n }\n }\n\n int lettersPlaced = len - overlaps;\n if (lettersPlaced > 0) {\n grid.solutions.add(format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr));\n }\n\n return lettersPlaced;\n }\n\n static void printResult(Grid grid) {\n if (grid == null || grid.numAttempts == 0) {\n System.out.println(\"No grid to display\");\n return;\n }\n int size = grid.solutions.size();\n\n System.out.println(\"Attempts: \" + grid.numAttempts);\n System.out.println(\"Number of words: \" + size);\n\n System.out.println(\"\\n 0 1 2 3 4 5 6 7 8 9\");\n for (int r = 0; r < nRows; r++) {\n System.out.printf(\"%n%d \", r);\n for (int c = 0; c < nCols; c++)\n System.out.printf(\" %c \", grid.cells[r][c]);\n }\n\n System.out.println(\"\\n\");\n\n for (int i = 0; i < size - 1; i += 2) {\n System.out.printf(\"%s %s%n\", grid.solutions.get(i),\n grid.solutions.get(i + 1));\n }\n if (size % 2 == 1)\n System.out.println(grid.solutions.get(size - 1));\n }\n}\n", "language": "Java" }, { "code": "using Random\n\nconst stepdirections = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nconst nrows = 10\nconst ncols = nrows\nconst gridsize = nrows * ncols\nconst minwords = 25\nconst minwordsize = 3\n\nmutable struct LetterGrid\n nattempts::Int\n nrows::Int\n ncols::Int\n cells::Matrix{Char}\n solutions::Vector{String}\n LetterGrid() = new(0, nrows, ncols, fill(' ', nrows, ncols), Vector{String}())\nend\n\nfunction wordmatrix(filename, usepropernames = true)\n words = [lowercase(line) for line in readlines(filename)\n if match(r\"^[a-zA-Z]+$\", line) != nothing && (usepropernames ||\n match(r\"^[a-z]\", line) != nothing) && length(line) >= minwordsize && length(line) <= ncols]\n n = 1000\n for i in 1:n\n grid = LetterGrid()\n messagelen = placemessage(grid, \"Rosetta Code\")\n target = grid.nrows * grid.ncols - messagelen\n cellsfilled = 0\n shuffle!(words)\n for word in words\n cellsfilled += tryplaceword(grid, word)\n if cellsfilled == target\n if length(grid.solutions) >= minwords\n grid.nattempts = i\n return grid\n else\n break\n end\n end\n end\n end\n throw(\"Failed to place words after $n attempts\")\nend\n\nfunction placemessage(grid, msg)\n msg = uppercase(msg)\n msg = replace(msg, r\"[^A-Z]\" => \"\")\n messagelen = length(msg)\n if messagelen > 0 && messagelen < gridsize\n p = Int.(floor.(LinRange(messagelen, gridsize, messagelen) .+\n (rand(messagelen) .- 0.5) * messagelen / 3)) .- div(messagelen, 3)\n foreach(i -> grid.cells[div(p[i], nrows) + 1, p[i] % nrows + 1] = msg[i], 1:length(p))\n return messagelen\n end\n return 0\nend\n\nfunction tryplaceword(grid, word)\n for dir in shuffle(stepdirections)\n for pos in shuffle(1:length(grid.cells))\n lettersplaced = trylocation(grid, word, dir, pos)\n if lettersplaced > 0\n return lettersplaced\n end\n end\n end\n return 0\nend\n\nfunction trylocation(grid, word, dir, pos)\n r, c = divrem(pos, nrows) .+ [1, 1]\n positions = [[r, c] .+ (dir .* i) for i in 1:length(word)]\n if !all(x -> 0 < x[1] <= nrows && 0 < x[2] <= ncols, positions)\n return 0\n end\n for (i, p) in enumerate(positions)\n letter = grid.cells[p[1],p[2]]\n if letter != ' ' && letter != word[i]\n return 0\n end\n end\n lettersplaced = 0\n for (i, p) in enumerate(positions)\n if grid.cells[p[1], p[2]] == ' '\n lettersplaced += 1\n grid.cells[p[1],p[2]] = word[i]\n end\n end\n if lettersplaced > 0\n push!(grid.solutions, lpad(word, 10) * \" $(positions[1]) to $(positions[end])\")\n end\n return lettersplaced\nend\n\nfunction printresult(grid)\n if grid.nattempts == 0\n println(\"No grid to display: no solution found.\")\n return\n end\n size = length(grid.solutions)\n println(\"Attempts: \", grid.nattempts)\n println(\"Number of words: \", size)\n println(\"\\n 0 1 2 3 4 5 6 7 8 9\")\n for r in 1:nrows\n print(\"\\n\", rpad(r, 4))\n for c in 1:ncols\n print(\" $(grid.cells[r, c]) \")\n end\n end\n println()\n for i in 1:2:size\n println(\"$(grid.solutions[i]) $(i < size ? grid.solutions[i+1] : \"\")\")\n end\nend\n\nprintresult(wordmatrix(\"words.txt\", false))\n", "language": "Julia" }, { "code": "// version 1.2.0\n\nimport java.util.Random\nimport java.io.File\n\nval dirs = listOf(\n intArrayOf( 1, 0), intArrayOf(0, 1), intArrayOf( 1, 1), intArrayOf( 1, -1),\n intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 1)\n)\n\nval nRows = 10\nval nCols = 10\nval gridSize = nRows * nCols\nval minWords = 25\nval rand = Random()\n\nclass Grid {\n var numAttempts = 0\n val cells = List(nRows) { CharArray(nCols) }\n val solutions = mutableListOf<String>()\n}\n\nfun readWords(fileName: String): List<String> {\n val maxLen = maxOf(nRows, nCols)\n val rx = Regex(\"^[a-z]{3,$maxLen}$\")\n val f = File(fileName)\n return f.readLines().map { it.trim().toLowerCase() }\n .filter { it.matches(rx) }\n}\n\nfun createWordSearch(words: List<String>): Grid {\n var numAttempts = 0\n lateinit var grid: Grid\n outer@ while (++numAttempts < 100) {\n grid = Grid()\n val messageLen = placeMessage(grid, \"Rosetta Code\")\n val target = gridSize - messageLen\n var cellsFilled = 0\n for (word in words.shuffled()) {\n cellsFilled += tryPlaceWord(grid, word)\n if (cellsFilled == target) {\n if (grid.solutions.size >= minWords) {\n grid.numAttempts = numAttempts\n break@outer\n }\n else { // grid is full but we didn't pack enough words, start over\n break\n }\n }\n }\n }\n return grid\n}\n\nfun placeMessage(grid: Grid, msg: String): Int {\n val rx = Regex(\"[^A-Z]\")\n val msg2 = msg.toUpperCase().replace(rx, \"\")\n val messageLen = msg2.length\n if (messageLen in (1 until gridSize)) {\n val gapSize = gridSize / messageLen\n for (i in 0 until messageLen) {\n val pos = i * gapSize + rand.nextInt(gapSize)\n grid.cells[pos / nCols][pos % nCols] = msg2[i]\n }\n return messageLen\n }\n return 0\n}\n\nfun tryPlaceWord(grid: Grid, word: String): Int {\n val randDir = rand.nextInt(dirs.size)\n val randPos = rand.nextInt(gridSize)\n for (d in 0 until dirs.size) {\n val dir = (d + randDir) % dirs.size\n for (p in 0 until gridSize) {\n val pos = (p + randPos) % gridSize\n val lettersPlaced = tryLocation(grid, word, dir, pos)\n if (lettersPlaced > 0) return lettersPlaced\n }\n }\n return 0\n}\n\nfun tryLocation(grid: Grid, word: String, dir: Int, pos: Int): Int {\n val r = pos / nCols\n val c = pos % nCols\n val len = word.length\n\n // check bounds\n if ((dirs[dir][0] == 1 && (len + c) > nCols)\n || (dirs[dir][0] == -1 && (len - 1) > c)\n || (dirs[dir][1] == 1 && (len + r) > nRows)\n || (dirs[dir][1] == -1 && (len - 1) > r)) return 0\n var overlaps = 0\n\n // check cells\n var rr = r\n var cc = c\n for (i in 0 until len) {\n if (grid.cells[rr][cc] != '\\u0000' && grid.cells[rr][cc] != word[i]) return 0\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n\n // place\n rr = r\n cc = c\n for (i in 0 until len) {\n if (grid.cells[rr][cc] == word[i])\n overlaps++\n else\n grid.cells[rr][cc] = word[i]\n\n if (i < len - 1) {\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n }\n\n val lettersPlaced = len - overlaps\n if (lettersPlaced > 0) {\n grid.solutions.add(String.format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr))\n }\n return lettersPlaced\n}\n\nfun printResult(grid: Grid) {\n if (grid.numAttempts == 0) {\n println(\"No grid to display\")\n return\n }\n val size = grid.solutions.size\n println(\"Attempts: ${grid.numAttempts}\")\n println(\"Number of words: $size\")\n println(\"\\n 0 1 2 3 4 5 6 7 8 9\")\n for (r in 0 until nRows) {\n print(\"\\n$r \")\n for (c in 0 until nCols) print(\" ${grid.cells[r][c]} \")\n }\n\n println(\"\\n\")\n\n for (i in 0 until size - 1 step 2) {\n println(\"${grid.solutions[i]} ${grid.solutions[i + 1]}\")\n }\n if (size % 2 == 1) println(grid.solutions[size - 1])\n}\n\nfun main(args: Array<String>) {\n printResult(createWordSearch(readWords(\"unixdict.txt\")))\n}\n", "language": "Kotlin" }, { "code": "import random, sequtils, strformat, strutils\n\nconst\n\n Dirs = [[1, 0], [ 0, 1], [ 1, 1],\n [1, -1], [-1, 0],\n [0, -1], [-1, -1], [-1, 1]]\n\n NRows = 10\n NCols = 10\n GridSize = NRows * NCols\n MinWords = 25\n\ntype Grid = ref object\n numAttempts: Natural\n cells: array[NRows, array[NCols, char]]\n solutions: seq[string]\n\nproc readWords(filename: string): seq[string] =\n\n const MaxLen = max(NRows, NCols)\n\n for word in filename.lines():\n if word.len in 3..MaxLen:\n if word.allCharsInSet(Letters):\n result.add word.toLowerAscii\n\n\nproc placeMessage(grid: var Grid; msg: string): int =\n let msg = msg.map(toUpperAscii).filter(isUpperAscii).join()\n if msg.len in 1..<GridSize:\n let gapSize = GridSize div msg.len\n for i in 0..msg.high:\n let pos = i * gapSize + rand(gapSize - 1)\n grid.cells[pos div NCols][pos mod NCols] = msg[i]\n result = msg.len\n\n\nproc tryLocation(grid: var Grid; word: string; dir, pos: Natural): int =\n let row = pos div NCols\n let col = pos mod NCols\n let length = word.len\n\n # Check bounds.\n if (Dirs[dir][0] == 1 and (length + col) > NCols) or\n (Dirs[dir][0] == -1 and (length - 1) > col) or\n (Dirs[dir][1] == 1 and (length + row) > NRows) or\n (Dirs[dir][1] == -1 and (length - 1) > row):\n return 0\n\n # Check cells.\n var r = row\n var c = col\n for ch in word:\n if grid.cells[r][c] != '\\0' and grid.cells[r][c] != ch: return 0\n c += Dirs[dir][0]\n r += Dirs[dir][1]\n\n # Place.\n r = row\n c = col\n var overlaps = 0\n for i, ch in word:\n if grid.cells[r][c] == ch: inc overlaps\n else: grid.cells[r][c] = ch\n if i < word.high:\n c += Dirs[dir][0]\n r += Dirs[dir][1]\n\n let lettersPlaced = length - overlaps\n if lettersPlaced > 0:\n grid.solutions.add &\"{word:<10} ({col}, {row}) ({c}, {r})\"\n\n result = lettersPlaced\n\n\nproc tryPlaceWord(grid: var Grid; word: string): int =\n let randDir = rand(Dirs.high)\n let randPos = rand(GridSize - 1)\n\n for dir in 0..Dirs.high:\n let dir = (dir + randDir) mod Dirs.len\n for pos in 0..<GridSize:\n let pos = (pos + randPos) mod GridSize\n let lettersPlaced = grid.tryLocation(word, dir, pos)\n if lettersPlaced > 0:\n return lettersPlaced\n\n\nproc initGrid(words: seq[string]): Grid =\n var words = words\n for numAttempts in 1..100:\n words.shuffle()\n new(result)\n let messageLen = result.placeMessage(\"Rosetta Code\")\n let target = GridSize - messageLen\n\n var cellsFilled = 0\n for word in words:\n cellsFilled += result.tryPlaceWord(word)\n if cellsFilled == target:\n if result.solutions.len >= MinWords:\n result.numAttempts = numAttempts\n return\n # Grid is full but we didn't pack enough words: start over.\n break\n\nproc printResult(grid: Grid) =\n if grid.isNil or grid.numAttempts == 0:\n echo \"No grid to display.\"\n return\n\n let size = grid.solutions.len\n echo \"Attempts: \", grid.numAttempts\n echo \"Number of words: \", size\n\n echo \"\\n 0 1 2 3 4 5 6 7 8 9\\n\"\n for r in 0..<NRows:\n echo &\"{r} \", grid.cells[r].join(\" \")\n echo()\n\n for i in countup(0, size - 2, 2):\n echo grid.solutions[i], \" \", grid.solutions[i + 1]\n if (size and 1) == 1:\n echo grid.solutions[^1]\n\n\nrandomize()\nlet grid = initGrid(\"unixdict.txt\".readWords())\ngrid.printResult()\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse feature <bitwise>;\nuse Path::Tiny;\nuse List::Util qw( shuffle );\n\nmy $size = 10;\nmy $s1 = $size + 1;\n$_ = <<END;\n.....R....\n......O...\n.......S..\n........E.\nT........T\n.A........\n..C.......\n...O......\n....D.....\n.....E....\nEND\n\nmy @words = shuffle path('/usr/share/dict/words')->slurp =~ /^[a-z]{3,7}$/gm;\nmy @played;\nmy %used;\n\nfor my $word ( (@words) x 5 )\n {\n my ($pat, $start, $end, $mask, $nulls) = find( $word );\n defined $pat or next;\n $used{$word}++ and next; # only use words once\n $nulls //= '';\n my $expand = $word =~ s/\\B/$nulls/gr;\n my $pos = $start;\n if( $start > $end )\n {\n $pos = $end;\n $expand = reverse $expand;\n }\n substr $_, $pos, length $mask,\n (substr( $_, $pos, length $mask ) &. ~. \"$mask\") |. \"$expand\";\n push @played, join ' ', $word, $start, $end;\n tr/.// > 0 or last;\n }\n\nprint \" 0 1 2 3 4 5 6 7 8 9\\n\\n\";\nmy $row = 0;\nprint s/(?<=.)(?=.)/ /gr =~ s/^/ $row++ . ' ' /gemr;\nprint \"\\nNumber of words: \", @played . \"\\n\\n\";\nmy @where = map\n {\n my ($word, $start, $end) = split;\n sprintf \"%11s %s\", $word, $start < $end\n ? \"(@{[$start % $s1]},@{[int $start / $s1]})->\" .\n \"(@{[$end % $s1 - 1]},@{[int $end / $s1]})\"\n : \"(@{[$start % $s1 - 1]},@{[int $start / $s1]})->\" .\n \"(@{[$end % $s1]},@{[int $end / $s1]})\";\n } sort @played;\nprint splice(@where, 0, 3), \"\\n\" while @where;\ntr/.// and die \"incomplete\";\n\nsub find\n {\n my ($word) = @_;\n my $n = length $word;\n my $nm1 = $n - 1;\n my %pats;\n\n for my $space ( 0, $size - 1 .. $size + 1 )\n {\n my $nulls = \"\\0\" x $space;\n my $mask = \"\\xff\" . ($nulls . \"\\xff\") x $nm1; # vert\n my $gap = qr/.{$space}/s;\n while( /(?=(.(?:$gap.){$nm1}))/g )\n {\n my $pat = ($1 &. $mask) =~ tr/\\0//dr;\n $pat =~ tr/.// or next;\n my $pos = \"$-[1] $+[1]\";\n $word =~ /$pat/ or reverse($word) =~ /$pat/ or next;\n push @{ $pats{$pat} }, \"$pos $mask $nulls\";\n }\n }\n\n for my $key ( sort keys %pats )\n {\n if( $word =~ /^$key$/ )\n {\n my @all = @{ $pats{$key} };\n return $key, split ' ', $all[ rand @all ];\n }\n elsif( (reverse $word) =~ /^$key$/ )\n {\n my @all = @{ $pats{$key} };\n my @parts = split ' ', $all[ rand @all ];\n return $key, @parts[ 1, 0, 2, 3]\n }\n }\n\n return undef;\n }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\wordsearch.exw\n -- ===========================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">message</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"ROSETTACODE\"</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">words</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unix_dict</span><span style=\"color: #0000FF;\">(),</span> <span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">placed</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">grid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"\"\"\n X 0 1 2 3 4 5 6 7 8 9 X\n 0 X\n 1 X\n 2 X\n 3 X\n 4 X\n 5 X\n 6 X\n 7 X\n 8 X\n 9 X\n X X X X X X X X X X X X\"\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">DX</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">DY</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">wordsearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rqd</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">rw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">))),</span>\n <span style=\"color: #000000;\">rd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">rs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">shuffle</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rs</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">sx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">rs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">sy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">4</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rw</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">rw</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">]]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rd</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">DX</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">rd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">]],</span><span style=\"color: #000000;\">DY</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">rd</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">]]},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sy</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">chcount</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">newgrid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #008000;\">' '</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">chcount</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">chcount</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">newgrid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">nx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">dx</span>\n <span style=\"color: #000000;\">ny</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">dy</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">chcount</span><span style=\"color: #0000FF;\">!=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">posinfo</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #000000;\">sy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">nx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #000000;\">ny</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">dy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">newdone</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]),</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">done</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]),</span><span style=\"color: #000000;\">posinfo</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">rqd</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">chcount</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">placed</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">newgrid</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">newdone</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">chcount</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">wordsearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">newgrid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rqd</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">left</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">chcount</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">newdone</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">valid_word</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ch</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #008000;\">'a'</span>\n <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">ch</span><span style=\"color: #0000FF;\">></span><span style=\"color: #008000;\">'z'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">valid_word</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[$]</span>\n <span style=\"color: #000000;\">words</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d words loaded\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">))</span> <span style=\"color: #000080;font-style:italic;\">-- 24822</span>\n\n <span style=\"color: #000000;\">wordsearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">grid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">25</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,{{},{}})</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">11</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">31</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">' '</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">message</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">message</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">substitute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">solution</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">'\\n'</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"X\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n%d words\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">placed</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">placed</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%10s %10s \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">placed</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #7060A8;\">sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">placed</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "import re\nfrom random import shuffle, randint\n\ndirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]\nn_rows = 10\nn_cols = 10\ngrid_size = n_rows * n_cols\nmin_words = 25\n\n\nclass Grid:\n def __init__(self):\n self.num_attempts = 0\n self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]\n self.solutions = []\n\n\ndef read_words(filename):\n max_len = max(n_rows, n_cols)\n\n words = []\n with open(filename, \"r\") as file:\n for line in file:\n s = line.strip().lower()\n if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:\n words.append(s)\n\n return words\n\n\ndef place_message(grid, msg):\n msg = re.sub(r'[^A-Z]', \"\", msg.upper())\n\n message_len = len(msg)\n if 0 < message_len < grid_size:\n gap_size = grid_size // message_len\n\n for i in range(0, message_len):\n pos = i * gap_size + randint(0, gap_size)\n grid.cells[pos // n_cols][pos % n_cols] = msg[i]\n\n return message_len\n\n return 0\n\n\ndef try_location(grid, word, direction, pos):\n r = pos // n_cols\n c = pos % n_cols\n length = len(word)\n\n # check bounds\n if (dirs[direction][0] == 1 and (length + c) > n_cols) or \\\n (dirs[direction][0] == -1 and (length - 1) > c) or \\\n (dirs[direction][1] == 1 and (length + r) > n_rows) or \\\n (dirs[direction][1] == -1 and (length - 1) > r):\n return 0\n\n rr = r\n cc = c\n i = 0\n overlaps = 0\n\n # check cells\n while i < length:\n if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:\n return 0\n cc += dirs[direction][0]\n rr += dirs[direction][1]\n i += 1\n\n rr = r\n cc = c\n i = 0\n # place\n while i < length:\n if grid.cells[rr][cc] == word[i]:\n overlaps += 1\n else:\n grid.cells[rr][cc] = word[i]\n\n if i < length - 1:\n cc += dirs[direction][0]\n rr += dirs[direction][1]\n\n i += 1\n\n letters_placed = length - overlaps\n if letters_placed > 0:\n grid.solutions.append(\"{0:<10} ({1},{2})({3},{4})\".format(word, c, r, cc, rr))\n\n return letters_placed\n\n\ndef try_place_word(grid, word):\n rand_dir = randint(0, len(dirs))\n rand_pos = randint(0, grid_size)\n\n for direction in range(0, len(dirs)):\n direction = (direction + rand_dir) % len(dirs)\n\n for pos in range(0, grid_size):\n pos = (pos + rand_pos) % grid_size\n\n letters_placed = try_location(grid, word, direction, pos)\n if letters_placed > 0:\n return letters_placed\n\n return 0\n\n\ndef create_word_search(words):\n grid = None\n num_attempts = 0\n\n while num_attempts < 100:\n num_attempts += 1\n shuffle(words)\n\n grid = Grid()\n message_len = place_message(grid, \"Rosetta Code\")\n target = grid_size - message_len\n\n cells_filled = 0\n for word in words:\n cells_filled += try_place_word(grid, word)\n if cells_filled == target:\n if len(grid.solutions) >= min_words:\n grid.num_attempts = num_attempts\n return grid\n else:\n break # grid is full but we didn't pack enough words, start over\n\n return grid\n\n\ndef print_result(grid):\n if grid is None or grid.num_attempts == 0:\n print(\"No grid to display\")\n return\n\n size = len(grid.solutions)\n\n print(\"Attempts: {0}\".format(grid.num_attempts))\n print(\"Number of words: {0}\".format(size))\n\n print(\"\\n 0 1 2 3 4 5 6 7 8 9\\n\")\n for r in range(0, n_rows):\n print(\"{0} \".format(r), end='')\n for c in range(0, n_cols):\n print(\" %c \" % grid.cells[r][c], end='')\n print()\n print()\n\n for i in range(0, size - 1, 2):\n print(\"{0} {1}\".format(grid.solutions[i], grid.solutions[i+1]))\n\n if size % 2 == 1:\n print(grid.solutions[size - 1])\n\n\nif __name__ == \"__main__\":\n print_result(create_word_search(read_words(\"unixdict.txt\")))\n", "language": "Python" }, { "code": " OPTION _EXPLICIT\n _TITLE \"Puzzle Builder for Rosetta\" 'by B+ started 2018-10-31\n ' 2018-11-02 Now that puzzle is working with basic and plus starters remove them and make sure puzzle works as well.\n ' Added Direction legend to printout.\n ' OverHauled LengthLimit()\n ' Reorgnize this to try a couple of times at given Randomize number\n ' TODO create alphabetical copy of word list and check grid for all words embedded in it.\n ' LoadWords makes a copy of word list in alpha order\n ' FindAllWords finds all the items from the dictionary\n ' OK it all seems to be working OK\n\n RANDOMIZE TIMER ' OK getting a good puzzle every time\n\n 'overhauled\n DIM SHARED LengthLimit(3 TO 10) AS _BYTE 'reset in Initialize, track and limit longer words\n\n 'LoadWords opens file of words and sets\n DIM SHARED NWORDS 'set in LoadWords, number of words with length: > 2 and < 11 and just letters\n\n ' word file words (shuffled) to be fit into puzzle and index position\n DIM SHARED WORDS$(1 TO 24945), CWORDS$(1 TO 24945), WORDSINDEX AS INTEGER 'the file has 24945 words but many are unsuitable\n\n 'words placed in Letters grid, word itself (W$) x, y head (WX, WY) and direction (WD), WI is the index to all these\n DIM SHARED W$(1 TO 100), WX(1 TO 100) AS _BYTE, WY(1 TO 100) AS _BYTE, WD(1 TO 100) AS _BYTE, WI AS _BYTE\n\n ' letters grid and direction arrays\n DIM SHARED L$(0 TO 9, 0 TO 9), DX(0 TO 7) AS _BYTE, DY(0 TO 7) AS _BYTE\n DX(0) = 1: DY(0) = 0\n DX(1) = 1: DY(1) = 1\n DX(2) = 0: DY(2) = 1\n DX(3) = -1: DY(3) = 1\n DX(4) = -1: DY(4) = 0\n DX(5) = -1: DY(5) = -1\n DX(6) = 0: DY(6) = -1\n DX(7) = 1: DY(7) = -1\n\n 'to store all the words found embedded in the grid L$()\n DIM SHARED ALL$(1 TO 200), AllX(1 TO 200) AS _BYTE, AllY(1 TO 200) AS _BYTE, AllD(1 TO 200) AS _BYTE 'to store all the words found embedded in the grid L$()\n DIM SHARED ALLindex AS INTEGER\n\n ' signal successful fill of puzzle\n DIM SHARED FILLED AS _BIT\n FILLED = 0\n DIM try AS _BYTE\n try = 1\n LoadWords 'this sets NWORDS count to work with\n WHILE try < 11\n Initialize\n ShowPuzzle\n FOR WORDSINDEX = 1 TO NWORDS\n PlaceWord\n ShowPuzzle\n IF FILLED THEN EXIT FOR\n NEXT\n IF FILLED AND WI > 24 THEN\n FindAllWords\n FilePuzzle\n LOCATE 23, 1: PRINT \"On try #\"; Trm$(try); \" a successful puzzle was built and filed.\"\n EXIT WHILE\n ELSE\n try = try + 1\n END IF\n WEND\n IF FILLED = 0 THEN LOCATE 23, 1: PRINT \"Sorry, 10 tries and no success.\"\n END\n\n SUB LoadWords\n DIM wd$, i AS INTEGER, m AS INTEGER, ok AS _BIT\n OPEN \"unixdict.txt\" FOR INPUT AS #1\n WHILE EOF(1) = 0\n INPUT #1, wd$\n IF LEN(wd$) > 2 AND LEN(wd$) < 11 THEN\n ok = -1\n FOR m = 1 TO LEN(wd$)\n IF ASC(wd$, m) < 97 OR ASC(wd$, m) > 122 THEN ok = 0: EXIT FOR\n NEXT\n IF ok THEN i = i + 1: WORDS$(i) = wd$: CWORDS$(i) = wd$\n END IF\n WEND\n CLOSE #1\n NWORDS = i\n END SUB\n\n SUB Shuffle\n DIM i AS INTEGER, r AS INTEGER\n FOR i = NWORDS TO 2 STEP -1\n r = INT(RND * i) + 1\n SWAP WORDS$(i), WORDS$(r)\n NEXT\n END SUB\n\n SUB Initialize\n DIM r AS _BYTE, c AS _BYTE, x AS _BYTE, y AS _BYTE, d AS _BYTE, wd$\n FOR r = 0 TO 9\n FOR c = 0 TO 9\n L$(c, r) = \" \"\n NEXT\n NEXT\n\n 'reset word arrays by resetting the word index back to zero\n WI = 0\n\n 'fun stuff for me but doubt others would like that much fun!\n 'pluggin \"basic\", 0, 0, 2\n 'pluggin \"plus\", 1, 0, 0\n\n 'to assure the spreading of ROSETTA CODE\n L$(INT(RND * 5) + 5, 0) = \"R\": L$(INT(RND * 9) + 1, 1) = \"O\"\n L$(INT(RND * 9) + 1, 2) = \"S\": L$(INT(RND * 9) + 1, 3) = \"E\"\n L$(1, 4) = \"T\": L$(9, 4) = \"T\": L$(INT(10 * RND), 5) = \"A\"\n L$(INT(10 * RND), 6) = \"C\": L$(INT(10 * RND), 7) = \"O\"\n L$(INT(10 * RND), 8) = \"D\": L$(INT(10 * RND), 9) = \"E\"\n\n 'reset limits\n LengthLimit(3) = 200\n LengthLimit(4) = 6\n LengthLimit(5) = 3\n LengthLimit(6) = 2\n LengthLimit(7) = 1\n LengthLimit(8) = 0\n LengthLimit(9) = 0\n LengthLimit(10) = 0\n\n 'reset word order\n Shuffle\n END SUB\n\n 'for fun plug-in of words\n SUB pluggin (wd$, x AS INTEGER, y AS INTEGER, d AS INTEGER)\n DIM i AS _BYTE\n FOR i = 0 TO LEN(wd$) - 1\n L$(x + i * DX(d), y + i * DY(d)) = MID$(wd$, i + 1, 1)\n NEXT\n WI = WI + 1\n W$(WI) = wd$: WX(WI) = x: WY(WI) = y: WD(WI) = d\n END SUB\n\n FUNCTION Trm$ (n AS INTEGER)\n Trm$ = RTRIM$(LTRIM$(STR$(n)))\n END FUNCTION\n\n SUB ShowPuzzle\n DIM i AS _BYTE, x AS _BYTE, y AS _BYTE, wate$\n CLS\n PRINT \" 0 1 2 3 4 5 6 7 8 9\"\n LOCATE 3, 1\n FOR i = 0 TO 9\n PRINT Trm$(i)\n NEXT\n FOR y = 0 TO 9\n FOR x = 0 TO 9\n LOCATE y + 3, 2 * x + 5: PRINT L$(x, y)\n NEXT\n NEXT\n FOR i = 1 TO WI\n IF i < 20 THEN\n LOCATE i + 1, 30: PRINT Trm$(i); \" \"; W$(i)\n ELSEIF i < 40 THEN\n LOCATE i - 20 + 1, 45: PRINT Trm$(i); \" \"; W$(i)\n ELSEIF i < 60 THEN\n LOCATE i - 40 + 1, 60: PRINT Trm$(i); \" \"; W$(i)\n END IF\n NEXT\n LOCATE 18, 1: PRINT \"Spaces left:\"; CountSpaces%\n LOCATE 19, 1: PRINT NWORDS\n LOCATE 20, 1: PRINT SPACE$(16)\n IF WORDSINDEX THEN LOCATE 20, 1: PRINT Trm$(WORDSINDEX); \" \"; WORDS$(WORDSINDEX)\n 'LOCATE 15, 1: INPUT \"OK, press enter... \"; wate$\n END SUB\n\n 'used in PlaceWord\n FUNCTION CountSpaces% ()\n DIM x AS _BYTE, y AS _BYTE, count AS INTEGER\n FOR y = 0 TO 9\n FOR x = 0 TO 9\n IF L$(x, y) = \" \" THEN count = count + 1\n NEXT\n NEXT\n CountSpaces% = count\n END FUNCTION\n\n 'used in PlaceWord\n FUNCTION Match% (word AS STRING, template AS STRING)\n DIM i AS INTEGER, c AS STRING\n Match% = 0\n IF LEN(word) <> LEN(template) THEN EXIT FUNCTION\n FOR i = 1 TO LEN(template)\n IF ASC(template, i) <> 32 AND (ASC(word, i) <> ASC(template, i)) THEN EXIT FUNCTION\n NEXT\n Match% = -1\n END FUNCTION\n\n 'heart of puzzle builder\n SUB PlaceWord\n ' place the words randomly in the grid\n ' start at random spot and work forward or back 100 times = all the squares\n ' for each open square try the 8 directions for placing the word\n ' even if word fits Rossetta Challenge task requires leaving 11 openings to insert ROSETTA CODE,\n ' exactly 11 spaces needs to be left, if/when this occurs FILLED will be set true to signal finished to main loop\n ' if place a word update L$, WI, W$(WI), WX(WI), WY(WI), WD(WI)\n\n DIM wd$, wLen AS _BYTE, spot AS _BYTE, testNum AS _BYTE, rdir AS _BYTE\n DIM x AS _BYTE, y AS _BYTE, d AS _BYTE, dNum AS _BYTE, rdd AS _BYTE\n DIM template$, b1 AS _BIT, b2 AS _BIT\n DIM i AS _BYTE, j AS _BYTE, wate$\n\n wd$ = WORDS$(WORDSINDEX) 'the right side is all shared\n 'skip too many long words\n IF LengthLimit(LEN(wd$)) THEN LengthLimit(LEN(wd$)) = LengthLimit(LEN(wd$)) - 1 ELSE EXIT SUB 'skip long ones\n wLen = LEN(wd$) - 1 ' from the spot there are this many letters to check\n spot = INT(RND * 100) ' a random spot on grid\n testNum = 1 ' when this hits 100 we've tested all possible spots on grid\n IF RND < .5 THEN rdir = -1 ELSE rdir = 1 ' go forward or back from spot for next test\n WHILE testNum < 101\n y = INT(spot / 10)\n x = spot MOD 10\n IF L$(x, y) = MID$(wd$, 1, 1) OR L$(x, y) = \" \" THEN\n d = INT(8 * RND)\n IF RND < .5 THEN rdd = -1 ELSE rdd = 1\n dNum = 1\n WHILE dNum < 9\n 'will wd$ fit? from at x, y\n template$ = \"\"\n b1 = wLen * DX(d) + x >= 0 AND wLen * DX(d) + x <= 9\n b2 = wLen * DY(d) + y >= 0 AND wLen * DY(d) + y <= 9\n IF b1 AND b2 THEN 'build the template of letters and spaces from Letter grid\n FOR i = 0 TO wLen\n template$ = template$ + L$(x + i * DX(d), y + i * DY(d))\n NEXT\n IF Match%(wd$, template$) THEN 'the word will fit but does it fill anything?\n FOR j = 1 TO LEN(template$)\n IF ASC(template$, j) = 32 THEN 'yes a space to fill\n FOR i = 0 TO wLen\n L$(x + i * DX(d), y + i * DY(d)) = MID$(wd$, i + 1, 1)\n NEXT\n WI = WI + 1\n W$(WI) = wd$: WX(WI) = x: WY(WI) = y: WD(WI) = d\n IF CountSpaces% = 0 THEN FILLED = -1\n EXIT SUB 'get out now that word is loaded\n END IF\n NEXT\n 'if still here keep looking\n END IF\n END IF\n d = (d + 8 + rdd) MOD 8\n dNum = dNum + 1\n WEND\n END IF\n spot = (spot + 100 + rdir) MOD 100\n testNum = testNum + 1\n WEND\n END SUB\n\n SUB FindAllWords\n DIM wd$, wLen AS _BYTE, i AS INTEGER, x AS _BYTE, y AS _BYTE, d AS _BYTE\n DIM template$, b1 AS _BIT, b2 AS _BIT, j AS _BYTE, wate$\n\n FOR i = 1 TO NWORDS\n wd$ = CWORDS$(i)\n wLen = LEN(wd$) - 1\n FOR y = 0 TO 9\n FOR x = 0 TO 9\n IF L$(x, y) = MID$(wd$, 1, 1) THEN\n FOR d = 0 TO 7\n b1 = wLen * DX(d) + x >= 0 AND wLen * DX(d) + x <= 9\n b2 = wLen * DY(d) + y >= 0 AND wLen * DY(d) + y <= 9\n IF b1 AND b2 THEN 'build the template of letters and spaces from Letter grid\n template$ = \"\"\n FOR j = 0 TO wLen\n template$ = template$ + L$(x + j * DX(d), y + j * DY(d))\n NEXT\n IF template$ = wd$ THEN 'founda word\n 'store it\n ALLindex = ALLindex + 1\n ALL$(ALLindex) = wd$: AllX(ALLindex) = x: AllY(ALLindex) = y: AllD(ALLindex) = d\n 'report it\n LOCATE 22, 1: PRINT SPACE$(50)\n LOCATE 22, 1: PRINT \"Found: \"; wd$; \" (\"; Trm$(x); \", \"; Trm$(y); \") >>>---> \"; Trm$(d);\n INPUT \" Press enter...\", wate$\n END IF\n END IF\n NEXT d\n END IF\n NEXT x\n NEXT y\n NEXT i\n END SUB\n\n SUB FilePuzzle\n DIM i AS _BYTE, r AS _BYTE, c AS _BYTE, b$\n OPEN \"WS Puzzle.txt\" FOR OUTPUT AS #1\n PRINT #1, \" 0 1 2 3 4 5 6 7 8 9\"\n PRINT #1, \"\"\n FOR r = 0 TO 9\n b$ = Trm$(r) + \" \"\n FOR c = 0 TO 9\n b$ = b$ + L$(c, r) + \" \"\n NEXT\n PRINT #1, b$\n NEXT\n PRINT #1, \"\"\n PRINT #1, \"Directions >>>---> 0 = East, 1 = SE, 2 = South, 3 = SW, 4 = West, 5 = NW, 6 = North, 7 = NE\"\n PRINT #1, \"\"\n PRINT #1, \" These are the items from unixdict.txt used to build the puzzle:\"\n PRINT #1, \"\"\n FOR i = 1 TO WI STEP 2\n PRINT #1, RIGHT$(SPACE$(7) + Trm$(i), 7); \") \"; RIGHT$(SPACE$(7) + W$(i), 10); \" (\"; Trm$(WX(i)); \", \"; Trm$(WY(i)); \") >>>---> \"; Trm$(WD(i));\n IF i + 1 <= WI THEN\n PRINT #1, RIGHT$(SPACE$(7) + Trm$(i + 1), 7); \") \"; RIGHT$(SPACE$(7) + W$(i + 1), 10); \" (\"; Trm$(WX(i + 1)); \", \"; Trm$(WY(i + 1)); \") >>>---> \"; Trm$(WD(i + 1))\n ELSE\n PRINT #1, \"\"\n END IF\n NEXT\n PRINT #1, \"\"\n PRINT #1, \" These are the items from unixdict.txt found embedded in the puzzle:\"\n PRINT #1, \"\"\n FOR i = 1 TO ALLindex STEP 2\n PRINT #1, RIGHT$(SPACE$(7) + Trm$(i), 7); \") \"; RIGHT$(SPACE$(7) + ALL$(i), 10); \" (\"; Trm$(AllX(i)); \", \"; Trm$(AllY(i)); \") >>>---> \"; Trm$(AllD(i));\n IF i + 1 <= ALLindex THEN\n PRINT #1, RIGHT$(SPACE$(7) + Trm$(i + 1), 7); \") \"; RIGHT$(SPACE$(7) + ALL$(i + 1), 10); \" (\"; Trm$(AllX(i + 1)); \", \"; Trm$(AllY(i + 1)); \") >>>---> \"; Trm$(AllD(i + 1))\n ELSE\n PRINT #1, \"\"\n END IF\n NEXT\n CLOSE #1\n END SUB\n", "language": "QB64" }, { "code": "#lang racket\n;; ---------------------------------------------------------------------------------------------------\n(module+ main\n (display-puzzle (create-word-search))\n (newline)\n (parameterize ((current-min-words 50))\n (display-puzzle (create-word-search #:n-rows 20 #:n-cols 20))))\n\n;; ---------------------------------------------------------------------------------------------------\n(define current-min-words (make-parameter 25))\n\n;; ---------------------------------------------------------------------------------------------------\n(define (all-words pzl)\n (filter-map (good-word? pzl) (file->lines \"data/unixdict.txt\")))\n\n(define (good-word? pzl)\n (let ((m (puzzle-max-word-size pzl)))\n (λ (w) (and (<= 3 (string-length w) m) (regexp-match #px\"^[A-Za-z]*$\" w) (string-downcase w)))))\n\n(struct puzzle (n-rows n-cols cells solutions) #:transparent)\n\n(define puzzle-max-word-size (match-lambda [(puzzle n-rows n-cols _ _) (max n-rows n-cols)]))\n\n(define dirs '((-1 -1 ↖) (-1 0 ↑) (-1 1 ↗) (0 -1 ←) (0 1 →) (1 -1 ↙) (1 0 ↓) (1 1 ↘)))\n\n;; ---------------------------------------------------------------------------------------------------\n(define (display-puzzle pzl) (displayln (puzzle->string pzl)))\n\n(define (puzzle->string pzl)\n (match-let*\n (((and pzl (puzzle n-rows n-cols cells (and solutions (app length size)))) pzl)\n (column-numbers (cons \"\" (range n-cols)))\n (render-row (λ (r) (cons r (map (λ (c) (hash-ref cells (cons r c) #\\_)) (range n-cols)))))\n (the-grid (add-between (map (curry map (curry ~a #:width 3))\n (cons column-numbers (map render-row (range n-rows)))) \"\\n\"))\n (solutions§ (solutions->string (sort solutions string<? #:key car))))\n (string-join (flatten (list the-grid \"\\n\\n\" solutions§)) \"\")))\n\n(define (solutions->string solutions)\n (let* ((l1 (compose string-length car))\n (format-solution-to-max-word-size (format-solution (l1 (argmax l1 solutions)))))\n (let recur ((solutions solutions) (need-newline? #f) (acc null))\n (if (null? solutions)\n (reverse (if need-newline? (cons \"\\n\" acc) acc))\n (let* ((spacer (if need-newline? \"\\n\" \" \"))\n (solution (format \"~a~a\" (format-solution-to-max-word-size (car solutions)) spacer)))\n (recur (cdr solutions) (not need-newline?) (cons solution acc)))))))\n\n(define (format-solution max-word-size)\n (match-lambda [(list word row col dir)\n (string-append (~a word #:width (+ max-word-size 1))\n (~a (format \"(~a,~a ~a)\" row col dir) #:width 9))]))\n\n;; ---------------------------------------------------------------------------------------------------\n(define (create-word-search #:msg (msg \"Rosetta Code\") #:n-rows (n-rows 10) #:n-cols (n-cols 10))\n (let* ((pzl (puzzle n-rows n-cols (hash) null))\n (MSG (sanitise-message msg))\n (n-holes (- (* n-rows n-cols) (string-length MSG))))\n (place-message (place-words pzl (shuffle (all-words pzl)) (current-min-words) n-holes) MSG)))\n\n(define (sanitise-message msg) (regexp-replace* #rx\"[^A-Z]\" (string-upcase msg) \"\"))\n\n(define (place-words pzl words needed-words holes)\n (let inner ((pzl pzl) (words words) (needed-words needed-words) (holes holes))\n (cond [(and (not (positive? needed-words)) (zero? holes)) pzl]\n [(null? words)\n (eprintf \"no solution... retrying (~a words remaining)~%\" needed-words)\n (inner pzl (shuffle words) needed-words)]\n [else\n (let/ec no-fit\n (let*-values\n (([word words...] (values (car words) (cdr words)))\n ([solution cells′ holes′]\n (fit-word word pzl holes (λ () (no-fit (inner pzl words... needed-words holes)))))\n ([solutions′] (cons solution (puzzle-solutions pzl)))\n ([pzl′] (struct-copy puzzle pzl (solutions solutions′) (cells cells′))))\n (inner pzl′ words... (sub1 needed-words) holes′)))])))\n\n(define (fit-word word pzl holes fail)\n (match-let* (((puzzle n-rows n-cols cells _) pzl)\n (rows (shuffle (range n-rows)))\n (cols (shuffle (range n-cols)))\n (fits? (let ((l (string-length word))) (λ (maxz z0 dz) (< -1 (+ z0 (* dz l)) maxz)))))\n (let/ec return\n (for* ((dr-dc-↗ (shuffle dirs))\n (r0 rows) (dr (in-value (car dr-dc-↗))) #:when (fits? n-rows r0 dr)\n (c0 cols) (dc (in-value (cadr dr-dc-↗))) #:when (fits? n-cols c0 dc)\n (↗ (in-value (caddr dr-dc-↗))))\n (let/ec retry/ec (attempt-word-fit pzl word r0 c0 dr dc ↗ holes return retry/ec)))\n (fail))))\n\n(define (attempt-word-fit pzl word r0 c0 dr dc ↗ holes return retry)\n (let-values (([cells′ available-cells′]\n (for/fold ((cells′ (puzzle-cells pzl)) (holes′ holes))\n ((w word) (i (in-naturals)))\n (define k (cons (+ r0 (* dr i)) (+ c0 (* dc i))))\n (cond [(not (hash-has-key? cells′ k))\n (if (zero? holes′) (retry) (values (hash-set cells′ k w) (sub1 holes′)))]\n [(char=? (hash-ref cells′ k) w) (values cells′ holes′)]\n [else (retry)]))))\n (return (list word r0 c0 ↗) cells′ available-cells′)))\n\n;; ---------------------------------------------------------------------------------------------------\n(define (place-message pzl MSG)\n (match-define (puzzle n-rows n-cols cells _) pzl)\n (struct-copy puzzle pzl\n (cells\n (let loop ((r 0) (c 0) (cells cells) (msg (string->list MSG)))\n (cond [(or (null? msg) (= r n-rows)) cells]\n [(= c n-cols) (loop (add1 r) 0 cells msg)]\n [(hash-has-key? cells (cons r c)) (loop r (add1 c) cells msg)]\n [else (loop r (add1 c) (hash-set cells (cons r c) (car msg)) (cdr msg))])))))\n", "language": "Racket" }, { "code": "my $rows = 10;\nmy $cols = 10;\n\nmy $message = q:to/END/;\n .....R....\n ......O...\n .......S..\n ........E.\n T........T\n .A........\n ..C.......\n ...O......\n ....D.....\n .....E....\n END\n\nmy %dir =\n '→' => (1,0),\n '↘' => (1,1),\n '↓' => (0,1),\n '↙' => (-1,1),\n '←' => (-1,0),\n '↖' => (-1,-1),\n '↑' => (0,-1),\n '↗' => (1,-1)\n;\n\nmy @ws = $message.comb(/<print>/);\n\nmy $path = './unixdict.txt'; # or wherever\n\nmy @words = $path.IO.slurp.words.grep( { $_ !~~ /<-[a..z]>/ and 2 < .chars < 11 } ).pick(*);\nmy %index;\nmy %used;\n\nwhile @ws.first( * eq '.') {\n\n # find an unfilled cell\n my $i = @ws.grep( * eq '.', :k ).pick;\n\n # translate the index to x / y coordinates\n my ($x, $y) = $i % $cols, floor($i / $rows);\n\n # find a word that fits\n my $word = find($x, $y);\n\n # Meh, reached an impasse, easier to just throw it all\n # away and start over rather than trying to backtrack.\n restart, next unless $word;\n\n %used{\"$word\"}++;\n\n # Keeps trying to place an already used word, choices\n # must be limited, start over\n restart, next if %used{$word} > 15;\n\n # Already used this word, try again\n next if %index{$word.key};\n\n # Add word to used word index\n %index ,= $word;\n\n # place the word into the grid\n place($x, $y, $word);\n\n}\n\ndisplay();\n\nsub display {\n put flat \" \", 'ABCDEFGHIJ'.comb;\n .put for (^10).map: { ($_).fmt(\" %2d\"), @ws[$_ * $cols .. ($_ + 1) * $cols - 1] }\n put \"\\n Words used:\";\n my $max = 1 + %index.keys.max( *.chars ).chars;\n for %index.sort {\n printf \"%{$max}s %4s %s \", .key, .value.key, .value.value;\n print \"\\n\" if $++ % 2;\n }\n say \"\\n\"\n}\n\nsub restart {\n @ws = $message.comb(/<print>/);\n %index = ();\n %used = ();\n}\n\nsub place ($x is copy, $y is copy, $w) {\n my @word = $w.key.comb;\n my $dir = %dir{$w.value.value};\n @ws[$y * $rows + $x] = @word.shift;\n while @word {\n ($x, $y) »+=« $dir;\n @ws[$y * $rows + $x] = @word.shift;\n }\n }\n\nsub find ($x, $y) {\n my @trials = %dir.keys.map: -> $dir {\n my $space = '.';\n my ($c, $r) = $x, $y;\n loop {\n ($c, $r) »+=« %dir{$dir};\n last if 9 < $r|$c;\n last if 0 > $r|$c;\n my $l = @ws[$r * $rows + $c];\n last if $l ~~ /<:Lu>/;\n $space ~= $l;\n }\n next if $space.chars < 3;\n [$space.trans( '.' => ' ' ),\n (\"{'ABCDEFGHIJ'.comb[$x]} {$y}\" => $dir)]\n };\n\n for @words.pick(*) -> $word {\n for @trials -> $space {\n next if $word.chars > $space[0].chars;\n return ($word => $space[1]) if compare($space[0].comb, $word.comb)\n }\n }\n}\n\nsub compare (@s, @w) {\n for ^@w {\n next if @s[$_] eq ' ';\n return False if @s[$_] ne @w[$_]\n }\n True\n}\n", "language": "Raku" }, { "code": "Module Module1\n\n ReadOnly Dirs As Integer(,) = {\n {1, 0}, {0, 1}, {1, 1},\n {1, -1}, {-1, 0},\n {0, -1}, {-1, -1}, {-1, 1}\n }\n\n Const RowCount = 10\n Const ColCount = 10\n Const GridSize = RowCount * ColCount\n Const MinWords = 25\n\n Class Grid\n Public cells(RowCount - 1, ColCount - 1) As Char\n Public solutions As New List(Of String)\n Public numAttempts As Integer\n\n Sub New()\n For i = 0 To RowCount - 1\n For j = 0 To ColCount - 1\n cells(i, j) = ControlChars.NullChar\n Next\n Next\n End Sub\n End Class\n\n Dim Rand As New Random()\n\n Sub Main()\n PrintResult(CreateWordSearch(ReadWords(\"unixdict.txt\")))\n End Sub\n\n Function ReadWords(filename As String) As List(Of String)\n Dim maxlen = Math.Max(RowCount, ColCount)\n Dim words As New List(Of String)\n\n Dim objReader As New IO.StreamReader(filename)\n Dim line As String\n Do While objReader.Peek() <> -1\n line = objReader.ReadLine()\n If line.Length > 3 And line.Length < maxlen Then\n If line.All(Function(c) Char.IsLetter(c)) Then\n words.Add(line)\n End If\n End If\n Loop\n\n Return words\n End Function\n\n Function CreateWordSearch(words As List(Of String)) As Grid\n For numAttempts = 1 To 1000\n Shuffle(words)\n\n Dim grid As New Grid()\n Dim messageLen = PlaceMessage(grid, \"Rosetta Code\")\n Dim target = GridSize - messageLen\n\n Dim cellsFilled = 0\n For Each word In words\n cellsFilled = cellsFilled + TryPlaceWord(grid, word)\n If cellsFilled = target Then\n If grid.solutions.Count >= MinWords Then\n grid.numAttempts = numAttempts\n Return grid\n Else\n 'grid is full but we didn't pack enough words, start over\n Exit For\n End If\n End If\n Next\n Next\n\n Return Nothing\n End Function\n\n Function PlaceMessage(grid As Grid, msg As String) As Integer\n msg = msg.ToUpper()\n msg = msg.Replace(\" \", \"\")\n\n If msg.Length > 0 And msg.Length < GridSize Then\n Dim gapSize As Integer = GridSize / msg.Length\n\n Dim pos = 0\n Dim lastPos = -1\n For i = 0 To msg.Length - 1\n If i = 0 Then\n pos = pos + Rand.Next(gapSize - 1)\n Else\n pos = pos + Rand.Next(2, gapSize - 1)\n End If\n Dim r As Integer = Math.Floor(pos / ColCount)\n Dim c = pos Mod ColCount\n\n grid.cells(r, c) = msg(i)\n\n lastPos = pos\n Next\n Return msg.Length\n End If\n\n Return 0\n End Function\n\n Function TryPlaceWord(grid As Grid, word As String) As Integer\n Dim randDir = Rand.Next(Dirs.GetLength(0))\n Dim randPos = Rand.Next(GridSize)\n\n For d = 0 To Dirs.GetLength(0) - 1\n Dim dd = (d + randDir) Mod Dirs.GetLength(0)\n\n For p = 0 To GridSize - 1\n Dim pp = (p + randPos) Mod GridSize\n\n Dim lettersPLaced = TryLocation(grid, word, dd, pp)\n If lettersPLaced > 0 Then\n Return lettersPLaced\n End If\n Next\n Next\n\n Return 0\n End Function\n\n Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer\n Dim r As Integer = pos / ColCount\n Dim c = pos Mod ColCount\n Dim len = word.Length\n\n 'check bounds\n If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then\n Return 0\n End If\n If r = RowCount OrElse c = ColCount Then\n Return 0\n End If\n\n Dim rr = r\n Dim cc = c\n\n 'check cells\n For i = 0 To len - 1\n If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then\n Return 0\n End If\n\n cc = cc + Dirs(dir, 0)\n rr = rr + Dirs(dir, 1)\n Next\n\n 'place\n Dim overlaps = 0\n rr = r\n cc = c\n For i = 0 To len - 1\n If grid.cells(rr, cc) = word(i) Then\n overlaps = overlaps + 1\n Else\n grid.cells(rr, cc) = word(i)\n End If\n\n If i < len - 1 Then\n cc = cc + Dirs(dir, 0)\n rr = rr + Dirs(dir, 1)\n End If\n Next\n\n Dim lettersPlaced = len - overlaps\n If lettersPlaced > 0 Then\n grid.solutions.Add(String.Format(\"{0,-10} ({1},{2})({3},{4})\", word, c, r, cc, rr))\n End If\n\n Return lettersPlaced\n End Function\n\n Sub PrintResult(grid As Grid)\n If IsNothing(grid) OrElse grid.numAttempts = 0 Then\n Console.WriteLine(\"No grid to display\")\n Return\n End If\n\n Console.WriteLine(\"Attempts: {0}\", grid.numAttempts)\n Console.WriteLine(\"Number of words: {0}\", GridSize)\n Console.WriteLine()\n\n Console.WriteLine(\" 0 1 2 3 4 5 6 7 8 9\")\n For r = 0 To RowCount - 1\n Console.WriteLine()\n Console.Write(\"{0} \", r)\n For c = 0 To ColCount - 1\n Console.Write(\" {0} \", grid.cells(r, c))\n Next\n Next\n\n Console.WriteLine()\n Console.WriteLine()\n\n For i = 0 To grid.solutions.Count - 1\n If i Mod 2 = 0 Then\n Console.Write(\"{0}\", grid.solutions(i))\n Else\n Console.WriteLine(\" {0}\", grid.solutions(i))\n End If\n Next\n\n Console.WriteLine()\n End Sub\n\n 'taken from https://stackoverflow.com/a/20449161\n Sub Shuffle(Of T)(list As IList(Of T))\n Dim r As Random = New Random()\n For i = 0 To list.Count - 1\n Dim index As Integer = r.Next(i, list.Count)\n If i <> index Then\n ' swap list(i) and list(index)\n Dim temp As T = list(i)\n list(i) = list(index)\n list(index) = temp\n End If\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"random\" for Random\nimport \"./ioutil\" for FileUtil\nimport \"./pattern\" for Pattern\nimport \"./str\" for Str\nimport \"./fmt\" for Fmt\n\nvar dirs = [ [1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1] ]\nvar Rows = 10\nvar Cols = 10\nvar gridSize = Rows * Cols\nvar minWords = 25\nvar rand = Random.new()\n\nclass Grid {\n construct new() {\n _numAttempts = 0\n _cells = List.filled(Rows, null)\n for (i in 0...Rows) _cells[i] = List.filled(Cols, \" \")\n _solutions = []\n }\n\n numAttempts { _numAttempts }\n numAttempts=(n) { _numAttempts = n }\n cells { _cells }\n solutions { _solutions }\n}\n\nvar readWords = Fn.new { |fileName|\n var maxLen = Rows.max(Cols)\n var p = Pattern.new(\"=3/l#0%(maxLen-3)/l\", Pattern.whole)\n return FileUtil.readLines(fileName)\n .map { |l| Str.lower(l.trim()) }\n .where { |l| p.isMatch(l) }.toList\n}\n\nvar placeMessage = Fn.new { |grid, msg|\n var p = Pattern.new(\"/U\")\n var msg2 = p.replaceAll(Str.upper(msg), \"\")\n var messageLen = msg2.count\n if (messageLen >= 1 && messageLen < gridSize) {\n var gapSize = (gridSize / messageLen).floor\n for (i in 0...messageLen) {\n var pos = i * gapSize + rand.int(gapSize)\n grid.cells[(pos / Cols).floor][pos % Cols] = msg2[i]\n }\n return messageLen\n }\n return 0\n}\n\nvar tryLocation = Fn.new { |grid, word, dir, pos|\n var r = (pos / Cols).floor\n var c = pos % Cols\n var len = word.count\n\n // check bounds\n if ((dirs[dir][0] == 1 && (len + c) > Cols) ||\n (dirs[dir][0] == -1 && (len - 1) > c) ||\n (dirs[dir][1] == 1 && (len + r) > Rows) ||\n (dirs[dir][1] == -1 && (len - 1) > r)) return 0\n var overlaps = 0\n\n // check cells\n var rr = r\n var cc = c\n for (i in 0...len) {\n if (grid.cells[rr][cc] != \" \" && grid.cells[rr][cc] != word[i]) return 0\n cc = cc + dirs[dir][0]\n rr = rr + dirs[dir][1]\n }\n\n // place\n rr = r\n cc = c\n for (i in 0...len) {\n if (grid.cells[rr][cc] == word[i]) {\n overlaps = overlaps + 1\n } else {\n grid.cells[rr][cc] = word[i]\n }\n if (i < len - 1) {\n cc = cc + dirs[dir][0]\n rr = rr + dirs[dir][1]\n }\n }\n\n var lettersPlaced = len - overlaps\n if (lettersPlaced > 0) {\n grid.solutions.add(Fmt.swrite(\"$-10s ($d,$d)($d,$d)\", word, c, r, cc, rr))\n }\n return lettersPlaced\n}\n\nvar tryPlaceWord = Fn.new { |grid, word|\n var randDir = rand.int(dirs.count)\n var randPos = rand.int(gridSize)\n for (d in 0...dirs.count) {\n var dir = (d + randDir) % dirs.count\n for (p in 0...gridSize) {\n var pos = (p + randPos) % gridSize\n var lettersPlaced = tryLocation.call(grid, word, dir, pos)\n if (lettersPlaced > 0) return lettersPlaced\n }\n }\n return 0\n}\n\nvar createWordSearch = Fn.new { |words|\n var numAttempts = 1\n var grid\n while (numAttempts < 100) {\n var outer = false\n grid = Grid.new()\n var messageLen = placeMessage.call(grid, \"Rosetta Code\")\n var target = gridSize - messageLen\n var cellsFilled = 0\n rand.shuffle(words)\n for (word in words) {\n cellsFilled = cellsFilled + tryPlaceWord.call(grid, word)\n if (cellsFilled == target) {\n if (grid.solutions.count >= minWords) {\n grid.numAttempts = numAttempts\n outer = true\n break\n }\n // grid is full but we didn't pack enough words, start over\n break\n }\n }\n if (outer) break\n numAttempts = numAttempts + 1\n }\n return grid\n}\n\nvar printResult = Fn.new { |grid|\n if (grid.numAttempts == 0) {\n System.print(\"No grid to display\")\n return\n }\n var size = grid.solutions.count\n System.print(\"Attempts: %(grid.numAttempts)\")\n System.print(\"Number of words: %(size)\")\n System.print(\"\\n 0 1 2 3 4 5 6 7 8 9\")\n for (r in 0...Rows) {\n System.write(\"\\n%(r) \")\n for (c in 0...Cols) System.write(\" %(grid.cells[r][c]) \")\n }\n System.print(\"\\n\")\n var i = 0\n while (i < size - 1) {\n System.print(\"%(grid.solutions[i]) %(grid.solutions[i + 1])\")\n i = i + 2\n }\n if (size % 2 == 1) System.print(grid.solutions[size - 1])\n}\n\nprintResult.call(createWordSearch.call(readWords.call(\"unixdict.txt\")))\n", "language": "Wren" }, { "code": "fcn buildVectors(R,C){ //-->up to 8 vectors of wild card strings\n var [const] dirs=T(T(1,0), T(0,1), T(1,1), T(1,-1), T(-1,0),T(0,-1), T(-1,-1), T(-1,1));\n vs,v:=List(),List();\n foreach dr,dc in (dirs){ v.clear(); r,c:=R,C;\n while( (0<=r<10) and (0<=c<10) ){ v.append(grid[r][c]); r+=dr; c+=dc; }\n vs.append(T(v.concat(), // eg \"???e??????\" would match \"cohen\" or \"mineral\"\n \tdr,dc));\n }\n vs.filter(fcn(v){ v[0].len()>2 }).shuffle()\n}\nfcn findFit(vs,words){ //-->(n, word) ie (nth vector,word), empty vs not seen\n do(1000){ foreach n,v in (vs.enumerate()){ do(10){ // lots of ties\n word:=words[(0).random(nwds)];\n if(word.matches(v[0][0,word.len()])) return(word,n); // \"??\" !match \"abc\"\n }}}\n False\n}\nfcn pasteWord(r,c, dr,dc, word) // jam word into grid along vector\n { foreach char in (word){ grid[r][c]=char; r+=dr; c+=dc; } }\nfcn printGrid{\n println(\"\\n 0 1 2 3 4 5 6 7 8 9\");\n foreach n,line in (grid.enumerate()){ println(n,\" \",line.concat(\" \")) }\n}\nfcn stuff(msg){ MSG:=msg.toUpper() : Utils.Helpers.cycle(_);\n foreach r,c in (10,10){ if(grid[r][c]==\"?\") grid[r][c]=MSG.next() }\n MSG._n==msg.len() // use all of, not more, not less, of msg?\n}\n", "language": "Zkl" }, { "code": "msg:=\"RosettaCode\";\n\nvalidWord:=RegExp(\"[A-Za-z]+\\n$\").matches;\nFile(\"unixdict.txt\").read(*) // dictionary file to blob, copied from web\n // blob to list of valid words\n .filter('wrap(w){ (3<w.len()<=10) and validWord(w) }) // \"word\\n\"\n .howza(11).pump(List,\"toLower\") // convert blob to list of words, removing \\n\n : words:=(_);\n\nreg fitted; do{\n var nwds=words.len(), grid=(10).pump(List(),(10).pump(List(),\"?\".copy).copy);\n fitted=List(); do(100){\n r,c:=(0).random(10), (0).random(10);\n if(grid[r][c]==\"?\"){\n\t vs,wn:=buildVectors(r,c), findFit(vs,words);\n\t if(wn){\n\t w,n:=wn; pasteWord(r,c,vs[n][1,*].xplode(),w);\n\t fitted.append(T(r,c,w));\n\t }\n }}\n print(\".\");\n}while(fitted.len()<25 or not stuff(msg));\n\nprintGrid();\nprintln(fitted.len(),\" words fitted\");\nfitted.pump(Console.println, T(Void.Read,3,False),\n fcn{ vm.arglist.pump(String,\n fcn([(r,c,w)]){ \"%-19s\".fmt(\"[%d,%d]: %s \".fmt(r,c,w)) }) }\n);\nfitted.apply(fcn(w){ w[2].len() }).sum(0).println();\n", "language": "Zkl" } ]
Word-search
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Word_wheel\nnote: Puzzles\n", "language": "00-META" }, { "code": "A \"word wheel\" is a type of word game commonly found on the \"puzzle\" page of\nnewspapers. You are presented with nine letters arranged in a circle or 3&times;3\ngrid. The objective is to find as many words as you can using only the letters\ncontained in the wheel or grid. Each word must contain the letter in the centre\nof the wheel or grid. Usually there will be a minimum word length of 3 or 4\ncharacters. Each letter may only be used as many times as it appears in the wheel\nor grid.\n\n\n;An example: <big><b>\n::::::: {| class=\"wikitable\"\n| N\n| D\n| E\n|-\n| O\n| style=\"font-weight: bold;\"| K\n| G\n|-\n| E\n| L\n| W\n|} \n</b></big>\n\n;Task:\nWrite a program to solve the above \"word wheel\" puzzle.\n\nSpecifically:\n:* Find all words of 3 or more letters using only the letters in the string &nbsp; '''ndeokgelw'''.\n:* All words must contain the central letter &nbsp; <big>'''K'''.</big>\n:* Each letter may be used only as many times as it appears in the string.\n:* For this task we'll use lowercase English letters exclusively.\n\n\nA \"word\" is defined to be any string contained in the file located at &nbsp; http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. \n<br>If you prefer to use a different dictionary, &nbsp; please state which one you have used.\n\n;Optional extra:\nWord wheel puzzles usually state that there is at least one nine-letter word to be found.\nUsing the above dictionary, find the 3x3 grids with at least one nine-letter\nsolution that generate the largest number of words of three or more letters.\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V GRID =\n‘N D E\n O K G\n E L W’\n\nF getwords()\n V words = File(‘unixdict.txt’).read().lowercase().split(\"\\n\")\n R words.filter(w -> w.len C 3..9)\n\nF solve(grid, dictionary)\n DefaultDict[Char, Int] gridcount\n L(g) grid\n gridcount[g]++\n\n F check_word(word)\n DefaultDict[Char, Int] lcount\n L(l) word\n lcount[l]++\n L(l, c) lcount\n I c > @gridcount[l]\n R 1B\n R 0B\n\n V mid = grid[4]\n R dictionary.filter(word -> @mid C word & !@check_word(word))\n\nV chars = GRID.lowercase().split_py().join(‘’)\nV found = solve(chars, dictionary' getwords())\nprint(found.join(\"\\n\"))\n", "language": "11l" }, { "code": "puts:\tequ\t9\t\t; CP/M syscall to print string\nfopen:\tequ\t15\t\t; CP/M syscall to open a file\nfread:\tequ\t20\t\t; CP/M syscall to read from file\nFCB1:\tequ\t5Ch\t\t; First FCB (input file)\nDTA:\tequ\t80h\t\t; Disk transfer address\n\torg\t100h\n\t;;;\tMake wheel (2nd argument) lowercase and store it\n\tlxi\td,DTA+1\t\t; Start of command line arguments\nscan:\tinr\te\t\t; Scan until we find a space\n\trz\t\t\t; Stop if not found in 128 bytes\n\tldax\td\n\tcpi\t' '\t\t; Found it?\n\tjnz\tscan\t\t; If not, try again\n\tinx\td\t\t; If so, wheel starts 1 byte onwards\n\tlxi\th,wheel\t\t; Space for wheel\n\tlxi\tb,920h\t\t; B=9 (chars), C=20 (case bit)\nwhlcpy:\tldax\td\t\t; Get wheel character\n\tora\tc\t\t; Make lowercase\n\tmov\tm,a\t\t; Store\n\tinx\td\t\t; Increment both pointers\n\tinx\th\n\tdcr\tb\t\t; Decrement counter\n\tjnz\twhlcpy\t\t; While not zero, copy next character\n\t;;;\tOpen file in FCB1\n\tmvi\te,FCB1\t\t; D is already 0\n\tmvi\tc,fopen\n\tcall\t5\t\t; Returns A=FF on error\n\tinr\ta\t\t; If incrementing A gives zero,\n\tjz\terr\t\t; then print error and stop\n\tlxi\th,word\t\t; Copy into word\n\t;;;\tRead a 128-byte block from the file\nblock:\tpush\th\t\t; Keep word pointer\n\tlxi\td,FCB1\t\t; Read from file\n\tmvi\tc,fread\n\tcall\t5\n\tpop\th\t\t; Restore word pointer\n\tdcr\ta\t\t; A=1 = EOF\n\trz\t\t\t; If so, stop.\n\tinr\ta\t\t; Otherwise, A<>0 = error\n\tjnz\terr\n\tlxi\td,DTA\t\t; Start reading at DTA\nchar:\tldax\td\t\t; Get character\n\tmov\tm,a\t\t; Store in word\n\tcpi\t26\t\t; EOF reached?\n\trz\t\t\t; Then stop\n\tcpi\t10\t\t; End of line reached?\n\tjz\tckword\t\t; Then we have a full word\n\tinx\th\t\t; Increment word pointer\nnxchar:\tinr\te\t\t; Increment DTA pointer (low byte)\n\tjz\tblock\t\t; If rollover, get next block\n\tjmp\tchar\t\t; Otherwise, handle next character in block\n\t;;;\tCheck if current word is valid\nckword:\tpush\td\t\t; Keep block pointer\n\tlxi\td,wheel\t\t; Copy the wheel\n\tlxi\th,wcpy\n\tmvi\tc,9\t\t; 9 characters\ncpyw:\tldax\td\t\t; Get character\n\tmov\tm,a\t\t; Store in copy\n\tinx\th\t\t; Increment pointers\n\tinx\td\n\tdcr\tc\t\t; Decrement counters\n\tjnz\tcpyw\t\t; Done yet?\n\tlxi\td,word\t\t; Read from current word\nwrdch:\tldax\td\t\t; Get character\n\tcpi\t32\t\t; Check if <32\n\tjc\twdone\t\t; If so, the word is done\n\tlxi\th,wcpy\t\t; Check against the wheel letters\n\tmvi\tb,9\nwlch:\tcmp\tm\t\t; Did we find it?\n\tjz\tfindch\n\tinx\th\t\t; If not, try next character in wheel\n\tdcr\tb\t\t; As long as there are characters\n\tjnz\twlch\t\t; If no match, this word is invalid\nwnext:\tpop\td\t\t; Restore block pointer\n\tlxi\th,word\t\t; Start reading new word\n\tjmp\tnxchar\t\t; Continue with character following word\nfindch:\tmvi\tm,0\t\t; Found a match - set char to 0\n\tinx\td\t\t; And look at next character in word\n\tjmp\twrdch\nwdone:\tlda\twcpy+4\t\t; Word is done - check if middle char used\n\tana\ta\t\t; If not, the word is invalid\n\tjnz\twnext\n\tlxi\th,wcpy\t\t; See how many characters used\n\tlxi\tb,9\t\t; C=9 (counter), B=0 (used)\nwhtest:\tmov\ta,m\t\t; Get wheel character\n\tana\ta\t\t; Is it zero?\n\tjnz\t$+4\t\t; If not, skip next instr\n\tinr\tb\t\t; If so, count it\n\tinx\th\t\t; Next wheel character\n\tdcr\tc\t\t; Decrement counter\n\tjnz\twhtest\n\tmvi\ta,2\t\t; At least 3 characters must be used\n\tcmp\tb\n\tjnc\twnext\t\t; If not, the word is invalid\n\txchg\t\t\t; If so, the word _is_ valid, pointer in HL\n\tmvi\tm,13\t\t; add CR\n\tinx\th\n\tmvi\tm,10\t\t; and LF\n\tinx\th\n\tmvi\tm,'$'\t\t; and the CP/M string terminator\n\tlxi\td,word\t\t; Then print the word\n\tmvi\tc,puts\n\tcall\t5\n\tjmp\twnext\nerr:\tlxi\td,errs\t\t; Print file error\n\tmvi\tc,puts\n\tjz\t5\nerrs:\tdb\t'File error$'\t; Error message\nwheel:\tds\t9\t\t; Room for wheel\nwcpy:\tds\t9\t\t; Copy of wheel (to mark characters used)\nword:\tequ\t$\t\t; Room for current word\n", "language": "8080-Assembly" }, { "code": "wordwheel←{\n words←((~∊)∘⎕TC⊆⊢) 80 ¯1⎕MAP ⍵\n match←{\n 0=≢⍵:1\n ~(⊃⍵)∊⍺:0\n ⍺[(⍳⍴⍺)~⍺⍳⊃⍵]∇1↓⍵\n }\n middle←(⌈0.5×≢)⊃⊢\n words←((middle ⍺)∊¨words)/words\n words←(⍺∘match¨words)/words\n (⍺⍺≤≢¨words)/words\n}\n", "language": "APL" }, { "code": "use AppleScript version \"2.4\"\nuse framework \"Foundation\"\nuse scripting additions\n\n\n------------------------ WORD WHEEL ----------------------\n\n-- wordWheelMatches :: NSString -> [String] -> String -> String\non wordWheelMatches(lexicon, wordWheelRows)\n\n set wheelGroups to group(sort(characters of ¬\n concat(wordWheelRows)))\n\n script isWheelWord\n on |λ|(w)\n script available\n on |λ|(a, b)\n length of a ≤ length of b\n end |λ|\n end script\n\n script used\n on |λ|(grp)\n w contains item 1 of grp\n end |λ|\n end script\n\n all(my identity, ¬\n zipWith(available, ¬\n group(sort(characters of w)), ¬\n filter(used, wheelGroups)))\n end |λ|\n end script\n\n set matches to filter(isWheelWord, ¬\n filteredLines(wordWheelPreFilter(wordWheelRows), lexicon))\n\n (length of matches as text) & \" matches:\" & ¬\n linefeed & linefeed & unlines(matches)\nend wordWheelMatches\n\n\n-- wordWheelPreFilter :: [String] -> String\non wordWheelPreFilter(wordWheelRows)\n set pivot to item 2 of item 2 of wordWheelRows\n set charSet to nub(concat(wordWheelRows))\n\n \"(2 < self.length) and (self contains '\" & pivot & \"') \" & ¬\n \"and not (self matches '^.*[^\" & charSet & \"].*$') \"\nend wordWheelPreFilter\n\n\n--------------------------- TEST -------------------------\non run\n set fpWordList to scriptFolder() & \"unixdict.txt\"\n if doesFileExist(fpWordList) then\n\n wordWheelMatches(readFile(fpWordList), ¬\n {\"nde\", \"okg\", \"elw\"})\n\n else\n display dialog \"Word list not found in script folder:\" & ¬\n linefeed & tab & fpWordList\n end if\nend run\n\n\n\n----------- GENERIC :: FILTERED LINES FROM FILE ----------\n\n-- doesFileExist :: FilePath -> IO Bool\non doesFileExist(strPath)\n set ca to current application\n set oPath to (ca's NSString's stringWithString:strPath)'s ¬\n stringByStandardizingPath\n set {bln, int} to (ca's NSFileManager's defaultManager's ¬\n fileExistsAtPath:oPath isDirectory:(reference))\n bln and (int ≠ 1)\nend doesFileExist\n\n\n-- filteredLines :: String -> NString -> [a]\non filteredLines(predicateString, s)\n -- A list of lines filtered by an NSPredicate string\n set ca to current application\n\n set predicate to ca's NSPredicate's predicateWithFormat:predicateString\n set array to ca's NSArray's ¬\n arrayWithArray:(s's componentsSeparatedByString:(linefeed))\n\n (array's filteredArrayUsingPredicate:(predicate)) as list\nend filteredLines\n\n\n-- readFile :: FilePath -> IO NSString\non readFile(strPath)\n set ca to current application\n set e to reference\n set {s, e} to (ca's NSString's ¬\n stringWithContentsOfFile:((ca's NSString's ¬\n stringWithString:strPath)'s ¬\n stringByStandardizingPath) ¬\n encoding:(ca's NSUTF8StringEncoding) |error|:(e))\n if missing value is e then\n s\n else\n (localizedDescription of e) as string\n end if\nend readFile\n\n\n-- scriptFolder :: () -> IO FilePath\non scriptFolder()\n -- The path of the folder containing this script\n try\n tell application \"Finder\" to ¬\n POSIX path of ((container of (path to me)) as alias)\n on error\n display dialog \"Script file must be saved\"\n end try\nend scriptFolder\n\n\n------------------------- GENERIC ------------------------\n\n-- Tuple (,) :: a -> b -> (a, b)\non Tuple(a, b)\n -- Constructor for a pair of values,\n -- possibly of two different types.\n {type:\"Tuple\", |1|:a, |2|:b, length:2}\nend Tuple\n\n\n-- all :: (a -> Bool) -> [a] -> Bool\non all(p, xs)\n -- True if p holds for every value in xs\n tell mReturn(p)\n set lng to length of xs\n repeat with i from 1 to lng\n if not |λ|(item i of xs, i, xs) then return false\n end repeat\n true\n end tell\nend all\n\n\n-- concat :: [[a]] -> [a]\n-- concat :: [String] -> String\non concat(xs)\n set lng to length of xs\n if 0 < lng and string is class of (item 1 of xs) then\n set acc to \"\"\n else\n set acc to {}\n end if\n repeat with i from 1 to lng\n set acc to acc & item i of xs\n end repeat\n acc\nend concat\n\n\n-- eq (==) :: Eq a => a -> a -> Bool\non eq(a, b)\n a = b\nend eq\n\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(p, xs)\n tell mReturn(p)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n if {text, string} contains class of xs then\n lst as text\n else\n lst\n end if\n end tell\nend filter\n\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n\n-- group :: Eq a => [a] -> [[a]]\non group(xs)\n script eq\n on |λ|(a, b)\n a = b\n end |λ|\n end script\n\n groupBy(eq, xs)\nend group\n\n\n-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]\non groupBy(f, xs)\n -- Typical usage: groupBy(on(eq, f), xs)\n set mf to mReturn(f)\n\n script enGroup\n on |λ|(a, x)\n if length of (active of a) > 0 then\n set h to item 1 of active of a\n else\n set h to missing value\n end if\n\n if h is not missing value and mf's |λ|(h, x) then\n {active:(active of a) & {x}, sofar:sofar of a}\n else\n {active:{x}, sofar:(sofar of a) & {active of a}}\n end if\n end |λ|\n end script\n\n if length of xs > 0 then\n set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs)\n if length of (active of dct) > 0 then\n sofar of dct & {active of dct}\n else\n sofar of dct\n end if\n else\n {}\n end if\nend groupBy\n\n\n-- identity :: a -> a\non identity(x)\n -- The argument unchanged.\n x\nend identity\n\n\n-- length :: [a] -> Int\non |length|(xs)\n set c to class of xs\n if list is c or string is c then\n length of xs\n else\n (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)\n end if\nend |length|\n\n\n-- min :: Ord a => a -> a -> a\non min(x, y)\n if y < x then\n y\n else\n x\n end if\nend min\n\n\n-- mReturn :: First-class m => (a -> b) -> m (a -> b)\non mReturn(f)\n -- 2nd class handler function\n -- lifted into 1st class script wrapper.\n if script is class of f then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n -- The list obtained by applying f\n -- to each element of xs.\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n\n-- nub :: [a] -> [a]\non nub(xs)\n nubBy(eq, xs)\nend nub\n\n\n-- nubBy :: (a -> a -> Bool) -> [a] -> [a]\non nubBy(f, xs)\n set g to mReturn(f)'s |λ|\n\n script notEq\n property fEq : g\n on |λ|(a)\n script\n on |λ|(b)\n not fEq(a, b)\n end |λ|\n end script\n end |λ|\n end script\n\n script go\n on |λ|(xs)\n if (length of xs) > 1 then\n set x to item 1 of xs\n {x} & go's |λ|(filter(notEq's |λ|(x), items 2 thru -1 of xs))\n else\n xs\n end if\n end |λ|\n end script\n\n go's |λ|(xs)\nend nubBy\n\n\n\n-- sort :: Ord a => [a] -> [a]\non sort(xs)\n ((current application's NSArray's arrayWithArray:xs)'s ¬\n sortedArrayUsingSelector:\"compare:\") as list\nend sort\n\n\n-- take :: Int -> [a] -> [a]\n-- take :: Int -> String -> String\non take(n, xs)\n if 0 < n then\n items 1 thru min(n, length of xs) of xs\n else\n {}\n end if\nend take\n\n\n-- unlines :: [String] -> String\non unlines(xs)\n -- A single string formed by the intercalation\n -- of a list of strings with the newline character.\n set {dlm, my text item delimiters} to ¬\n {my text item delimiters, linefeed}\n set s to xs as text\n set my text item delimiters to dlm\n s\nend unlines\n\n\n-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\non zipWith(f, xs, ys)\n set lng to min(|length|(xs), |length|(ys))\n if 1 > lng then return {}\n set xs_ to take(lng, xs) -- Allow for non-finite\n set ys_ to take(lng, ys) -- generators like cycle etc\n set lst to {}\n tell mReturn(f)\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs_, item i of ys_)\n end repeat\n return lst\n end tell\nend zipWith\n", "language": "AppleScript" }, { "code": "letters := [\"N\", \"D\", \"E\", \"O\", \"K\", \"G\", \"E\", \"L\", \"W\"]\n\nFileRead, wList, % A_Desktop \"\\unixdict.txt\"\nresult := \"\"\nfor word in Word_wheel(wList, letters, 3)\n result .= word \"`n\"\nMsgBox % result\nreturn\n\nWord_wheel(wList, letters, minL){\n oRes := []\n for i, w in StrSplit(wList, \"`n\", \"`r\")\n {\n if (StrLen(w) < minL)\n continue\n word := w\n for i, l in letters\n w := StrReplace(w, l,,, 1)\n if InStr(word, letters[5]) && !StrLen(w)\n oRes[word] := true\n }\n return oRes\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f WORD_WHEEL.AWK letters unixdict.txt\n# the required letter must be first\n#\n# example: GAWK -f WORD_WHEEL.AWK Kndeogelw unixdict.txt\n#\nBEGIN {\n letters = tolower(ARGV[1])\n required = substr(letters,1,1)\n size = 3\n ARGV[1] = \"\"\n}\n{ word = tolower($0)\n leng_word = length(word)\n if (word ~ required && leng_word >= size) {\n hits = 0\n for (i=1; i<=leng_word; i++) {\n if (letters ~ substr(word,i,1)) {\n hits++\n }\n }\n if (leng_word == hits && hits >= size) {\n for (i=1; i<=leng_word; i++) {\n c = substr(word,i,1)\n if (gsub(c,\"&\",word) > gsub(c,\"&\",letters)) {\n next\n }\n }\n words++\n printf(\"%s \",word)\n }\n }\n}\nEND {\n printf(\"\\nletters: %s, '%s' required, %d words >= %d characters\\n\",letters,required,words,size)\n exit(0)\n}\n", "language": "AWK" }, { "code": "10 DEFINT A-Z\n20 DATA \"ndeokgelw\",\"unixdict.txt\"\n30 READ WH$, F$\n40 OPEN \"I\",1,F$\n50 IF EOF(1) THEN CLOSE 1: END\n60 C$ = WH$\n70 LINE INPUT #1, W$\n80 FOR I=1 TO LEN(W$)\n90 FOR J=1 TO LEN(C$)\n100 IF MID$(W$,I,1)=MID$(C$,J,1) THEN MID$(C$,J,1)=\"@\": GOTO 120\n110 NEXT J: GOTO 50\n120 NEXT I\n130 IF MID$(C$,(LEN(C$)+1)/2,1)<>\"@\" GOTO 50\n140 C=0: FOR I=1 TO LEN(C$): C=C-(MID$(C$,I,1)=\"@\"): NEXT\n150 IF C>=3 THEN PRINT W$,\n160 GOTO 50\n", "language": "BASIC" }, { "code": "get \"libhdr\"\n\n// Read word from selected input\nlet readword(v) = valof\n$( let ch = ?\n v%0 := 0\n $( ch := rdch()\n if ch = endstreamch then resultis false\n if ch = '*N' then resultis true\n v%0 := v%0 + 1\n v%(v%0) := ch\n $) repeat\n$)\n\n// Test word against wheel\nlet match(wheel, word) = valof\n$( let wcopy = vec 2+9/BYTESPERWORD\n for i = 0 to wheel%0 do wcopy%i := wheel%i\n for i = 1 to word%0 do\n $( let idx = ?\n test valof\n $( for j = 1 to wcopy%0 do\n if word%i = wcopy%j then\n $( idx := j\n resultis true\n $)\n resultis false\n $) then wcopy%idx := 0 // we've used this letter\n else resultis false // word cannot be made\n $)\n resultis\n wcopy%((wcopy%0+1)/2)=0 & // middle letter must be used\n 3 <= valof // at least 3 letters must be used\n $( let count = 0\n for i = 1 to wcopy%0 do\n if wcopy%i=0 then count := count + 1\n resultis count\n $)\n$)\n\n// Test unixdict.txt against ndeokgelw\nlet start() be\n$( let word = vec 2+64/BYTESPERWORD\n let file = findinput(\"unixdict.txt\")\n let wheel = \"ndeokgelw\"\n\n selectinput(file)\n while readword(word) do\n if match(wheel, word) do\n writef(\"%S*N\", word)\n endread()\n$)\n", "language": "BCPL" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n\n#define MAX_WORD 80\n#define LETTERS 26\n\nbool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n\nint index(char c) { return c - 'a'; }\n\nvoid word_wheel(const char* letters, char central, int min_length, FILE* dict) {\n int max_count[LETTERS] = { 0 };\n for (const char* p = letters; *p; ++p) {\n char c = *p;\n if (is_letter(c))\n ++max_count[index(c)];\n }\n char word[MAX_WORD + 1] = { 0 };\n while (fgets(word, MAX_WORD, dict)) {\n int count[LETTERS] = { 0 };\n for (const char* p = word; *p; ++p) {\n char c = *p;\n if (c == '\\n') {\n if (p >= word + min_length && count[index(central)] > 0)\n printf(\"%s\", word);\n } else if (is_letter(c)) {\n int i = index(c);\n if (++count[i] > max_count[i]) {\n break;\n }\n } else {\n break;\n }\n }\n }\n}\n\nint main(int argc, char** argv) {\n const char* dict = argc == 2 ? argv[1] : \"unixdict.txt\";\n FILE* in = fopen(dict, \"r\");\n if (in == NULL) {\n perror(dict);\n return 1;\n }\n word_wheel(\"ndeokgelw\", 'k', 3, in);\n fclose(in);\n return 0;\n}\n", "language": "C" }, { "code": "#include <array>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <vector>\n#include <boost/program_options.hpp>\n\n// A multiset specialized for strings consisting of lowercase\n// letters ('a' to 'z').\nclass letterset {\npublic:\n letterset() {\n count_.fill(0);\n }\n explicit letterset(const std::string& str) {\n count_.fill(0);\n for (char c : str)\n add(c);\n }\n bool contains(const letterset& set) const {\n for (size_t i = 0; i < count_.size(); ++i) {\n if (set.count_[i] > count_[i])\n return false;\n }\n return true;\n }\n unsigned int count(char c) const {\n return count_[index(c)];\n }\n bool is_valid() const {\n return count_[0] == 0;\n }\n void add(char c) {\n ++count_[index(c)];\n }\nprivate:\n static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }\n static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }\n // elements 1..26 contain the number of times each lowercase\n // letter occurs in the word\n // element 0 is the number of other characters in the word\n std::array<unsigned int, 27> count_;\n};\n\ntemplate <typename iterator, typename separator>\nstd::string join(iterator begin, iterator end, separator sep) {\n std::string result;\n if (begin != end) {\n result += *begin++;\n for (; begin != end; ++begin) {\n result += sep;\n result += *begin;\n }\n }\n return result;\n}\n\nusing dictionary = std::vector<std::pair<std::string, letterset>>;\n\ndictionary load_dictionary(const std::string& filename, int min_length,\n int max_length) {\n std::ifstream in(filename);\n if (!in)\n throw std::runtime_error(\"Cannot open file \" + filename);\n std::string word;\n dictionary result;\n while (getline(in, word)) {\n if (word.size() < min_length)\n continue;\n if (word.size() > max_length)\n continue;\n letterset set(word);\n if (set.is_valid())\n result.emplace_back(word, set);\n }\n return result;\n}\n\nvoid word_wheel(const dictionary& dict, const std::string& letters,\n char central_letter) {\n letterset set(letters);\n if (central_letter == 0 && !letters.empty())\n central_letter = letters.at(letters.size()/2);\n std::map<size_t, std::vector<std::string>> words;\n for (const auto& pair : dict) {\n const auto& word = pair.first;\n const auto& subset = pair.second;\n if (subset.count(central_letter) > 0 && set.contains(subset))\n words[word.size()].push_back(word);\n }\n size_t total = 0;\n for (const auto& p : words) {\n const auto& v = p.second;\n auto n = v.size();\n total += n;\n std::cout << \"Found \" << n << \" \" << (n == 1 ? \"word\" : \"words\")\n << \" of length \" << p.first << \": \"\n << join(v.begin(), v.end(), \", \") << '\\n';\n }\n std::cout << \"Number of words found: \" << total << '\\n';\n}\n\nvoid find_max_word_count(const dictionary& dict, int word_length) {\n size_t max_count = 0;\n std::vector<std::pair<std::string, char>> max_words;\n for (const auto& pair : dict) {\n const auto& word = pair.first;\n if (word.size() != word_length)\n continue;\n const auto& set = pair.second;\n dictionary subsets;\n for (const auto& p : dict) {\n if (set.contains(p.second))\n subsets.push_back(p);\n }\n letterset done;\n for (size_t index = 0; index < word_length; ++index) {\n char central_letter = word[index];\n if (done.count(central_letter) > 0)\n continue;\n done.add(central_letter);\n size_t count = 0;\n for (const auto& p : subsets) {\n const auto& subset = p.second;\n if (subset.count(central_letter) > 0)\n ++count;\n }\n if (count > max_count) {\n max_words.clear();\n max_count = count;\n }\n if (count == max_count)\n max_words.emplace_back(word, central_letter);\n }\n }\n std::cout << \"Maximum word count: \" << max_count << '\\n';\n std::cout << \"Words of \" << word_length << \" letters producing this count:\\n\";\n for (const auto& pair : max_words)\n std::cout << pair.first << \" with central letter \" << pair.second << '\\n';\n}\n\nconstexpr const char* option_filename = \"filename\";\nconstexpr const char* option_wheel = \"wheel\";\nconstexpr const char* option_central = \"central\";\nconstexpr const char* option_min_length = \"min-length\";\nconstexpr const char* option_part2 = \"part2\";\n\nint main(int argc, char** argv) {\n const int word_length = 9;\n int min_length = 3;\n std::string letters = \"ndeokgelw\";\n std::string filename = \"unixdict.txt\";\n char central_letter = 0;\n bool do_part2 = false;\n\n namespace po = boost::program_options;\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (option_filename, po::value<std::string>(), \"name of dictionary file\")\n (option_wheel, po::value<std::string>(), \"word wheel letters\")\n (option_central, po::value<char>(), \"central letter (defaults to middle letter of word)\")\n (option_min_length, po::value<int>(), \"minimum word length\")\n (option_part2, \"include part 2\");\n\n try {\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if (vm.count(option_filename))\n filename = vm[option_filename].as<std::string>();\n if (vm.count(option_wheel))\n letters = vm[option_wheel].as<std::string>();\n if (vm.count(option_central))\n central_letter = vm[option_central].as<char>();\n if (vm.count(option_min_length))\n min_length = vm[option_min_length].as<int>();\n if (vm.count(option_part2))\n do_part2 = true;\n\n auto dict = load_dictionary(filename, min_length, word_length);\n // part 1\n word_wheel(dict, letters, central_letter);\n // part 2\n if (do_part2) {\n std::cout << '\\n';\n find_max_word_count(dict, word_length);\n }\n } catch (const std::exception& ex) {\n std::cerr << ex.what() << '\\n';\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n", "language": "C++" }, { "code": "#include <algorithm>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main() {\n\tconst std::string word_wheel_letters = \"ndeokgelw\";\n\tconst std::string middle_letter = word_wheel_letters.substr(4, 1);\n\n\tstd::vector<std::string> words;\n\tstd::fstream file_stream;\n\tfile_stream.open(\"../unixdict.txt\");\n\tstd::string word;\n\twhile ( file_stream >> word ) {\n\t\twords.emplace_back(word);\n\t}\n\n\tstd::vector<std::string> correct_words;\n\tfor ( const std::string& word : words ) {\n\t\tif ( 3 <= word.length() && word.length() <= 9 &&\n\t\t\tword.find(middle_letter) != std::string::npos &&\n\t\t\tword.find_first_not_of(word_wheel_letters) == std::string::npos ) {\n\n\t\t\tcorrect_words.emplace_back(word);\n\t\t}\n\t}\n\n\tfor ( const std::string& correct_word : correct_words ) {\n\t\tstd::cout << correct_word << std::endl;\n\t}\n\n\tint32_t max_words_found = 0;\n\tstd::vector<std::string> best_words9;\n\tstd::vector<char> best_central_letters;\n\tstd::vector<std::string> words9;\n\tfor ( const std::string& word : words ) {\n\t\tif ( word.length() == 9 ) {\n\t\t\twords9.emplace_back(word);\n\t\t}\n\t}\n\n\tfor ( const std::string& word9 : words9 ) {\n\t\tstd::vector<char> distinct_letters(word9.begin(), word9.end());\n\t\tstd::sort(distinct_letters.begin(), distinct_letters.end());\n\t\tdistinct_letters.erase(std::unique(distinct_letters.begin(), distinct_letters.end()), distinct_letters.end());\n\n\t\tfor ( const char& letter : distinct_letters ) {\n\t\t\tint32_t words_found = 0;\n\t\t\tfor ( const std::string& word : words ) {\n\t\t\t\tif ( word.length() >= 3 && word.find(letter) != std::string::npos ) {\n\t\t\t\t\tstd::vector<char> letters = distinct_letters;\n\t\t\t\t\tbool valid_word = true;\n\t\t\t\t\tfor ( const char& ch : word ) {\n\t\t\t\t\t\tstd::vector<char>::iterator iter = std::find(letters.begin(), letters.end(), ch);\n\t\t\t\t\t\tint32_t index = ( iter == letters.end() ) ? -1 : std::distance(letters.begin(), iter);\n\t\t\t\t\t\tif ( index == -1 ) {\n\t\t\t\t\t\t\tvalid_word = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tletters.erase(letters.begin() + index);\n\t\t\t\t\t}\n\t\t\t\t\tif ( valid_word ) {\n\t\t\t\t\t\twords_found++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( words_found > max_words_found ) {\n\t\t\t\tmax_words_found = words_found;\n\t\t\t\tbest_words9.clear();\n\t\t\t\tbest_words9.emplace_back(word9);\n\t\t\t\tbest_central_letters.clear();\n\t\t\t\tbest_central_letters.emplace_back(letter);\n\t\t\t} else if ( words_found == max_words_found ) {\n\t\t\t\tbest_words9.emplace_back(word9);\n\t\t\t\tbest_central_letters.emplace_back(letter);\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << \"\\n\" << \"Most words found = \" << max_words_found << std::endl;\n\tstd::cout << \"The nine letter words producing this total are:\" << std::endl;\n\tfor ( uint64_t i = 0; i < best_words9.size(); ++i ) {\n\t\tstd::cout << best_words9[i] << \" with central letter '\" << best_central_letters[i] << \"'\" << std::endl;\n\t}\n}\n", "language": "C++" }, { "code": "program Word_wheel;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n System.SysUtils,\n System.Classes;\n\nfunction IsInvalid(s: string): Boolean;\nvar\n c: char;\n leters: set of char;\n firstE: Boolean;\nbegin\n Result := (s.Length < 3) or (s.IndexOf('k') = -1) or (s.Length > 9);\n if not Result then\n begin\n leters := ['d', 'e', 'g', 'k', 'l', 'n', 'o', 'w'];\n firstE := true;\n for c in s do\n begin\n if c in leters then\n if (c = 'e') and (firstE) then\n firstE := false\n else\n Exclude(leters, AnsiChar(c))\n else\n exit(true);\n end;\n end;\nend;\n\nvar\n dict: TStringList;\n i: Integer;\nbegin\n dict := TStringList.Create;\n dict.LoadFromFile('unixdict.txt');\n\n for i := dict.count - 1 downto 0 do\n if IsInvalid(dict[i]) then\n dict.Delete(i);\n\n Writeln('The following ', dict.Count, ' words are the solutions to the puzzle:');\n Writeln(dict.Text);\n\n dict.Free;\n readln;\nend.\n", "language": "Delphi" }, { "code": "// Word Wheel: Nigel Galloway. May 25th., 2021\nlet fG k n g=g|>Seq.exists(fun(n,_)->n=k) && g|>Seq.forall(fun(k,g)->Map.containsKey k n && g<=n.[k])\nlet wW n g=let fG=fG(Seq.item 4 g)(g|>Seq.countBy id|>Map.ofSeq) in seq{use n=System.IO.File.OpenText(n) in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(fun n->2<(Seq.length n)&&(Seq.countBy id>>fG)n)\nwW \"unixdict.txt\" \"ndeokgelw\"|>Seq.iter(printfn \"%s\")\n", "language": "F-Sharp" }, { "code": "USING: assocs io.encodings.ascii io.files kernel math\nmath.statistics prettyprint sequences sorting ;\n\n! Only consider words longer than two letters and words that\n! contain elt.\n: pare ( elt seq -- new-seq )\n [ [ member? ] keep length 2 > and ] with filter ;\n\n: words ( input-str path -- seq )\n [ [ midpoint@ ] keep nth ] [ ascii file-lines pare ] bi* ;\n\n: ?<= ( m n/f -- ? ) dup f = [ nip ] [ <= ] if ;\n\n! Can we make sequence 1 with the elements in sequence 2?\n: can-make? ( seq1 seq2 -- ? )\n [ histogram ] bi@ [ swapd at ?<= ] curry assoc-all? ;\n\n: solve ( input-str path -- seq )\n [ words ] keepd [ can-make? ] curry filter ;\n\n\"ndeokgelw\" \"unixdict.txt\" solve [ length ] sort-with .\n", "language": "Factor" }, { "code": "#include \"file.bi\"\n\nFunction String_Split(s_in As String,chars As String,result() As String) As Long\n Dim As Long ctr,ctr2,k,n,LC=Len(chars)\n Dim As boolean tally(Len(s_in))\n #macro check_instring()\n n=0\n While n<Lc\n If chars[n]=s_in[k] Then\n tally(k)=true\n If (ctr2-1) Then ctr+=1\n ctr2=0\n Exit While\n End If\n n+=1\n Wend\n #endmacro\n\n #macro split()\n If tally(k) Then\n If (ctr2-1) Then ctr+=1:result(ctr)=Mid(s_in,k+2-ctr2,ctr2-1)\n ctr2=0\n End If\n #endmacro\n '================== LOOP TWICE =======================\n For k =0 To Len(s_in)-1\n ctr2+=1:check_instring()\n Next k\n if ctr=0 then\n if len(s_in) andalso instr(chars,chr(s_in[0])) then ctr=1':beep\n end if\n If ctr Then Redim result(1 To ctr): ctr=0:ctr2=0 Else Return 0\n For k =0 To Len(s_in)-1\n ctr2+=1:split()\n Next k\n '===================== Last one ========================\n If ctr2>0 Then\n Redim Preserve result(1 To ctr+1)\n result(ctr+1)=Mid(s_in,k+1-ctr2,ctr2)\n End If\n\n Return Ubound(result)\nEnd Function\n\nFunction loadfile(file As String) As String\n\tIf Fileexists(file)=0 Then Print file;\" not found\":Sleep:End\n Dim As Long f=Freefile\n Open file For Binary Access Read As #f\n Dim As String text\n If Lof(f) > 0 Then\n text = String(Lof(f), 0)\n Get #f, , text\n End If\n Close #f\n Return text\nEnd Function\n\nFunction tally(SomeString As String,PartString As String) As Long\n Dim As Long LenP=Len(PartString),count\n Dim As Long position=Instr(SomeString,PartString)\n If position=0 Then Return 0\n While position>0\n count+=1\n position=Instr(position+LenP,SomeString,PartString)\n Wend\n Return count\nEnd Function\n\nSub show(g As String,file As String,byref matches as long,minsize as long,mustdo as string)\n Redim As String s()\n Var L=lcase(loadfile(file))\n g=lcase(g)\n string_split(L,Chr(10),s())\n For m As Long=minsize To len(g)\n For n As Long=Lbound(s) To Ubound(s)\n If Len(s(n))=m Then\n For k As Long=0 To m-1\n If Instr(g,Chr(s(n)[k]))=0 Then Goto lbl\n Next k\n If Instr(s(n),mustdo) Then\n For j As Long=0 To Len(s(n))-1\n If tally(s(n),Chr(s(n)[j]))>tally(g,Chr(s(n)[j])) Then Goto lbl\n Next j\n Print s(n)\n matches+=1\n End If\n End If\n lbl:\n Next n\n Next m\nEnd Sub\n\ndim as long matches\ndim as double t=timer\nshow(\"ndeokgelw\",\"unixdict.txt\",matches,3,\"k\")\nprint\nprint \"Overall time taken \";timer-t;\" seconds\"\nprint matches;\" matches\"\nSleep\n", "language": "FreeBASIC" }, { "code": "#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}\n\ninclude \"NSLog.incl\"\n\nlocal fn CountCharacterInString( string as CFStringRef, character as CFStringRef ) as NSUInteger\nend fn = len(string) - len( fn StringByReplacingOccurrencesOfString( string, character, @\"\" ) )\n\nlocal fn IsLegal( wordStr as CFStringRef ) as BOOL\n NSUInteger i, count = len( wordStr )\n CFStringRef letters = @\"ndeokgelw\"\n\n if count < 3 || fn StringContainsString( wordStr, @\"k\" ) == NO then exit fn = NO\n for i = 0 to count - 1\n if fn CountCharacterInString( letters, mid( wordStr, i, 1 ) ) < fn CountCharacterInString( wordStr, mid( wordStr, i, 1 ) )\n exit fn = NO\n end if\n next\nend fn = YES\n\nlocal fn ArrayOfDictionaryWords as CFArrayRef\n CFURLRef url = fn URLWithString( @\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\" )\n CFStringRef string = lcase( fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) )\n CFArrayRef wordArr = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet )\nend fn = wordArr\n\nvoid local fn FindWheelWords\n CFArrayRef wordArr = fn ArrayOfDictionaryWords\n CFStringRef wordStr\n CFMutableStringRef mutStr = fn MutableStringNew\n\n for wordStr in wordArr\n if fn IsLegal( wordStr ) then MutableStringAppendFormat( mutStr, fn StringWithFormat( @\"%@\\n\", wordStr ) )\n next\n NSLog( @\"%@\", mutStr )\nend fn\n\nfn FindWheelWords\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"sort\"\n \"strings\"\n)\n\nfunc main() {\n b, err := ioutil.ReadFile(\"unixdict.txt\")\n if err != nil {\n log.Fatal(\"Error reading file\")\n }\n letters := \"deegklnow\"\n wordsAll := bytes.Split(b, []byte{'\\n'})\n // get rid of words under 3 letters or over 9 letters\n var words [][]byte\n for _, word := range wordsAll {\n word = bytes.TrimSpace(word)\n le := len(word)\n if le > 2 && le < 10 {\n words = append(words, word)\n }\n }\n var found []string\n for _, word := range words {\n le := len(word)\n if bytes.IndexByte(word, 'k') >= 0 {\n lets := letters\n ok := true\n for i := 0; i < le; i++ {\n c := word[i]\n ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n if ix < len(lets) && lets[ix] == c {\n lets = lets[0:ix] + lets[ix+1:]\n } else {\n ok = false\n break\n }\n }\n if ok {\n found = append(found, string(word))\n }\n }\n }\n fmt.Println(\"The following\", len(found), \"words are the solutions to the puzzle:\")\n fmt.Println(strings.Join(found, \"\\n\"))\n\n // optional extra\n mostFound := 0\n var mostWords9 []string\n var mostLetters []byte\n // extract 9 letter words\n var words9 [][]byte\n for _, word := range words {\n if len(word) == 9 {\n words9 = append(words9, word)\n }\n }\n // iterate through them\n for _, word9 := range words9 {\n letterBytes := make([]byte, len(word9))\n copy(letterBytes, word9)\n sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })\n // get distinct bytes\n distinctBytes := []byte{letterBytes[0]}\n for _, b := range letterBytes[1:] {\n if b != distinctBytes[len(distinctBytes)-1] {\n distinctBytes = append(distinctBytes, b)\n }\n }\n distinctLetters := string(distinctBytes)\n for _, letter := range distinctLetters {\n found := 0\n letterByte := byte(letter)\n for _, word := range words {\n le := len(word)\n if bytes.IndexByte(word, letterByte) >= 0 {\n lets := string(letterBytes)\n ok := true\n for i := 0; i < le; i++ {\n c := word[i]\n ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })\n if ix < len(lets) && lets[ix] == c {\n lets = lets[0:ix] + lets[ix+1:]\n } else {\n ok = false\n break\n }\n }\n if ok {\n found = found + 1\n }\n }\n }\n if found > mostFound {\n mostFound = found\n mostWords9 = []string{string(word9)}\n mostLetters = []byte{letterByte}\n } else if found == mostFound {\n mostWords9 = append(mostWords9, string(word9))\n mostLetters = append(mostLetters, letterByte)\n }\n }\n }\n fmt.Println(\"\\nMost words found =\", mostFound)\n fmt.Println(\"Nine letter words producing this total:\")\n for i := 0; i < len(mostWords9); i++ {\n fmt.Println(mostWords9[i], \"with central letter\", string(mostLetters[i]))\n }\n}\n", "language": "Go" }, { "code": "import Data.Char (toLower)\nimport Data.List (sort)\nimport System.IO (readFile)\n\n------------------------ WORD WHEEL ----------------------\n\ngridWords :: [String] -> [String] -> [String]\ngridWords grid =\n filter\n ( ((&&) . (2 <) . length)\n <*> (((&&) . elem mid) <*> wheelFit wheel)\n )\n where\n cs = toLower <$> concat grid\n wheel = sort cs\n mid = cs !! 4\n\nwheelFit :: String -> String -> Bool\nwheelFit wheel = go wheel . sort\n where\n go _ [] = True\n go [] _ = False\n go (w : ws) ccs@(c : cs)\n | w == c = go ws cs\n | otherwise = go ws ccs\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n readFile \"unixdict.txt\"\n >>= ( mapM_ putStrLn\n . gridWords [\"NDE\", \"OKG\", \"ELW\"]\n . lines\n )\n", "language": "Haskell" }, { "code": "require'stats'\nwwhe=: {{\n ref=. /:~each words=. cutLF tolower fread 'unixdict.txt'\n y=.,y assert. 9=#y\n ch0=. 4{y\n chn=. (<<<4){y\n r=. ''\n for_i.2}.i.9 do.\n target=. <\"1 ~./:~\"1 ch0,.(i comb 8){chn\n ;:inv r=. r,words #~ ref e. target\n end.\n}}\n", "language": "J" }, { "code": " wwhe'ndeokgelw'\neke elk keg ken wok keel keen keno knee knew know kong leek week woke kneel knowledge\n", "language": "J" }, { "code": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Predicate;\n\npublic final class WordWheelExtended {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tString wordWheel = \"N D E\"\n\t\t\t\t + \"O K G\"\n\t\t\t\t + \"E L W\";\n\t\t\n\t\tString url = \"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\";\t\t\n\t\tInputStream stream = URI.create(url).toURL().openStream();\n\t\tBufferedReader reader = new BufferedReader( new InputStreamReader(stream) );\n\t\tList<String> words = reader.lines().toList();\t\n\t\treader.close();\n\t\t\n\t\tString allLetters = wordWheel.toLowerCase().replace(\" \", \"\");\t\t\n\t\tString middleLetter = allLetters.substring(4, 5);\n\t\t\n\t\tPredicate<String> firstFilter = word -> word.contains(middleLetter) && 2 < word.length() && word.length() < 10;\n\t\tPredicate<String> secondFilter = word -> word.chars().allMatch( ch -> allLetters.indexOf(ch) >= 0 );\n\t\tPredicate<String> correctWords = firstFilter.and(secondFilter);\n\t\t\n\t\twords.stream().filter(correctWords).forEach(System.out::println);\n\t\t\n\t\tint maxWordsFound = 0;\n\t\tList<String> bestWords9 = new ArrayList<String>();\n\t\tList<Character> bestCentralLetters = new ArrayList<Character>();\n\t\tList<String> words9 = words.stream().filter( word -> word.length() == 9 ).toList();\n\n\t\tfor ( String word9 : words9 ) {\t\t\t\n\t\t\tList<Character> distinctLetters = word9.chars().mapToObj( i -> (char) i ).distinct().toList();\t\t\t\n\t\t\tfor ( char letter : distinctLetters ) {\n\t\t\t\tint wordsFound = 0;\n\t\t\t\tfor ( String word : words ) {\n\t\t\t\t\tif ( word.length() >= 3 && word.indexOf(letter) >= 0 ) {\n\t\t List<Character> letters = new ArrayList<Character>(distinctLetters);\n\t\t boolean validWord = true;\n\t\t for ( char ch : word.toCharArray() ) {\n\t\t final int index = letters.indexOf(ch);\n\t\t if ( index == -1 ) {\n\t\t validWord = false;\n\t\t break;\n\t\t }\n\t\t letters.remove(index);\n\t\t }\n\t\t if ( validWord ) {\n\t\t \twordsFound += 1;\n\t\t }\n\t\t }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif ( wordsFound > maxWordsFound ) {\n\t\t maxWordsFound = wordsFound;\n\t\t bestWords9.clear();\n\t\t bestWords9.add(word9);\n\t\t bestCentralLetters.clear();\n\t\t bestCentralLetters.add(letter);\n\t\t } else if ( wordsFound == maxWordsFound ) {\n\t\t bestWords9.add(word9);\n\t\t bestCentralLetters.add(letter);\n\t\t }\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tSystem.out.println(System.lineSeparator() + \"Most words found = \" + maxWordsFound);\n\t\tSystem.out.println(\"The nine letter words producing this total are:\");\n\t\tfor ( int i = 0; i < bestWords9.size(); i++ ) {\n\t\t System.out.println(bestWords9.get(i) + \" with central letter '\" + bestCentralLetters.get(i) + \"'\");\n\t\t}\t\t\n\t}\t\n\n}\n", "language": "Java" }, { "code": "(() => {\n \"use strict\";\n\n // ------------------- WORD WHEEL --------------------\n\n // gridWords :: [String] -> [String] -> [String]\n const gridWords = grid =>\n lexemes => {\n const\n wheel = sort(toLower(grid.join(\"\"))),\n wSet = new Set(wheel),\n mid = wheel[4];\n\n return lexemes.filter(w => {\n const cs = [...w];\n\n return 2 < cs.length && cs.every(\n c => wSet.has(c)\n ) && cs.some(x => mid === x) && (\n wheelFit(wheel, cs)\n );\n });\n };\n\n\n // wheelFit :: [Char] -> [Char] -> Bool\n const wheelFit = (wheel, word) => {\n const go = (ws, cs) =>\n 0 === cs.length ? (\n true\n ) : 0 === ws.length ? (\n false\n ) : ws[0] === cs[0] ? (\n go(ws.slice(1), cs.slice(1))\n ) : go(ws.slice(1), cs);\n\n return go(wheel, sort(word));\n };\n\n\n // ---------------------- TEST -----------------------\n // main :: IO ()\n const main = () =>\n gridWords([\"NDE\", \"OKG\", \"ELW\"])(\n lines(readFile(\"unixdict.txt\"))\n )\n .join(\"\\n\");\n\n\n // ---------------- GENERIC FUNCTIONS ----------------\n\n // lines :: String -> [String]\n const lines = s =>\n // A list of strings derived from a single string\n // which is delimited by \\n or by \\r\\n or \\r.\n Boolean(s.length) ? (\n s.split(/\\r\\n|\\n|\\r/u)\n ) : [];\n\n\n // readFile :: FilePath -> IO String\n const readFile = fp => {\n // The contents of a text file at the\n // given file path.\n const\n e = $(),\n ns = $.NSString\n .stringWithContentsOfFileEncodingError(\n $(fp).stringByStandardizingPath,\n $.NSUTF8StringEncoding,\n e\n );\n\n return ObjC.unwrap(\n ns.isNil() ? (\n e.localizedDescription\n ) : ns\n );\n };\n\n\n // sort :: Ord a => [a] -> [a]\n const sort = xs =>\n Array.from(xs).sort();\n\n\n // toLower :: String -> String\n const toLower = s =>\n // Lower-case version of string.\n s.toLocaleLowerCase();\n\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# remove words with fewer than 3 or more than 9 letters\ndef words: inputs | select(length | . > 2 and . < 10);\n\n# The central letter in `puzzle` should be the central letter of the word wheel\ndef solve(puzzle):\n def chars: explode[] | [.] | implode;\n def profile(s): reduce s as $c (null; .[$c] += 1);\n profile(puzzle[]) as $profile\n | def ok($prof): all($prof|keys_unsorted[]; . as $k | $prof[$k] <= $profile[$k]);\n (puzzle | .[ (length - 1) / 2]) as $central\n | words\n | select(index($central) and ok( profile(chars) )) ;\n\n\"The solutions to the puzzle are as follows:\",\nsolve( [\"d\", \"e\", \"e\", \"g\", \"k\", \"l\", \"n\", \"o\", \"w\"] )\n", "language": "Jq" }, { "code": "using Combinatorics\n\nconst tfile = download(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\")\nconst wordlist = Dict(w => 1 for w in split(read(tfile, String), r\"\\s+\"))\n\nfunction wordwheel(wheel, central)\n returnlist = String[]\n for combo in combinations([string(i) for i in wheel])\n if central in combo && length(combo) > 2\n for perm in permutations(combo)\n word = join(perm)\n if haskey(wordlist, word) && !(word in returnlist)\n push!(returnlist, word)\n end\n end\n end\n end\n return returnlist\nend\n\nprintln(wordwheel(\"ndeokgelw\", \"k\"))\n", "language": "Julia" }, { "code": "const tfile = download(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\")\nconst wordarraylist = [[string(c) for c in w] for w in split(read(tfile, String), r\"\\s+\")]\n\nfunction wordwheel2(wheel, central)\n warr, maxlen = [string(c) for c in wheel], length(wheel)\n returnarraylist = filter(a -> 2 < length(a) <= maxlen && central in a &&\n all(c -> sum(x -> x == c, a) <= sum(x -> x == c, warr), a), wordarraylist)\n return join.(returnarraylist)\nend\n\nprintln(wordwheel2(\"ndeokgelw\", \"k\"))\n", "language": "Julia" }, { "code": "LetterCounter = {\n new = function(self, word)\n local t = { word=word, letters={} }\n for ch in word:gmatch(\".\") do t.letters[ch] = (t.letters[ch] or 0) + 1 end\n return setmetatable(t, self)\n end,\n contains = function(self, other)\n for k,v in pairs(other.letters) do\n if (self.letters[k] or 0) < v then return false end\n end\n return true\n end\n}\nLetterCounter.__index = LetterCounter\n\ngrid = \"ndeokgelw\"\nmidl = grid:sub(5,5)\nltrs = LetterCounter:new(grid)\nfile = io.open(\"unixdict.txt\", \"r\")\nfor word in file:lines() do\n if #word >= 3 and word:find(midl) and ltrs:contains(LetterCounter:new(word)) then\n print(word)\n end\nend\n", "language": "Lua" }, { "code": "ClearAll[possible]\npossible[letters_List][word_String] := Module[{c1, c2, m},\n c1 = Counts[Characters@word];\n c2 = Counts[letters];\n m = Merge[{c1, c2}, Identity];\n Length[Select[Select[m, Length /* GreaterThan[1]], Apply[Greater]]] == 0\n ]\nchars = Characters@\"ndeokgelw\";\nwords = Import[\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\", \"String\"];\nwords = StringSplit[ToLowerCase[words], \"\\n\"];\nwords //= Select[StringLength /* GreaterEqualThan[3]];\nwords //= Select[StringContainsQ[\"k\"]];\nwords //= Select[StringMatchQ[Repeated[Alternatives @@ chars]]];\nwords //= Select[possible[chars]];\nwords\n", "language": "Mathematica" }, { "code": "import strutils, sugar, tables\n\nconst Grid = \"\"\"N D E\n O K G\n E L W\"\"\"\n\nlet letters = Grid.toLowerAscii.splitWhitespace.join()\n\nlet words = collect(newSeq):\n for word in \"unixdict.txt\".lines:\n if word.len in 3..9:\n word\n\nlet midLetter = letters[4]\n\nlet gridCount = letters.toCountTable\nfor word in words:\n block checkWord:\n if midLetter in word:\n for ch, count in word.toCountTable.pairs:\n if count > gridCount[ch]:\n break checkWord\n echo word\n", "language": "Nim" }, { "code": "program WordWheel;\n\n{$mode objfpc}{$H+}\n\nuses\n SysUtils;\n\nconst\n WheelSize = 9;\n MinLength = 3;\n WordListFN = 'unixdict.txt';\n\nprocedure search(Wheel : string);\nvar\n Allowed, Required, Available, w : string;\n Len, i, p : integer;\n WordFile : TextFile;\n Match : boolean;\nbegin\n AssignFile(WordFile, WordListFN);\n try\n Reset(WordFile);\n except\n writeln('Could not open dictionary file: ' + WordListFN);\n exit;\n end;\n Allowed := LowerCase(Wheel);\n Required := copy(Allowed, 5, 1); { central letter is required }\n while not eof(WordFile) do\n begin\n readln(WordFile, w);\n Len := length(w);\n if (Len < MinLength) or (Len > WheelSize) then continue;\n if pos(Required, w) = 0 then continue;\n Available := Allowed;\n Match := True;\n for i := 1 to Len do\n begin\n p := pos(w[i], Available);\n if p > 0 then\n { prevent re-use of letter }\n delete(Available, p, 1)\n else\n begin\n Match := False;\n break;\n end;\n end;\n if Match then\n writeln(w);\n end;\n CloseFile(WordFile);\nend;\n\n{ exercise the procedure }\nbegin\n search('NDE' + 'OKG' + 'ELW');\nend.\n", "language": "Pascal" }, { "code": "#!/usr/bin/perl\n\nuse strict; # https://rosettacode.org/wiki/Word_wheel\nuse warnings;\n\n$_ = <<END;\n N D E\n O K G\n E L W\nEND\n\nmy $file = do { local(@ARGV, $/) = 'unixdict.txt'; <> };\nmy $length = my @letters = lc =~ /\\w/g;\nmy $center = $letters[@letters / 2];\nmy $toomany = (join '', sort @letters) =~ s/(.)\\1*/\n my $count = length \"$1$&\"; \"(?!(?:.*$1){$count})\" /ger;\nmy $valid = qr/^(?=.*$center)$toomany([@letters]{3,$length}$)$/m;\n\nmy @words = $file =~ /$valid/g;\n\nprint @words . \" words for\\n$_\\n@words\\n\" =~ s/.{60}\\K /\\n/gr;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.1\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (fixed another glitch in unique())</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">wheel</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"ndeokgelw\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">musthave</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">wheel</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">words</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unix_dict</span><span style=\"color: #0000FF;\">(),</span>\n <span style=\"color: #000000;\">word9</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #000080;font-style:italic;\">-- (for the optional extra part)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">lower</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lw</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lw</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">9</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">word9</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">musthave</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">remaining</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">wheel</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">lw</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">lw</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">remaining</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">remaining</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'\\0'</span> <span style=\"color: #000080;font-style:italic;\">-- (prevent re-use)</span>\n <span style=\"color: #000000;\">lw</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">lw</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">jbw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join_by</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"The following %d words were found:\\n %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">jbw</span><span style=\"color: #0000FF;\">})</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- optional extra</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- (works but no progress/blank screen for 2min 20s)\n -- (the \"working\" won't show, even w/o the JS check)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mostFound</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mostWheels</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">mustHaves</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word9</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">try_wheel</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word9</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">try_wheel</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">9</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">musthaves</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">unique</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">try_wheel</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">musthaves</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word9</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word9</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">musthaves</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">rest</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">try_wheel</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ix</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">rest</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">ix</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">rest</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ix</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">'\\0'</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">found</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">ok</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000080;font-style:italic;\">-- (wouldn't show up anyway)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"working (%s)\\r\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">try_wheel</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">mostFound</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mostFound</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">found</span>\n <span style=\"color: #000000;\">mostWheels</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">try_wheel</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">mustHaves</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">musthaves</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">]}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">found</span><span style=\"color: #0000FF;\">==</span><span style=\"color: #000000;\">mostFound</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">mostWheels</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mostWheels</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">try_wheel</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">mustHaves</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mustHaves</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">musthaves</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Most words found = %d\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mostFound</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Nine letter words producing this total:\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mostWheels</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s with central letter '%c'\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">mostWheels</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">mustHaves</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "main =>\n MinLen = 3,\n MaxLen = 9,\n Chars = \"ndeokgelw\",\n MustContain = 'k',\n\n WordList = \"unixdict.txt\",\n Words = read_file_lines(WordList),\n Res = word_wheel(Chars,Words,MustContain,MinLen, MaxLen),\n println(Res),\n println(len=Res.len),\n nl.\n\nword_wheel(Chars,Words,MustContain,MinLen,MaxLen) = Res.reverse =>\n Chars := to_lowercase(Chars),\n D = make_hash(Chars),\n Res = [],\n foreach(W in Words, W.len >= MinLen, W.len <= MaxLen, membchk(MustContain,W))\n WD = make_hash(W),\n Check = true,\n foreach(C in keys(WD), break(Check == false))\n if not D.has_key(C) ; WD.get(C,0) > D.get(C,0) then\n Check := false\n end\n end,\n if Check == true then\n Res := [W|Res]\n end\n end.\n\n% Returns a map of the elements and their occurrences\n% in the list L.\nmake_hash(L) = D =>\n D = new_map(),\n foreach(E in L)\n D.put(E,D.get(E,0)+1)\n end.\n", "language": "Picat" }, { "code": "main =>\n WordList = \"unixdict.txt\",\n MinLen = 3,\n MaxLen = 9,\n Words = [Word : Word in read_file_lines(WordList), Word.len >= MinLen, Word.len <= MaxLen],\n TargetWords = [Word : Word in Words, Word.len == MaxLen],\n MaxResWord = [],\n MaxResLen = 0,\n foreach(Word in TargetWords)\n foreach(MustContain in Word.remove_dups)\n Res = word_wheel(Word,Words,MustContain,MinLen, MaxLen),\n Len = Res.len,\n if Len >= MaxResLen then\n if Len == MaxResLen then\n MaxResWord := MaxResWord ++ [[word=Word,char=MustContain]]\n else\n MaxResWord := [[word=Word,char=MustContain]],\n MaxResLen := Len\n end\n end\n end\n end,\n println(maxLResen=MaxResLen),\n println(maxWord=MaxResWord).\n", "language": "Picat" }, { "code": "Procedure.b check_word(word$)\n Shared letters$\n If Len(word$)<3 Or FindString(word$,\"k\")<1\n ProcedureReturn #False\n EndIf\n For i=1 To Len(word$)\n If CountString(letters$,Mid(word$,i,1))<CountString(word$,Mid(word$,i,1))\n ProcedureReturn #False\n EndIf\n Next\n ProcedureReturn #True\nEndProcedure\n\nIf ReadFile(0,\"./Data/unixdict.txt\")\n txt$=LCase(ReadString(0,#PB_Ascii|#PB_File_IgnoreEOL))\n CloseFile(0)\nEndIf\n\nIf OpenConsole()\n letters$=\"ndeokgelw\"\n wordcount=1\n Repeat\n buf$=StringField(txt$,wordcount,~\"\\n\")\n wordcount+1\n If check_word(buf$)=#False\n Continue\n EndIf\n PrintN(buf$) : r+1\n Until buf$=\"\"\n PrintN(\"- Finished: \"+Str(r)+\" words found -\")\n Input()\nEndIf\nEnd\n", "language": "PureBasic" }, { "code": "import urllib.request\nfrom collections import Counter\n\n\nGRID = \"\"\"\nN \tD \tE\nO \tK \tG\nE \tL \tW\n\"\"\"\n\n\ndef getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):\n \"Return lowercased words of 3 to 9 characters\"\n words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n return (w for w in words if 2 < len(w) < 10)\n\ndef solve(grid, dictionary):\n gridcount = Counter(grid)\n mid = grid[4]\n return [word for word in dictionary\n if mid in word and not (Counter(word) - gridcount)]\n\n\nif __name__ == '__main__':\n chars = ''.join(GRID.strip().lower().split())\n found = solve(chars, dictionary=getwords())\n print('\\n'.join(found))\n", "language": "Python" }, { "code": "'''Word wheel'''\n\nfrom os.path import expanduser\n\n\n# gridWords :: [String] -> [String] -> [String]\ndef gridWords(grid):\n '''The subset of words in ws which contain the\n central letter of the grid, and can be completed\n by single uses of some or all of the remaining\n letters in the grid.\n '''\n def go(ws):\n cs = ''.join(grid).lower()\n wheel = sorted(cs)\n wset = set(wheel)\n mid = cs[4]\n return [\n w for w in ws\n if 2 < len(w) and (mid in w) and (\n all(c in wset for c in w)\n ) and wheelFit(wheel, w)\n ]\n return go\n\n\n# wheelFit :: String -> String -> Bool\ndef wheelFit(wheel, word):\n '''True if a given word can be constructed\n from (single uses of) some subset of\n the letters in the wheel.\n '''\n def go(ws, cs):\n return True if not cs else (\n False if not ws else (\n go(ws[1:], cs[1:]) if ws[0] == cs[0] else (\n go(ws[1:], cs)\n )\n )\n )\n return go(wheel, sorted(word))\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Word wheel matches for a given grid in a copy of\n http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\n '''\n print('\\n'.join(\n gridWords(['NDE', 'OKG', 'ELW'])(\n readFile('~/unixdict.txt').splitlines()\n )\n ))\n\n\n# ------------------------ GENERIC -------------------------\n\n# readFile :: FilePath -> IO String\ndef readFile(fp):\n '''The contents of any file at the path\n derived by expanding any ~ in fp.\n '''\n with open(expanduser(fp), 'r', encoding='utf-8') as f:\n return f.read()\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "ce:count each\nlc:ce group@ / letter count\ndict:\"\\n\"vs .Q.hg \"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\"\n// dictionary of 3-9 letter words\nd39:{x where(ce x)within 3 9}{x where all each x in .Q.a}dict\n\nsolve:{[grid;dict]\n i:where(grid 4)in'dict;\n dict i where all each 0<=(lc grid)-/:lc each dict i }[;d39]\n", "language": "Q" }, { "code": "q)`$solve \"ndeokglew\"\n`eke`elk`keel`keen`keg`ken`keno`knee`kneel`knew`know`knowledge`kong`leek`week`wok`woke\n", "language": "Q" }, { "code": "bust:{[dict]\n grids:distinct raze(til 9)rotate\\:/:dict where(ce dict)=9;\n wc:(count solve@)each grids;\n grids where wc=max wc }\n", "language": "Q" }, { "code": "best:{[dict]\n dlc:lc each dict; / letter counts of dictionary words\n ig:where(ce dict)=9; / find grids (9-letter words)\n igw:where each(all'')0<=(dlc ig)-/:\\:dlc; / find words composable from each grid (length ig)\n grids:raze(til 9)rotate\\:/:dict ig; / 9 permutations of each grid\n iaz:(.Q.a)!where each .Q.a in'\\:dict; / find words containing a, b, c etc\n ml:4 rotate'dict ig; / mid letters for each grid\n wc:ce raze igw inter/:'iaz ml; / word counts for grids\n distinct grids where wc=max wc } / grids with most words\n", "language": "Q" }, { "code": "q)show w:best d39\n\"ntclaremo\"\n\"tspearmin\"\n\nq)ce solve each w\n215 215\n", "language": "Q" }, { "code": " [ over find swap found ] is has ( $ c --> b )\n\n [ over find\n split 1 split\n swap drop join ] is remove ( $ c --> $ )\n\n $ \"rosetta/unixdict.txt\" sharefile\n drop nest$\n [] swap\n witheach\n [ dup size 3 < iff drop done\n dup size 9 > iff drop done\n dup char k has not iff drop done\n dup $ \"ndeokgelw\"\n witheach remove\n $ \"\" != iff drop done\n nested join ]\n 30 wrap$\n", "language": "Quackery" }, { "code": "use Terminal::Boxer;\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nunit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);\n\nmy $must-have = $wheel.comb[4].lc;\n\nmy $has = $wheel.comb».lc.Bag;\n\nmy %words;\n$dict.IO.slurp.words».lc.map: {\n next if not .contains($must-have) or .chars < $min;\n %words{.chars}.push: $_ if .comb.Bag ⊆ $has;\n};\n\nsay \"Using $dict, minimum $min letters.\";\n\nprint rs-box :3col, :3cw, :indent(\"\\t\"), $wheel.comb».uc;\n\nsay \"{sum %words.values».elems} words found\";\n\nprintf \"%d letters: %s\\n\", .key, .value.sort.join(', ') for %words.sort;\n", "language": "Raku" }, { "code": "raku word-wheel.raku\n", "language": "Raku" }, { "code": "raku word-wheel.raku --dict=./words.txt\n", "language": "Raku" }, { "code": "/*REXX pgm finds (dictionary) words which can be found in a specified word wheel (grid).*/\nparse arg grid minL iFID . /*obtain optional arguments from the CL*/\nif grid==''|grid==\",\" then grid= 'ndeokgelw' /*Not specified? Then use the default.*/\nif minL==''|minL==\",\" then minL= 3 /* \" \" \" \" \" \" */\nif iFID==''|iFID==\",\" then iFID= 'UNIXDICT.TXT' /* \" \" \" \" \" \" */\noMinL= minL; minL= abs(minL) /*if negative, then don't show a list. */\ngridU= grid; upper gridU /*get an uppercase version of the grid.*/\nLg= length(grid); Hg= Lg % 2 + 1 /*get length of grid & the middle char.*/\nctr= substr(grid, Hg, 1); upper ctr /*get uppercase center letter in grid. */\nwrds= 0 /*# words that are in the dictionary. */\nwees= 0 /*\" \" \" \" too short. */\nbigs= 0 /*\" \" \" \" too long. */\ndups= 0 /*\" \" \" \" duplicates. */\nills= 0 /*\" \" \" contain \"not\" letters.*/\ngood= 0 /*\" \" \" contain center letter. */\nnine= 0 /*\" wheel─words that contain 9 letters.*/\nsay ' Reading the file: ' iFID /*align the text. */\n@.= . /*uppercase non─duplicated dict. words.*/\n$= /*the list of dictionary words in grid.*/\n do recs=0 while lines(iFID)\\==0 /*process all words in the dictionary. */\n u= space( linein(iFID), 0); upper u /*elide blanks; uppercase the word. */\n L= length(u) /*obtain the length of the word. */\n if @.u\\==. then do; dups= dups+1; iterate; end /*is this a duplicate? */\n if L<minL then do; wees= wees+1; iterate; end /*is the word too short? */\n if L>Lg then do; bigs= bigs+1; iterate; end /*is the word too long? */\n if \\datatype(u,'M') then do; ills= ills+1; iterate; end /*has word non─letters? */\n @.u= /*signify that U is a dictionary word*/\n wrds= wrds + 1 /*bump the number of \"good\" dist. words*/\n if pos(ctr, u)==0 then iterate /*word doesn't have center grid letter.*/\n good= good + 1 /*bump # center─letter words in dict. */\n if verify(u, gridU)\\==0 then iterate /*word contains a letter not in grid. */\n if pruned(u, gridU) then iterate /*have all the letters not been found? */\n if L==9 then nine= nine + 1 /*bump # words that have nine letters. */\n $= $ u /*add this word to the \"found\" list. */\n end /*recs*/\nsay\nsay ' number of records (words) in the dictionary: ' right( commas(recs), 9)\nsay ' number of ill─formed words in the dictionary: ' right( commas(ills), 9)\nsay ' number of duplicate words in the dictionary: ' right( commas(dups), 9)\nsay ' number of too─small words in the dictionary: ' right( commas(wees), 9)\nsay ' number of too─long words in the dictionary: ' right( commas(bigs), 9)\nsay ' number of acceptable words in the dictionary: ' right( commas(wrds), 9)\nsay ' number center─letter words in the dictionary: ' right( commas(good), 9)\nsay ' the minimum length of words that can be used: ' right( commas(minL), 9)\nsay ' the word wheel (grid) being used: ' grid\nsay ' center of the word wheel (grid) being used: ' right('↑', Hg)\nsay; #= words($); $= strip($)\nsay ' number of word wheel words in the dictionary: ' right( commas(# ), 9)\nsay ' number of nine-letter wheel words found: ' right( commas(nine), 9)\nif #==0 | oMinL<0 then exit #\nsay\nsay ' The list of word wheel words found:'; say copies('─', length($)); say lower($)\nexit # /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nlower: arg aa; @='abcdefghijklmnopqrstuvwxyz'; @u=@; upper @u; return translate(aa,@,@U)\ncommas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _\n/*──────────────────────────────────────────────────────────────────────────────────────*/\npruned: procedure; parse arg aa,gg /*obtain word to be tested, & the grid.*/\n do n=1 for length(aa); p= pos( substr(aa,n,1), gg); if p==0 then return 1\n gg= overlay(., gg, p) /*\"rub out\" the found character in grid*/\n end /*n*/; return 0 /*signify that the AA passed the test*/\n", "language": "REXX" }, { "code": "wheel = \"ndeokgelw\"\nmiddle, wheel_size = wheel[4], wheel.size\n\nres = File.open(\"unixdict.txt\").each_line.select do |word|\n w = word.chomp\n next unless w.size.between?(3, wheel_size)\n next unless w.match?(middle)\n wheel.each_char{|c| w.sub!(c, \"\") } #sub! substitutes only the first occurrence (gsub would substitute all)\n w.empty?\nend\n\nputs res\n", "language": "Ruby" }, { "code": "#lang transd\n\nMainModule: {\n maxwLen: 9,\n minwLen: 3,\n dict: Vector<String>(),\n subWords: Vector<String>(),\n\n procGrid: (λ grid String() cent String() subs Bool()\n (with cnt 0 (sort grid)\n (for w in dict where (and (neq (index-of w cent) -1)\n (match w \"^[[:alpha:]]+$\")) do\n (if (is-subset grid (sort (cp w))) (+= cnt 1)\n (if subs (append subWords w))\n )\n )\n (ret cnt)\n )),\n\n _start: (λ locals: res 0 maxRes 0\n (with fs FileStream()\n (open-r fs \"/mnt/proj/res/unixdict.txt\")\n (for w in (read-lines fs)\n where (within (size w) minwLen maxwLen) do\n (append dict w))\n )\n\n (lout \"Main part of task:\\n\")\n (procGrid \"ndeokgelw\" \"k\" true)\n (lout \"Number of words: \" (size subWords) \";\\nword list: \" subWords)\n\n (lout \"\\n\\nOptional part of task:\\n\")\n (for w in dict where (eq (size w) maxwLen) do\n (for centl in (split (unique (sort (cp w))) \"\") do\n (if (>= (= res (procGrid (cp w) centl false)) maxRes) (= maxRes res)\n (lout \"New max. number: \" maxRes \", word: \" w \", central letter: \" centl)\n ) ) ) )\n}\n", "language": "Transd" }, { "code": "Const wheel=\"ndeokgelw\"\n\nSub print(s):\n On Error Resume Next\n WScript.stdout.WriteLine (s)\n If err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\nEnd Sub\n\nDim oDic\nSet oDic = WScript.CreateObject(\"scripting.dictionary\")\nDim cnt(127)\nDim fso\nSet fso = WScript.CreateObject(\"Scripting.Filesystemobject\")\nSet ff=fso.OpenTextFile(\"unixdict.txt\")\ni=0\nprint \"reading words of 3 or more letters\"\nWhile Not ff.AtEndOfStream\n x=LCase(ff.ReadLine)\n If Len(x)>=3 Then\n If Not odic.exists(x) Then oDic.Add x,0\n End If\nWend\nprint \"remaining words: \"& oDic.Count & vbcrlf\nff.Close\nSet ff=Nothing\nSet fso=Nothing\n\nSet re=New RegExp\nprint \"removing words with chars not in the wheel\"\nre.pattern=\"[^\"& wheel &\"]\"\nFor Each w In oDic.Keys\n If re.test(w) Then oDic.remove(w)\nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"ensuring the mandatory letter \"& Mid(wheel,5,1) & \" is present\"\nre.Pattern=Mid(wheel,5,1)\nFor Each w In oDic.Keys\n If Not re.test(w) Then oDic.remove(w)\nNext\nprint \"remaining words: \"& oDic.Count & vbcrlf\n\nprint \"checking number of chars\"\n\nDim nDic\nSet nDic = WScript.CreateObject(\"scripting.dictionary\")\nFor i=1 To Len(wheel)\n x=Mid(wheel,i,1)\n If nDic.Exists(x) Then\n a=nDic(x)\n nDic(x)=Array(a(0)+1,0)\n Else\n nDic.add x,Array(1,0)\n End If\nNext\n\nFor Each w In oDic.Keys\n For Each c In nDic.Keys\n ndic(c)=Array(nDic(c)(0),0)\n Next\n For ii = 1 To len(w)\n c=Mid(w,ii,1)\n a=nDic(c)\n If (a(0)=a(1)) Then\n oDic.Remove(w):Exit For\n End If\n nDic(c)=Array(a(0),a(1)+1)\n Next\nNext\n\nprint \"Remaining words \"& oDic.count\nFor Each w In oDic.Keys\n print w\nNext\n", "language": "VBScript" }, { "code": "import \"io\" for File\nimport \"./sort\" for Sort, Find\nimport \"./seq\" for Lst\n\nvar letters = [\"d\", \"e\", \"e\", \"g\", \"k\", \"l\", \"n\", \"o\",\"w\"]\n\nvar words = File.read(\"unixdict.txt\").split(\"\\n\")\n// get rid of words under 3 letters or over 9 letters\nwords = words.where { |w| w.count > 2 && w.count < 10 }.toList\nvar found = []\nfor (word in words) {\n if (word.indexOf(\"k\") >= 0) {\n var lets = letters.toList\n var ok = true\n for (c in word) {\n var ix = Find.first(lets, c)\n if (ix == - 1) {\n ok = false\n break\n }\n lets.removeAt(ix)\n }\n if (ok) found.add(word)\n }\n}\n\nSystem.print(\"The following %(found.count) words are the solutions to the puzzle:\")\nSystem.print(found.join(\"\\n\"))\n\n// optional extra\nvar mostFound = 0\nvar mostWords9 = []\nvar mostLetters = []\n// iterate through all 9 letter words in the dictionary\nfor (word9 in words.where { |w| w.count == 9 }) {\n letters = word9.toList\n Sort.insertion(letters)\n // get distinct letters\n var distinctLetters = Lst.distinct(letters)\n // place each distinct letter in the middle and see what we can do with the rest\n for (letter in distinctLetters) {\n found = 0\n for (word in words) {\n if (word.indexOf(letter) >= 0) {\n var lets = letters.toList\n var ok = true\n for (c in word) {\n var ix = Find.first(lets, c)\n if (ix == - 1) {\n ok = false\n break\n }\n lets.removeAt(ix)\n }\n if (ok) found = found + 1\n }\n }\n if (found > mostFound) {\n mostFound = found\n mostWords9 = [word9]\n mostLetters = [letter]\n } else if (found == mostFound) {\n mostWords9.add(word9)\n mostLetters.add(letter)\n }\n }\n}\nSystem.print(\"\\nMost words found = %(mostFound)\")\nSystem.print(\"Nine letter words producing this total:\")\nfor (i in 0...mostWords9.count) {\n System.print(\"%(mostWords9[i]) with central letter '%(mostLetters[i])'\")\n}\n", "language": "Wren" }, { "code": "string 0; \\use zero-terminated strings\nint I, Set, HasK, HasOther, HasDup, ECnt, Ch;\nchar Word(25);\ndef LF=$0A, CR=$0D, EOF=$1A;\n[FSet(FOpen(\"unixdict.txt\", 0), ^I);\nOpenI(3);\nrepeat I:= 0; HasK:= false; HasOther:= false;\n ECnt:= 0; Set:= 0; HasDup:= false;\n loop [repeat Ch:= ChIn(3) until Ch # CR; \\remove possible CR\n if Ch=LF or Ch=EOF then quit;\n Word(I):= Ch;\n I:= I+1;\n if Ch = ^k then HasK:= true;\n case Ch of ^k,^n,^d,^e,^o,^g,^l,^w: [] \\assume all lowercase\n other HasOther:= true;\n if Ch = ^e then ECnt:= ECnt+1\n else [if Set & 1<<(Ch-^a) then HasDup:= true;\n Set:= Set ! 1<<(Ch-^a);\n ];\n ];\n Word(I):= 0; \\terminate string\n if I>=3 & HasK & ~HasOther & ~HasDup & ECnt<=2 then\n [Text(0, Word); CrLf(0);\n ];\nuntil Ch = EOF;\n]\n", "language": "XPL0" } ]
Word-wheel
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Wordiff\nnote: Games\n", "language": "00-META" }, { "code": "Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from\nthe last by a change in one letter.\n\n\nThe change can be either:\n# a deletion of one letter; \n# addition of one letter; \n# or change in one letter.\n\n\nNote:\n* All words must be in the dictionary.\n* No word in a game can be repeated.\n* The first word must be three or four letters long.\n\n\n;Task:\nCreate a program to aid in the playing of the game by:\n* Asking for contestants names.\n* Choosing an initial random three or four letter word from the dictionary.\n* Asking each contestant in their turn for a wordiff word.\n* Checking the wordiff word is:\n:* in the dictionary, \n:* not a repetition of past words, \n:* and differs from the last appropriately.\n\n\n;Optional stretch goals:\n* Add timing.\n* Allow players to set a maximum playing time for the game.\n* An internal timer accumulates how long each user takes to respond in their turns.\n* Play is halted if the maximum playing time is exceeded on a players input.\n:* That last player must have entered a wordiff or loses.\n:* If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds.\n\n\n{{Template:Strings}}\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V dict_fname = ‘unixdict.txt’\n\nF load_dictionary(String fname = dict_fname)\n ‘Return appropriate words from a dictionary file’\n R Set(File(fname).read().split(\"\\n\").filter(word -> re:‘[a-z]{3,}’.match(word)))\n\nF get_players()\n V names = input(‘Space separated list of contestants: ’)\n R names.trim(‘ ’).split(‘ ’, group_delimiters' 1B).map(n -> n.capitalize())\n\nF is_wordiff_removal(word, String prev; comment = 1B)\n ‘Is word derived from prev by removing one letter?’\n V ans = word C Set((0 .< prev.len).map(i -> @prev[0 .< i]‘’@prev[i + 1 ..]))\n I !ans\n I comment\n print(‘Word is not derived from previous by removal of one letter.’)\n R ans\n\nF counter(s)\n DefaultDict[Char, Int] d\n L(c) s\n d[c]++\n R d\n\nF is_wordiff_insertion(String word, prev; comment = 1B) -> Bool\n ‘Is word derived from prev by adding one letter?’\n V diff = counter(word)\n L(c) prev\n I --diff[c] <= 0\n diff.pop(c)\n V diffcount = sum(diff.values())\n I diffcount != 1\n I comment\n print(‘More than one character insertion difference.’)\n R 0B\n\n V insert = Array(diff.keys())[0]\n V ans = word C Set((0 .. prev.len).map(i -> @prev[0 .< i]‘’@insert‘’@prev[i ..]))\n I !ans\n I comment\n print(‘Word is not derived from previous by insertion of one letter.’)\n R ans\n\nF is_wordiff_change(String word, String prev; comment = 1B) -> Bool\n ‘Is word derived from prev by changing exactly one letter?’\n V diffcount = sum(zip(word, prev).map((w, p) -> Int(w != p)))\n I diffcount != 1\n I comment\n print(‘More or less than exactly one character changed.’)\n R 0B\n R 1B\n\nF is_wordiff(wordiffs, word, dic, comment = 1B)\n ‘Is word a valid wordiff from wordiffs[-1] ?’\n I word !C dic\n I comment\n print(‘That word is not in my dictionary’)\n R 0B\n I word C wordiffs\n I comment\n print(‘That word was already used.’)\n R 0B\n I word.len < wordiffs.last.len\n R is_wordiff_removal(word, wordiffs.last, comment)\n E I word.len > wordiffs.last.len\n R is_wordiff_insertion(word, wordiffs.last, comment)\n\n R is_wordiff_change(word, wordiffs.last, comment)\n\nF could_have_got(wordiffs, dic)\n R (dic - Set(wordiffs)).filter(word -> is_wordiff(@wordiffs, word, @dic, comment' 0B))\n\nV dic = load_dictionary()\nV dic_3_4 = dic.filter(word -> word.len C (3, 4))\nV start = random:choice(dic_3_4)\nV wordiffs = [start]\nV players = get_players()\nV cur_player = 0\nL\n V name = players[cur_player]\n cur_player = (cur_player + 1) % players.len\n\n V word = input(name‘: Input a wordiff from '’wordiffs.last‘': ’).trim(‘ ’)\n I is_wordiff(wordiffs, word, dic)\n wordiffs.append(word)\n E\n print(‘YOU HAVE LOST ’name‘!’)\n print(‘Could have used: ’(could_have_got(wordiffs, dic)[0.<10]).join(‘, ’)‘ ...’)\n L.break\n", "language": "11l" }, { "code": "wordset: map read.lines relative \"unixdict.txt\" => strip\n\nvalidAnswer?: function [answer][\n if not? contains? wordset answer [\n prints \"\\tNot a valid dictionary word.\"\n return false\n ]\n if contains? pastWords answer [\n prints \"\\tWord already used.\"\n return false\n ]\n if 1 <> levenshtein answer last pastWords [\n prints \"\\tNot a correct wordiff.\"\n return false\n ]\n return true\n]\n\nplayerA: input \"player A: what is your name? \"\nplayerB: input \"player B: what is your name? \"\n\npastWords: new @[sample select wordset 'word [ contains? [3 4] size word ]]\n\nprint [\"\\nThe initial word is:\" last pastWords \"\\n\"]\n\ncurrent: playerA\nwhile ø [\n neww: strip input ~\"|current|, what is the next word? \"\n while [not? validAnswer? neww][\n neww: strip input \" Try again: \"\n ]\n 'pastWords ++ neww\n current: (current=playerA)? -> playerB -> playerA\n print \"\"\n]\n", "language": "Arturo" }, { "code": "#include <algorithm>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <string>\n#include <vector>\n\nstd::vector<std::string> request_player_names() {\n\tstd::vector<std::string> player_names;\n\tstd::string player_name;\n\tfor ( uint32_t i = 0; i < 2; ++i ) {\n\t\tstd::cout << \"Please enter the player's name: \";\n\t\tstd::getline(std::cin, player_name);\n\t\tplayer_names.emplace_back(player_name);\n\t}\n\treturn player_names;\n}\n\nbool is_letter_removed(const std::string& previous_word, const std::string& current_word) {\n\tfor ( uint64_t i = 0; i < previous_word.length(); ++i ) {\n\t\tif ( current_word == previous_word.substr(0, i) + previous_word.substr(i + 1) ) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool is_letter_added(const std::string& previous_word, const std::string& current_word) {\n\treturn is_letter_removed(current_word, previous_word);\n}\n\nbool is_letter_changed(const std::string& previous_word, const std::string& current_word) {\n\tif ( previous_word.length() != current_word.length() ) {\n\t\treturn false;\n\t}\n\n\tuint32_t difference_count = 0;\n\tfor ( uint64_t i = 0; i < current_word.length(); ++i ) {\n\t\tdifference_count += ( current_word[i] == previous_word[i] ) ? 0 : 1;\n\t}\n\treturn difference_count == 1;\n}\n\nbool is_wordiff(const std::string& current_word,\n\t\t const std::vector<std::string>& words_used,\n\t\t\t\tconst std::vector<std::string>& dictionary) {\n\tif ( std::find(dictionary.begin(), dictionary.end(), current_word) == dictionary.end()\n\t\t|| std::find(words_used.begin(), words_used.end(), current_word) != words_used.end() ) {\n\t\treturn false;\n\t}\n\n\tstd::string previous_word = words_used.back();\n\treturn is_letter_changed(previous_word, current_word)\n\t\t|| is_letter_removed(previous_word, current_word) || is_letter_added(previous_word, current_word);\n}\n\nstd::vector<std::string> could_have_entered(const std::vector<std::string>& words_used,\n\t\t\t\t\t\t\t\t\t\t const std::vector<std::string>& dictionary) {\n\tstd::vector<std::string> result;\n\tfor ( const std::string& word : dictionary ) {\n\t\tif ( std::find(words_used.begin(), words_used.end(), word) == words_used.end()\n\t\t\t&& is_wordiff(word, words_used, dictionary) ) {\n\t\t\tresult.emplace_back(word);\n\t\t}\n\t}\n\treturn result;\n}\n\nint main() {\n\tstd::vector<std::string> dictionary;\n\tstd::vector<std::string> starters;\n\tstd::fstream file_stream;\n\tfile_stream.open(\"../unixdict.txt\");\n\tstd::string word;\n\twhile ( file_stream >> word ) {\n\t\tdictionary.emplace_back(word);\n\t\tif ( word.length() == 3 || word.length() == 4 ) {\n\t\t\tstarters.emplace_back(word);\n\t\t}\n\t}\n\n\tstd::random_device rand;\n\tstd::mt19937 mersenne_twister(rand());\n\tstd::shuffle(starters.begin(), starters.end(), mersenne_twister);\n\tstd::vector<std::string> words_used;\n\twords_used.emplace_back(starters[0]);\n\n\tstd::vector<std::string> player_names = request_player_names();\n\tbool playing = true;\n\tuint32_t playerIndex = 0;\n\tstd::string current_word;\n\tstd::cout << \"The first word is: \" << words_used.back() << std::endl;\n\n\twhile ( playing ) {\n\t\tstd::cout << player_names[playerIndex] << \" enter your word: \";\n\t\tstd::getline(std::cin, current_word);\n\t\tif ( is_wordiff(current_word, words_used, dictionary) ) {\n\t\t\twords_used.emplace_back(current_word);\n\t\t\tplayerIndex = ( playerIndex == 0 ) ? 1 : 0;\n\t\t} else {\n\t\t\tstd::cout << \"You have lost the game, \" << player_names[playerIndex] << std::endl;\n\t\t\tstd::vector<std::string> missed_words = could_have_entered(words_used, dictionary);\n\t\t\tstd::cout << \"You could have entered: [\";\n\t\t\tfor ( uint64_t i = 0; i < missed_words.size() - 1; ++i ) {\n\t\t\t\tstd::cout << missed_words[i] << \", \";\n\t\t\t}\n\t\t\tstd::cout << missed_words.back() << \"]\" << std::endl;\n\t\t\tplaying = false;\n\t\t}\n\t}\n}\n", "language": "C++" }, { "code": "REM Wordiff ' 10 march 2024 '\n\n'--- Declaración de variables globales ---\nDim Shared As String words()\nDim Shared As String used()\nDim Shared As String player1\nDim Shared As String player2\nDim Shared As String player\nDim Shared As String prevWord\nDim Shared As Integer prevLen\n\n'--- SUBrutinas y FUNCiones ---\nSub loadWords\n Dim As Integer i, j, numLines\n Dim As String linea\n\n Open \"unixdict.txt\" For Input As #1\n While Not Eof(1)\n Line Input #1, linea\n If Len(linea) = 3 Or Len(linea) = 4 Then\n Redim Preserve words(numLines)\n words(numLines) = linea\n numLines += 1\n End If\n Wend\n Close #1\nEnd Sub\n\nSub Intro\n Cls\n Color 10, 0 '10, black\n Locate 10, 30 : Print \"---WORDIFF---\"\n Locate 12, 5 : Print \"Por turnos, teclear nuevas palabras del \"\n Locate 13, 5 : Print \"diccionario de tres o mas caracteres que \"\n Locate 14, 5 : Print \"se diferencien de la anterior en una letra.\"\n\n Color 14\n Locate 16, 5 : Input \"Player 1, please enter your name: \", player1\n Locate 17, 5 : Input \"Player 2, please enter your name: \", player2\n If player2 = player1 Then player2 &= \"2\"\n Color 7\nEnd Sub\n\n\nFunction wordExists(word As String) As Boolean\n For i As Integer = 0 To Ubound(words)\n If words(i) = word Then Return True\n Next i\n Return False\nEnd Function\n\nFunction wordUsed(word As String) As Boolean\n For i As Integer = 0 To Ubound(used)\n If used(i) = word Then Return True\n Next i\n Return False\nEnd Function\n\nSub addUsedWord(word As String)\n Redim Preserve used(Ubound(used) + 1)\n used(Ubound(used)) = word\nEnd Sub\n\nSub MenuPrincipal\n Dim As String word\n Dim As Integer i, changes, longi\n Dim As Boolean ok\n\n Cls\n prevWord = words(Int(Rnd * Ubound(words)))\n prevLen = Len(prevWord)\n player = player1\n Print \"The first word is \";\n Color 15 : Print prevWord : Color 7\n Do\n Color 7 : Print player; \", plays:\";\n Color 15 : Input \" \", word\n word = Lcase(word)\n longi = Len(word)\n ok = False\n Color 12\n If longi < 3 Then\n Print \"Words must be at least 3 letters long.\"\n Elseif wordExists(word) = 0 Then\n Print \"Not in dictionary.\"\n Elseif wordUsed(word) <> 0 Then\n Print \"Word has been used before.\"\n Elseif word = prevWord Then\n Print \"You must change the previous word.\"\n Elseif longi = prevLen Then\n changes = 0\n For i = 1 To longi\n If Mid(word, i, 1) <> Mid(prevWord, i, 1) Then changes += 1\n Next i\n If changes > 1 Then\n Print \"Only one letter can be changed.\"\n Else\n ok = True\n End If\n Else\n Print \"Invalid change.\"\n End If\n If ok Then\n prevLen = longi\n prevWord = word\n addUsedWord(word)\n player = Iif(player = player1, player2, player1)\n Else\n Print \"So, sorry \"; player; \", you've lost!\"\n Dim As String KBD\n Do: KBD = Inkey: Loop While KBD = \"\"\n Exit Do\n End If\n Loop\nEnd Sub\n\n'--- Programa Principal ---\nRandomize Timer\nIntro\nloadWords\nMenuPrincipal\nEnd\n'--------------------------\n", "language": "FreeBASIC" }, { "code": "output file \"Wordiff\" ' 27 november 2022 '\n\n#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES}\n\nbegin enum 1\n _playerLabel : _playerInput : _wordLabel : _wordInPlay : _playsLabel\n _scrlView : _textView\n _resignBtn : _againBtn : _quitBtn\nend enum\n\nbegin globals\nCFMutableArrayRef gWords, gNames, gUsed\ngWords = fn MutableArrayWithCapacity( 0 )\ngNames = fn MutableArrayWithCapacity( 0 )\ngUsed = fn MutableArrayWithCapacity( 0 )\nCFMutableStringRef gTxt\ngTxt = fn MutableStringWithCapacity( 0 )\nend globals\n\nvoid local fn BuildInterface\n window 1, @\"Wordiff\", ( 0, 0, 400, 450 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable\n // Fields for labels and input\n textlabel _playerLabel, @\"The players:\", ( 0, 370, 148, 24 )\n textlabel _wordLabel, @\"Word in play:\", ( 68, 409, 100, 24 )\n textlabel _playsLabel, , ( 113, 370, 150, 24 )\n textfield _playerInput, Yes, , ( 160, 372, 150, 24 )\n textfield _wordInPlay, No, @\". . .\", ( 160, 412, 148, 24 )\n ControlSetAlignment( _playerLabel, NSTextAlignmentRight )\n ControlSetAlignment( _playerInput, NSTextAlignmentCenter )\n ControlSetAlignment( _wordInPlay, NSTextAlignmentCenter )\n ControlSetFormat( _playerInput, @\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", YES, 8, _formatCapitalize )\n TextFieldSetTextColor( _wordLabel, fn ColorLightGray )\n TextFieldSetTextColor( _wordInPlay, fn ColorLightGray )\n TextFieldSetSelectable( _wordInPlay, No )\n // Fields for computer feedback\n scrollview _scrlView, ( 20, 60, 356, 300 ), NSBezelBorder\n textview _textView, , _scrlView, , 1\n ScrollViewSetHasVerticalScroller( _scrlView, YES )\n TextViewSetTextContainerInset( _textView, fn CGSizeMake( 3, 3 ) )\n TextSetFontWithName( _textView, @\"Menlo\", 12 )\n TextSetColor( _textView, fn colorLightGray )\n TextSetString( _textView, @\"First, enter the name of each player and press Return to confirm. ¬\n When done, press Return to start the game.\" )\n // Buttons and menus\n button _resignBtn, No, , @\"Resign\", ( 251, 15, 130, 32 )\n button _againBtn, No, , @\"New game\", ( 114, 15, 130, 32 )\n button _quitBtn, Yes, , @\"Quit\", ( 15, 15, 92, 32 )\n filemenu 1 : menu 1, , No ' Nothing to file\n editmenu 2 : menu 2, , No ' Nothing to edit\n WindowMakeFirstResponder( 1, _playerInput ) ' Activate player input field\nend fn\n\nvoid local fn LoadWords\n CFURLRef url\n CFStringRef words, string\n CFArrayRef tmp\n CFRange range\n // Fill the gWords list with just the lowercase words in unixdict\n url = fn URLWithString( @\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\" )\n words = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )\n tmp = fn StringComponentsSeparatedByCharactersInSet( ( words ), fn CharacterSetNewlineSet )\n for string in tmp\n range = fn StringRangeOfStringWithOptions( string, @\"^[a-z]+$\", NSRegularExpressionSearch )\n if range.location != NSNotFound then MutableArrayAddObject( gWords, string )\n next\nend fn\n\nvoid local fn Say(str1 as CFStringRef, str2 as CFStringRef )\n // Add strings to the computer feedback\n fn MutableStringAppendString( gTxt, str1 )\n fn MutableStringAppendString( gTxt, str2 )\n TextSetString( _textView, gTxt )\n TextScrollRangeToVisible( _textView, fn CFRangeMake( len( fn TextString( _textView ) ), 0) )\nend fn\n\nlocal fn CompareEqual( wrd1 as CFStringRef, wrd2 as CFStringRef ) as short\n NSInteger i, k\n CFStringRef a, b\n //Find the number of differences in two strings\n k = 0\n for i = 0 to len( wrd1 ) - 1\n a = mid( wrd1, i, 1 ) : b = mid( wrd2, i, 1 )\n if fn StringIsEqual( a, b ) == No then k++\n next\nend fn = k\n\n\nlocal fn ChopAndStitch( sShort as CFStringRef, sLong as CFStringRef ) as CFStringRef\n NSInteger i, k\n CFStringRef a, b\n // Find the extra letter in the long string and remove it\n k = 0\n for i = 0 to len( sLong ) - 1\n a = mid( sShort, i, 1 ) : b = mid( sLong, i, 1 )\n if fn StringIsEqual( a, b ) == No then k = i : break ' Found it\n next\n a = left( sLong, k ) : b = mid( sLong, k + 1 ) 'Removed it\nend fn = fn StringByAppendingString( a, b )\n\n\nlocal fn WordiffWords( wrd1 as CFStringRef, wrd2 as CFStringRef ) as short\n Short err = 0\n // If a letter was added or removed, the strings should be identical after\n // we remove the extra letter from the longest string.\n // If they are the same length, the strings may differ at just one place.\n select case\n case len( wrd2 ) > len( wrd1 )\n wrd2 = fn ChopAndStitch( wrd1, wrd2 )\n if fn CompareEqual( wrd1, wrd2 ) != 0 then err = 1 ' Words identical?\n case len( wrd1 ) > len( wrd2 )\n wrd1 = fn ChopAndStitch( wrd2, wrd1 )\n if fn CompareEqual( wrd1, wrd2 ) != 0 then err = 2\n case len( wrd2 ) = len( wrd1 )\n if fn CompareEqual( wrd1, wrd2 ) != 1 then err = 3 ' Only one change?\n end select\nend fn = err\n\nlocal fn CheckWord( wrd1 as CFStringRef, wrd2 as CFStringRef ) as short\n Short err = 0\n // Preliminary tests to generate error codes\n select case\n case fn StringIsEqual( wrd1, wrd2 ) : err = 1\n case len( wrd2 ) < 3 : err = 2\n case len( wrd2 ) - len( wrd1 ) > 1 : err = 3\n case len( wrd1 ) - len( wrd2 ) > 1 : err = 4\n case fn ArrayContainsObject( gUsed, wrd2 ) == Yes : err = 5\n case fn ArrayContainsObject( gWords, wrd2 ) == No : err = 6\n end select\n // Report error. If no error, check against Wordiff rules\n select err\n case 1 : fn Say( @\"Don't be silly.\", @\"\\n\" )\n case 2 : fn Say( @\"New word must be three or more letters.\", @\"\\n\" )\n case 3 : fn Say( @\"Add just one letter, please.\", @\"\\n\" )\n case 4 : fn Say( @\"Delete just one letter, please.\", @\"\\n\" )\n case 5 : fn Say( fn StringCapitalizedString( wrd2 ), @\" was already used.\\n\" )\n case 6 : fn Say( fn StringCapitalizedString( wrd2 ), @\" is not in the dictionary.\\n\")\n case 0\n err = fn WordiffWords ( wrd1, wrd2 )\n select err\n case 1 : fn Say( @\"Either change or add a letter.\", @\"\\n\" )\n case 2 : fn Say( @\"Either change or delete a letter.\", @\"\\n\" )\n case 3 : fn Say( @\"Don't change more than one letter.\", @\"\\n\")\n end select\n end select\nend fn = err\n\nvoid local fn ShowAllPossible\n CFMutableArrayRef poss\n CFStringRef wrd1, wrd2\n NSUInteger i\n // Check all words in dictionary, ignore error messages\n poss = fn MutableArrayWithCapacity( 0 )\n wrd1 = fn ControlStringValue( _wordInPlay )\n for i = 0 to fn ArrayCount( gWords ) - 1\n wrd2 = fn ArrayObjectAtIndex( gWords, i )\n if fn fabs( len( wrd1 ) - len( wrd2 ) ) < 2 ' Not too long or short?\n if len( wrd2 ) > 2 ' Has more than 2 chars?\n if fn ArrayContainsObject( gUsed, wrd2 ) == No ' Not used before?\n if ( fn WordiffWords( wrd1, wrd2 ) == 0 ) ' According to rules?\n MutableArrayAddObject( poss, wrd2 ) ' Legal, so add to the pot\n end if\n end if\n end if\n end if\n next\n // Display legal words\n fn Say( @\"\\n\", fn ControlStringValue( _playerLabel ) )\n if fn ArrayCount( poss ) > 0 ' Any words left?\n fn Say( @\" resigns, but could have chosen:\", @\"\\n\" )\n fn MutableStringAppendString( gTxt, fn ArrayComponentsJoinedByString( poss, @\", or \" ) )\n TextSetString( _textView, gTxt )\n else\n fn Say(@\" resigns, there were no words left to play. \", @\"New game?\\n\" )\n end if\n textfield _playerInput, No ' Just to be safe\nend fn\n\nvoid local fn Play\n CFStringRef old, new, name\n NSUInteger n\n // Gather the info\n name = fn ControlStringValue( _playerLabel )\n new = fn ControlStringValue( _playerInput )\n old = fn ArrayLastObject( gUsed )\n if len( new ) == 0 then exit fn ' Just to be safe\n fn Say(new, @\"\\n\" )\n if fn CheckWord( old, new ) == 0\n // Input OK, so get ready next player\n n = ( ( fn ArrayIndexOfObject( gNames, name ) + 1 ) mod fn ArrayCount( gNames ) )\n name = fn ArrayObjectAtIndex( gNames, n )\n textlabel _playerLabel, name\n textfield _wordInPlay, , new\n MutableArrayAddObject( gUsed, new )\n end if\n fn Say( name, @\" plays: \" )\n textfield _playerInput, , @\"\"\nend fn\n\nvoid local fn StartNewGame\n CFStringRef name, wrd\n NSUInteger n\n // Pick a first player\n n = rnd( fn ArrayCount( gNames ) )\n name = fn ArrayObjectAtIndex( gNames, n - 1 )\n // Pick a first word\n MutableArrayRemoveAllObjects( gUsed )\n do\n n = rnd( fn ArrayCount( gWords ) ) - 1\n wrd = fn ArrayObjectAtIndex( gWords, n )\n until ( len( wrd ) = 3 ) or ( len( wrd ) = 4 )\n MutableArrayAddObject( gUsed, wrd )\n // Update window\n ControlSetFormat( _playerInput, @\"abcdefghijklmnopqrstuvwxyz\", YES, 0, _formatLowercase )\n fn Say( @\"\\n\", @\"Word in play: \" ) : fn Say( wrd, @\"\\n\" )\n fn Say( name, @\" plays: \" )\n textfield _wordInPlay, Yes, wrd\n textlabel _playerLabel, name, (0, 370, 110, 24 )\n textlabel _playsLabel, @\"plays:\"\n textfield _playerInput, Yes\n button _againBtn, Yes\n button _resignBtn, Yes\n WindowMakeFirstResponder( 1, _playerInput )\nend fn\n\nvoid local fn AskNames\n CFStringRef name\n name = fn ControlStringValue( _playerInput )\n if len( name ) > 0 ' Another player?\n MutableArrayAddObject( gNames, name )\n fn Say( @\"Welcome, \", name )\n fn Say( @\"!\", @\"\\n\" )\n textfield _playerInput, YES, @\"\"\n else\n if fn ArrayFirstObject( gNames ) != Null ' Just to be safe\n fn StartNewGame\n end if\n end if\nend fn\n\nvoid local fn DoDialog( evt as Long, tag as Long )\n select evt\n case _btnClick\n select tag\n case _againBtn\n fn MutableStringSetString( gTxt, @\"\" )\n fn StartNewGame\n case _resignBtn\n button _resignBtn, No\n fn ShowAllPossible\n case _quitBtn : end\n end select\n case _textFieldDidEndEditing\n if fn ArrayCount( gUsed ) == 0\n fn AskNames\n else\n fn Play\n end if\n case _windowShouldClose : end\n end select\nend fn\n\non dialog fn DoDialog\n\nfn BuildInterface\nfn LoadWords\n\nhandleevents\n", "language": "FutureBasic" }, { "code": "require'general/misc/prompt'\nwordiff=: {{\n words=: cutLF tolower fread'unixdict.txt'\n c1=: prompt 'Name of contestant 1: '\n c2=: prompt 'Name of contestant 2: '\n hist=. ,word=. ({~ ?@#) (#~ 3 4 e.~ #@>) words\n echo 'First word is ',toupper;word\n echo 'each contestant must pick a new word'\n echo 'the new word must either change 1 letter or remove or add 1 letter'\n echo 'the new word cannot be an old word'\n while. do.\n next=. <tolower prompt 'Pick a new word ',c1,': '\n if. next e. hist do.\n echo next,&;' has already been picked'\n break.\n end.\n if. -. next e. words do.\n echo next,&;' is not in the dictionary'\n break.\n end.\n if. next =&#&> word do.\n if. 1~:+/d=.next~:&;word do.\n echo next,&;' differs from ',word,&;' by ',(\":d),' characters'\n break.\n end.\n else.\n if. -. */1=(-&#&>/,[:+/=/&>/)(\\:#@>) next,word do.\n echo next,&;' differs too much from ',;word\n break.\n end.\n end.\n hist=. hist,word=. next\n 'c2 c1'=. c1;c2\n end.\n echo c2,' wins'\n}}\n", "language": "J" }, { "code": " wordiff''\nName of contestant 1: Jack\nName of contestant 2: Jill\nFirst word is FLAX\neach contestant must pick a new word\nthe new word must either change 1 letter or remove or add 1 letter\nthe new word cannot be an old word\nPick a new word Jack: flak\nPick a new word Jill: flap\nPick a new word Jack: clap\nPick a new word Jill: slap\nPick a new word Jack: slam\nPick a new word Jill: slap\nslap has already been picked\nJack wins\n", "language": "J" }, { "code": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Scanner;\nimport java.util.stream.Collectors;\n\npublic final class Wordiff {\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tList<String> dictionary = Files.lines(Path.of(\"unixdict.txt\")).toList();\n\t\tList<String> starters = dictionary.stream()\n\t\t\t.filter( word -> word.length() == 3 || word.length() == 4 ).collect(Collectors.toList());\n\t\tCollections.shuffle(starters);\n\t\tList<String> wordsUsed = new ArrayList<String>();\n\t\twordsUsed.add(starters.get(0));\t\t\n\t\t\n\t\tScanner scanner = new Scanner(System.in);\n\t\tList<String> playerNames = requestPlayerNames(scanner);\t\t\n\t\tboolean playing = true;\n\t\tint playerIndex = 0;\n\t\tSystem.out.println(\"The first word is: \" + wordsUsed.get(wordsUsed.size() - 1));\t\t\n\t\t\n\t\twhile ( playing ) {\t\t\t\n\t\t\tSystem.out.println(playerNames.get(playerIndex) + \" enter your word: \");\n\t\t\tString currentWord = scanner.nextLine();\n\t\t\tif ( isWordiff(currentWord, wordsUsed, dictionary) ) {\n\t\t\t\twordsUsed.add(currentWord);\n\t\t\t\tplayerIndex = ( playerIndex == 0 ) ? 1 : 0;\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"You have lost the game, \" + playerNames.get(playerIndex));\n\t\t\t\tSystem.out.println(\"You could have entered: \" + couldHaveEntered(wordsUsed, dictionary));\n\t\t\t\tplaying = false;\n\t\t\t}\t\t\t\n\t\t}\n\t\tscanner.close();\n\t}\t\n\t\n\tprivate static boolean isWordiff(String currentWord, List<String> wordsUsed, List<String> dictionary) {\n\t\tif ( ! dictionary.contains(currentWord) || wordsUsed.contains(currentWord) ) {\n\t\t\treturn false;\n\t\t}\n\t\n\t\tString previousWord = wordsUsed.get(wordsUsed.size() - 1);\n\t\treturn isLetterChanged(previousWord, currentWord)\n\t\t\t|| isLetterRemoved(previousWord, currentWord) || isLetterAdded(previousWord, currentWord);\n\t}\n\t\n\tprivate static boolean isLetterRemoved(String previousWord, String currentWord) {\n\t\tfor ( int i = 0; i < previousWord.length(); i++ ) {\n\t\t if ( currentWord.equals(previousWord.substring(0, i) + previousWord.substring(i + 1)) ) {\n\t\t \treturn true;\n\t\t }\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate static boolean isLetterAdded(String previousWord, String currentWord) {\n\t\treturn isLetterRemoved(currentWord, previousWord);\n\t}\n\n\tprivate static boolean isLetterChanged(String previousWord, String currentWord) {\n\t\tif ( previousWord.length() != currentWord.length() ) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint differenceCount = 0;\n\t\tfor ( int i = 0; i < currentWord.length(); i++ ) {\n\t\t differenceCount += ( currentWord.charAt(i) == previousWord.charAt(i) ) ? 0 : 1;\n\t\t}\n\t\treturn differenceCount == 1;\n\t}\t\n\t\n\tprivate static List<String> couldHaveEntered(List<String> wordsUsed, List<String> dictionary) {\n\t\tList<String> result = new ArrayList<String>();\t\t\n\t for ( String word : dictionary ) {\n\t\t if ( ! wordsUsed.contains(word) && isWordiff(word, wordsUsed, dictionary) ) {\n\t\t result.add(word);\n\t\t }\n\t }\n\t return result;\n\t}\n\t\n\tprivate static List<String> requestPlayerNames(Scanner scanner) {\n\t\tList<String> playerNames = new ArrayList<String>();\n\t\tfor ( int i = 0; i < 2; i++ ) {\n\t\t\tSystem.out.print(\"Please enter the player's name: \");\t\n\t\t\tString playerName = scanner.nextLine().trim();\n\t\t\tplayerNames.add(playerName);\n\t\t}\n\t return playerNames;\n\t}\n\n}\n", "language": "Java" }, { "code": "isoneless(nw, ow) = any(i -> nw == ow[begin:i-1] * ow[i+1:end], eachindex(ow))\nisonemore(nw, ow) = isoneless(ow, nw)\nisonechanged(x, y) = length(x) == length(y) && count(i -> x[i] != y[i], eachindex(y)) == 1\nonefrom(nw, ow) = isoneless(nw, ow) || isonemore(nw, ow) || isonechanged(nw, ow)\n\nfunction askprompt(prompt)\n ans = \"\"\n while isempty(ans)\n print(prompt)\n ans = strip(readline())\n end\n return ans\nend\n\nfunction wordiff(dictfile = \"unixdict.txt\")\n wordlist = [w for w in split(read(dictfile, String), r\"\\s+\") if !occursin(r\"\\W\", w) && length(w) > 2]\n starters = [w for w in wordlist if 3 <= length(w) <= 4]\n\n timelimit = something(tryparse(Float64, askprompt(\"Time limit (min) or 0 for none: \")), 0.0)\n\n players = split(askprompt(\"Enter players' names. Separate by commas: \"), r\"\\s*,\\s*\")\n times, word = Dict(player => Float32[] for player in players), rand(starters)\n used, totalsecs, timestart = [word], timelimit * 60, time()\n while length(players) > 1\n player = popfirst!(players)\n playertimestart = time()\n newword = askprompt(\"$player, your move. The current word is $word. Your worddiff? \")\n if timestart + totalsecs > time()\n if onefrom(newword, word) && !(newword in used) && lowercase(newword) in wordlist\n println(\"Correct.\")\n push!(players, player)\n word = newword\n push!(used, newword)\n push!(times[player], time() - playertimestart)\n else\n println(\"Wordiff choice incorrect. Player $player exits game.\")\n end\n else # out of time\n println(\"Sorry, time was up. Timing ranks for remaining players:\")\n avtimes = Dict(p => isempty(times[p]) ? NaN : sum(times[p]) / length(times[p])\n for p in players)\n sort!(players, lt = (x, y) -> avtimes[x] < avtimes[y])\n foreach(p -> println(\" $p:\", lpad(avtimes[p], 10), \" seconds average\"), players)\n break\n end\n sleep(rand() * 3)\n end\n length(players) < 2 && println(\"Player $(first(players)) is the only one left, and wins the game.\")\nend\n\nwordiff()\n", "language": "Julia" }, { "code": "import httpclient, sequtils, sets, strutils, sugar\nfrom unicode import capitalize\n\nconst\n DictFname = \"unixdict.txt\"\n DictUrl1 = \"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\" # ~25K words\n DictUrl2 = \"https://raw.githubusercontent.com/dwyl/english-words/master/words.txt\" # ~470K words\n\n\ntype Dictionary = HashSet[string]\n\n\nproc loadDictionary(fname = DictFname): Dictionary =\n ## Return appropriate words from a dictionary file.\n for word in fname.lines():\n if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii\n\n\nproc loadWebDictionary(url: string): Dictionary =\n ## Return appropriate words from a dictionary web page.\n let client = newHttpClient()\n for word in client.getContent(url).splitLines():\n if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii\n\n\nproc getPlayers(): seq[string] =\n ## Return inputted ordered list of contestant names.\n try:\n stdout.write \"Space separated list of contestants: \"\n stdout.flushFile()\n result = stdin.readLine().splitWhitespace().map(capitalize)\n if result.len == 0:\n quit \"Empty list of names. Quitting.\", QuitFailure\n except EOFError:\n echo()\n quit \"Encountered end of file. Quitting.\", QuitFailure\n\n\nproc isWordiffRemoval(word, prev: string; comment = true): bool =\n ## Is \"word\" derived from \"prev\" by removing one letter?\n for i in 0..prev.high:\n if word == prev[0..<i] & prev[i+1..^1]: return true\n if comment: echo \"Word is not derived from previous by removal of one letter.\"\n result = false\n\n\nproc isWordiffInsertion(word, prev: string; comment = true): bool =\n ## Is \"word\" derived from \"prev\" by adding one letter?\n for i in 0..word.high:\n if prev == word[0..<i] & word[i+1..^1]: return true\n if comment: echo \"Word is not derived from previous by insertion of one letter.\"\n return false\n\n\nproc isWordiffChange(word, prev: string; comment = true): bool =\n ## Is \"word\" derived from \"prev\" by changing exactly one letter?\n var diffcount = 0\n for i in 0..word.high:\n diffcount += ord(word[i] != prev[i])\n if diffcount != 1:\n if comment:\n echo \"More or less than exactly one character changed.\"\n return false\n result = true\n\n\nproc isWordiff(word: string; wordiffs: seq[string]; dict: Dictionary; comment = true): bool =\n ## Is \"word\" a valid wordiff from \"wordiffs[^1]\"?\n if word notin dict:\n if comment:\n echo \"That word is not in my dictionary.\"\n return false\n if word in wordiffs:\n if comment:\n echo \"That word was already used.\"\n return false\n result = if word.len < wordiffs[^1].len: word.isWordiffRemoval(wordiffs[^1], comment)\n elif word.len > wordiffs[^1].len: word.isWordiffInsertion(wordiffs[^1], comment)\n else: word.isWordiffChange(wordiffs[^1], comment)\n\n\nproc couldHaveGot(wordiffs: seq[string]; dict: Dictionary): seq[string] =\n for word in dict - wordiffs.toHashSet:\n if word.isWordiff(wordiffs, dict, comment = false):\n result.add word\n\n\nwhen isMainModule:\n import random\n\n randomize()\n let dict = loadDictionary(DictFname)\n let dict34 = collect(newSeq):\n for word in dict:\n if word.len in [3, 4]: word\n let start = sample(dict34)\n var wordiffs = @[start]\n let players = getPlayers()\n var iplayer = 0\n var word: string\n while true:\n let name = players[iplayer]\n while true:\n stdout.write \"$1, input a wordiff from “$2”: \".format(name, wordiffs[^1])\n stdout.flushFile()\n try:\n word = stdin.readLine().strip()\n if word.len > 0: break\n except EOFError:\n quit \"Encountered end of file. Quitting.\", QuitFailure\n if word.isWordiff(wordiffs, dict):\n wordiffs.add word\n else:\n echo \"You have lost, $#.\".format(name)\n let possibleWords = couldHaveGot(wordiffs, dict)\n if possibleWords.len > 0:\n echo \"You could have used: \", possibleWords[0..min(possibleWords.high, 20)].join(\" \")\n break\n iplayer = (iplayer + 1) mod players.len\n", "language": "Nim" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse List::Util 'min';\n\nmy %cache;\nsub leven {\n my ($s, $t) = @_;\n return length($t) if $s eq '';\n return length($s) if $t eq '';\n $cache{$s}{$t} //=\n do {\n my ($s1, $t1) = (substr($s, 1), substr($t, 1));\n (substr($s, 0, 1) eq substr($t, 0, 1))\n ? leven($s1, $t1)\n : 1 + min(\n leven($s1, $t1),\n leven($s, $t1),\n leven($s1, $t ),\n );\n };\n}\n\nprint \"What is your name?\"; my $name = <STDIN>;\n$name = 'Number 6';\nsay \"What is your quest? Never mind that, I will call you '$name'\";\nsay 'Hey! I am not a number, I am a free man!';\n\nmy @starters = grep { length() < 6 } my @words = grep { /.{2,}/ } split \"\\n\", `cat unixdict.txt`;\n\nmy(%used,@possibles,$guess);\nmy $rounds = 0;\nmy $word = say $starters[ rand $#starters ];\n\nwhile () {\n say \"Word in play: $word\";\n $used{$word} = 1;\n @possibles = ();\n for my $w (@words) {\n next if abs(length($word) - length($w)) > 1;\n push @possibles, $w if leven($word, $w) == 1 and ! defined $used{$w};\n }\n print \"Your word? \"; $guess = <STDIN>; chomp $guess;\n last unless grep { $guess eq $_ } @possibles;\n $rounds++;\n $word = $guess;\n}\n\nmy $already = defined $used{$guess} ? \" '$guess' was already played but\" : '';\n\nif (@possibles) { say \"\\nSorry $name,${already} one of <@possibles> would have continued the game.\" }\nelse { say \"\\nGood job $name,${already} there were no possible words to play.\" }\nsay \"You made it through $rounds rounds.\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">-- demo\\rosetta\\Wordiff.exw</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">playerset</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">current</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">help</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">quit</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">hframe</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">timer</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">t0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Wordiff game\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">help_text</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n Allows single or multi-player modes.\n Enter eg \"Pete\" to play every round yourself,\n \"Computer\" for the computer to play itself,\n \"Pete,Computer\" (or vice versa) to play against the computer,\n \"Pete,Sue\" for a standard two-payer game, or\n \"Pete,Computer,Sue,Computer\" for auto-plays between each human.\n Words must be 3 letters or more, and present in the dictionary,\n and not already used. You must key return (not tab) to finish\n entering your move. The winner is the fastest average time, if\n the timer is running (/non-zero), otherwise play continues\n until player elimination leaves one (or less) remaining.\n NB: Pressing tab or clicking on help will restart or otherwise\n mess up the gameplay.\n \"\"\"</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">help_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandln</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupMessage</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">help_text</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetFocus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">over2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">less5</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)<</span><span style=\"color: #000000;\">5</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">words</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">unix_dict</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">over2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">used</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">word</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">lw</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">eliminated</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">times</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">averages</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">player</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">levenshtein1</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">false</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">lw</span><span style=\"color: #0000FF;\">)<=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">costs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">lw</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">costs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">newcost</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">pj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">costs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">ne</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">],</span>\n <span style=\"color: #000000;\">nc</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">newcost</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">ne</span>\n <span style=\"color: #000000;\">pj</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">pj</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cj</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">nc</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000000;\">costs</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">j</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">pj</span>\n <span style=\"color: #000000;\">newcost</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cj</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">costs</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]==</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">game_over</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"GAME OVER:\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">valids</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"You could have had \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\", \"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">valids</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">winner</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"nobody\"</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">best</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">player</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span> <span style=\"color: #000000;\">msg</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">eliminated</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\": eliminated\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">average</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">averages</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">average</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\": no times\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">msg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\": %.3f\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">average</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">best</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">average</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">best</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">winner</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">player</span>\n <span style=\"color: #000000;\">best</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">average</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">msg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"And the winner is: \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">winner</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">timer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"RUN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">score</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">times</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">times</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">averages</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">times</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">])/</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">times</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">used</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">word</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">move</span>\n <span style=\"color: #000000;\">lw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">levenshtein1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">current</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Current word: \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">advance_player</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">player</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">))+</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">eliminated</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #008000;\">\"'s turn:\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupRefreshChildren</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">autoplay</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"no more moves possible\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">game_over</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">exit</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">proper</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">])!=</span><span style=\"color: #008000;\">\"Computer\"</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">move</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">))]</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s's move: %s\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">score</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">advance_player</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">new_game</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bStart</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">bActive</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">bActive</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">bActive</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">bActive</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">bStart</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">w34</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">less5</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rand</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w34</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">word</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">w34</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">lw</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">used</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #000000;\">valid</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">filter</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">levenshtein1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">w34</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">current</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Current word: \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]&</span><span style=\"color: #008000;\">\"'s turn:\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupRefreshChildren</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"REMOVEITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ALL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Initial word: \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">word</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">eliminated</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">times</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">({},</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">averages</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">t0</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">t1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">timer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"RUN\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">autoplay</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">players_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandln</span> <span style=\"color: #000080;font-style:italic;\">/*playerset*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">players</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">split</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">playerset</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\",\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">player</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">new_game</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">playtime_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*playtime*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">t</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">t</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Remaining: %.1fs\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupRefreshChildren</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">focus_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*input*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">new_game</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">verify_move</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">move</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUE\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">okstr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"ok\"</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">okstr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"already used\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">words</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">okstr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"not in dictionary\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">valid</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">okstr</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"more than one change\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">used</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">used</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">okstr</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008000;\">\", player eliminated\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"APPENDITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s's move: %s %s\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">okstr</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TOPITEM\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">ok</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">eliminated</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">player</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">players</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #7060A8;\">sum</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">eliminated</span><span style=\"color: #0000FF;\">)<=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">game_over</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">score</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">move</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">advance_player</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">autoplay</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">timer_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*timer*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">e</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">time</span><span style=\"color: #0000FF;\">()-</span><span style=\"color: #000000;\">t0</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">t</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Remaining: 0s\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">game_over</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Remaining: %.1fs\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">t</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">e</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">quit_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*dlg*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_CR</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">Ihandln</span> <span style=\"color: #000000;\">focus</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetFocus</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">focus</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">playerset</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetFocus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">focus</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">playtime</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupSetFocus</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">new_game</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">focus</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">input</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">verify_move</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_F1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">help_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_cC</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"COUNT\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">hist</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">hist</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetAttributeId</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">hist</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hist</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">Ihandln</span> <span style=\"color: #000000;\">clip</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupClipboard</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">clip</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TEXT\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hist</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">clip</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDestroy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">clip</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">playerset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`EXPAND=HORIZONTAL`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">playtime</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`SPIN=Yes, SPINMIN=0, RASTERSIZE=48x`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">playerset</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #008000;\">\"KILLFOCUS_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"players_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VALUECHANGED_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"playtime_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">turn</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"turn\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"ACTIVE=NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">input</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupText</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL, ACTIVE=NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"GETFOCUS_CB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"focus_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">current</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Current word:\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"EXPAND=HORIZONTAL\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">remain</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Remaining time:0s\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"VISIBLE=NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">history</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupList</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"VISIBLELINES=10, EXPAND=YES, CANFOCUS=NO\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">hframe</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupFrame</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">history</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE=History, PADDING=5x4\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">help</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Help (F1)\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"help_cb\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"PADDING=5x4\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">quit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupButton</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Close\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"quit_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000000;\">timer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupTimer</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"timer_cb\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">buttons</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #7060A8;\">IupFill</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">help</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupFill</span><span style=\"color: #0000FF;\">(),</span><span style=\"color: #000000;\">quit</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">IupFill</span><span style=\"color: #0000FF;\">()}</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">acp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"ALIGNMENT=ACENTER, PADDING=5\"</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">settings</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Contestant name(s)\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">playerset</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #7060A8;\">IupLabel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"Timer (seconds)\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">playtime</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">acp</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">currbox</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">current</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">remain</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">acp</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">numbox</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">turn</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">input</span><span style=\"color: #0000FF;\">},</span><span style=\"color: #000000;\">acp</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">btnbox</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupHbox</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">buttons</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"PADDING=40, NORMALIZESIZE=BOTH\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">vbox</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupVbox</span><span style=\"color: #0000FF;\">({</span><span style=\"color: #000000;\">settings</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">currbox</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">numbox</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">hframe</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">btnbox</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #008000;\">\"GAP=5,MARGIN=5x5\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">vbox</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">`TITLE=\"%s\", SIZE=500x220`</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"K_ANY\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "# -*- coding: utf-8 -*-\n\nfrom typing import List, Tuple, Dict, Set\nfrom itertools import cycle, islice\nfrom collections import Counter\nimport re\nimport random\nimport urllib\n\ndict_fname = 'unixdict.txt'\ndict_url1 = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' # ~25K words\ndict_url2 = 'https://raw.githubusercontent.com/dwyl/english-words/master/words.txt' # ~470K words\n\nword_regexp = re.compile(r'^[a-z]{3,}$') # reduce dict words to those of three or more a-z characters.\n\n\ndef load_dictionary(fname: str=dict_fname) -> Set[str]:\n \"Return appropriate words from a dictionary file\"\n with open(fname) as f:\n return {lcase for lcase in (word.strip().lower() for word in f)\n if word_regexp.match(lcase)}\n\ndef load_web_dictionary(url: str) -> Set[str]:\n \"Return appropriate words from a dictionary web page\"\n words = urllib.request.urlopen(url).read().decode().strip().lower().split()\n return {word for word in words if word_regexp.match(word)}\n\n\ndef get_players() -> List[str]:\n \"Return inputted ordered list of contestant names.\"\n names = input('Space separated list of contestants: ')\n return [n.capitalize() for n in names.strip().split()]\n\ndef is_wordiff(wordiffs: List[str], word: str, dic: Set[str], comment=True) -> bool:\n \"Is word a valid wordiff from wordiffs[-1] ?\"\n if word not in dic:\n if comment:\n print('That word is not in my dictionary')\n return False\n if word in wordiffs:\n if comment:\n print('That word was already used.')\n return False\n if len(word) < len(wordiffs[-1]):\n return is_wordiff_removal(word, wordiffs[-1], comment)\n elif len(word) > len(wordiffs[-1]):\n return is_wordiff_insertion(word, wordiffs[-1], comment)\n\n return is_wordiff_change(word, wordiffs[-1], comment)\n\n\ndef is_wordiff_removal(word: str, prev: str, comment=True) -> bool:\n \"Is word derived from prev by removing one letter?\"\n ...\n ans = word in {prev[:i] + prev[i+1:] for i in range(len(prev))}\n if not ans:\n if comment:\n print('Word is not derived from previous by removal of one letter.')\n return ans\n\n\ndef is_wordiff_insertion(word: str, prev: str, comment=True) -> bool:\n \"Is word derived from prev by adding one letter?\"\n diff = Counter(word) - Counter(prev)\n diffcount = sum(diff.values())\n if diffcount != 1:\n if comment:\n print('More than one character insertion difference.')\n return False\n\n insert = list(diff.keys())[0]\n ans = word in {prev[:i] + insert + prev[i:] for i in range(len(prev) + 1)}\n if not ans:\n if comment:\n print('Word is not derived from previous by insertion of one letter.')\n return ans\n\n\ndef is_wordiff_change(word: str, prev: str, comment=True) -> bool:\n \"Is word derived from prev by changing exactly one letter?\"\n ...\n diffcount = sum(w != p for w, p in zip(word, prev))\n if diffcount != 1:\n if comment:\n print('More or less than exactly one character changed.')\n return False\n return True\n\ndef could_have_got(wordiffs: List[str], dic: Set[str]):\n return (word for word in (dic - set(wordiffs))\n if is_wordiff(wordiffs, word, dic, comment=False))\n\nif __name__ == '__main__':\n dic = load_web_dictionary(dict_url2)\n dic_3_4 = [word for word in dic if len(word) in {3, 4}]\n start = random.choice(dic_3_4)\n wordiffs = [start]\n players = get_players()\n for name in cycle(players):\n word = input(f\"{name}: Input a wordiff from {wordiffs[-1]!r}: \").strip()\n if is_wordiff(wordiffs, word, dic):\n wordiffs.append(word)\n else:\n print(f'YOU HAVE LOST {name}!')\n print(\"Could have used:\",\n ', '.join(islice(could_have_got(wordiffs, dic), 10)), '...')\n break\n", "language": "Python" }, { "code": "my @words = 'unixdict.txt'.IO.slurp.lc.words.grep(*.chars > 2);\n\nmy @small = @words.grep(*.chars < 6);\n\nuse Text::Levenshtein;\n\nmy ($rounds, $word, $guess, @used, @possibles) = 0;\n\nloop {\n my $lev;\n $word = @small.pick;\n hyper for @words -> $this {\n next if ($word.chars - $this.chars).abs > 1;\n last if ($lev = distance($word, $this)[0]) == 1;\n }\n last if $lev;\n}\n\nmy $name = ',';\n\n#[[### Entirely unnecessary and unuseful \"chatty repartee\" but is required by the task\n\nrun 'clear';\n$name = prompt \"Hello player one, what is your name? \";\nsay \"Cool. I'm going to call you Gomer.\";\n$name = ' Gomer,';\nsleep 1;\nsay \"\\nPlayer two, what is your name?\\nOh wait, this isn't a \\\"specified number of players\\\" game...\";\nsleep 1;\nsay \"Nevermind.\\n\";\n\n################################################################################]]\n\nloop {\n say \"Word in play: $word\";\n push @used, $word;\n @possibles = @words.hyper.map: -> $this {\n next if ($word.chars - $this.chars).abs > 1;\n $this if distance($word, $this)[0] == 1 and $this ∉ @used;\n }\n $guess = prompt \"your word? \";\n last unless $guess ∈ @possibles;\n ++$rounds;\n say qww<Ok! Woot! 'Way to go!' Nice! 👍 😀>.pick ~ \"\\n\";\n $word = $guess;\n}\n\nmy $already = ($guess ∈ @used) ?? \" $guess was already played but\" !! '';\n\nif @possibles {\n say \"\\nOops. Sorry{$name}{$already} one of [{@possibles}] would have continued the game.\"\n} else {\n say \"\\nGood job{$name}{$already} there were no possible words to play.\"\n}\nsay \"You made it through $rounds rounds.\";\n", "language": "Raku" }, { "code": "/*REXX program acts as a host and allows two or more people to play the WORDIFF game.*/\nsignal on halt /*allow the user(s) to halt the game. */\nparse arg iFID seed . /*obtain optional arguments from the CL*/\nif iFID=='' | iFID==\",\" then iFID='unixdict.txt' /*Not specified? Then use the default.*/\nif datatype(seed, 'W') then call random ,,seed /*If \" \" \" \" seed. */\ncall read\ncall IDs\nfirst= random(1, min(100000, starters) ) /*get a random start word for the game.*/\nlist= $$$.first\nsay; say eye \"OK, let's play the WORDIFF game.\"; say; say\n do round=1\n do player=1 for players\n call show; ou= o; upper ou\n call CBLF word(names, player)\n end /*players*/\n end /*round*/\n\nhalt: say; say; say eye 'The WORDIFF game has been halted.'\ndone: exit 0 /*stick a fork in it, we're all done. */\nquit: say; say; say eye 'The WORDDIF game is quitting.'; signal done\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nisMix: return datatype(arg(1), 'M') /*return unity if arg has mixed letters*/\nser: say; say eye '***error*** ' arg(1).; say; return /*issue error message. */\nlast: parse arg y; return word(y, words(y) ) /*get last word in list.*/\nover: call ser 'word ' _ x _ arg(1); say eye 'game over,' you; signal done /*game over*/\nshow: o= last(list); say; call what; say; L= length(o); return\nverE: m= 0; do v=1 for L; m= m + (substr(ou,v,1)==substr(xu,v,1)); end; return m==L-1\nverL: do v=1 for L; if space(overlay(' ', ou, v), 0)==xu then return 1; end; return 0\nverG: do v=1 for w; if space(overlay(' ', xu, v), 0)==ou then return 1; end; return 0\nwhat: say eye 'The current word in play is: ' _ o _; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nCBLF: parse arg you /*ask carbon-based life form for a word*/\n do getword=0 by 0 until x\\==''\n say eye \"What's your word to be played, \" you'?'\n parse pull x; x= space(x); #= words(x); if #==0 then iterate; w= length(x)\n if #>1 then do; call ser 'too many words given: ' x\n x=; iterate getword\n end\n if \\isMix(x) then do; call ser 'the name' _ x _ \" isn't alphabetic\"\n x=; iterate getword\n end\n end /*getword*/\n\n if wordpos(x, list)>0 then call over \" has already been used\"\n xu= x; upper xu /*obtain an uppercase version of word. */\n if \\@.xu then call over \" doesn't exist in the dictionary: \" iFID\n if length(x) <3 then call over \" must be at least three letters long.\"\n if w <L then if \\verL() then call over \" isn't a legal letter deletion.\"\n if w==L then if \\verE() then call over \" isn't a legal letter substitution.\"\n if w >L then if \\verG() then call over \" isn't a legal letter addition.\"\n list= list x /*add word to the list of words used. */\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nIDs: ?= \"Enter the names of the people that'll be playing the WORDIFF game (or Quit):\"\n names= /*start with a clean slate (of names). */\n do getIDs=0 by 0 until words(names)>1\n say; say eye ?\n parse pull ids; ids= space( translate(ids, , ',') ) /*elide any commas. */\n if ids=='' then iterate; q= ids; upper q /*use uppercase QUIT*/\n if abbrev('QUIT', q, 1) then signal quit\n do j=1 for words(ids); x= word(ids, j)\n if \\isMix(x) then do; call ser 'the name' _ x _ \" isn't alphabetic\"\n names=; iterate getIDs\n end\n if wordpos(x, names)>0 then do; call ser 'the name' _ x _ \" is already taken\"\n names=; iterate getIDs\n end\n names= space(names x)\n end /*j*/\n end /*getIDs*/\n say\n players= words(names)\n do until ans\\==''\n say eye 'The ' players \" player's names are: \" names\n say eye 'Is this correct?'; pull ans; ans= space(ans)\n end /*until*/\n yeahs= 'yah yeah yes ja oui si da'; upper yeahs\n do ya=1 for words(yeahs)\n if abbrev( word(yeahs, ya), ans, 2) | ans=='Y' then return\n end /*ya*/\n call IDS; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nread: _= '───'; eye= copies('─', 8) /*define a couple of eye catchers. */\n say; say eye eye eye 'Welcome to the WORDIFF word game.' eye eye eye; say\n @.= 0; starters= 0\n do r=1 while lines(iFID)\\==0 /*read each word in the file (word=X).*/\n x= strip(linein(iFID)) /*pick off a word from the input line. */\n if \\isMix(x) then iterate /*Not a suitable word for WORDIFF? Skip*/\n y= x; upper x /*pick off a word from the input line. */\n @.x= 1; L= length(x) /*set a semaphore for uppercased word. */\n if L<3 | L>4 then iterate /*only use short words for the start. */\n starters= starters + 1 /*bump the count of starter words. */\n $$$.starters= y /*save short words for the starter word*/\n end /*#*/\n if r>100 & starters> 10 then return /*is the dictionary satisfactory ? */\n call ser 'Dictionary file ' _ iFID _ \"wasn't found or isn't satisfactory.\"; exit 13\n", "language": "REXX" }, { "code": "import os\nimport rand\nimport time\nimport arrays\n\nfn is_wordiff(guesses []string, word string, dict []string) bool {\n if word !in dict {\n println('That word is not in the dictionary')\n return false\n }\n if word in guesses {\n println('That word has already been used')\n return false\n }\n if word.len < guesses[guesses.len-1].len {\n return is_wordiff_removal(word, guesses[guesses.len-1])\n } else if word.len > guesses[guesses.len-1].len {\n return is_wordiff_insertion(word, guesses[guesses.len-1])\n }\n return is_wordiff_change(word,guesses[guesses.len-1])\n}\nfn is_wordiff_removal(new_word string, last_word string) bool {\n for i in 0..last_word.len {\n if new_word == last_word[..i] + last_word[i+1..] {\n return true\n }\n }\n println('Word is not derived from previous by removal of one letter')\n return false\n}\nfn is_wordiff_insertion(new_word string, last_word string) bool {\n if new_word.len > last_word.len+1 {\n println('More than one character insertion difference')\n return false\n }\n mut a := new_word.split('')\n b := last_word.split('')\n for c in b {\n idx := a.index(c)\n if idx >=0 {\n a.delete(idx)\n }\n }\n if a.len >1 {\n println('Word is not derived from previous by insertion of one letter')\n return false\n }\n return true\n}\nfn is_wordiff_change(new_word string, last_word string) bool {\n mut diff:=0\n for i,c in new_word {\n if c != last_word[i] {\n diff++\n }\n }\n if diff != 1 {\n println('More or less than exactly one character changed')\n return false\n }\n return true\n}\n\nfn main() {\n words := os.read_lines('unixdict.txt')?\n time_limit := os.input('Time limit (sec) or 0 for none: ').int()\n players := os.input('Please enter player names, separated by commas: ').split(',')\n\n dic_3_4 := words.filter(it.len in [3,4])\n mut wordiffs := rand.choose<string>(dic_3_4,1)?\n mut timing := [][]f64{len: players.len}\n start := time.now()\n mut turn_count := 0\n for {\n turn_start := time.now()\n word := os.input('${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ')\n if time_limit != 0.0 && time.since(start).seconds()>time_limit{\n println('TIMES UP ${players[turn_count%players.len]}')\n break\n } else {\n if is_wordiff(wordiffs, word, words) {\n wordiffs<<word\n }else{\n timing[turn_count%players.len] << time.since(turn_start).seconds()\n println('YOU HAVE LOST ${players[turn_count%players.len]}')\n break\n }\n }\n timing[turn_count%players.len] << time.since(turn_start).seconds()\n turn_count++\n }\n println('Timing ranks:')\n for i,p in timing {\n sum := arrays.sum<f64>(p) or {0}\n println(' ${players[i]}: ${sum/p.len:10.3 f} seconds average')\n }\n}\n", "language": "V-(Vlang)" }, { "code": "import \"random\" for Random\nimport \"./ioutil\" for File, Input\nimport \"./str\" for Str\nimport \"./sort\" for Find\n\nvar rand = Random.new()\nvar words = File.read(\"unixdict.txt\").trim().split(\"\\n\")\n\nvar player1 = Input.text(\"Player 1, please enter your name : \", 1)\nvar player2 = Input.text(\"Player 2, please enter your name : \", 1)\nif (player2 == player1) player2 = player2 + \"2\"\n\nvar words3or4 = words.where { |w| w.count == 3 || w.count == 4 }.toList\nvar n = words3or4.count\nvar firstWord = words3or4[rand.int(n)]\nvar prevLen = firstWord.count\nvar prevWord = firstWord\nvar used = []\nvar player = player1\nSystem.print(\"\\nThe first word is %(firstWord)\\n\")\nwhile (true) {\n var word = Str.lower(Input.text(\"%(player), enter your word : \", 1))\n var len = word.count\n var ok = false\n if (len < 3) {\n System.print(\"Words must be at least 3 letters long.\")\n } else if (Find.first(words, word) == -1) {\n System.print(\"Not in dictionary.\")\n } else if (used.contains(word)) {\n System.print(\"Word has been used before.\")\n } else if (word == prevWord) {\n System.print(\"You must change the previous word.\")\n } else if (len == prevLen) {\n var changes = 0\n for (i in 0...len) {\n if (word[i] != prevWord[i]) {\n changes = changes + 1\n }\n }\n if (changes > 1) {\n System.print(\"Only one letter can be changed.\")\n } else ok = true\n } else if (len == prevLen + 1) {\n var addition = false\n var temp = word\n for (i in 0...prevLen) {\n if (word[i] != prevWord[i]) {\n addition = true\n temp = Str.delete(temp, i)\n if (temp == prevWord) {\n ok = true\n }\n break\n }\n }\n if (!addition) ok = true\n if (!ok) System.print(\"Invalid addition.\")\n } else if (len == prevLen - 1) {\n var deletion = false\n var temp = prevWord\n for (i in 0...len) {\n if (word[i] != prevWord[i]) {\n deletion = true\n temp = Str.delete(temp, i)\n if (temp == word) {\n ok = true\n }\n break\n }\n }\n if (!deletion) ok = true\n if (!ok) System.print(\"Invalid deletion.\")\n } else {\n System.print(\"Invalid change.\")\n }\n if (ok) {\n prevLen = word.count\n prevWord = word\n used.add(word)\n player = (player == player1) ? player2 : player1\n } else {\n System.print(\"So, sorry %(player), you've lost!\")\n return\n }\n}\n", "language": "Wren" } ]
Wordiff
[ { "code": "---\nfrom: http://rosettacode.org/wiki/World_Cup_group_stage\n", "language": "00-META" }, { "code": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. &nbsp; Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. &nbsp; Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group [[wp:Round-robin tournament|plays all three other teams once]]. &nbsp; The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. &nbsp; The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* &nbsp; A win is worth three points.\n:::* &nbsp; A draw/tie is worth one point. \n:::* &nbsp; A loss is worth zero points.\n\n\n;Task:\n:* &nbsp; Generate all possible outcome combinations for the six group stage games. &nbsp; With three possible outcomes for each game there should be 3<sup>6</sup> = 729 of them. \n:* &nbsp; Calculate the standings points for each team with each combination of outcomes. \n:* &nbsp; Show a histogram (graphical, &nbsp; ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. &nbsp; We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n<small>''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. &nbsp; Oddly enough, there is no way to get 8 points at all.''</small>\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V games = [‘12’, ‘13’, ‘14’, ‘23’, ‘24’, ‘34’]\nV results = ‘000000’\n\nF numberToBase(=n, b)\n I n == 0\n R ‘0’\n V digits = ‘’\n L n != 0\n digits ‘’= String(Int(n % b))\n n I/= b\n R reversed(digits)\n\nF nextResult()\n I :results == ‘222222’\n R 0B\n V res = Int(:results, radix' 3) + 1\n :results = numberToBase(res, 3).zfill(6)\n R 1B\n\nV points = [[0] * 10] * 4\nL\n V records = [0] * 4\n L(i) 0 .< games.len\n S results[i]\n ‘2’\n records[games[i][0].code - ‘1’.code] += 3\n ‘1’\n records[games[i][0].code - ‘1’.code]++\n records[games[i][1].code - ‘1’.code]++\n ‘0’\n records[games[i][1].code - ‘1’.code] += 3\n\n records.sort()\n L(i) 4\n points[i][records[i]]++\n\n I !nextResult()\n L.break\n\nprint(|‘POINTS 0 1 2 3 4 5 6 7 8 9\n -------------------------------------------------------------’)\nV places = [‘1st’, ‘2nd’, ‘3rd’, ‘4th’]\nL(i) 4\n print(places[i], end' ‘ place ’)\n L(j) 10\n print(‘#<5’.format(points[3 - i][j]), end' ‘’)\n print()\n", "language": "11l" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n// to supply to qsort\nint compare(const void *a, const void *b) {\n int int_a = *((int *)a);\n int int_b = *((int *)b);\n return (int_a > int_b) - (int_a < int_b);\n}\n\nchar results[7];\nbool next_result() {\n char *ptr = results + 5;\n int num = 0;\n size_t i;\n\n // check if the space has been examined\n if (strcmp(results, \"222222\") == 0) {\n return false;\n }\n\n // translate the base 3 string back to a base 10 integer\n for (i = 0; results[i] != 0; i++) {\n int d = results[i] - '0';\n num = 3 * num + d;\n }\n\n // to the next value to process\n num++;\n\n // write the base 3 string (fixed width)\n while (num > 0) {\n int rem = num % 3;\n num /= 3;\n *ptr-- = rem + '0';\n }\n // zero fill the remainder\n while (ptr > results) {\n *ptr-- = '0';\n }\n\n return true;\n}\n\nchar *games[6] = { \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" };\nchar *places[4] = { \"1st\", \"2nd\", \"3rd\", \"4th\" };\nint main() {\n int points[4][10];\n size_t i, j;\n\n strcpy(results, \"000000\");\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 10; j++) {\n points[i][j] = 0;\n }\n }\n\n do {\n int records[] = { 0, 0, 0, 0 };\n\n for (i = 0; i < 6; i++) {\n switch (results[i]) {\n case '2':\n records[games[i][0] - '1'] += 3;\n break;\n case '1':\n records[games[i][0] - '1']++;\n records[games[i][1] - '1']++;\n break;\n case '0':\n records[games[i][1] - '1'] += 3;\n break;\n default:\n break;\n }\n }\n\n qsort(records, 4, sizeof(int), compare);\n for (i = 0; i < 4; i++) {\n points[i][records[i]]++;\n }\n } while (next_result());\n\n printf(\"POINTS 0 1 2 3 4 5 6 7 8 9\\n\");\n printf(\"-----------------------------------------------------------\\n\");\n for (i = 0; i < 4; i++) {\n printf(\"%s place\", places[i]);\n for (j = 0; j < 10; j++) {\n printf(\"%5d\", points[3 - i][j]);\n }\n printf(\"\\n\");\n }\n\n return 0;\n}\n", "language": "C" }, { "code": "#include <algorithm>\n#include <array>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nstd::array<std::string, 6> games{ \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" };\nstd::string results = \"000000\";\n\nint fromBase3(std::string num) {\n int out = 0;\n for (auto c : num) {\n int d = c - '0';\n out = 3 * out + d;\n }\n return out;\n}\n\nstd::string toBase3(int num) {\n std::stringstream ss;\n\n while (num > 0) {\n int rem = num % 3;\n num /= 3;\n ss << rem;\n }\n\n auto str = ss.str();\n std::reverse(str.begin(), str.end());\n return str;\n}\n\nbool nextResult() {\n if (results == \"222222\") {\n return false;\n }\n\n auto res = fromBase3(results);\n\n std::stringstream ss;\n ss << std::setw(6) << std::setfill('0') << toBase3(res + 1);\n results = ss.str();\n\n return true;\n}\n\nint main() {\n std::array<std::array<int, 10>, 4> points;\n for (auto &row : points) {\n std::fill(row.begin(), row.end(), 0);\n }\n\n do {\n std::array<int, 4> records {0, 0, 0, 0 };\n\n for (size_t i = 0; i < games.size(); i++) {\n switch (results[i]) {\n case '2':\n records[games[i][0] - '1'] += 3;\n break;\n case '1':\n records[games[i][0] - '1']++;\n records[games[i][1] - '1']++;\n break;\n case '0':\n records[games[i][1] - '1'] += 3;\n break;\n default:\n break;\n }\n }\n\n std::sort(records.begin(), records.end());\n for (size_t i = 0; i < records.size(); i++) {\n points[i][records[i]]++;\n }\n } while (nextResult());\n\n std::cout << \"POINTS 0 1 2 3 4 5 6 7 8 9\\n\";\n std::cout << \"-------------------------------------------------------------\\n\";\n std::array<std::string, 4> places{ \"1st\", \"2nd\", \"3rd\", \"4th\" };\n for (size_t i = 0; i < places.size(); i++) {\n std::cout << places[i] << \" place\";\n for (size_t j = 0; j < points[i].size(); j++) {\n std::cout << std::setw(5) << points[3 - i][j];\n }\n std::cout << '\\n';\n }\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing static System.Console;\nusing static System.Linq.Enumerable;\n\nnamespace WorldCupGroupStage\n{\n public static class WorldCupGroupStage\n {\n static int[][] _histogram;\n\n static WorldCupGroupStage()\n {\n int[] scoring = new[] { 0, 1, 3 };\n\n _histogram = Repeat<Func<int[]>>(()=>new int[10], 4).Select(f=>f()).ToArray();\n\n var teamCombos = Range(0, 4).Combinations(2).Select(t2=>t2.ToArray()).ToList();\n\n foreach (var results in Range(0, 3).CartesianProduct(6))\n {\n var points = new int[4];\n\n foreach (var (result, teams) in results.Zip(teamCombos, (r, t) => (r, t)))\n {\n points[teams[0]] += scoring[result];\n points[teams[1]] += scoring[2 - result];\n }\n\n foreach(var (p,i) in points.OrderByDescending(a => a).Select((p,i)=>(p,i)))\n _histogram[i][p]++;\n }\n }\n\n // https://gist.github.com/martinfreedman/139dd0ec7df4737651482241e48b062f\n\n static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) =>\n seqs.Aggregate(Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s))));\n\n static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) =>\n Repeat(seq, repeat).CartesianProduct();\n\n static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) =>\n seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));\n\n static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) =>\n seq.Combinations().Where(s => s.Count() == numItems);\n\n private static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }\n\n static new string ToString()\n {\n var sb = new StringBuilder();\n\n var range = String.Concat(Range(0, 10).Select(i => $\"{i,-3} \"));\n sb.AppendLine($\"Points : {range}\");\n\n var u = String.Concat(Repeat(\"─\", 40+13));\n sb.AppendLine($\"{u}\");\n\n var places = new[] { \"First\", \"Second\", \"Third\", \"Fourth\" };\n foreach (var row in _histogram.Select((r, i) => (r, i)))\n {\n sb.Append($\"{places[row.i],-6} place: \");\n foreach (var standing in row.r)\n sb.Append($\"{standing,-3} \");\n sb.Append(\"\\n\");\n }\n\n return sb.ToString();\n }\n\n static void Main(string[] args)\n {\n Write(ToString());\n Read();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(defun histo ()\n (let ((scoring (vector 0 1 3))\n (histo (list (vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)\n (vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)))\n (team-combs (vector '(0 1) '(0 2) '(0 3) '(1 2) '(1 3) '(2 3)))\n (single-tupel)\n (sum))\n ; six nested dotimes produces the tupels of the cartesian product of\n ; six lists like '(0 1 2), but without to store all tuples in a list\n (dotimes (x0 3) (dotimes (x1 3) (dotimes (x2 3)\n (dotimes (x3 3) (dotimes (x4 3) (dotimes (x5 3)\n (setf single-tupel (vector x0 x1 x2 x3 x4 x5))\n (setf sum (vector 0 0 0 0))\n (dotimes (i (length single-tupel))\n (setf (elt sum (first (elt team-combs i)))\n (+ (elt sum (first (elt team-combs i)))\n (elt scoring (elt single-tupel i))))\n\n (setf (elt sum (second (elt team-combs i)))\n (+ (elt sum (second (elt team-combs i)))\n (elt scoring (- 2 (elt single-tupel i))))))\n\n (dotimes (i (length (sort sum #'<)))\n (setf (elt (nth i histo) (elt sum i))\n (1+ (elt (nth i histo) (elt sum i)))))\n ))))))\n (reverse histo)))\n\n; friendly output\n(dolist (el (histo))\n (dotimes (i (length el))\n (format t \"~3D \" (aref el i)))\n (format t \"~%\"))\n", "language": "Common-Lisp" }, { "code": "void main() {\n import std.stdio, std.range, std.array, std.algorithm, combinations3;\n\n immutable scoring = [0, 1, 3];\n /*immutable*/ auto r3 = [0, 1, 2];\n immutable combs = 4.iota.array.combinations(2).array;\n uint[10][4] histo;\n\n foreach (immutable results; cartesianProduct(r3, r3, r3, r3, r3, r3)) {\n int[4] s;\n foreach (immutable r, const g; [results[]].zip(combs)) {\n s[g[0]] += scoring[r];\n s[g[1]] += scoring[2 - r];\n }\n\n foreach (immutable i, immutable v; s[].sort().release)\n histo[i][v]++;\n }\n writefln(\"%(%s\\n%)\", histo[].retro);\n}\n", "language": "D" }, { "code": "import core.stdc.stdio, std.range, std.array, std.algorithm, combinations3;\n\nimmutable uint[2][6] combs = 4u.iota.array.combinations(2).array;\n\nvoid main() nothrow @nogc {\n immutable uint[3] scoring = [0, 1, 3];\n uint[10][4] histo;\n\n foreach (immutable r0; 0 .. 3)\n foreach (immutable r1; 0 .. 3)\n foreach (immutable r2; 0 .. 3)\n foreach (immutable r3; 0 .. 3)\n foreach (immutable r4; 0 .. 3)\n foreach (immutable r5; 0 .. 3) {\n uint[4] s;\n foreach (immutable i, immutable r; [r0, r1, r2, r3, r4, r5]) {\n s[combs[i][0]] += scoring[r];\n s[combs[i][1]] += scoring[2 - r];\n }\n\n foreach (immutable i, immutable v; s[].sort().release)\n histo[i][v]++;\n }\n\n foreach_reverse (const ref h; histo) {\n foreach (immutable x; h)\n printf(\"%u \", x);\n printf(\"\\n\");\n }\n}\n", "language": "D" }, { "code": "import system'routines;\nimport extensions;\n\npublic singleton program\n{\n static games := new string[]{\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"};\n\n static results := \"000000\";\n\n nextResult()\n {\n var s := results;\n\n if (results==\"222222\") { ^ false };\n\n results := (results.toInt(3) + 1).toString(3).padLeft($48, 6);\n\n ^ true\n }\n\n function()\n {\n var points := IntMatrix.allocate(4, 10);\n\n int counter := 0;\n do\n {\n var records := new int[]{0,0,0,0};\n\n for(int i := 0; i < 6; i += 1)\n {\n var r := results[i];\n r =>\n \"2\" { records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 3 }\n \"1\" {\n records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 1;\n records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 1\n }\n \"0\" { records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 3 };\n };\n\n records := records.ascendant();\n\n for(int i := 0; i <= 3; i += 1)\n {\n points[i][records[i]] := points[i][records[i]] + 1\n }\n }\n while(program.nextResult());\n\n new Range(0, 4).zipForEach(new string[]{\"1st\", \"2nd\", \"3rd\", \"4th\"}, (i,l)\n {\n console.printLine(l,\": \", points[3 - i].toArray())\n });\n }\n}\n", "language": "Elena" }, { "code": "defmodule World_Cup do\n def group_stage do\n results = [[3,0],[1,1],[0,3]]\n teams = [0,1,2,3]\n allresults = combos(2,teams) |> combinations(results)\n allpoints = for list <- allresults, do: (for {l1,l2} <- list, do: Enum.zip(l1,l2)) |> List.flatten\n totalpoints = for list <- allpoints, do: (for t <- teams, do: {t, Enum.sum(for {t_,points} <- list, t_==t, do: points)} )\n sortedtotalpoints = for list <- totalpoints, do: Enum.sort(list,fn({_,a},{_,b}) -> a > b end)\n pointsposition = for n <- teams, do: (for list <- sortedtotalpoints, do: elem(Enum.at(list,n),1))\n for n <- teams do\n for points <- 0..9 do\n Enum.at(pointsposition,n) |> Enum.filter(&(&1 == points)) |> length\n end\n end\n end\n\n defp combos(1, list), do: (for x <- list, do: [x])\n defp combos(k, list) when k == length(list), do: [list]\n defp combos(k, [h|t]) do\n (for subcombos <- combos(k-1, t), do: [h | subcombos]) ++ (combos(k, t))\n end\n\n defp combinations([h],list2), do: (for item <- list2, do: [{h,item}])\n defp combinations([h|t],list2) do\n for item <- list2, comb <- combinations(t,list2), do: [{h,item} | comb]\n end\nend\n\nformat = String.duplicate(\"~4w\", 10) <> \"~n\"\n:io.format(format, Enum.to_list(0..9))\nIO.puts String.duplicate(\" ---\", 10)\nEnum.each(World_Cup.group_stage, fn x -> :io.format(format, x) end)\n", "language": "Elixir" }, { "code": "-module(world_cup).\n\n-export([group_stage/0]).\n\ngroup_stage() ->\n\tResults = [[3,0],[1,1],[0,3]],\n\tTeams = [1,2,3,4],\n\tMatches = combos(2,Teams),\n\tAllResults =\n\t\tcombinations(Matches,Results),\n\tAllPoints =\n\t\t[lists:flatten([lists:zip(L1,L2) || {L1,L2} <- L]) || L <- AllResults],\n\tTotalPoints =\n\t\t[ [ {T,lists:sum([Points || {T_,Points} <- L, T_ == T])} || T <- Teams] || L <- AllPoints],\n\tSortedTotalPoints =\n\t\t[ lists:sort(fun({_,A},{_,B}) -> A > B end,L) || L <- TotalPoints],\n\tPointsPosition =\n\t\t[ [element(2,lists:nth(N, L))|| L <- SortedTotalPoints ] || N <- Teams],\n\t[ [length(lists:filter(fun(Points_) -> Points_ == Points end,lists:nth(N, PointsPosition) ))\n\t\t|| Points <- lists:seq(0,9)] || N <- Teams].\n\ncombos(1, L) ->\n\t[[X] || X <- L];\ncombos(K, L) when K == length(L) ->\n\t[L];\ncombos(K, [H|T]) ->\n [[H | Subcombos] || Subcombos <- combos(K-1, T)]\n ++ (combos(K, T)).\n\ncombinations([H],List2) ->\n\t[[{H,Item}] || Item <- List2];\ncombinations([H|T],List2) ->\n\t[ [{H,Item} | Comb] || Item <- List2, Comb <- combinations(T,List2)].\n", "language": "Erlang" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strconv\"\n)\n\nvar games = [6]string{\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"}\nvar results = \"000000\"\n\nfunc nextResult() bool {\n if results == \"222222\" {\n return false\n }\n res, _ := strconv.ParseUint(results, 3, 32)\n results = fmt.Sprintf(\"%06s\", strconv.FormatUint(res+1, 3))\n return true\n}\n\nfunc main() {\n var points [4][10]int\n for {\n var records [4]int\n for i := 0; i < len(games); i++ {\n switch results[i] {\n case '2':\n records[games[i][0]-'1'] += 3\n case '1':\n records[games[i][0]-'1']++\n records[games[i][1]-'1']++\n case '0':\n records[games[i][1]-'1'] += 3\n }\n }\n sort.Ints(records[:])\n for i := 0; i < 4; i++ {\n points[i][records[i]]++\n }\n if !nextResult() {\n break\n }\n }\n fmt.Println(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\n fmt.Println(\"-------------------------------------------------------------\")\n places := [4]string{\"1st\", \"2nd\", \"3rd\", \"4th\"}\n for i := 0; i < 4; i++ {\n fmt.Print(places[i], \" place \")\n for j := 0; j < 10; j++ {\n fmt.Printf(\"%-5d\", points[3-i][j])\n }\n fmt.Println()\n }\n}\n", "language": "Go" }, { "code": "require'stats'\noutcome=: 3 0,1 1,:0 3\npairs=: (i.4) e.\"1(2 comb 4)\nstandings=: +/@:>&>,{<\"1<\"1((i.4) e.\"1 pairs)#inv\"1/ outcome\n", "language": "J" }, { "code": " $standings\n729 4\n", "language": "J" }, { "code": " $~.standings\n556 4\n", "language": "J" }, { "code": " ~.#/.~standings\n1 2 3 4 6\n", "language": "J" }, { "code": " (I.6=#/.~standings){{./.~standings\n4 4 4 4\n", "language": "J" }, { "code": " (I.4=#/.~standings){{./.~standings\n6 6 3 3\n6 3 3 6\n6 3 6 3\n3 6 6 3\n3 6 3 6\n3 3 6 6\n", "language": "J" }, { "code": " +/standings =/ i.10\n27 81 81 108 162 81 81 81 0 27\n27 81 81 108 162 81 81 81 0 27\n27 81 81 108 162 81 81 81 0 27\n27 81 81 108 162 81 81 81 0 27\n", "language": "J" }, { "code": " +/(\\:\"1~ standings)=/\"1 i.10\n 0 0 0 1 14 148 152 306 0 108\n 0 0 4 33 338 172 164 18 0 0\n 0 18 136 273 290 4 8 0 0 0\n108 306 184 125 6 0 0 0 0 0\n", "language": "J" }, { "code": "import java.util.Arrays;\n\npublic class GroupStage{\n //team left digit vs team right digit\n static String[] games = {\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"};\n static String results = \"000000\";//start with left teams all losing\n\n private static boolean nextResult(){\n if(results.equals(\"222222\")) return false;\n int res = Integer.parseInt(results, 3) + 1;\n results = Integer.toString(res, 3);\n while(results.length() < 6) results = \"0\" + results;\t//left pad with 0s\n return true;\n }\n\n public static void main(String[] args){\n int[][] points = new int[4][10]; \t\t//playing 3 games, points range from 0 to 9\n do{\n int[] records = {0,0,0,0};\n for(int i = 0; i < 6; i++){\n switch(results.charAt(i)){\n case '2': records[games[i].charAt(0) - '1'] += 3; break; //win for left team\n case '1': //draw\n records[games[i].charAt(0) - '1']++;\n records[games[i].charAt(1) - '1']++;\n break;\n case '0': records[games[i].charAt(1) - '1'] += 3; break; //win for right team\n }\n }\n Arrays.sort(records);\t//sort ascending, first place team on the right\n points[0][records[0]]++;\n points[1][records[1]]++;\n points[2][records[2]]++;\n points[3][records[3]]++;\n }while(nextResult());\n System.out.println(\"First place: \" + Arrays.toString(points[3]));\n System.out.println(\"Second place: \" + Arrays.toString(points[2]));\n System.out.println(\"Third place: \" + Arrays.toString(points[1]));\n System.out.println(\"Fourth place: \" + Arrays.toString(points[0]));\n }\n}\n", "language": "Java" }, { "code": "function worldcupstages()\n games = [\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"]\n results = \"000000\"\n\n function nextresult()\n if (results == \"222222\")\n return false\n end\n results = lpad(string(parse(Int, results, base=3) + 1, base=3), 6, '0')\n true\n end\n\n points = zeros(Int, 4, 10)\n while true\n records = zeros(Int, 4)\n for i in 1:length(games)\n if results[i] == '2'\n records[games[i][1] - '0'] += 3\n elseif results[i] == '1'\n records[games[i][1] - '0'] += 1\n records[games[i][2] - '0'] += 1\n elseif results[i] == '0'\n records[games[i][2] - '0'] += 3\n end\n end\n sort!(records)\n for i in 1:4\n points[i, records[i] + 1] += 1\n end\n if !nextresult()\n break\n end\n end\n\n for (i, place) in enumerate([\"First\", \"Second\", \"Third\", \"Fourth\"])\n println(\"$place place: $(points[5 - i, :])\")\n end\nend\n\nworldcupstages()\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nval games = arrayOf(\"12\", \"13\", \"14\", \"23\", \"24\", \"34\")\nvar results = \"000000\"\n\nfun nextResult(): Boolean {\n if (results == \"222222\") return false\n val res = results.toInt(3) + 1\n results = res.toString(3).padStart(6, '0')\n return true\n}\n\nfun main(args: Array<String>) {\n val points = Array(4) { IntArray(10) }\n do {\n val records = IntArray(4)\n for (i in 0..5) {\n when (results[i]) {\n '2' -> records[games[i][0] - '1'] += 3\n '1' -> { records[games[i][0] - '1']++ ; records[games[i][1] - '1']++ }\n '0' -> records[games[i][1] - '1'] += 3\n }\n }\n records.sort()\n for (i in 0..3) points[i][records[i]]++\n }\n while(nextResult())\n println(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\n println(\"-------------------------------------------------------------\")\n val places = arrayOf(\"1st\", \"2nd\", \"3rd\", \"4th\")\n for (i in 0..3) {\n print(\"${places[i]} place \")\n points[3 - i].forEach { print(\"%-5d\".format(it)) }\n println()\n }\n}\n", "language": "Kotlin" }, { "code": "function array1D(a, d)\n local m = {}\n for i=1,a do\n table.insert(m, d)\n end\n return m\nend\n\nfunction array2D(a, b, d)\n local m = {}\n for i=1,a do\n table.insert(m, array1D(b, d))\n end\n return m\nend\n\nfunction fromBase3(num)\n local out = 0\n for i=1,#num do\n local c = num:sub(i,i)\n local d = tonumber(c)\n out = 3 * out + d\n end\n return out\nend\n\nfunction toBase3(num)\n local ss = \"\"\n while num > 0 do\n local rem = num % 3\n num = math.floor(num / 3)\n ss = ss .. tostring(rem)\n end\n return string.reverse(ss)\nend\n\ngames = { \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" }\n\nresults = \"000000\"\nfunction nextResult()\n if results == \"222222\" then\n return false\n end\n\n local res = fromBase3(results)\n results = string.format(\"%06s\", toBase3(res + 1))\n\n return true\nend\n\npoints = array2D(4, 10, 0)\n\nrepeat\n local records = array1D(4, 0)\n\n for i=1,#games do\n if results:sub(i,i) == '2' then\n local j = tonumber(games[i]:sub(1,1))\n records[j] = records[j] + 3\n elseif results:sub(i,i) == '1' then\n local j = tonumber(games[i]:sub(1,1))\n records[j] = records[j] + 1\n j = tonumber(games[i]:sub(2,2))\n records[j] = records[j] + 1\n elseif results:sub(i,i) == '0' then\n local j = tonumber(games[i]:sub(2,2))\n records[j] = records[j] + 3\n end\n end\n\n table.sort(records)\n for i=1,#records do\n points[i][records[i]+1] = points[i][records[i]+1] + 1\n end\nuntil not nextResult()\n\nprint(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\nprint(\"-------------------------------------------------------------\")\nplaces = { \"1st\", \"2nd\", \"3rd\", \"4th\" }\nfor i=1,#places do\n io.write(places[i] .. \" place\")\n local row = points[i]\n for j=1,#row do\n io.write(string.format(\"%5d\", points[5 - i][j]))\n end\n print()\nend\n", "language": "Lua" }, { "code": "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 var s: array[4, int]\n for (r, g) in zip(results, toSeq(combinations([0, 1, 2, 3], 2))):\n s[g[0]] += Scoring[r]\n s[g[1]] += Scoring[2 - r]\n for i, v in sorted(s):\n inc histo[i][v]\n\nfor x in reversed(histo):\n echo x.mapIt(($it).align(3)).join(\" \")\n", "language": "Nim" }, { "code": "use Math::Cartesian::Product;\n\n@scoring = (0, 1, 3);\npush @histo, [(0) x 10] for 1..4;\npush @aoa, [(0,1,2)] for 1..6;\n\nfor $results (cartesian {@_} @aoa) {\n my @s;\n my @g = ([0,1],[0,2],[0,3],[1,2],[1,3],[2,3]);\n for (0..$#g) {\n $r = $results->[$_];\n $s[$g[$_][0]] += $scoring[$r];\n $s[$g[$_][1]] += $scoring[2 - $r];\n }\n\n my @ss = sort @s;\n $histo[$_][$ss[$_]]++ for 0..$#s;\n}\n\n$fmt = ('%3d ') x 10 . \"\\n\";\nprintf $fmt, @$_ for reverse @histo;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">game_combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- collect the full sets</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">)=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">[$]+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">pool</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">game_combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">games</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">game_combinations</span><span style=\"color: #0000FF;\">({},</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- ie {{1,2},{1,3},{1,4},{2,3},{2,4},{3,4}}</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">scores</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">}}</span> <span style=\"color: #000080;font-style:italic;\">-- ie win/draw/lose</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">points</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- 1st..4th place, 0..9 points</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">result_combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">={})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000080;font-style:italic;\">-- (here, chosen is {1,1,1,1,1,1}..{3,3,3,3,3,3}, 729 in all)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">results</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">team1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">team2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">games</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">points1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">points2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">scores</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]]</span>\n <span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">team1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">points1</span>\n <span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">team2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">points2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000000;\">results</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sort</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">do</span> <span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">results</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">pool</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">result_combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">pool</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">needed</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">chosen</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- accumulate the results of all possible outcomes (1..3) of 6 games:</span>\n <span style=\"color: #000000;\">result_combinations</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (the result ends up in points)\n --result_combinations(length(scores),length(games)) -- (equivalent)</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%5d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">))&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">cardinals</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"st\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"nd\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"rd\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"th\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" points \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'-'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">69</span><span style=\"color: #0000FF;\">)&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">4</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%d%s place \"</span><span style=\"color: #0000FF;\">&</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cardinals</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]}&</span><span style=\"color: #000000;\">points</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">5</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "from itertools import product, combinations, izip\n\nscoring = [0, 1, 3]\nhisto = [[0] * 10 for _ in xrange(4)]\n\nfor results in product(range(3), repeat=6):\n s = [0] * 4\n for r, g in izip(results, combinations(range(4), 2)):\n s[g[0]] += scoring[r]\n s[g[1]] += scoring[2 - r]\n\n for h, v in izip(histo, sorted(s)):\n h[v] += 1\n\nfor x in reversed(histo):\n print x\n", "language": "Python" }, { "code": "#lang racket\n;; Tim Brown 2014-09-15\n(define (sort-standing stndg#)\n (sort (hash->list stndg#) > #:key cdr))\n\n(define (hash-update^2 hsh key key2 updater2 dflt2)\n (hash-update hsh key (λ (hsh2) (hash-update hsh2 key2 updater2 dflt2)) hash))\n\n(define all-standings\n (let ((G '((a b) (a c) (a d) (b c) (b d) (c d)))\n (R '((3 0) (1 1) (0 3))))\n (map\n sort-standing\n (for*/list ((r1 R) (r2 R) (r3 R) (r4 R) (r5 R) (r6 R))\n (foldr (λ (gm rslt h)\n (hash-update\n (hash-update h (second gm) (λ (n) (+ n (second rslt))) 0)\n (first gm) (curry + (first rslt)) 0))\n (hash) G (list r1 r2 r3 r4 r5 r6))))))\n\n(define histogram\n (for*/fold ((rv (hash)))\n ((stndng (in-list all-standings)) (psn (in-range 0 4)))\n (hash-update^2 rv (add1 psn) (cdr (list-ref stndng psn)) add1 0)))\n\n;; Generalised histogram printing functions...\n(define (show-histogram hstgrm# captions)\n (define (min* a b)\n (if (and a b) (min a b) (or a b)))\n (define-values (position-mn position-mx points-mn points-mx)\n (for*/fold ((mn-psn #f) (mx-psn 0) (mn-pts #f) (mx-pts 0))\n (((psn rw) (in-hash hstgrm#)))\n (define-values (min-pts max-pts)\n (for*/fold ((mn mn-pts) (mx mx-pts)) ((pts (in-hash-keys rw)))\n (values (min* pts mn) (max pts mx))))\n (values (min* mn-psn psn) (max mx-psn psn) min-pts max-pts)))\n\n (define H\n (let ((lbls-row# (for/hash ((i (in-range points-mn (add1 points-mx)))) (values i i))))\n (hash-set hstgrm# 'thead lbls-row#)))\n\n (define cap-col-width (for/fold ((m 0)) ((v (in-hash-values captions))) (max m (string-length v))))\n\n (for ((plc (in-sequences\n (in-value 'thead)\n (in-range position-mn (add1 position-mx)))))\n (define cnts (for/list ((pts (in-range points-mn (add1 points-mx))))\n (~a #:align 'center #:width 3 (hash-ref (hash-ref H plc) pts 0))))\n (printf \"~a ~a~%\"\n (~a (hash-ref captions plc (curry format \"#~a:\")) #:width cap-col-width)\n (string-join cnts \" \"))))\n\n(define captions\n (hash 'thead \"POINTS:\"\n 1 \"1st Place:\"\n 2 \"2nd Place:\"\n 3 \"Sack the manager:\"\n 4 \"Sack the team!\"))\n\n(show-histogram histogram captions)\n", "language": "Racket" }, { "code": "constant scoring = 0, 1, 3;\nmy @histo = [0 xx 10] xx 4;\n\nfor [X] ^3 xx 6 -> @results {\n my @s;\n\n for @results Z (^4).combinations(2) -> ($r, @g) {\n @s[@g[0]] += scoring[$r];\n @s[@g[1]] += scoring[2 - $r];\n }\n\n for @histo Z @s.sort -> (@h, $v) {\n ++@h[$v];\n }\n}\n\nsay .fmt('%3d',' ') for @histo.reverse;\n", "language": "Raku" }, { "code": "/* REXX -------------------------------------------------------------------*/\nresults = '000000' /*start with left teams all losing */\ngames = '12 13 14 23 24 34'\npoints.=0\nrecords.=0\nDo Until nextResult(results)=0\n records.=0\n Do i=1 To 6\n r=substr(results,i,1)\n g=word(games,i); Parse Var g g1 +1 g2\n Select\n When r='2' Then /* win for left team */\n records.g1=records.g1+3\n When r='1' Then Do /* draw */\n records.g1=records.g1+1\n records.g2=records.g2+1\n End\n When r='0' Then /* win for right team */\n records.g2=records.g2+3\n End\n End\n Call sort_records /* sort ascending, */\n /* first place team on the right */\n r1=records.1\n r2=records.2\n r3=records.3\n r4=records.4\n points.0.r1=points.0.r1+1\n points.1.r2=points.1.r2+1\n points.2.r3=points.2.r3+1\n points.3.r4=points.3.r4+1\n End\nol.='['\nsep=', '\nDo i=0 To 9\n If i=9 Then sep=']'\n ol.0=ol.0||points.0.i||sep\n ol.1=ol.1||points.1.i||sep\n ol.2=ol.2||points.2.i||sep\n ol.3=ol.3||points.3.i||sep\n End\nSay ol.3\nSay ol.2\nSay ol.1\nSay ol.0\nExit\n\nnextResult: Procedure Expose results\n/* results is a string of 6 base 3 digits to which we add 1 */\n/* e.g., '000212 +1 -> 000220 */\nIf results=\"222222\" Then Return 0\nres=0\ndo i=1 To 6\n res=res*3+substr(results,i,1)\n End\nres=res+1\ns=''\nDo i=1 To 6\n b=res//3\n res=res%3\n s=b||s\n End\nresults=s\nReturn 1\n\nsort_records: Procedure Expose records.\nDo i=1 To 3\n Do j=i+1 To 4\n If records.j<records.i Then\n Parse Value records.i records.j With records.j records.i\n End\n End\nReturn\n", "language": "REXX" }, { "code": "/*REXX pgm calculates world cup standings based on the number of games won by the teams.*/\nparse arg teams win . /*obtain optional argument from the CL.*/\nif teams=='' | teams==\",\" then teams= 4 /*Not specified? Then use the default.*/\nif win=='' | win==\",\" then win= 3 /* \" \" \" \" \" \" */\nsets= 0; gs= /*the number of sets (so far). */\n do j=1 for teams\n do k=j+1 to teams; sets= sets + 1 /*bump the number of game sets. */\n games.sets= j || k; gs= gs j || k /*generate the game combinations. */\n end /*j*/\n end /*k*/\nz= 1; setLimit= copies(2, sets) /*Z: max length of any number shown. */\nsay teams ' teams, ' sets \" game sets: \" gs /*display what's being used for calcs. */\nresults = copies(0, sets); say /*start with left-most teams all losing*/\npoints. = 0 /*zero all the team's point. */\n do until \\nextResult(results); @.= 0\n do j=1 for sets; r= substr( results, j, 1)\n parse var games.j A +1 B /*get the A and B teams*/\n if r==0 then @.B= @.B + win /*win for right─most team.*/\n if r==1 then do; @.A= @.A + 1; @.B= @.B + 1; end /*draw for both teams*/\n if r==2 then @.A= @.A + win /*win for left─most team. */\n end /*j*/\n call sort teams\n do t=1 for teams; tm= t - 1; _= @.t\n points.tm._ = points.tm._ + 1; z= max(z, length( points.tm._) )\n end /*t*/\n end /*until*/\n$.=\n do j=0 for teams+6; do k=0 for teams; $.k= $.k || right( points.k.j, z)'│ '; end\n end /*j*/\nsay /* [↓] build grid line for the box*/\nL= length($.1) -2; $$= translate( translate( left($.1, L), , 0123456789), '─', \" \")\nsay left('', 15) center(\"points\", L) /*display the boxed title. */\nsay left('', 15) \"╔\"translate($$, '═╤', \"─│\")'╗' /*display the bottom sep for title.*/\np= 0\n do m=teams-1 by -1 for teams; p = p + 1 /*bump the place holder (counter)*/\n say right('('th(p) \"place)\", 14) \" ║\"left($.m, L)'║'\n if m>0 then say right(' ', 14) \" ╟\"translate($$, '┼', \"│\")'╢'\n end /*m*/\nsay left('', 15) \"╚\"translate( $$, '═╧', \"─│\")'╝' /*display the bottom sep for title.*/\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nnextResult: if results==setLimit then return 0 /* [↓] do arithmetic in base three. */\n res= 0; do k=1 for sets; res= res * 3 + substr( results, k, 1)\n end /*k*/\n results=; res= res + 1\n do sets; results= res // 3 || results; res= res % 3\n end /*sets*/; return 1\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nsort: procedure expose @.; arg #; do j=1 for #-1 /*a bubble sort, ascending order.*/\n do k=j+1 to # /*swap two elements out of order.*/\n if @.k<@.j then parse value @.j @.k with @.k @.j\n end /*k*/\n end /*j*/; return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nth: arg th; return (th/1) || word('th st nd rd', 1 +(th//10) *(th//100%10\\==1)*(th//10<4))\n", "language": "REXX" }, { "code": "teams = [:a, :b, :c, :d]\nmatches = teams.combination(2).to_a\noutcomes = [:win, :draw, :loss]\ngains = {win:[3,0], draw:[1,1], loss:[0,3]}\nplaces_histogram = Array.new(4) {Array.new(10,0)}\n\n# The Array#repeated_permutation method generates the 3^6 different\n# possible outcomes\noutcomes.repeated_permutation(6).each do |outcome|\n results = Hash.new(0)\n\n # combine this outcomes with the matches, and generate the points table\n outcome.zip(matches).each do |decision, (team1, team2)|\n results[team1] += gains[decision][0]\n results[team2] += gains[decision][1]\n end\n\n # accumulate the results\n results.values.sort.reverse.each_with_index do |points, place|\n places_histogram[place][points] += 1\n end\nend\n\nfmt = \"%s :\" + \"%4s\"*10\nputs fmt % [\" \", *0..9]\nputs fmt % [\"-\", *[\"---\"]*10]\nplaces_histogram.each.with_index(1) {|hist,place| puts fmt % [place, *hist]}\n", "language": "Ruby" }, { "code": "object GroupStage extends App { //team left digit vs team right digit\n val games = Array(\"12\", \"13\", \"14\", \"23\", \"24\", \"34\")\n val points = Array.ofDim[Int](4, 10) //playing 3 games, points range from 0 to 9\n var results = \"000000\" //start with left teams all losing\n\n private def nextResult: Boolean = {\n if (results == \"222222\") false\n else {\n results = Integer.toString(Integer.parseInt(results, 3) + 1, 3)\n while (results.length < 6) results = \"0\" + results //left pad with 0s\n true\n }\n }\n\n do {\n val records = Array(0, 0, 0, 0)\n for (i <- results.indices.reverse by -1) {\n results(i) match {\n case '2' => records(games(i)(0) - '1') += 3\n case '1' => //draw\n records(games(i)(0) - '1') += 1\n records(games(i)(1) - '1') += 1\n case '0' => records(games(i)(1) - '1') += 3\n }\n }\n java.util.Arrays.sort(records) //sort ascending, first place team on the right\n\n points(0)(records(0)) += 1\n points(1)(records(1)) += 1\n points(2)(records(2)) += 1\n points(3)(records(3)) += 1\n } while (nextResult)\n\n println(\"First place: \" + points(3).mkString(\"[\",\", \",\"]\"))\n println(\"Second place: \" + points(2).mkString(\"[\",\", \",\"]\"))\n println(\"Third place: \" + points(1).mkString(\"[\",\", \",\"]\"))\n println(\"Fourth place: \" + points(0).mkString(\"[\",\", \",\"]\"))\n\n}\n", "language": "Scala" }, { "code": "package require Tcl 8.6\nproc groupStage {} {\n foreach n {0 1 2 3} {\n\tset points($n) {0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0}\n }\n set results 0\n set games {0 1 0 2 0 3 1 2 1 3 2 3}\n while true {\n\tset R {0 0 1 0 2 0 3 0}\n\tforeach r [split [format %06d $results] \"\"] {A B} $games {\n\t switch $r {\n\t\t2 {dict incr R $A 3}\n\t\t1 {dict incr R $A; dict incr R $B}\n\t\t0 {dict incr R $B 3}\n\t }\n\t}\n\tforeach n {0 1 2 3} r [lsort -integer [dict values $R]] {\n\t dict incr points($n) $r\n\t}\n\n\tif {$results eq \"222222\"} break\n\twhile {[regexp {[^012]} [incr results]]} continue\n }\n return [lmap n {3 2 1 0} {dict values $points($n)}]\n}\n\nforeach nth {First Second Third Fourth} nums [groupStage] {\n puts \"$nth place:\\t[join [lmap n $nums {format %3s $n}] {, }]\"\n}\n", "language": "Tcl" }, { "code": "Imports System.Text\n\nModule Module1\n\n Dim games As New List(Of String) From {\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"}\n Dim results = \"000000\"\n\n Function FromBase3(num As String) As Integer\n Dim out = 0\n For Each c In num\n Dim d = Asc(c) - Asc(\"0\"c)\n out = 3 * out + d\n Next\n Return out\n End Function\n\n Function ToBase3(num As Integer) As String\n Dim ss As New StringBuilder\n\n While num > 0\n Dim re = num Mod 3\n num \\= 3\n ss.Append(re)\n End While\n\n Return New String(ss.ToString().Reverse().ToArray())\n End Function\n\n Function NextResult() As Boolean\n If results = \"222222\" Then\n Return False\n End If\n\n Dim res = FromBase3(results)\n\n Dim conv = ToBase3(res + 1)\n results = conv.PadLeft(6, \"0\"c)\n\n Return True\n End Function\n\n Sub Main()\n Dim points(0 To 3, 0 To 9) As Integer\n Do\n Dim records(0 To 3) As Integer\n For index = 0 To games.Count - 1\n Select Case results(index)\n Case \"2\"c\n records(Asc(games(index)(0)) - Asc(\"1\"c)) += 3\n Case \"1\"c\n records(Asc(games(index)(0)) - Asc(\"1\"c)) += 1\n records(Asc(games(index)(1)) - Asc(\"1\"c)) += 1\n Case \"0\"c\n records(Asc(games(index)(1)) - Asc(\"1\"c)) += 3\n End Select\n Next\n\n Array.Sort(records)\n For index = 0 To records.Length - 1\n Dim t = records(index)\n points(index, t) += 1\n Next\n Loop While NextResult()\n\n Console.WriteLine(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\n Console.WriteLine(\"-------------------------------------------------------------\")\n Dim places As New List(Of String) From {\"1st\", \"2nd\", \"3rd\", \"4th\"}\n For i = 0 To places.Count - 1\n Console.Write(\"{0} place\", places(i))\n For j = 0 To 9\n Console.Write(\"{0,5}\", points(3 - i, j))\n Next\n Console.WriteLine()\n Next\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./fmt\" for Conv, Fmt\nimport \"./sort\" for Sort\n\nvar games = [\"12\", \"13\", \"14\", \"23\", \"24\", \"34\"]\nvar results = \"000000\"\n\nvar nextResult = Fn.new {\n if (results == \"222222\") return false\n var res = Conv.atoi(results, 3) + 1\n results = Fmt.swrite(\"$06t\", res)\n return true\n}\n\nvar points = List.filled(4, null)\nfor (i in 0..3) points[i] = List.filled(10, 0)\nwhile (true) {\n var records = List.filled(4, 0)\n for (i in 0..5) {\n var g0 = Num.fromString(games[i][0]) - 1\n var g1 = Num.fromString(games[i][1]) - 1\n if (results[i] == \"2\") {\n records[g0] = records[g0] + 3\n } else if (results[i] == \"1\") {\n records[g0] = records[g0] + 1\n records[g1] = records[g1] + 1\n } else if (results[i] == \"0\") {\n records[g1] = records[g1] + 3\n }\n }\n Sort.insertion(records)\n for (i in 0..3) points[i][records[i]] = points[i][records[i]] +1\n if (!nextResult.call()) break\n}\nSystem.print(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\nSystem.print(\"---------------------------------------------------------------\")\nfor (i in 0..3) {\n Fmt.write(\"$r place \", i+1)\n points[3-i].each { |p| Fmt.write(\"$5d\", p) }\n System.print()\n}\n", "language": "Wren" }, { "code": "data \"12\", \"13\", \"14\", \"23\", \"24\", \"34\"\n\ndim game$(6)\n\nfor i = 1 to 6 : read game$(i) : next\n\nresult$ = \"000000\"\n\n\nsub ParseInt(number$, base)\n local x, i, pot, digits\n\n digits = len(number$)\n\n for i = digits to 1 step -1\n x = x + base^pot * dec(mid$(number$, i, 1))\n pot = pot + 1\n next\n\n return x\nend sub\n\n\nsub Format$(decimal, base)\n local cociente, i, j, conv$\n\n repeat\n cociente = int(decimal / base)\n conv$ = str$(mod(decimal, base)) + conv$\n decimal = cociente\n i = i + 1\n until(cociente = 0)\n\n return conv$\nend sub\n\n\nsub nextResult()\n if result$ = \"222222\" return false\n res = ParseInt(result$, 3)\n result$ = Format$(res+1, 3)\n while(len(result$) < 6) result$ = \"0\" + result$ wend\n return true\nend sub\n\n\nsub Sort(array())\n local n, i, t, sw\n\n n = arraysize(array(), 1)\n\n repeat\n sw = false\n for i = 0 to n - 1\n if array(i) > array(i + 1) then\n sw = true\n t = array(i)\n array(i) = array(i + 1)\n array(i + 1) = t\n end if\n next\n until(not sw)\nend sub\n\n\ndim points(4, 10)\n\nsub compute()\n local records(4), i, t\n\n for i = 1 to arraysize(game$(), 1)\n switch mid$(result$, i, 1)\n case \"2\":\n t = val(mid$(game$(i), 1, 1))\n records(t) = records(t) + 3\n break\n case \"1\":\n t = val(mid$(game$(i), 1, 1))\n records(t) = records(t) + 1\n t = val(mid$(game$(i), 2, 1))\n records(t) = records(t) + 1\n break\n case \"0\":\n t = val(mid$(game$(i), 2, 1))\n records(t) = records(t) + 3\n break\n end switch\n next\n Sort(records())\n for i = 1 to 4\n points(i, records(i)) = points(i, records(i)) + 1\n next\n if not nextResult() return false\n return true\nend sub\n\nrepeat until(not compute())\n\nprint \"POINTS 0 1 2 3 4 5 6 7 8 9\"\nprint \"-------------------------------------------------------------\"\n\ndim place$(4)\n\ndata \"1st\", \"2nd\", \"3rd\", \"4th\"\nfor i = 1 to 4 : read place$(i) : next\n\nfor i = 1 to 4\n print place$(i), \" place \";\n for j = 0 to 9\n print points(5 - i, j) using \"%-4.0f\";\n next\n print\nnext\n", "language": "Yabasic" }, { "code": "combos :=Utils.Helpers.pickNFrom(2,T(0,1,2,3)); // ( (0,1),(0,2) ... )\nscoring:=T(0,1,3);\nhisto :=(0).pump(4,List().write,(0).pump(10,List().write,0).copy); //[4][10] of zeros\n\nforeach r0,r1,r2,r3,r4,r5 in ([0..2],[0..2],[0..2],[0..2],[0..2],[0..2]){\n s:=L(0,0,0,0);\n foreach i,r in (T(r0,r1,r2,r3,r4,r5).enumerate()){\n g:=combos[i];\n s[g[0]]+=scoring[r];\n s[g[1]]+=scoring[2 - r];\n }\n foreach h,v in (histo.zip(s.sort())){ h[v]+=1; }\n}\nforeach h in (histo.reverse()){ println(h.apply(\"%3d \".fmt).concat()) }\n", "language": "Zkl" } ]
World-Cup-group-stage
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Write_entire_file\nnote: File handling\n", "language": "00-META" }, { "code": ";Task:\n(Over)write a file so that it contains a string.\n\n\nThe reverse of [[Read entire file]]—for when you want to update or create a file which you would read in its entirety all at once.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "File(filename, ‘w’).write(string)\n", "language": "11l" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program writeFile64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessErreur: .asciz \"Error open file.\\n\"\nszMessErreur1: .asciz \"Error close file.\\n\"\nszMessErreur2: .asciz \"Error write file.\\n\"\nszMessWriteOK: .asciz \"String write in file OK.\\n\"\n\nszParamNom: .asciz \"./fic1.txt\" // file name\nsZoneEcrit: .ascii \"(Over)write a file so that it contains a string.\"\n .equ LGZONEECRIT, . - sZoneEcrit\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n // file open\n mov x0,AT_FDCWD // current directory\n ldr x1,qAdrszParamNom // filename\n mov x2,O_CREAT|O_WRONLY // flags\n ldr x3,oficmask1 // mode\n mov x8,OPEN // Linux call system\n svc 0 //\n cmp x0,0 // error ?\n ble erreur // yes\n mov x28,x0 // save File Descriptor\n // x0 = FD\n ldr x1,qAdrsZoneEcrit // write string address\n mov x2,LGZONEECRIT // string size\n mov x8,WRITE // Linux call system\n svc 0\n cmp x0,0 // error ?\n ble erreur2 // yes\n // close file\n mov x0,x28 // File Descriptor\n mov x8,CLOSE // Linuc call system\n svc 0\n cmp x0,0 // error ?\n blt erreur1\n ldr x0,qAdrszMessWriteOK\n bl affichageMess\n mov x0,#0 // return code OK\n b 100f\nerreur:\n ldr x1,qAdrszMessErreur\n bl affichageMess // display error message\n mov x0,#1\n b 100f\nerreur1:\n ldr x1,qAdrszMessErreur1 // x0 <- adresse chaine\n bl affichageMess // display error message\n mov x0,#1 // return code error\n b 100f\nerreur2:\n ldr x0,qAdrszMessErreur2\n bl affichageMess // display error message\n mov x0,#1 // return code error\n b 100f\n100: // program end\n mov x8,EXIT\n svc #0\nqAdrszParamNom: .quad szParamNom\nqAdrszMessErreur: .quad szMessErreur\nqAdrszMessErreur1: .quad szMessErreur1\nqAdrszMessErreur2: .quad szMessErreur2\nqAdrszMessWriteOK: .quad szMessWriteOK\nqAdrsZoneEcrit: .quad sZoneEcrit\noficmask1: .quad 0644 // this zone is Octal number (0 before)\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "proc MAIN()\n open (1,\"D:FILE.TXT\",8,0)\n printde(1,\"My string\")\n close(1)\nreturn\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Write_Whole_File is\n File_Name : constant String := \"the_file.txt\";\n\n F : File_Type;\nbegin\n begin\n Open (F, Mode => Out_File, Name => File_Name);\n exception\n when Name_Error => Create (F, Mode => Out_File, Name => File_Name);\n end;\n\n Put (F, \"(Over)write a file so that it contains a string. \" &\n \"The reverse of Read entire file—for when you want to update or \" &\n \"create a file which you would read in its entirety all at once.\");\n Close (F);\nend Write_Whole_File;\n", "language": "Ada" }, { "code": "IF FILE output;\n STRING output file name = \"output.txt\";\n open( output, output file name, stand out channel ) = 0\nTHEN\n # file opened OK #\n put( output, ( \"line 1\", newline, \"line 2\", newline ) );\n close( output )\nELSE\n # unable to open the output file #\n print( ( \"Cannot open \", output file name, newline ) )\nFI\n", "language": "ALGOL-68" }, { "code": " 10 D$ = CHR$ (4)\n 20 F$ = \"OUTPUT.TXT\"\n 30 PRINT D$\"OPEN\"F$\n 40 PRINT D$\"CLOSE\"F$\n 50 PRINT D$\"DELETE\"F$\n 60 PRINT D$\"OPEN\"F$\n 70 PRINT D$\"WRITE\"F$\n 80 PRINT \"THIS STRING IS TO BE WRITTEN TO THE FILE\"\n 90 PRINT D$\"CLOSE\"F$\n", "language": "Applesoft-BASIC" }, { "code": "contents: \"Hello World!\"\nwrite \"output.txt\" contents\n", "language": "Arturo" }, { "code": "file := FileOpen(\"test.txt\", \"w\")\nfile.Write(\"this is a test string\")\nfile.Close()\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK\nBEGIN {\n dev = \"FILENAME.TXT\"\n print(\"(Over)write a file so that it contains a string.\") >dev\n close(dev)\n exit(0)\n}\n", "language": "AWK" }, { "code": "SAVE s$ TO filename$\n", "language": "BaCon" }, { "code": "BSAVE mem TO filename$ SIZE n\n", "language": "BaCon" }, { "code": "f = freefile\nopen f, \"output.txt\"\nwrite f, \"This string is to be written to the file\"\nclose f\n", "language": "BASIC256" }, { "code": "file% = OPENOUT filename$\nPRINT#file%, text$\nCLOSE#file%\n", "language": "BBC-BASIC" }, { "code": "put$(\"(Over)write a file so that it contains a string.\",file,NEW)\n", "language": "Bracmat" }, { "code": "/*\n * Write Entire File -- RossetaCode -- dirty hackish solution\n */\n#define _CRT_SECURE_NO_WARNINGS // turn off MS Visual Studio restrictions\n#include <stdio.h>\n\nint main(void)\n{\n return 0 >= fputs(\"ANY STRING TO WRITE TO A FILE AT ONCE.\",\n freopen(\"sample.txt\",\"wb\",stdout));\n}\n", "language": "C" }, { "code": "/*\n * Write Entire File -- RossetaCode -- ASCII version with BUFFERED files\n */\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n/**\n * Write entire file at once.\n *\n * @param fileName file name\n * @param data buffer with data\n * @param size number of bytes to write\n *\n * @return Number of bytes have been written.\n */\nint writeEntireFile(char* fileName, const void* data, size_t size)\n{\n size_t numberBytesWritten = 0; // will be updated\n\n // Notice: assertions can be turned off by #define NDEBUG\n //\n assert( fileName != NULL );\n assert( data != NULL );\n assert( size > 0 );\n\n // Check for a null pointer or an empty file name.\n //\n // BTW, should we write if ( ptr != NULL) or simply if ( ptr ) ?\n // Both of these forms are correct. At issue is which is more readable.\n //\n if ( fileName != NULL && *fileName != '\\0' )\n {\n // Try to open file in BINARY MODE\n //\n FILE* file = fopen(fileName,\"wb\");\n\n // There is a possibility to allocate a big buffer to speed up i/o ops:\n //\n // const size_t BIG_BUFFER_SIZE = 0x20000; // 128KiB\n // void* bigBuffer = malloc(BIG_BUFFER_SIZE);\n // if ( bigBuffer != NULL )\n // {\n // setvbuf(file,bigBuffer,_IOFBF,BIG_BUFFER_SIZE);\n // }\n //\n // Of course, you should release the malloc allocated buffer somewhere.\n // Otherwise, bigBuffer will be released after the end of the program.\n\n\n if ( file != NULL )\n {\n // Return value from fwrite( data, 1, size, file ) is the number\n // of bytes written. Return value from fwrite( data, size, 1, file )\n // is the number of blocks (either 0 or 1) written.\n //\n // Notice, that write (see io.h) is less capable than fwrite.\n //\n\n if ( data != NULL )\n {\n numberBytesWritten = fwrite( data, 1, size, file );\n }\n fclose( file );\n }\n }\n return numberBytesWritten;\n}\n\n#define DATA_LENGTH 8192 /* 8KiB */\n\nint main(void)\n{\n // Large arrays can exhaust memory on the stack. This is why the static\n // keyword is used.Static variables are allocated outside the stack.\n //\n static char data[DATA_LENGTH];\n\n // Filling data array with 'A' character.\n // Of course, you can use any other data here.\n //\n int i;\n for ( i = 0; i < DATA_LENGTH; i++ )\n {\n data[i] = 'A';\n }\n\n // Write entire file at once.\n //\n if ( writeEntireFile(\"sample.txt\", data, DATA_LENGTH ) == DATA_LENGTH )\n return EXIT_SUCCESS;\n else\n return EXIT_FAILURE;\n}\n", "language": "C" }, { "code": "/*\n * Write Entire File -- RossetaCode -- plain POSIX write() from io.h\n */\n\n#define _CRT_SECURE_NO_WARNINGS // turn off MS Visual Studio restrictions\n#define _CRT_NONSTDC_NO_WARNINGS // turn off MS Visual Studio restrictions\n\n#include <assert.h>\n#include <fcntl.h>\n#include <io.h>\n\n/**\n * Write entire file at once.\n *\n * @param fileName file name\n * @param data buffer with data\n * @param size number of bytes to write\n *\n * @return Number of bytes have been written.\n */\nint writeEntireFile(char* fileName, const void* data, size_t size)\n{\n size_t numberBytesWritten = 0; // will be updated\n int file; // file handle is an integer (see Fortran ;)\n\n // Notice: we can not trust in assertions to work.\n // Assertions can be turned off by #define NDEBUG.\n //\n assert( fileName );\n assert( data );\n assert( size > 0 );\n\n if(fileName && fileName[0] && (file=open(fileName,O_CREAT|O_BINARY|O_WRONLY))!=(-1))\n {\n if ( data )\n numberBytesWritten = write( file, data, size );\n close( file );\n }\n return numberBytesWritten;\n}\n\n#define DATA_LENGTH 8192 /* 8KiB */\n\nint main(void)\n{\n // Large arrays can exhaust memory on the stack. This is why the static\n // keyword is used.Static variables are allocated outside the stack.\n //\n static char data[DATA_LENGTH];\n\n // Filling data array with 'Z' character.\n // Of course, you can use any other data here.\n //\n int i;\n for ( i = 0; i < DATA_LENGTH; i++ )\n {\n data[i] = 'Z';\n }\n\n // Write entire file at once.\n //\n if ( writeEntireFile(\"sample.txt\", data, DATA_LENGTH ) == DATA_LENGTH )\n return 0;\n else\n return 1;\n}\n", "language": "C" }, { "code": "#include <fstream>\nusing namespace std;\n\nint main()\n{\n ofstream file(\"new.txt\");\n file << \"this is a string\";\n file.close();\n return 0;\n}\n", "language": "C++" }, { "code": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\");\n", "language": "C-sharp" }, { "code": "(spit \"file.txt\" \"this is a string\")\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. Overwrite.\n AUTHOR. Bill Gunshannon.\n INSTALLATION. Home.\n DATE-WRITTEN. 31 December 2021.\n ************************************************************\n ** Program Abstract:\n ** Simple COBOL task. Open file for output. Write\n ** data to file. Close file. Done...\n ************************************************************\n\n ENVIRONMENT DIVISION.\n\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT File-Name ASSIGN TO \"File.txt\"\n ORGANIZATION IS LINE SEQUENTIAL.\n DATA DIVISION.\n\n FILE SECTION.\n\n FD File-Name\n DATA RECORD IS Record-Name.\n 01 Record-Name.\n 02 Field1 PIC X(80).\n\n WORKING-STORAGE SECTION.\n\n 01 New-Val PIC X(80)\n VALUE 'Hello World'.\n\n\n PROCEDURE DIVISION.\n\n Main-Program.\n OPEN OUTPUT File-Name.\n WRITE Record-Name FROM New-Val.\n CLOSE File-Name.\n STOP RUN.\n\n END-PROGRAM.\n", "language": "COBOL" }, { "code": "(with-open-file (str \"filename.txt\"\n :direction :output\n :if-exists :supersede\n :if-does-not-exist :create)\n (format str \"File content...~%\"))\n", "language": "Common-Lisp" }, { "code": "import std.stdio;\n\nvoid main() {\n auto file = File(\"new.txt\", \"wb\");\n file.writeln(\"Hello World!\");\n}\n", "language": "D" }, { "code": "program Write_entire_file;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.IoUtils;\n\nbegin\n TFile.WriteAllText('filename.txt', 'This file contains a string.');\nend.\n", "language": "Delphi" }, { "code": "import system'io;\n\npublic program()\n{\n File.assign(\"filename.txt\").saveContent(\"This file contains a string.\")\n}\n", "language": "Elena" }, { "code": "File.write(\"file.txt\", string)\n", "language": "Elixir" }, { "code": "System.IO.File.WriteAllText(\"filename.txt\", \"This file contains a string.\")\n", "language": "F-Sharp" }, { "code": "USING: io.encodings.utf8 io.files ;\n\"this is a string\" \"file.txt\" utf8 set-file-contents\n", "language": "Factor" }, { "code": ": >file ( string len filename len -- )\n w/o create-file throw dup >r write-file throw r> close-file throw ;\n\ns\" This is a string.\" s\" file.txt\" >file\n", "language": "Forth" }, { "code": " OPEN (F,FILE=\"SomeFileName.txt\",STATUS=\"REPLACE\")\n WRITE (F,*) \"Whatever you like.\"\n WRITE (F) BIGARRAY\n", "language": "Fortran" }, { "code": "program overwriteFile(input, output, stdErr);\n{$mode objFPC} // for exception treatment\nuses\n\tsysUtils; // for applicationName, getTempDir, getTempFileName\n\t// also: importing sysUtils converts all run-time errors to exceptions\nresourcestring\n\thooray = 'Hello world!';\nvar\n\tFD: text;\nbegin\n\t// on a Debian GNU/Linux distribution,\n\t// this will write to /tmp/overwriteFile00000.tmp (or alike)\n\tassign(FD, getTempFileName(getTempDir(false), applicationName()));\n\ttry\n\t\trewrite(FD); // could fail, if user has no permission to write\n\t\twriteLn(FD, hooray);\n\tfinally\n\t\tclose(FD);\n\tend;\nend.\n", "language": "Free-Pascal-Lazarus" }, { "code": "' FB 1.05.0 Win64\n\nOpen \"output.txt\" For Output As #1\nPrint #1, \"This is a string\"\nClose #1\n", "language": "FreeBASIC" }, { "code": "w = new Writer[\"test.txt\"]\nw.print[\"I am the captain now.\"]\nw.close[]\n", "language": "Frink" }, { "code": "void local fn SaveFile\nCFStringRef fileString = @\"The quick brown fox jumped over the lazy dog's back.\"\nCFURLRef url = savepanel 1, @\"Choose location to save file.\", @\"txt\", @\"Untitled\", @\"Save\"\nif (url)\n fn StringWriteToURL( fileString, url, YES, NSUTF8StringEncoding, NULL )\nelse\n // User canceled\nend if\nend fn\n\nfn SaveFile\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nFile.Save(User.home &/ \"test.txt\", \"(Over)write a file so that it contains a string.\")\n\nEnd\n", "language": "Gambas" }, { "code": "import \"io/ioutil\"\n\nfunc main() {\n ioutil.WriteFile(\"path/to/your.file\", []byte(\"data\"), 0644)\n}\n", "language": "Go" }, { "code": " new File(\"myFile.txt\").text = \"\"\"a big string\nthat can be\nsplitted over lines\n\"\"\"\n", "language": "Groovy" }, { "code": "main :: IO ( )\nmain = do\n putStrLn \"Enter a string!\"\n str <- getLine\n putStrLn \"Where do you want to store this string ?\"\n myFile <- getLine\n appendFile myFile str\n", "language": "Haskell" }, { "code": " characters fwrite filename\n", "language": "J" }, { "code": " characters 1!:2<filename\n", "language": "J" }, { "code": "import java.io.*;\n\npublic class Test {\n\n public static void main(String[] args) throws IOException {\n try (BufferedWriter bw = new BufferedWriter(new FileWriter(\"test.txt\"))) {\n bw.write(\"abc\");\n }\n }\n}\n", "language": "Java" }, { "code": "import java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.StandardOpenOption;\n\npublic final class WriteEntireFile {\n\n\tpublic static void main(String[] aArgs) throws IOException {\n\t\tString contents = \"Hello World\";\n\t\tString filePath = \"output.txt\";\n\t\t\n\t\tFiles.write(Path.of(filePath), contents.getBytes(), StandardOpenOption.CREATE);\n\t}\n\n}\n", "language": "Java" }, { "code": "function writeFile(filename, data)\n\tf = open(filename, \"w\")\n\twrite(f, data)\n\tclose(f)\nend\n\nwriteFile(\"test.txt\", \"Hi there.\")\n", "language": "Julia" }, { "code": "\"example.txt\" 0:\"example file contents\"\n", "language": "K" }, { "code": "// version 1.1.2\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n val text = \"empty vessels make most noise\"\n File(\"output.txt\").writeText(text)\n}\n", "language": "Kotlin" }, { "code": "----------------------------------------\n-- Saves string as file\n-- @param {string} tFile\n-- @param {string} tString\n-- @return {bool} success\n----------------------------------------\non writeFile (tFile, tString)\n fp = xtra(\"fileIO\").new()\n fp.openFile(tFile, 2)\n err = fp.status()\n if not (err) then fp.delete()\n else if (err and not (err = -37)) then return false\n fp.createFile(tFile)\n if fp.status() then return false\n fp.openFile(tFile, 2)\n if fp.status() then return false\n fp.writeString(tString)\n fp.closeFile()\n return true\nend\n", "language": "Lingo" }, { "code": "put \"this is a string\" into URL \"file:~/Desktop/TestFile.txt\"\n", "language": "LiveCode" }, { "code": "function writeFile (filename, data)\n\tlocal f = io.open(filename, 'w')\n\tf:write(data)\n\tf:close()\nend\n\nwriteFile(\"stringFile.txt\", \"Mmm... stringy.\")\n", "language": "Lua" }, { "code": "Export(\"directory/filename.txt\", string);\n", "language": "Maple" }, { "code": "Export[\"filename.txt\",\"contents string\"]\n", "language": "Mathematica" }, { "code": "import Nanoquery.IO\n\nnew(File, fname).create().write(string)\n", "language": "Nanoquery" }, { "code": "writeFile(\"filename.txt\", \"An arbitrary string\")\n", "language": "Nim" }, { "code": "use System.IO.File;\n\nclass WriteFile {\n function : Main(args : String[]) ~ Nil {\n writer ← FileWriter→New(\"test.txt\");\n leaving {\n writer→Close();\n };\n writer→WriteString(\"this is a test string\");\n }\n}\n", "language": "Objeck" }, { "code": "let write_file filename s =\n let oc = open_out filename in\n output_string oc s;\n close_out oc;\n;;\n\nlet () =\n let filename = \"test.txt\" in\n let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in\n write_file filename s\n", "language": "OCaml" }, { "code": "{$ifDef FPC}{$mode ISO}{$endIf}\nprogram overwriteFile(FD);\nbegin\n\twriteLn(FD, 'Whasup?');\n\tclose(FD);\nend.\n", "language": "Pascal" }, { "code": "./overwriteFile >&- <&- 0>/tmp/foo # open file descriptor with index 0 for writing\n", "language": "Pascal" }, { "code": "use File::Slurper 'write_text';\nwrite_text($filename, $data);\n", "language": "Perl" }, { "code": "use Path::Tiny;\npath($filename)->spew_utf8($data);\n", "language": "Perl" }, { "code": "open my $fh, '>:encoding(UTF-8)', $filename or die \"Could not open '$filename': $!\";\nprint $fh $data;\nclose $fh;\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (file i/o)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">write_lines</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"file.txt\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"line 1\\nline 2\"</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">=-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #7060A8;\">crash</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"error\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "file_put_contents($filename, $data)\n", "language": "PHP" }, { "code": "(out \"file.txt\"\n (prinl \"My string\") )\n", "language": "PicoLisp" }, { "code": "Stdio.write_file(\"file.txt\", \"My string\");\n", "language": "Pike" }, { "code": "Get-Process | Out-File -FilePath .\\ProcessList.txt\n", "language": "PowerShell" }, { "code": "EnableExplicit\n\nDefine fOutput$ = \"output.txt\" ; enter path of file to create or overwrite\nDefine str$ = \"This string is to be written to the file\"\n\nIf OpenConsole()\n If CreateFile(0, fOutput$)\n WriteString(0, str$)\n CloseFile(0)\n Else\n PrintN(\"Error creating or opening output file\")\n EndIf\n PrintN(\"Press any key to close the console\")\n Repeat: Delay(10) : Until Inkey() <> \"\"\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "with open(filename, 'w') as f:\n f.write(data)\n", "language": "Python" }, { "code": "from pathlib import Path\n\nPath(filename).write_text(any_string)\nPath(filename).write_bytes(any_binary_data)\n", "language": "Python" }, { "code": "f = FREEFILE\nOPEN \"output.txt\" FOR OUTPUT AS #f\nPRINT #f, \"This string is to be written to the file\"\nCLOSE #\n", "language": "QBasic" }, { "code": "#lang racket/base\n(with-output-to-file \"/tmp/out-file.txt\" #:exists 'replace\n (lambda () (display \"characters\")))\n", "language": "Racket" }, { "code": "spurt 'path/to/file', $file-data;\n", "language": "Raku" }, { "code": "'path/to/file'.IO.spurt: $file-data;\n", "language": "Raku" }, { "code": "# Program to overwrite an existing file\n\nopen(11,FILE=\"file.txt\")\n101 format(A)\nwrite(11,101) \"Hello World\"\nclose(11)\n\nend\n", "language": "RATFOR" }, { "code": "/*REXX*/\n\nof='file.txt'\n'erase' of\ns=copies('1234567890',10000)\nCall charout of,s\nCall lineout of\nSay chars(of) length(s)\n", "language": "REXX" }, { "code": "/*REXX program writes an entire file with a single write (a long text record). */\noFID= 'OUTPUT.DAT' /*name of the output file to be used. */\n /* [↓] 50 bytes, including the fences.*/\n$ = '<<<This is the text that is written to a file. >>>'\n /* [↓] COPIES creates a 50k byte str.*/\ncall charout oFID, copies($,1000), 1 /*write the longish text to the file. */\n /* [↑] the \"1\" writes text ──► rec #1*/\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "write(\"myfile.txt\",\"Hello, World!\")\n", "language": "Ring" }, { "code": "open(fname, 'w'){|f| f.write(str) }\n", "language": "Ruby" }, { "code": "open \"output.txt\" for output as #1\nprint #1, \"This string is to be written to the file\"\nclose #1\n", "language": "Run-BASIC" }, { "code": "use std::fs::File;\nuse std::io::Write;\n\nfn main() -> std::io::Result<()> {\n let data = \"Sample text.\";\n let mut file = File::create(\"filename.txt\")?;\n write!(file, \"{}\", data)?;\n Ok(())\n}\n", "language": "Rust" }, { "code": "import java.io.{File, PrintWriter}\n\nobject Main extends App {\n val pw = new PrintWriter(new File(\"Flumberboozle.txt\"),\"UTF8\"){\n print(\"My zirconconductor short-circuited and I'm having trouble fixing this issue.\\nI researched\" +\n \" online and they said that I need to connect my flumberboozle to the XKG virtual port, but I was\" +\n \" wondering if I also needed a galvanized tungsten retrothruster array? Maybe it'd help the\" +\n \" frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?\")\n close()}\n}\n", "language": "Scala" }, { "code": "put \"New String\" into file \"~/Desktop/myFile.txt\"\n", "language": "SenseTalk" }, { "code": "var file = File(__FILE__)\nfile.open_w(\\var fh, \\var err) || die \"Can't open #{file}: #{err}\"\nfh.print(\"Hello world!\") || die \"Can't write to #{file}: #{$!}\"\n", "language": "Sidef" }, { "code": "File(__FILE__).open_w.print(\"Hello world!\")\n", "language": "Sidef" }, { "code": "'file.txt' asFilename contents:'Hello World'\n", "language": "Smalltalk" }, { "code": "#.writetext(\"file.txt\",\"This is the string\")\n", "language": "SPL" }, { "code": "fun writeFile (path, str) =\n (fn strm =>\n TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)\n", "language": "Standard-ML" }, { "code": "proc writefile {filename data} {\n set fd [open $filename w] ;# truncate if exists, else create\n try {\n puts -nonewline $fd $data\n } finally {\n close $fd\n }\n}\n", "language": "Tcl" }, { "code": "OPEN #1: NAME \"output.txt\", CREATE NEWOLD\nPRINT #1: \"This string is to be written to the file\"\nCLOSE #1\nEND\n", "language": "True-BASIC" }, { "code": "$$ MODE TUSCRIPT\ncontent=\"new text that will overwrite content of myfile\"\nLOOP\n path2file=FULLNAME (TUSTEP,\"myfile\",-std-)\n status=WRITE (path2file,content)\n IF (status==\"OK\") EXIT\n IF (status==\"CREATE\") ERROR/STOP CREATE (\"myfile\",seq-o,-std-)\nENDLOOP\n", "language": "TUSCRIPT" }, { "code": "import os\n\nos.write_file('./hello_text.txt', 'Hello there!') or {println('Error: failed to write.') exit(1)}\n", "language": "V-(Vlang)" }, { "code": "Option Explicit\n\nConst strName As String = \"MyFileText.txt\"\nConst Text As String = \"(Over)write a file so that it contains a string. \" & vbCrLf & _\n \"The reverse of Read entire file—for when you want to update or \" & vbCrLf & _\n \"create a file which you would read in its entirety all at once.\"\n\nSub Main()\nDim Nb As Integer\n\nNb = FreeFile\nOpen \"C:\\Users\\\" & Environ(\"username\") & \"\\Desktop\\\" & strName For Output As #Nb\n Print #1, Text\nClose #Nb\nEnd Sub\n", "language": "VBA" }, { "code": "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nSourceFile = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\out.txt\"\nContent = \"(Over)write a file so that it contains a string.\" & vbCrLf &_\n\t\t\"The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.\"\n\t\t\nWith objFSO.OpenTextFile(SourceFile,2,True,0)\n\t.Write Content\n\t.Close\nEnd With\n\nSet objFSO = Nothing\n", "language": "VBScript" }, { "code": "Module Module1\n\n Sub Main()\n My.Computer.FileSystem.WriteAllText(\"new.txt\", \"This is a string\", False)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"io\" for File\n\n// create a text file\nFile.create(\"hello.txt\") { |file|\n file.writeBytes(\"hello\")\n}\n\n// check it worked\nSystem.print(File.read(\"hello.txt\"))\n\n// overwrite it by 'creating' the file again\nFile.create(\"hello.txt\") {|file|\n file.writeBytes(\"goodbye\")\n}\n\n// check it worked\nSystem.print(File.read(\"hello.txt\"))\n", "language": "Wren" }, { "code": "(define n (open-output-file \"example.txt\"))\n(write \"(Over)write a file so that it contains a string.\" n)\n(close-output-port n)\n", "language": "XLISP" }, { "code": "[FSet(FOpen(\"output.txt\", 1), ^o);\nText(3, \"This is a string.\");\n]\n", "language": "XPL0" }, { "code": "open \"output.txt\" for writing as #1\nprint #1 \"This is a string\"\nclose #1\n", "language": "Yabasic" }, { "code": " // write returns bytes written, GC will close the file (eventually)\nFile(\"foo\",\"wb\").write(\"this is a test\",1,2,3); //-->17\n\nf:=File(\"bar\",wb\");\ndata.pump(f,g); // use g to process data as it is written to file\nf.close(); // don't wait for GC\n", "language": "Zkl" } ]
Write-entire-file
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII\n", "language": "00-META" }, { "code": ";Task:\nWrite/display a language's name in '''3D''' ASCII. \n\n\n(We can leave the definition of \"3D ASCII\" fuzzy, \nso long as the result is interesting or amusing, \nnot a cheap hack to satisfy the task.)\n\n\n;Related tasks:\n* [[Draw_a_sphere|draw a sphere]]\n* [[Draw_a_cuboid|draw a cuboid]]\n* [[Draw_a_rotating_cube|draw a rotating cube]]\n* [[Death_Star|draw a Deathstar]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V s =\n|‘ XX\n X\n X\n X\n X\n X\n XXXXX’\n\nV lines = s.split(\"\\n\")\nV width = max(lines.map(l -> l.len))\n\nL(line) lines\n print((‘ ’ * (lines.len - L.index - 1))‘’(line.ljust(width).replace(‘ ’, ‘ ’).replace(‘X’, ‘__/’) * 3))\n", "language": "11l" }, { "code": "THREED CSECT\n STM 14,12,12(13)\n BALR 12,0\n USING *,12\n XPRNT =CL23'0 ####. #. ###.',23\n XPRNT =CL24'1 #. #. #. #.',24\n XPRNT =CL24'1 ##. # ##. #. #.',24\n XPRNT =CL24'1 #. #. #. #. #.',24\n XPRNT =CL23'1 ####. ###. ###.',23\n LM 14,12,12(13)\n BR 14\n LTORG\n END\n", "language": "360-Assembly" }, { "code": "BYTE ARRAY data = [\n $00 $00 $00 $00 $4E $4E $4E $00 $00 $00 $00 $00 $00 $00 $00 $00 $4E $00 $00 $00 $00 $4E $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $4E $00 $00 $00\n $00 $00 $00 $46 $47 $00 $00 $47 $00 $00 $00 $00 $00 $00 $00 $42 $47 $47 $00 $00 $42 $47 $47 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $42 $47 $47 $00 $00\n $00 $00 $42 $47 $48 $80 $80 $80 $4A $00 $00 $4E $4E $4E $00 $42 $00 $80 $4E $00 $00 $47 $80 $00 $00 $4E $4E $00 $00 $00 $4E $4E $4E $00 $00 $42 $00 $80 $00 $00\n $00 $00 $42 $00 $80 $00 $42 $00 $80 $00 $46 $47 $00 $00 $47 $42 $00 $80 $00 $47 $00 $4E $00 $00 $46 $47 $00 $47 $00 $42 $47 $00 $00 $47 $00 $42 $00 $80 $00 $00\n $00 $00 $42 $00 $80 $00 $42 $00 $80 $42 $47 $48 $80 $80 $80 $42 $00 $80 $80 $80 $42 $47 $47 $42 $47 $48 $80 $80 $4A $42 $00 $80 $80 $80 $4A $42 $00 $80 $00 $00\n $00 $00 $42 $00 $80 $4D $4D $47 $80 $42 $00 $80 $00 $00 $00 $42 $00 $80 $00 $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $00\n $00 $00 $42 $00 $80 $80 $80 $80 $80 $42 $00 $80 $00 $00 $00 $42 $00 $80 $00 $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $47 $80 $00 $00\n $00 $00 $42 $00 $80 $00 $42 $00 $80 $42 $00 $80 $4E $4E $00 $42 $00 $80 $4E $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $4E $00 $00 $00\n $00 $00 $42 $00 $80 $00 $42 $00 $80 $00 $47 $80 $00 $00 $47 $00 $47 $80 $00 $47 $42 $00 $80 $00 $47 $80 $4D $47 $80 $42 $00 $80 $42 $00 $80 $42 $47 $47 $00 $00\n $00 $00 $00 $47 $80 $00 $00 $47 $80 $00 $00 $CA $80 $80 $80 $00 $00 $CA $80 $80 $00 $47 $80 $00 $00 $CA $80 $80 $C8 $00 $47 $80 $00 $47 $80 $00 $47 $80 $00 $00]\n\nPROC Main()\n BYTE POINTER ptr\n\n Graphics(0)\n SetColor(2,0,2)\n ptr=PeekC(88)+280\n MoveBlock(ptr,data,400)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\nprocedure AsciiArt is\n art : constant array(1..27) of String(1..14) :=\n (1=>\" /\\\\\\\\\\\\ \", 2=>\" /\\\\\\\",\n 3|6|9=>\" \", 4|12=>\" /\\\\\\\\\\\\\\\\\\\\ \",\n 5|8|11=>\" \\/\\\\\\\", 7|17|21=>\" /\\\\\\//////\\\\\\\",\n 10|19|20|22=>\"\\/\\\\\\ \\/\\\\\\\", 13|23|24=>\"\\/\\\\\\\\\\\\\\\\\\\\\\\\\",\n 14|18=>\" /\\\\\\\\\\\\\\\\\\\\\\\", 15=>\" \\/////////\\\\\\\",\n 16=>\"\\/\\\\\\//////\\\\\\\", 25=>\"\\/// \\/// \",\n 26|27=>\"\\//////////// \");\nbegin\n for i in art'Range loop\n Put(art(i)&' ');\n if i mod 3 = 0 then New_Line; Put(i/3*' '); end if;\n end loop;\nend AsciiArt;\n", "language": "Ada" }, { "code": "10 S$ = \"BASIC\" : REM OUR LANGUAGE NAME\n20 DIM B(5,5) : REM OUR BIGMAP CHARACTERS\n30 FOR L = 1 TO 5 : REM 5 CHARACTERS\n40 FOR M = 1 TO 5 : REM 5 ROWS\n50 READ B(L,M)\n60 NEXT M, L\n\n100 GR : REM BLACK BACKGROUND\n110 COLOR = 1 : REM OUR SHADOW WILL BE RED\n120 HOME : REM CLS\n130 R = 9 : REM SHADOW WILL START ON ROW 5\n140 C = 2 : REM SHADOW WILL START AT COLUMN 2\n150 GOSUB 2000\"DRAW SHADOW\n160 COLOR = 13 : REM OUR FOREGROUND WILL BE YELLOW\n170 R = 10 : REM FOREGROUND WILL START ON ROW 6\n180 C = 3 : REM FOREGROUND WILL START ON COLUMN 3\n190 GOSUB 2000\"DISPLAY THE LANGUAGE NAME\n\n999 STOP\n\n1000 REM CONVERT TO BINARY BIGMAP\n1010 T = N : REM TEMPORARY VARIABLE\n1020 G$ = \"\" : REM THIS WILL CONTAIN OUR 5 CHARACTER BINARY BIGMAP\n1040 FOR Z = 5 TO 0 STEP -1\n1050 D$ = \" \" : REM ASSUME NEXT DIGIT IS ZERO (DRAW A SPACE)\n1055 S = 2 ^ Z\n1060 IF T >= S THEN D$ = \"*\" : T = T - S : REM IS A BLOCK\n1070 G$ = G$ + D$\n1080 NEXT Z\n1090 RETURN\n\n2000 REM DISPLAY THE BIG LETTERS\n2010 FOR L = 1 TO 5 : REM OUR 5 ROWS\n2020 X = C : Y = R + L - 1 : REM PRINT AT R+L-1,C;\n2030 FOR M = 1 TO 5 : REM BIGMAP FOR EACH CHARACTER\n2040 N = B(M, L)\n2050 GOSUB 1000\n2060 FOR I = 1 TO LEN(G$) : IF MID$(G$, I, 1) <> \" \" THEN PLOT X,Y :REM 5 CHARACTER BIGMAP\n2070 X = X + 1 : NEXT I\n2080 X = X + 1 : REM PRINT \" \";: REM SPACE BETWEEN EACH LETTER\n2090 NEXT M, L\n2100 RETURN\n\n9000 DATA 30,17,30,17,30: REM B\n9010 DATA 14,17,31,17,17: REM A\n9020 DATA 15,16,14,1,30: REM S\n9030 DATA 31,4,4,4,31: REM I\n9040 DATA 14,17,16,17,14: REM C\n", "language": "Applesoft-BASIC" }, { "code": "print {:\n ______ __\n/\\ _ \\ /\\ \\__\n\\ \\ \\L\\ \\ _ __\\ \\ ,_\\ __ __ _ __ ___\n \\ \\ __ \\/\\`'__\\ \\ \\/ /\\ \\/\\ \\/\\`'__\\/ __`\\\n \\ \\ \\/\\ \\ \\ \\/ \\ \\ \\_\\ \\ \\_\\ \\ \\ \\//\\ \\L\\ \\\n \\ \\_\\ \\_\\ \\_\\ \\ \\__\\\\ \\____/\\ \\_\\\\ \\____/\n \\/_/\\/_/\\/_/ \\/__/ \\/___/ \\/_/ \\/___/\n:}\n", "language": "Arturo" }, { "code": "AutoTrim, Off\ndraw =\n(\n ______ __ __ __ __\n/\\ __ \\/\\ \\_\\ \\/\\ \\/ /\n\\ \\ __ \\ \\ __ \\ \\ _\"-.\n \\ \\_\\ \\_\\ \\_\\ \\_\\ \\_\\ \\_\\\n \\/_/\\/_/\\/_/\\/_/\\/_/\\/_/\n)\nGui, +ToolWindow\nGui, Color, 1A1A1A, 1A1A1A\nGui, Font, s8 cLime w800, Courier New\nGui, Add, text, x4 y0 , % \" \" draw\nGui, Show, w192 h82, AHK in 3D\nreturn\n\nGuiClose:\nExitApp\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f WRITE_LANGUAGE_NAME_IN_3D_ASCII.AWK\nBEGIN {\n arr[1] = \" xxxx x x x x\"\n arr[2] = \"x x x x x x\"\n arr[3] = \"x x x x x x\"\n arr[4] = \"xxxxxx x x xx\"\n arr[5] = \"x x x xx x xx\"\n arr[6] = \"x x xx xx x x\"\n arr[7] = \"x x xx xx x x\"\n arr[8] = \"A V P J B W\"\n for (i=1; i<=8; i++) {\n x = arr[i]\n gsub(/./,\"& \",x)\n gsub(/[xA-Z] /,\"_/\",x)\n print(x)\n }\n exit(0)\n}\n", "language": "AWK" }, { "code": "@echo off\nfor %%b in (\n\"\"\n\" /####### ###### /######## ###### /## /##\"\n\"| ##__ ## /##__ ##|__ ##__/ /##__ ##| ## | ##\"\n\"| ## | ##| ## | ## | ## | ## \\__/| ## | ##\"\n\"| ####### | ######## | ## | ## | ########\"\n\"| ##__ ##| ##__ ## | ## | ## | ##__ ##\"\n\"| ## | ##| ## | ## | ## | ## /##| ## | ##\"\n\"| #######/| ## | ## | ## | ######/| ## | ##\"\n\"|_______/ |__/ |__/ |__/ \\______/ |__/ |__/\"\n\"\"\n) do echo(%%~b\npause\n", "language": "Batch-File" }, { "code": " PROC3dname(\"BBC BASIC\")\n END\n\n DEF PROC3dname(name$)\n LOCAL A%, X%, Y%, char%, row%, patt%, bit%\n DIM X% 8 : A% = 10 : Y% = X% DIV 256\n FOR row% = 1 TO 8\n FOR char% = 1 TO LEN(name$)\n ?X% = ASCMID$(name$,char%)\n CALL &FFF1\n patt% = X%?row%\n FOR bit% = 7 TO 0 STEP -1\n CASE TRUE OF\n WHEN (patt% AND 2^bit%) <> 0 : PRINT \"#\";\n WHEN GET$(POS-1,VPOS-1) = \"#\": PRINT \"\\\";\n OTHERWISE: PRINT \" \";\n ENDCASE\n NEXT\n NEXT char%\n PRINT\n NEXT row%\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "0\" &7&%h&'&%| &7&%7%&%&'&%&'&%&7&%\"v\nv\"'%$%'%$%3$%$%7% 0%&7&%&7&(%$%'%$\"<\n>\"%$%7%$%&%$%&'&%7%$%7%$%, '&+(%$%\"v\nv\"+&'&%+('%$%$%'%$%$%$%$%$%$%$%'%$\"<\n>\"(%$%$%'%$%$%( %$+(%&%$+(%&%$+(%&\"v\nv\"(; $%$%(+$%&%(+$%$%'%$%+&%$%$%$%\"<\n? \";(;(+(+$%+(%&(;(3%$%&$ 7`+( \":v >\n^v!:-1<\\,:g7+*63%4 \\/_#4:_v#:-*84_$@\n$_\\:,\\^ >55+,$:^:$\n", "language": "Befunge" }, { "code": "v THE DATA IMAGE.(totally useless after loading into stack)\n>89 v Made by gamemanj\nv0000122010000000000022201220000020000< For rosettacode\n>9 v The 'image' is upsidedown\nv2220100010002220101000101000000000000< The 3d offset isn't applied on this\n>9 v and it's encoded weirdly\nv1010122012001010101022201220000010000< Is that enough decoding needed\n>9 v for the '3d' ascii requirement?\nv2220100010001010222010101000000010000< Huh.(sees Batch) I think so.\n>9 v 0:blank\nv1000122012200000000022201220000010000< 1:\\\n>9 v 2:-\nv p000< 9:newline\n>:9-v Check for 9:Newline 8:end\n v_v (note that cell 0,0 isn't ever used after the first tick!)\n no yes | | >\" \",v\n >$55+,00g1+:00p:|: -1< Newline With Spacing Encoder\n^ v# $<\n :\n 8 check for end\n no-yes\n v_v\n >< make the program pause for the user forever.Ik,it's stupid\n\n Numeric Decoder \\/\n >:1-v\n v_vCheck for 1 '\\'\n NO: \"YES\n 2 \\\n - \"\n v_ >v\n \" \"\n^ -\n \" \"\n^ $,< < < (code path reuse here,all 3 end in ,$ so I merged them)\n", "language": "Befunge" }, { "code": "++++[>++++>++<[>>++>+++>++++++> ++++++<<<<<-]<-]>>++>..>->---->\n-...[<]<+++[>++++[>>...<<-]<-]> >>..>>>.....<<<..>>>...[<]++[>>\n.....>>>...<<<<<-]>.>.>.>.<<..> >.[<]<+++++[>++++[>>.<<-]<-]>>>\n..>>>...[<]+++++[>>..<<-]+++>>. >.<..>>>...<.[[>]<.<.<<..>>.>..\n<<<.<<-]+++>.>.>>.<<.>>.<<..>>. >....<<<.>>>...<<<..>>>...<<<.>\n>>......<<.>.>..<.<<..>>>..<<<. .>>>....<.<<..>>.>..<<.[[>]<<.>\n..<<<...>>>.<.<<<<-]+++>.>..>>. <<.>>.<<...>>>..<<<.>>..<<..>>.\n<.<.>>>..<..>...<<<...>>.<<.>>> .<<.>>.<<.<..>>.<.<.>>>.<<<..>>\n.>.<<<...>>>..<.>.<<.>.>..<.<.. >>.<<.>.>..<.<..>>.<<.>.>..<.<.\n<<.>...>>.<<.>>.<<..>>.<.>.<<.> >..<<...>.>>..<<..>>...<.<<...>\n>..<<..>>..<<...>.<.>>.<<..>>.. <<..>>.>.<<.<[[>]<<<<.>>.<.>>..\n<<.<..<<-]>.>....>>.<<.>>.<<..> >.>.<.<<.>>..<<..>>.<<...>.>.<<\n..>>>.<<<....>>..<<..>>..<<..>> ..<<.>>.<<..>>..<<..>>.<<<.>...\n..>>.<<.>>.>......<..>..<.<<..> >.<<.>>.>...<<.>.>..<..>..<..>.\n.<..<<.>>.>..<..>..<.<<<.>..... .>>.<.>>......<<..>>..<<.<...>>\n.<.>>..<<.>.<.>>..<<..>>..<<..> >..<<.<.>>.<.>>..<<..>>..<<.<<.\n", "language": "Brainf---" }, { "code": "#include <stdio.h>\nconst char*s = \" _____\\n /____/\\\\\\n/ ___\\\\/\\n\\\\ \\\\/__/\\n \\\\____/\";\nint main(){ puts(s); return 0; }\n", "language": "C" }, { "code": "#include <windows.h>\n#include <iostream>\n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nint main(int argc, char* argv[])\n{\n\tcout <<\n\t\t\" ______ ______ \" << endl <<\n\t\t\" _____ _____|\\\\ \\\\ _____|\\\\ \\\\ \" << endl <<\n\t\t\" _____\\\\ \\\\_ / / | | / / | |\" << endl <<\n\t\t\" / /| || |/ /|| |/ /|\" << endl <<\n\t\t\" / / /____/|| |\\\\____/ || |\\\\____/ |\" << endl <<\n\t\t\"| | |____|/ |\\\\ \\\\ | / |\\\\ \\\\ | / \" << endl <<\n\t\t\"| | _____ | \\\\ \\\\___|/ | \\\\ \\\\___|/ \" << endl <<\n\t\t\"|\\\\ \\\\|\\\\ \\\\ | \\\\ \\\\ | \\\\ \\\\ \" << endl <<\n\t\t\"| \\\\_____\\\\| | \\\\ \\\\_____\\\\ \\\\ \\\\_____\\\\ \" << endl <<\n\t\t\"| | /____/| \\\\ | | \\\\ | | \" << endl <<\n\t\t\" \\\\|_____| || \\\\|_____| \\\\|_____| \" << endl <<\n\t\t\" |____|/ \";\n\n\tcout << endl << endl << endl;\n\n\tsystem( \"pause\" );\n\treturn 0;\n}\n//--------------------------------------------------------------------------------------------------\n", "language": "C++" }, { "code": "// @author Martin Ettl (http://www.martinettl.de)\n// @date 2013-07-26\n// A program to print the letters 'CPP' in 3D ASCII-art.\n\n#include <iostream>\n#include <string>\n\nint main()\n{\n std::string strAscii3D =\n \" /$$$$$$ /$$$$$$$ /$$$$$$$ \\n\"\n \" /$$__ $$| $$__ $$| $$__ $$\\n\"\n \"| $$ \\\\__/| $$ \\\\ $$| $$ \\\\ $$\\n\"\n \"| $$ | $$$$$$$/| $$$$$$$/\\n\"\n \"| $$ | $$____/ | $$____/ \\n\"\n \"| $$ $$| $$ | $$ \\n\"\n \"| $$$$$$/| $$ | $$ \\n\"\n \" \\\\______/ |__/ |__/ \\n\";\n\n std::cout << \"\\n\" << strAscii3D << std::endl;\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Text;\n\nnamespace Language_name_in_3D_ascii\n{\n public class F5\n {\n char[] z = { ' ', ' ', '_', '/', };\n long[,] f ={\n {87381,87381,87381,87381,87381,87381,87381,},\n {349525,375733,742837,742837,375733,349525,349525,},\n {742741,768853,742837,742837,768853,349525,349525,},\n {349525,375733,742741,742741,375733,349525,349525,},\n {349621,375733,742837,742837,375733,349525,349525,},\n {349525,375637,768949,742741,375733,349525,349525,},\n {351157,374101,768949,374101,374101,349525,349525,},\n {349525,375733,742837,742837,375733,349621,351157,},\n {742741,768853,742837,742837,742837,349525,349525,},\n {181,85,181,181,181,85,85,},\n {1461,1365,1461,1461,1461,1461,2901,},\n {742741,744277,767317,744277,742837,349525,349525,},\n {181,181,181,181,181,85,85,},\n {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,},\n {349525,768853,742837,742837,742837,349525,349525,},\n {349525,375637,742837,742837,375637,349525,349525,},\n {349525,768853,742837,742837,768853,742741,742741,},\n {349525,375733,742837,742837,375733,349621,349621,},\n {349525,744373,767317,742741,742741,349525,349525,},\n {349525,375733,767317,351157,768853,349525,349525,},\n {374101,768949,374101,374101,351157,349525,349525,},\n {349525,742837,742837,742837,375733,349525,349525,},\n {5592405,11883957,11883957,5987157,5616981,5592405,5592405,},\n {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,},\n {349525,742837,375637,742837,742837,349525,349525,},\n {349525,742837,742837,742837,375733,349621,375637,},\n {349525,768949,351061,374101,768949,349525,349525,},\n {375637,742837,768949,742837,742837,349525,349525,},\n {768853,742837,768853,742837,768853,349525,349525,},\n {375733,742741,742741,742741,375733,349525,349525,},\n {192213,185709,185709,185709,192213,87381,87381,},\n {1817525,1791317,1817429,1791317,1817525,1398101,1398101,},\n {768949,742741,768853,742741,742741,349525,349525,},\n {375733,742741,744373,742837,375733,349525,349525,},\n {742837,742837,768949,742837,742837,349525,349525,},\n {48053,23381,23381,23381,48053,21845,21845,},\n {349621,349621,349621,742837,375637,349525,349525,},\n {742837,744277,767317,744277,742837,349525,349525,},\n {742741,742741,742741,742741,768949,349525,349525,},\n {11883957,12278709,11908533,11883957,11883957,5592405,5592405,},\n {11883957,12277173,11908533,11885493,11883957,5592405,5592405,},\n {375637,742837,742837,742837,375637,349525,349525,},\n {768853,742837,768853,742741,742741,349525,349525,},\n {6010197,11885397,11909973,11885397,6010293,5592405,5592405,},\n {768853,742837,768853,742837,742837,349525,349525,},\n {375733,742741,375637,349621,768853,349525,349525,},\n {12303285,5616981,5616981,5616981,5616981,5592405,5592405,},\n {742837,742837,742837,742837,375637,349525,349525,},\n {11883957,11883957,11883957,5987157,5616981,5592405,5592405,},\n {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,},\n {11883957,5987157,5616981,5987157,11883957,5592405,5592405,},\n {11883957,5987157,5616981,5616981,5616981,5592405,5592405,},\n {12303285,5593941,5616981,5985621,12303285,5592405,5592405,}\n };\n\n private F5(string s)\n {\n StringBuilder[] o = new StringBuilder[7];\n for (int i = 0; i < 7; i++) o[i] = new StringBuilder();\n for (int i = 0, l = s.Length; i < l; i++)\n {\n int c = s[i];\n if (65 <= c && c <= 90) c -= 39;\n else if (97 <= c && c <= 122) c -= 97;\n else c = -1;\n long[] d = new long[7];\n Buffer.BlockCopy(f, (++c * sizeof(long) * 7), d, 0, 7 * sizeof(long));\n for (int j = 0; j < 7; j++)\n {\n StringBuilder b = new StringBuilder();\n long v = d[j];\n while (v > 0)\n {\n b.Append(z[(int)(v & 3)]);\n v >>= 2;\n }\n char[] charArray = b.ToString().ToCharArray();\n Array.Reverse(charArray);\n o[j].Append(new string(charArray));\n }\n }\n for (int i = 0; i < 7; i++)\n {\n for (int j = 0; j < 7 - i; j++)\n System.Console.Write(' ');\n System.Console.WriteLine(o[i]);\n }\n }\n\n public static void Main(string[] args)\n {\n new F5(args.Length > 0 ? args[0] : \"C sharp\");\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(use 'clj-figlet.core)\n(println\n (render-to-string\n (load-flf \"ftp://ftp.figlet.org/pub/figlet/fonts/contributed/larry3d.flf\")\n \"Clojure\"))\n", "language": "Clojure" }, { "code": " IDENTIFICATION DIVISION.\n PROGRAM-ID. cobol-3d.\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 cobol-area.\n 03 cobol-text-data PIC X(1030) VALUE \"________/\\\\\\\\\\\\\\\\\\____\n - \"____/\\\\\\\\\\________/\\\\\\\\\\\\\\\\\\\\\\\\\\__________/\\\\\\\\\\________\n - \"/\\\\\\_____________ _____/\\\\\\////////_______/\\\\\\//\n - \"/\\\\\\_____\\/\\\\\\/////////\\\\\\______/\\\\\\///\\\\\\_____\\/\\\\\\____\n - \"_________ ___/\\\\\\/______________/\\\\\\/__\\///\\\\\\__\n - \"_\\/\\\\\\_______\\/\\\\\\____/\\\\\\/__\\///\\\\\\___\\/\\\\\\____________\n - \"_ __/\\\\\\_______________/\\\\\\______\\//\\\\\\__\\/\\\\\\\\\\\n - \"\\\\\\\\\\\\\\\\\\____/\\\\\\______\\//\\\\\\__\\/\\\\\\_____________\n - \" _\\/\\\\\\______________\\/\\\\\\_______\\/\\\\\\__\\/\\\\\\/////////\\\\\\\n - \"__\\/\\\\\\_______\\/\\\\\\__\\/\\\\\\_____________ _\\//\\\\\\_\n - \"____________\\//\\\\\\______/\\\\\\___\\/\\\\\\_______\\/\\\\\\__\\//\\\\\\\n - \"______/\\\\\\___\\/\\\\\\_____________ __\\///\\\\\\_______\n - \"_____\\///\\\\\\__/\\\\\\_____\\/\\\\\\_______\\/\\\\\\___\\///\\\\\\__/\\\\\\\n - \"_____\\/\\\\\\_____________ ____\\////\\\\\\\\\\\\\\\\\\_____\\\n - \"///\\\\\\\\\\/______\\/\\\\\\\\\\\\\\\\\\\\\\\\\\/______\\///\\\\\\\\\\/______\\/\\\n - \"\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _______\\/////////________\\/////_\n - \"_______\\/////////////__________\\/////________\\//////////\n - \"/////__\" *> \" Sorry for the syntax highlighting.\n .\n 03 cobol-text-table REDEFINES cobol-text-data.\n 05 cobol-text PIC X(103) OCCURS 10 TIMES.\n\n 01 i PIC 99.\n 01 j PIC 9(4).\n\n PROCEDURE DIVISION.\n *> Display 'COBOL' line-by-line applying a shadow effect.\n PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i\n MOVE 1 TO j\n PERFORM UNTIL 103 < j\n *> When the top of a letter meets the right edge,\n *> take care to shadow only the wall ('/').\n IF cobol-text (i) (j:4) = \"\\\\\\/\"\n DISPLAY cobol-text (i) (j:3) AT LINE i COL j\n WITH FOREGROUND-COLOR 7, HIGHLIGHT\n\n ADD 3 TO j\n DISPLAY cobol-text (i) (j:1) AT LINE i COL j\n WITH FOREGROUND-COLOR 0, HIGHLIGHT\n\n ADD 1 TO j\n\n EXIT PERFORM CYCLE\n END-IF\n\n *> Apply shadows to the walls, base and the char\n *> before the base.\n IF cobol-text (i) (j:1) = \"/\"\n OR cobol-text (i) (FUNCTION SUM(j, 1):1) = \"/\"\n OR cobol-text (i) (FUNCTION SUM(j, 1):2)\n = \"\\/\"\n DISPLAY cobol-text (i) (j:1) AT LINE i COL j\n WITH FOREGROUND-COLOR 0, HIGHLIGHT\n *> Do not apply a shadow to anything else.\n ELSE\n DISPLAY cobol-text (i) (j:1) AT LINE i COL j\n WITH FOREGROUND-COLOR 7 , HIGHLIGHT\n END-IF\n\n ADD 1 TO j\n END-PERFORM\n END-PERFORM\n\n *> Prompt the user so that they have a chance to see the\n *> ASCII art, as sometimes the screen data is overwritten by\n *> what was on the console before starting the program.\n DISPLAY \"Press enter to stop appreciating COBOL in 3D.\"\n AT LINE 11 COL 1\n ACCEPT i AT LINE 11 COL 46\n\n GOBACK\n .\n", "language": "COBOL" }, { "code": "(ql:quickload :cl-ppcre)\n(defvar txt\n\"\n xxxx xxxx x x x x xxxx x x x x xxxx xxxxx\nx x x x xx xx xx xx x x xx x x x x x x\nx x x x xx x x xx x x x x x x x x xxx x x\nx x x x x x x x x x x x x x xxx xxxxx\nx x x x x x x x x x x xx x x x x x\n xxxx xxxx x x x x xxxx x x xxxxx x xxxx x\n\"\n)\n(princ (cl-ppcre:regex-replace-all \" \" (cl-ppcre:regex-replace-all \"x\" txt \"_/\") \" \" ))\n", "language": "Common-Lisp" }, { "code": "startshape START\n\nshape START {\n\tloop i = 6 [y -1 x -1 z 10] NAME [b 1-((i+1)*0.11)]\n}\n\nshape NAME {\t\n\tC [ x 34 z 1]\n\tO [ x 46 z 2]\n\tN [ x 64 z 3]\n\tT [ x 85 z 4]\n\tE [ x 95 z 5]\n\tX [ x 106 z 6]\n\tT [ x 125 z 7]\n\t\n\tHYPHEN[x 135]\n\n\tF [ x 145 z 8]\n\tR [ x 158 z 9]\n\tE [ x 175 z 10]\n\tE [ x 188 z 11]\n\t\n\n}\n\nshape C {\n\tARCL [ y 12 flip 90 ]\n\tARCL [ y 12 r 180 ]\n}\n\n\nshape E {\n\tLINE [ s 0.9 ]\n\tLINE [ s 0.9 -1 y 24 ]\n\tLINE [ s 0.4 r -90 y 0 ]\n\tLINE [ s 0.4 r -90 y 12 ]\n\tLINE [ s 0.4 r -90 y 24 ]\n}\n\nshape F {\t\n\tLINE [ s 0.9 -1 y 24 ]\n\tLINE [ s 0.4 r -90 y 12 ]\n\tLINE [ s 0.4 r -90 y 24 ]\n}\n\n\nshape M {\n\tLINE [ y 24 r 180 ]\n\tLINE [ y 24 r -160 s 0.75 ]\n\tLINE [ y 24 x 12 r 160 s 0.75 ]\n\tLINE [ y 24 x 12 r 180 ]\n}\n\nshape N {\n\tLINE [ y 24 r 180 ]\n\tLINE [ y 24 r -160 ]\n\tLINE [ y 24 x 9 r 180 ]\n}\n\nshape O {\n\tARCL [ y 12 flip 90]\n\tARCL [ y 12 r 180 ]\n\tARCL [ y 12 x 14 r 180 flip 90]\n\tARCL [ y 12 x 14 ]\n}\n\nshape R {\t\n\tLINE [ s 0.9 -1 y 24 ]\n\tLINE [ s 0.4 r -90 y 12 ]\n\tLINE [ s 0.4 r -90 y 24 ]\n\tLINE [ y 12 r -140 s 0.65 ]\n\n\tARCL [ y 18 x 12 r 180 flip 90 s 0.8 0.5]\n\tARCL [ y 18 x 12 s 0.8 0.5 ]\n\n}\n\nshape T {\t\n\tLINE [ s 0.9 -1 y 24 ]\n\tLINE [ s 0.4 r -90 y 24 ]\n\tLINE [ s 0.4 r 90 y 24 ]\n}\n\nshape X {\n\tLINE [ x 8 y 24 r 160 ]\n\tLINE [ y 24 r -160 ]\n}\n\nshape HYPHEN{\n\tSQUARE[y 11.5 s 4 0.5]\n}\n\nshape LINE {\n\tTRIANGLE [[ s 1 30 y 0.26 ]]\n\n}\n\nshape ARCL {\n\tSQUARE [ ]\n\tARCL [ size 0.97 y 0.55 r 1.5 ]\n}\n", "language": "ContextFree" }, { "code": "// Derived from AA3D - ASCII art stereogram generator\n// by Jan Hubicka and Thomas Marsh\n// (GNU General Public License)\n// http://aa-project.sourceforge.net/aa3d/\n// http://en.wikipedia.org/wiki/ASCII_stereogram\n\nimport std.stdio, std.string, std.random;\n\nimmutable image = \"\n 111111111111111\n 1111111111111111\n 11111 1111\n 11111 1111\n 11111 1111\n 11111 1111\n 11111 1111\n 11111 1111\n 1111111111111111\n 111111111111111\n\n\";\n\nvoid main() {\n enum int width = 50;\n immutable text = \"DLanguage\";\n enum int skip = 12;\n\n char[65536 / 2] data;\n\n foreach (y, row; image.splitLines()) {\n immutable int shift = uniform(0, int.max);\n bool l = false;\n\n foreach (x; 0 .. width) {\n int s;\n if (!l && x > skip) {\n s = (x < row.length) ? row[x] : '\\n';\n if (s == ' ') {\n s = 0;\n } else if (s == '\\n') {\n s = 0;\n l = true;\n } else if (s >= '0' && s <= '9') {\n s = '0' - s;\n } else\n s = -2;\n } else\n s = 0;\n\n s += skip;\n s = x - s;\n s = (s < 0) ? text[(x + shift) % text.length] : data[s];\n data[x] = cast(char)s;\n write(data[x]);\n }\n\n writeln();\n }\n}\n", "language": "D" }, { "code": "void main(){\n print(\"\"\"\n\n XXX XX XXX XXXX\n X X X X X X X\n X X XXXX XXX X\n XXX X X X X X\n \"\"\".replaceAll('X','_/'));\n}\n", "language": "Dart" }, { "code": "program Write_language_name_in_3D_ASCII;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils;\n\nconst\n z: TArray<char> = [' ', ' ', '_', '/'];\n f: TArray<TArray<Cardinal>> = [[87381, 87381, 87381, 87381, 87381, 87381,\n 87381], [349525, 375733, 742837, 742837, 375733, 349525, 349525], [742741,\n 768853, 742837, 742837, 768853, 349525, 349525], [349525, 375733, 742741,\n 742741, 375733, 349525, 349525], [349621, 375733, 742837, 742837, 375733,\n 349525, 349525], [349525, 375637, 768949, 742741, 375733, 349525, 349525], [351157,\n 374101, 768949, 374101, 374101, 349525, 349525], [349525, 375733, 742837,\n 742837, 375733, 349621, 351157], [742741, 768853, 742837, 742837, 742837,\n 349525, 349525], [181, 85, 181, 181, 181, 85, 85], [1461, 1365, 1461, 1461,\n 1461, 1461, 2901], [742741, 744277, 767317, 744277, 742837, 349525, 349525],\n [181, 181, 181, 181, 181, 85, 85], [1431655765, 3149249365, 3042661813,\n 3042661813, 3042661813, 1431655765, 1431655765], [349525, 768853, 742837,\n 742837, 742837, 349525, 349525], [349525, 375637, 742837, 742837, 375637,\n 349525, 349525], [349525, 768853, 742837, 742837, 768853, 742741, 742741], [349525,\n 375733, 742837, 742837, 375733, 349621, 349621], [349525, 744373, 767317,\n 742741, 742741, 349525, 349525], [349525, 375733, 767317, 351157, 768853,\n 349525, 349525], [374101, 768949, 374101, 374101, 351157, 349525, 349525], [349525,\n 742837, 742837, 742837, 375733, 349525, 349525], [5592405, 11883957,\n 11883957, 5987157, 5616981, 5592405, 5592405], [366503875925, 778827027893,\n 778827027893, 392374737749, 368114513237, 366503875925, 366503875925], [349525,\n 742837, 375637, 742837, 742837, 349525, 349525], [349525, 742837, 742837,\n 742837, 375733, 349621, 375637], [349525, 768949, 351061, 374101, 768949,\n 349525, 349525], [375637, 742837, 768949, 742837, 742837, 349525, 349525], [768853,\n 742837, 768853, 742837, 768853, 349525, 349525], [375733, 742741, 742741,\n 742741, 375733, 349525, 349525], [192213, 185709, 185709, 185709, 192213,\n 87381, 87381], [1817525, 1791317, 1817429, 1791317, 1817525, 1398101,\n 1398101], [768949, 742741, 768853, 742741, 742741, 349525, 349525], [375733,\n 742741, 744373, 742837, 375733, 349525, 349525], [742837, 742837, 768949,\n 742837, 742837, 349525, 349525], [48053, 23381, 23381, 23381, 48053, 21845,\n 21845], [349621, 349621, 349621, 742837, 375637, 349525, 349525], [742837,\n 744277, 767317, 744277, 742837, 349525, 349525], [742741, 742741, 742741,\n 742741, 768949, 349525, 349525], [11883957, 12278709, 11908533, 11883957,\n 11883957, 5592405, 5592405], [11883957, 12277173, 11908533, 11885493,\n 11883957, 5592405, 5592405], [375637, 742837, 742837, 742837, 375637, 349525,\n 349525], [768853, 742837, 768853, 742741, 742741, 349525, 349525], [6010197,\n 11885397, 11909973, 11885397, 6010293, 5592405, 5592405], [768853, 742837,\n 768853, 742837, 742837, 349525, 349525], [375733, 742741, 375637, 349621,\n 768853, 349525, 349525], [12303285, 5616981, 5616981, 5616981, 5616981,\n 5592405, 5592405], [742837, 742837, 742837, 742837, 375637, 349525, 349525],\n [11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405], [3042268597,\n 3042268597, 3042661813, 1532713813, 1437971797, 1431655765, 1431655765], [11883957,\n 5987157, 5616981, 5987157, 11883957, 5592405, 5592405], [11883957, 5987157,\n 5616981, 5616981, 5616981, 5592405, 5592405], [12303285, 5593941, 5616981,\n 5985621, 12303285, 5592405, 5592405]];\n\nfunction ReverseString(s: string): string;\nvar\n i, len: integer;\nbegin\n len := s.Length;\n SetLength(Result, len);\n for i := 1 to len do\n Result[len - i + 1] := s[i];\nend;\n\nprocedure F5(s: ansistring);\nbegin\n var o: TArray<TStringBuilder>;\n SetLength(o, 7);\n for var i := 0 to High(o) do\n o[i] := TStringBuilder.Create;\n\n var l := length(s);\n for var i := 1 to l do\n begin\n var c: Integer := ord(s[i]);\n if c in [65..90] then\n c := c - 39\n else if c in [97..122] then\n c := c - 97\n else\n c := -1;\n\n inc(c);\n var d: TArray<Cardinal> := f[c];\n for var j := 0 to 6 do\n begin\n var b := TStringBuilder.Create;\n var v := d[j];\n\n while v > 0 do\n begin\n b.Append(z[Trunc(v and 3)]);\n v := v shr 2;\n end;\n o[j].Append(ReverseString(b.ToString));\n b.Free;\n end;\n end;\n for var i := 0 to 6 do\n begin\n for var j := 0 to 6 - i do\n write(' ');\n writeln(o[i].ToString);\n end;\n\n for var i := 0 to High(o) do\n o[i].Free;\nend;\n\nbegin\n F5('Delphi');\n F5('Thanks Java');\n F5('guy');\n readln;\nend.\n", "language": "Delphi" }, { "code": "defmodule ASCII3D do\n def decode(str) do\n Regex.scan(~r/(\\d+)(\\D+)/, str)\n |> Enum.map_join(fn[_,n,s] -> String.duplicate(s, String.to_integer(n)) end)\n |> String.replace(\"B\", \"\\\\\") # Backslash\n end\nend\n\ndata = \"1 12_4 2_1\\n1/B2 9_1B2 1/2B 3 2_18 2_1\\nB2 B8_1/ 3 B2 1/B_B4 2_6 2_2 1/B_B6 4_1\n3 B7_3 4 B2/_2 1/2B_1_2 1/B_B B2/_4 1/ 3_1B\\n 2 B2 6_1B3 3 B2 1/B2 B1/_/B_B3/ 2 1/2B 1 /B B2_1/\n2 3 B5_1/4 6 B3 1B/_/2 /1_2 6 B1\\n3 3 B10_6 B3 3 /2B_1_6 B1\n4 2 B11_2B 1B_B2 B1_B 3 /1B/_/B_B2 B B_B1\\n6 1B/11_1/3 B/_/2 3 B/_/\"\nIO.puts ASCII3D.decode(data)\n", "language": "Elixir" }, { "code": "%% Implemented by Arjun Sunel\n-module(three_d).\n-export([main/0]).\n\nmain() ->\n\tio:format(\" _____ _ \\n| ___| | | \\n| |__ _ __| | __ _ _ __ __ _ \\n| __| '__| |/ _` | '_ \\\\ / _` |\\n| |__| | | | (_| | | | | (_| |\\n|____/_| |_|\\\\__,_|_| |_|\\\\__, |\\n __/ |\\n |___/\\n\").\n", "language": "Erlang" }, { "code": "-module(ascii3d).\n-export([decode/1]).\n\ndecode(Str) ->\n Splited = re:split(Str, \"(\\\\d+)(\\\\D+)\", [{return,list},group,trim]),\n Fun = fun([_,N,S]) -> {Num,_} = string:to_integer(N), lists:duplicate(Num, S) end,\n Joined = string:join(lists:flatmap(Fun, Splited), \"\"),\n Lines = binary:replace(binary:list_to_bin(Joined), <<\"B\">>, <<\"\\\\\">>, [global]),\n io:format(\"~s~n\", [Lines]).\n", "language": "Erlang" }, { "code": "PROGRAM 3D_NAME\n\nDIM TBL$[17,1]\n\nBEGIN\n\nFOR I=0 TO 17 DO\n READ(TBL$[I,0],TBL$[I,1])\nEND FOR\n\nPRINT(CHR$(12);) ! CLS\n\nFOR I=0 TO 17 DO\n PRINT(TBL$[I,1];TBL$[I,0];TBL$[I,0];TBL$[I,1])\nEND FOR\n\nDATA(\"_________________ \",\"_____________ \")\nDATA(\"|\\ \\ \",\"|\\ \\ \")\nDATA(\"|\\\\_______________\\ \",\"|\\\\___________\\ \")\nDATA(\"|\\\\| \\ \",\"|\\\\| | \")\nDATA(\"|\\\\| ________ | \",\"|\\\\| ________| \")\nDATA(\"|\\\\| | |\\| | \",\"|\\\\| | \")\nDATA(\"|\\\\| |______|\\| | \",\"|\\\\| |____ \")\nDATA(\"|\\\\| | \\| | \",\"|\\\\| | \\ \")\nDATA(\"|\\\\| |________| | \",\"|\\\\| |_____\\ \")\nDATA(\"|\\\\| | \",\"|\\\\| | \")\nDATA(\"|\\\\| ___ ____/ \",\"|\\\\| _____| \")\nDATA(\"|\\\\| | \\\\\\ \\ \",\"|\\\\| | \")\nDATA(\"|\\\\| | \\\\\\ \\ \",\"|\\\\| | \")\nDATA(\"|\\\\| | \\\\\\ \\ \",\"|\\\\| |______ \")\nDATA(\"|\\\\| | \\\\\\ \\ \",\"|\\\\| | \\ \")\nDATA(\"|\\\\| | \\\\\\ \\ \",\"|\\\\| |_______\\ \")\nDATA(\" \\\\| | \\\\\\ \\ \",\" \\\\| | \")\nDATA(\" \\|___| \\\\\\___\\\",\" \\|___________| \")\n\nEND PROGRAM\n", "language": "ERRE" }, { "code": "let make2Darray (picture : string list) =\n let maxY = picture.Length\n let maxX = picture |> List.maxBy String.length |> String.length\n let arr =\n (fun y x ->\n if picture.[y].Length <= x then ' '\n else picture.[y].[x])\n |> Array2D.init maxY maxX\n (arr, maxY, maxX)\n\nlet (cube, cy, cx) =\n [\n @\"///\\\";\n @\"\\\\\\/\";\n ]\n |> make2Darray\n\n\nlet (p2, my, mx) =\n [\n \"*****\";\n \"* * * \";\n \"* * * \";\n \"* **********\";\n \"**** * * \";\n \"* * * \";\n \"* **********\";\n \"* * * \";\n \"* * * \";\n ]\n |> make2Darray\n\nlet a2 = Array2D.create (cy/2 * (my+1)) (cx/2 * mx + my) ' '\n\nlet imax = my * (cy/2)\nfor y in 0 .. Array2D.length1 p2 - 1 do\n for x in 0 .. Array2D.length2 p2 - 1 do\n let indent = Math.Max(imax - y, 0)\n if p2.[y, x] = '*' then Array2D.blit cube 0 0 a2 y (indent+x) cy cx\n\nArray2D.iteri (fun y x c ->\n if x = 0 then printfn \"\"\n printf \"%c\" c) a2\n", "language": "F-Sharp" }, { "code": "\\ Rossetta Code Write language name in 3D ASCII\n\\ Simple Method\n\n: l1 .\" /\\\\\\\\\\\\\\\\\\\\\\\\\\ /\\\\\\\\ /\\\\\\\\\\\\\\ /\\\\\\\\\\\\\\\\\\\\\\\\\\ /\\\\\\ /\\\\\\\" CR ;\n: l2 .\" \\/\\\\\\///////// /\\\\\\//\\\\\\ /\\\\\\/////\\\\\\ \\//////\\\\\\//// \\/\\\\\\ \\/\\\\\\\" CR ;\n: l3 .\" \\/\\\\\\ /\\\\\\/ \\///\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\\" CR ;\n: l4 .\" \\/\\\\\\\\\\\\\\\\\\ /\\\\\\ \\//\\\\\\ \\/\\\\\\\\\\\\\\\\\\/ \\/\\\\\\ \\/\\\\\\\\\\\\\\\\\\\\\\\\\\\" CR ;\n: l5 .\" \\/\\\\\\///// \\/\\\\\\ \\/\\\\\\ \\/\\\\\\////\\\\\\ \\/\\\\\\ \\/\\\\\\///////\\\\\\\" CR ;\n: l6 .\" \\/\\\\\\ \\//\\\\\\ /\\\\\\ \\/\\\\\\ \\//\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\\" CR ;\n: l7 .\" \\/\\\\\\ \\///\\\\\\ /\\\\\\ \\/\\\\\\ \\//\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\\" CR ;\n: l8 .\" \\/\\\\\\ \\///\\\\\\\\/ \\/\\\\\\ \\//\\\\\\ \\/\\\\\\ \\/\\\\\\ \\/\\\\\\\" CR ;\n: l9 .\" \\/// \\//// \\/// \\/// \\/// \\/// \\///\" CR ;\n\n: \"FORTH\" cr L1 L2 L3 L4 L5 L6 L7 L8 l9 ;\n\n( test at the console )\npage \"forth\"\n", "language": "Forth" }, { "code": "\\ Original code: \"Short phrases with BIG Characters by Wil Baden 2003-02-23\n\\ Modified BFox for simple 3D presentation 2015-07-14\n\n\\ Forth is a very low level language but by using primitive operations\n\\ we create new words in the language to solve the problem.\n\n\\ This solution coverts an acsii string to big text characters\n\nHEX\n: toUpper ( char -- char ) 05F and ;\n\n\n: w, ( n -- ) CSWAP , ; \\ compile 'n', a 16 bit integer, into memory in the correct order\n\n\nCREATE Banner-Matrix\n 0000 w, 0000 w, 0000 w, 0000 w, 2020 w, 2020 w, 2000 w, 2000 w,\n 5050 w, 5000 w, 0000 w, 0000 w, 5050 w, F850 w, F850 w, 5000 w,\n 2078 w, A070 w, 28F0 w, 2000 w, C0C8 w, 1020 w, 4098 w, 1800 w,\n 40A0 w, A040 w, A890 w, 6800 w, 3030 w, 1020 w, 0000 w, 0000 w,\n 2040 w, 8080 w, 8040 w, 2000 w, 2010 w, 0808 w, 0810 w, 2000 w,\n 20A8 w, 7020 w, 70A8 w, 2000 w, 0020 w, 2070 w, 2020 w, 0000 w,\n 0000 w, 0030 w, 3010 w, 2000 w, 0000 w, 0070 w, 0000 w, 0000 w,\n 0000 w, 0000 w, 0030 w, 3000 w, 0008 w, 1020 w, 4080 w, 0000 w,\n\n 7088 w, 98A8 w, C888 w, 7000 w, 2060 w, 2020 w, 2020 w, 7000 w,\n 7088 w, 0830 w, 4080 w, F800 w, F810 w, 2030 w, 0888 w, 7000 w,\n 1030 w, 5090 w, F810 w, 1000 w, F880 w, F008 w, 0888 w, 7000 w,\n 3840 w, 80F0 w, 8888 w, 7000 w, F808 w, 1020 w, 4040 w, 4000 ,\n 7088 w, 8870 w, 8888 w, 7000 w, 7088 w, 8878 w, 0810 w, E000 w,\n 0060 w, 6000 w, 6060 w, 0000 w, 0060 w, 6000 w, 6060 w, 4000 w,\n 1020 w, 4080 w, 4020 w, 1000 w, 0000 w, F800 w, F800 w, 0000 w,\n 4020 w, 1008 w, 1020 w, 4000 w, 7088 w, 1020 w, 2000 w, 2000 w,\n\n 7088 w, A8B8 w, B080 w, 7800 w, 2050 w, 8888 w, F888 w, 8800 w,\n F088 w, 88F0 w, 8888 w, F000 w, 7088 w, 8080 w, 8088 w, 7000 w,\n F048 w, 4848 w, 4848 w, F000 w, F880 w, 80F0 w, 8080 w, F800 w,\n F880 w, 80F0 w, 8080 w, 8000 w, 7880 w, 8080 w, 9888 w, 7800 w,\n 8888 w, 88F8 w, 8888 w, 8800 w, 7020 w, 2020 w, 2020 w, 7000 w,\n 0808 w, 0808 w, 0888 w, 7800 w, 8890 w, A0C0 w, A090 w, 8800 w,\n 8080 w, 8080 w, 8080 w, F800 w, 88D8 w, A8A8 w, 8888 w, 8800 w,\n 8888 w, C8A8 w, 9888 w, 8800 w, 7088 w, 8888 w, 8888 w, 7000 w,\n\n F088 w, 88F0 w, 8080 w, 8000 w, 7088 w, 8888 w, A890 w, 6800 w,\n F088 w, 88F0 w, A090 w, 8800 w, 7088 w, 8070 w, 0888 w, 7000 w,\n F820 w, 2020 w, 2020 w, 2000 w, 8888 w, 8888 w, 8888 w, 7000 w,\n 8888 w, 8888 w, 8850 w, 2000 w, 8888 w, 88A8 w, A8D8 w, 8800 w,\n 8888 w, 5020 w, 5088 w, 8800 w, 8888 w, 5020 w, 2020 w, 2000 w,\n F808 w, 1020 w, 4080 w, F800 w, 7840 w, 4040 w, 4040 w, 7800 w,\n 0080 w, 4020 w, 1008 w, 0000 w, F010 w, 1010 w, 1010 w, F000 w,\n 0000 w, 2050 w, 8800 w, 0000 w, 0000 w, 0000 w, 0000 w, 00F8 w,\n\n\n: >col ( char -- ndx ) \\ convert ascii char into column index in the matrix\n toupper BL - 0 MAX ; \\ Space char (BL) = 0. Index is clipped to 0 as minimum value\n\n\n: ]banner-matrix ( row ascii -- addr ) \\ convert Banner-matrix memory to a 2 dimensional matrix\n >col 8 * Banner-matrix + + ;\n\n\n: PLACE ( str len addr -- ) \\ store a string with length at addr\n 2DUP 2>R 1+ SWAP MOVE 2R> C! ;\n\nsynonym len c@ \\ fetch the 1st char of a counted string to return the length\n\n: BIT? ( byte bit# -- -1 | 0) \\ given a byte and bit# on stack, return true or false flag\n 1 swap lshift AND ;\n\nDECIMAL\n\nvariable bannerstr 5 allot \\ memory for the character string\n\n\\ Font selection characters stored as counted strings\n: STARFONT S\" *\" bannerstr PLACE ;\n: HASHFONT S\" ##\" bannerstr PLACE ;\n: 3DFONT S\" _/\" bannerstr PLACE ;\n\n\n: .BIGCHAR ( matrix-byte -- )\n 2 7 \\ we use bits 7 to 2\n DO\n dup I bit? \\ check bit I in the matrix-byte on stack\n IF bannerstr count TYPE \\ if BIT=TRUE\n ELSE bannerstr len SPACES \\ if BIT=false\n THEN\n -1 +LOOP \\ loop backwards\n DROP ; \\ drop the matrix-byte\n\n: BANNER ( str len -- )\n 8 0\n DO CR \\ str len\n 2dup\n BOUNDS \\ calc. begin & end addresses of string\n DO\n J I C@ ]Banner-Matrix C@ .BIGCHAR\n LOOP \\ str len\n LOOP\n 2DROP ; \\ drop str & len\n\n\\ test the solution in the Forth console\n", "language": "Forth" }, { "code": "dim as integer yres=hiword(width)\ndim as integer xres=loword(width)\n\n#define map(a,b,x,c,d) ((d)-(c))*((x)-(a))/((b)-(a))+(c)\n#define _X(num) int( map(0,xres,(num),0,loword(width)))\n#define _Y(num) int( map(0,yres,(num),0,hiword(width)))\n\nType pt\n As Integer x,y\nEnd Type\nDim As pt a(1 To ...)=_\n{(4,2),(6,2),(8,2),(12,2),(14,2),(16,2),(20,2),(22,2),(24,2),(28,2),(30,2),(32,2),_\n(4,3),(12,3),(16,3),(20,3),(28,3),_\n(4,4),(6,4),(12,4),(14,4),(16,4),(20,4),(22,4),(28,4),(30,4),_\n(4,5),(12,5),(20,5),(28,5),_\n(4,6),(12,6),(16,6),(20,6),(22,6),(24,6),(28,6),(30,6),(32,6)}\n\n\nFor i As Integer=0 To 12\n For n As Integer=Lbound(a) To Ubound(a)\n Locate _Y(a(n).y+i),_X(a(n).x+i)\n If i<12 Then Print \"\\\" Else Print \"#\"\n Next n\nNext i\nlocate(csrlin-1,40)\nprint \"BASIC\"\nSleep\n", "language": "FreeBASIC" }, { "code": "_window = 1\nbegin enum 1\n _asciiField\nend enum\n\nvoid local fn BuildWindow\n CGRect r = fn CGRectMake( 0, 0, 610, 140 )\n window _window, @\"Rosetta Code — FutureBasic in 3D ASCII\", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable\n WindowSetBackgroundColor( _window, fn ColorBlack )\n\n CFStringRef asciiFB = @\" ¬\n /$$$$$$$$ / $$ /$$$$$$$ /$$ \\n¬\n | $$_____/ | $$ | $$__ $$ |__/ \\n¬\n | $$ /$$ /$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ | $$ \\\\ $$ /$$$$$$ /$$$$$$$ /$$ /$$$$$$$\\n¬\n | $$$$$ | $$ | $$|_ $$_/ | $$ | $$ /$$__ $$ /$$__ $$| $$$$$$$ |____ $$ /$$_____/| $$ /$$_____/\\n¬\n | $$__/ | $$ | $$ | $$ | $$ | $$| $$ \\\\__/| $$$$$$$$| $$__ $$ /$$$$$$$| $$$$$$ | $$| $$ \\n¬\n | $$ | $$ | $$ | $$ /$$| $$ | $$| $$ | $$_____/| $$ \\\\ $$ /$$__ $$ \\\\____ $$| $$| $$ \\n¬\n | $$ | $$$$$$/ | $$$$/| $$$$$$/| $$ | $$$$$$$| $$$$$$$/| $$$$$$$ /$$$$$$$/| $$| $$$$$$$\\n¬\n |__/ \\\\______/ \\\\___/ \\\\______/ |__/ \\\\_______/|_______/ \\\\_______/|_______/ |__/ \\\\_______/\\n\"\n\n r = fn CGRectMake( 22, 20, 582, 100 )\n textfield _asciiField, YES, asciiFB, r, _window\n TextFieldSetTextColor( _asciiField, fn ColorYellow )\n TextFieldSetBordered( _asciiField, NO )\n TextFieldSetBackgroundColor( _asciiField, fn ColorBlack )\n ControlSetFontWithName( _asciiField, @\"Menlo\", 9.0 )\nend fn\n\nvoid local fn DoDialog( ev as long, tag as long, wnd as long )\n select ( ev )\n case _windowWillClose : end\n end select\nend fn\n\non dialog fn DoDialog\n\nfn BuildWindow\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar lean = font{\n height: 5,\n slant: 1,\n spacing: 2,\n m: map[rune][]string{\n 'G': []string{\n ` _/_/_/`,\n `_/ `,\n `_/ _/_/`,\n `_/ _/`,\n ` _/_/_/`,\n },\n 'o': []string{\n ` `,\n ` _/_/ `,\n `_/ _/`,\n `_/ _/`,\n ` _/_/ `,\n },\n }}\n\nvar smallKeyboard = font{\n height: 4,\n slant: 0,\n spacing: -1,\n m: map[rune][]string{\n 'G': []string{\n ` ____ `,\n `||G ||`,\n `||__||`,\n `|/__\\|`,\n },\n 'o': []string{\n ` ____ `,\n `||o ||`,\n `||__||`,\n `|/__\\|`,\n },\n }}\n\ntype font struct {\n height int\n slant int\n spacing int\n m map[rune][]string\n}\n\nfunc render(s string, f font) string {\n rows := make([]string, f.height)\n if f.slant != 0 {\n start := 0\n if f.slant > 0 {\n start = f.height\n }\n for i := range rows {\n rows[i] = strings.Repeat(\" \", (start-i)*f.slant)\n }\n }\n if f.spacing >= 0 {\n spacing := strings.Repeat(\" \", f.spacing)\n for j, c := range s {\n for i, r := range f.m[c] {\n if j > 0 {\n r = spacing + r\n }\n rows[i] += r\n }\n }\n } else {\n overlap := -f.spacing\n for j, c := range s {\n for i, r := range f.m[c] {\n if j > 0 {\n r = r[overlap:]\n }\n rows[i] += r\n }\n }\n }\n return strings.Join(rows, \"\\n\")\n}\n\nfunc main() {\n fmt.Println(render(\"Go\", lean))\n fmt.Println(render(\"Go\", smallKeyboard))\n}\n", "language": "Go" }, { "code": "println \"\"\"\\\n _|_|_|\n_| _| _|_| _|_| _|_| _| _| _| _|\n_| _|_| _|_| _| _| _| _| _| _| _| _|\n_| _| _| _| _| _| _| _| _| _| _|\n _|_|_| _| _|_| _|_| _| _|_|_|\n _|\n _|_|\"\"\"\n", "language": "Groovy" }, { "code": "String.metaClass.getAsAsciiArt = {\n def request = \"http://www.network-science.de/ascii/ascii.php?TEXT=${delegate}&x=23&y=10&FONT=block&RICH=no&FORM=left&STRE=no&WIDT=80\"\n def html = new URL(request).text\n (html =~ '<TD><PRE>([^<]+)</PRE>')[-1][1]\n}\n\nprintln \"Groovy\".asAsciiArt\n", "language": "Groovy" }, { "code": "module Main where\n{-\n __ __ __ ___ ___\n/\\ \\/\\ \\ /\\ \\ /\\_ \\ /\\_ \\\n\\ \\ \\_\\ \\ __ ____\\ \\ \\/'\\ __\\//\\ \\ \\//\\ \\\n \\ \\ _ \\ /'__`\\ /',__\\\\ \\ , < /'__`\\\\ \\ \\ \\ \\ \\\n \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\__, `\\\\ \\ \\\\`\\ /\\ __/ \\_\\ \\_ \\_\\ \\_\n \\ \\_\\ \\_\\ \\__/.\\_\\/\\____/ \\ \\_\\ \\_\\ \\____\\/\\____\\/\\____\\\n \\/_/\\/_/\\/__/\\/_/\\/___/ \\/_/\\/_/\\/____/\\/____/\\/____/\n-}\n\nascii3d :: String\nascii3d = \" __ __ __ ___ ___ \\n\" ++\n \"/\\\\ \\\\/\\\\ \\\\ /\\\\ \\\\ /\\\\_ \\\\ /\\\\_ \\\\ \\n\" ++\n \"\\\\ \\\\ \\\\_\\\\ \\\\ __ ____\\\\ \\\\ \\\\/'\\\\ __\\\\//\\\\ \\\\ \\\\//\\\\ \\\\ \\n\" ++\n \" \\\\ \\\\ _ \\\\ /'__`\\\\ /',__\\\\\\\\ \\\\ , < /'__`\\\\\\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\n\" ++\n \" \\\\ \\\\ \\\\ \\\\ \\\\/\\\\ \\\\L\\\\.\\\\_/\\\\__, `\\\\\\\\ \\\\ \\\\\\\\`\\\\ /\\\\ __/ \\\\_\\\\ \\\\_ \\\\_\\\\ \\\\_ \\n\" ++\n \" \\\\ \\\\_\\\\ \\\\_\\\\ \\\\__/.\\\\_\\\\/\\\\____/ \\\\ \\\\_\\\\ \\\\_\\\\ \\\\____\\\\/\\\\____\\\\/\\\\____\\\\\\n\" ++\n \" \\\\/_/\\\\/_/\\\\/__/\\\\/_/\\\\/___/ \\\\/_/\\\\/_/\\\\/____/\\\\/____/\\\\/____/\"\n\nmain = putStrLn ascii3d\n", "language": "Haskell" }, { "code": "procedure main(arglist)\nwrite(ExpandText(\n if !arglist == \"icon\" then\n \"14/\\\\\\n14\\\\/\\n12/\\\\\\n11/1/\\n10/1/1/\\\\\\n10\\\\/1/2\\\\\\n12/1/\\\\1\\\\\\n_\n 12\\\\1\\\\1\\\\/\\n10/\\\\1\\\\1\\\\2/\\\\\\n9/2\\\\1\\\\/1/2\\\\\\n_\n 8/1/\\\\1\\\\2/1/\\\\1\\\\2/\\\\\\n8\\\\1\\\\/1/2\\\\1\\\\/1/2\\\\1\\\\\\n_\n 6/\\\\1\\\\2/4\\\\2/1/\\\\1\\\\1\\\\\\n5/1/2\\\\/6\\\\/1/2\\\\1\\\\/\\n_\n /\\\\2/1/1/\\\\10/1/\\\\1\\\\2/\\\\\\n\\\\/2\\\\1\\\\/1/10\\\\/1/1/2\\\\/\\n_\n 2/\\\\1\\\\2/1/\\\\6/\\\\2/1/\\n2\\\\1\\\\1\\\\/1/2\\\\4/2\\\\1\\\\/\\n_\n 3\\\\1\\\\2/1/\\\\1\\\\2/1/\\\\1\\\\\\n4\\\\/2\\\\1\\\\/1/2\\\\1\\\\/1/\\n_\n 9\\\\2/1/\\\\1\\\\2/\\n10\\\\/2\\\\1\\\\1\\\\/\\n12/\\\\1\\\\1\\\\\\n12\\\\1\\\\/1/\\n_\n 13\\\\2/1/\\\\\\n14\\\\/1/1/\\n16/1/\\n16\\\\/\\n14/\\\\\\n14\\\\/\\n\"\n else\n \"13/\\\\\\n12/1/\\n11/1/1/\\\\\\n11\\\\1\\\\/1/\\n12\\\\2/1/\\\\\\n13\\\\/1/2\\\\\\n_\n 15/1/\\\\1\\\\2/\\\\\\n15\\\\/1/1/2\\\\/\\n17/1/1/\\\\18/\\\\\\n17\\\\/1/1/17/2\\\\\\n_\n 19/1/1/\\\\14/1/\\\\1\\\\\\n19\\\\/1/2\\\\13\\\\1\\\\1\\\\/\\n21/1/\\\\1\\\\10/\\\\1\\\\1\\\\\\n_\n 21\\\\1\\\\1\\\\/10\\\\1\\\\1\\\\/\\n19/\\\\1\\\\1\\\\2/\\\\6/\\\\1\\\\1\\\\\\n_\n 18/2\\\\1\\\\/1/2\\\\5\\\\1\\\\/1/\\n17/1/\\\\1\\\\2/1/\\\\1\\\\2/\\\\1\\\\2/\\n_\n 17\\\\1\\\\/1/2\\\\1\\\\/1/2\\\\1\\\\1\\\\/\\n15/\\\\1\\\\2/4\\\\2/1/\\\\1\\\\1\\\\\\n_\n 14/1/2\\\\/6\\\\/1/2\\\\1\\\\/\\n9/\\\\2/1/1/\\\\10/1/\\\\1\\\\2/\\\\\\n_\n 9\\\\/2\\\\1\\\\/1/10\\\\/1/1/2\\\\/\\n11/\\\\1\\\\2/1/\\\\6/\\\\2/1/\\n_\n 11\\\\1\\\\1\\\\/1/2\\\\4/2\\\\1\\\\/\\n9/\\\\1\\\\1\\\\2/1/\\\\1\\\\2/1/\\\\1\\\\\\n_\n 8/2\\\\1\\\\/2\\\\1\\\\/1/2\\\\1\\\\/1/\\n7/1/\\\\1\\\\5\\\\2/1/\\\\1\\\\2/\\n_\n 7\\\\1\\\\1\\\\/6\\\\/2\\\\1\\\\1\\\\/\\n5/\\\\1\\\\1\\\\10/\\\\1\\\\1\\\\\\n_\n 5\\\\1\\\\1\\\\/10\\\\1\\\\/1/\\n3/\\\\1\\\\1\\\\13\\\\2/1/\\\\\\n3\\\\1\\\\/1/14\\\\/1/1/\\n_\n 4\\\\2/17/1/1/\\\\\\n5\\\\/18\\\\/1/1/\\n23/\\\\2/1/1/\\\\\\n23\\\\/2\\\\1\\\\/1/\\n_\n 28\\\\2/1/\\\\\\n29\\\\/1/2\\\\\\n31/1/\\\\1\\\\\\n31\\\\/1/1/\\n33/1/\\n33\\\\/\\n\"\n ))\nend\n\nprocedure ExpandText(s)\ns ? until pos(0) do\n writes(repl(\" \",tab(many(&digits)))|tab(upto(&digits)|0))\nend\n", "language": "Icon" }, { "code": " require 'vrml.ijs' NB. Due to Andrew Nikitin\n view 5#.^:_1]21-~a.i.'j*ez`C3\\toy.G)' NB. Due to Oleg Kobchenko\n ________________________\n |\\ \\ \\ \\ \\\n | \\_____\\_____\\_____\\_____\\\n | | | | |\\ \\\n |\\| | | | \\_____\\\n | \\_____|_____|_____| | |\n | | | | | |\\| |\n \\| | |\\| | \\_____|\n \\_____| | \\_____|\n | | |\n |\\| |\n | \\_____|\n ______ | | |\n|\\ \\ |\\| |\n| \\_____\\_________|_\\_____|\n| |\\ \\ \\ \\ |\n \\| \\_____\\_____\\_____\\ |\n | | | | |___|\n \\| | | |\n \\_____|_____|_____|\n", "language": "J" }, { "code": " view 8 8 8#:'\"#$%&,4<DHLPTYZ[\\'-&(a.&i.)' '\n\n\n\n\n ______\n |\\ \\\n | \\_____\\\n | |\\ \\\n \\| \\_____\\\n | |\\ \\\n \\| \\_____\\\n | |\\ \\\n |\\| \\_____\\\n | | |\\ \\\n | |\\| \\_____\\\n ______ |\\| | | |\n|\\ \\| \\__\\| |\n| \\_____| | \\_____|\n| | |\\| |\n|\\| | \\_____|\n| \\_____| | |\n| | |\\| |\n \\| | \\_____|\n \\_____| | |\n |\\ |\\| |\n | \\___| \\_____|\n | |\\ | | |\n \\| \\_|\\| |\n | |\\| \\_____|\n \\| | | |\n | |\\| |\n \\| \\_____|\n | | |\n \\| |\n \\_____|\n", "language": "J" }, { "code": "public class F5{\n char[]z={' ',' ','_','/',};\n long[][]f={\n {87381,87381,87381,87381,87381,87381,87381,},\n {349525,375733,742837,742837,375733,349525,349525,},\n {742741,768853,742837,742837,768853,349525,349525,},\n {349525,375733,742741,742741,375733,349525,349525,},\n {349621,375733,742837,742837,375733,349525,349525,},\n {349525,375637,768949,742741,375733,349525,349525,},\n {351157,374101,768949,374101,374101,349525,349525,},\n {349525,375733,742837,742837,375733,349621,351157,},\n {742741,768853,742837,742837,742837,349525,349525,},\n {181,85,181,181,181,85,85,},\n {1461,1365,1461,1461,1461,1461,2901,},\n {742741,744277,767317,744277,742837,349525,349525,},\n {181,181,181,181,181,85,85,},\n {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,},\n {349525,768853,742837,742837,742837,349525,349525,},\n {349525,375637,742837,742837,375637,349525,349525,},\n {349525,768853,742837,742837,768853,742741,742741,},\n {349525,375733,742837,742837,375733,349621,349621,},\n {349525,744373,767317,742741,742741,349525,349525,},\n {349525,375733,767317,351157,768853,349525,349525,},\n {374101,768949,374101,374101,351157,349525,349525,},\n {349525,742837,742837,742837,375733,349525,349525,},\n {5592405,11883957,11883957,5987157,5616981,5592405,5592405,},\n {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,},\n {349525,742837,375637,742837,742837,349525,349525,},\n {349525,742837,742837,742837,375733,349621,375637,},\n {349525,768949,351061,374101,768949,349525,349525,},\n {375637,742837,768949,742837,742837,349525,349525,},\n {768853,742837,768853,742837,768853,349525,349525,},\n {375733,742741,742741,742741,375733,349525,349525,},\n {192213,185709,185709,185709,192213,87381,87381,},\n {1817525,1791317,1817429,1791317,1817525,1398101,1398101,},\n {768949,742741,768853,742741,742741,349525,349525,},\n {375733,742741,744373,742837,375733,349525,349525,},\n {742837,742837,768949,742837,742837,349525,349525,},\n {48053,23381,23381,23381,48053,21845,21845,},\n {349621,349621,349621,742837,375637,349525,349525,},\n {742837,744277,767317,744277,742837,349525,349525,},\n {742741,742741,742741,742741,768949,349525,349525,},\n {11883957,12278709,11908533,11883957,11883957,5592405,5592405,},\n {11883957,12277173,11908533,11885493,11883957,5592405,5592405,},\n {375637,742837,742837,742837,375637,349525,349525,},\n {768853,742837,768853,742741,742741,349525,349525,},\n {6010197,11885397,11909973,11885397,6010293,5592405,5592405,},\n {768853,742837,768853,742837,742837,349525,349525,},\n {375733,742741,375637,349621,768853,349525,349525,},\n {12303285,5616981,5616981,5616981,5616981,5592405,5592405,},\n {742837,742837,742837,742837,375637,349525,349525,},\n {11883957,11883957,11883957,5987157,5616981,5592405,5592405,},\n {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,},\n {11883957,5987157,5616981,5987157,11883957,5592405,5592405,},\n {11883957,5987157,5616981,5616981,5616981,5592405,5592405,},\n {12303285,5593941,5616981,5985621,12303285,5592405,5592405,},};\n public static void main(String[]a){\n new F5(a.length>0?a[0]:\"Java\");}\n private F5(String s){\n StringBuilder[]o=new StringBuilder[7];\n for(int i=0;i<7;i++)o[i]=new StringBuilder();\n for(int i=0,l=s.length();i<l;i++){\n int c=s.charAt(i);\n if(65<=c&&c<=90)c-=39;\n else if(97<=c&&c<=122)c-=97;\n else c=-1;\n long[]d=f[++c];\n for(int j=0;j<7;j++){\n StringBuilder b=new StringBuilder();\n long v=d[j];\n while(v>0){\n b.append(z[(int)(v&3)]);\n v>>=2;}\n o[j].append(b.reverse().toString());}}\n for(int i=0;i<7;i++){\n for(int j=0;j<7-i;j++)\n System.out.print(' ');\n System.out.println(o[i]);}}}\n", "language": "Java" }, { "code": "def jq:\n\"\\(\"\n #\n #\n # # ###\n # # # #\n # # # #\n # # # # ####\n # ### #\n #\n\")\";\n\ndef banner3D:\n jq | split(\"\\n\") | map( gsub(\"#\"; \"╔╗\") | gsub(\" \"; \" \") )\n | [[range(length;0;-1) | \" \" * .], . ] | transpose[] | join(\"\") ;\n\nbanner3D\n", "language": "Jq" }, { "code": "println(replace(raw\"\"\"\n xxxxx\n x x\n x x x\n x x x x\n x x x x x xxx\n x x x x x x x\n x x x x x x x xx\n xx xx x x x x xx\n \"\"\", \"x\" => \"_/\"))\n", "language": "Julia" }, { "code": "// version 1.1\n\nclass Ascii3D(s: String) {\n val z = charArrayOf(' ', ' ', '_', '/')\n\n val f = arrayOf(\n longArrayOf(87381, 87381, 87381, 87381, 87381, 87381, 87381),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(742741, 768853, 742837, 742837, 768853, 349525, 349525),\n longArrayOf(349525, 375733, 742741, 742741, 375733, 349525, 349525),\n longArrayOf(349621, 375733, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(349525, 375637, 768949, 742741, 375733, 349525, 349525),\n longArrayOf(351157, 374101, 768949, 374101, 374101, 349525, 349525),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 351157),\n longArrayOf(742741, 768853, 742837, 742837, 742837, 349525, 349525),\n longArrayOf(181, 85, 181, 181, 181, 85, 85),\n longArrayOf(1461, 1365, 1461, 1461, 1461, 1461, 2901),\n longArrayOf(742741, 744277, 767317, 744277, 742837, 349525, 349525),\n longArrayOf(181, 181, 181, 181, 181, 85, 85),\n longArrayOf(1431655765, 3149249365L, 3042661813L, 3042661813L, 3042661813L, 1431655765, 1431655765),\n longArrayOf(349525, 768853, 742837, 742837, 742837, 349525, 349525),\n longArrayOf(349525, 375637, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(349525, 768853, 742837, 742837, 768853, 742741, 742741),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 349621),\n longArrayOf(349525, 744373, 767317, 742741, 742741, 349525, 349525),\n longArrayOf(349525, 375733, 767317, 351157, 768853, 349525, 349525),\n longArrayOf(374101, 768949, 374101, 374101, 351157, 349525, 349525),\n longArrayOf(349525, 742837, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(5592405, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405),\n longArrayOf(366503875925L, 778827027893L, 778827027893L, 392374737749L, 368114513237L, 366503875925L, 366503875925L),\n longArrayOf(349525, 742837, 375637, 742837, 742837, 349525, 349525),\n longArrayOf(349525, 742837, 742837, 742837, 375733, 349621, 375637),\n longArrayOf(349525, 768949, 351061, 374101, 768949, 349525, 349525),\n longArrayOf(375637, 742837, 768949, 742837, 742837, 349525, 349525),\n longArrayOf(768853, 742837, 768853, 742837, 768853, 349525, 349525),\n longArrayOf(375733, 742741, 742741, 742741, 375733, 349525, 349525),\n longArrayOf(192213, 185709, 185709, 185709, 192213, 87381, 87381),\n longArrayOf(1817525, 1791317, 1817429, 1791317, 1817525, 1398101, 1398101),\n longArrayOf(768949, 742741, 768853, 742741, 742741, 349525, 349525),\n longArrayOf(375733, 742741, 744373, 742837, 375733, 349525, 349525),\n longArrayOf(742837, 742837, 768949, 742837, 742837, 349525, 349525),\n longArrayOf(48053, 23381, 23381, 23381, 48053, 21845, 21845),\n longArrayOf(349621, 349621, 349621, 742837, 375637, 349525, 349525),\n longArrayOf(742837, 744277, 767317, 744277, 742837, 349525, 349525),\n longArrayOf(742741, 742741, 742741, 742741, 768949, 349525, 349525),\n longArrayOf(11883957, 12278709, 11908533, 11883957, 11883957, 5592405, 5592405),\n longArrayOf(11883957, 12277173, 11908533, 11885493, 11883957, 5592405, 5592405),\n longArrayOf(375637, 742837, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(768853, 742837, 768853, 742741, 742741, 349525, 349525),\n longArrayOf(6010197, 11885397, 11909973, 11885397, 6010293, 5592405, 5592405),\n longArrayOf(768853, 742837, 768853, 742837, 742837, 349525, 349525),\n longArrayOf(375733, 742741, 375637, 349621, 768853, 349525, 349525),\n longArrayOf(12303285, 5616981, 5616981, 5616981, 5616981, 5592405, 5592405),\n longArrayOf(742837, 742837, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405),\n longArrayOf(3042268597L, 3042268597L, 3042661813L, 1532713813, 1437971797, 1431655765, 1431655765),\n longArrayOf(11883957, 5987157, 5616981, 5987157, 11883957, 5592405, 5592405),\n longArrayOf(11883957, 5987157, 5616981, 5616981, 5616981, 5592405, 5592405),\n longArrayOf(12303285, 5593941, 5616981, 5985621, 12303285, 5592405, 5592405)\n )\n\n init {\n val o = Array(7) { StringBuilder() }\n for (i in 0 until s.length) {\n var c = s[i].toInt()\n if (c in 65..90) {\n c -= 39\n } else if (c in 97..122) {\n c -= 97\n } else {\n c = -1\n }\n val d = f[++c]\n for (j in 0 until 7) {\n val b = StringBuilder()\n var v = d[j]\n while (v > 0) {\n b.append(z[(v and 3).toInt()])\n v = v shr 2\n }\n o[j].append(b.reverse().toString())\n }\n }\n for (i in 0 until 7) {\n for (j in 0 until 7 - i) print(' ')\n println(o[i])\n }\n }\n}\n\nfun main(args: Array<String>) {\n Ascii3D(\"KOTLIN\")\n Ascii3D(\"with thanks\")\n Ascii3D(\"to the author\")\n Ascii3D(\"of the\")\n Ascii3D(\"Java entry\")\n}\n", "language": "Kotlin" }, { "code": "local(lasso = \"\n---------------------------------------------------------------\n| ,--, |\n| ,---.'| ,----.. |\n| | | : ,---, .--.--. .--.--. / / \\\\ |\n| : : | ' .' \\\\ / / '. / / '. / . : |\n| | ' : / ; '. | : /`. /| : /`. / . / ;. \\\\ |\n| ; ; ' : : \\\\ ; | |--` ; | |--` . ; / ` ; |\n| ' | |__ : | /\\\\ \\\\| : ;_ | : ;_ ; | ; \\\\ ; | |\n| | | :.'|| : ' ;. :\\\\ \\\\ `. \\\\ \\\\ `. | : | ; | ' |\n| ' : ;| | ;/ \\\\ \\\\`----. \\\\ `----. \\\\. | ' ' ' : |\n| | | ./ ' : | \\\\ \\\\ ,'__ \\\\ \\\\ | __ \\\\ \\\\ |' ; \\\\; / | |\n| ; : ; | | ' '--' / /`--' // /`--' / \\\\ \\\\ ', / |\n| | ,/ | : : '--'. /'--'. / ; : / |\n| '---' | | ,' `--'---' `--'---' \\\\ \\\\ .' |\n| `--'' `---` |\n----------------------------------------------------------------\n\")\n\nstdoutnl(#lasso)\n", "language": "Lasso" }, { "code": "r=21:s=9:c=s\nFor i=1 To 11\n Read d\n If d <> 0 Then\n For j=1 To 31\n If (d And(2^(31-j)))>0 Then\n Locate c+1,r:Print \"___\";\n Locate c,r+1:Print \"/_ /|\";\n Locate c,r+2:Print \"[_]/\";\n End If\n c=c+3\n Next\n Else\n s=1:c=s\n End If\n r=r-2:s=s+2:c=s\n Next\nData 479667712,311470336,485697536,311699712,476292608,0,1976518785,1160267905,1171157123,1160267909,1171223529\n", "language": "Liberty-BASIC" }, { "code": "10 mode 2:defint a-z\n20 locate 1,25\n30 print \"Basic\";\n40 ' add some kerning so the characters will fit in 80 columns:\n50 off(2)=1:off(4)=-2:off(5)=-4\n60 for c=0 to 4\n70 for y=7 to 0 step -1\n80 for x=0 to 7\n90 v=test(x+8*c,2*y)\n100 plot x+8*c,2*y,0\n110 if v>0 then gosub 180\n120 next x\n130 next y\n140 next c\n150 call &bb06 ' wait for key press\n160 end\n170 ' print pixel\n180 xp=16*c+2*x+1+y+off(c+1)\n190 yp=8-y\n200 if xp>77 then return\n210 locate xp,yp\n220 print \"//\\\";\n230 locate xp,yp+1\n240 print \"\\\\/\";\n250 return\n", "language": "Locomotive-Basic" }, { "code": "io.write(\" /$$\\n\")\nio.write(\"| $$\\n\")\nio.write(\"| $$ /$$ /$$ /$$$$$$\\n\")\nio.write(\"| $$ | $$ | $$ |____ $$\\n\")\nio.write(\"| $$ | $$ | $$ /$$$$$$$\\n\")\nio.write(\"| $$ | $$ | $$ /$$__ $$\\n\")\nio.write(\"| $$$$$$$$| $$$$$$/| $$$$$$$\\n\")\nio.write(\"|________/ \\______/ \\_______/\\n\")\n", "language": "Lua" }, { "code": "print[[\n __\n/\\ \\\n\\ \\ \\ __ __ ____\n \\ \\ \\ /\\ \\/\\ \\ / __ \\\n \\ \\ \\___\\ \\ \\_\\ \\/\\ \\_\\ \\_\n \\ \\____\\\\ \\____/\\ \\___/\\_\\\n \\/____/ \\/___/ \\/__/\\/_/]]\n", "language": "Lua" }, { "code": "locs = Position[\n ImageData[Binarize[Rasterize[\"Mathematica\", ImageSize -> 150]]], 0];\nPrint[StringRiffle[\n StringJoin /@\n ReplacePart[\n ReplacePart[\n ConstantArray[\n \" \", {Max[locs[[All, 1]]] + 1, Max[locs[[All, 2]]] + 1}],\n locs -> \"\\\\\"], Map[# + 1 &, locs, {2}] -> \"#\"], \"\\n\"]];\n", "language": "Mathematica" }, { "code": "data = [\n\" ______ _____ _________\",\n\"|\\ \\/ \\ ___ ________ ___|\\ _____\\ ________ ________ ___ ________ _________ \",\n\"\\ \\ _ \\ _ \\|\\ \\|\\ ___ \\|\\ \\ \\ \\____||\\ ____\\|\\ ____\\|\\ \\|\\ __ \\|\\___ ___\\ \",\n\" \\ \\ \\\\\\__\\ \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\ \\_____ \\ \\ \\___|\\ \\ \\___|\\ \\ \\ \\ \\|\\ \\|___ \\ \\_| \",\n\" \\ \\ \\\\|__| \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\|____|\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ ____\\ \\ \\ \\ \",\n\" \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\____\\_\\ \\ \\ \\____\\ \\ \\ \\ \\ \\ \\ \\___| \\ \\ \\ \",\n\" \\ \\__\\ \\ \\__\\ \\__\\ \\__\\\\ \\__\\ \\__\\_________\\ \\_______\\ \\__\\ \\ \\__\\ \\__\\ \\ \\__\\\",\n\" \\|__| \\|__|\\|__|\\|__| \\|__|\\|__||________|\\|_______|\\|__| \\|__|\\|__| \\|__|\"]\n\nfor line in data\n print line\nend for\n", "language": "MiniScript" }, { "code": "MODULE Art;\nFROM Terminal IMPORT WriteString,WriteLn,ReadChar;\n\nBEGIN\n (* 3D, but does not fit in the terminal window *)\n (*\n WriteString(\"_____ ______ ________ ________ ___ ___ ___ ________ _______\");\n WriteLn;\n WriteString(\"|\\ _ \\ _ \\|\\ __ \\|\\ ___ \\|\\ \\|\\ \\|\\ \\ |\\ __ \\ / ___ \\\");\n WriteLn;\n WriteString(\"\\ \\ \\\\\\__\\ \\ \\ \\ \\|\\ \\ \\ \\_|\\ \\ \\ \\\\\\ \\ \\ \\ \\ \\ \\|\\ \\ ____________ /__/|_/ /|\");\n WriteLn;\n WriteString(\" \\ \\ \\\\|__| \\ \\ \\ \\\\\\ \\ \\ \\ \\\\ \\ \\ \\\\\\ \\ \\ \\ \\ \\ __ \\|\\____________\\__|// / /\");\n WriteLn;\n WriteString(\" \\ \\ \\ \\ \\ \\ \\ \\\\\\ \\ \\ \\_\\\\ \\ \\ \\\\\\ \\ \\ \\____\\ \\ \\ \\ \\|____________| / /_/__\");\n WriteLn;\n WriteString(\" \\ \\__\\ \\ \\__\\ \\_______\\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ |\\________\\\");\n WriteLn;\n WriteString(\" \\|__| \\|__|\\|_______|\\|_______|\\|_______|\\|_______|\\|__|\\|__| \\|_______|\");\n WriteLn;\n *)\n\n (* Not 3D, but fits in the terminal window *)\n WriteString(\" __ __ _ _ ___\");\n WriteLn;\n WriteString(\" | \\/ | | | | | |__ \\\");\n WriteLn;\n WriteString(\" | \\ / | ___ __| |_ _| | __ _ ______ ) |\");\n WriteLn;\n WriteString(\" | |\\/| |/ _ \\ / _` | | | | |/ _` |______/ /\");\n WriteLn;\n WriteString(\" | | | | (_) | (_| | |_| | | (_| | / /_\");\n WriteLn;\n WriteString(\" |_| |_|\\___/ \\__,_|\\__,_|_|\\__,_| |____|\");\n WriteLn;\n\n ReadChar\nEND Art.\n", "language": "Modula-2" }, { "code": "println \" ________ ________ ________ ________ ________ ___ ___ _______ ________ ___ ___ \"\nprintln \"|\\\\ ___ \\\\|\\\\ __ \\\\|\\\\ ___ \\\\|\\\\ __ \\\\|\\\\ __ \\\\|\\\\ \\\\|\\\\ \\\\|\\\\ ___ \\\\ |\\\\ __ \\\\ |\\\\ \\\\ / /| \"\nprintln \"\\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ \\\\|\\\\ \\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ \\\\|\\\\ \\\\ \\\\ \\\\|\\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ __/|\\\\ \\\\ \\\\|\\\\ \\\\ \\\\ \\\\ \\\\/ / / \"\nprintln \" \\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ __ \\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\_|/_\\\\ \\\\ _ _\\\\ \\\\ \\\\ / / \"\nprintln \" \\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\\\\\ \\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\\\\\\\\\ \\\\ \\\\ \\\\_|\\\\ \\\\ \\\\ \\\\\\\\ \\\\| \\\\/ / / \"\nprintln \" \\\\ \\\\__\\\\\\\\ \\\\__\\\\ \\\\__\\\\ \\\\__\\\\ \\\\__\\\\\\\\ \\\\__\\\\ \\\\_______\\\\ \\\\_____ \\\\ \\\\_______\\\\ \\\\_______\\\\ \\\\__\\\\\\\\ _\\\\ __/ / / \"\nprintln \" \\\\|__| \\\\|__|\\\\|__|\\\\|__|\\\\|__| \\\\|__|\\\\|_______|\\\\|___| \\\\__\\\\|_______|\\\\|_______|\\\\|__|\\\\|__|\\\\___/ / \"\nprintln \" \\\\|__| \\\\|___|/ \"\n", "language": "Nanoquery" }, { "code": "/* NetRexx */\noptions replace format comments java crossref symbols nobinary\n\ntxt = '';\nx = 0\nx = x + 1; txt[0] = x; txt[x] = ' * * *****'\nx = x + 1; txt[0] = x; txt[x] = ' ** * * * *'\nx = x + 1; txt[0] = x; txt[x] = ' * * * *** *** * * *** * * * *'\nx = x + 1; txt[0] = x; txt[x] = ' * * * * * * ***** * * * * * *'\nx = x + 1; txt[0] = x; txt[x] = ' * ** ***** * * * ***** * *'\nx = x + 1; txt[0] = x; txt[x] = ' * * * * * * * * * * *'\nx = x + 1; txt[0] = x; txt[x] = ' * * *** ** * * *** * * * *'\nx = x + 1; txt[0] = x; txt[x] = ''\n\n_top = '_TOP'\n_bot = '_BOT'\ntxt = Banner3D(txt, isTrue())\nloop ll = 1 to txt[0]\n say txt[ll, _top]\n say txt[ll, _bot]\n end ll\n\nreturn\n\nmethod Banner3D(txt, slope = '') public static\n\n select\n when slope = isTrue() then nop\n when slope = isFalse() then nop\n otherwise do\n if slope = '' then slope = isFalse()\n else slope = isTrue()\n end\n end\n\n _top = '_TOP'\n _bot = '_BOT'\n loop ll = 1 to txt[0]\n txt[ll, _top] = txt[ll]\n txt[ll, _bot] = txt[ll]\n txt[ll, _top] = txt[ll, _top].changestr(' ', ' ')\n txt[ll, _bot] = txt[ll, _bot].changestr(' ', ' ')\n txt[ll, _top] = txt[ll, _top].changestr('*', '///')\n txt[ll, _bot] = txt[ll, _bot].changestr('*', '\\\\\\\\\\\\')\n txt[ll, _top] = txt[ll, _top] || ' '\n txt[ll, _bot] = txt[ll, _bot] || ' '\n txt[ll, _top] = txt[ll, _top].changestr('/ ', '/\\\\')\n txt[ll, _bot] = txt[ll, _bot].changestr('\\\\ ', '\\\\/')\n end ll\n\n if slope then do\n loop li = txt[0] to 1 by -1\n ll = txt[0] - li + 1\n txt[ll, _top] = txt[ll, _top].insert('', 1, li - 1, ' ')\n txt[ll, _bot] = txt[ll, _bot].insert('', 1, li - 1, ' ')\n end li\n end\n\n return txt\n\nmethod isTrue public constant binary returns boolean\n return 1 == 1\n\nmethod isFalse public constant binary returns boolean\n return \\isTrue()\n", "language": "NetRexx" }, { "code": "import strutils\n\nconst nim = \"\"\"\n # # ##### # #\n ## # # ## ##\n # # # # # ## #\n # # # # # #\n # ## # # #\n # # ##### # #\n \"\"\"\nlet lines = nim.dedent.multiReplace((\"#\", \"<<<\"), (\" \", \" \"), (\"< \", \"<>\"), (\"<\\n\", \"<>\\n\")).splitLines\nfor i, line in lines:\n echo spaces(lines.len - i), line\n", "language": "Nim" }, { "code": " print_string \"\n _|_|_| _|_|_| _|_| _|_| _|_| _|\n _| _| _| _| _| _| _| _| _| _|\n _| _| _| _|_|_| _| _| _| _| _|\n _| _| _| _| _| _| _| _|\n _|_|_| _|_|_| _| _| _| _| _|_|_|_|_|\n \"\n", "language": "OCaml" }, { "code": "program WritePascal;\n\nconst\n i64: int64 = 1055120232691680095; (* This defines \"Pascal\" *)\n cc: array[-1..15] of string = (* Here are all string-constants *)\n ('_______v---',\n '__', '\\_', '___', '\\__',\n ' ', ' ', ' ', ' ',\n '/ ', ' ', '_/ ', '\\/ ',\n ' _', '__', ' _', ' _');\nvar\n x, y: integer;\n\nbegin\n for y := 0 to 7 do\n begin\n Write(StringOfChar(cc[(not y and 1) shl 2][1], 23 - y and 6));\n Write(cc[((i64 shr (y div 2)) and 1) shl 3 + (not y and 1) shl 2 + 2]);\n for x := 0 to 15 do\n Write(cc[((i64 shr ((x and 15) * 4 + y div 2)) and 1) +\n ((i64 shr (((x + 1) and 15) * 4 + y div 2)) and 1) shl 3 +\n (x mod 3) and 2 + (not y and 1) shl 2]);\n writeln(cc[1 + (not y and 1) shl 2] + cc[(not y and 1) shl 3 - 1]);\n end;\nend.\n", "language": "Pascal" }, { "code": "#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nfor my $tuple ([\" \", 2], [\"_\", 1], [\" \", 1], [\"\\\\\", 1], [\" \", 11], [\"|\", 1], [\"\\n\", 1],\n [\" \", 1], [\"|\", 1], [\" \", 3], [\"|\", 1], [\" \", 1], [\"_\", 1], [\" \", 1], [\"\\\\\", 1], [\" \", 2], [\"_\", 2], [\"|\", 1], [\" \", 1], [\"|\", 1], [\"\\n\", 1],\n [\" \", 1], [\"_\", 3], [\"/\", 1], [\" \", 2], [\"_\", 2], [\"/\", 1], [\" \", 1], [\"|\", 1], [\" \", 4], [\"|\", 1], [\"\\n\", 1],\n [\"_\", 1], [\"|\", 1], [\" \", 3], [\"\\\\\", 1], [\"_\", 3], [\"|\", 1], [\"_\", 1], [\"|\", 1], [\" \", 3], [\"_\", 1], [\"|\", 1], [\"\\n\", 1]\n ) {\n print $tuple->[0] x $tuple->[1];\n}\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">s</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n ------*** *\n -----* * *\n ----* * * *\n ---*** *\n --* *** * * *\n -* * * * *\n * * * * * *\n \"\"\"</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"* \"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"_/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">}))</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">q</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0(30)10C</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(31)176</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(32)2A4</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(33)6N3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(34)7GP</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(35)DWF</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0(36)QC4</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%16b\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">q</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\" 10\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"_/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" \"</span><span style=\"color: #0000FF;\">})&</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"\"\n __ ________\n /_/\\ / ______ \\\n \\ \\ \\/ /\\____/ /\\ __\n \\ \\ \\/ / / / //_/\\\n \\ \\ \\/___/ / / \\_\\/_ __\n /\\ \\______/ / /_/\\/ /\\\n / /\\ ____ \\ \\ \\ \\ \\/ /\n / / /\\ \\ \\ \\ \\ \\ \\_\\ /\n / / / \\ \\ \\ \\ \\ \\ / / \\\n /_/ / \\ \\ \\ \\ \\ \\ /_/ /\\ \\\n \\_\\/ \\_\\/ \\_\\/ \\_\\/\\_\\/\n \"\"\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- or if you prefer something a little more cryptic (same output):</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\" __ ________\\n /_/\\\\ / ______ \\\\\\n \\\\ \\\\ \\\\/ /\\\\____/ /\\\\ __\\n \"</span><span style=\"color: #0000FF;\">&</span>\n <span style=\"color: #008000;\">\"\\\\ \\\\ \\\\/ / / / //_/\\\\\\n \\\\ \\\\ \\\\/___/ / / \\\\_\\\\/_ __\\n /\\\\ \\\\__\"</span><span style=\"color: #0000FF;\">&</span>\n <span style=\"color: #008000;\">\"____/ / /_/\\\\/ /\\\\\\n / /\\\\ ____ \\\\ \\\\ \\\\ \\\\ \\\\/ /\\n / / /\\\\ \\\\ \"</span><span style=\"color: #0000FF;\">&</span>\n <span style=\"color: #008000;\">\"\\\\ \\\\ \\\\ \\\\ \\\\_\\\\ /\\n / / / \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ / / \\\\\\n/_/ / \\\\\"</span><span style=\"color: #0000FF;\">&</span>\n <span style=\"color: #008000;\">\" \\\\ \\\\ \\\\ \\\\ \\\\ /_/ /\\\\ \\\\\\n\\\\_\\\\/ \\\\_\\\\/ \\\\_\\\\/ \\\\_\\\\/\\\\_\\\\/\\n\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(de Lst\n \"***** * \"\n \"* * * * * \"\n \"* * **** **** * **** ****\"\n \"***** * * * * * * * * * *\"\n \"* * * * * * * * ****\"\n \"* * * * * * * * * \"\n \"* * * * * * * * * * \"\n \"* * **** **** **** * **** * \" )\n\n(de transform (Lst A B)\n (make\n (chain (need (length Lst) \" \"))\n (for (L (chop (car Lst)) L)\n (ifn (= \"*\" (pop 'L))\n (link \" \" \" \" \" \")\n (chain (need 3 A))\n (when (sp? (car L))\n (link B \" \" \" \")\n (pop 'L) ) ) ) ) )\n\n(prinl (transform Lst \"/\" \"\\\\\"))\n\n(mapc\n '((X Y)\n (mapc\n '((A B)\n (prin (if (sp? B) A B)) )\n X\n Y )\n (prinl) )\n (maplist '((X) (transform X \"\\\\\" \"/\")) Lst)\n (maplist '((X) (transform X \"/\" \"\\\\\")) (cdr Lst)) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "To run:\nStart up.\nPrint the language name in 3D ASCII.\nWait for the escape key.\nShut down.\n\nTo print the language name in 3D ASCII:\nWrite \"Osmosian Order of\" to the console.\nWrite \" ____ _ _\" to the console.\nWrite \"/___ \\ /_/| /_/|\" to the console.\nWrite \"| \\ \\| || ____ |_|/ _____\" to the console.\nWrite \"| |\\ \\|| || /___/| _ /____/\\\" to the console.\nWrite \"| | | || || / ||/_/|| \\ \\\" to the console.\nWrite \"| |/ / | ||/ /| ||| ||| |\\ \\/\" to the console.\nWrite \"| __/ | ||| | | ||| ||| | | ||\" to the console.\nWrite \"| || | ||\\ \\| ||| ||| | | ||\" to the console.\nWrite \"|_|/ |_|/ \\____|/|_|/|_| |_|/\" to the console.\nWrite \" ______ _ _ _\" to the console.\nWrite \"/_____/| /_/|/_/| /_/|\" to the console.\nWrite \"| ___|/ _____ ____ | |||_|/ _______| ||__\" to the console.\nWrite \"| ||___ /____/\\ /___/|| || _ /______/| /__/\\\" to the console.\nWrite \"| |/__/|| \\ \\ / ||| ||/_/|/ ___|/| \\ \\\" to the console.\nWrite \"| ___|/| |\\ \\// /| ||| ||| ||| |___/\\| |\\ \\/\" to the console.\nWrite \"| ||___ | | | ||| | | ||| ||| ||\\____ \\|| | | ||\" to the console.\nWrite \"| |/__/|| | | ||\\ \\| ||| ||| ||____| || | | ||\" to the console.\nWrite \"|_____|/|_| |_|/ \\__ |||_|/|_|/|_____/ |_| |_|/\" to the console.\nWrite \" ___| ||\" to the console.\nWrite \" /___/ //\" to the console.\nWrite \" |____//\" to the console.\nWrite \"Programmers\" to the console.\n", "language": "Plain-English" }, { "code": "If OpenConsole()\n PrintN(\" ////\\ ////\\ ////| \")\n PrintN(\" //// \\ __ //// \\ __ |XX|_/ \")\n PrintN(\" //// /| | ////\\ ////\\//// |//// /| | //// | ////\\ ////\\ \")\n PrintN(\"|XX| |X| ////\\X| ////\\// //// /||XX| |X| |//// /|| //// _| ////\\ //// \\ \")\n PrintN(\"|XX| |X||XX| |X||XX| |/ |XX| |X||XX| |/ /|XX| |X||//// / |XX| | //// /\\ |\")\n PrintN(\"|XX| |/ |XX| |X||XX| /|XX| |//|XX| \\|XX|/// |XX| |/\\ |XX| ||XX| |XX\\|\")\n PrintN(\"|XX| /|XX| |X||XX| / |XX| //|XX| /| |//// |XX| ||XX| ||XX| | \")\n PrintN(\"|$$| / |$$| |&||$$| | |$$| |&||$$| |&| |$$| /||\\\\\\\\/| ||$$| ||$$| |///|\")\n PrintN(\"|%%| | |%%| |i||%%| | |%%| |/ |%%| |i| |%%| |i|| |%%| ||%%| ||%%| |// |\")\n PrintN(\"|ii| | |ii| |/ |ii| | |ii| /|ii| |/ /|ii| \\/|/ |ii| /|ii| ||ii| |/ / \")\n PrintN(\"|::| | \\\\\\\\ /|::| | |::| / |::| / |::| / //// / |::| | \\\\\\\\ / \")\n PrintN(\"|..| | \\\\\\\\/ |..|/ \\\\\\\\/ |..| / \\\\\\\\/ \\\\\\\\ / |..|/ \\\\\\\\/ \")\n PrintN(\" \\\\\\\\| \\\\\\\\/ \")\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "py = '''\\\n #### # # ##### # # ### # #\n # # # # # # # # # ## #\n #### # # ##### # # # # #\n # # # # # # # # ##\n # # # # # ### # #'''\n\nlines = py.replace('#', '<<<').replace(' ','X') \\\n .replace('X', ' ').replace('\\n', ' Y') \\\n .replace('< ', '<>').split('Y')\n\nfor i, l in enumerate(lines):\n print(' ' * (len(lines) - i) + l)\n", "language": "Python" }, { "code": "charWidth = 10\ncharHeight = 8\n\n# char table is split into sets to prevent very long lines...\ncharSet1 = [\n\" ###### /####### ###### /###### /######## /######## ###### /## /##\",\n\" /##__ ##| ##__ ## /##__ ##| ##__ ## | ##_____/| ##_____/ /##__ ##| ## | ##\",\n\"| ## | ##| ## | ##| ## \\__/| ## \\ ##| ## | ## | ## \\__/| ## | ##\",\n\"| ########| ####### | ## | ## | ##| ########| ########| ## #####| ########\",\n\"| ##__ ##| ##__ ##| ## | ## | ##| ##_____/| ##_____/| ##|_ ##| ##__ ##\",\n\"| ## | ##| ## | ##| ## /##| ## /##/| ## | ## | ## | ##| ## | ##\",\n\"| ## | ##| #######/| ######/| ######/ | ########| ## | ######/| ## | ##\",\n\"|__/ |__/|_______/ \\______/ |______/ |________/|__/ \\______/ |__/ |__/\",\n]\n\ncharSet2 = [\n\" /######## /## /## /## /## /### ### /## /## ###### /####### \",\n\"|__ ##__/ | ##| ## /##/| ## | ########| ### | ## /##__ ##| ##__ ##\",\n\" | ## | ##| ## /##/ | ## | ## ## ##| ####| ##| ## | ##| ## | ##\",\n\" | ## | ##| #####/ | ## | ## ## ##| ## ## ##| ## | ##| #######/\",\n\" | ## | ##| ## ## | ## | ## ## ##| ## ####| ## | ##| ##____/ \",\n\" | ## /## | ##| ##\\ ## | ## | ##__/ ##| ##\\ ###| ## | ##| ## \",\n\" /########\\ ######/| ## \\ ##| ########| ## | ##| ## \\ ##| ######/| ## \",\n\"|________/ \\______/ |__/ \\__/|________/|__/ |__/|__/ \\__/ \\______/ |__/ \",\n]\n\ncharSet3 = [\n\" ###### /####### ###### /######## /## /## /## /## /## /## /## /##\",\n\" /##__ ##| ##__ ## /##__ ##|__ ##__/| ## | ##| ## | ##| ## | ##\\ ## /##/\",\n\"| ## | ##| ## | ##| ## \\__/ | ## | ## | ##| ## | ##| ## ## ## \\ ####/ \",\n\"| ## | ##| #######/ \\ ###### | ## | ## | ##| ## | ##| ## ## ## \\ ##/ \",\n\"| ## ## ##| ## ## \\___ ## | ## | ## | ##| ## ##/| ## ## ## / #### \",\n\"| ##\\ ###/| ##\\ ## /## \\ ## | ## | ## | ## \\ ####/ | ######## / ## ## \",\n\"| #### ##| ## \\ ##\\ ######/ | ## | ######/ \\ ##/ | ###| ###/ ## \\ ##\",\n\" \\____\\__/|__/ \\__/ \\______/ |__/ \\______/ \\__/ |___/|___/\\__/ \\__/\",\n]\n\ncharSet4 = [\n\" /## /## /######## ###### \",\n\"\\ ## /##/|____ ##/ /##__ ## \",\n\" \\ ####/ / ##/ | ## | ## \",\n\" \\ ##/ / ##/ |__//####/ \",\n\" | ## / ##/ | ##_/ \",\n\" | ## / ##/ |__/ \",\n\" | ## / ######## /## \",\n\" |__/ \\________/ |__/ \",\n]\n\n# ...then the sets are combined back by barbequing them together!\ncharTable = [(charSet1[i] +\n charSet2[i] +\n charSet3[i] +\n charSet4[i]) for i in range(charHeight)]\n\nif __name__ == '__main__':\n text = input(\"Enter the text to convert:\\n\")\n if not text:\n text = \"PYTHON\"\n\n for i in range(charHeight):\n lineOut = \"\"\n for chr in text:\n # get value of character 'chr' in alphabet\n if chr.isalpha():\n val = ord(chr.upper()) - 65\n elif chr == \" \":\n val= 27\n else:\n val = 26\n beginStr = val * charWidth # begin string position of 3D letter\n endStr = (val + 1) * charWidth # end string position of 3D letter\n lineOut += charTable[i][beginStr:endStr]\n print(lineOut)\n", "language": "Python" }, { "code": "import requests\nimport html\n\ntext = \"Python\"\nfont = \"larry3d\"\nurl = f\"http://www.network-science.de/ascii/ascii.php?TEXT={text}&FONT={font}&RICH=no&FORM=left&WIDT=1000\"\n\nr = requests.get(url)\nr.raise_for_status()\n\nascii_text = html.unescape(r.text)\npre_ascii = \"<TD><PRE>\"\npost_ascii = \"\\n</PRE>\"\nascii_text = ascii_text[ascii_text.index(pre_ascii) + len(pre_ascii):]\nascii_text = ascii_text[:ascii_text.index(post_ascii)]\n\nprint(ascii_text)\n", "language": "Python" }, { "code": "say \" ________ ___ ___ ________ ________ ___ __ _______ ________ ___ ___\" cr\nsay \"|\\ __ \\|\\ \\|\\ \\|\\ __ \\|\\ ____\\|\\ \\|\\ \\ |\\ ___ \\ |\\ __ \\|\\ \\ / /|\" cr\nsay \"\\ \\ \\|\\ \\ \\ \\ \\ \\ \\ \\|\\ \\ \\ \\___|\\ \\ \\/ /|\\ \\ __/|\\ \\ \\|\\ \\ \\ \\/ / /\" cr\nsay \" \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ __ \\ \\ \\ \\ \\ ___ \\ \\ \\_|/ \\ \\ _ _\\ \\ / /\" cr\nsay \" \\ \\ \\_\\ \\ \\ \\_\\ \\ \\ \\ \\ \\ \\ \\____\\ \\ \\\\ \\ \\ \\ \\__\\_\\ \\ \\\\ \\ / / /\" cr\nsay \" \\ \\_____ \\ \\_______\\ \\__\\ \\__\\ \\_______\\ \\__\\\\ \\__\\ \\_______\\ \\__\\\\ _\\ / /\" cr\nsay \" \\|___| \\ \\|_______|\\|__|\\|__|\\|_______|\\|__| \\|__|\\|_______|\\|__|\\|__| / /\" cr\nsay \" \\ \\ \\_______________________________________________________/ / /\" cr\nsay \" \\ \\____________________________________________________________/ /\" cr\nsay \" \\|____________________________________________________________|/\" cr\n", "language": "Quackery" }, { "code": "#lang racket/gui\n\n;; Get the language name\n(define str (cadr (regexp-match #rx\"Welcome to (.*?) *v[0-9.]+\\n*$\" (banner))))\n\n;; Font to use\n(define font (make-object font% 12 \"MiscFixed\" 'decorative 'normal 'bold))\n;; (get-face-list) -> get a list of faces to try in the above\n\n;; Calculate the needed size (leave space for a drop-down shadow)\n(define-values [W H]\n (let ([bdc (make-object bitmap-dc% (make-object bitmap% 1 1 #t))])\n (call-with-values\n (λ() (send* bdc (set-font font) (get-text-extent str font)))\n (λ(w h _1 _2) (values (+ 2 (inexact->exact (round w)))\n (+ 2 (inexact->exact (round h))))))))\n\n;; Draw the text\n(define bmp (make-bitmap W H #t))\n(define dc (send bmp make-dc))\n(send* dc (set-font font) (draw-text str 2 0))\n\n;; Grab the pixels as a string, 3d-ed with \"/\"s\n(define scr\n (let* ([size (* W H 4)] [buf (make-bytes size)])\n (send bmp get-argb-pixels 0 0 W H buf)\n (define scr (make-string (* (add1 W) (add1 H)) #\\space))\n (for ([i (in-range 0 size 4)] [j (* W H)]\n #:unless (zero? (bytes-ref buf i)))\n (string-set! scr j #\\@)\n (for ([k (list j (+ j W -1))] [c \"/.\"] #:when #t\n [k (list (- k 1) (+ k W) (+ k W -1))]\n #:when (and (< -1 k (string-length scr))\n (member (string-ref scr k) '(#\\space #\\.))))\n (string-set! scr k c)))\n scr))\n\n;; Show it, dropping empty lines\n(let ([lines (for/list ([y H]) (substring scr (* y W) (* (add1 y) W)))])\n (define (empty? l) (not (regexp-match #rx\"[^ ]\" l)))\n (for ([line (dropf-right (dropf lines empty?) empty?)])\n (displayln (string-trim line #:left? #f))))\n", "language": "Racket" }, { "code": "# must be evenly padded with white-space$\nmy $text = q:to/END/;\n\n @@@@@ @@\n @ @ @ @@@\n @ @ @ @@\n @ @ @@@ @ @@ @ @@\n @@@@@ @ @ @@ @ @ @@@@@\n @ @@@@@ @ @ @@ @@\n @ @ @ @ @@ @@\n @ @@@ @ @@ @@@@\n\nEND\n\nsay '' for ^5;\nfor $text.lines -> $_ is copy {\n my @chars = |「-+ ., ;: '\"」.comb.pick(*) xx *;\n s:g [' '] = @chars.shift;\n print \" $_ \";\n s:g [('@'+)(.)] = @chars.shift ~ $0;\n .say;\n}\nsay '' for ^5;\n", "language": "Raku" }, { "code": "[\n\" ##### #### # # #### # #\"\n\" # # # # # # # ## #\"\n\" # # # # # # ### # # #\"\n\" ##### ###### # # ### # # #\"\n\" # # # # # # # # ##\"\n\" # # # # # #### # #\"\n] as $str\n\n\"/\" as $r1\n\">\" as $r2\n\n#$str each \"%s\\n\" print\n\n$str each as $line\n $line r/#/@@@/g r/ /X/g r/X/ /g r/@ /@!/g r/@$/@!/g as $l1\n $l1 \"@\" split $r1 join \"!\" split $r2 join print \"\\n\" print\n", "language": "Raven" }, { "code": "/*REXX program that displays a \"REXX\" 3D \"ASCII art\" as a logo. */\nsignal . /* Uses left-hand shadows, slightly raised view.\n0=5~2?A?2?A?\n@)E)3@)B)1)2)8()2)1)2)8()2)\n@]~\")2@]0`)0@)%)6{)%)0@)%)6{)%)\n#E)1#A@0}2)4;2(1}2)4;2(\n#3??3@0#2??@1}2)2;2(3}2)2;2(\n#2@5@)@2@0#2@A}2)0;2(5}2)0;2(\n#2@?\"@)@2@0#2@?7}2){2(7}2){2(\n#2@6)@2@0#2@3)7}2)(2(9}2)(2(\n#2@??@2@0#2@?_)7}5(B}5(\n#F@0#8@8}3(D}3(\n#3%3?(1#3?_@7;3)C;3)\n#2@0}2)5#2@C;5)A;5)\n#2@1}2)4#2@B;2()2)8;2()2)\n#2@2}2)3#2@?\"4;2(}2)6;2(}2)\n#2@3}2)2#2@5)2;2(1}2)4;2(1}2)\n#2@4}2)1#2@?%)0;2(3}2)2;2(3}2)\n0]@2@5}2)1]@A@0)[2(5}2)1)[2(5}2)\n1)@%@6}%)1)@`@1V%(7}%)1V%(7}%)\n*/;.:a=sigL+1;signal ..;..:u='_';do j=a to sigl-1\n_=sourceline(j);_=_('(',\"/\");_=_('[',\"//\");_=_('{',\"///\")\n_=_(';',\"////\");_=_(')',\"\\\");_=_(']',\"\\\\\");_=_('}',\"\\\\\\\");_=_('\"',\"__\")\n_=_('%',\"___\");_=_('?',left('',4,u));_=_('`',left('',11,u));_=_('~',left('',\n,13,u));_=_('=',left('',16,u));_=_('#','|\\\\|');_=translate(_,\"|\"u,'@\"')\ndo k=0 for 16;x=d2x(k,1);_=_(x,left('',k+1));end;say ' '_;end;exit;_:return,\nchangestr(arg(1),_,arg(2))\n", "language": "REXX" }, { "code": "/* Rexx */\n\ndrop !top !bot\nx = 0\nx = x + 1; txt.0 = x; txt.x = ' *****'\nx = x + 1; txt.0 = x; txt.x = ' * *'\nx = x + 1; txt.0 = x; txt.x = ' * * ***** * * * *'\nx = x + 1; txt.0 = x; txt.x = ' ***** * * * * *'\nx = x + 1; txt.0 = x; txt.x = ' * * *** * *'\nx = x + 1; txt.0 = x; txt.x = ' * * * * * * *'\nx = x + 1; txt.0 = x; txt.x = ' * * ***** * * * *'\nx = x + 1; txt.0 = x; txt.x = ''\n\ncall Banner3D isTrue()\ndo ll = 1 to txt.0\n say txt.ll.!top\n say txt.ll.!bot\n end ll\n\nreturn\nexit\n\nBanner3D:\nprocedure expose txt.\n drop !top !bot\n parse arg slope .\n\n select\n when slope = isTrue() then nop\n when slope = isFalse() then nop\n otherwise do\n if slope = '' then slope = isFalse()\n else slope = isTrue()\n end\n end\n\n do ll = 1 to txt.0\n txt.ll.!top = txt.ll\n txt.ll.!bot = txt.ll\n txt.ll.!top = changestr(' ', txt.ll.!top, ' ')\n txt.ll.!bot = changestr(' ', txt.ll.!bot, ' ')\n txt.ll.!top = changestr('*', txt.ll.!top, '///')\n txt.ll.!bot = changestr('*', txt.ll.!bot, '\\\\\\')\n txt.ll.!top = txt.ll.!top || ' '\n txt.ll.!bot = txt.ll.!bot || ' '\n txt.ll.!top = changestr('/ ', txt.ll.!top, '/\\')\n txt.ll.!bot = changestr('\\ ', txt.ll.!bot, '\\/')\n end ll\n\n if slope then do\n do li = txt.0 to 1 by -1\n ll = txt.0 - li + 1\n txt.ll.!top = insert('', txt.ll.!top, 1, li - 1, ' ')\n txt.ll.!bot = insert('', txt.ll.!bot, 1, li - 1, ' ')\n end li\n end\n\n return\nexit\n\nisTrue:\nprocedure\n return 1 == 1\n\nisFalse:\nprocedure\n return \\isTrue()\n", "language": "REXX" }, { "code": "/*REXX pgm draws a \"3D\" image of text representation; any character except / and \\ */\n#=7; @.1 = '@@@@ '\n @.2 = '@ @ '\n @.3 = '@ @ @@@@ @ @ @ @ '\n @.4 = '@@@@ @ @ @ @ @ '\n @.5 = '@ @ @@@ @ @ '\n @.6 = '@ @ @ @ @ @ @ '\n @.7 = '@ @ @@@@ @ @ @ @ '\n do j=1 for #; x=left(strip(@.j),1) /* [↓] display the (above) text lines.*/\n $.1 = changestr( \" \" , @.j, ' ' ) ; $.2 = $.1\n $.1 = changestr( x , $.1, '///' )\" \"\n $.2 = changestr( x , $.2, '\\\\\\' )\" \"\n $.1 = changestr( \"/ \", $.1, '/\\' )\n $.2 = changestr( \"\\ \", $.2, '\\/' )\n do k=1 for 2; say strip(left('',#-j)$.k,\"T\") /*the LEFT BIF does indentation.*/\n end /*k*/ /* [↑] display a line and its shadow.*/\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "text = <<EOS\n#### #\n# # #\n# # #\n#### # # ### # #\n# # # # # # # #\n# # # # # # #\n# # ### ### #\n #\n #\nEOS\n\ndef banner3D_1(text, shift=-1)\n txt = text.each_line.map{|line| line.gsub('#','__/').gsub(' ',' ')}\n offset = Array.new(txt.size){|i| \" \" * shift.abs * i}\n offset.reverse! if shift < 0\n puts offset.zip(txt).map(&:join)\nend\nbanner3D_1(text)\n\nputs\n# Other display:\ndef banner3D_2(text, shift=-2)\n txt = text.each_line.map{|line| line.chomp + ' '}\n offset = txt.each_index.map{|i| \" \" * shift.abs * i}\n offset.reverse! if shift < 0\n txt.each_with_index do |line,i|\n line2 = offset[i] + line.gsub(' ',' ').gsub('#','///').gsub('/ ','/\\\\')\n puts line2, line2.tr('/\\\\\\\\','\\\\\\\\/')\n end\nend\nbanner3D_2(text)\n\nputs\n# Another display:\ndef banner3D_3(text)\n txt = text.each_line.map(&:rstrip)\n offset = [*0...txt.size].reverse\n area = Hash.new(' ')\n box = [%w(/ / / \\\\), %w(\\\\ \\\\ \\\\ /)]\n txt.each_with_index do |line,i|\n line.each_char.with_index do |c,j|\n next if c==' '\n x = offset[i] + 2*j\n box[0].each_with_index{|c,k| area[[x+k,i ]] = c}\n box[1].each_with_index{|c,k| area[[x+k,i+1]] = c}\n end\n end\n (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax)\n puts (ymin..ymax).map{|y| (xmin..xmax).map{|x| area[[x,y]]}.join}\nend\n\nbanner3D_3 <<EOS\n#### #\n# # #\n# # #\n# # #\n#### # # #### # #\n# # # # # # # #\n# # # # # # # #\n# # # # # # #\n# # ### #### #\n #\n #\nEOS\n", "language": "Ruby" }, { "code": "enc = \"9 8u18 2u1\\n8 1s 6u1 b16 1s sb\\n6 2 s1b4u1s sb13 3 s1\\n5 3 s3 3s 11 3 s1\\n4 2 s1us3u1su2s 2u4 2u3 2 s1us3u4 2u6 2u1\\n4 1s 6u1sbubs2 s1b 2 s1b2 1s 6u1 b2 1susb3 2 s1b\\n2 2 s1b2 3u1bs2 8 s1b4u1s s4b 3 s1\\n 3 s3b 2 9 s3 3s 3 b2s 1s\\n 3s 3 b1 2 s2us4 s1us2u2us1 s3 3 b1s s\\nsu2s 2 4 b6u2s 1s7u1sbubs6 1bub2 1s\\nbubs6 1bubs2 1b5u1bs b7u1bs8 3 s1\\n42 2u2s 1s\\n41 1s3u1s s\\n41 1b3u1bs\\n\"\ndef decode(str)\n str.split(/(\\d+)(\\D+)/).each_slice(3).map{|_,n,s| s * n.to_i}.join.tr('sub','/_\\\\')\nend\nputs decode(enc)\n", "language": "Ruby" }, { "code": "pub fn char_from_id(id: u8) -> char {\n [' ', '#', '/', '_', 'L', '|', '\\n'][id as usize]\n}\n\nconst ID_BITS: u8 = 3;\n\npub fn decode(code: &[u8]) -> String {\n let mut ret = String::new();\n let mut carry = 0;\n let mut carry_bits = 0;\n for &b in code {\n let mut bit_pos = ID_BITS - carry_bits;\n let mut cur = b >> bit_pos;\n let mask = (1 << bit_pos) - 1;\n let id = carry | (b & mask) << carry_bits;\n ret.push(char_from_id(id));\n while bit_pos + ID_BITS < 8 {\n ret.push(char_from_id(cur & ((1 << ID_BITS) - 1)));\n cur >>= ID_BITS;\n bit_pos += ID_BITS;\n }\n carry = cur;\n carry_bits = 8 - bit_pos;\n }\n ret\n}\n\nfn main() {\n let code = [\n 72, 146, 36, 0, 0, 0, 0, 0, 0, 0, 128, 196, 74, 182, 41, 1, 0, 0, 0, 0, 0, 0, 160, 196, 77, 0,\n 52, 1, 18, 0, 9, 144, 36, 9, 146, 36, 113, 147, 36, 9, 160, 4, 80, 130, 100, 155, 160, 41, 145,\n 155, 108, 74, 128, 38, 64, 19, 41, 73, 2, 160, 137, 155, 0, 84, 130, 38, 64, 19, 112, 155, 18,\n 160, 137, 155, 0, 160, 18, 42, 73, 18, 36, 73, 2, 128, 74, 76, 1, 0, 40, 128, 219, 38, 104, 219,\n 4, 0, 160, 0\n ];\n\n println!(\"{}\", decode(&code));\n}\n", "language": "Rust" }, { "code": "def ASCII3D = {\n\nval name = \"\"\"\n *\n ** ** * * *\n * * * * * * *\n * * * * * * *\n * * *** * ***\n * * * * * * *\n * * * * * * *\n ** ** * * *** * *\n *\n *\n \"\"\"\n\n// Create Array\n\ndef getMaxSize(s: String): (Int, Int) = {\n var width = 0\n var height = 0\n\n val nameArray = s.split(\"\\n\")\n height = nameArray.size\n nameArray foreach { i => width = (i.size max width) }\n\n (width, height)\n}\n\nval size = getMaxSize(name)\nvar arr = Array.fill(size._2 + 1, (size._1 * 3) + (size._2 + 1))(' ')\n\n//\n// Map astrisk to 3D cube\n//\nval cubeTop = \"\"\"///\\\"\"\" //\"\nval cubeBottom = \"\"\"\\\\\\/\"\"\" //\"\n\nval nameArray = name.split(\"\\n\")\n\nfor (j <- (0 until nameArray.size)) {\n for (i <- (0 until nameArray(j).size)) {\n if (nameArray(j)(i) == '*') {\n val indent = nameArray.size - j\n arr(j) = arr(j) patch ((i * 3 + indent), cubeTop, cubeTop.size)\n arr(j + 1) = arr(j + 1) patch ((i * 3 + indent), cubeBottom, cubeBottom.size)\n }\n }\n}\n\n//\n// Map Array to String\n//\nvar name3D = \"\"\n\nfor (j <- (0 until arr.size)) {\n for (i <- (0 until arr(j).size)) { name3D += arr(j)(i) }\n name3D += \"\\n\"\n }\n name3D\n }\n\n println(ASCII3D)\n", "language": "Scala" }, { "code": "import scala.collection.mutable.ArraySeq\n\nobject Ascii3D extends App {\n def ASCII3D = {\n val picture = \"\"\" *\n ** ** * * *\n * * * * * * *\n * * * * * * *\n * * *** * ***\n * * * * * * *\n * * * * * * *\n ** ** * * *** * *\n *\n *\"\"\".split(\"\\n\")\n\n var arr = {\n val (x, y) = // Get maximal format and create a 2-D array with it.\n (picture.foldLeft(0)((i, s) => i max s.length), picture.size)\n ArraySeq.fill(y + 1, (x * 3) + (y + 1))(' ')\n }\n\n //\n // Map asterisks to 3D cube\n //\n val (cubeTop, cubeBottom) = (\"\"\"///\\\"\"\", \"\"\"\\\\\\/\"\"\") // \"\n\n for {\n y <- 0 until picture.size\n x <- 0 until picture(y).size\n if picture(y)(x) == '*'\n indent = picture.size - y\n } {\n arr(y) = arr(y) patch ((x * 3 + indent), cubeTop, cubeTop.size)\n arr(y + 1) = arr(y + 1) patch ((x * 3 + indent), cubeBottom, cubeBottom.size)\n }\n // Transform array to String\n arr.map(_.mkString).mkString(\"\\n\")\n }\n\n println(ASCII3D)\n}\n", "language": "Scala" }, { "code": "$include \"seed7_05.s7i\";\n\nconst array string: name is [] (\n \" *** * ***** \",\n \"* * * \",\n \"* *** *** **** * \",\n \"* * * * * * * * \",\n \" *** * * * * * * * \",\n \" * ***** ***** * * * \",\n \" * * * * * * \",\n \" * * * * * * \",\n \" *** *** *** **** * \");\n\nconst proc: main is func\n local\n var integer: index is 0;\n var string: help is \"\";\n var string: line is \"\";\n var string: previousLine is \"\";\n var integer: pos is 0;\n begin\n for index range 1 to length(name) do\n help := replace(name[index], \" \", \" \");\n line := \"\" lpad length(name) - index <&\n replace(replace(help, \"*\", \"///\"), \"/ \", \"/\\\\\");\n if previousLine = \"\" then\n writeln(line);\n else\n for pos range 1 to length(line) do\n if line[pos] <> ' ' then\n write(line[pos]);\n else\n write(previousLine[pos]);\n end if;\n end for;\n writeln;\n end if;\n previousLine := \"\" lpad length(name) - index <&\n replace(replace(help, \"*\", \"\\\\\\\\\\\\\"), \"\\\\ \", \"\\\\/\");\n end for;\n writeln(previousLine);\n end func;\n", "language": "Seed7" }, { "code": "var text = <<'EOT';\n\n ***\n * * * **\n * * *\n * * * *** **\n *** * **** * * *\n * * * * ***** *\n * * * * * *\n * * * * * *\n *** * **** *** *\nEOT\n\nfunc banner3D(text, shift=-1) {\n var txt = text.lines.map{|line| line.gsub('*','__/').gsub(' ',' ')};\n var offset = txt.len.of {|i| \" \" * (shift.abs * i)};\n shift < 0 && offset.reverse!;\n (offset »+« txt).join(\"\\n\");\n};\n\nsay banner3D(text);\n", "language": "Sidef" }, { "code": "select ' SSS\\ ' as s, ' QQQ\\ ' as q, 'L\\ ' as l from dual\nunion all select 'S \\|', 'Q Q\\ ', 'L | ' from dual\nunion all select '\\SSS ', 'Q Q |', 'L | ' from dual\nunion all select ' \\ S\\', 'Q Q Q |', 'L | ' from dual\nunion all select ' SSS |', '\\QQQ\\\\|', 'LLLL\\' from dual\nunion all select ' \\__\\/', ' \\_Q_/ ', '\\___\\' from dual\nunion all select ' ', ' \\\\ ', ' ' from dual;\n", "language": "SQL" }, { "code": "package require Tcl 8.5\n\nproc mergeLine {upper lower} {\n foreach u [split $upper \"\"] l [split $lower \"\"] {\n\tlappend result [expr {$l in {\" \" \"\"} ? $u : $l}]\n }\n return [join $result \"\"]\n}\nproc printLines lines {\n set n [llength $lines]\n foreach line $lines {\n\tset indent [string repeat \" \" $n]\n\tlappend upper $indent[string map {\"/ \" \"/\\\\\"} [\n\t\tstring map {\" \" \" \" \"*\" \"///\"} \"$line \"]]\n\tlappend lower $indent[string map {\"\\\\ \" \"\\\\/\"} [\n\t\tstring map {\" \" \" \" \"*\" \"\\\\\\\\\\\\\"} \"$line \"]]\n\tincr n -1\n }\n # Now do some line merging to strengthen the visual effect\n set p [string repeat \" \" [string length [lindex $upper 0]]]\n foreach u $upper l $lower {\n\tputs [mergeLine $p $u]\n\tset p $l\n }\n puts $p\n}\n\nset lines {\n {***** *}\n { * *}\n { * *** *}\n { * * *}\n { * * *}\n { * *** *}\n}\nprintLines $lines\n", "language": "Tcl" }, { "code": "Disp “ .....+ .....+\nDisp “ +o+ooo +o+ooo\nDisp “ .o .o\nDisp “ .o ...+.+\nDisp “ +o +ooooo\nDisp “\nDisp “ BASIC\n", "language": "TI-83-BASIC" }, { "code": "#!/usr/bin/env bash\nmapfile -t name <<EOF\nAimhacks\nEOF\n\nmain() {\n banner3d_1 \"${name[@]}\"\n echo\n banner3d_2 \"${name[@]}\"\n echo\n banner3d_3 \"${name[@]}\"\n}\n\nspace() {\n local -i n i\n (( n=$1 )) || n=1\n if (( n < 1 )); then n=1; fi\n for ((i=0; i<n; ++i)); do\n printf ' '\n done\n printf '\\n'\n}\n\nbanner3d_1() {\n local txt i\n mapfile -t txt < <(printf '%s\\n' \"$@\" | sed -e 's,#,__/,g' -e 's/ / /g')\n for i in \"${!txt[@]}\"; do\n printf '%s%s\\n' \"$(space $(( ${#txt[@]} - i )))\" \"${txt[i]}\"\n done\n}\n\nbanner3d_2() {\n local txt i line line2\n mapfile -t txt < <(printf '%s \\n' \"$@\")\n for i in \"${!txt[@]}\"; do\n line=${txt[i]}\n line2=$(printf '%s%s' \"$(space $(( 2 * (${#txt[@]} - i) )))\" \"$(sed -e 's, , ,g' -e 's,#,///,g' -e 's,/ ,/\\\\,g' <<<\"$line\")\")\n printf '%s\\n%s\\n' \"$line2\" \"$(tr '/\\\\' '\\\\/' <<<\"$line2\")\"\n done\n}\n\nbanner3d_3() {\n # hard-coded fancy one\n cat <<'EOF'\n ______________ ___________ ___________ ____ ____␣\n / /\\ / |\\ /| \\ |\\ \\ |\\ \\\n/_____________/ /| /___________|| ||___________\\| \\___\\ | \\___\\␣\n| \\ / |/ \\ / | | | | | |\n| ________ | | ________ | | _________| | | | | |\n| | |___| | | | |____| | | |_______ | | |____| | |\n| | / | | /| | / | | | | \\ | | | \\ | |\n| |/_____| |/ | |/_____| | | |________\\| | |______\\| |\n| / /| | | \\ | |\n| ______ \\ / | _______ | \\_________ | | ________ |\n| | |___| | | | | | | _________/| | | | | | |\n| | / | | | | | | | | || | | | | | |\n| |/_____| | /| | | | | |_________|/ | | | \\ | |\n| |/ | | | | | | | | | \\| |\n|_____________/ |___|/ |___| |_____________/ \\|___| |___|\nEOF\n}\n\nmain \"$@\"\n", "language": "UNIX-Shell" }, { "code": "Module Module1\n\n Sub Main()\n Console.WriteLine(\" ___ ___ ___ ________ ___ ___ ________ ___ ________ ________ ________ ___ ________ ________ _______ _________\n|\\ \\ / /|\\ \\|\\ ____\\|\\ \\|\\ \\|\\ __ \\|\\ \\ |\\ __ \\|\\ __ \\|\\ ____\\|\\ \\|\\ ____\\ |\\ ___ \\|\\ ___ \\|\\___ ___\\\n\\ \\ \\ / / | \\ \\ \\ \\___|\\ \\ \\\\\\ \\ \\ \\|\\ \\ \\ \\ \\ \\ \\|\\ /\\ \\ \\|\\ \\ \\ \\___|\\ \\ \\ \\ \\___| \\ \\ \\\\ \\ \\ \\ __/\\|___ \\ \\_|\n \\ \\ \\/ / / \\ \\ \\ \\_____ \\ \\ \\\\\\ \\ \\ __ \\ \\ \\ \\ \\ __ \\ \\ __ \\ \\_____ \\ \\ \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\_|/__ \\ \\ \\\n \\ \\ / / \\ \\ \\|____|\\ \\ \\ \\\\\\ \\ \\ \\ \\ \\ \\ \\____ \\ \\ \\|\\ \\ \\ \\ \\ \\|____|\\ \\ \\ \\ \\ \\____ __\\ \\ \\\\ \\ \\ \\ \\_|\\ \\ \\ \\ \\\n \\ \\__/ / \\ \\__\\____\\_\\ \\ \\_______\\ \\__\\ \\__\\ \\_______\\ \\ \\_______\\ \\__\\ \\__\\____\\_\\ \\ \\__\\ \\_______\\ |\\__\\ \\__\\\\ \\__\\ \\_______\\ \\ \\__\\\n \\|__|/ \\|__|\\_________\\|_______|\\|__|\\|__|\\|_______| \\|_______|\\|__|\\|__|\\_________\\|__|\\|_______| \\|__|\\|__| \\|__|\\|_______| \\|__|\n \\|_________| \\|_________|\n\n\n\")\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var w = \"\"\"\n ____ ____ ____\n |\\ \\ |\\ \\ |\\ \\\n | \\ \\ | \\ \\ | \\ \\\n \\ \\ \\\\ / \\\\ / /|\n \\ \\ \\V \\V / |\n \\ \\ /\\ / /\n \\ \\____/ \\____/ /\n \\ | | /| | /\n \\|____|/ |____|/\n\"\"\".split(\"\\n\")\n\nvar r = \"\"\"\n _______ ____\n |\\__ \\ / \\\n || |\\ \\/ ___\\\n \\|_| \\ /|__|\n \\ \\ //\n \\ \\ \\\n \\ \\____\\\n \\ | |\n \\|____|\n\"\"\".split(\"\\n\")\n\nvar e = \"\"\"\n ___________\n / _____ \\\n / /_____\\ \\\n |\\ _____/|\n | \\ /|____|/\n \\ \\ \\/_______/\\\n \\ \\_____________/|\n \\ | | |\n \\|____________|/\n\"\"\".split(\"\\n\")\n\nvar n = \"\"\"\n _____ _______\n |\\__ \\/ \\\n || |\\ __ \\\n \\|_| \\ /| \\ \\\n \\ \\ \\/\\ \\ \\\n \\ \\ \\ \\ \\ \\\n \\ \\___\\ \\ \\___\\\n \\ | | \\| |\n \\|___| |___|\n\"\"\".split(\"\\n\")\n\nfor (i in 0..8) {\n System.print(\"%(w[i]) %(r[i]) %(e[i]) %(n[i])\")\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\n\nproc DrawBlock(X, Y);\nint X, Y;\n[Cursor(X+1, Y); Text(0, \"///\\\");\n Cursor(X, Y+1); Text(0,\"/// \\\");\n Cursor(X, Y+2); Text(0,\"\\\\\\ /\");\n Cursor(X+1, Y+3); Text(0, \"\\\\\\/\");\n];\n\nint Data, D, X, Y;\n[ChOut(0, $C); \\form feed, clears screen\nData:= [%1000100011110000100000001110,\n %1000100010001000100000010001,\n %0101000010001000100000010011,\n %0010000011110000100000010101,\n %0101000010000000100000011001,\n %1000100010000000100000010001,\n %1000100010000000111110001110];\nfor Y:= 0 to 6 do\n [D:= Data(Y);\n for X:= 0 to 27 do\n [if D&1<<27 then DrawBlock(X*2+(6-Y)*2, Y*2);\n D:= D<<1;\n ];\n ];\n]\n", "language": "XPL0" }, { "code": "// Method 1\n// r$ = system$(\"explorer \\\"http://www.network-science.de/ascii/ascii.php?TEXT=${delegate}&x=23&y=10&FONT=block&RICH=no&FORM=left&STRE=no&WIDT=80&TEXT=Yabasic\\\"\")\n\n// Method 2\n// print\n// print \" _| _| _| _| \"\n// print \" _| _| _|_|_| _|_|_| _|_|_| _|_|_| _|_|_| \"\n// print \" _| _| _| _| _| _| _| _|_| _| _| \"\n// print \" _| _| _| _| _| _| _| _|_| _| _| \"\n// print \" _| _|_|_| _|_|_| _|_|_| _|_|_| _| _|_|_| \"\n// print\n\n// Method 3\nclear screen\n\ndim d$(5)\n\nd$(0) = \"X X X XXXX X XXX X XXX \"\nd$(1) = \" X X X X X X X X X X X X\"\nd$(2) = \" X XXXXX XXXX XXXXX XXX X X \"\nd$(3) = \" X X X X X X X X X X X\"\nd$(4) = \" X X X XXXX X X XXXX X XXX \"\n\nlong = len(d$(0))\n\nsub write(dx, dy, c$)\n\tlocal x, y\n\t\n\tfor y = 0 to 4\n\t\tfor x = 0 to long\n\t\t\tif mid$(d$(y), x, 1) = \"X\" print at(x + dx, y + dy) c$\n\t\tnext x\n\tnext y\nend sub\n\nwrite(2, 2, \"\\\\\")\nwrite(1, 1, \"#\")\nprint\n", "language": "Yabasic" }, { "code": "#<<<\n\"\nxxxxxx x x x\n x x x x\n x x x x\nx x x x\nxxxxx x x xxxx\n\"\n#<<<<\n.replace(\" \",\" \").replace(\"x\",\"_/\").println();\n", "language": "Zkl" }, { "code": " 10 DIM b(5,5): REM our bigmap characters\n 20 FOR l=1 TO 5: REM 5 characters\n 30 FOR m=1 TO 5: REM 5 rows\n 40 READ b(m,l)\n 50 NEXT m\n 60 NEXT l\n 70 PAPER 0: BORDER 0: REM black background and border\n 80 INK 2: REM our shadow will be red\n 90 CLS\n 100 LET r=8: REM shadow will start on row 8\n 110 LET c=1: REM shadow will start at column 1\n 120 GO SUB 2000: REM draw shadow\n 130 INK 6: REM our foreground will be yellow\n 140 LET r=9: REM foreground will start on row 9\n 150 LET c=2: REM foreground will start on column 2\n 160 GO SUB 2000: REM display the language name\n 999 STOP\n1000 REM convert to binary bigmap\n1010 LET z=16\n1020 IF t>=z THEN PRINT AT r+l-1,c+c1;CHR$ (143);: LET t=t-z: REM 143 is a block\n1040 LET c1=c1+1: LET z=z/2\n1050 IF z>=1 THEN GO TO 1020\n1060 RETURN\n2000 REM display the big letters\n2010 FOR l=1 TO 5: LET c1=0: REM our 5 rows\n2030 FOR m=1 TO 5: REM bigmap for each character\n2040 LET t=b(l,m)\n2050 GO SUB 1000\n2060 LET c1=c1+1: REM PRINT \" \";: REM space between each letter\n2070 NEXT m\n2080 NEXT l\n2090 RETURN\n9000 DATA 30,17,30,17,30: REM B\n9010 DATA 14,17,31,17,17: REM A\n9020 DATA 15,16,14,1,30: REM S\n9030 DATA 31,4,4,4,31: REM I\n9040 DATA 14,17,16,17,14: REM C\n", "language": "ZX-Spectrum-Basic" }, { "code": "5 PAPER 0: CLS\n10 LET d=0: INK 1: GO SUB 40\n20 LET d=1: INK 6: GO SUB 40\n30 STOP\n40 RESTORE\n50 FOR n=1 TO 5\n60 READ a$\n70 FOR j=1 TO LEN a$\n80 PRINT AT n+7,j+5+d;\n90 IF a$(j)=\"X\" THEN PRINT CHR$ 143: REM Equivalent to 219 in ASCII extended for IBM PC\n100 NEXT j\n110 NEXT n\n120 RETURN\n130 DATA \"XXX XXXX XXX X XXX\"\n140 DATA \"X X X X X X X \"\n150 DATA \"XXX XXXX XXX X X \"\n160 DATA \"X X X X X X X \"\n170 DATA \"XXX X X XXX X XXX\"\n", "language": "ZX-Spectrum-Basic" } ]
Write-language-name-in-3D-ASCII
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Write_to_Windows_event_log\n", "language": "00-META" }, { "code": ";Task:\nWrite script status to the Windows Event Log\n<br><br>\n\n", "language": "00-TASK" }, { "code": ":start:\nI :argv.len != 5\n print(‘Usage : #. < Followed by level, id, source string and description>’.format(:argv[0]))\nE\n os:(‘EventCreate /t #. /id #. /l APPLICATION /so #. /d \"#.\"’.format(:argv[1], :argv[2], :argv[3], :argv[4]))\n", "language": "11l" }, { "code": "; By ABCza, http://www.autohotkey.com/board/topic/76170-function-send-windows-log-events/\nh := RegisterForEvents(\"AutoHotkey\")\nSendWinLogEvent(h, \"Test Message\")\nDeregisterForEvents(h)\n\n/*\n--------------------------------------------------------------------------------------------------------------------------------\nFUNCTION: SendWinLogEvent\n--------------------------------------------------------------------------------------------------------------------------------\nWrites an entry at the end of the specified Windows event log. Returns nonzero if the function succeeds or zero if it fails.\n\nPARAMETERS:\n~~~~~~~~~~~\nhSource\t\t- Handle to a previously registered events source with RegisterForEvents.\nevType\t\t- EVENTLOG_SUCCESS\t\t\t:= 0x0000\n\t\t\t EVENTLOG_AUDIT_FAILURE\t:= 0x0010\n\t\t\t EVENTLOG_AUDIT_SUCCESS\t:= 0x0008\n\t\t\t EVENTLOG_ERROR_TYPE\t\t:= 0x0001\n\t\t\t EVENTLOG_INFORMATION_TYPE\t:= 0x0004\n\t\t\t EVENTLOG_WARNING_TYPE\t\t:= 0x0002\nevId\t\t- Event ID, can be any dword value.\nevCat\t\t- Any value, used to organize events in categories.\npStrings\t- A continuation section with newline separated strings (each max 31839 chars).\npData\t\t- A buffer containing the binary data.\n--------------------------------------------------------------------------------------------------------------------------------\nSYSTEM CALLS, STRUCTURES AND INFO:\n--------------------------------------------------------------------------------------------------------------------------------\nReportEvent\t\t\t\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx\nEvent Identifiers\t\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363651(v=vs.85).aspx\nEvent categories\t\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363649(v=vs.85).aspx\n--------------------------------------------------------------------------------------------------------------------------------\n*/\nSendWinLogEvent(hSource, String=\"\", evType=0x0004, evId=0x03EA, evCat=0, pData=0) {\n\tPtr := A_PtrSize ? \"Ptr\" : \"UInt\"\n\tLPCtSTRs := A_PtrSize ? \"Ptr*\" : \"UInt\"\n\tStringPut := A_IsUnicode ? \"StrPut\" : \"StrPut2\"\n\n\t; Reserve and initialise space for the event message.\n\tVarSetCapacity(eventMessage, StrLen(String), 0)\n\t%StringPut%(String, &eventMessage, A_IsUnicode ? \"UTF-16\" : \"\")\n\tr := DllCall(\"Advapi32.dll\\ReportEvent\" (A_IsUnicode ? \"W\" : \"A\")\n\t\t, UInt, hSource\t\t\t; handle\n\t\t, UShort, evType\t\t; WORD, eventlog_information_type\n\t\t, UShort, evCat\t\t\t; WORD, category\n\t\t, UInt, evId\t\t\t; DWORD, event ID, 0x03EA\n\t\t, Ptr, 0\t\t\t; PSID, ptr to user security ID\n\t\t, UShort, 1\t\t\t; WORD, number of strings\n\t\t, UInt, VarSetCapacity(pData)\t; DWORD, data size\n\t\t, LPCtSTRs, &eventMessage\t; LPCTSTR*, ptr to a buffer ...\n\t\t, Ptr, (VarSetCapacity(pData)) ? &pData : 0 )\t; ptr to a buffer of binary data\n\t\n\t; Release memory.\n\tVarSetCapacity(eventMessage, 0)\n\t\n\tReturn r\n}\n/*\n--------------------------------------------------------------------------------------------------------------------------------\nFUNCTION: RegisterForEvents\n--------------------------------------------------------------------------------------------------------------------------------\nRegisters the application to send Windows log events. Returns a handle to the registered source.\n\nPARAMETERS:\n~~~~~~~~~~~\nlogName\t - Can be \"Application\", \"System\" or a custom log name.\n--------------------------------------------------------------------------------------------------------------------------------\nSYSTEM CALLS, STRUCTURES AND INFO:\n--------------------------------------------------------------------------------------------------------------------------------\nRegisterEventSource\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363678(v=VS.85).aspx\nEvent Sources\t\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx\n--------------------------------------------------------------------------------------------------------------------------------\n*/\nRegisterForEvents(logName) {\n\tReturn DllCall(\"Advapi32.dll\\RegisterEventSource\" (A_IsUnicode ? \"W\" : \"A\")\n\t\t, UInt, 0\t\t\t\t; LPCTSTR, Local computer\n\t\t, Str, logName)\t\t\t; LPCTSTR Source name\n}\n/*\n--------------------------------------------------------------------------------------------------------------------------------\nFUNCTION: DeregisterForEvents\n--------------------------------------------------------------------------------------------------------------------------------\nDeregisters the previously registered application.\n\nPARAMETERS:\n~~~~~~~~~~~\nhSource\t - Handle to a registered source.\n--------------------------------------------------------------------------------------------------------------------------------\nSYSTEM CALLS, STRUCTURES AND INFO:\n--------------------------------------------------------------------------------------------------------------------------------\nDeregisterEventSource\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363642(v=vs.85).aspx\nEvent Sources\t\t\t\t\t\t\t\t- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx\n--------------------------------------------------------------------------------------------------------------------------------\n*/\nDeregisterForEvents(hSource) {\n\tIfNotEqual, hSource, 0, Return DllCall( \"Advapi32.dll\\DeregisterEventSource\"\n\t\t, UInt, hSource )\n}\n\n; StrPut for AutoHotkey Basic\nStrPut2(String, Address=\"\", Length=-1, Encoding=0)\n{\n\t; Flexible parameter handling:\n\tif Address is not integer\t\t ; StrPut(String [, Encoding])\n\t\tEncoding := Address,\tLength := 0,\tAddress := 1024\n\telse if Length is not integer\t ; StrPut(String, Address, Encoding)\n\t\tEncoding := Length,\tLength := -1\n\t\n\t; Check for obvious errors.\n\tif (Address+0 < 1024)\n\t\treturn\n\t\n\t; Ensure 'Encoding' contains a numeric identifier.\n\tif Encoding = UTF-16\n\t\tEncoding = 1200\n\telse if Encoding = UTF-8\n\t\tEncoding = 65001\n\telse if SubStr(Encoding,1,2)=\"CP\"\n\t\tEncoding := SubStr(Encoding,3)\n\t\n\tif !Encoding ; \"\" or 0\n\t{\n\t\t; No conversion required.\n\t\tchar_count := StrLen(String) + 1 ; + 1 because generally a null-terminator is wanted.\n\t\tif (Length)\n\t\t{\n\t\t\t; Check for sufficient buffer space.\n\t\t\tif (StrLen(String) <= Length || Length == -1)\n\t\t\t{\n\t\t\t\tif (StrLen(String) == Length)\n\t\t\t\t\t; Exceptional case: caller doesn't want a null-terminator.\n\t\t\t\t\tchar_count--\n\t\t\t\t; Copy the string, including null-terminator if requested.\n\t\t\t\tDllCall(\"RtlMoveMemory\", \"uint\", Address, \"uint\", &String, \"uint\", char_count)\n\t\t\t}\n\t\t\telse\n\t\t\t\t; For consistency with the sections below, don't truncate the string.\n\t\t\t\tchar_count = 0\n\t\t}\n\t\t;else: Caller just wants the the required buffer size (char_count), which will be returned below.\n\t}\n\telse if Encoding = 1200 ; UTF-16\n\t{\n\t\t; See the 'else' to this 'if' below for comments.\n\t\tif (Length <= 0)\n\t\t{\n\t\t\tchar_count := DllCall(\"MultiByteToWideChar\", \"uint\", 0, \"uint\", 0, \"uint\", &String, \"int\", StrLen(String), \"uint\", 0, \"int\", 0) + 1\n\t\t\tif (Length == 0)\n\t\t\t\treturn char_count\n\t\t\tLength := char_count\n\t\t}\n\t\tchar_count := DllCall(\"MultiByteToWideChar\", \"uint\", 0, \"uint\", 0, \"uint\", &String, \"int\", StrLen(String), \"uint\", Address, \"int\", Length)\n\t\tif (char_count && char_count < Length)\n\t\t\tNumPut(0, Address+0, char_count++*2, \"UShort\")\n\t}\n\telse if Encoding is integer\n\t{\n\t\t; Convert native ANSI string to UTF-16 first.\tNOTE - wbuf_len includes the null-terminator.\n\t\tVarSetCapacity(wbuf, 2 * wbuf_len := StrPut2(String, \"UTF-16\")), StrPut2(String, &wbuf, \"UTF-16\")\n\t\t\n\t\t; UTF-8 and some other encodings do not support this flag.\tAvoid it for UTF-8\n\t\t; (which is probably common) and rely on the fallback behaviour for other encodings.\n\t\tflags := Encoding=65001 ? 0 : 0x400\t; WC_NO_BEST_FIT_CHARS\n\t\tif (Length <= 0) ; -1 or 0\n\t\t{\n\t\t\t; Determine required buffer size.\n\t\t\tloop 2 {\n\t\t\t\tchar_count := DllCall(\"WideCharToMultiByte\", \"uint\", Encoding, \"uint\", flags, \"uint\", &wbuf, \"int\", wbuf_len, \"uint\", 0, \"int\", 0, \"uint\", 0, \"uint\", 0)\n\t\t\t\tif (char_count || A_LastError != 1004) ; ERROR_INVALID_FLAGS\n\t\t\t\t\tbreak\n\t\t\t\tflags := 0\t; Try again without WC_NO_BEST_FIT_CHARS.\n\t\t\t}\n\t\t\tif (!char_count)\n\t\t\t\treturn ; FAIL\n\t\t\tif (Length == 0) ; Caller just wants the required buffer size.\n\t\t\t\treturn char_count\n\t\t\t; Assume there is sufficient buffer space and hope for the best:\n\t\t\tLength := char_count\n\t\t}\n\t\t; Convert to target encoding.\n\t\tchar_count := DllCall(\"WideCharToMultiByte\", \"uint\", Encoding, \"uint\", flags, \"uint\", &wbuf, \"int\", wbuf_len, \"uint\", Address, \"int\", Length, \"uint\", 0, \"uint\", 0)\n\t\t; Since above did not null-terminate, check for buffer space and null-terminate if there's room.\n\t\t; It is tempting to always null-terminate (potentially replacing the last byte of data),\n\t\t; but that would exclude this function as a means to copy a string into a fixed-length array.\n\t\tif (char_count && char_count < Length)\n\t\t\tNumPut(0, Address+0, char_count++, \"Char\")\n\t\t; else no space to null-terminate; or conversion failed.\n\t}\n\t; Return the number of characters copied.\n\treturn char_count\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK\nBEGIN {\n write(\"INFORMATION\",1,\"Rosetta Code\")\n exit (errors == 0) ? 0 : 1\n}\nfunction write(type,id,description, cmd,esf) {\n esf = errors # errors so far\n cmd = sprintf(\"EVENTCREATE.EXE /T %s /ID %d /D \\\"%s\\\" >NUL\",type,id,description)\n printf(\"%s\\n\",cmd)\n if (toupper(type) !~ /^(SUCCESS|ERROR|WARNING|INFORMATION)$/) { error(\"/T is invalid\") }\n if (id+0 < 1 || id+0 > 1000) { error(\"/ID is invalid\") }\n if (description == \"\") { error(\"/D is invalid\") }\n if (errors == esf) {\n system(cmd)\n }\n return(errors)\n}\nfunction error(message) { printf(\"error: %s\\n\",message) ; errors++ }\n", "language": "AWK" }, { "code": "@echo off\nEventCreate /t ERROR /id 123 /l SYSTEM /so \"A Batch File\" /d \"This is found in system log.\"\nEventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d \"This is found in apps log\"\n", "language": "Batch-File" }, { "code": "@echo off\nEventCreate /t ERROR /id 123 /l SYSTEM /so \"A Batch File\" /d \"This is found in system log.\" >NUL 2>&1\nEventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d \"This is found in apps log\" >NUL 2>&1\n::That \">NUL 2>&1\" trick actually works in any command!\n", "language": "Batch-File" }, { "code": " INSTALL @lib$+\"COMLIB\"\n PROC_cominitlcid(1033)\n\n WshShell% = FN_createobject(\"WScript.Shell\")\n PROC_callmethod(WshShell%, \"LogEvent(0, \"\"Test from BBC BASIC\"\")\")\n\n PROC_releaseobject(WshShell%)\n PROC_comexit\n", "language": "BBC-BASIC" }, { "code": "#include<stdlib.h>\n#include<stdio.h>\n\nint main(int argC,char* argV[])\n{\n\tchar str[1000];\n\t\n\tif(argC!=5)\n\t\tprintf(\"Usage : %s < Followed by level, id, source string and description>\",argV[0]);\n\telse{\n\t\tsprintf(str,\"EventCreate /t %s /id %s /l APPLICATION /so %s /d \\\"%s\\\"\",argV[1],argV[2],argV[3],argV[4]);\n\t\tsystem(str);\n\t}\n\t\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <sstream>\n\nint main(int argc, char *argv[]) {\n using namespace std;\n\n#if _WIN32\n if (argc != 5) {\n cout << \"Usage : \" << argv[0] << \" (type) (id) (source string) (description>)\\n\";\n cout << \" Valid types: SUCCESS, ERROR, WARNING, INFORMATION\\n\";\n } else {\n stringstream ss;\n ss << \"EventCreate /t \" << argv[1] << \" /id \" << argv[2] << \" /l APPLICATION /so \" << argv[3] << \" /d \\\"\" << argv[4] << \"\\\"\";\n system(ss.str().c_str());\n }\n#else\n cout << \"Not implemented for *nix, only windows.\\n\";\n#endif\n\n return 0;\n}\n", "language": "C++" }, { "code": "using System.Diagnostics;\n\nnamespace RC\n{\n internal class Program\n {\n public static void Main()\n {\n string sSource = \"Sample App\";\n string sLog = \"Application\";\n string sEvent = \"Hello from RC!\";\n\n if (!EventLog.SourceExists(sSource))\n EventLog.CreateEventSource(sSource, sLog);\n\n EventLog.WriteEntry(sSource, sEvent);\n EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(use 'clojure.java.shell)\n(sh \"eventcreate\" \"/T\" \"INFORMATION\" \"/ID\" \"123\" \"/D\" \"Rosetta Code example\")\n", "language": "Clojure" }, { "code": "import std.process;\nimport std.stdio;\n\nvoid main() {\n auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d \"Rosetta Code Example\"`);\n\n if (cmd.status == 0) {\n writeln(\"Output: \", cmd.output);\n } else {\n writeln(\"Failed to execute command, status=\", cmd.status);\n }\n}\n", "language": "D" }, { "code": "program WriteToEventLog;\n\n{$APPTYPE CONSOLE}\n\nuses Windows;\n\nprocedure WriteLog(aMsg: string);\nvar\n lHandle: THandle;\n lMessagePtr: Pointer;\nbegin\n lMessagePtr := PChar(aMsg);\n lHandle := RegisterEventSource(nil, 'Logger');\n if lHandle > 0 then\n begin\n try\n ReportEvent(lHandle, 4 {Information}, 0, 0, nil, 1, 0, @lMessagePtr, nil);\n finally\n DeregisterEventSource(lHandle);\n end;\n end;\nend;\n\nbegin\n WriteLog('Message to log.');\nend.\n", "language": "Delphi" }, { "code": "use log = new System.Diagnostics.EventLog()\nlog.Source <- \"Sample Application\"\nlog.WriteEntry(\"Entered something in the Application Eventlog!\")\n", "language": "F-Sharp" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os/exec\"\n)\n\nfunc main() {\n command := \"EventCreate\"\n args := []string{\"/T\", \"INFORMATION\", \"/ID\", \"123\", \"/L\", \"APPLICATION\",\n \"/SO\", \"Go\", \"/D\", \"\\\"Rosetta Code Example\\\"\"}\n cmd := exec.Command(command, args...)\n err := cmd.Run()\n if err != nil {\n fmt.Println(err)\n }\n}\n", "language": "Go" }, { "code": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.stream.Collectors;\n\npublic class WriteToWindowsEventLog {\n public static void main(String[] args) throws IOException, InterruptedException {\n String osName = System.getProperty(\"os.name\").toUpperCase(Locale.ENGLISH);\n if (!osName.startsWith(\"WINDOWS\")) {\n System.err.println(\"Not windows\");\n return;\n }\n\n Process process = Runtime.getRuntime().exec(\"EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \\\"Rosetta Code Example\\\"\");\n process.waitFor(10, TimeUnit.SECONDS);\n int exitValue = process.exitValue();\n System.out.printf(\"Process exited with value %d\\n\", exitValue);\n if (exitValue != 0) {\n InputStream errorStream = process.getErrorStream();\n String result = new BufferedReader(new InputStreamReader(errorStream))\n .lines()\n .collect(Collectors.joining(\"\\n\"));\n System.err.println(result);\n }\n }\n}\n", "language": "Java" }, { "code": " cmd = \"eventcreate /T INFORMATION /ID 123 /D \\\"Rosetta Code Write to Windows event log task example\\\"\"\n Base.run(`$cmd`)\n", "language": "Julia" }, { "code": "// version 1.1.4-3\n\nfun main(args: Array<String>) {\n val command = \"EventCreate\" +\n \" /t INFORMATION\" +\n \" /id 123\" +\n \" /l APPLICATION\" +\n \" /so Kotlin\" +\n \" /d \\\"Rosetta Code Example\\\"\"\n\n Runtime.getRuntime().exec(command)\n}\n", "language": "Kotlin" }, { "code": "shell = xtra(\"Shell\").new()\nprops = [:]\nprops[\"operation\"] = \"runas\"\nprops[\"parameters\"] = \"/t INFORMATION /id 123 /l APPLICATION /so Lingo /d \"&QUOTE&\"Rosetta Code Example\"&QUOTE\nshell.shell_exec(\"EventCreate\", props)\n", "language": "Lingo" }, { "code": "use strict;\nuse warnings;\n\nuse Win32::EventLog;\nmy $handle = Win32::EventLog->new(\"Application\");\n\nmy $event = {\n\tComputer \t=>\t$ENV{COMPUTERNAME},\n\tSource\t\t=> \t'Rosettacode',\n\tEventType \t=> \tEVENTLOG_INFORMATION_TYPE,\n\tCategory \t=> \t'test',\n\tEventID \t=> \t0,\n\tData \t\t=> \t'a test for rosettacode',\n\tStrings \t=> \t'a string test for rosettacode',\n};\n$handle->Report($event);\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">WINDOWS</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (as in this will not work on Linux or p2js, duh)</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (as above, also prevent pointless attempts to transpile)</span>\n <span style=\"color: #7060A8;\">system</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\"`</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": ": (call 'logger \"This is a test\")\n-> T\n\n: (call 'logger \"This\" 'is \"another\" 'test)\n-> T\n", "language": "PicoLisp" }, { "code": "# Create Event Log object\n$EventLog=new-object System.Diagnostics.EventLog(\"Application\")\n#Declare Event Source; must be 'registered' with Windows\n$EventLog.Source=\"Application\" # It is possible to register a new source (see Note2)\n# Setup the Event Types; you don't have to use them all, but I'm including all the possibilities for reference\n$infoEvent=[System.Diagnostics.EventLogEntryType]::Information\n$errorEvent=[System.Diagnostics.EventLogEntryType]::Error\n$warningEvent=[System.Diagnostics.EventLogEntryType]::Warning\n$successAuditEvent=[System.Diagnostics.EventLogEntryType]::SuccessAudit\n$failureAuditEvent=[System.Diagnostics.EventLogEntryType]::FailureAudit\n\n# Write the event in the format \"Event test\",EventType,EventID\n$EventLog.WriteEntry(\"My Test Event\",$infoevent,70)\n", "language": "PowerShell" }, { "code": " $MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' +\n 'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' +\n 'his immediate release from jail and that he be allowed to run in the upcoming elections.'\n Write-EventLog -LogName 'System' -Source 'Eventlog' -Message $MessageFreeLula -EventId 13 -EntryType 'Information'\n 'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the system log event.'\n", "language": "PowerShell" }, { "code": " $MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' +\n 'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' +\n 'his immediate release from jail and that he be allowed to run in the upcoming elections.'\n New-EventLog -LogName 'Free Lula!' -Source '#FreeLula'\n Limit-EventLog -OverflowAction 'OverWriteAsNeeded' -MaximumSize (64KB*13) -LogName 'Free Lula!'\n Write-EventLog -LogName 'Free Lula!' -Source '#FreeLula' -Message $MessageFreeLula -EventId 13 -EntryType 'Information'\n 'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the \"Free Lula!\" log event.'\n", "language": "PowerShell" }, { "code": "Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)\n\n Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray\n Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result\n Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$)\n\n If lLogAPIRetVal\n lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata\n DeregisterEventSource_(lLogAPIRetVal)\n Result=#True\n EndIf\n\n ProcedureReturn Result\nEndProcedure\n", "language": "PureBasic" }, { "code": "import win32api\nimport win32con\nimport win32evtlog\nimport win32security\nimport win32evtlogutil\n\nph = win32api.GetCurrentProcess()\nth = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)\nmy_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]\n\napplicationName = \"My Application\"\neventID = 1\ncategory = 5\t# Shell\nmyType = win32evtlog.EVENTLOG_WARNING_TYPE\ndescr = [\"A warning\", \"An even more dire warning\"]\ndata = \"Application\\0Data\".encode(\"ascii\")\n\nwin32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,\n\teventType=myType, strings=descr, data=data, sid=my_sid)\n", "language": "Python" }, { "code": "#lang racket\n(log-warning \"Warning: nothing went wrong.\")\n", "language": "Racket" }, { "code": "given $*DISTRO {\n when .is-win {\n my $cmd = \"eventcreate /T INFORMATION /ID 123 /D \\\"Bla de bla bla bla\\\"\";\n run($cmd);\n }\n default { # most POSIX environments\n use Log::Syslog::Native;\n my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);\n $logger.info(\"[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.\");\n }\n}\n", "language": "Raku" }, { "code": "/*REXX program writes a \"record\" (event) to the (Microsoft) Windows event log. */\n\n eCMD = 'EVENTCREATE' /*name of the command that'll be used. */\n type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */\n id = 234 /*in range: 1 ───► 1000 (inclusive).*/\n logName = 'APPLICATION' /*information about what this is. */\n source = 'REXX' /* \" \" who's doing this. */\n desc = 'attempting to add an entry for a Rosetta Code demonstration.'\n desc = '\"' || desc || '\"' /*enclose description in double quotes.*/\n\neCMD '/T' type \"/ID\" id '/L' logName \"/SO\" source '/D' desc\n\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program writes a \"record\" (event) to the (Microsoft) Windows event log. */\n /* [↓] cmd options have extra spacing.*/\n\n'EVENTCREATE /T INFORMATION /ID 234 /L APPLICATION /SO REXX' ,\n '/D \"attempting to add an entry for a Rosetta Code demonstration.\"'\n\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "require 'win32/eventlog'\nlogger = Win32::EventLog.new\nlogger.report_event(:event_type => Win32::EventLog::INFO, :data => \"a test event log entry\")\n", "language": "Ruby" }, { "code": "#[cfg(windows)]\nmod bindings {\n ::windows::include_bindings!();\n}\n\n#[cfg(windows)]\nuse bindings::{\n Windows::Win32::Security::{\n GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,\n TOKEN_USER,\n },\n Windows::Win32::SystemServices::{\n GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,\n },\n};\n\n#[cfg(windows)]\nfn main() -> windows::Result<()> {\n let ph = unsafe { GetCurrentProcess() };\n let mut th: HANDLE = HANDLE(0);\n unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?;\n\n // Determine the required buffer size, ignore ERROR_INSUFFICIENT_BUFFER\n let mut length = 0_u32;\n unsafe {\n GetTokenInformation(\n th,\n TOKEN_INFORMATION_CLASS::TokenUser,\n std::ptr::null_mut(),\n 0,\n &mut length,\n )\n }\n .ok()\n .unwrap_err();\n\n // Retrieve the user token.\n let mut token_user_bytes = vec![0u8; length as usize];\n unsafe {\n GetTokenInformation(\n th,\n TOKEN_INFORMATION_CLASS::TokenUser,\n token_user_bytes.as_mut_ptr().cast(),\n length,\n &mut length,\n )\n }\n .ok()?;\n\n // Extract the pointer to the user SID.\n let user_sid: PSID = unsafe { (*token_user_bytes.as_ptr().cast::<TOKEN_USER>()).User.Sid };\n\n // use the Application event log\n let event_log_handle = unsafe { OpenEventLogA(PSTR::default(), \"Application\") };\n\n let mut event_msg = PSTR(b\"Hello in the event log\\0\".as_ptr() as _);\n unsafe {\n ReportEventA(\n HANDLE(event_log_handle.0), //h_event_log: T0__,\n ReportEvent_wType::EVENTLOG_WARNING_TYPE, // for type use EVENTLOG_WARNING_TYPE w_type: u16,\n 5, // for category use \"Shell\" w_category: u16,\n 1, // for ID use 1 dw_event_id: u32,\n user_sid, // lp_user_sid: *mut c_void,\n 1, // w_num_strings: u16,\n 0, // dw_data_size: u32,\n &mut event_msg, // lp_strings: *mut PSTR,\n std::ptr::null_mut(), // lp_raw_data: *mut c_void,\n )\n }\n .ok()?;\n\n Ok(())\n}\n\n#[cfg(not(windows))]\nfn main() {\n println!(\"Not implemented\");\n}\n", "language": "Rust" }, { "code": "fn main() {\n #[cfg(windows)]\n {\n windows::build!(Windows::Win32::SystemServices::{GetCurrentProcess, ReportEventA, OpenEventLogA, ReportEvent_wType, HANDLE, PSTR},\n Windows::Win32::Security::{OpenProcessToken, GetTokenInformation, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS, TOKEN_USER, PSID});\n }\n}\n", "language": "Rust" }, { "code": "[target.'cfg(windows)'.dependencies]\nwindows = \"0.7.0\"\n\n[target.'cfg(windows)'.build-dependencies]\nwindows = \"0.7.0\"\n", "language": "Rust" }, { "code": "object RegisterWinLogEvent extends App {\n\n import sys.process._\n\n def eventCreate= Seq(\"EVENTCREATE\", \"/T\", \"SUCCESS\", \"/id\", \"123\", \"/l\", \"APPLICATION\", \"/so\", \"Scala RegisterWinLogEvent\", \"/d\", \"Rosetta Code Example\" ).!!\n\n println(eventCreate)\n\n println(s\"\\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]\")\n\n}\n", "language": "Scala" }, { "code": "OS.Process.system \"logger \\\"Log event\\\" \" ;\n", "language": "Standard-ML" }, { "code": "OS.Process.system \"EventCreate /t WARNING /id 458 /l APPLICATION /so SomeSource /d \\\"Settastring\\\"\" ;\n", "language": "Standard-ML" }, { "code": "package require twapi\n\n# This command handles everything; use “-type error” to write an error message\ntwapi::eventlog_log \"My Test Event\" -type info\n", "language": "Tcl" }, { "code": "Sub write_event(event_type,msg)\n\tSet objShell = CreateObject(\"WScript.Shell\")\n\tSelect Case event_type\n\t\tCase \"SUCCESS\"\n\t\t\tn = 0\n\t\tCase \"ERROR\"\n\t\t\tn = 1\n\t\tCase \"WARNING\"\n\t\t\tn = 2\n\t\tCase \"INFORMATION\"\n\t\t\tn = 4\n\t\tCase \"AUDIT_SUCCESS\"\n\t\t\tn = 8\n\t\tCase \"AUDIT_FAILURE\"\n\t\t\tn = 16\n\tEnd Select\n\tobjShell.LogEvent n, msg\n\tSet objShell = Nothing\nEnd Sub\n\nCall write_event(\"INFORMATION\",\"This is a test information.\")\n", "language": "VBScript" }, { "code": "/* Write_to_Windows_event_log.wren */\n\nclass Windows {\n foreign static eventCreate(args)\n}\n\nvar args = [\n \"/T\", \"INFORMATION\", \"/ID\", \"123\", \"/L\", \"APPLICATION\",\n \"/SO\", \"Wren\", \"/D\", \"\\\"Rosetta Code Example\\\"\"\n].join(\" \")\n\nWindows.eventCreate(args)\n", "language": "Wren" }, { "code": "/* gcc Write_to_Windows_event_log.c -o Write_to_Windows_event_log -lwren -lm */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"wren.h\"\n\n/* C <=> Wren interface functions */\n\nvoid C_eventCreate(WrenVM* vm) {\n const char *args = wrenGetSlotString(vm, 1);\n char command[strlen(args) + 13];\n strcpy(command, \"EventCreate \");\n strcat(command, args);\n system(command);\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Windows\") == 0) {\n if (isStatic && strcmp(signature, \"eventCreate(_)\") == 0) return C_eventCreate;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignMethodFn = &bindForeignMethod;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Write_to_Windows_event_log.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" }, { "code": "zkl: System.cmd(0'|eventcreate \"/T\" \"INFORMATION\" \"/ID\" \"123\" \"/D\" \"Rosetta Code example\"|)\n", "language": "Zkl" } ]
Write-to-Windows-event-log
[ { "code": "---\ncategory:\n- Graphics algorithms\nfrom: http://rosettacode.org/wiki/Xiaolin_Wu's_line_algorithm\nnote: Raster graphics operations\n", "language": "00-META" }, { "code": ";Task:\nImplement the &nbsp; [[wp:Xiaolin Wu's line algorithm|Xiaolin Wu's line algorithm]] &nbsp; described in Wikipedia. \n\n\nThis algorithm draws anti-aliased lines. \n\n\n;Related task:\n* &nbsp; See &nbsp; [[Bresenham's line algorithm]] &nbsp; for ''aliased'' lines.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "INCLUDE \"H6:REALMATH.ACT\"\n\nREAL one\n\nPROC PutBigPixel(INT x,y,col)\n IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN\n y==LSH 2\n IF col<0 THEN col=0\n ELSEIF col>15 THEN col=15 FI\n Color=col\n Plot(x,y)\n DrawTo(x,y+3)\n FI\nRETURN\n\nINT FUNC Abs(INT x)\n IF x<0 THEN RETURN (-x) FI\nRETURN (x)\n\nPROC Swap(INT POINTER a,b)\n INT tmp\n\n tmp=a^ a^=b^ b^=tmp\nRETURN\n\nPROC Line(INT x1,y1,x2,y2,col)\n INT x,y,dx,dy,c\n INT POINTER px,py\n REAL rx,ry,grad,rcol,tmp1,tmp2\n\n dx=Abs(x2-x1)\n dy=Abs(y2-y1)\n IF dy>dx THEN\n Swap(@x1,@y1)\n Swap(@x2,@y2)\n px=@y py=@x\n ELSE\n px=@x py=@y\n FI\n\n IF x1>x2 THEN\n Swap(@x1,@x2)\n Swap(@y1,@y2)\n FI\n\n x=x2-x1\n IF x=0 THEN x=1 FI\n IntToRealForNeg(x,rx)\n IntToRealForNeg(y2-y1,ry)\n RealDiv(ry,rx,grad)\n\n IntToRealForNeg(y1,ry)\n IntToReal(col,rcol)\n FOR x=x1 TO x2\n DO\n Frac(ry,tmp1)\n IF IsNegative(tmp1) THEN\n RealAdd(one,tmp1,tmp2)\n RealAssign(tmp2,tmp1)\n FI\n RealMult(rcol,tmp1,tmp2)\n c=Round(tmp2)\n y=Floor(ry)\n PutBigPixel(px^,py^,col-c)\n y==+1\n PutBigPixel(px^,py^,c)\n RealAdd(ry,grad,tmp1)\n RealAssign(tmp1,ry)\n OD\nRETURN\n\nPROC Main()\n BYTE CH=$02FC ;Internal hardware value for last key pressed\n REAL tmp,c\n BYTE i,x1,y1,x2,y2\n\n MathInit()\n IntToReal(1,one)\n\n Graphics(9)\n FOR i=0 TO 11\n DO\n Line(0,i*4,38,1+i*5,15)\n Line(40+i*4,0,41+i*6,47,15)\n OD\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "/* ARM assembly Raspberry PI */\n/* program xiaolin1.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess displayerror\n see at end oh this program the instruction include */\n\n/* REMARK 2 : display use a FrameBuffer device : see raspberry pi FrameBuffer documentation\n this solution write directly on the screen of raspberry pi\n other solution is to use X11 windows but X11 has a function drawline !! */\n\n/* REMARK 3 : this program do not respect the convention for use, save and restau registers\n in rhe routine call !!!! */\n\n/*******************************************/\n/* Constantes */\n/*******************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ OPEN, 5\n.equ CLOSE, 6\n.equ IOCTL, 0x36\n.equ MMAP, 0xC0\n.equ UNMAP, 0x5B\n.equ O_RDWR, 0x0002 @ open for reading and writing\n.equ MAP_SHARED, 0x01 @ Share changes.\n.equ PROT_READ, 0x1 @ Page can be read.\n.equ PROT_WRITE, 0x2 @ Page can be written.\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessErreur: .asciz \"File open error.\\n\"\nszMessErreur1: .asciz \"File close error.\\n\"\nszMessErreur2: .asciz \"File mapping error.\\n\"\nszMessDebutPgm: .asciz \"Program start. \\n\"\nszMessFinOK: .asciz \"Normal end program. \\n\"\nszMessErrFix: .asciz \"Read error info fix framebuffer \\n\"\nszMessErrVar: .asciz \"Read error info var framebuffer \\n\"\nszRetourligne: .asciz \"\\n\"\nszParamNom: .asciz \"/dev/fb0\" @ FrameBuffer device name\nszLigneVar: .ascii \"Variables info : \"\nsWidth: .fill 11, 1, ' '\n .ascii \" * \"\nsHeight: .fill 11, 1, ' '\n .ascii \" Bits par pixel : \"\nsBits: .fill 11, 1, ' '\n .asciz \"\\n\"\n/*************************************************/\nszMessErr: .ascii\t\"Error code hexa : \"\nsHexa: .space 9,' '\n .ascii \" decimal : \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\n.align 4\n/* codes fonction pour la récupération des données fixes et variables */\nFBIOGET_FSCREENINFO: .int 0x4602 @ function code for read infos fixes Framebuffer\nFBIOGET_VSCREENINFO: .int 0x4600 @ function code for read infos variables Framebuffer\n\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n.align 4\nfix_info: .skip FBFIXSCinfo_fin @ memory reserve for structure FSCREENINFO\n.align 4\nvar_info: .skip FBVARSCinfo_fin @ memory reserve for structure VSCREENINFO\n/**********************************************/\n/* -- Code section */\n/**********************************************/\n.text\n.global main\n\nmain:\n ldr r0,iAdrszMessDebutPgm\n bl affichageMess @ display message\n ldr r0,iAdrszParamNom @ frameBuffer device name\n mov r1,#O_RDWR @ flags read/write\n mov r2,#0 @ mode\n mov r7,#OPEN @ open device FrameBuffer\n svc 0\n cmp r0,#0 @ error ?\n ble erreur\n mov r10,r0 @ save FD du device FrameBuffer in r10\n\n ldr r1,iAdrFBIOGET_VSCREENINFO @ read variables datas of FrameBuffer\n ldr r1,[r1] @ load code function\n ldr r2,iAdrvar_info @ structure memory address\n mov r7, #IOCTL @ call system\n swi 0\n cmp r0,#0\n blt erreurVar\n ldr r2,iAdrvar_info\n ldr r0,[r2,#FBVARSCinfo_xres] @ load screen width\n ldr r1,iAdrsWidth @ and convert in string for display\n bl conversion10S\n ldr r0,[r2,#FBVARSCinfo_yres] @ load screen height\n ldr r1,iAdrsHeight @ and convert in string for display\n bl conversion10S\n ldr r0,[r2,#FBVARSCinfo_bits_per_pixel] @ load bits by pixel\n ldr r1,iAdrsBits @ and convert in string for display\n bl conversion10S\n ldr r0,iAdrszLigneVar @ display result\n bl affichageMess\n\n mov r0,r10 @ FD du FB\n ldr r1,iAdrFBIOGET_FSCREENINFO @ read fixes datas of FrameBuffe\n ldr r1,[r1] @ load code function\n ldr r2,iAdrfix_info @ structure memory address\n mov r7, #IOCTL @ call system\n svc 0\n cmp r0,#0 @ error ?\n blt erreurFix\n ldr r0,iAdrfix_info\n\n ldr r1,iAdrfix_info @ read size memory for datas\n ldr r1,[r1,#FBFIXSCinfo_smem_len] @ in octets\n @ datas mapping\n mov r0,#0\n ldr r2,iFlagsMmap\n mov r3,#MAP_SHARED\n mov r4,r10\n mov r5,#0\n mov r7, #MMAP @ 192 call system for mapping\n swi #0\n cmp r0,#0 @ error ?\n beq erreur2\n mov r9,r0 @ save mapping address in r9\n /*************************************/\n /* display draw */\n bl dessin\n /************************************/\n mov r0,r9 @ mapping close\n ldr r1,iAdrfix_info\n ldr r1,[r1,#FBFIXSCinfo_smem_len] @ mapping memory size\n mov r7,#UNMAP @call system 91 for unmapping\n svc #0 @ error ?\n cmp r0,#0\n blt erreur1\n @ close device FrameBuffer\n mov r0,r10 @ load FB du device\n mov r7, #CLOSE @ call system\n swi 0\n ldr r0,iAdrszMessFinOK @ display end message\n bl affichageMess\n mov r0,#0 @ return code = OK\n b 100f\nerreurFix: @ display read error datas fix\n ldr r1,iAdrszMessErrFix @ message address\n bl displayError @ call display\n mov r0,#1 @ return code = error\n b 100f\nerreurVar: @ display read error datas var\n ldr r1,iAdrszMessErrVar\n bl displayError\n mov r0,#1\n b 100f\nerreur: @ display open error\n ldr r1,iAdrszMessErreur\n bl displayError\n mov r0,#1\n b 100f\nerreur1: @ display unmapped error\n ldr r1,iAdrszMessErreur1\n bl displayError\n mov r0,#1\n b 100f\nerreur2: @ display mapped error\n ldr r1,iAdrszMessErreur2\n bl displayError\n mov r0,#1\n b 100f\n100: @ end program\n mov r7, #EXIT\n svc 0\n/************************************/\niAdrszParamNom: .int szParamNom\niFlagsMmap: .int PROT_READ|PROT_WRITE\niAdrszMessErreur: .int szMessErreur\niAdrszMessErreur1: .int szMessErreur1\niAdrszMessErreur2: .int szMessErreur2\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessFinOK: .int szMessFinOK\niAdrszMessErrFix: .int szMessErrFix\niAdrszMessErrVar: .int szMessErrVar\niAdrszLigneVar: .int szLigneVar\niAdrvar_info: .int var_info\niAdrfix_info: .int fix_info\niAdrFBIOGET_FSCREENINFO: .int FBIOGET_FSCREENINFO\niAdrFBIOGET_VSCREENINFO: .int FBIOGET_VSCREENINFO\niAdrsWidth: .int sWidth\niAdrsHeight: .int sHeight\niAdrsBits: .int sBits\n/***************************************************/\n/* dessin */\n/***************************************************/\n/* r9 framebuffer memory address */\ndessin:\n push {r1-r12,lr} @ save registers\n mov r0,#255 @ red\n mov r1,#255 @ green\n mov r2,#255 @ blue 3 bytes 255 = white\n bl codeRGB @ code color RGB 32 bits\n mov r1,r0 @ background color\n ldr r0,iAdrfix_info @ load memory mmap size\n ldr r0,[r0,#FBFIXSCinfo_smem_len]\n bl coloriageFond @\n /* draw line 1 */\n mov r0,#200 @ X start line\n mov r1,#200 @ Y start line\n mov r2,#200 @ X end line\n mov r3,#100 @ Y end line\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres] @ load screen width\n bl drawLine\n /* draw line 2 */\n mov r0,#200\n mov r1,#200\n mov r2,#200\n mov r3,#300\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 3 */\n mov r0,#200\n mov r1,#200\n mov r2,#100\n mov r3,#200\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 4 */\n mov r0,#200\n mov r1,#200\n mov r2,#300\n mov r3,#200\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 5 */\n mov r0,#200\n mov r1,#200\n mov r2,#100\n mov r3,#100\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 6 */\n mov r0,#200\n mov r1,#200\n mov r2,#100\n mov r3,#300\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 7 */\n mov r0,#200\n mov r1,#200\n mov r2,#300\n mov r3,#300\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n /* draw line 8 */\n mov r0,#200\n mov r1,#200\n mov r2,#300\n mov r3,#100\n ldr r4,iAdrvar_info\n ldr r4,[r4,#FBVARSCinfo_xres]\n bl drawLine\n\n100:\n pop {r1-r12,lr} @ restaur registers\n bx lr @ end function\n\n/********************************************************/\n/* set background color */\n/********************************************************/\n/* r0 contains size screen memory */\n/* r1 contains rgb code color */\n/* r9 contains screen memory address */\ncoloriageFond:\n push {r2,lr}\n mov r2,#0 @ counter\n1: @ begin loop\n str r1,[r9,r2]\n add r2,#4\n cmp r2,r0\n blt 1b\n pop {r2,lr}\n bx lr\n/********************************************************/\n/* Xiaolin Wu line algorithm */\n/* no floating point compute, multiply value for 128 */\n/* for integer compute */\n/********************************************************/\n/* r0 x1 start line */\n/* r1 y1 start line */\n/* r2 x2 end line */\n/* r3 y2 end line */\n/* r4 screen width */\ndrawLine:\n push {fp,lr} @ save registers ( no other registers save )\n mov r5,r0 @ save x1\n mov r6,r1 @ save y1\n cmp r2,r5 @ compar x2,x1\n subgt r1,r2,r5\n suble r1,r5,r2 @ compute dx=abs val de x1-x2\n cmp r3,r6 @ compar y2,y1\n subgt r0,r3,r6\n suble r0,r6,r3 @ compute dy = abs val de y1-y2\n cmp r1,r0 @ compare dx , dy\n blt 5f @ dx < dy\n @ dx > dy\n cmp r2,r5 @ compare x2,x1\n movlt r8,r5 @ x2 < x1\n movlt r5,r2 @ swap x2,x1\n movlt r2,r8\n movlt r8,r6 @ swap y2,y1\n movlt r6,r3\n movlt r3,r8\n lsl r0,#7 @ * by 128\n mov r7,r2 @ save x2\n mov r8,r3 @ save y2\n cmp r1,#0 @ divisor = 0 ?\n moveq r10,#128\n beq 1f\n bl division @ gradient compute (* 128)\n mov r10,r2 @ r10 contient le gradient\n1:\n @ display start points\n mov r0,#64\n bl colorPixel\n mov r3,r0 @ RGB color\n mov r0,r5 @ x1\n mov r1,r6 @ y1\n mov r2,r4 @ screen witdh\n bl aff_pixel_codeRGB32 @ display pixel\n add r1,#1 @ increment y1\n bl aff_pixel_codeRGB32\n @ display end points\n mov r0,r7 @ x2\n mov r1,r8 @ y2\n bl aff_pixel_codeRGB32\n add r1,#1 @ increment y2\n bl aff_pixel_codeRGB32\n cmp r8,r6 @ compar y2,y1\n blt 3f @ y2 < y1\n mov r4,r5 @ x = x1\n lsl r5,r6,#7 @ compute y1 * 128\n add r5,r10 @ compute intery = (y1 * 128 + gradient * 128)\n2: @ start loop draw line pixels\n lsr r1,r5,#7 @ intery / 128 = y\n lsl r8,r1,#7\n sub r6,r5,r8 @ reminder of intery /128 = brightness\n mov r0,r6\n bl colorPixel @ compute rgb color brightness\n mov r3,r0 @ rgb color\n mov r0,r4 @ x\n bl aff_pixel_codeRGB32 @ display pixel 1\n add r1,#1 @ increment y\n rsb r0,r6,#128 @ compute 128 - brightness\n bl colorPixel @ compute new rgb color\n mov r3,r0\n mov r0,r4\n bl aff_pixel_codeRGB32 @ display pixel 2\n add r5,r10 @ add gradient to intery\n add r4,#1 @ increment x\n cmp r4,r7 @ x < x2\n ble 2b @ yes -> loop\n b 100f @ else end\n3: @ y2 < y1\n mov r4,r7 @ x = x2\n mov r7,r5 @ save x1\n lsl r5,r8,#7 @ y = y1 * 128\n add r5,r10 @ compute intery = (y1 * 128 + gradient * 128)\n4:\n lsr r1,r5,#7 @ y = ent(intery / 128)\n lsl r8,r1,#7\n sub r8,r5,r8 @ brightness = remainder\n mov r0,r8\n bl colorPixel\n mov r3,r0\n mov r0,r4\n bl aff_pixel_codeRGB32\n add r1,#1\n rsb r0,r8,#128\n bl colorPixel\n mov r3,r0\n mov r0,r4\n bl aff_pixel_codeRGB32\n add r5,r10\n sub r4,#1 @ decrement x\n cmp r4,r7 @ x > x1\n bgt 4b @ yes -> loop\n b 100f\n5: @ dx < dy\n cmp r3,r6 @ compare y2,y1\n movlt r8,r5 @ y2 < y1\n movlt r5,r2 @ swap x1,x2\n movlt r2,r8\n movlt r8,r6 @ swap y1,y2\n movlt r6,r3\n movlt r3,r8\n mov r8,r1 @ swap r0,r1 for routine division\n mov r1,r0\n lsl r0,r8,#7 @ dx * by 128\n mov r7,r2 @ save x2\n mov r8,r3 @ save y2\n cmp r1,#0 @ dy = zero ?\n moveq r10,#128\n beq 6f\n bl division @ compute gradient * 128\n mov r10,r2 @ gradient -> r10\n6:\n @ display start points\n mov r0,#64\n bl colorPixel\n mov r3,r0 @ color pixel\n mov r0,r5 @ x1\n mov r1,r6 @ y1\n mov r2,r4 @ screen width\n bl aff_pixel_codeRGB32\n add r1,#1\n bl aff_pixel_codeRGB32\n @ display end points\n mov r0,r7\n mov r1,r8\n bl aff_pixel_codeRGB32\n add r1,#1\n bl aff_pixel_codeRGB32\n cmp r5,r7 @ x1 < x2 ?\n blt 8f\n mov r4,r6 @ y = y1\n lsl r5,#7 @ compute x1 * 128\n add r5,r10 @ compute interx\n7:\n lsr r1,r5,#7 @ compute x = ent ( interx / 128)\n lsl r3,r1,#7\n sub r6,r5,r3 @ brightness = remainder\n mov r0,r6\n bl colorPixel\n mov r3,r0\n mov r0,r1 @ new x\n add r7,r0,#1\n mov r1,r4 @ y\n bl aff_pixel_codeRGB32\n rsb r0,r6,#128\n bl colorPixel\n mov r3,r0\n mov r0,r7 @ new x + 1\n mov r1,r4 @ y\n bl aff_pixel_codeRGB32\n add r5,r10\n add r4,#1\n cmp r4,r8\n ble 7b\n b 100f\n8:\n mov r4,r8 @ y = y2\n lsl r5,#7 @ compute x1 * 128\n add r5,r10 @ compute interx\n9:\n lsr r1,r5,#7 @ compute x\n lsl r3,r1,#7\n sub r8,r5,r3\n mov r0,r8\n bl colorPixel\n mov r3,r0\n mov r0,r1 @ new x\n add r7,r0,#1\n mov r1,r4 @ y\n bl aff_pixel_codeRGB32\n rsb r0,r8,#128\n bl colorPixel\n mov r3,r0\n mov r0,r7 @ new x + 1\n mov r1,r4 @ y\n bl aff_pixel_codeRGB32\n add r5,r10\n sub r4,#1\n cmp r4,r6\n bgt 9b\n b 100f\n100:\n pop {fp,lr}\n bx lr\n/********************************************************/\n/* brightness color pixel */\n/********************************************************/\n/* r0 % brightness ( 0 to 128) */\ncolorPixel:\n push {r1,r2,lr} /* save des 2 registres frame et retour */\n cmp r0,#0\n beq 100f\n cmp r0,#128\n mov r0,#127\n lsl r0,#1 @ red = brightness * 2 ( 2 to 254)\n mov r1,r0 @ green = red\n mov r2,r0 @ blue = red\n bl codeRGB @ compute rgb code color 32 bits\n100:\n pop {r1,r2,lr}\n bx lr\n\n/***************************************************/\n/* display pixels 32 bits */\n/***************************************************/\n/* r9 framebuffer memory address */\n/* r0 = x */\n/* r1 = y */\n/* r2 screen width in pixels */\n/* r3 code color RGB 32 bits */\naff_pixel_codeRGB32:\n push {r0-r4,lr} @ save registers\n @ compute location pixel\n mul r4,r1,r2 @ compute y * screen width\n add r0,r0,r4 @ + x\n lsl r0,#2 @ * 4 octets\n str r3,[r9,r0] @ store rgb code in mmap memory\n pop {r0-r4,lr} @ restaur registers\n bx lr\n/********************************************************/\n/* Code color RGB */\n/********************************************************/\n/* r0 red r1 green r2 blue */\n/* r0 returns RGB code */\ncodeRGB:\n lsl r0,#16 @ shift red color 16 bits\n lsl r1,#8 @ shift green color 8 bits\n eor r0,r1 @ or two colors\n eor r0,r2 @ or 3 colors in r0\n bx lr\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"./affichage.inc\"\n\n/***************************************************/\n/* DEFINITION DES STRUCTURES */\n/***************************************************/\n/* structure FSCREENINFO */\n/* voir explication détaillée : https://www.kernel.org/doc/Documentation/fb/api.txt */\n .struct 0\nFBFIXSCinfo_id: /* identification string eg \"TT Builtin\" */\n .struct FBFIXSCinfo_id + 16\nFBFIXSCinfo_smem_start: /* Start of frame buffer mem */\n .struct FBFIXSCinfo_smem_start + 4\nFBFIXSCinfo_smem_len: /* Length of frame buffer mem */\n .struct FBFIXSCinfo_smem_len + 4\nFBFIXSCinfo_type: /* see FB_TYPE_* */\n .struct FBFIXSCinfo_type + 4\nFBFIXSCinfo_type_aux: /* Interleave for interleaved Planes */\n .struct FBFIXSCinfo_type_aux + 4\nFBFIXSCinfo_visual: /* see FB_VISUAL_* */\n .struct FBFIXSCinfo_visual + 4\nFBFIXSCinfo_xpanstep: /* zero if no hardware panning */\n .struct FBFIXSCinfo_xpanstep + 2\nFBFIXSCinfo_ypanstep: /* zero if no hardware panning */\n .struct FBFIXSCinfo_ypanstep + 2\nFBFIXSCinfo_ywrapstep: /* zero if no hardware ywrap */\n .struct FBFIXSCinfo_ywrapstep + 4\nFBFIXSCinfo_line_length: /* length of a line in bytes */\n .struct FBFIXSCinfo_line_length + 4\nFBFIXSCinfo_mmio_start: /* Start of Memory Mapped I/O */\n .struct FBFIXSCinfo_mmio_start + 4\nFBFIXSCinfo_mmio_len: /* Length of Memory Mapped I/O */\n .struct FBFIXSCinfo_mmio_len + 4\nFBFIXSCinfo_accel: /* Indicate to driver which specific chip/card we have */\n .struct FBFIXSCinfo_accel + 4\nFBFIXSCinfo_capabilities: /* see FB_CAP_* */\n .struct FBFIXSCinfo_capabilities + 4\nFBFIXSCinfo_reserved: /* Reserved for future compatibility */\n .struct FBFIXSCinfo_reserved + 8\nFBFIXSCinfo_fin:\n\n/* structure VSCREENINFO */\n .struct 0\nFBVARSCinfo_xres: /* visible resolution */\n .struct FBVARSCinfo_xres + 4\nFBVARSCinfo_yres:\n .struct FBVARSCinfo_yres + 4\nFBVARSCinfo_xres_virtual: /* virtual resolution */\n .struct FBVARSCinfo_xres_virtual + 4\nFBVARSCinfo_yres_virtual:\n .struct FBVARSCinfo_yres_virtual + 4\nFBVARSCinfo_xoffset: /* offset from virtual to visible resolution */\n .struct FBVARSCinfo_xoffset + 4\nFBVARSCinfo_yoffset:\n .struct FBVARSCinfo_yoffset + 4\nFBVARSCinfo_bits_per_pixel: /* bits par pixel */\n .struct FBVARSCinfo_bits_per_pixel + 4\nFBVARSCinfo_grayscale: /* 0 = color, 1 = grayscale, >1 = FOURCC */\n .struct FBVARSCinfo_grayscale + 4\nFBVARSCinfo_red: /* bitfield in fb mem if true color, */\n .struct FBVARSCinfo_red + 4\nFBVARSCinfo_green: /* else only length is significant */\n .struct FBVARSCinfo_green + 4\nFBVARSCinfo_blue:\n .struct FBVARSCinfo_blue + 4\nFBVARSCinfo_transp: /* transparency */\n .struct FBVARSCinfo_transp + 4\nFBVARSCinfo_nonstd: /* != 0 Non standard pixel format */\n .struct FBVARSCinfo_nonstd + 4\nFBVARSCinfo_activate: /* see FB_ACTIVATE_* */\n .struct FBVARSCinfo_activate + 4\nFBVARSCinfo_height: /* height of picture in mm */\n .struct FBVARSCinfo_height + 4\nFBVARSCinfo_width: /* width of picture in mm */\n .struct FBVARSCinfo_width + 4\nFBVARSCinfo_accel_flags: /* (OBSOLETE) see fb_info.flags */\n .struct FBVARSCinfo_accel_flags + 4\n/* Timing: All values in pixclocks, except pixclock (of course) */\nFBVARSCinfo_pixclock: /* pixel clock in ps (pico seconds) */\n .struct FBVARSCinfo_pixclock + 4\nFBVARSCinfo_left_margin:\n .struct FBVARSCinfo_left_margin + 4\nFBVARSCinfo_right_margin:\n .struct FBVARSCinfo_right_margin + 4\nFBVARSCinfo_upper_margin:\n .struct FBVARSCinfo_upper_margin + 4\nFBVARSCinfo_lower_margin:\n .struct FBVARSCinfo_lower_margin + 4\nFBVARSCinfo_hsync_len: /* length of horizontal sync */\n .struct FBVARSCinfo_hsync_len + 4\nFBVARSCinfo_vsync_len: /* length of vertical sync */\n .struct FBVARSCinfo_vsync_len + 4\nFBVARSCinfo_sync: /* see FB_SYNC_* */\n .struct FBVARSCinfo_sync + 4\nFBVARSCinfo_vmode: /* see FB_VMODE_* */\n .struct FBVARSCinfo_vmode + 4\nFBVARSCinfo_rotate: /* angle we rotate counter clockwise */\n .struct FBVARSCinfo_rotate + 4\nFBVARSCinfo_colorspace: /* colorspace for FOURCC-based modes */\n .struct FBVARSCinfo_colorspace + 4\nFBVARSCinfo_reserved: /* Reserved for future compatibility */\n .struct FBVARSCinfo_reserved + 16\nFBVARSCinfo_fin:\n", "language": "ARM-Assembly" }, { "code": "#include \"share/atspre_staload.hats\"\nstaload UN = \"prelude/SATS/unsafe.sats\"\n\n%{^\n#include <float.h>\n#include <math.h>\n%}\n\ntypedef color = double\n\ntypedef drawing_surface (u0 : int, v0 : int,\n u1 : int, v1 : int) =\n [u0 <= u1; v0 <= v1]\n '{\n u0 = int u0,\n v0 = int v0,\n u1 = int u1,\n v1 = int v1,\n pixels = matrixref (color, (u1 - u0) + 1, (v1 - v0) + 1)\n }\n\nfn\ndrawing_surface_make\n {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (u0 : int u0,\n v0 : int v0,\n u1 : int u1,\n v1 : int v1)\n : drawing_surface (u0, v0, u1, v1) =\n let\n val w = succ (u1 - u0) and h = succ (v1 - v0)\n in\n '{\n u0 = u0,\n v0 = v0,\n u1 = u1,\n v1 = v1,\n pixels = matrixref_make_elt (i2sz w, i2sz h, 0.0)\n }\n end\n\nfn\ndrawing_surface_get_at\n {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (s : drawing_surface (u0, v0, u1, v1),\n x : int,\n y : int)\n : color =\n let\n val '{ u0 = u0, v0 = v0, u1 = u1, v1 = v1, pixels = pixels } = s\n and x = g1ofg0 x and y = g1ofg0 y\n in\n if (u0 <= x) * (x <= u1) * (v0 <= y) * (y <= v1) then\n (* Notice there are THREE values in the square brackets. The\n matrixref does not store its dimensions and so we have to\n specify a stride as the second value. The value must,\n however, be the CORRECT stride. This is checked at compile\n time. (Here ATS is striving to be efficient rather than\n convenient!) *)\n pixels[x - u0, succ (v1 - v0), v1 - y]\n else\n $extval (double, \"nan (\\\"0\\\")\")\n end\n\nfn\ndrawing_surface_set_at\n {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (s : drawing_surface (u0, v0, u1, v1),\n x : int,\n y : int,\n c : color)\n : void =\n let\n val '{ u0 = u0, v0 = v0, u1 = u1, v1 = v1, pixels = pixels } = s\n and x = g1ofg0 x and y = g1ofg0 y\n in\n if (u0 <= x) * (x <= u1) * (v0 <= y) * (y <= v1) then\n pixels[x - u0, succ (v1 - v0), v1 - y] := c\n end\n\n(* Indices outside the drawing_surface are allowed. They are handled\n by treating them as if you were trying to draw on the air. *)\noverload [] with drawing_surface_get_at\noverload [] with drawing_surface_set_at\n\nfn\nwrite_PGM {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (outf : FILEref,\n s : drawing_surface (u0, v0, u1, v1))\n : void =\n (* Write a Portable Grayscale Map. *)\n let\n val '{ u0 = u0, v0 = v0, u1 = u1, v1 = v1, pixels = pixels } = s\n\n stadef w = (u1 - u0) + 1\n stadef h = (v1 - v0) + 1\n val w : int w = succ (u1 - u0)\n and h : int h = succ (v1 - v0)\n\n fun\n loop {x, y : int | 0 <= x; x <= w; 0 <= y; y <= h}\n .<h - y, w - x>.\n (x : int x,\n y : int y) : void =\n if y = h then\n ()\n else if x = w then\n loop (0, succ y)\n else\n let\n (* I do no gamma correction, but gamma correction can be\n done afterwards by running the output through \"pnmgamma\n -lineartobt709\" *)\n val intensity = 1.0 - pixels[x, h, y]\n val pgm_value : int =\n g0f2i ($extfcall (double, \"rint\", 65535 * intensity))\n val more_significant_byte = pgm_value / 256\n and less_significant_byte = pgm_value mod 256\n val msbyte = int2uchar0 more_significant_byte\n and lsbyte = int2uchar0 less_significant_byte\n in\n fprint_val<uchar> (outf, msbyte);\n fprint_val<uchar> (outf, lsbyte);\n loop (succ x, y)\n end\n in\n fprintln! (outf, \"P5\");\n fprintln! (outf, w, \" \", h);\n fprintln! (outf, \"65535\");\n loop (0, 0)\n end\n\nfn\nipart (x : double) : int =\n g0f2i ($extfcall (double, \"floor\", x))\n\nfn\niround (x : double) : int =\n ipart (x + 0.5)\n\nfn\nfpart (x : double) : double =\n x - $extfcall (double, \"floor\", x)\n\nfn\nrfpart (x : double) : double =\n 1.0 - fpart (x)\n\nfn\nplot {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (s : drawing_surface (u0, v0, u1, v1),\n x : int,\n y : int,\n c : color)\n : void =\n let\n (* One might prefer a more sophisticated function than mere\n addition. *)\n val combined_color = s[x, y] + c\n in\n s[x, y] := min (combined_color, 1.0)\n end\n\nfn\n_drawln {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (s : drawing_surface (u0, v0, u1, v1),\n x0 : double,\n y0 : double,\n x1 : double,\n y1 : double,\n steep : bool)\n : void =\n let\n val dx = x1 - x0 and dy = y1 - y0\n val gradient = (if dx = 0.0 then 1.0 else dy / dx) : double\n\n (* Handle the first endpoint. *)\n val xend = iround x0\n val yend = y0 + (gradient * (g0i2f xend - x0))\n val xgap = rfpart (x0 + 0.5)\n val xpxl1 = xend and ypxl1 = ipart yend\n val () =\n if steep then\n begin\n plot (s, ypxl1, xpxl1, rfpart yend * xgap);\n plot (s, succ ypxl1, xpxl1, fpart yend * xgap)\n end\n else\n begin\n plot (s, xpxl1, ypxl1, rfpart yend * xgap);\n plot (s, xpxl1, succ ypxl1, fpart yend * xgap)\n end\n\n (* The first y-intersection. Notice it is a \"var\" (a variable)\n instead of a \"val\" (an immutable value). There is no need to\n box it as a \"ref\", the way one must typically do in an ML\n dialect. We could have done so, but the following treats the\n variable as an ordinary C automatic variable, and is more\n efficient. *)\n var intery : double = yend + gradient\n\n (* Handle the second endpoint. *)\n val xend = iround (x1)\n val yend = y1 + (gradient * (g0i2f xend - x1))\n val xgap = fpart (x1 + 0.5)\n val xpxl2 = xend and ypxl2 = ipart yend\n val () =\n if steep then\n begin\n plot (s, ypxl2, xpxl2, rfpart yend * xgap);\n plot (s, succ ypxl2, xpxl2, fpart yend * xgap)\n end\n else\n begin\n plot (s, xpxl2, ypxl2, rfpart yend * xgap);\n plot (s, xpxl2, succ ypxl2, fpart yend * xgap)\n end\n in\n (* Loop over the rest of the points. I use procedural \"for\"-loops\n instead of the more usual (for ATS) tail recursion. *)\n if steep then\n let\n var x : int\n in\n for (x := succ xpxl1; x <> xpxl2; x := succ x)\n begin\n plot (s, ipart intery, x, rfpart intery);\n plot (s, succ (ipart intery), x, fpart intery);\n intery := intery + gradient\n end\n end\n else\n let\n var x : int\n in\n for (x := succ xpxl1; x <> xpxl2; x := succ x)\n begin\n plot (s, x, ipart intery, rfpart intery);\n plot (s, x, succ (ipart intery), fpart intery);\n intery := intery + gradient\n end\n end\n end\n\nfn\ndraw_line {u0, v0, u1, v1 : int | u0 <= u1; v0 <= v1}\n (s : drawing_surface (u0, v0, u1, v1),\n x0 : double,\n y0 : double,\n x1 : double,\n y1 : double)\n : void =\n let\n val xdiff = abs (x1 - x0) and ydiff = abs (y1 - y0)\n in\n if ydiff <= xdiff then\n begin\n if x0 <= x1 then\n _drawln (s, x0, y0, x1, y1, false)\n else\n _drawln (s, x1, y1, x0, y0, false)\n end\n else\n begin\n if y0 <= y1 then\n _drawln (s, y0, x0, y1, x1, true)\n else\n _drawln (s, y1, x1, y0, x0, true)\n end\n end\n\nimplement\nmain0 () =\n let\n macdef M_PI = $extval (double, \"M_PI\")\n\n val u0 = 0 and v0 = 0\n and u1 = 639 and v1 = 479\n\n val s = drawing_surface_make (u0, v0, u1, v1)\n\n fun\n loop (theta : double) : void =\n if theta < 360.0 then\n let\n val cos_theta = $extfcall (double, \"cos\",\n theta * (M_PI / 180.0))\n and sin_theta = $extfcall (double, \"sin\",\n theta * (M_PI / 180.0))\n and x0 = 380.0 and y0 = 130.0\n val x1 = x0 + (cos_theta * 1000.0)\n and y1 = y0 + (sin_theta * 1000.0)\n in\n draw_line (s, x0, y0, x1, y1);\n loop (theta + 5.0)\n end\n in\n loop 0.0;\n write_PGM (stdout_ref, s)\n end\n", "language": "ATS" }, { "code": "#SingleInstance, Force\n#NoEnv\nSetBatchLines, -1\n\npToken := Gdip_Startup()\nglobal pBitmap := Gdip_CreateBitmap(500, 500)\ndrawLine(100,50,400,400)\nGdip_SaveBitmapToFile(pBitmap, A_ScriptDir \"\\linetest.png\")\nGdip_DisposeImage(pBitmap)\nGdip_Shutdown(pToken)\nRun, % A_ScriptDir \"\\linetest.png\"\nExitApp\n\nplot(x, y, c) {\n A := DecToBase(255 * c, 16)\n Gdip_SetPixel(pBitmap, x, y, \"0x\" A \"000000\")\n}\n\n; integer part of x\nipart(x) {\n return x // 1\n}\n\nrnd(x) {\n return ipart(x + 0.5)\n}\n\n; fractional part of x\nfpart(x) {\n if (x < 0)\n return 1 - (x - floor(x))\n return x - floor(x)\n}\n\nrfpart(x) {\n return 1 - fpart(x)\n}\n\ndrawLine(x0,y0,x1,y1) {\n steep := abs(y1 - y0) > abs(x1 - x0)\n\n if (steep) {\n temp := x0, x0 := y0, y0 := temp\n temp := x1, x1 := y1, y1 := temp\n }\n if (x0 > x1 then) {\n temp := x0, x0 := x1, x1 := temp\n temp := y0, y0 := y1, y1 := temp\n }\n\n dx := x1 - x0\n dy := y1 - y0\n gradient := dy / dx\n\n ; handle first endpoint\n xend := rnd(x0)\n yend := y0 + gradient * (xend - x0)\n xgap := rfpart(x0 + 0.5)\n xpxl1 := xend ; this will be used in the main loop\n ypxl1 := ipart(yend)\n if (steep) {\n plot(ypxl1, xpxl1, rfpart(yend) * xgap)\n plot(ypxl1+1, xpxl1, fpart(yend) * xgap)\n }\n else {\n plot(xpxl1, ypxl1 , rfpart(yend) * xgap)\n plot(xpxl1, ypxl1+1, fpart(yend) * xgap)\n }\n intery := yend + gradient ; first y-intersection for the main loop\n\n ; handle second endpoint\n xend := rnd(x1)\n yend := y1 + gradient * (xend - x1)\n xgap := fpart(x1 + 0.5)\n xpxl2 := xend ;this will be used in the main loop\n ypxl2 := ipart(yend)\n if (steep) {\n plot(ypxl2 , xpxl2, rfpart(yend) * xgap)\n plot(ypxl2+1, xpxl2, fpart(yend) * xgap)\n }\n else {\n plot(xpxl2, ypxl2, rfpart(yend) * xgap)\n plot(xpxl2, ypxl2+1, fpart(yend) * xgap)\n }\n\n ; main loop\n while (x := xpxl1 + A_Index) < xpxl2 {\n if (steep) {\n plot(ipart(intery) , x, rfpart(intery))\n plot(ipart(intery)+1, x, fpart(intery))\n }\n else {\n plot(x, ipart (intery), rfpart(intery))\n plot(x, ipart (intery)+1, fpart(intery))\n }\n intery := intery + gradient\n }\n}\n\nDecToBase(n, Base) {\n static U := A_IsUnicode ? \"w\" : \"a\"\n VarSetCapacity(S,65,0)\n DllCall(\"msvcrt\\_i64to\" U, \"Int64\",n, \"Str\",S, \"Int\",Base)\n return, S\n}\n", "language": "AutoHotkey" }, { "code": " PROCdrawAntiAliasedLine(100, 100, 600, 400, 0, 0, 0)\n END\n\n DEF PROCdrawAntiAliasedLine(x1, y1, x2, y2, r%, g%, b%)\n LOCAL dx, dy, xend, yend, grad, yf, xgap, ix1%, iy1%, ix2%, iy2%, x%\n\n dx = x2 - x1\n dy = y2 - y1\n IF ABS(dx) < ABS(dy) THEN\n SWAP x1, y1\n SWAP x2, y2\n SWAP dx, dy\n ENDIF\n\n IF x2 < x1 THEN\n SWAP x1, x2\n SWAP y1, y2\n ENDIF\n\n grad = dy / dx\n\n xend = INT(x1 + 0.5)\n yend = y1 + grad * (xend - x1)\n xgap = xend + 0.5 - x1\n ix1% = xend\n iy1% = INT(yend)\n PROCplot(ix1%, iy1%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)\n PROCplot(ix1%, iy1% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)\n yf = yend + grad\n\n xend = INT(x2 + 0.5)\n yend = y2 + grad * (xend - x2)\n xgap = x2 + 0.5 - xend\n ix2% = xend\n iy2% = INT(yend)\n PROCplot(ix2%, iy2%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)\n PROCplot(ix2%, iy2% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)\n\n FOR x% = ix1% + 1 TO ix2% - 1\n PROCplot(x%, INT(yf), r%, b%, g%, INT(yf) + 1 - yf)\n PROCplot(x%, INT(yf) + 1, r%, b%, g%, yf - INT(yf))\n yf += grad\n NEXT\n ENDPROC\n\n DEF PROCplot(X%, Y%, R%, G%, B%, a)\n LOCAL C%\n C% = TINT(X%*2,Y%*2)\n COLOUR 1, R%*a + (C% AND 255)*(1-a), \\\n \\ G%*a + (C% >> 8 AND 255)*(1-a), \\\n \\ B%*a + (C% >> 16 AND 255)*(1-a)\n GCOL 1\n LINE X%*2, Y%*2, X%*2, Y%*2\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "void draw_line_antialias(\n image img,\n unsigned int x0, unsigned int y0,\n unsigned int x1, unsigned int y1,\n color_component r,\n color_component g,\n color_component b );\n", "language": "C" }, { "code": "inline void _dla_changebrightness(rgb_color_p from,\n\t\t\t\t rgb_color_p to, float br)\n{\n if ( br > 1.0 ) br = 1.0;\n /* linear... Maybe something more complex could give better look */\n to->red = br * (float)from->red;\n to->green = br * (float)from->green;\n to->blue = br * (float)from->blue;\n}\n\n#define plot_(X,Y,D) do{ rgb_color f_;\t\t\t\t\\\n f_.red = r; f_.green = g; f_.blue = b;\t\t\t\\\n _dla_plot(img, (X), (Y), &f_, (D)) ; }while(0)\n\ninline void _dla_plot(image img, int x, int y, rgb_color_p col, float br)\n{\n rgb_color oc;\n _dla_changebrightness(col, &oc, br);\n put_pixel_clip(img, x, y, oc.red, oc.green, oc.blue);\n}\n\n#define ipart_(X) ((int)(X))\n#define round_(X) ((int)(((double)(X))+0.5))\n#define fpart_(X) (((double)(X))-(double)ipart_(X))\n#define rfpart_(X) (1.0-fpart_(X))\n\n#define swap_(a, b) do{ __typeof__(a) tmp; tmp = a; a = b; b = tmp; }while(0)\nvoid draw_line_antialias(\n image img,\n unsigned int x1, unsigned int y1,\n unsigned int x2, unsigned int y2,\n color_component r,\n color_component g,\n color_component b )\n{\n double dx = (double)x2 - (double)x1;\n double dy = (double)y2 - (double)y1;\n if ( fabs(dx) > fabs(dy) ) {\n if ( x2 < x1 ) {\n swap_(x1, x2);\n swap_(y1, y2);\n }\n double gradient = dy / dx;\n double xend = round_(x1);\n double yend = y1 + gradient*(xend - x1);\n double xgap = rfpart_(x1 + 0.5);\n int xpxl1 = xend;\n int ypxl1 = ipart_(yend);\n plot_(xpxl1, ypxl1, rfpart_(yend)*xgap);\n plot_(xpxl1, ypxl1+1, fpart_(yend)*xgap);\n double intery = yend + gradient;\n\n xend = round_(x2);\n yend = y2 + gradient*(xend - x2);\n xgap = fpart_(x2+0.5);\n int xpxl2 = xend;\n int ypxl2 = ipart_(yend);\n plot_(xpxl2, ypxl2, rfpart_(yend) * xgap);\n plot_(xpxl2, ypxl2 + 1, fpart_(yend) * xgap);\n\n int x;\n for(x=xpxl1+1; x < xpxl2; x++) {\n plot_(x, ipart_(intery), rfpart_(intery));\n plot_(x, ipart_(intery) + 1, fpart_(intery));\n intery += gradient;\n }\n } else {\n if ( y2 < y1 ) {\n swap_(x1, x2);\n swap_(y1, y2);\n }\n double gradient = dx / dy;\n double yend = round_(y1);\n double xend = x1 + gradient*(yend - y1);\n double ygap = rfpart_(y1 + 0.5);\n int ypxl1 = yend;\n int xpxl1 = ipart_(xend);\n plot_(xpxl1, ypxl1, rfpart_(xend)*ygap);\n plot_(xpxl1 + 1, ypxl1, fpart_(xend)*ygap);\n double interx = xend + gradient;\n\n yend = round_(y2);\n xend = x2 + gradient*(yend - y2);\n ygap = fpart_(y2+0.5);\n int ypxl2 = yend;\n int xpxl2 = ipart_(xend);\n plot_(xpxl2, ypxl2, rfpart_(xend) * ygap);\n plot_(xpxl2 + 1, ypxl2, fpart_(xend) * ygap);\n\n int y;\n for(y=ypxl1+1; y < ypxl2; y++) {\n plot_(ipart_(interx), y, rfpart_(interx));\n plot_(ipart_(interx) + 1, y, fpart_(interx));\n interx += gradient;\n }\n }\n}\n#undef swap_\n#undef plot_\n#undef ipart_\n#undef fpart_\n#undef round_\n#undef rfpart_\n", "language": "C" }, { "code": "#include <functional>\n#include <algorithm>\n#include <utility>\n\nvoid WuDrawLine(float x0, float y0, float x1, float y1,\n const std::function<void(int x, int y, float brightess)>& plot) {\n auto ipart = [](float x) -> int {return int(std::floor(x));};\n auto round = [](float x) -> float {return std::round(x);};\n auto fpart = [](float x) -> float {return x - std::floor(x);};\n auto rfpart = [=](float x) -> float {return 1 - fpart(x);};\n\n const bool steep = abs(y1 - y0) > abs(x1 - x0);\n if (steep) {\n std::swap(x0,y0);\n std::swap(x1,y1);\n }\n if (x0 > x1) {\n std::swap(x0,x1);\n std::swap(y0,y1);\n }\n\n const float dx = x1 - x0;\n const float dy = y1 - y0;\n const float gradient = (dx == 0) ? 1 : dy/dx;\n\n int xpx11;\n float intery;\n {\n const float xend = round(x0);\n const float yend = y0 + gradient * (xend - x0);\n const float xgap = rfpart(x0 + 0.5);\n xpx11 = int(xend);\n const int ypx11 = ipart(yend);\n if (steep) {\n plot(ypx11, xpx11, rfpart(yend) * xgap);\n plot(ypx11 + 1, xpx11, fpart(yend) * xgap);\n } else {\n plot(xpx11, ypx11, rfpart(yend) * xgap);\n plot(xpx11, ypx11 + 1, fpart(yend) * xgap);\n }\n intery = yend + gradient;\n }\n\n int xpx12;\n {\n const float xend = round(x1);\n const float yend = y1 + gradient * (xend - x1);\n const float xgap = rfpart(x1 + 0.5);\n xpx12 = int(xend);\n const int ypx12 = ipart(yend);\n if (steep) {\n plot(ypx12, xpx12, rfpart(yend) * xgap);\n plot(ypx12 + 1, xpx12, fpart(yend) * xgap);\n } else {\n plot(xpx12, ypx12, rfpart(yend) * xgap);\n plot(xpx12, ypx12 + 1, fpart(yend) * xgap);\n }\n }\n\n if (steep) {\n for (int x = xpx11 + 1; x < xpx12; x++) {\n plot(ipart(intery), x, rfpart(intery));\n plot(ipart(intery) + 1, x, fpart(intery));\n intery += gradient;\n }\n } else {\n for (int x = xpx11 + 1; x < xpx12; x++) {\n plot(x, ipart(intery), rfpart(intery));\n plot(x, ipart(intery) + 1, fpart(intery));\n intery += gradient;\n }\n }\n}\n", "language": "C++" }, { "code": "public class Line\n {\n private double x0, y0, x1, y1;\n private Color foreColor;\n private byte lineStyleMask;\n private int thickness;\n private float globalm;\n\n public Line(double x0, double y0, double x1, double y1, Color color, byte lineStyleMask, int thickness)\n {\n this.x0 = x0;\n this.y0 = y0;\n this.y1 = y1;\n this.x1 = x1;\n\n this.foreColor = color;\n\n this.lineStyleMask = lineStyleMask;\n\n this.thickness = thickness;\n\n }\n\n private void plot(Bitmap bitmap, double x, double y, double c)\n {\n int alpha = (int)(c * 255);\n if (alpha > 255) alpha = 255;\n if (alpha < 0) alpha = 0;\n Color color = Color.FromArgb(alpha, foreColor);\n if (BitmapDrawHelper.checkIfInside((int)x, (int)y, bitmap))\n {\n bitmap.SetPixel((int)x, (int)y, color);\n }\n }\n\n int ipart(double x) { return (int)x;}\n\n int round(double x) {return ipart(x+0.5);}\n\n double fpart(double x) {\n if(x<0) return (1-(x-Math.Floor(x)));\n return (x-Math.Floor(x));\n }\n\n double rfpart(double x) {\n return 1-fpart(x);\n }\n\n\n public void draw(Bitmap bitmap) {\n bool steep = Math.Abs(y1-y0)>Math.Abs(x1-x0);\n double temp;\n if(steep){\n temp=x0; x0=y0; y0=temp;\n temp=x1;x1=y1;y1=temp;\n }\n if(x0>x1){\n temp = x0;x0=x1;x1=temp;\n temp = y0;y0=y1;y1=temp;\n }\n\n double dx = x1-x0;\n double dy = y1-y0;\n double gradient = dy/dx;\n\n double xEnd = round(x0);\n double yEnd = y0+gradient*(xEnd-x0);\n double xGap = rfpart(x0+0.5);\n double xPixel1 = xEnd;\n double yPixel1 = ipart(yEnd);\n\n if(steep){\n plot(bitmap, yPixel1, xPixel1, rfpart(yEnd)*xGap);\n plot(bitmap, yPixel1+1, xPixel1, fpart(yEnd)*xGap);\n }else{\n plot(bitmap, xPixel1,yPixel1, rfpart(yEnd)*xGap);\n plot(bitmap, xPixel1, yPixel1+1, fpart(yEnd)*xGap);\n }\n double intery = yEnd+gradient;\n\n xEnd = round(x1);\n yEnd = y1+gradient*(xEnd-x1);\n xGap = fpart(x1+0.5);\n double xPixel2 = xEnd;\n double yPixel2 = ipart(yEnd);\n if(steep){\n plot(bitmap, yPixel2, xPixel2, rfpart(yEnd)*xGap);\n plot(bitmap, yPixel2+1, xPixel2, fpart(yEnd)*xGap);\n }else{\n plot(bitmap, xPixel2, yPixel2, rfpart(yEnd)*xGap);\n plot(bitmap, xPixel2, yPixel2+1, fpart(yEnd)*xGap);\n }\n\n if(steep){\n for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){\n plot(bitmap, ipart(intery), x, rfpart(intery));\n plot(bitmap, ipart(intery)+1, x, fpart(intery));\n intery+=gradient;\n }\n }else{\n for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){\n plot(bitmap, x,ipart(intery), rfpart(intery));\n plot(bitmap, x, ipart(intery)+1, fpart(intery));\n intery+=gradient;\n }\n }\n }\n }\n", "language": "C-sharp" }, { "code": ";;; The program outputs a transparency mask in plain Portable Gray Map\n;;; format.\n;;; -------------------------------------------------------------------\n\n(defstruct (drawing-surface\n (:constructor make-drawing-surface (u0 v0 u1 v1)))\n (u0 0 :type fixnum :read-only t)\n (v0 0 :type fixnum :read-only t)\n (u1 0 :type fixnum :read-only t)\n (v1 0 :type fixnum :read-only t)\n (pixels (make-array (* (- u1 u0 -1) (- v1 v0 -1))\n :element-type 'single-float\n :initial-element 0.0)))\n\n;;; In calls to drawing-surface-ref and drawing-surface-set, indices\n;;; outside the drawing_surface are allowed. Such indices are treated\n;;; as if you were trying to draw on the air.\n\n(defun drawing-surface-ref (s x y)\n (let ((u0 (drawing-surface-u0 s))\n (v0 (drawing-surface-v0 s))\n (u1 (drawing-surface-u1 s))\n (v1 (drawing-surface-v1 s)))\n (if (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (aref (drawing-surface-pixels s)\n (+ (- x u0) (* (- v1 y) (- u1 u0 -1))))\n 0.0))) ;; The Scheme for this returns +nan.0\n\n(defun drawing-surface-set (s x y opacity)\n (let ((u0 (drawing-surface-u0 s))\n (v0 (drawing-surface-v0 s))\n (u1 (drawing-surface-u1 s))\n (v1 (drawing-surface-v1 s)))\n (when (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (setf (aref (drawing-surface-pixels s)\n (+ (- x u0) (* (- v1 y) (- u1 u0 -1))))\n opacity))))\n\n(defun write-transparency-mask (s)\n ;; In the Scheme, I had the program write a Portable Arbitrary Map\n ;; with both a color and a transparency map. Here, by contrast, only\n ;; the transparency map will be output. It will be in plain Portable\n ;; Gray Map format, but representing opacities rather than\n ;; whitenesses. (Thus there will be no need for gamma corrections.)\n ;; See the pgm(5) manpage for a discussion of this use of PGM\n ;; format.\n (let* ((u0 (drawing-surface-u0 s))\n (v0 (drawing-surface-v0 s))\n (u1 (drawing-surface-u1 s))\n (v1 (drawing-surface-v1 s))\n (w (- u1 u0 -1))\n (h (- v1 v0 -1))\n (|(w * h) - 1| (1- (* w h)))\n (opacities (drawing-surface-pixels s)))\n ;; \"format\" is not standard in Scheme, although it is widely\n ;; implemented as an extension. However, in Common Lisp it is\n ;; standardized. So let us use it.\n (format t \"P2~%\")\n (format t \"# transparency map~%\")\n (format t \"~a ~a~%\" w h)\n (format t \"255~%\")\n (loop for i from 0 to |(w * h) - 1|\n do (let* ((opacity (aref opacities i))\n (byteval (round (* 255 opacity))))\n ;; Using \"plain\" PGM format avoids the issue of how to\n ;; write raw bytes. OTOH it makes the output file large\n ;; and slow to work with. (In the R7RS Scheme,\n ;; \"bytevectors\" provided an obvious way to write\n ;; bytes.)\n (princ byteval)\n (terpri)))))\n\n;;;-------------------------------------------------------------------\n\n(defun ipart (x) (floor x))\n(defun iround (x) (ipart (+ x 0.5)))\n(defun fpart (x) (nth-value 1 (floor x)))\n(defun rfpart (x) (- 1.0 (fpart x)))\n\n(defun plot-shallow (s x y opacity)\n (let ((combined-opacity\n (+ opacity (drawing-surface-ref s x y))))\n (drawing-surface-set s x y (min combined-opacity 1.0))))\n\n(defun plot-steep (s x y opacity)\n (plot-shallow s y x opacity))\n\n(defun drawln% (s x0 y0 x1 y1 plot)\n (let* ((dx (- x1 x0))\n (dy (- y1 y0))\n (gradient (if (zerop dx) 1.0 (/ dy dx)))\n\n ;; Handle the first endpoint.\n (xend (iround x0))\n (yend (+ y0 (* gradient (- xend x0))))\n (xgap (rfpart (+ x0 0.5)))\n (xpxl1 xend)\n (ypxl1 (ipart yend))\n (_ (funcall plot s xpxl1 ypxl1 (* (rfpart yend) xgap)))\n (_ (funcall plot s xpxl1 (1+ ypxl1) (* (fpart yend) xgap)))\n\n (first-y-intersection (+ yend gradient))\n\n ;; Handle the second endpoint.\n (xend (iround x1))\n (yend (+ y1 (* gradient (- xend x1))))\n (xgap (fpart (+ x1 0.5)))\n (xpxl2 xend)\n (ypxl2 (ipart yend))\n (_ (funcall plot s xpxl2 ypxl2 (* (rfpart yend) xgap)))\n (_ (funcall plot s xpxl2 (1+ ypxl2) (* (fpart yend) xgap))))\n\n ;; Loop over the rest of the points.\n (do ((x (+ xpxl1 1) (1+ x))\n (intery first-y-intersection (+ intery gradient)))\n ((= x xpxl2))\n (funcall plot s x (ipart intery) (rfpart intery))\n (funcall plot s x (1+ (ipart intery)) (fpart intery)))))\n\n(defun draw-line (s x0 y0 x1 y1)\n (let ((x0 (coerce x0 'single-float))\n (y0 (coerce y0 'single-float))\n (x1 (coerce x1 'single-float))\n (y1 (coerce y1 'single-float)))\n (let ((xdiff (abs (- x1 x0)))\n (ydiff (abs (- y1 y0))))\n (if (<= ydiff xdiff)\n (if (<= x0 x1)\n (drawln% s x0 y0 x1 y1 #'plot-shallow)\n (drawln% s x1 y1 x0 y0 #'plot-shallow))\n (if (<= y0 y1)\n (drawln% s y0 x0 y1 x1 #'plot-steep)\n (drawln% s y1 x1 y0 x0 #'plot-steep))))))\n\n;;;-------------------------------------------------------------------\n;;; Draw a catenary as the evolute of a tractrix. See\n;;; https://en.wikipedia.org/w/index.php?title=Tractrix&oldid=1143719802#Properties\n;;; See also https://archive.is/YfgXW\n\n(defvar u0 -399)\n(defvar v0 -199)\n(defvar u1 400)\n(defvar v1 600)\n\n(defvar s (make-drawing-surface u0 v0 u1 v1))\n\n\n(loop for i from -300 to 300 by 10\n for t_ = (/ i 100.0) ; Independent parameter.\n for x = (- t_ (tanh t_)) ; Parametric tractrix coordinates.\n for y = (/ (cosh t_)) ;\n for u = y ; Parametric normal vector.\n for v = (* y (sinh t_)) ;\n for x0 = (* 100.0 (- x (* 10.0 u))) ; Scaled for plotting.\n for y0 = (* 100.0 (- y (* 10.0 v)))\n for x1 = (* 100.0 (+ x (* 10.0 u)))\n for y1 = (* 100.0 (+ y (* 10.0 v)))\n do (draw-line s x0 y0 x1 y1))\n\n(write-transparency-mask s)\n\n;;;-------------------------------------------------------------------\n", "language": "Common-Lisp" }, { "code": "#!/bin/sh\n\nsbcl --script xiaolin_wu_line_algorithm.lisp > alpha.pgm\npamgradient black black darkblue darkblue 800 800 > bluegradient.pam\npamgradient red red magenta magenta 800 800 > redgradient.pam\npamcomp -alpha=alpha.pgm redgradient.pam bluegradient.pam | pamtopng > image.png\n", "language": "Common-Lisp" }, { "code": "import std.math, std.algorithm, grayscale_image;\n\n/// Plots anti-aliased line by Xiaolin Wu's line algorithm.\nvoid aaLine(Color)(ref Image!Color img,\n double x1, double y1,\n double x2, double y2,\n in Color color) pure nothrow @safe @nogc {\n // Straight translation of Wikipedia pseudocode.\n\n // std.math.round is not pure. **\n static double round(in double x) pure nothrow @safe @nogc {\n return floor(x + 0.5);\n }\n\n static double fpart(in double x) pure nothrow @safe @nogc {\n return x - x.floor;\n }\n\n static double rfpart(in double x) pure nothrow @safe @nogc {\n return 1 - fpart(x);\n }\n\n auto dx = x2 - x1;\n auto dy = y2 - y1;\n immutable ax = dx.abs;\n immutable ay = dy.abs;\n\n static Color mixColors(in Color c1, in Color c2, in double p)\n pure nothrow @safe @nogc {\n static if (is(Color == RGB))\n return Color(cast(ubyte)(c1.r * p + c2.r * (1 - p)),\n cast(ubyte)(c1.g * p + c2.g * (1 - p)),\n cast(ubyte)(c1.b * p + c2.b * (1 - p)));\n else\n // This doesn't work for every kind of Color.\n return Color(cast(ubyte)(c1 * p + c2 * (1 - p)));\n }\n\n // Plot function set here to handle the two cases of slope.\n void function(ref Image!Color, in int, in int, in double, in Color)\n pure nothrow @safe @nogc plot;\n\n if (ax < ay) {\n swap(x1, y1);\n swap(x2, y2);\n swap(dx, dy);\n //plot = (img, x, y, p, col) {\n plot = (ref img, x, y, p, col) {\n assert(p >= 0.0 && p <= 1.0);\n img[y, x] = mixColors(col, img[y, x], p);\n };\n } else {\n //plot = (img, x, y, p, col) {\n plot = (ref img, x, y, p, col) {\n assert(p >= 0.0 && p <= 1.0);\n img[x, y] = mixColors(col, img[x, y], p);\n };\n }\n\n if (x2 < x1) {\n swap(x1, x2);\n swap(y1, y2);\n }\n immutable gradient = dy / dx;\n\n // Handle first endpoint.\n auto xEnd = round(x1);\n auto yEnd = y1 + gradient * (xEnd - x1);\n auto xGap = rfpart(x1 + 0.5);\n // This will be used in the main loop.\n immutable xpxl1 = cast(int)xEnd;\n immutable ypxl1 = cast(int)yEnd.floor;\n plot(img, xpxl1, ypxl1, rfpart(yEnd) * xGap, color);\n plot(img, xpxl1, ypxl1 + 1, fpart(yEnd) * xGap, color);\n // First y-intersection for the main loop.\n auto yInter = yEnd + gradient;\n\n // Handle second endpoint.\n xEnd = round(x2);\n yEnd = y2 + gradient * (xEnd - x2);\n xGap = fpart(x2 + 0.5);\n // This will be used in the main loop.\n immutable xpxl2 = cast(int)xEnd;\n immutable ypxl2 = cast(int)yEnd.floor;\n plot(img, xpxl2, ypxl2, rfpart(yEnd) * xGap, color);\n plot(img, xpxl2, ypxl2 + 1, fpart(yEnd) * xGap, color);\n\n // Main loop.\n foreach (immutable x; xpxl1 + 1 .. xpxl2) {\n plot(img, x, cast(int)yInter.floor, rfpart(yInter), color);\n plot(img, x, cast(int)yInter.floor + 1, fpart(yInter), color);\n yInter += gradient;\n }\n}\n\nvoid main() {\n auto im1 = new Image!Gray(400, 300);\n im1.clear(Gray.white);\n im1.aaLine(7.4, 12.3, 307, 122.5, Gray.black);\n im1.aaLine(177.4, 12.3, 127, 222.5, Gray.black);\n im1.savePGM(\"xiaolin_lines1.pgm\");\n\n auto im2 = new Image!RGB(400, 300);\n im2.clear(RGB(0, 255, 0));\n immutable red = RGB(255, 0, 0);\n im2.aaLine(7.4, 12.3, 307, 122.5, red);\n im2.aaLine(177.4, 12.3, 127, 222.5, red);\n im2.savePPM6(\"xiaolin_lines2.ppm\");\n}\n", "language": "D" }, { "code": "program xiaolin_wu_line_algorithm\n use, intrinsic :: ieee_arithmetic\n implicit none\n\n type :: drawing_surface\n integer :: u0, v0, u1, v1\n real, allocatable :: pixels(:)\n end type drawing_surface\n\n interface\n subroutine point_plotter (s, x, y, opacity)\n import drawing_surface\n type(drawing_surface), intent(inout) :: s\n integer, intent(in) :: x, y\n real, intent(in) :: opacity\n end subroutine point_plotter\n end interface\n\n real, parameter :: pi = 4.0 * atan (1.0)\n\n integer, parameter :: u0 = -499\n integer, parameter :: v0 = -374\n integer, parameter :: u1 = 500\n integer, parameter :: v1 = 375\n\n real, parameter :: a = 200.0 ! Ellipse radius on x axis.\n real, parameter :: b = 350.0 ! Ellipse radius on y axis.\n\n type(drawing_surface) :: s\n integer :: i, step_size\n real :: t, c, d\n real :: x, y\n real :: xnext, ynext\n real :: u, v\n real :: rhs, ad, bc\n real :: x0, y0, x1, y1\n\n s = make_drawing_surface (u0, v0, u1, v1)\n\n ! Draw both an ellipse and the normals of that ellipse.\n step_size = 2\n do i = 0, 359, step_size\n ! Parametric representation of an ellipse.\n t = i * (pi / 180.0)\n c = cos (t)\n d = sin (t)\n x = a * c\n y = b * d\n\n ! Draw a piecewise linear approximation of the ellipse. The\n ! endpoints of the line segments will lie on the curve.\n xnext = a * cos ((i + step_size) * (pi / 180.0))\n ynext = b * sin ((i + step_size) * (pi / 180.0))\n call draw_line (s, x, y, xnext, ynext)\n\n ! The parametric equation of the normal:\n !\n ! (a * sin (t) * xnormal) - (b * cos (t) * ynormal)\n ! = (a**2 - b**2) * cos (t) * sin (t)\n !\n ! That is:\n !\n ! (a * d * xnormal) - (b * c * ynormal) = (a**2 - b**2) * c * d\n !\n rhs = (a**2 - b**2) * c * d\n ad = a * d\n bc = b * c\n if (abs (ad) < abs (bc)) then\n x0 = -1000.0\n y0 = ((ad * x0) - rhs) / bc\n x1 = 1000.0\n y1 = ((ad * x1) - rhs) / bc\n else\n y0 = -1000.0\n x0 = (rhs - (bc * y0)) / ad\n y1 = 1000.0\n x1 = (rhs - (bc * y1)) / ad\n end if\n\n call draw_line (s, x0, y0, x1, y1)\n end do\n\n call write_transparency_mask (s)\n\ncontains\n\n function make_drawing_surface (u0, v0, u1, v1) result (s)\n integer, intent(in) :: u0, v0, u1, v1\n type(drawing_surface) :: s\n\n integer :: w, h\n\n if (u1 < u0 .or. v1 < v0) error stop\n s%u0 = u0; s%v0 = v0\n s%u1 = u1; s%v1 = v1\n w = u1 - u0 + 1\n h = v1 - v0 + 1\n allocate (s%pixels(0:(w * h) - 1), source = 0.0)\n end function make_drawing_surface\n\n function drawing_surface_ref (s, x, y) result (c)\n type(drawing_surface), intent(in) :: s\n integer, intent(in) :: x, y\n real :: c\n\n ! In calls to drawing_surface_ref and drawing_surface_set, indices\n ! outside the drawing_surface are allowed. Such indices are\n ! treated as if you were trying to draw on the air.\n\n if (s%u0 <= x .and. x <= s%u1 .and. s%v0 <= y .and. y <= s%v1) then\n c = s%pixels((x - s%u0) + ((s%v1 - y) * (s%u1 - s%u0 + 1)))\n else\n c = ieee_value (s%pixels(0), ieee_quiet_nan)\n end if\n end function drawing_surface_ref\n\n subroutine drawing_surface_set (s, x, y, c)\n type(drawing_surface), intent(inout) :: s\n integer, intent(in) :: x, y\n real, intent(in) :: c\n\n ! In calls to drawing_surface_ref and drawing_surface_set, indices\n ! outside the drawing_surface are allowed. Such indices are\n ! treated as if you were trying to draw on the air.\n\n if (s%u0 <= x .and. x <= s%u1 .and. s%v0 <= y .and. y <= s%v1) then\n s%pixels((x - s%u0) + ((s%v1 - y) * (s%u1 - s%u0 + 1))) = c\n end if\n end subroutine drawing_surface_set\n\n subroutine write_transparency_mask (s)\n type(drawing_surface), intent(in) :: s\n\n ! Write a transparency mask, in plain (ASCII or EBCDIC) Portable\n ! Gray Map format, but representing opacities rather than\n ! whitenesses. (Thus there will be no need for gamma corrections.)\n ! See the pgm(5) manpage for a discussion of this use of PGM\n ! format.\n\n integer :: w, h\n integer :: i\n\n w = s%u1 - s%u0 + 1\n h = s%v1 - s%v0 + 1\n\n write (*, '(\"P2\")')\n write (*, '(\"# transparency mask\")')\n write (*, '(I0, 1X, I0)') w, h\n write (*, '(\"255\")')\n write (*, '(15I4)') (nint (255 * s%pixels(i)), i = 0, (w * h) - 1)\n end subroutine write_transparency_mask\n\n subroutine draw_line (s, x0, y0, x1, y1)\n type(drawing_surface), intent(inout) :: s\n real, intent(in) :: x0, y0, x1, y1\n\n real :: xdiff, ydiff\n\n xdiff = abs (x1 - x0)\n ydiff = abs (y1 - y0)\n if (ydiff <= xdiff) then\n if (x0 <= x1) then\n call drawln (s, x0, y0, x1, y1, plot_shallow)\n else\n call drawln (s, x1, y1, x0, y0, plot_shallow)\n end if\n else\n if (y0 <= y1) then\n call drawln (s, y0, x0, y1, x1, plot_steep)\n else\n call drawln (s, y1, x1, y0, x0, plot_steep)\n end if\n end if\n end subroutine draw_line\n\n subroutine drawln (s, x0, y0, x1, y1, plot)\n type(drawing_surface), intent(inout) :: s\n real, intent(in) :: x0, y0, x1, y1\n procedure(point_plotter) :: plot\n\n real :: dx, dy, gradient\n real :: yend, xgap\n real :: first_y_intersection, intery\n integer :: xend\n integer :: xpxl1, ypxl1\n integer :: xpxl2, ypxl2\n integer :: x\n\n dx = x1 - x0; dy = y1 - y0\n if (dx == 0.0) then\n gradient = 1.0\n else\n gradient = dy / dx\n end if\n\n ! Handle the first endpoint.\n xend = iround (x0)\n yend = y0 + (gradient * (xend - x0))\n xgap = rfpart (x0 + 0.5)\n xpxl1 = xend\n ypxl1 = ipart (yend)\n call plot (s, xpxl1, ypxl1, rfpart (yend) * xgap)\n call plot (s, xpxl1, ypxl1 + 1, fpart (yend) * xgap)\n\n first_y_intersection = yend + gradient\n\n ! Handle the second endpoint.\n xend = iround (x1)\n yend = y1 + (gradient * (xend - x1))\n xgap = fpart (x1 + 0.5)\n xpxl2 = xend\n ypxl2 = ipart (yend)\n call plot (s, xpxl2, ypxl2, (rfpart (yend) * xgap))\n call plot (s, xpxl2, ypxl2 + 1, fpart (yend) * xgap)\n\n ! Loop over the rest of the points.\n intery = first_y_intersection\n do x = xpxl1 + 1, xpxl2 - 1\n call plot (s, x, ipart (intery), rfpart (intery))\n call plot (s, x, ipart (intery) + 1, fpart (intery))\n intery = intery + gradient\n end do\n end subroutine drawln\n\n subroutine plot_shallow (s, x, y, opacity)\n type(drawing_surface), intent(inout) :: s\n integer, intent(in) :: x, y\n real, intent(in) :: opacity\n\n real :: combined_opacity\n\n ! Let us simply add opacities, up to the maximum of 1.0. You might\n ! wish to do something different, of course.\n combined_opacity = opacity + drawing_surface_ref (s, x, y)\n call drawing_surface_set (s, x, y, min (combined_opacity, 1.0))\n end subroutine plot_shallow\n\n subroutine plot_steep (s, x, y, opacity)\n type(drawing_surface), intent(inout) :: s\n integer, intent(in) :: x, y\n real, intent(in) :: opacity\n call plot_shallow (s, y, x, opacity)\n end subroutine plot_steep\n\n elemental function ipart (x) result (i)\n real, intent(in) :: x\n integer :: i\n i = floor (x)\n end function ipart\n\n elemental function iround (x) result (i)\n real, intent(in) :: x\n integer :: i\n i = ipart (x + 0.5)\n end function iround\n\n elemental function fpart (x) result (y)\n real, intent(in) :: x\n real :: y\n y = modulo (x, 1.0)\n end function fpart\n\n elemental function rfpart (x) result (y)\n real, intent(in) :: x\n real :: y\n y = 1.0 - fpart (x)\n end function rfpart\n\nend program xiaolin_wu_line_algorithm\n", "language": "Fortran" }, { "code": "#!/bin/sh\n\n# Using the optimizer, even at low settings, avoids trampolines and\n# executable stacks.\ngfortran -std=f2018 -g -O1 xiaolin_wu_line_algorithm.f90\n\n./a.out > alpha.pgm\nppmpat -anticamo -randomseed=36 1000 750 | pambrighten -value=-60 -saturation=50 > fg.pam\nppmpat -poles -randomseed=57 1000 750 | pambrighten -value=+200 -saturation=-80 > bg.pam\npamcomp -alpha=alpha.pgm fg.pam bg.pam | pamtopng > image.png\n", "language": "Fortran" }, { "code": "' version 21-06-2015\n' compile with: fbc -s console or fbc -s gui\n' Xiaolin Wu’s line-drawing algorithm\n'shared var and macro's\n\nDim Shared As UInteger wu_color\n\n#Macro ipart(x)\nInt(x) ' integer part\n#EndMacro\n\n#Macro round(x)\nInt((x) + .5) ' round off\n#EndMacro\n\n#Macro fpart(x)\nFrac(x) ' fractional part\n#EndMacro\n\n#Macro rfpart(x)\n' 1 - Frac(x) ' seems to give problems for very small x\nIIf(1 - Frac(x) >= 1, 1, 1 - Frac(x))\n#EndMacro\n\n#Macro plot(x, y , c)\n' use the alpha channel to set the amount of color\nPSet(x,y), wu_color Or (Int(c * 255)) Shl 24\n#EndMacro\n\nSub drawline(x0 As Single, y0 As Single, x1 As Single, y1 As Single,_\n col As UInteger = RGB(255,255,255))\n\n wu_color = col And &HFFFFFF ' strip off the alpha channel information\n\n Dim As Single gradient\n Dim As Single xend, yend, xgap, intery\n Dim As UInteger xpxl1, ypxl1, xpxl2, ypxl2, x\n Dim As Integer steep = Abs(y1 - y0) > Abs(x1 - x0) ' boolean\n\n If steep Then\n Swap x0, y0\n Swap x1, y1\n End If\n\n If x0 > x1 Then\n Swap x0, x1\n Swap y0, y1\n End If\n\n gradient = (y1 - y0) / (x1 - x0)\n\n ' first endpoint\n ' xend = round(x0)\n xend = ipart(x0)\n yend = y0 + gradient * (xend - x0)\n xgap = rfpart(x0 + .5)\n xpxl1 = xend ' this will be used in the main loop\n ypxl1 = ipart(yend)\n If steep Then\n plot(ypxl1, xpxl1, rfpart(yend) * xgap)\n plot(ypxl1+1, xpxl1, fpart(yend) * xgap)\n Else\n plot(xpxl1, ypxl1, rfpart(yend) * xgap)\n plot(xpxl1, ypxl1+1, fpart(yend) * xgap)\n End If\n intery = yend + gradient ' first y-intersecction for the main loop\n\n ' handle second endpoint\n ' xend = round(x1)\n xend = ipart(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = fpart(x1 + .5)\n xpxl2 = xend ' this will be used in the main loop\n ypxl2 = ipart(yend)\n If steep Then\n plot(ypxl2, xpxl2, rfpart(yend) * xgap)\n plot(ypxl2+1, xpxl2, fpart(yend) * xgap)\n Else\n plot(xpxl2, ypxl2, rfpart(yend) * xgap)\n plot(xpxl2, ypxl2+1, fpart(yend) * xgap)\n End If\n\n ' main loop\n If steep Then\n For x = xpxl1 + 1 To xpxl2 - 1\n plot(ipart(intery), x, rfpart(intery))\n plot(ipart(intery)+1, x, fpart(intery))\n intery = intery + gradient\n Next\n Else\n For x = xpxl1 + 1 To xpxl2 - 1\n plot(x, ipart(intery), rfpart(intery))\n plot(x, ipart(intery)+1, fpart(intery))\n intery = intery + gradient\n Next\n End If\n\nEnd Sub\n\n' ------=< MAIN >=------\n\n#Define W_ 600\n#Define H_ 600\n\n#Include Once \"fbgfx.bi\" ' needed setting the screen attributes\nDim As Integer i\nDim As String fname = __FILE__\n\nScreenRes W_, H_, 32,, FB.GFX_ALPHA_PRIMITIVES\n\nRandomize Timer\n\nFor i = 0 To H_ Step H_\\30\n drawline(0, 0, W_, i, Int(Rnd * &HFFFFFF))\nNext\n\nFor i = 0 To W_ Step W_\\30\n drawline(0, 0, i, H_, Int(Rnd * &HFFFFFF))\nNext\n\ni = InStr(fname,\".bas\")\nfname = Left(fname, Len(fname)-i+1)\nWindowTitle fname + \" hit any key to end program\"\n\nWhile Inkey <> \"\" : Wend\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package raster\n\nimport \"math\"\n\nfunc ipart(x float64) float64 {\n return math.Floor(x)\n}\n\nfunc round(x float64) float64 {\n return ipart(x + .5)\n}\n\nfunc fpart(x float64) float64 {\n return x - ipart(x)\n}\n\nfunc rfpart(x float64) float64 {\n return 1 - fpart(x)\n}\n\n// AaLine plots anti-aliased line by Xiaolin Wu's line algorithm.\nfunc (g *Grmap) AaLine(x1, y1, x2, y2 float64) {\n // straight translation of WP pseudocode\n dx := x2 - x1\n dy := y2 - y1\n ax := dx\n if ax < 0 {\n ax = -ax\n }\n ay := dy\n if ay < 0 {\n ay = -ay\n }\n // plot function set here to handle the two cases of slope\n var plot func(int, int, float64)\n if ax < ay {\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n dx, dy = dy, dx\n plot = func(x, y int, c float64) {\n g.SetPx(y, x, uint16(c*math.MaxUint16))\n }\n } else {\n plot = func(x, y int, c float64) {\n g.SetPx(x, y, uint16(c*math.MaxUint16))\n }\n }\n if x2 < x1 {\n x1, x2 = x2, x1\n y1, y2 = y2, y1\n }\n gradient := dy / dx\n\n // handle first endpoint\n xend := round(x1)\n yend := y1 + gradient*(xend-x1)\n xgap := rfpart(x1 + .5)\n xpxl1 := int(xend) // this will be used in the main loop\n ypxl1 := int(ipart(yend))\n plot(xpxl1, ypxl1, rfpart(yend)*xgap)\n plot(xpxl1, ypxl1+1, fpart(yend)*xgap)\n intery := yend + gradient // first y-intersection for the main loop\n\n // handle second endpoint\n xend = round(x2)\n yend = y2 + gradient*(xend-x2)\n xgap = fpart(x2 + 0.5)\n xpxl2 := int(xend) // this will be used in the main loop\n ypxl2 := int(ipart(yend))\n plot(xpxl2, ypxl2, rfpart(yend)*xgap)\n plot(xpxl2, ypxl2+1, fpart(yend)*xgap)\n\n // main loop\n for x := xpxl1 + 1; x <= xpxl2-1; x++ {\n plot(x, int(ipart(intery)), rfpart(intery))\n plot(x, int(ipart(intery))+1, fpart(intery))\n intery = intery + gradient\n }\n}\n", "language": "Go" }, { "code": "package main\n\n// Files required to build supporting package raster are found in:\n// * This task (immediately above)\n// * Bitmap\n// * Grayscale image\n// * Write a PPM file\n\nimport \"raster\"\n\nfunc main() {\n g := raster.NewGrmap(400, 300)\n g.AaLine(7.4, 12.3, 307, 122.5)\n g.AaLine(177.4, 12.3, 127, 222.5)\n g.Bitmap().WritePpmFile(\"wu.ppm\")\n}\n", "language": "Go" }, { "code": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main (main) where\n\nimport Codec.Picture (writePng)\nimport Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel)\nimport Control.Monad (void)\nimport Control.Monad.Primitive (PrimMonad, PrimState)\nimport Data.Foldable (foldlM)\n\ntype MImage m px = MutableImage (PrimState m) px\n\n-- | Create an image given a function to apply to an empty mutable image\nwithMutableImage\n :: (Pixel px, PrimMonad m)\n => Int -- ^ image width\n -> Int -- ^ image height\n -> px -- ^ background colour\n -> (MImage m px -> m ()) -- ^ function to apply to mutable image\n -> m (Image px) -- ^ action\nwithMutableImage w h px f = createMutableImage w h px >>= \\m -> f m >> unsafeFreezeImage m\n\n-- | Plot a pixel at the given point in the given colour\nplot\n :: (Pixel px, PrimMonad m)\n => MImage m px -- ^ mutable image\n -> Int -- ^ x-coordinate of point\n -> Int -- ^ y-coordinate of point\n -> px -- ^ colour\n -> m () -- ^ action\nplot = writePixel\n\n-- | Draw an antialiased line from first point to second point in given colour\ndrawAntialiasedLine\n :: forall px m . (Pixel px, PrimMonad m)\n => MImage m px -- ^ mutable image\n -> Int -- ^ x-coordinate of first point\n -> Int -- ^ y-coordinate of first point\n -> Int -- ^ x-coordinate of second point\n -> Int -- ^ y-coordinate of second point\n -> (Double -> px) -- ^ colour generator function\n -> m () -- ^ action\ndrawAntialiasedLine m p1x p1y p2x p2y colour = do\n let steep = abs (p2y - p1y) > abs (p2x - p1x)\n ((p3x, p4x), (p3y, p4y)) = swapIf steep ((p1x, p2x), (p1y, p2y))\n ((ax, ay), (bx, by)) = swapIf (p3x > p4x) ((p3x, p3y), (p4x, p4y))\n dx = bx - ax\n dy = by - ay\n gradient = if dx == 0 then 1.0 else fromIntegral dy / fromIntegral dx\n\n -- handle first endpoint\n let xpxl1 = ax -- round (fromIntegral ax)\n yend1 = fromIntegral ay + gradient * fromIntegral (xpxl1 - ax)\n xgap1 = rfpart (fromIntegral ax + 0.5)\n endpoint steep xpxl1 yend1 xgap1\n\n -- handle second endpoint\n let xpxl2 = bx -- round (fromIntegral bx)\n yend2 = fromIntegral by + gradient * fromIntegral (xpxl2 - bx)\n xgap2 = fpart (fromIntegral bx + 0.5)\n endpoint steep xpxl2 yend2 xgap2\n\n -- main loop\n let intery = yend1 + gradient\n void $ if steep\n then foldlM (\\i x -> do\n plot m (ipart i) x (colour (rfpart i))\n plot m (ipart i + 1) x (colour (fpart i))\n pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1]\n else foldlM (\\i x -> do\n plot m x (ipart i) (colour (rfpart i))\n plot m x (ipart i + 1) (colour (fpart i))\n pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1]\n\n where\n endpoint :: Bool -> Int -> Double -> Double -> m ()\n endpoint True xpxl yend xgap = do\n plot m ypxl xpxl (colour (rfpart yend * xgap))\n plot m (ypxl + 1) xpxl (colour (fpart yend * xgap))\n where ypxl = ipart yend\n endpoint False xpxl yend xgap = do\n plot m xpxl ypxl (colour (rfpart yend * xgap))\n plot m xpxl (ypxl + 1) (colour (fpart yend * xgap))\n where ypxl = ipart yend\n\nswapIf :: Bool -> (a, a) -> (a, a)\nswapIf False p = p\nswapIf True (x, y) = (y, x)\n\nipart :: Double -> Int\nipart = truncate\n\nfpart :: Double -> Double\nfpart x\n | x > 0 = x - temp\n | otherwise = x - (temp + 1)\n where temp = fromIntegral (ipart x)\n\nrfpart :: Double -> Double\nrfpart x = 1 - fpart x\n\nmain :: IO ()\nmain = do\n -- We start and end the line with sufficient clearance from the edge of the\n -- image to be able to see the endpoints\n img <- withMutableImage 640 480 (PixelRGB8 0 0 0) $ \\m@(MutableImage w h _) ->\n drawAntialiasedLine m 2 2 (w - 2) (h - 2)\n (\\brightness -> let level = round (brightness * 255) in PixelRGB8 level level level)\n\n -- Write it out to a file on disc\n writePng \"xiaolin-wu-algorithm.png\" img\n", "language": "Haskell" }, { "code": "link graphics\n\n$define YES 1\n$define NO &null\n\nprocedure main ()\n local width, height\n local done, w, event\n local x1, y1, x2, y2, press_is_active\n\n width := 640\n height := 480\n\n w := WOpen (\"size=\" || width || \",\" || height, \"bg=white\") |\n stop (\"failed to open a window\")\n\n press_is_active := NO\n done := NO\n while /done do\n {\n if *(Pending (w)) ~= 0 then\n {\n event := Event (w)\n case event of\n {\n QuitEvents () : done := YES\n &lpress :\n {\n if /press_is_active then\n {\n x1 := &x; y1 := &y\n press_is_active := YES\n }\n else\n {\n x2 := &x; y2 := &y\n draw_line (w, x1, y1, x2, y2)\n press_is_active := NO\n }\n }\n }\n }\n }\n\n # GIF is the only format \"regular\" Icon is documented to be able to\n # write on all platforms. (Icon used to run on, for instance, 16-bit\n # MSDOS boxes.)\n WriteImage (w, \"xiaolin_wu_line_algorithm_Arizona.gif\") |\n stop (\"failed to write a GIF\")\nend\n\nprocedure draw_line (w, x0, y0, x1, y1)\n local steep\n local dx, dy, gradient\n local xend, yend, xgap, intery\n local xpxl1, ypxl1\n local xpxl2, ypxl2\n local x\n\n x0 := real (x0)\n y0 := real (y0)\n x1 := real (x1)\n y1 := real (y1)\n\n # In Icon, comparisons DO NOT return boolean values! They either\n # SUCCEED or they FAIL. Thus the need for an \"if-then-else\" here.\n steep := (if abs (y1 - y0) > abs (x1 - x0) then YES else NO)\n\n if \\steep then { x0 :=: y0; x1 :=: y1 }\n if x0 > x1 then { x0 :=: x1; y0 :=: y1 }\n dx := x1 - x0; dy := y1 - y0\n gradient := (if dx = 0 then 1.0 else dy / dx)\n\n # Handle the first endpoint.\n xend := round (x0); yend := y0 + (gradient * (xend - x0))\n xgap := rfpart (x0 + 0.5)\n xpxl1 := xend; ypxl1 := ipart (yend)\n if \\steep then\n {\n plot (w, ypxl1, xpxl1, rfpart (yend) * xgap)\n plot (w, ypxl1 + 1, xpxl1, fpart(yend) * xgap)\n }\n else\n {\n plot (w, xpxl1, ypxl1, rfpart (yend) * xgap)\n plot (w, xpxl1, ypxl1 + 1, fpart (yend) * xgap)\n }\n\n # The first y-intersection.\n intery := yend + gradient\n\n # Handle the second endpoint.\n xend := round (x1); yend := y1 + (gradient * (xend - x1))\n xgap := fpart (x1 + 0.5)\n xpxl2 := xend; ypxl2 := ipart (yend)\n if \\steep then\n {\n plot (w, ypxl2, xpxl2, rfpart (yend) * xgap)\n plot (w, ypxl2 + 1, xpxl2, fpart (yend) * xgap)\n }\n else\n {\n plot (w, xpxl2, ypxl2, rfpart (yend) * xgap)\n plot (w, xpxl2, ypxl2 + 1, fpart (yend) * xgap)\n }\n\n if \\steep then\n every x := xpxl1 + 1 to xpxl2 - 1 do\n {\n plot (w, ipart (intery), x, rfpart (intery))\n plot (w, ipart (intery) + 1, x, fpart (intery))\n intery := intery + gradient\n }\n else\n every x := xpxl1 + 1 to xpxl2 - 1 do\n {\n plot(w, x, ipart (intery), rfpart (intery))\n plot(w, x, ipart (intery) + 1, fpart (intery))\n intery := intery + gradient\n }\n\n return\nend\n\nprocedure plot (w, x, y, c)\n # In Object Icon, one can vary the opacity. But not in \"regular\"\n # Icon. Here we vary, instead, the shade of gray.\n c := round ((1.0 - c) * 65535)\n Fg (w, c || \",\" || c || \",\" || c)\n DrawPoint (w, x, y)\n return\nend\n\nprocedure ipart (x)\n local i\n i := integer (x)\n return (if i = x then i else if x < 0 then i - 1 else i)\nend\n\nprocedure round (x)\n return ipart (x + 0.5)\nend\n\nprocedure fpart (x)\n return x - ipart (x)\nend\n\nprocedure rfpart (x)\n return 1.0 - fpart (x)\nend\n\n# Unlike Object Icon, \"regular\" Icon has no \"abs\" built-in.\nprocedure abs (x)\n return (if x < 0 then -x else x)\nend\n", "language": "Icon" }, { "code": "load'gl2'\ncoinsert'jgl2'\n\ndrawpt=:4 :0\"0 1\n glrgb <.(-.x)*255 255 255\n glpixel y\n)\n\ndrawLine=:3 :0 NB. drawline x1,y1,x2,y2\n pts=. 2 2$y\n isreversed=. </ |d=. -~/pts\n r=. |.^:isreversed\"1\n pts=. /:~ pts \\:\"1 |d\n gradient=. %~/ (\\:|)d\n\n 'x y'=. |:pts\n xend=. <.0.5+ x\n yend=. y + gradient* xend-x\n xgap=. -.1|x+0.5\n\n n=. i. >: -~/ xend\n 'xlist ylist'=. (n*/~1,gradient) + ({.xend),({.yend)\n weights=. ((2&}.,~ xgap*2&{.)&.(_1&|.) (,.~-.) 1|ylist)\n weights (drawpt r)\"1 2 (,:+&0 1)\"1 xlist,.<.ylist\n)\n", "language": "J" }, { "code": " wd'pc win closeok; xywh 0 0 300 200;cc g isigraph; pas 0 0; pshow;' NB. J6 or earlier\n wd'pc win closeok; minwh 600 400;cc g isidraw flush; pshow;' NB. J802 or later\n glpaint glclear ''\n glpaint drawLine 10 10 590 390\n", "language": "J" }, { "code": "import java.awt.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class XiaolinWu extends JPanel {\n\n public XiaolinWu() {\n Dimension dim = new Dimension(640, 640);\n setPreferredSize(dim);\n setBackground(Color.white);\n }\n\n void plot(Graphics2D g, double x, double y, double c) {\n g.setColor(new Color(0f, 0f, 0f, (float)c));\n g.fillOval((int) x, (int) y, 2, 2);\n }\n\n int ipart(double x) {\n return (int) x;\n }\n\n double fpart(double x) {\n return x - floor(x);\n }\n\n double rfpart(double x) {\n return 1.0 - fpart(x);\n }\n\n void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) {\n\n boolean steep = abs(y1 - y0) > abs(x1 - x0);\n if (steep)\n drawLine(g, y0, x0, y1, x1);\n\n if (x0 > x1)\n drawLine(g, x1, y1, x0, y0);\n\n double dx = x1 - x0;\n double dy = y1 - y0;\n double gradient = dy / dx;\n\n // handle first endpoint\n double xend = round(x0);\n double yend = y0 + gradient * (xend - x0);\n double xgap = rfpart(x0 + 0.5);\n double xpxl1 = xend; // this will be used in the main loop\n double ypxl1 = ipart(yend);\n\n if (steep) {\n plot(g, ypxl1, xpxl1, rfpart(yend) * xgap);\n plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap);\n } else {\n plot(g, xpxl1, ypxl1, rfpart(yend) * xgap);\n plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap);\n }\n\n // first y-intersection for the main loop\n double intery = yend + gradient;\n\n // handle second endpoint\n xend = round(x1);\n yend = y1 + gradient * (xend - x1);\n xgap = fpart(x1 + 0.5);\n double xpxl2 = xend; // this will be used in the main loop\n double ypxl2 = ipart(yend);\n\n if (steep) {\n plot(g, ypxl2, xpxl2, rfpart(yend) * xgap);\n plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap);\n } else {\n plot(g, xpxl2, ypxl2, rfpart(yend) * xgap);\n plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap);\n }\n\n // main loop\n for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) {\n if (steep) {\n plot(g, ipart(intery), x, rfpart(intery));\n plot(g, ipart(intery) + 1, x, fpart(intery));\n } else {\n plot(g, x, ipart(intery), rfpart(intery));\n plot(g, x, ipart(intery) + 1, fpart(intery));\n }\n intery = intery + gradient;\n }\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n\n drawLine(g, 550, 170, 50, 435);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Xiaolin Wu's line algorithm\");\n f.setResizable(false);\n f.add(new XiaolinWu(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}\n", "language": "Java" }, { "code": "using Images\n\nfpart(x) = mod(x, one(x))\nrfpart(x) = one(x) - fpart(x)\n\nfunction drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer)\n steep = abs(y1 - y0) > abs(x1 - x0)\n\n if steep\n x0, y0 = y0, x0\n x1, y1 = y1, x1\n end\n if x0 > x1\n x0, x1 = x1, x0\n y0, y1 = y1, y0\n end\n\n dx = x1 - x0\n dy = y1 - y0\n grad = dy / dx\n\n if iszero(dx)\n grad = oftype(grad, 1.0)\n end\n\n # handle first endpoint\n xend = round(Int, x0)\n yend = y0 + grad * (xend - x0)\n xgap = rfpart(x0 + 0.5)\n xpxl1 = xend\n ypxl1 = floor(Int, yend)\n\n if steep\n img[ypxl1, xpxl1] = rfpart(yend) * xgap\n img[ypxl1+1, xpxl1] = fpart(yend) * xgap\n else\n img[xpxl1, ypxl1 ] = rfpart(yend) * xgap\n img[xpxl1, ypxl1+1] = fpart(yend) * xgap\n end\n intery = yend + grad # first y-intersection for the main loop\n\n # handle second endpoint\n xend = round(Int, x1)\n yend = y1 + grad * (xend - x1)\n xgap = fpart(x1 + 0.5)\n xpxl2 = xend\n ypxl2 = floor(Int, yend)\n if steep\n img[ypxl2, xpxl2] = rfpart(yend) * xgap\n img[ypxl2+1, xpxl2] = fpart(yend) * xgap\n else\n img[xpxl2, ypxl2 ] = rfpart(yend) * xgap\n img[xpxl2, ypxl2+1] = fpart(yend) * xgap\n end\n\n # main loop\n if steep\n for x in xpxl1+1:xpxl2-1\n img[floor(Int, intery), x] = rfpart(intery)\n img[floor(Int, intery)+1, x] = fpart(intery)\n intery += grad\n end\n else\n for x in xpxl1+1:xpxl2-1\n img[x, floor(Int, intery) ] = rfpart(intery)\n img[x, floor(Int, intery)+1] = fpart(intery)\n intery += grad\n end\n end\n\n return img\nend\n\nimg = fill(Gray(1.0N0f8), 250, 250);\ndrawline!(img, 8, 8, 192, 154)\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.awt.*\nimport javax.swing.*\n\nclass XiaolinWu: JPanel() {\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n }\n\n private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) {\n g.color = Color(0f, 0f, 0f, c.toFloat())\n g.fillOval(x.toInt(), y.toInt(), 2, 2)\n }\n\n private fun ipart(x: Double) = x.toInt()\n\n private fun fpart(x: Double) = x - Math.floor(x)\n\n private fun rfpart(x: Double) = 1.0 - fpart(x)\n\n private fun drawLine(g: Graphics2D, x0: Double, y0: Double, x1: Double, y1: Double) {\n val steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)\n if (steep) drawLine(g, y0, x0, y1, x1)\n if (x0 > x1) drawLine(g, x1, y1, x0, y0)\n\n val dx = x1 - x0\n val dy = y1 - y0\n val gradient = dy / dx\n\n // handle first endpoint\n var xend = Math.round(x0).toDouble()\n var yend = y0 + gradient * (xend - x0)\n var xgap = rfpart(x0 + 0.5)\n val xpxl1 = xend // this will be used in the main loop\n val ypxl1 = ipart(yend).toDouble()\n\n if (steep) {\n plot(g, ypxl1, xpxl1, rfpart(yend) * xgap)\n plot(g, ypxl1 + 1.0, xpxl1, fpart(yend) * xgap)\n }\n else {\n plot(g, xpxl1, ypxl1, rfpart(yend) * xgap)\n plot(g, xpxl1, ypxl1 + 1.0, fpart(yend) * xgap)\n }\n\n // first y-intersection for the main loop\n var intery = yend + gradient\n\n // handle second endpoint\n xend = Math.round(x1).toDouble()\n yend = y1 + gradient * (xend - x1)\n xgap = fpart(x1 + 0.5)\n val xpxl2 = xend // this will be used in the main loop\n val ypxl2 = ipart(yend).toDouble()\n\n if (steep) {\n plot(g, ypxl2, xpxl2, rfpart(yend) * xgap)\n plot(g, ypxl2 + 1.0, xpxl2, fpart(yend) * xgap)\n }\n else {\n plot(g, xpxl2, ypxl2, rfpart(yend) * xgap)\n plot(g, xpxl2, ypxl2 + 1.0, fpart(yend) * xgap)\n }\n\n // main loop\n var x = xpxl1 + 1.0\n while (x <= xpxl2 - 1) {\n if (steep) {\n plot(g, ipart(intery).toDouble(), x, rfpart(intery))\n plot(g, ipart(intery).toDouble() + 1.0, x, fpart(intery))\n }\n else {\n plot(g, x, ipart(intery).toDouble(), rfpart(intery))\n plot(g, x, ipart(intery).toDouble() + 1.0, fpart(intery))\n }\n intery += gradient\n x++\n }\n }\n\n override protected fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n drawLine(g, 550.0, 170.0, 50.0, 435.0)\n }\n}\n\nfun main(args: Array<String>) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Xiaolin Wu's line algorithm\"\n f.isResizable = false\n f.add(XiaolinWu(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}\n", "language": "Kotlin" }, { "code": "NoMainWin\nWindowWidth = 270\nWindowHeight = 290\nUpperLeftX=int((DisplayWidth-WindowWidth)/2)\nUpperLeftY=int((DisplayHeight-WindowHeight)/2)\n\nGlobal variablesInitialized : variablesInitialized = 0\nGlobal BackColor$ : BackColor$ = \"0 0 0\"\n' BackColor$ = \"255 255 255\"\n 'now, right click randomizes BG\nGlobal size : size = 1'4\nglobal mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1\n\n'StyleBits #main.gbox, 0, _WS_BORDER, 0, 0\nGraphicBox #main.gbox, 0, 0, 253, 252\n\nOpen \"Click Twice to Form Line\" For Window As #main\nPrint #main, \"TrapClose quit\"\nPrint #main.gbox, \"Down; Color Black\"\nPrint #main.gbox, \"Down; fill \";BackColor$\nPrint #main.gbox, \"When leftButtonUp gBoxClick\"\nPrint #main.gbox, \"When rightButtonUp RandomBG\"\nPrint #main.gbox, \"Size \"; size\n\nresult = drawAntiAliasedLine(126.5, 0, 126.5, 252, \"255 0 0\")\nresult = drawAntiAliasedLine(0, 126, 253, 126, \"255 0 0\")\nresult = drawAntiAliasedLine(0, 0, 253, 252, \"255 0 0\")\nresult = drawAntiAliasedLine(253, 0, 0, 252, \"255 0 0\")\nWait\n\n\n Sub quit handle$\n Close #main\n End\n End Sub\n\nsub RandomBG handle$, MouseX, MouseY\n BackColor$ = int(rnd(1)*256);\" \";int(rnd(1)*256);\" \";int(rnd(1)*256)\n Print #main.gbox, \"CLS; fill \";BackColor$\n variablesInitialized = 0\nend sub\n\n Sub gBoxClick handle$, MouseX, MouseY\n 'We will use the mousepoints \"struct\" to hold the values\n 'that way they are retained between subroutine calls\n If variablesInitialized = 0 Then\n Print #main.gbox, \"CLS; fill \";BackColor$\n mousepoints.mouseX0 = MouseX\n mousepoints.mouseY0 = MouseY\n variablesInitialized = 1\n Else\n If variablesInitialized = 1 Then\n mousepoints.mouseX1 = MouseX\n mousepoints.mouseY1 = MouseY\n variablesInitialized = 0\n result = drawAntiAliasedLine(mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1, \"255 0 0\")\n End If\n End If\n End Sub\n\n Function Swap(Byref a,Byref b)\n aTemp = b\n b = a\n a = aTemp\n End Function\n\n Function RoundtoInt(val)\n RoundtoInt = Int(val + 0.5)\n End Function\n\n Function PlotAntiAliased(x, y, RGB$, b, steep)\n\n RGB$ = Int(Val(Word$(BackColor$, 1))*(1-b) + Val(Word$(RGB$, 1)) * b) ; \" \" ; _\n Int(Val(Word$(BackColor$, 2))*(1-b) + Val(Word$(RGB$, 3)) * b) ; \" \" ; _\n Int(Val(Word$(BackColor$, 3))*(1-b) + Val(Word$(RGB$, 2)) * b)\n\n if steep then 'x and y reversed\n Print #main.gbox, \"Down; Color \" + RGB$ + \"; Set \" + str$(y) + \" \" + str$(x)\n else\n Print #main.gbox, \"Down; Color \" + RGB$ + \"; Set \" + str$(x) + \" \" + str$(y)\n end if\n End Function\n\n Function fracPart(x)\n fracPart = (x Mod 1)\n End function\n\n Function invFracPart(x)\n invFracPart = (1 - fracPart(x))\n End Function\n\n Function drawAntiAliasedLine(x1, y1, x2, y2, RGB$)\n If (x2 - x1)=0 Or (y2 - y1)=0 Then\n Print #main.gbox, \"Down; Color \" + RGB$\n result = BresenhamLine(x1, y1, x2, y2)\n Exit Function\n End If\n steep = abs(x2 - x1) < abs(y2 - y1)\n if steep then 'x and y should be reversed\n result = Swap(x1, y1)\n result = Swap(x2, y2)\n end if\n\n If (x2 < x1) Then\n result = Swap(x1, x2)\n result = Swap(y1, y2)\n End If\n dx = (x2 - x1)\n dy = (y2 - y1)\n grad = (dy/ dx)\n 'Handle the First EndPoint\n xend = RoundtoInt(x1)\n yend = y1 + grad * (xend - x1)\n xgap = invFracPart(x1 + 0.5)\n ix1 = xend\n iy1 = Int(yend)\n result = PlotAntiAliased(ix1, iy1, RGB$, invFracPart(yend) * xgap, steep )\n result = PlotAntiAliased(ix1, (iy1 + size), RGB$, fracPart(yend) * xgap, steep )\n yf = (yend + grad)\n 'Handle the Second EndPoint\n xend = RoundtoInt(x2)\n yend = y2 + grad * (xend - x2)\n xgap = fracPart(x2 + 0.5)\n ix2 = xend\n iy2 = Int(yend)\n result = PlotAntiAliased(ix2, iy2, RGB$, invFracPart(yend) * xgap, steep )\n result = PlotAntiAliased(ix2, (iy2 + size), RGB$, fracPart(yend) * xgap, steep )\n For x = ix1 + 1 To ix2 - 1\n result = PlotAntiAliased(x, Int(yf), RGB$, invFracPart(yf), steep )\n result = PlotAntiAliased(x, (Int(yf) + size), RGB$, fracPart(yf), steep )\n yf = (yf + grad)\n Next x\n End Function\n\n\n Function BresenhamLine(x0, y0, x1, y1)\n dx = Abs(x1 - x0)\n dy = Abs(y1 - y0)\n sx = ((x1 > x0) + Not(x0 < x1))\n sy = ((y1 > y0) + Not(y0 < y1))\n errornum = (dx - dy)\n Do While 1\n Print #main.gbox, \"Set \" + str$(x0) + \" \" + str$(y0)\n If (x0 = x1) And (y0 = y1) Then Exit Do\n errornum2 = (2 * errornum)\n If errornum2 > (-1 * dy) Then\n errornum = (errornum - dy)\n x0 = (x0 + sx)\n End If\n If errornum2 < dx Then\n errornum = (errornum + dx)\n y0 = (y0 + sy)\n End If\n Loop\n End Function\n", "language": "Liberty-BASIC" }, { "code": "ClearAll[ReverseFractionalPart, ReplacePixelWithAlpha, DrawEndPoint, DrawLine]\nReverseFractionalPart[x_] := 1 - FractionalPart[x]\nReplacePixelWithAlpha[img_Image, pos_ -> colvals : {_, _, _},\n alpha_] := Module[{vals,},\n vals = PixelValue[img, pos];\n vals = (1 - alpha) vals + alpha colvals;\n ReplacePixelValue[img, pos -> vals]\n ]\nDrawEndPoint[img_Image, pt : {x_, y_}, grad_, p_] :=\n Module[{xend, yend, xgap, px, py, i},\n xend = Round[x];\n yend = y + grad (xend - x);\n xgap = ReverseFractionalPart[x + 0.5];\n {px, py} = Floor[{xend, yend}];\n i = ReplacePixelWithAlpha[img, p[{x, py}] -> {1, 1, 1}, ReverseFractionalPart[yend] xgap];\n i = ReplacePixelWithAlpha[i, p[{x, py + 1}] -> {1, 1, 1}, FractionalPart[yend] xgap];\n {px, i}\n ]\nDrawLine[img_Image, p1 : {_, _}, p2 : {_, _}] :=\n Module[{x1, x2, y1, y2, steep, p, grad, intery, xend, yend, x, y,\n xstart, ystart, dx, dy, i},\n {x1, y1} = p1;\n {x2, y2} = p2;\n dx = x2 - x1;\n dy = y2 - y1;\n steep = Abs[dx] < Abs[dy];\n p = If[steep, Reverse[#], #] &;\n If[steep,\n {x1, y1, x2, y2, dx, dy} = {y1, x1, y2, x2, dy, dx}\n ];\n If[x2 < x1,\n {x1, x2, y1, y2} = {x2, x1, y2, y1}\n ];\n grad = dy/dx;\n intery = y1 + ReverseFractionalPart[x1] grad;\n {xstart, i} = DrawEndPoint[img, p[p1], grad, p];\n xstart += 1;\n {xend, i} = DrawEndPoint[i, p[p2], grad, p];\n Do[\n y = Floor[intery];\n i = ReplacePixelWithAlpha[i, p[{x, y}] -> {1, 1, 1}, ReverseFractionalPart[intery]];\n i = ReplacePixelWithAlpha[i, p[{x, y + 1}] -> {1, 1, 1}, FractionalPart[intery]];\n intery += grad\n ,\n {x, xstart, xend}\n ];\n i\n ]\nimage = ConstantImage[Black, {100, 100}];\nFold[DrawLine[#1, {20, 10}, #2] &, image, AngleVector[{20, 10}, {75, #}] & /@ Subdivide[0, Pi/2, 10]]\n", "language": "Mathematica" }, { "code": "clear all;close all;clc;\n% Example usage:\nimg = ones(250, 250);\nimg = drawline(img, 8, 8, 192, 154);\nimshow(img); % Display the image\n\nfunction img = drawline(img, x0, y0, x1, y1)\n function f = fpart(x)\n f = mod(x, 1);\n end\n\n function rf = rfpart(x)\n rf = 1 - fpart(x);\n end\n\n steep = abs(y1 - y0) > abs(x1 - x0);\n\n if steep\n [x0, y0] = deal(y0, x0);\n [x1, y1] = deal(y1, x1);\n end\n if x0 > x1\n [x0, x1] = deal(x1, x0);\n [y0, y1] = deal(y1, y0);\n end\n\n dx = x1 - x0;\n dy = y1 - y0;\n grad = dy / dx;\n\n if dx == 0\n grad = 1.0;\n end\n\n % handle first endpoint\n xend = round(x0);\n yend = y0 + grad * (xend - x0);\n xgap = rfpart(x0 + 0.5);\n xpxl1 = xend;\n ypxl1 = floor(yend);\n\n if steep\n img(ypxl1, xpxl1) = rfpart(yend) * xgap;\n img(ypxl1+1, xpxl1) = fpart(yend) * xgap;\n else\n img(xpxl1, ypxl1 ) = rfpart(yend) * xgap;\n img(xpxl1, ypxl1+1) = fpart(yend) * xgap;\n end\n intery = yend + grad; % first y-intersection for the main loop\n\n % handle second endpoint\n xend = round(x1);\n yend = y1 + grad * (xend - x1);\n xgap = fpart(x1 + 0.5);\n xpxl2 = xend;\n ypxl2 = floor(yend);\n if steep\n img(ypxl2, xpxl2) = rfpart(yend) * xgap;\n img(ypxl2+1, xpxl2) = fpart(yend) * xgap;\n else\n img(xpxl2, ypxl2 ) = rfpart(yend) * xgap;\n img(xpxl2, ypxl2+1) = fpart(yend) * xgap;\n end\n\n % main loop\n if steep\n for x = (xpxl1+1):(xpxl2-1)\n img(floor(intery), x) = rfpart(intery);\n img(floor(intery)+1, x) = fpart(intery);\n intery = intery + grad;\n end\n else\n for x = (xpxl1+1):(xpxl2-1)\n img(x, floor(intery) ) = rfpart(intery);\n img(x, floor(intery)+1) = fpart(intery);\n intery = intery + grad;\n end\n end\nend\n", "language": "MATLAB" }, { "code": "MODULE Xiaolin_Wu_Task;\n\n(* The program is for ISO Modula-2. To compile with GNU Modula-2\n (gm2), use the \"-fiso\" option. *)\n\nIMPORT RealMath;\nIMPORT SRawIO;\nIMPORT STextIO;\nIMPORT SWholeIO;\nIMPORT SYSTEM;\n\nCONST MaxDrawingSurfaceIndex = 1999;\nCONST MaxDrawingSurfaceSize =\n (MaxDrawingSurfaceIndex + 1) * (MaxDrawingSurfaceIndex + 1);\n\nTYPE DrawingSurfaceIndex = [0 .. MaxDrawingSurfaceIndex];\nTYPE PixelsIndex = [0 .. MaxDrawingSurfaceSize - 1];\nTYPE DrawingSurface =\n RECORD\n u0, v0, u1, v1 : INTEGER;\n pixels : ARRAY PixelsIndex OF REAL;\n END;\nTYPE PointPlotter = PROCEDURE (VAR DrawingSurface,\n INTEGER, INTEGER, REAL);\n\nPROCEDURE InitializeDrawingSurface (VAR s : DrawingSurface;\n u0, v0, u1, v1 : INTEGER);\n VAR i : PixelsIndex;\nBEGIN\n s.u0 := u0; s.v0 := v0;\n s.u1 := u1; s.v1 := v1;\n FOR i := 0 TO MaxDrawingSurfaceSize - 1 DO\n s.pixels[i] := 0.0\n END\nEND InitializeDrawingSurface;\n\nPROCEDURE DrawingSurfaceRef (VAR s : DrawingSurface;\n x, y : DrawingSurfaceIndex) : REAL;\n VAR c : REAL;\nBEGIN\n IF (s.u0 <= x) AND (x <= s.u1) AND (s.v0 <= y) AND (y <= s.v1) THEN\n c := s.pixels[(x - s.u0) + ((s.v1 - y) * (s.u1 - s.u0 + 1))]\n ELSE\n (* (x,y) is outside the drawing surface. Return a somewhat\n arbitrary value. \"Not a number\" would be better. *)\n c := 0.0\n END;\n RETURN c\nEND DrawingSurfaceRef;\n\nPROCEDURE DrawingSurfaceSet (VAR s : DrawingSurface;\n x, y : DrawingSurfaceIndex;\n c : REAL);\nBEGIN\n (* Store the value only if (x,y) is within the drawing surface. *)\n IF (s.u0 <= x) AND (x <= s.u1) AND (s.v0 <= y) AND (y <= s.v1) THEN\n s.pixels[(x - s.u0) + ((s.v1 - y) * (s.u1 - s.u0 + 1))] := c\n END\nEND DrawingSurfaceSet;\n\nPROCEDURE WriteTransparencyMask (VAR s : DrawingSurface);\n VAR w, h : INTEGER;\n i : DrawingSurfaceIndex;\n byteval : [0 .. 255];\n byte : SYSTEM.LOC;\nBEGIN\n (* Send to standard output a transparency map in raw Portable Gray\n Map format. *)\n w := s.u1 - s.u0 + 1;\n h := s.v1 - s.v0 + 1;\n STextIO.WriteString ('P5');\n STextIO.WriteLn;\n STextIO.WriteString ('# transparency mask');\n STextIO.WriteLn;\n SWholeIO.WriteCard (VAL (CARDINAL, w), 0);\n STextIO.WriteString (' ');\n SWholeIO.WriteCard (VAL (CARDINAL, h), 0);\n STextIO.WriteLn;\n STextIO.WriteString ('255');\n STextIO.WriteLn;\n FOR i := 0 TO (w * h) - 1 DO\n byteval := RealMath.round (255.0 * s.pixels[i]);\n byte := SYSTEM.CAST (SYSTEM.LOC, byteval);\n SRawIO.Write (byte)\n END\nEND WriteTransparencyMask;\n\nPROCEDURE ipart (x : REAL) : INTEGER;\n VAR i : INTEGER;\nBEGIN\n i := VAL (INTEGER, x);\n IF x < VAL (REAL, i) THEN\n i := i - 1;\n END;\n RETURN i\nEND ipart;\n\nPROCEDURE iround (x : REAL) : INTEGER;\nBEGIN\n RETURN ipart (x + 0.5)\nEND iround;\n\nPROCEDURE fpart (x : REAL) : REAL;\nBEGIN\n RETURN x - VAL (REAL, ipart (x))\nEND fpart;\n\nPROCEDURE rfpart (x : REAL) : REAL;\nBEGIN\n RETURN 1.0 - fpart (x)\nEND rfpart;\n\nPROCEDURE PlotShallow (VAR s : DrawingSurface;\n x, y : INTEGER;\n opacity : REAL);\n VAR combined_opacity : REAL;\nBEGIN\n (* Let us simply add opacities, up to the maximum of 1.0. You might,\n of course, wish to do something different. *)\n combined_opacity := opacity + DrawingSurfaceRef (s, x, y);\n IF combined_opacity > 1.0 THEN\n combined_opacity := 1.0\n END;\n DrawingSurfaceSet (s, x, y, combined_opacity)\nEND PlotShallow;\n\nPROCEDURE PlotSteep (VAR s : DrawingSurface;\n x, y : INTEGER;\n opacity : REAL);\nBEGIN\n PlotShallow (s, y, x, opacity)\nEND PlotSteep;\n\nPROCEDURE drawln (VAR s : DrawingSurface;\n x0, y0, x1, y1 : REAL;\n plot : PointPlotter);\n VAR dx, dy, gradient : REAL;\n yend, xgap : REAL;\n first_y_intersection, intery : REAL;\n xend : INTEGER;\n xpxl1, ypxl1 : INTEGER;\n xpxl2, ypxl2 : INTEGER;\n x : INTEGER;\nBEGIN\n dx := x1 - x0; dy := y1 - y0;\n IF dx = 0.0 THEN\n gradient := 1.0\n ELSE\n gradient := dy / dx\n END;\n\n (* Handle the first endpoint. *)\n xend := iround (x0);\n yend := y0 + (gradient * (VAL (REAL, xend) - x0));\n xgap := rfpart (x0 + 0.5);\n xpxl1 := xend;\n ypxl1 := ipart (yend);\n plot (s, xpxl1, ypxl1, rfpart (yend) * xgap);\n plot (s, xpxl1, ypxl1 + 1, fpart (yend) * xgap);\n\n first_y_intersection := yend + gradient;\n\n (* Handle the second endpoint. *)\n xend := iround (x1);\n yend := y1 + (gradient * (VAL (REAL, xend) - x1));\n xgap := fpart (x1 + 0.5);\n xpxl2 := xend;\n ypxl2 := ipart (yend);\n plot (s, xpxl2, ypxl2, (rfpart (yend) * xgap));\n plot (s, xpxl2, ypxl2 + 1, fpart (yend) * xgap);\n\n (* Loop over the rest of the points. *)\n intery := first_y_intersection;\n FOR x := xpxl1 + 1 TO xpxl2 - 1 DO\n plot (s, x, ipart (intery), rfpart (intery));\n plot (s, x, ipart (intery) + 1, fpart (intery));\n intery := intery + gradient\n END\nEND drawln;\n\nPROCEDURE DrawLine (VAR s : DrawingSurface;\n x0, y0, x1, y1 : REAL);\n VAR xdiff, ydiff : REAL;\nBEGIN\n xdiff := ABS (x1 - x0);\n ydiff := ABS (y1 - y0);\n IF ydiff <= xdiff THEN\n IF x0 <= x1 THEN\n drawln (s, x0, y0, x1, y1, PlotShallow)\n ELSE\n drawln (s, x1, y1, x0, y0, PlotShallow)\n END\n ELSE\n IF y0 <= y1 THEN\n drawln (s, y0, x0, y1, x1, PlotSteep)\n ELSE\n drawln (s, y1, x1, y0, x0, PlotSteep)\n END\n END\nEND DrawLine;\n\nCONST u0 = -299;\n u1 = 300;\n v0 = -20;\n v1 = 379;\nCONST Kx = 4.0;\n Ky = 0.1;\nVAR s : DrawingSurface;\n i : INTEGER;\n t : REAL;\n x0, y0, x1, y1 : REAL;\n x, y, u, v : REAL;\nBEGIN\n InitializeDrawingSurface (s, u0, v0, u1, v1);\n\n (* Draw a parabola. *)\n FOR i := -101 TO 100 DO\n t := VAL (REAL, i); x0 := Kx * t; y0 := Ky * t * t;\n t := VAL (REAL, i + 1); x1 := Kx * t; y1 := Ky * t * t;\n DrawLine (s, x0, y0, x1, y1)\n END;\n\n (* Draw normals to that parabola. The parabola has equation y=A*x*x,\n where A=Ky/(Kx*Kx). Therefore the slope at x is dy/dx=2*A*x. The\n slope of the normal is the negative reciprocal, and so equals\n -1/(2*A*x)=-(Kx*Kx)/(2*Ky*(Kx*t))=-Kx/(2*Ky*t). *)\n FOR i := -101 TO 101 DO\n t := VAL (REAL, i);\n x := Kx * t; y := Ky * t * t; (* (x,y) = a point on the parabola *)\n IF ABS (t) <= 0.000000001 THEN (* (u,v) = a normal vector *)\n u := 0.0; v := 1.0\n ELSE\n u := 1.0; v := -Kx / (2.0 * Ky * t)\n END;\n x0 := x - (1000.0 * u); y0 := y - (1000.0 * v);\n x1 := x + (1000.0 * u); y1 := y + (1000.0 * v);\n DrawLine (s, x0, y0, x1, y1);\n END;\n\n WriteTransparencyMask (s)\nEND Xiaolin_Wu_Task.\n", "language": "Modula-2" }, { "code": "#!/bin/sh\n\n# Set GM2 to wherever you have a GNU Modula-2 compiler.\nGM2=\"/usr/x86_64-pc-linux-gnu/gcc-bin/13/gm2\"\n\n${GM2} -g -fbounds-check -fiso xiaolin_wu_line_algorithm_Modula2.mod\n./a.out > alpha.pgm\nppmmake rgb:5C/06/8C 600 400 > bg.ppm\nppmmake rgb:E2/E8/68 600 400 > fg.ppm\npamcomp -alpha=alpha.pgm fg.ppm bg.ppm | pamtopng > image.png\n", "language": "Modula-2" }, { "code": "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 BG = ColorRGBF64([0.0, 0.0, 0.0])\n FG = ColorRGBF64([1.0, 1.0, 1.0])\n\nfunc plot(img: var Image; x, y: int; c: float) =\n ## Draw a point with brigthness c.\n let d = 1 - c\n img[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 ## Draw an anti-aliased line from (x0, y0) to (x1, y1).\n\n var (x0, y0, x1, y1) = (x0, y0, x1, y1)\n let steep = abs(y1 - y0) > abs(x1 - x0)\n if steep:\n swap x0, y0\n swap x1, y1\n if x0 > x1:\n swap x0, x1\n swap y0, y1\n\n let dx = x1 - x0\n let dy = y1 - y0\n var gradient = dy / dx\n if dx == 0:\n gradient = 1\n\n # Handle first endpoint.\n var xend = round(x0)\n var yend = y0 + gradient * (xend - x0)\n var xgap = rfpart(x0 + 0.5)\n let xpxl1 = xend.toInt\n let ypxl1 = yend.toInt\n if steep:\n img.plot(ypxl1, xpxl1, rfpart(yend) * xgap)\n img.plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)\n else:\n img.plot(xpxl1, ypxl1, rfpart(yend) * xgap)\n img.plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)\n var intery = yend + gradient # First y-intersection for the main loop.\n\n # Handle second endpoint.\n xend = round(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = fpart(x1 + 0.5)\n let xpxl2 = xend.toInt\n let ypxl2 = yend.toInt\n if steep:\n img.plot(ypxl2, xpxl2, rfpart(yend) * xgap)\n img.plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)\n else:\n img.plot(xpxl2, ypxl2, rfpart(yend) * xgap)\n img.plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)\n\n # Main loop.\n if steep:\n for x in (xpxl1 + 1)..(xpxl2 - 1):\n img.plot(intery.int, x, rfpart(intery))\n img.plot(intery.int + 1, x, fpart(intery))\n intery += gradient\n else:\n for x in (xpxl1 + 1)..(xpxl2 - 1):\n img.plot(x, intery.int, rfpart(intery))\n img.plot(x, intery.int + 1, fpart(intery))\n intery += gradient\n\n\nwhen isMainModule:\n var img = initImage[ColorRGBF64](800, 800)\n img.fill(BG)\n for x1 in countup(100, 700, 60):\n img.drawLine(400, 700, x1.toFloat, 100)\n img.savePNG(\"xiaoling_wu.png\", compression = 9)\n", "language": "Nim" }, { "code": "import\n graphics(Mouse, Window),\n io(stop),\n ipl.graphics(QuitEvents)\n\nprocedure main ()\n local width, height\n local done, w, event\n local x1, y1, x2, y2, press_is_active\n\n width := 640\n height := 480\n\n w := Window().\n set_size(width, height).\n set_bg(\"white\").\n set_canvas(\"normal\") | stop(&why)\n\n press_is_active := &no\n done := &no\n while /done do\n {\n if *w.pending() ~= 0 then\n {\n event := w.event()\n case event[1] of\n {\n QuitEvents() : done := &yes\n Mouse.LEFT_PRESS:\n {\n if /press_is_active then\n {\n x1 := event[2]; y1 := event[3]\n press_is_active := &yes\n }\n else\n {\n x2 := event[2]; y2 := event[3]\n draw_line (w, x1, y1, x2, y2)\n press_is_active := &no\n }\n }\n }\n }\n }\n\n w.get_pixels().to_file(\"xiaolin_wu_line_algorithm_OI.png\")\nend\n\nprocedure draw_line (w, x0, y0, x1, y1)\n local steep\n local dx, dy, gradient\n local xend, yend, xgap, intery\n local xpxl1, ypxl1\n local xpxl2, ypxl2\n local x\n\n x0 := real (x0)\n y0 := real (y0)\n x1 := real (x1)\n y1 := real (y1)\n\n # In Object Icon (as in Icon), comparisons DO NOT return boolean\n # values! They either SUCCEED or they FAIL. Thus the need for an\n # \"if-then-else\" here.\n steep := if abs (y1 - y0) > abs (x1 - x0) then &yes else &no\n\n if \\steep then { x0 :=: y0; x1 :=: y1 }\n if x0 > x1 then { x0 :=: x1; y0 :=: y1 }\n dx := x1 - x0; dy := y1 - y0\n gradient := if dx = 0 then 1.0 else dy / dx\n\n # Handle the first endpoint.\n xend := round (x0); yend := y0 + (gradient * (xend - x0))\n xgap := rfpart (x0 + 0.5)\n xpxl1 := xend; ypxl1 := ipart (yend)\n if \\steep then\n {\n plot (w, ypxl1, xpxl1, rfpart (yend) * xgap)\n plot (w, ypxl1 + 1, xpxl1, fpart(yend) * xgap)\n }\n else\n {\n plot (w, xpxl1, ypxl1, rfpart (yend) * xgap)\n plot (w, xpxl1, ypxl1 + 1, fpart (yend) * xgap)\n }\n\n # The first y-intersection.\n intery := yend + gradient\n\n # Handle the second endpoint.\n xend := round (x1); yend := y1 + (gradient * (xend - x1))\n xgap := fpart (x1 + 0.5)\n xpxl2 := xend; ypxl2 := ipart (yend)\n if \\steep then\n {\n plot (w, ypxl2, xpxl2, rfpart (yend) * xgap)\n plot (w, ypxl2 + 1, xpxl2, fpart (yend) * xgap)\n }\n else\n {\n plot (w, xpxl2, ypxl2, rfpart (yend) * xgap)\n plot (w, xpxl2, ypxl2 + 1, fpart (yend) * xgap)\n }\n\n if \\steep then\n every x := xpxl1 + 1 to xpxl2 - 1 do\n {\n plot (w, ipart (intery), x, rfpart (intery))\n plot (w, ipart (intery) + 1, x, fpart (intery))\n intery := intery + gradient\n }\n else\n every x := xpxl1 + 1 to xpxl2 - 1 do\n {\n plot(w, x, ipart (intery), rfpart (intery))\n plot(w, x, ipart (intery) + 1, fpart (intery))\n intery := intery + gradient\n }\n\n return\nend\n\nprocedure plot (w, x, y, c)\n w.set_fg (\"black \" || round (100.0 * c) || \"%\")\n w.draw_point (x, y)\n return\nend\n\nprocedure ipart (x)\n local i\n i := integer (x)\n return (if i = x then i else if x < 0 then i - 1 else i)\nend\n\nprocedure round (x)\n return ipart (x + 0.5)\nend\n\nprocedure fpart (x)\n return x - ipart (x)\nend\n\nprocedure rfpart (x)\n return 1.0 - fpart (x)\nend\n", "language": "ObjectIcon" }, { "code": "program wu;\nuses\n SDL2,\n math;\n\nconst\n FPS = 1000 div 60;\n SCALE = 6;\n\nvar\n win: PSDL_Window;\n ren: PSDL_Renderer;\n mouse_x, mouse_y: longint;\n origin: TSDL_Point;\n event: TSDL_Event;\n line_alpha: byte = 255;\n\nprocedure SDL_RenderDrawWuLine(renderer: PSDL_Renderer; x1, y1, x2, y2: longint);\nvar\n r, g, b, a, a_new: Uint8;\n gradient, iy: real;\n x, y: longint;\n px, py: plongint;\n\n procedure swap(var a, b: longint);\n var\n tmp: longint;\n begin\n tmp := a;\n a := b;\n b := tmp;\n end;\n\nbegin\n if a = 0 then\n exit;\n SDL_GetRenderDrawColor(renderer, @r, @g, @b, @a);\n if abs(y2 - y1) > abs(x2 - x1) then\n begin\n swap(x1, y1);\n swap(x2, y2);\n px := @y;\n py := @x;\n end\n else\n begin\n px := @x;\n py := @y;\n end;\n if x1 > x2 then\n begin\n swap(x1, x2);\n swap(y1, y2);\n end;\n x := x2 - x1;\n if x = 0 then\n x := 1;\n gradient := (y2 - y1) / x;\n iy := y1;\n for x := x1 to x2 do\n begin\n a_new := round(a * frac(iy));\n y := floor(iy);\n SDL_SetRenderDrawColor(renderer, r, g, b, a-a_new);\n SDL_RenderDrawPoint(renderer, px^, py^);\n inc(y);\n SDL_SetRenderDrawColor(renderer, r, g, b, a_new);\n SDL_RenderDrawPoint(renderer, px^, py^);\n iy := iy + gradient;\n end;\n SDL_SetRenderDrawColor(renderer, r, g, b, a);\nend;\n\nbegin\n SDL_Init(SDL_INIT_VIDEO);\n win := SDL_CreateWindow('Xiaolin Wu''s line algorithm', SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n 640, 480, SDL_WINDOW_RESIZABLE);\n ren := SDL_CreateRenderer(win, -1, 0);\n if ren = NIL then\n begin\n writeln(SDL_GetError);\n halt;\n end;\n SDL_SetRenderDrawBlendMode(ren, SDL_BLENDMODE_BLEND);\n SDL_RenderSetScale(ren, SCALE, SCALE);\n SDL_SetCursor(SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR));\n\n mouse_x := 0;\n mouse_y := 0;\n origin.x := 0;\n origin.y := 0;\n repeat\n while SDL_PollEvent(@event) = 1 do\n case event.type_ of\n SDL_KEYDOWN:\n if event.key.keysym.sym = SDLK_ESCAPE then\n halt;\n SDL_MOUSEBUTTONDOWN:\n begin\n origin.x := mouse_x;\n origin.y := mouse_y;\n end;\n SDL_MOUSEMOTION:\n with event.motion do\n begin\n mouse_x := x div SCALE;\n mouse_y := y div SCALE;\n end;\n SDL_MOUSEWHEEL:\n line_alpha := EnsureRange(line_alpha + event.wheel.y * 20, 0, 255);\n SDL_QUITEV:\n halt;\n end;\n\n SDL_SetRenderDrawColor(ren, 35, 35, 35, line_alpha);\n SDL_RenderDrawWuLine(ren, origin.x, origin.y, mouse_x, mouse_y);\n SDL_RenderPresent(ren);\n SDL_SetRenderDrawColor(ren, 255, 255, 255, 255);\n SDL_RenderClear(ren);\n SDL_Delay(FPS);\n until false;\nend.\n", "language": "Pascal" }, { "code": "#!perl\nuse strict;\nuse warnings;\n\nsub plot {\n\tmy ($x, $y, $c) = @_;\n\tprintf \"plot %d %d %.1f\\n\", $x, $y, $c if $c;\n}\n\nsub ipart {\n\tint shift;\n}\n\nsub round {\n\tint( 0.5 + shift );\n}\n\nsub fpart {\n\tmy $x = shift;\n\t$x - int $x;\n}\n\nsub rfpart {\n\t1 - fpart(shift);\n}\n\nsub drawLine {\n\tmy ($x0, $y0, $x1, $y1) = @_;\n\n\tmy $plot = \\&plot;\n\n\tif( abs($y1 - $y0) > abs($x1 - $x0) ) {\n\t\t$plot = sub { plot( @_[1, 0, 2] ) };\n\t\t($x0, $y0, $x1, $y1) = ($y0, $x0, $y1, $x1);\n\t}\n\n\tif( $x0 > $x1 ) {\n\t\t($x0, $x1, $y0, $y1) = ($x1, $x0, $y1, $y0);\n\t}\n\n\tmy $dx = $x1 - $x0;\n\tmy $dy = $y1 - $y0;\n\tmy $gradient = $dy / $dx;\n\n\tmy @xends;\n\tmy $intery;\n\n\t# handle the endpoints\n\tfor my $xy ([$x0, $y0], [$x1, $y1]) {\n\t\tmy ($x, $y) = @$xy;\n\t\tmy $xend = round($x);\n\t\tmy $yend = $y + $gradient * ($xend - $x);\n\t\tmy $xgap = rfpart($x + 0.5);\n\n\t\tmy $x_pixel = $xend;\n\t\tmy $y_pixel = ipart($yend);\n\t\tpush @xends, $x_pixel;\n\n\t\t$plot->($x_pixel, $y_pixel , rfpart($yend) * $xgap);\n\t\t$plot->($x_pixel, $y_pixel+1, fpart($yend) * $xgap);\n\t\tnext if defined $intery;\n\t\t# first y-intersection for the main loop\n\t\t$intery = $yend + $gradient;\n\t}\n\n\t# main loop\n\n\tfor my $x ( $xends[0] + 1 .. $xends[1] - 1 ) {\n\t\t$plot->($x, ipart ($intery), rfpart($intery));\n\t\t$plot->($x, ipart ($intery)+1, fpart($intery));\n\t\t$intery += $gradient;\n\t}\n}\n\nif( $0 eq __FILE__ ) {\n\tdrawLine( 0, 1, 10, 2 );\n}\n__END__\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\XiaolinWuLine.exw\n -- ==============================\n --\n -- Resize the window to show lines at any angle\n --\n -- For education/comparision purposes only: see demo\\pGUI\\aaline.exw\n -- for a much shorter version, but \"wrong algorithm\" for the RC task.\n -- Also note this blends with BACK rather than the actual pixel,\n -- whereas aaline.exw does it properly.\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span> <span style=\"color: #000080;font-style:italic;\">-- not really fair: pwa/p2js uses OpenGL\n -- and does not draw bresenham lines anyway/ever, plus the next line\n -- makes no difference whatsoever when running this in a browser.</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">TITLE</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"Xiaolin Wu's line algorithm\"</span>\n\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span>\n\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">wuline</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #000080;font-style:italic;\">-- space toggles, for comparison\n -- when false, and with USE_OPENGL, lines are still smooth,\n -- but a bit thicker - and therefore less \"ropey\".\n -- when false, but without USE_OPENGL, it draws bresenham\n -- lines (ie jagged, without anti-aliasing [desktop only]).</span>\n\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">BACK</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_PARCHMENT</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">LINE</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">CD_BLUE</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">rB</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">gB</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">bB</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_rgb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">BACK</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">rL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">gL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">bL</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">to_rgb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">LINE</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- plot the pixel at (x, y) with brightness c (where 0 &lt;= c &lt;= 1)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">steep</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">C</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">c</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">rgb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">rL</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">rB</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">C</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gL</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">gB</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">C</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">bL</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">bB</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">C</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasPixel</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">plot2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xgap</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">xgap</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,(</span><span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">xgap</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- fractional part of x</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">wu_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">steep</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\">></span> <span style=\"color: #7060A8;\">abs</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">steep</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">x1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">dx</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">dy</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">y0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">gradient</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">:</span> <span style=\"color: #000000;\">dy</span> <span style=\"color: #0000FF;\">/</span> <span style=\"color: #000000;\">dx</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- handle first endpoint</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">xend</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">yend</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">y0</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">gradient</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xend</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">x0</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">xgap</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x0</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">xpxl1</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">xend</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- this will be used in the main loop</span>\n <span style=\"color: #000000;\">ypxl1</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yend</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xpxl1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ypxl1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yend</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">xgap</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">intery</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">yend</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">gradient</span> <span style=\"color: #000080;font-style:italic;\">-- first y-intersection for the main loop\n\n -- handle second endpoint</span>\n <span style=\"color: #000000;\">xend</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">yend</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">gradient</span> <span style=\"color: #0000FF;\">*</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xend</span> <span style=\"color: #0000FF;\">-</span> <span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">xgap</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">0.5</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">xpxl2</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">xend</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000080;font-style:italic;\">-- this will be used in the main loop</span>\n <span style=\"color: #000000;\">ypxl2</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yend</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xpxl2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ypxl2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yend</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">xgap</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- main loop</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xpxl1</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">xpxl2</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">plot2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">intery</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">intery</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">steep</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">intery</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">gradient</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">plot_4_points</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">x2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">y1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">90.01</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">angle</span> <span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">angle1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">angle</span> <span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">angle2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- top right</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">180</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">angle1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">180</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)<=</span><span style=\"color: #000000;\">angle2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- top left</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">180</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">angle1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">180</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)<=</span><span style=\"color: #000000;\">angle2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- btm left</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)>=</span><span style=\"color: #000000;\">angle1</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)<=</span><span style=\"color: #000000;\">angle2</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">plot</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">f</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- btm right</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">wu_ellipse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--\n -- (draws a circle when w=h) credit:\n -- https://yellowsplash.wordpress.com/2009/10/23/fast-antialiased-circles-and-ellipses-from-xiaolin-wus-concepts/\n --</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">w</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">h</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">angle1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">angle2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Match cdCanvasArc/Sector angles:</span>\n <span style=\"color: #000000;\">angle1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">atan2</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #7060A8;\">sin</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">CD_DEG2RAD</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #7060A8;\">cos</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">CD_DEG2RAD</span><span style=\"color: #0000FF;\">))*</span><span style=\"color: #004600;\">CD_RAD2DEG</span>\n <span style=\"color: #000000;\">angle2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">atan2</span><span style=\"color: #0000FF;\">((</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #7060A8;\">sin</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">CD_DEG2RAD</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #7060A8;\">cos</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #004600;\">CD_DEG2RAD</span><span style=\"color: #0000FF;\">))*</span><span style=\"color: #004600;\">CD_RAD2DEG</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">angle1</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">angle2</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">360</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">asq</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">bsq</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">sqab</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">asq</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">bsq</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">ffd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">asq</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">sqab</span><span style=\"color: #0000FF;\">),</span> <span style=\"color: #000080;font-style:italic;\">-- forty-five-degree coord</span>\n <span style=\"color: #000000;\">xj</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">yj</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">frc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">flr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- draw top right, and the 3 mirrors of it in horizontal fashion\n -- (ie 90 to 45 degrees for a circle)</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">ffd</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">yj</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">asq</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- real y value</span>\n <span style=\"color: #000000;\">frc</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yj</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">flr</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yj</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">angle</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">90</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yj</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #004600;\">CD_RAD2DEG</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot_4_points</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">flr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">frc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot_4_points</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xi</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">flr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">frc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- switch from horizontal to vertial mode for the rest, ditto 3\n -- (ie 45..0 degrees for a circle)</span>\n\n <span style=\"color: #000000;\">ffd</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">round</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bsq</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">sqab</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">ffd</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">xj</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #7060A8;\">sqrt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">bsq</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- real x value</span>\n <span style=\"color: #000000;\">frc</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #000000;\">fpart</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xj</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">flr</span> <span style=\"color: #0000FF;\">:=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xj</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">angle</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xj</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #7060A8;\">arctan</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">xj</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #004600;\">CD_RAD2DEG</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot_4_points</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">flr</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">frc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">plot_4_points</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">flr</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">yi</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">frc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasClear</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">cdCanvasSetLineWidth</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wuline</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">wuline</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">wu_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">wu_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">wu_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">wu_line</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasLine</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">wuline</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">wu_ellipse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360) </span>\n <span style=\"color: #000000;\">wu_ellipse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">300</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- wu_ellipse(200,200,300,100,15,85)\n -- cdCanvasArc(cddbuffer, 205, 205, 300, 100, 15, 85) </span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #7060A8;\">cdCanvasArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- cdCanvasSector(cddbuffer, 200, 200, 200, 200, 0, 360) </span>\n <span style=\"color: #7060A8;\">cdCanvasArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">300</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000080;font-style:italic;\">--test - it works (much better) if you draw the polygon /after/ the lines!!\n -- cdCanvasBegin(cddbuffer,CD_FILL)\n -- cdCanvasVertex(cddbuffer,w,h)\n -- cdCanvasVertex(cddbuffer,0,h)\n -- cdCanvasVertex(cddbuffer,200,200)\n -- cdCanvasEnd(cddbuffer)\n --/test</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupGLSwapBuffers</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupGLMakeCurrent</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetDouble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SCREENDPI\"</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">25.4</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_GL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"10x10 %g\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">cdcanvas</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">cdcanvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cddbuffer</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_DBUFFER</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">BACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cddbuffer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">LINE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">canvas_resize_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*canvas*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">canvas_width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas_height</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetDouble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SCREENDPI\"</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">25.4</span>\n <span style=\"color: #7060A8;\">cdCanvasSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cdcanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"%dx%d %g\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">canvas_width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas_height</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">set_title</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">TITLE</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wuline</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\" (wu_line)\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" (opengl)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wuline</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\" (anti-aliased)\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" (bresenham)\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">IupSetStrAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">key_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #004600;\">K_ESC</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CLOSE</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #008000;\">' '</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">wuline</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #000000;\">wuline</span>\n <span style=\"color: #000000;\">set_title</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupRedraw</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_CONTINUE</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">USE_OPENGL</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGLCanvas</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"BUFFER\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DOUBLE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupCanvas</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"640x480\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"RESIZE_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"canvas_resize_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">set_title</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupSetCallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"KEY_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"key_cb\"</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "(scl 2)\n\n(de plot (Img X Y C)\n (set (nth Img (*/ Y 1.0) (*/ X 1.0)) (- 100 C)) )\n\n(de ipart (X)\n (* 1.0 (/ X 1.0)) )\n\n(de iround (X)\n (ipart (+ X 0.5)) )\n\n(de fpart (X)\n (% X 1.0) )\n\n(de rfpart (X)\n (- 1.0 (fpart X)) )\n\n(de xiaolin (Img X1 Y1 X2 Y2)\n (let (DX (- X2 X1) DY (- Y2 Y1))\n (use (Grad Xend Yend Xgap Xpxl1 Ypxl1 Xpxl2 Ypxl2 Intery)\n (when (> (abs DY) (abs DX))\n (xchg 'X1 'Y1 'X2 'Y2) )\n (when (> X1 X2)\n (xchg 'X1 'X2 'Y1 'Y2) )\n (setq\n Grad (*/ DY 1.0 DX)\n Xend (iround X1)\n Yend (+ Y1 (*/ Grad (- Xend X1) 1.0))\n Xgap (rfpart (+ X1 0.5))\n Xpxl1 Xend\n Ypxl1 (ipart Yend) )\n (plot Img Xpxl1 Ypxl1 (*/ (rfpart Yend) Xgap 1.0))\n (plot Img Xpxl1 (+ 1.0 Ypxl1) (*/ (fpart Yend) Xgap 1.0))\n (setq\n Intery (+ Yend Grad)\n Xend (iround X2)\n Yend (+ Y2 (*/ Grad (- Xend X2) 1.0))\n Xgap (fpart (+ X2 0.5))\n Xpxl2 Xend\n Ypxl2 (ipart Yend) )\n (plot Img Xpxl2 Ypxl2 (*/ (rfpart Yend) Xgap 1.0))\n (plot Img Xpxl2 (+ 1.0 Ypxl2) (*/ (fpart Yend) Xgap 1.0))\n (for (X (+ Xpxl1 1.0) (>= (- Xpxl2 1.0) X) (+ X 1.0))\n (plot Img X (ipart Intery) (rfpart Intery))\n (plot Img X (+ 1.0 (ipart Intery)) (fpart Intery))\n (inc 'Intery Grad) ) ) ) )\n\n(let Img (make (do 90 (link (need 120 99)))) # Create image 120 x 90\n (xiaolin Img 10.0 10.0 110.0 80.0) # Draw lines\n (xiaolin Img 10.0 10.0 110.0 45.0)\n (xiaolin Img 10.0 80.0 110.0 45.0)\n (xiaolin Img 10.0 80.0 110.0 10.0)\n (out \"img.pgm\" # Write to bitmap file\n (prinl \"P2\")\n (prinl 120 \" \" 90)\n (prinl 100)\n (for Y Img (apply printsp Y)) ) )\n", "language": "PicoLisp" }, { "code": "Macro PlotB(x, y, Color, b)\n Plot(x, y, RGB(Red(Color) * (b), Green(Color) * (b), Blue(Color) * (b)))\nEndMacro\n\nProcedure.f fracPart(x.f)\n ProcedureReturn x - Int(x)\nEndProcedure\n\nProcedure.f invFracPart(x.f)\n ProcedureReturn 1.0 - fracPart(x)\nEndProcedure\n\nProcedure drawAntiAliasedLine(x1.f, y1.f, x2.f, y2.f, color)\n Protected.f dx, dy, xend, yend, grad, yf, xgap, ix1, iy1, ix2, iy2\n Protected x\n\n dx = x2 - x1\n dy = y2 - y1\n If Abs(dx) < Abs(dy)\n Swap x1, y1\n Swap x2, y2\n Swap dx, dy\n EndIf\n\n If x2 < x1\n Swap x1, x2\n Swap y1, y2\n EndIf\n\n grad = dy / dx\n\n ;handle first endpoint\n xend = Round(x1, #pb_round_nearest)\n yend = y1 + grad * (xend - x1)\n xgap = invFracPart(x1 + 0.5)\n ix1 = xend ;this will be used in the MAIN loop\n iy1 = Int(yend)\n PlotB(ix1, iy1, color, invFracPart(yend) * xgap)\n PlotB(ix1, iy1 + 1, color, fracPart(yend) * xgap)\n yf = yend + grad ;first y-intersection for the MAIN loop\n\n ;handle second endpoint\n xend = Round(x2, #pb_round_nearest)\n yend = y2 + grad * (xend - x2)\n xgap = fracPart(x2 + 0.5)\n ix2 = xend ;this will be used in the MAIN loop\n iy2 = Int(yend)\n PlotB(ix2, iy2, color, invFracPart(yend) * xgap)\n PlotB(ix2, iy2 + 1, color, fracPart(yend) * xgap)\n ;MAIN loop\n For x = ix1 + 1 To ix2 - 1\n PlotB(x, Int(yf), color, invFracPart(yf))\n PlotB(x, Int(yf) + 1, color, fracPart(yf))\n yf + grad\n Next\nEndProcedure\n\nDefine w = 200, h = 200, img = 1\nCreateImage(img, w, h) ;img is internal id of the image\n\nOpenWindow(0, 0, 0, w, h,\"Xiaolin Wu's line algorithm\", #PB_Window_SystemMenu)\n\nStartDrawing(ImageOutput(img))\n drawAntiAliasedLine(80,20, 130,80, RGB(255, 0, 0))\nStopDrawing()\n\nImageGadget(0, 0, 0, w, h, ImageID(img))\n\nDefine event\nRepeat\n event = WaitWindowEvent()\nUntil event = #PB_Event_CloseWindow\n", "language": "PureBasic" }, { "code": "\"\"\"Script demonstrating drawing of anti-aliased lines using Xiaolin Wu's line\nalgorithm\n\nusage: python xiaolinwu.py [output-file]\n\n\"\"\"\nfrom __future__ import division\nimport sys\n\nfrom PIL import Image\n\n\ndef _fpart(x):\n return x - int(x)\n\ndef _rfpart(x):\n return 1 - _fpart(x)\n\ndef putpixel(img, xy, color, alpha=1):\n \"\"\"\n Paints color over the background at the point xy in img.\n Use alpha for blending. alpha=1 means a completely opaque foreground.\n \"\"\"\n compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))\n c = compose_color(img.getpixel(xy), color)\n img.putpixel(xy, c)\n\ndef draw_line(img, p1, p2, color):\n \"\"\"Draws an anti-aliased line in img from p1 to p2 with the given color.\"\"\"\n x1, y1 = p1\n x2, y2 = p2\n dx, dy = x2-x1, y2-y1\n steep = abs(dx) < abs(dy)\n p = lambda px, py: ((px,py), (py,px))[steep]\n\n if steep:\n x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx\n if x2 < x1:\n x1, x2, y1, y2 = x2, x1, y2, y1\n\n grad = dy/dx\n intery = y1 + _rfpart(x1) * grad\n def draw_endpoint(pt):\n x, y = pt\n xend = round(x)\n yend = y + grad * (xend - x)\n xgap = _rfpart(x + 0.5)\n px, py = int(xend), int(yend)\n putpixel(img, p(px, py), color, _rfpart(yend) * xgap)\n putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)\n return px\n\n xstart = draw_endpoint(p(*p1)) + 1\n xend = draw_endpoint(p(*p2))\n\n for x in range(xstart, xend):\n y = int(intery)\n putpixel(img, p(x, y), color, _rfpart(intery))\n putpixel(img, p(x, y+1), color, _fpart(intery))\n intery += grad\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print 'usage: python xiaolinwu.py [output-file]'\n sys.exit(-1)\n\n blue = (0, 0, 255)\n yellow = (255, 255, 0)\n img = Image.new(\"RGB\", (500,500), blue)\n for a in range(10, 431, 60):\n draw_line(img, (10, 10), (490, a), yellow)\n draw_line(img, (10, 10), (a, 490), yellow)\n draw_line(img, (10, 10), (490, 490), yellow)\n filename = sys.argv[1]\n img.save(filename)\n print 'image saved to', filename\n", "language": "Python" }, { "code": "#lang racket\n(require 2htdp/image)\n\n(define (plot img x y c)\n (define c*255 (exact-round (* (- 1 c) 255)))\n (place-image\n (rectangle 1 1 'solid (make-color c*255 c*255 c*255 255))\n x y img))\n\n(define ipart exact-floor) ; assume that a \"round-down\" is what we want when -ve\n;;; `round` is built in -- but we'll use exact round (and I'm not keen on over-binding round)\n\n(define (fpart n) (- n (exact-floor n)))\n(define (rfpart n) (- 1 (fpart n)))\n\n(define (draw-line img x0 y0 x1 y1)\n (define (draw-line-steeped img x0 y0 x1 y1 steep?)\n (define (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?)\n (define dx (- x1 x0))\n (define dy (- y1 y0))\n (define gradient (/ dy dx))\n\n (define (handle-end-point img x y)\n (define xend (exact-round x))\n (define yend (+ y (* gradient (- xend x))))\n (define xgap (rfpart (+ x 0.5)))\n (define ypxl (ipart yend))\n (define intery (+ yend gradient))\n\n (case steep?\n [(#t)\n (define img* (plot img ypxl xend (* xgap (rfpart yend))))\n (values (plot img* (+ ypxl 1) xend (* xgap (fpart yend))) xend intery)]\n [(#f)\n (define img* (plot img xend ypxl (* xgap (rfpart yend))))\n (values (plot img* xend (+ ypxl 1) (* xgap (fpart yend))) xend intery)]))\n\n (define-values (img-with-l-endpoint xpl1 intery) (handle-end-point img x0 y0))\n (define-values (img-with-r-endpoint xpl2 _) (handle-end-point img-with-l-endpoint x1 y1))\n\n (for/fold ((img img-with-l-endpoint) (y intery))\n ((x (in-range (+ xpl1 1) xpl2)))\n (define y-i (ipart y))\n (values\n (case steep?\n [(#t)\n (define img* (plot img y-i x (rfpart y)))\n (plot img* (+ 1 y-i) x (fpart y))]\n [(#f)\n (define img* (plot img x y-i (rfpart y)))\n (plot img* x (+ 1 y-i) (fpart y))])\n (+ y gradient))))\n\n (if (> x0 x1)\n (draw-line-steeped-l-to-r img x1 y1 x0 y0 steep?)\n (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?)))\n\n (define steep? (> (abs (- y1 y0)) (abs (- x1 x0))))\n (define-values (img* _)\n (if steep?\n (draw-line-steeped img y0 x0 y1 x1 steep?)\n (draw-line-steeped img x0 y0 x1 y1 steep?)))\n img*)\n\n(define img-1\n(beside\n (scale 3 (draw-line (empty-scene 150 100) 12 12 138 88))\n (above\n (scale 1 (draw-line (empty-scene 150 100) 12 50 138 50))\n (scale 1 (draw-line (empty-scene 150 100) 75 12 75 88))\n (scale 1 (draw-line (empty-scene 150 100) 12 88 138 12)))))\n\n(define img-2\n (beside\n (scale 3 (draw-line (empty-scene 100 150) 12 12 88 138))\n (above (scale 1 (draw-line (empty-scene 100 150) 50 12 50 138))\n (scale 1 (draw-line (empty-scene 100 150) 12 75 88 75))\n (scale 1 (draw-line (empty-scene 100 150) 88 12 12 138)))))\n\nimg-1\nimg-2\n(save-image img-1 \"images/xiaolin-wu-racket-1.png\")\n(save-image img-2 \"images/xiaolin-wu-racket-2.png\")\n", "language": "Racket" }, { "code": "sub plot(\\x, \\y, \\c) { say \"plot {x} {y} {c}\" }\n\nsub fpart(\\x) { x - floor(x) }\n\nsub draw-line(@a is copy, @b is copy) {\n my Bool \\steep = abs(@b[1] - @a[1]) > abs(@b[0] - @a[0]);\n my $plot = &OUTER::plot;\n\n if steep {\n\t$plot = -> $y, $x, $c { plot($x, $y, $c) }\n\t@a.=reverse;\n\t@b.=reverse;\n }\n if @a[0] > @b[0] { my @t = @a; @a = @b; @b = @t }\n\n my (\\x0,\\y0) = @a;\n my (\\x1,\\y1) = @b;\n\n my \\dx = x1 - x0;\n my \\dy = y1 - y0;\n my \\gradient = dy / dx;\n\n # handle first endpoint\n my \\x-end1 = round(x0);\n my \\y-end1 = y0 + gradient * (x-end1 - x0);\n my \\x-gap1 = 1 - round(x0 + 0.5);\n\n my \\x-pxl1 = x-end1; # this will be used in the main loop\n my \\y-pxl1 = floor(y-end1);\n my \\c1 = fpart(y-end1) * x-gap1;\n\n $plot(x-pxl1, y-pxl1 , 1 - c1) unless c1 == 1;\n $plot(x-pxl1, y-pxl1 + 1, c1 ) unless c1 == 0;\n\n # handle second endpoint\n my \\x-end2 = round(x1);\n my \\y-end2 = y1 + gradient * (x-end2 - x1);\n my \\x-gap2 = fpart(x1 + 0.5);\n\n my \\x-pxl2 = x-end2; # this will be used in the main loop\n my \\y-pxl2 = floor(y-end2);\n my \\c2 = fpart(y-end2) * x-gap2;\n\n my \\intery = y-end1 + gradient;\n\n # main loop\n for (x-pxl1 + 1 .. x-pxl2 - 1)\n\tZ\n\t(intery, intery + gradient ... *)\n -> (\\x,\\y) {\n\tmy \\c = fpart(y);\n\t$plot(x, floor(y) , 1 - c) unless c == 1;\n\t$plot(x, floor(y) + 1, c ) unless c == 0;\n }\n\n $plot(x-pxl2, y-pxl2 , 1 - c2) unless c2 == 1;\n $plot(x-pxl2, y-pxl2 + 1, c2 ) unless c2 == 0;\n}\n\ndraw-line [0,1], [10,2];\n", "language": "Raku" }, { "code": "/*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */\nbackground= '·' /*background character: a middle-dot. */\n image.= background /*fill the array with middle-dots. */\n plotC= '░▒▓█' /*characters used for plotting points. */\n EoE= 3000 /*EOE = End Of Earth, er, ··· graph. */\n do j=-EoE to +EoE /*define the graph: lowest ──► highest.*/\n image.j.0= '─' /*define the graph's horizontal axis. */\n image.0.j= '│' /* \" \" \" verical \" */\n end /*j*/\n image.0.0= '┼' /*define the graph's axis origin (char)*/\nparse arg xi yi xf yf . /*allow specifying the line-end points.*/\nif xi=='' | xi==\",\" then xi= 1 /*Not specified? Then use the default.*/\nif yi=='' | yi==\",\" then yi= 2 /* \" \" \" \" \" \" */\nif xf=='' | xf==\",\" then xf=11 /* \" \" \" \" \" \" */\nif yf=='' | yf==\",\" then yf=12 /* \" \" \" \" \" \" */\nminX=0; minY=0 /*use these as the limits for plotting.*/\nmaxX=0; maxY=0 /* \" \" \" \" \" \" \" */\ncall drawLine xi, yi, xf, yf /*invoke subroutine and graph the line.*/\nborder=2 /*allow additional space (plot border).*/\nminX=minX - border * 2; maxX=maxX + border * 2 /*preserve screen's aspect ratio {*2}.*/\nminY=minY - border ; maxY=maxY + border\n do y=maxY to minY by -1; $= /*construct a row.*/\n do x=minX to maxX; $=$ || image.x.y; end /*x*/\n say $ /*display the constructed row to term. */\n end /*y*/ /*graph is cropped by the MINs and MAXs*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ndrawLine: parse arg x1,y1,x2,y2; switchXY=0; dx=x2-x1\n dy=y2-y1\n if abs(dx)<abs(dy) then parse value x1 y1 x2 y2 dx dy with y1 x2 y2 x2 dy dx\n if x2<x1 then parse value x1 x2 y1 y2 1 with x2 x1 y2 y1 switchXY\n gradient=dy/dx\n xend=round(x1) /*◄─────────────────1st endpoint.══════════════*/\n yend=y1 + gradient * (xend-x1); xgap=1 - fpart(x1 + .5)\n xpx11=xend; ypx11=floor(yend)\n intery=yend+gradient\n call plotXY xpx11, ypx11, brite(1 - fpart(yend*xgap)), switchXY\n call plotXY xpx11, ypx11+1, brite( fpart(yend*xgap)), switchXY\n xend=round(x2) /*◄─────────────────2nd endpoint.══════════════*/\n yend=y2 + gradient * (xend-x2); xgap= fpart(x2 + .5)\n xpx12=xend; ypx12=floor(yend)\n call plotXY xpx12, ypx12 , brite(1 - fpart(yend*xgap)), switchXY\n call plotXY xpx12, ypx12+1, brite( fpart(yend*xgap)), switchXY\n\n do x=xpx11+1 to xpx12-1 /*◄═════════════════draw the line.═════════════*/\n !intery=floor(intery)\n call plotXY x, !intery , brite(1 - fpart(intery)), switchXY\n call plotXY x, !intery+1, brite( fpart(intery)), switchXY\n intery=intery + gradient\n end /*x*/\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nbrite: return substr(background || plotC, 1 + round( abs( arg(1) ) * length(plotC)), 1)\nfloor: parse arg #; _=trunc(#); return _ - (#<0) * (#\\=_)\nfpart: parse arg #; return abs(# - trunc(#) )\nround: return format(arg(1), , word(arg(2) 0, 1) )\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nplotXY: parse arg xx,yy,bc,switchYX; if switchYX then parse arg yy,xx\n image.xx.yy=bc; minX=min(minX, xx); maxX=max(maxX,xx)\n minY=min(minY, yy); maxY=max(maxY,yy); return\n", "language": "REXX" }, { "code": "def ipart(n); n.truncate; end\ndef fpart(n); n - ipart(n); end\ndef rfpart(n); 1.0 - fpart(n); end\n\nclass Pixmap\n def draw_line_antialised(p1, p2, colour)\n x1, y1 = p1.x, p1.y\n x2, y2 = p2.x, p2.y\n\n steep = (y2 - y1).abs > (x2 - x1).abs\n if steep\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n end\n if x1 > x2\n x1, x2 = x2, x1\n y1, y2 = y2, y1\n end\n deltax = x2 - x1\n deltay = (y2 - y1).abs\n gradient = 1.0 * deltay / deltax\n\n # handle the first endpoint\n xend = x1.round\n yend = y1 + gradient * (xend - x1)\n xgap = rfpart(x1 + 0.5)\n xpxl1 = xend\n ypxl1 = ipart(yend)\n put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap)\n put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap)\n itery = yend + gradient\n\n # handle the second endpoint\n xend = x2.round\n yend = y2 + gradient * (xend - x2)\n xgap = rfpart(x2 + 0.5)\n xpxl2 = xend\n ypxl2 = ipart(yend)\n put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap)\n put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap)\n\n # in between\n (xpxl1 + 1).upto(xpxl2 - 1).each do |x|\n put_colour(x, ipart(itery), colour, steep, rfpart(itery))\n put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery))\n itery = itery + gradient\n end\n end\n\n def put_colour(x, y, colour, steep, c)\n x, y = y, x if steep\n self[x, y] = anti_alias(colour, self[x, y], c)\n end\n\n def anti_alias(new, old, ratio)\n blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round}\n RGBColour.new(*blended)\n end\nend\n\nbitmap = Pixmap.new(500, 500)\nbitmap.fill(RGBColour::BLUE)\n10.step(430, 60) do |a|\n bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW)\n bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW)\nend\nbitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW)\n", "language": "Ruby" }, { "code": "import java.awt.Color\nimport math.{floor => ipart, round, abs}\n\ncase class Point(x: Double, y: Double) {def swap = Point(y, x)}\n\ndef plotter(bm: RgbBitmap, c: Color)(x: Double, y: Double, v: Double) = {\n val X = round(x).toInt\n val Y = round(y).toInt\n val V = v.toFloat\n // tint the existing pixels\n val c1 = c.getRGBColorComponents(null)\n val c2 = bm.getPixel(X, Y).getRGBColorComponents(null)\n val c3 = (c1 zip c2).map{case (n, o) => n * V + o * (1 - V)}\n bm.setPixel(X, Y, new Color(c3(0), c3(1), c3(2)))\n}\n\ndef drawLine(plotter: (Double,Double,Double) => _)(p1: Point, p2: Point) {\n def fpart(x: Double) = x - ipart(x)\n def rfpart(x: Double) = 1 - fpart(x)\n def avg(a: Float, b: Float) = (a + b) / 2\n\n val steep = abs(p2.y - p1.y) > abs(p2.x - p1.x)\n val (p3, p4) = if (steep) (p1.swap, p2.swap) else (p1, p2)\n val (a, b) = if (p3.x > p4.x) (p4, p3) else (p3, p4)\n val dx = b.x - a.x\n val dy = b.y - a.y\n val gradient = dy / dx\n var intery = 0.0\n\n def endpoint(xpxl: Double, yend: Double, xgap: Double) {\n val ypxl = ipart(yend)\n if (steep) {\n plotter(ypxl, xpxl, rfpart(yend) * xgap)\n plotter(ypxl+1, xpxl, fpart(yend) * xgap)\n } else {\n plotter(xpxl, ypxl , rfpart(yend) * xgap)\n plotter(xpxl, ypxl+1, fpart(yend) * xgap)\n }\n }\n\n // handle first endpoint\n var xpxl1 = round(a.x);\n {\n val yend = a.y + gradient * (xpxl1 - a.x)\n val xgap = rfpart(a.x + 0.5)\n endpoint(xpxl1, yend, xgap)\n intery = yend + gradient\n }\n\n // handle second endpoint\n val xpxl2 = round(b.x);\n {\n val yend = b.y + gradient * (xpxl2 - b.x)\n val xgap = fpart(b.x + 0.5)\n endpoint(xpxl2, yend, xgap)\n }\n\n // main loop\n for (x <- (xpxl1 + 1) to (xpxl2 - 1)) {\n if (steep) {\n plotter(ipart(intery) , x, rfpart(intery))\n plotter(ipart(intery)+1, x, fpart(intery))\n } else {\n plotter(x, ipart (intery), rfpart(intery))\n plotter(x, ipart (intery)+1, fpart(intery))\n }\n intery = intery + gradient\n }\n}\n", "language": "Scala" }, { "code": "val r = 120\nval img = new RgbBitmap(r*2+1, r*2+1)\nval line = drawLine(plotter(img, Color.GRAY)_)_\nimg.fill(Color.WHITE)\nfor (angle <- 0 to 360 by 30; θ = math toRadians angle; θ2 = θ + math.Pi) {\n val a = Point(r + r * math.sin(θ), r + r * math.cos(θ))\n val b = Point(r + r * math.sin(θ2), r + r * math.cos(θ2))\n line(a, b)\n}\njavax.imageio.ImageIO.write(img.image, \"png\", new java.io.File(\"XiaolinWuLineAlgorithm.png\"))\n", "language": "Scala" }, { "code": ";;;-------------------------------------------------------------------\n\n(import (scheme base))\n(import (scheme file))\n(import (scheme inexact))\n(import (scheme process-context))\n(import (scheme write))\n\n;; (srfi 160 f32) is more properly known as (scheme vector f32), but\n;; is not part of R7RS-small. The following will work in both Gauche\n;; and CHICKEN Schemes.\n(import (srfi 160 f32))\n\n;;;-------------------------------------------------------------------\n\n(define-record-type <color>\n (make-color r g b)\n color?\n (r color-r)\n (g color-g)\n (b color-b))\n\n;;; See https://yeun.github.io/open-color/\n(define violet9 (make-color (/ #x5F 255.0)\n (/ #x3D 255.0)\n (/ #xC4 255.0)))\n\n;;;-------------------------------------------------------------------\n\n(define-record-type <drawing-surface>\n (drawing-surface% u0 v0 u1 v1 pixels)\n drawing-surface?\n (u0 u0%)\n (v0 v0%)\n (u1 u1%)\n (v1 v1%)\n (pixels pixels%))\n\n(define (make-drawing-surface u0 v0 u1 v1)\n (unless (and (<= u0 u1) (<= v0 v1))\n (error \"illegal drawing-surface corners\"))\n (let ((width (- u1 u0 -1))\n (height (- v1 v0 -1)))\n (let ((pixels (make-f32vector (* width height) 0.0)))\n (drawing-surface% u0 v0 u1 v1 pixels))))\n\n;;; In calls to drawing-surface-ref and drawing-surface-set! indices\n;;; outside the drawing_surface are allowed. Such indices are treated\n;;; as if you were trying to draw on the air.\n\n(define (drawing-surface-ref s x y)\n (let ((u0 (u0% s))\n (v0 (v0% s))\n (u1 (u1% s))\n (v1 (v1% s)))\n (if (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (f32vector-ref (pixels% s)\n (+ (* (- x u0) (- v1 v0 -1)) (- v1 y)))\n +nan.0)))\n\n(define (drawing-surface-set! s x y opacity)\n (let ((u0 (u0% s))\n (v0 (v0% s))\n (u1 (u1% s))\n (v1 (v1% s)))\n (when (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (f32vector-set! (pixels% s)\n (+ (* (- x u0) (- v1 v0 -1)) (- v1 y))\n opacity))))\n\n(define (write-PAM s color)\n ;; Write a Portable Arbitrary Map to the current output port, using\n ;; the given color as the foreground color and the drawing-surface\n ;; values as opacities.\n\n (define (float->byte v) (exact (round (* 255 v))))\n\n (define r (float->byte (color-r color)))\n (define g (float->byte (color-g color)))\n (define b (float->byte (color-b color)))\n\n (define w (- (u1% s) (u0% s) -1))\n (define h (- (v1% s) (v0% s) -1))\n (define opacities (pixels% s))\n\n (define (loop x y)\n (cond ((= y h) )\n ((= x w) (loop 0 (+ y 1)))\n (else\n (let ((alpha (float->byte\n (f32vector-ref opacities (+ (* x h) y)))))\n (write-bytevector (bytevector r g b alpha))\n (loop (+ x 1) y)))))\n\n (display \"P7\") (newline)\n (display \"WIDTH \") (display (- (u1% s) (u0% s) -1)) (newline)\n (display \"HEIGHT \") (display (- (v1% s) (v0% s) -1)) (newline)\n (display \"DEPTH 4\") (newline)\n (display \"MAXVAL 255\") (newline)\n (display \"TUPLTYPE RGB_ALPHA\") (newline)\n (display \"ENDHDR\") (newline)\n (loop 0 0))\n\n;;;-------------------------------------------------------------------\n\n(define (ipart x) (exact (floor x)))\n(define (iround x) (ipart (+ x 0.5)))\n(define (fpart x) (- x (floor x)))\n(define (rfpart x) (- 1.0 (fpart x)))\n\n(define (plot s x y opacity)\n ;; One might prefer a more sophisticated function than mere\n ;; addition. Here, however, the function is addition.\n (let ((combined-opacity (+ opacity (drawing-surface-ref s x y))))\n (drawing-surface-set! s x y (min combined-opacity 1.0))))\n\n(define (drawln% s x0 y0 x1 y1 steep)\n (let* ((dx (- x1 x0))\n (dy (- y1 y0))\n (gradient (if (zero? dx) 1.0 (/ dy dx)))\n\n ;; Handle the first endpoint.\n (xend (iround x0))\n (yend (+ y0 (* gradient (- xend x0))))\n (xgap (rfpart (+ x0 0.5)))\n (xpxl1 xend)\n (ypxl1 (ipart yend))\n (_ (if steep\n (begin\n (plot s ypxl1 xpxl1 (* (rfpart yend) xgap))\n (plot s (+ ypxl1 1) xpxl1 (* (fpart yend) xgap)))\n (begin\n (plot s xpxl1 ypxl1 (* (rfpart yend) xgap))\n (plot s xpxl1 (+ ypxl1 1) (* (fpart yend) xgap)))))\n\n ;; The first y-intersection.\n (intery (+ yend gradient))\n\n ;; Handle the second endpoint.\n (xend (iround x1))\n (yend (+ y1 (* gradient (- xend x1))))\n (xgap (fpart (+ x1 0.5)))\n (xpxl2 xend)\n (ypxl2 (ipart yend))\n (_ (if steep\n (begin\n (plot s ypxl2 xpxl2 (* (rfpart yend) xgap))\n (plot s (+ ypxl2 1) xpxl2 (* (fpart yend) xgap)))\n (begin\n (plot s xpxl2 ypxl2 (* (rfpart yend) xgap))\n (plot s xpxl2 (+ ypxl2 1) (* (fpart yend) xgap))))))\n\n ;; Loop over the rest of the points.\n (if steep\n (do ((x (+ xpxl1 1) (+ x 1))\n (intery intery (+ intery gradient)))\n ((= x xpxl2))\n (plot s (ipart intery) x (rfpart intery))\n (plot s (+ (ipart intery) 1) x (fpart intery)))\n (do ((x (+ xpxl1 1) (+ x 1))\n (intery intery (+ intery gradient)))\n ((= x xpxl2))\n (plot s x (ipart intery) (rfpart intery))\n (plot s x (+ (ipart intery) 1) (fpart intery))))))\n\n(define (draw-line s x0 y0 x1 y1)\n (let ((xdiff (abs (- x1 x0)))\n (ydiff (abs (- y1 y0))))\n (if (<= ydiff xdiff)\n (if (<= x0 x1)\n ;; R7RS lets you say #false and #true, as equivalents of\n ;; #f and #t. (To support such things as #false and #true,\n ;; the \"r7rs\" egg for CHICKEN Scheme 5 comes with a\n ;; special reader.)\n (drawln% s x0 y0 x1 y1 #false)\n (drawln% s x1 y1 x0 y0 #false))\n (if (<= y0 y1)\n (drawln% s y0 x0 y1 x1 #true)\n (drawln% s y1 x1 y0 x0 #true)))))\n\n;;;-------------------------------------------------------------------\n\n(define u0 0)\n(define v0 0)\n(define u1 999)\n(define v1 749)\n\n(define PI (* 4.0 (atan 1.0)))\n(define PI/180 (/ PI 180.0))\n\n(define (cosdeg theta) (cos (* theta PI/180)))\n(define (sindeg theta) (sin (* theta PI/180)))\n\n(define s (make-drawing-surface u0 v0 u1 v1))\n\n;; The values of theta are exactly representable in either binary or\n;; decimal floating point, and therefore the following loop will NOT\n;; do the angle zero twice. (If you might stray from exact\n;; representations, you must do something different, such as increment\n;; an integer.)\n(let ((x0 (inexact (* (/ 380 640) u1)))\n (y0 (inexact (* (/ 130 480) v1))))\n (do ((theta 0.0 (+ theta 5.0)))\n ((<= 360.0 theta))\n (let ((cos-theta (cosdeg theta))\n (sin-theta (sindeg theta)))\n (let ((x1 (+ x0 (* cos-theta 1200.0)))\n (y1 (+ y0 (* sin-theta 1200.0))))\n (draw-line s x0 y0 x1 y1)))))\n\n(define args (command-line))\n(unless (= (length args) 2)\n (parameterize ((current-output-port (current-error-port)))\n (display (string-append \"Usage: \" (car args) \" FILENAME\"))\n (newline)\n (display (string-append \" \" (car args) \" -\"))\n (newline) (newline)\n (display (string-append \"The second form writes the PAM file\"\n \" to standard output.\"))\n (newline)\n (exit 1)))\n(if (string=? (cadr args) \"-\")\n (write-PAM s violet9)\n (with-output-to-file (list-ref args 1)\n (lambda () (write-PAM s violet9))))\n\n;;;-------------------------------------------------------------------\n", "language": "Scheme" }, { "code": ";;;-------------------------------------------------------------------\n\n(import (scheme base))\n(import (scheme file))\n(import (scheme inexact))\n(import (scheme process-context))\n(import (scheme write))\n\n;; (srfi 160 f32) is more properly known as (scheme vector f32), but\n;; is not part of R7RS-small. The following will work in both Gauche\n;; and CHICKEN Schemes.\n(import (srfi 160 f32))\n\n;;;-------------------------------------------------------------------\n\n(define-record-type <color>\n (make-color r g b)\n color?\n (r color-r)\n (g color-g)\n (b color-b))\n\n;;; See https://yeun.github.io/open-color/\n(define violet9 (make-color (/ #x5F 255.0)\n (/ #x3D 255.0)\n (/ #xC4 255.0)))\n\n;;;-------------------------------------------------------------------\n\n(define-record-type <drawing-surface>\n (drawing-surface% u0 v0 u1 v1 pixels)\n drawing-surface?\n (u0 u0%)\n (v0 v0%)\n (u1 u1%)\n (v1 v1%)\n (pixels pixels%))\n\n(define (make-drawing-surface u0 v0 u1 v1)\n (unless (and (<= u0 u1) (<= v0 v1))\n (error \"illegal drawing-surface corners\"))\n (let ((width (- u1 u0 -1))\n (height (- v1 v0 -1)))\n (let ((pixels (make-f32vector (* width height) 0.0)))\n (drawing-surface% u0 v0 u1 v1 pixels))))\n\n;;; In calls to drawing-surface-ref and drawing-surface-set! indices\n;;; outside the drawing_surface are allowed. Such indices are treated\n;;; as if you were trying to draw on the air.\n\n(define (drawing-surface-ref s x y)\n (let ((u0 (u0% s))\n (v0 (v0% s))\n (u1 (u1% s))\n (v1 (v1% s)))\n (if (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (f32vector-ref (pixels% s)\n (+ (* (- x u0) (- v1 v0 -1)) (- v1 y)))\n +nan.0)))\n\n(define (drawing-surface-set! s x y opacity)\n (let ((u0 (u0% s))\n (v0 (v0% s))\n (u1 (u1% s))\n (v1 (v1% s)))\n (when (and (<= u0 x) (<= x u1) (<= v0 y) (<= y v1))\n (f32vector-set! (pixels% s)\n (+ (* (- x u0) (- v1 v0 -1)) (- v1 y))\n opacity))))\n\n(define (write-PAM s color)\n ;; Write a Portable Arbitrary Map to the current output port, using\n ;; the given color as the foreground color and the drawing-surface\n ;; values as opacities.\n\n (define (float->byte v) (exact (round (* 255 v))))\n\n (define r (float->byte (color-r color)))\n (define g (float->byte (color-g color)))\n (define b (float->byte (color-b color)))\n\n (define w (- (u1% s) (u0% s) -1))\n (define h (- (v1% s) (v0% s) -1))\n (define opacities (pixels% s))\n\n (define (loop x y)\n (cond ((= y h) )\n ((= x w) (loop 0 (+ y 1)))\n (else\n (let ((alpha (float->byte\n (f32vector-ref opacities (+ (* x h) y)))))\n (write-bytevector (bytevector r g b alpha))\n (loop (+ x 1) y)))))\n\n (display \"P7\") (newline)\n (display \"WIDTH \") (display (- (u1% s) (u0% s) -1)) (newline)\n (display \"HEIGHT \") (display (- (v1% s) (v0% s) -1)) (newline)\n (display \"DEPTH 4\") (newline)\n (display \"MAXVAL 255\") (newline)\n (display \"TUPLTYPE RGB_ALPHA\") (newline)\n (display \"ENDHDR\") (newline)\n (loop 0 0))\n\n;;;-------------------------------------------------------------------\n\n(define-syntax ipart\n (syntax-rules ()\n ((_ x) (exact (floor x)))))\n\n(define-syntax iround\n (syntax-rules ()\n ((_ x) (ipart (+ x 0.5)))))\n\n(define-syntax fpart\n (syntax-rules ()\n ((_ x) (- x (floor x)))))\n\n(define-syntax rfpart\n (syntax-rules ()\n ((_ x) (- 1.0 (fpart x)))))\n\n(define-syntax plot-shallow\n (syntax-rules ()\n ((_ s x y opacity)\n ;; One might prefer a more sophisticated function than mere\n ;; addition. Here, however, the function is addition.\n (let ((combined-opacity (+ opacity (drawing-surface-ref s x y))))\n (drawing-surface-set! s x y (min combined-opacity 1.0))))))\n\n(define-syntax plot-steep\n (syntax-rules ()\n ((_ s x y opacity)\n (plot-shallow s y x opacity))))\n\n(define-syntax drawln%\n (syntax-rules ()\n ((_ s x0 y0 x1 y1 plot)\n (let* ((dx (- x1 x0))\n (dy (- y1 y0))\n (gradient (if (zero? dx) 1.0 (/ dy dx)))\n\n ;; Handle the first endpoint.\n (xend (iround x0))\n (yend (+ y0 (* gradient (- xend x0))))\n (xgap (rfpart (+ x0 0.5)))\n (xpxl1 xend)\n (ypxl1 (ipart yend))\n (_ (plot s xpxl1 ypxl1 (* (rfpart yend) xgap)))\n (_ (plot s xpxl1 (+ ypxl1 1) (* (fpart yend) xgap)))\n\n ;; The first y-intersection.\n (intery (+ yend gradient))\n\n ;; Handle the second endpoint.\n (xend (iround x1))\n (yend (+ y1 (* gradient (- xend x1))))\n (xgap (fpart (+ x1 0.5)))\n (xpxl2 xend)\n (ypxl2 (ipart yend))\n (_ (plot s xpxl2 ypxl2 (* (rfpart yend) xgap)))\n (_ (plot s xpxl2 (+ ypxl2 1) (* (fpart yend) xgap))))\n\n ;; Loop over the rest of the points.\n (do ((x (+ xpxl1 1) (+ x 1))\n (intery intery (+ intery gradient)))\n ((= x xpxl2))\n (plot s x (ipart intery) (rfpart intery))\n (plot s x (+ (ipart intery) 1) (fpart intery)))))))\n\n(define (draw-line s x0 y0 x1 y1)\n (let ((xdiff (abs (- x1 x0)))\n (ydiff (abs (- y1 y0))))\n (if (<= ydiff xdiff)\n (if (<= x0 x1)\n (drawln% s x0 y0 x1 y1 plot-shallow)\n (drawln% s x1 y1 x0 y0 plot-shallow))\n (if (<= y0 y1)\n (drawln% s y0 x0 y1 x1 plot-steep)\n (drawln% s y1 x1 y0 x0 plot-steep)))))\n\n;;;-------------------------------------------------------------------\n\n(define u0 0)\n(define v0 0)\n(define u1 999)\n(define v1 749)\n\n(define PI (* 4.0 (atan 1.0)))\n(define PI/180 (/ PI 180.0))\n\n(define (cosdeg theta) (cos (* theta PI/180)))\n(define (sindeg theta) (sin (* theta PI/180)))\n\n(define s (make-drawing-surface u0 v0 u1 v1))\n\n;; The values of theta are exactly representable in either binary or\n;; decimal floating point, and therefore the following loop will NOT\n;; do the angle zero twice. (If you might stray from exact\n;; representations, you must do something different, such as increment\n;; an integer.)\n(let ((x0 (inexact (* (/ 380 640) u1)))\n (y0 (inexact (* (/ 130 480) v1))))\n (do ((theta 0.0 (+ theta 5.0)))\n ((<= 360.0 theta))\n (let ((cos-theta (cosdeg theta))\n (sin-theta (sindeg theta)))\n (let ((x1 (+ x0 (* cos-theta 1200.0)))\n (y1 (+ y0 (* sin-theta 1200.0))))\n (draw-line s x0 y0 x1 y1)))))\n\n(define args (command-line))\n(unless (= (length args) 2)\n (parameterize ((current-output-port (current-error-port)))\n (display (string-append \"Usage: \" (car args) \" FILENAME\"))\n (newline)\n (display (string-append \" \" (car args) \" -\"))\n (newline) (newline)\n (display (string-append \"The second form writes the PAM file\"\n \" to standard output.\"))\n (newline)\n (exit 1)))\n(if (string=? (cadr args) \"-\")\n (write-PAM s violet9)\n (with-output-to-file (list-ref args 1)\n (lambda () (write-PAM s violet9))))\n\n;;;-------------------------------------------------------------------\n", "language": "Scheme" }, { "code": "func plot(x, y, c) {\n c && printf(\"plot %d %d %.1f\\n\", x, y, c);\n}\n\nfunc fpart(x) {\n x - int(x);\n}\n\nfunc rfpart(x) {\n 1 - fpart(x);\n}\n\nfunc drawLine(x0, y0, x1, y1) {\n\n var p = plot;\n if (abs(y1 - y0) > abs(x1 - x0)) {\n p = {|arg| plot(arg[1, 0, 2]) };\n (x0, y0, x1, y1) = (y0, x0, y1, x1);\n }\n\n if (x0 > x1) {\n (x0, x1, y0, y1) = (x1, x0, y1, y0);\n }\n\n var dx = (x1 - x0);\n var dy = (y1 - y0);\n var gradient = (dy / dx);\n\n var xends = [];\n var intery;\n\n # handle the endpoints\n for x,y in [[x0, y0], [x1, y1]] {\n var xend = int(x + 0.5);\n var yend = (y + gradient*(xend-x));\n var xgap = rfpart(x + 0.5);\n\n var x_pixel = xend;\n var y_pixel = yend.int;\n xends << x_pixel;\n\n p.call(x_pixel, y_pixel , rfpart(yend) * xgap);\n p.call(x_pixel, y_pixel+1, fpart(yend) * xgap);\n defined(intery) && next;\n\n # first y-intersection for the main loop\n intery = (yend + gradient);\n }\n\n # main loop\n range(xends[0]+1, xends[1]-1).each { |x|\n p.call(x, intery.int, rfpart(intery));\n p.call(x, intery.int+1, fpart(intery));\n intery += gradient;\n }\n}\n\ndrawLine(0, 1, 10, 2);\n", "language": "Sidef" }, { "code": "import Darwin\n// apply pixel of color at x,y with an OVER blend to the bitmap\npublic func pixel(color: Color, x: Int, y: Int) {\n let idx = x + y * self.width\n if idx >= 0 && idx < self.bitmap.count {\n self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color)\n }\n}\n\n// return the fractional part of a Double\nfunc fpart(_ x: Double) -> Double {\n return modf(x).1\n}\n\n// reciprocal of the fractional part of a Double\nfunc rfpart(_ x: Double) -> Double {\n return 1 - fpart(x)\n}\n\n// draw a 1px wide line using Xiolin Wu's antialiased line algorithm\npublic func smoothLine(_ p0: Point, _ p1: Point) {\n var x0 = p0.x, x1 = p1.x, y0 = p0.y, y1 = p1.y //swapable ptrs\n let steep = abs(y1 - y0) > abs(x1 - x0)\n if steep {\n swap(&x0, &y0)\n swap(&x1, &y1)\n }\n if x0 > x1 {\n swap(&x0, &x1)\n swap(&y0, &y1)\n }\n let dX = x1 - x0\n let dY = y1 - y0\n\n var gradient: Double\n if dX == 0.0 {\n gradient = 1.0\n }\n else {\n gradient = dY / dX\n }\n\n // handle endpoint 1\n var xend = round(x0)\n var yend = y0 + gradient * (xend - x0)\n var xgap = self.rfpart(x0 + 0.5)\n let xpxl1 = Int(xend)\n let ypxl1 = Int(yend)\n\n // first y-intersection for the main loop\n var intery = yend + gradient\n\n if steep {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl1, y: xpxl1)\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl1 + 1, y: xpxl1)\n }\n else {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl1, y: ypxl1)\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl1, y: ypxl1 + 1)\n }\n\n xend = round(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = self.fpart(x1 + 0.5)\n let xpxl2 = Int(xend)\n let ypxl2 = Int(yend)\n\n // handle second endpoint\n if steep {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl2, y: xpxl2)\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl2 + 1, y: xpxl2)\n }\n else {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl2, y: ypxl2)\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl2, y: ypxl2 + 1)\n }\n\n // main loop\n if steep {\n for x in xpxl1+1..<xpxl2 {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: Int(intery), y: x)\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: Int(intery) + 1, y:x)\n intery += gradient\n }\n }\n else {\n for x in xpxl1+1..<xpxl2 {\n self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(intery)), x: x, y: Int(intery))\n self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(intery)), x: x, y: Int(intery) + 1)\n intery += gradient\n }\n }\n}\n", "language": "Swift" }, { "code": "package require Tcl 8.5\npackage require Tk\n\nproc ::tcl::mathfunc::ipart x {expr {int($x)}}\nproc ::tcl::mathfunc::fpart x {expr {$x - int($x)}}\nproc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}}\n\nproc drawAntialiasedLine {image colour p1 p2} {\n lassign $p1 x1 y1\n lassign $p2 x2 y2\n\n set steep [expr {abs($y2 - $y1) > abs($x2 - $x1)}]\n if {$steep} {\n lassign [list $x1 $y1] y1 x1\n lassign [list $x2 $y2] y2 x2\n }\n if {$x1 > $x2} {\n lassign [list $x1 $x2] x2 x1\n lassign [list $y1 $y2] y2 y1\n }\n set deltax [expr {$x2 - $x1}]\n set deltay [expr {abs($y2 - $y1)}]\n set gradient [expr {1.0 * $deltay / $deltax}]\n\n # handle the first endpoint\n set xend [expr {round($x1)}]\n set yend [expr {$y1 + $gradient * ($xend - $x1)}]\n set xgap [expr {rfpart($x1 + 0.5)}]\n set xpxl1 $xend\n set ypxl1 [expr {ipart($yend)}]\n plot $image $colour $steep $xpxl1 $ypxl1 [expr {rfpart($yend)*$xgap}]\n plot $image $colour $steep $xpxl1 [expr {$ypxl1+1}] [expr {fpart($yend)*$xgap}]\n set itery [expr {$yend + $gradient}]\n\n # handle the second endpoint\n set xend [expr {round($x2)}]\n set yend [expr {$y2 + $gradient * ($xend - $x2)}]\n set xgap [expr {rfpart($x2 + 0.5)}]\n set xpxl2 $xend\n set ypxl2 [expr {ipart($yend)}]\n plot $image $colour $steep $xpxl2 $ypxl2 [expr {rfpart($yend)*$xgap}]\n plot $image $colour $steep $xpxl2 [expr {$ypxl2+1}] [expr {fpart($yend)*$xgap}]\n\n for {set x [expr {$xpxl1 + 1}]} {$x < $xpxl2} {incr x} {\n plot $image $colour $steep $x [expr {ipart($itery)}] [expr {rfpart($itery)}]\n plot $image $colour $steep $x [expr {ipart($itery) + 1}] [expr {fpart($itery)}]\n set itery [expr {$itery + $gradient}]\n }\n}\n\nproc plot {image colour steep x y c} {\n set point [expr {$steep ? [list $y $x] : [list $x $y]}]\n set newColour [antialias $colour [getPixel $image $point] $c]\n setPixel $image $newColour $point\n}\n\nproc antialias {newColour oldColour c} {\n # get the new colour r,g,b\n if {[scan $newColour \"#%2x%2x%2x%c\" nr ng gb -] != 3} {\n scan [colour2rgb $newColour] \"#%2x%2x%2x\" nr ng nb\n }\n\n # get the current colour r,g,b\n scan $oldColour \"#%2x%2x%2x\" cr cg cb\n\n # blend the colours in the ratio defined by \"c\"\n foreach new [list $nr $ng $nb] curr [list $cr $cg $cb] {\n append blend [format {%02x} [expr {round($new*$c + $curr*(1.0-$c))}]]\n }\n return #$blend\n}\n\nproc colour2rgb {color_name} {\n foreach part [winfo rgb . $color_name] {\n append colour [format %02x [expr {$part >> 8}]]\n }\n return #$colour\n}\n\nset img [newImage 500 500]\nfill $img blue\nfor {set a 10} {$a < 500} {incr a 60} {\n drawAntialiasedLine $img yellow {10 10} [list 490 $a]\n drawAntialiasedLine $img yellow {10 10} [list $a 490]\n}\ntoplevel .wu\nlabel .wu.l -image $img\npack .wu.l\n", "language": "Tcl" }, { "code": "import \"graphics\" for Canvas, Color\nimport \"dome\" for Window\nimport \"math\" for Math\n\nclass XiaolinWu {\n construct new(width, height) {\n Window.title = \"Xiaolin Wu's line algorithm\"\n Window.resize(width, height)\n Canvas.resize(width, height)\n }\n\n init() {\n Canvas.cls(Color.white)\n drawLine(550, 170, 50, 435)\n }\n\n plot(x, y, c) {\n var col = Color.rgb(0, 0, 0, c * 255)\n x = ipart(x)\n y = ipart(y)\n Canvas.ellipsefill(x, y, x + 2, y + 2, col)\n }\n\n ipart(x) { x.truncate }\n\n fpart(x) { x.fraction }\n\n rfpart(x) { 1 - fpart(x) }\n\n drawLine(x0, y0, x1, y1) {\n var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)\n if (steep) drawLine(y0, x0, y1, x1)\n if (x0 > x1) drawLine(x1, y1, x0, y0)\n var dx = x1 - x0\n var dy = y1 - y0\n var gradient = dy / dx\n\n // handle first endpoint\n var xend = Math.round(x0)\n var yend = y0 + gradient * (xend - x0)\n var xgap = rfpart(x0 + 0.5)\n var xpxl1 = xend // this will be used in the main loop\n var ypxl1 = ipart(yend)\n\n if (steep) {\n plot(ypxl1, xpxl1, rfpart(yend) * xgap)\n plot(ypxl1 + 1, xpxl1, fpart(yend) * xgap)\n } else {\n plot(xpxl1, ypxl1, rfpart(yend) * xgap)\n plot(xpxl1, ypxl1 + 1, fpart(yend) * xgap)\n }\n\n // first y-intersection for the main loop\n var intery = yend + gradient\n\n // handle second endpoint\n xend = Math.round(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = fpart(x1 + 0.5)\n var xpxl2 = xend // this will be used in the main loop\n var ypxl2 = ipart(yend)\n\n if (steep) {\n plot(ypxl2, xpxl2, rfpart(yend) * xgap)\n plot(ypxl2 + 1, xpxl2, fpart(yend) * xgap)\n } else {\n plot(xpxl2, ypxl2, rfpart(yend) * xgap)\n plot(xpxl2, ypxl2 + 1, fpart(yend) * xgap)\n }\n\n // main loop\n var x = xpxl1 + 1\n while (x <= xpxl2 - 1) {\n if (steep) {\n plot(ipart(intery), x, rfpart(intery))\n plot(ipart(intery) + 1, x, fpart(intery))\n } else {\n plot(x, ipart(intery), rfpart(intery))\n plot(x, ipart(intery) + 1, fpart(intery))\n }\n intery = intery + gradient\n x = x + 1\n }\n }\n\n update() {}\n\n draw(alpha) {}\n}\n\nvar Game = XiaolinWu.new(640, 640)\n", "language": "Wren" }, { "code": "bresline = false // space toggles, for comparison\n\nrB = 255 : gB = 255 : bB = 224\nrL = 0 : gL = 0 : bL = 255\n\nsub round(x)\n return int(x + .5)\nend sub\n\nsub plot(x, y, c, steep)\n// plot the pixel at (x, y) with brightness c (where 0 <= c <= 1)\n\n local t, C\n\n if steep then t = x : x = y : y = t end if\n C = 1 - c\n color rL * c + rB * C, gL * c + gB * C, bL * c + bB * C\n\n dot x, y\nend sub\n\nsub plot2(x, y, f, xgap, steep)\n plot(x, y, (1 - f) * xgap, steep)\n plot(x, y + 1, f * xgap, steep)\nend sub\n\nsub draw_line(x0, y0, x1, y1)\n local steep, t, dx, dy, gradient, xend, yend, xgap, xpxl1, ypxl1, xpxl2, ypxl2, intery\n\n if bresline then\n line x0, y0, x1, y1\n return\n end if\n steep = abs(y1 - y0) > abs(x1 - x0)\n if steep then\n t = x0 : x0 = y0 : y0 = t\n t = x1 : x1 = y1 : y1 = t\n end if\n if x0 > x1 then\n t = x0 : x0 = x1 : x1 = t\n t = y0 : y0 = y1 : y1 = t\n end if\n\n dx = x1 - x0\n dy = y1 - y0\n if dx = 0 then\n gradient = 1\n else\n gradient = dy / dx\n end if\n\n // handle first endpoint\n xend = round(x0)\n yend = y0 + gradient * (xend - x0)\n xgap = 1 - frac(x0 + 0.5)\n xpxl1 = xend // this will be used in the main loop\n ypxl1 = int(yend)\n plot2(xpxl1, ypxl1, frac(yend), xgap, steep)\n intery = yend + gradient // first y-intersection for the main loop\n\n // handle second endpoint\n xend = round(x1)\n yend = y1 + gradient * (xend - x1)\n xgap = frac(x1 + 0.5)\n xpxl2 = xend // this will be used in the main loop\n ypxl2 = int(yend)\n plot2(xpxl2, ypxl2, frac(yend), xgap, steep)\n\n // main loop\n for x = xpxl1 + 1 to xpxl2 - 1\n plot2(x, int(intery), frac(intery), 1, steep)\n intery = intery + gradient\n next x\nend sub\n\nw = 640 : h = 480\nopen window w, h\n\ncolor 0, 0, 255\n\ndraw_line(0, 0, 200, 200)\ndraw_line(w, 0, 200, 200)\ndraw_line(0, h, 200, 200)\ndraw_line(w, h, 200, 200)\n", "language": "Yabasic" } ]
Xiaolin-Wus-line-algorithm
[ { "code": "---\nfrom: http://rosettacode.org/wiki/XML/Input\nnote: XML\n", "language": "00-META" }, { "code": "Given the following XML fragment, extract the list of ''student names'' using whatever means desired. If the only viable method is to use XPath, refer the reader to the task [[XML and XPath]].\n\n<syntaxhighlight lang=\"xml\"><Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students></syntaxhighlight>\n\nExpected Output\n\n April\n Bob\n Chad\n Dave\n Émily\n\n", "language": "00-TASK" }, { "code": "\\ Load the XML text into the var 'x':\nquote *\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n* xml:parse var, x\n\n\\ print only xml nodes which have a tag of 'Student' and whose attributes are not empty\n: .xml \\ xml --\n\txml:tag@ \"Student\" s:cmp if drop ;; then\n\txml:attrs null? if drop ;; then\n\n\t\"Name\" m:@ . cr drop ;\n\n\\ Iterate over the XML document in the var 'x'\nx @ ' .xml xml:each bye\n", "language": "8th" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program inputXml64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n/* program constantes */\n.equ XML_ELEMENT_NODE, 1\n.equ XML_ATTRIBUTE_NODE, 2\n .equ XML_TEXT_NODE, 3\n.equ XML_CDATA_SECTION_NODE, 4\n.equ XML_ENTITY_REF_NODE, 5\n.equ XML_ENTITY_NODE, 6\n.equ XML_PI_NODE, 7\n.equ XML_COMMENT_NODE, 8\n.equ XML_DOCUMENT_NODE, 9\n.equ XML_DOCUMENT_TYPE_NODE, 10\n.equ XML_DOCUMENT_FRAG_NODE, 11\n.equ XML_NOTATION_NODE, 12\n.equ XML_HTML_DOCUMENT_NODE, 13\n.equ XML_DTD_NODE, 14\n.equ XML_ELEMENT_DECL, 15\n.equ XML_ATTRIBUTE_DECL, 16\n.equ XML_ENTITY_DECL, 17\n.equ XML_NAMESPACE_DECL, 18\n.equ XML_XINCLUDE_START, 19\n.equ XML_XINCLUDE_END, 20\n.equ XML_DOCB_DOCUMENT_NODE, 21\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structure xmlNode */\n .struct 0\nxmlNode_private: // application data\n .struct xmlNode_private + 8\nxmlNode_type: // type number, must be second !\n .struct xmlNode_type + 8\nxmlNode_name: // the name of the node, or the entity\n .struct xmlNode_name + 8\nxmlNode_children: // parent->childs link\n .struct xmlNode_children + 8\nxmlNode_last: // last child link\n .struct xmlNode_last + 8\nxmlNode_parent: // child->parent link\n .struct xmlNode_parent + 8\nxmlNode_next: // next sibling link\n .struct xmlNode_next + 8\nxmlNode_prev: // previous sibling link\n .struct xmlNode_prev + 8\nxmlNode_doc: // the containing document\n .struct xmlNode_doc + 8\nxmlNode_ns: // pointer to the associated namespace\n .struct xmlNode_ns + 8\nxmlNode_content: // the content\n .struct xmlNode_content + 8\nxmlNode_properties: // properties list\n .struct xmlNode_properties + 8\nxmlNode_nsDef: // namespace definitions on this node\n .struct xmlNode_nsDef + 8\nxmlNode_psvi: // for type/PSVI informations\n .struct xmlNode_psvi + 8\nxmlNode_line: // line number\n .struct xmlNode_line + 4\nxmlNode_extra: // extra data for XPath/XSLT\n .struct xmlNode_extra + 4\nxmlNode_fin:\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"Normal end of program.\\n\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszText: .ascii \"<Students>\\n\"\n .ascii \"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\n .ascii \"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\n .ascii \"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\n .ascii \"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\n .ascii \"<Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\n .ascii \"</Student>\\n\"\n .ascii \"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\n .asciz \"</Students>\"\n.equ LGSZTEXT, . - szText // compute text size (. is current address)\n\nszLibExtract: .asciz \"Student\"\nszLibName: .asciz \"Name\"\nszCarriageReturn: .asciz \"\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrszText // text buffer\n mov x1,#LGSZTEXT // text size\n mov x2,#0 // param 3\n mov x3,#0 // param 4\n mov x4,#0 // param 5\n bl xmlReadMemory // read text in document\n cmp x0,#0 // error ?\n beq 99f\n mov x19,x0 // doc address\n mov x0,x19\n bl xmlDocGetRootElement // search root return in x0\n bl affElement // display elements\n mov x0,x19\n bl xmlFreeDoc\n\n bl xmlCleanupParser\n ldr x0,qAdrszMessEndpgm\n bl affichageMess\n b 100f\n99: // error\n ldr x0,qAdrszMessError\n bl affichageMess\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n\nqAdrszMessError: .quad szMessError\nqAdrszMessEndpgm: .quad szMessEndpgm\nqAdrszText: .quad szText\nqAdrszCarriageReturn: .quad szCarriageReturn\n\n/******************************************************************/\n/* display name of student */\n/******************************************************************/\n/* x0 contains the address of node */\naffElement:\n stp x24,lr,[sp,-16]! // save registers\n mov x24,x0 // save node\n1:\n ldr x12,[x24,#xmlNode_type] // type ?\n cmp x12,#XML_ELEMENT_NODE\n bne 2f\n ldr x0,[x24,#xmlNode_name] // name = \"Student\" ?\n ldr x1,qAdrszLibExtract\n bl comparString\n cmp x0,#0\n bne 2f // no\n mov x0,x24\n ldr x1,qAdrszLibName // load property of \"Name\"\n bl xmlHasProp\n cmp x0,#0\n beq 2f\n ldr x1,[x0,#xmlNode_children] // children node of property name\n ldr x0,[x1,#xmlNode_content] // and address of content\n bl affichageMess // for display\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n2:\n ldr x0,[x24,#xmlNode_children] // node have children ?\n cbz x0,3f\n bl affElement // yes -> call procedure\n3:\n ldr x1,[x24,#xmlNode_next] // other element ?\n cmp x1,#0\n beq 100f // no -> end procedure\n\n mov x24,x1 // else loop with next element\n b 1b\n\n100:\n ldp x24,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszLibName: .quad szLibName\nqAdrszLibExtract: .quad szLibExtract\n/************************************/\n/* Strings comparaison */\n/************************************/\n/* x0 et x1 contains strings addresses */\n/* x0 return 0 dans x0 if equal */\n/* return -1 if string x0 < string x1 */\n/* return 1 if string x0 > string x1 */\ncomparString:\n stp x2,lr,[sp,-16]! // save registers\n stp x3,x4,[sp,-16]! // save registers\n mov x2,#0 // indice\n1:\n ldrb w3,[x0,x2] // one byte string 1\n ldrb w4,[x1,x2] // one byte string 2\n cmp w3,w4\n blt 2f // less\n bgt 3f // greather\n cmp w3,#0 // 0 final\n beq 4f // equal and end\n add x2,x2,#1 //\n b 1b // else loop\n2:\n mov x0,#-1 // less\n b 100f\n3:\n mov x0,#1 // greather\n b 100f\n4:\n mov x0,#0 // equal\n b 100f\n100:\n ldp x3,x4,[sp],16 // restaur 2 registers\n ldp x2,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "package\n{\n import flash.display.Sprite;\n\n public class XMLReading extends Sprite\n {\n public function XMLReading()\n {\n var xml:XML = <Students>\n <Student Name=\"April\" />\n <Student Name=\"Bob\" />\n <Student Name=\"Chad\" />\n <Student Name=\"Dave\" />\n <Student Name=\"Emily\" />\n </Students>;\n for each(var node:XML in xml..Student)\n {\n trace(node.@Name);\n }\n }\n }\n}\n", "language": "ActionScript" }, { "code": "with Sax.Readers;\nwith Input_Sources.Strings;\nwith Unicode.CES.Utf8;\nwith My_Reader;\n\nprocedure Extract_Students is\n Sample_String : String :=\n\"<Students>\" &\n \"<Student Name=\"\"April\"\" Gender=\"\"F\"\" DateOfBirth=\"\"1989-01-02\"\" />\" &\n \"<Student Name=\"\"Bob\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1990-03-04\"\" />\" &\n \"<Student Name=\"\"Chad\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1991-05-06\"\" />\" &\n \"<Student Name=\"\"Dave\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1992-07-08\"\">\" &\n \"<Pet Type=\"\"dog\"\" Name=\"\"Rover\"\" />\" &\n \"</Student>\" &\n \"<Student DateOfBirth=\"\"1993-09-10\"\" Gender=\"\"F\"\" Name=\"\"&#x00C9;mily\"\" />\" &\n\"</Students>\";\n Reader : My_Reader.Reader;\n Input : Input_Sources.Strings.String_Input;\nbegin\n Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input);\n My_Reader.Parse (Reader, Input);\n Input_Sources.Strings.Close (Input);\nend Extract_Students;\n", "language": "Ada" }, { "code": "with Sax.Attributes;\nwith Sax.Readers;\nwith Unicode.CES;\npackage My_Reader is\n type Reader is new Sax.Readers.Reader with null record;\n procedure Start_Element\n (Handler : in out Reader;\n Namespace_URI : Unicode.CES.Byte_Sequence := \"\";\n Local_Name : Unicode.CES.Byte_Sequence := \"\";\n Qname : Unicode.CES.Byte_Sequence := \"\";\n Atts : Sax.Attributes.Attributes'Class);\nend My_Reader;\n", "language": "Ada" }, { "code": "with Ada.Text_IO;\npackage body My_Reader is\n procedure Start_Element\n (Handler : in out Reader;\n Namespace_URI : Unicode.CES.Byte_Sequence := \"\";\n Local_Name : Unicode.CES.Byte_Sequence := \"\";\n Qname : Unicode.CES.Byte_Sequence := \"\";\n Atts : Sax.Attributes.Attributes'Class) is\n begin\n if Local_Name = \"Student\" then\n Ada.Text_IO.Put_Line (Sax.Attributes.Get_Value (Atts, \"Name\"));\n end if;\n end Start_Element;\nend My_Reader;\n", "language": "Ada" }, { "code": "with Ada.Text_IO;\nwith Sax.Readers;\nwith Input_Sources.Strings;\nwith Unicode.CES.Utf8;\nwith DOM.Readers;\nwith DOM.Core.Documents;\nwith DOM.Core.Nodes;\nwith DOM.Core.Attrs;\n\nprocedure Extract_Students is\n Sample_String : String :=\n\"<Students>\" &\n \"<Student Name=\"\"April\"\" Gender=\"\"F\"\" DateOfBirth=\"\"1989-01-02\"\" />\" &\n \"<Student Name=\"\"Bob\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1990-03-04\"\" />\" &\n \"<Student Name=\"\"Chad\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1991-05-06\"\" />\" &\n \"<Student Name=\"\"Dave\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1992-07-08\"\">\" &\n \"<Pet Type=\"\"dog\"\" Name=\"\"Rover\"\" />\" &\n \"</Student>\" &\n \"<Student DateOfBirth=\"\"1993-09-10\"\" Gender=\"\"F\"\" Name=\"\"&#x00C9;mily\"\" />\" &\n\"</Students>\";\n Input : Input_Sources.Strings.String_Input;\n Reader : DOM.Readers.Tree_Reader;\n Document : DOM.Core.Document;\n List : DOM.Core.Node_List;\nbegin\n Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input);\n DOM.Readers.Parse (Reader, Input);\n Input_Sources.Strings.Close (Input);\n Document := DOM.Readers.Get_Tree (Reader);\n List := DOM.Core.Documents.Get_Elements_By_Tag_Name (Document, \"Student\");\n for I in 0 .. DOM.Core.Nodes.Length (List) - 1 loop\n Ada.Text_IO.Put_Line\n (DOM.Core.Attrs.Value\n (DOM.Core.Nodes.Get_Named_Item\n (DOM.Core.Nodes.Attributes\n (DOM.Core.Nodes.Item (List, I)), \"Name\")\n )\n );\n end loop;\n DOM.Readers.Free (Reader);\nend Extract_Students;\n", "language": "Ada" }, { "code": "with League.Application;\nwith XML.SAX.Input_Sources.Streams.Files;\nwith XML.SAX.Simple_Readers;\n\nwith Handlers;\n\nprocedure Main is\n Handler : aliased Handlers.Handler;\n Input : aliased XML.SAX.Input_Sources.Streams.Files.File_Input_Source;\n Reader : aliased XML.SAX.Simple_Readers.SAX_Simple_Reader;\n\nbegin\n Input.Open_By_File_Name (League.Application.Arguments.Element (1));\n Reader.Set_Content_Handler (Handler'Unchecked_Access);\n Reader.Parse (Input'Unchecked_Access);\nend Main;\n", "language": "Ada" }, { "code": "with League.Strings;\nwith XML.SAX.Attributes;\nwith XML.SAX.Content_Handlers;\n\npackage Handlers is\n\n type Handler is\n limited new XML.SAX.Content_Handlers.SAX_Content_Handler with null record;\n\n overriding procedure Start_Element\n (Self : in out Handler;\n Namespace_URI : League.Strings.Universal_String;\n Local_Name : League.Strings.Universal_String;\n Qualified_Name : League.Strings.Universal_String;\n Attributes : XML.SAX.Attributes.SAX_Attributes;\n Success : in out Boolean);\n\n overriding function Error_String\n (Self : Handler) return League.Strings.Universal_String;\n\nend Handlers;\n", "language": "Ada" }, { "code": "with Ada.Wide_Wide_Text_IO;\n\npackage body Handlers is\n\n use type League.Strings.Universal_String;\n\n function \"+\"\n (Item : Wide_Wide_String) return League.Strings.Universal_String\n renames League.Strings.To_Universal_String;\n\n ------------------\n -- Error_String --\n ------------------\n\n overriding function Error_String\n (Self : Handler) return League.Strings.Universal_String is\n begin\n return League.Strings.Empty_Universal_String;\n end Error_String;\n\n -------------------\n -- Start_Element --\n -------------------\n\n overriding procedure Start_Element\n (Self : in out Handler;\n Namespace_URI : League.Strings.Universal_String;\n Local_Name : League.Strings.Universal_String;\n Qualified_Name : League.Strings.Universal_String;\n Attributes : XML.SAX.Attributes.SAX_Attributes;\n Success : in out Boolean) is\n begin\n if Qualified_Name = +\"Student\" then\n Ada.Wide_Wide_Text_IO.Put_Line\n (Attributes.Value (+\"Name\").To_Wide_Wide_String);\n end if;\n end Start_Element;\n\nend Handlers;\n", "language": "Ada" }, { "code": "import xml\n\nvar s = openin (\"t.xml\")\nvar tree = XML.parseStream (s)\n\nforeach node tree {\n if (node.name == \"Students\") {\n foreach studentnode node {\n if (studentnode.name == \"Student\") {\n println (studentnode.getAttribute (\"Name\"))\n }\n }\n }\n}\n", "language": "Aikido" }, { "code": "/* ARM assembly Raspberry PI */\n/* program inputXml.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ XML_ELEMENT_NODE, 1\n.equ XML_ATTRIBUTE_NODE, 2\n .equ XML_TEXT_NODE, 3\n.equ XML_CDATA_SECTION_NODE, 4\n.equ XML_ENTITY_REF_NODE, 5\n.equ XML_ENTITY_NODE, 6\n.equ XML_PI_NODE, 7\n.equ XML_COMMENT_NODE, 8\n.equ XML_DOCUMENT_NODE, 9\n.equ XML_DOCUMENT_TYPE_NODE, 10\n.equ XML_DOCUMENT_FRAG_NODE, 11\n.equ XML_NOTATION_NODE, 12\n.equ XML_HTML_DOCUMENT_NODE, 13\n.equ XML_DTD_NODE, 14\n.equ XML_ELEMENT_DECL, 15\n.equ XML_ATTRIBUTE_DECL, 16\n.equ XML_ENTITY_DECL, 17\n.equ XML_NAMESPACE_DECL, 18\n.equ XML_XINCLUDE_START, 19\n.equ XML_XINCLUDE_END, 20\n.equ XML_DOCB_DOCUMENT_NODE 21\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structure linkedlist*/\n .struct 0\nxmlNode_private: @ application data\n .struct xmlNode_private + 4\nxmlNode_type: @ type number, must be second !\n .struct xmlNode_type + 4\nxmlNode_name: @ the name of the node, or the entity\n .struct xmlNode_name + 4\nxmlNode_children: @ parent->childs link\n .struct xmlNode_children + 4\nxmlNode_last: @ last child link\n .struct xmlNode_last + 4\nxmlNode_parent: @ child->parent link\n .struct xmlNode_parent + 4\nxmlNode_next: @ next sibling link\n .struct xmlNode_next + 4\nxmlNode_prev: @ previous sibling link\n .struct xmlNode_prev + 4\nxmlNode_doc: @ the containing document\n .struct xmlNode_doc + 4\nxmlNode_ns: @ pointer to the associated namespace\n .struct xmlNode_ns + 4\nxmlNode_content: @ the content\n .struct xmlNode_content + 4\nxmlNode_properties: @ properties list\n .struct xmlNode_properties + 4\nxmlNode_nsDef: @ namespace definitions on this node\n .struct xmlNode_nsDef + 4\nxmlNode_psvi: @ for type/PSVI informations\n .struct xmlNode_psvi + 4\nxmlNode_line: @ line number\n .struct xmlNode_line + 4\nxmlNode_extra: @ extra data for XPath/XSLT\n .struct xmlNode_extra + 4\nxmlNode_fin:\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"Normal end of program.\\n\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszText: .ascii \"<Students>\\n\"\n .ascii \"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\n .ascii \"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\n .ascii \"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\n .ascii \"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\n .ascii \"<Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\n .ascii \"</Student>\\n\"\n .ascii \"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\n .asciz \"</Students>\"\n.equ LGSZTEXT, . - szText @ compute text size (. is current address)\n\nszLibExtract: .asciz \"Student\"\nszLibName: .asciz \"Name\"\nszCarriageReturn: .asciz \"\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrszText @ text buffer\n mov r1,#LGSZTEXT @ text size\n mov r2,#0 @ param 3\n mov r3,#0 @ param 4\n mov r4,#0 @ param 5\n sub sp,#4 @ stack assignement\n push {r4} @ param 5 on stack\n bl xmlReadMemory @ read text in document\n add sp,#8 @ stack assignement for 1 push and align stack\n cmp r0,#0 @ error ?\n beq 1f\n mov r9,r0 @ doc address\n mov r0,r9\n bl xmlDocGetRootElement @ search root return in r0\n bl affElement @ display elements\n\n mov r0,r9\n bl xmlFreeDoc\n1:\n bl xmlCleanupParser\n ldr r0,iAdrszMessEndpgm\n bl affichageMess\n b 100f\n99:\n @ error\n ldr r0,iAdrszMessError\n bl affichageMess\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrszMessEndpgm: .int szMessEndpgm\niAdrszText: .int szText\niAdrszCarriageReturn: .int szCarriageReturn\n\n/******************************************************************/\n/* display name of student */\n/******************************************************************/\n/* r0 contains the address of node */\naffElement:\n push {r1-r4,lr} @ save registres\n mov r4,r0 @ save node\n1:\n ldr r2,[r4,#xmlNode_type] @ type ?\n cmp r2,#XML_ELEMENT_NODE\n bne 2f\n ldr r0,[r4,#xmlNode_name] @ name = \"Student\" ?\n ldr r1,iAdrszLibExtract\n bl comparString\n cmp r0,#0\n bne 2f @ no\n mov r0,r4\n ldr r1,iAdrszLibName @ load property of \"Name\"\n bl xmlHasProp\n cmp r0,#0\n beq 2f\n ldr r1,[r0,#xmlNode_children] @ children node of property name\n ldr r0,[r1,#xmlNode_content] @ and address of content\n bl affichageMess @ for display\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n2:\n ldr r0,[r4,#xmlNode_children] @ node have children ?\n cmp r0,#0\n blne affElement @ yes -> call procedure\n\n ldr r1,[r4,#xmlNode_next] @ other element ?\n cmp r1,#0\n beq 100f @ no -> end procedure\n\n mov r4,r1 @ else loop with next element\n b 1b\n\n100:\n pop {r1-r4,lr} @ restaur registers */\n bx lr @ return\niAdrszLibName: .int szLibName\niAdrszLibExtract: .int szLibExtract\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur registers */\n bx lr @ return\n/******************************************************************/\n/* Converting a register to a decimal */\n/******************************************************************/\n/* r0 contains value and r1 address area */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers\n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0\n subne r2,#1 @ previous position\n bne 1b @ else loop\n @ end replaces digit in front of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4] @ store in area begin\n add r4,#1\n add r2,#1 @ previous position\n cmp r2,#LGZONECAL @ end\n ble 2b @ loop\n mov r1,#' '\n3:\n strb r1,[r3,r4]\n add r4,#1\n cmp r4,#LGZONECAL @ end\n ble 3b\n100:\n pop {r1-r4,lr} @ restaur registres\n bx lr @return\n/***************************************************/\n/* division par 10 signé */\n/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*\n/* and http://www.hackersdelight.org/ */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\n/* r1 remainder */\ndivisionpar10:\n /* r0 contains the argument to be divided by 10 */\n push {r2-r4} @ save registers */\n mov r4,r0\n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)\n mov r2, r2, ASR #2 @ r2 <- r2 >> 2\n mov r1, r0, LSR #31 @ r1 <- r0 >> 31\n add r0, r2, r1 @ r0 <- r2 + r1\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5\n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2-r4}\n bx lr @ return\n/************************************/\n/* comparaison de chaines */\n/************************************/\n/* r0 et r1 contiennent les adresses des chaines */\n/* retour 0 dans r0 si egalite */\n/* retour -1 si chaine r0 < chaine r1 */\n/* retour 1 si chaine r0> chaine r1 */\ncomparString:\n push {r1-r4} @ save des registres\n mov r2,#0 @ indice\n1:\n ldrb r3,[r0,r2] @ octet chaine 1\n ldrb r4,[r1,r2] @ octet chaine 2\n cmp r3,r4\n movlt r0,#-1 @ plus petite\n movgt r0,#1 @ plus grande\n bne 100f @ pas egaux\n cmp r3,#0 @ 0 final\n moveq r0,#0 @ egalite\n beq 100f @ c est la fin\n add r2,r2,#1 @ sinon plus 1 dans indice\n b 1b @ et boucle\n100:\n pop {r1-r4}\n bx lr\n", "language": "ARM-Assembly" }, { "code": "data: {\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n}\n\nstudents: read.xml data\nprint join.with:\"\\n\" map students 'student -> student\\Name\n", "language": "Arturo" }, { "code": "students =\n(\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n)\n\nquote = \" ; \"\npos = 1\nwhile, pos := RegExMatch(students, \"Name=.(\\w+)\" . quote . \"\\sGender\"\n, name, pos + 1)\nnames .= name1 . \"`n\"\n\nmsgbox % names\n", "language": "AutoHotkey" }, { "code": "function parse_buf()\n{\n if ( match(buffer, /<Student[ \\t]+[^>]*Name[ \\t]*=[ \\t]*\"([^\"]*)\"/, mt) != 0 ) {\n students[mt[1]] = 1\n }\n buffer = \"\"\n}\n\nBEGIN {\n FS=\"\"\n mode = 0\n buffer = \"\"\n li = 1\n}\n\nmode==1 {\n for(i=1; i <= NF; i++) {\n buffer = buffer $i\n if ( $i == \">\" ) {\n mode = 0;\n break;\n }\n }\n if ( mode == 0 ) {\n li = i\n } else {\n li = 1\n }\n # let us process the buffer if \"complete\"\n if ( mode == 0 ) {\n parse_buf()\n }\n}\n\nmode==0 {\n for(i=li; i <= NF; i++) {\n if ( $i == \"<\" ) {\n mode = 1\n break;\n }\n }\n for(j=i; i <= NF; i++) {\n buffer = buffer $i\n if ( $i == \">\" ) {\n mode = 0\n parse_buf()\n }\n }\n li = 1\n}\n\nEND {\n for(k in students) {\n print k\n }\n}\n", "language": "AWK" }, { "code": "awk -f getXML.awk sample.xml | awk '\n $1 == \"TAG\" {tag = $2}\n tag == \"Student\" && /Name=/ {print substr($0, index($0, \"=\") + 1)}\n'\n", "language": "AWK" }, { "code": "gawk -f xmlparser.awk sample.xml | awk '\n $1 == \"begin\" {tag = $2}\n $1 == \"attrib\" {attrib = $2}\n $1 == \"value\" && tag == \"STUDENT\" && attrib == \"name\" {print $2}\n'\n", "language": "AWK" }, { "code": " INSTALL @lib$+\"XMLLIB\"\n xmlfile$ = \"C:\\students.xml\"\n PROC_initXML(xmlobj{}, xmlfile$)\n\n level% = FN_skipTo(xmlobj{}, \"Students\", 0)\n IF level%=0 ERROR 100, \"Students not found\"\n\n REPEAT\n IF FN_isTag(xmlobj{}) THEN\n tag$ = FN_nextToken(xmlobj{})\n IF LEFT$(tag$, 8) = \"<Student\" THEN\n np% = INSTR(tag$, \"Name\")\n IF np% THEN PRINT FN_repEnt(EVAL(MID$(tag$, np%+5)))\n ENDIF\n ELSE\n dummy$ = FN_nextToken(xmlobj{})\n ENDIF\n UNTIL FN_getLevel(xmlobj{}) < level%\n\n PROC_exitXML(xmlobj{})\n", "language": "BBC-BASIC" }, { "code": "( :?names\n& ( get$(\"students.xml\",X,ML)\n : ?\n ( ( Student\n . (? (Name.?name) ?,)\n | ? (Name.?name) ?\n )\n & !names !name:?names\n & ~\n )\n ?\n | !names\n )\n)\n", "language": "Bracmat" }, { "code": "( :?names\n& ( get\n $ ( \"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\"\n , MEM\n , X\n , ML\n )\n : ?\n ( ( Student\n . (? (Name.?name) ?,)\n | ? (Name.?name) ?\n )\n & !names !name:?names\n & ~\n )\n ?\n | !names\n )\n)\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nstatic void print_names(xmlNode *node)\n{\n xmlNode *cur_node = NULL;\n for (cur_node = node; cur_node; cur_node = cur_node->next) {\n if (cur_node->type == XML_ELEMENT_NODE) {\n if ( strcmp(cur_node->name, \"Student\") == 0 ) {\n\txmlAttr *prop = NULL;\n\tif ( (prop = xmlHasProp(cur_node, \"Name\")) != NULL ) {\n\t printf(\"%s\\n\", prop->children->content);\n\t\n\t}\n }\n }\n print_names(cur_node->children);\n }\n}\n\nconst char *buffer =\n \"<Students>\\n\"\n \" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\n \" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\n \" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\n \" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\n \" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\n \" </Student>\\n\"\n \" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\n \"</Students>\\n\";\n\nint main()\n{\n xmlDoc *doc = NULL;\n xmlNode *root = NULL;\n\n doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0);\n if ( doc != NULL ) {\n root = xmlDocGetRootElement(doc);\n print_names(root);\n xmlFreeDoc(doc);\n }\n xmlCleanupParser();\n return 0;\n}\n", "language": "C" }, { "code": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\nMain\n Assert( Arg_count == 2, end_input );\n Get_arg_str( xml_file, 1 );\n Assert( Exist_file(xml_file), file_not_exist );\n\n char* xml = Load_string(xml_file);\n\n ST_GETTAG field = Unparser( &xml, \"Students\");\n Assert ( field.content, fail_content );\n\n while ( Occurs (\"Student\",field.content ) )\n {\n ST_GETTAG sub_field = Unparser( &field.content, \"Student\");\n\n if(sub_field.attrib)\n {\n int i=0;\n Iterator up i [ 0: 1: sub_field.len ]\n {\n if ( strcmp(sub_field.name[i], \"Name\" )==0 )\n {\n Get_fn_let( sub_field.attrib[i], Str_tran( sub_field.attrib[i], \"&#x00C9;\",\"É\" ) );\n /* OK... I must write the function that change this diabolic characters :D */\n Print \"%s\\n\",sub_field.attrib[i];\n break;\n }\n }\n }\n\n Free tag sub_field;\n }\n\n Free tag field;\n\n /* Exceptions areas */\n Exception( fail_content ){\n Msg_red(\"Not content for \\\"Students\\\" field\\n\");\n }\n Free secure xml;\n\n Exception( file_not_exist ){\n Msg_redf(\"File \\\"%s\\\" not found\\n\", xml_file);\n }\n Free secure xml_file;\n\n Exception( end_input ){\n Msg_yellow(\"Use:\\n RC_xml <xml_file.xml>\");\n }\n\nEnd\n", "language": "C" }, { "code": "<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n", "language": "C" }, { "code": "/*\nUsing the Qt library's XML parser.\n*/\n#include <iostream>\n\n#include <QDomDocument>\n#include <QObject>\n\nint main() {\n QDomDocument doc;\n\n doc.setContent(\n QObject::tr(\n \"<Students>\\n\"\n \"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\n \"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\n \"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\n \"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\n \"<Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\n \"</Student>\\n\"\n \"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\n \"</Students>\"));\n\n QDomElement n = doc.documentElement().firstChildElement(\"Student\");\n while(!n.isNull()) {\n std::cout << qPrintable(n.attribute(\"Name\")) << std::endl;\n n = n.nextSiblingElement();\n }\n return 0;\n}\n", "language": "C++" }, { "code": "class Program\n{\n static void Main(string[] args)\n {\n XDocument xmlDoc = XDocument.Load(\"XMLFile1.xml\");\n var query = from p in xmlDoc.Descendants(\"Student\")\n select p.Attribute(\"Name\");\n\n foreach (var item in query)\n {\n Console.WriteLine(item.Value);\n }\n Console.ReadLine();\n }\n}\n", "language": "C-sharp" }, { "code": "(import '(java.io ByteArrayInputStream))\n(use 'clojure.xml) ; defines 'parse\n\n(def xml-text \"<Students>\n <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />\n <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />\n <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />\n <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>\n <Pet Type='dog' Name='Rover' />\n </Student>\n <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />\n</Students>\")\n\n(def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))\n", "language": "Clojure" }, { "code": "(doseq [{:keys [tag attrs]} (xml-seq students)]\n (if (= :Student tag)\n (println (:Name attrs))))\n", "language": "Clojure" }, { "code": "(defparameter *xml-blob*\n\"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\")\n\n(let* ((document (cxml:parse *xml-blob* (cxml-dom:make-dom-builder)))\n (students (dom:item (dom:get-elements-by-tag-name document \"Students\") 0))\n (student-names '()))\n (dom:do-node-list (child (dom:child-nodes students) (nreverse student-names))\n (when (dom:element-p child)\n (push (dom:get-attribute child \"Name\") student-names))))\n", "language": "Common-Lisp" }, { "code": "(\"April\" \"Bob\" \"Chad\" \"Dave\" \"Émily\")\n", "language": "Common-Lisp" }, { "code": "import kxml.xml;\nchar[]xmlinput =\n\"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\";\n\nvoid main() {\n auto root = readDocument(xmlinput);\n foreach(students;root.getChildren) if (!students.isCData && students.getName == \"Students\") {\n // now look for student subnodes\n foreach(student;students.getChildren) if (!student.isCData && student.getName == \"Student\") {\n // we found a student!\n std.stdio.writefln(\"%s\",student.getAttribute(\"Name\"));\n }\n // we only want one, so break out of the loop once we find a match\n break;\n }\n}\n", "language": "D" }, { "code": "//You need to use these units\nuses\n SysUtils,\n Dialogs,\n XMLIntf,\n XMLDoc;\n\n//..............................................\n\n//This function process the XML\nfunction GetStudents(aXMLInput: string): string;\nvar\n XMLDoc: IXMLDocument;\n i: Integer;\nbegin\n //Creating the TXMLDocument instance\n XMLDoc:= TXMLDocument.Create(nil);\n\n //Loading8 the XML string\n XMLDoc.LoadFromXML(aXMLInput);\n\n //Parsing the xml document\n for i:=0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do\n Result:= Result + XMLDoc.DocumentElement.ChildNodes.Get(i).GetAttributeNS('Name', '') + #13#10;\n\n //Removing the trailing #13#10 characters\n Result:= Trim(Result);\nend;\n\n//..............................................\n\n//Consuming code example (fragment)\nvar\n XMLInput: string;\nbegin\n XMLInput:= '<Students>' +\n '<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />' +\n '<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />' +\n '<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />' +\n '<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">' +\n '<Pet Type=\"dog\" Name=\"Rover\" />' +\n '</Student>' +\n '<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />'+\n '</Students>';\n Showmessage(GetStudents(XMLInput));\nend;\n", "language": "Delphi" }, { "code": "-module( xml_input ).\n\n-export( [task/0] ).\n\n-include_lib(\"xmerl/include/xmerl.hrl\").\n\ntask() ->\n {XML, []} = xmerl_scan:string( xml(), [{encoding, \"iso-10646-utf-1\"}] ),\n Attributes = lists:flatten( [X || #xmlElement{name='Student', attributes=X} <- XML#xmlElement.content] ),\n [io:fwrite(\"~s~n\", [X]) || #xmlAttribute{name='Name', value=X} <- Attributes].\n\n\n\nxml() -> \"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\".\n", "language": "Erlang" }, { "code": "open System.IO\nopen System.Xml\nopen System.Xml.Linq\n\nlet xn s = XName.Get(s)\n\nlet xd = XDocument.Load(new StringReader(\"\"\"\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"\"\")) // \"\n\n\n\n[<EntryPoint>]\nlet main argv =\n let students = xd.Descendants <| xn \"Student\"\n let names = students.Attributes <| xn \"Name\"\n Seq.iter ((fun (a : XAttribute) -> a.Value) >> printfn \"%s\") names\n 0\n", "language": "F-Sharp" }, { "code": "USING: io multiline sequences xml xml.data xml.traversal ;\n\n: print-student-names ( string -- )\n string>xml \"Student\" tags-named [ \"Name\" attr print ] each ;\n\n[[ <Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>]] print-student-names\n", "language": "Factor" }, { "code": "using xml\n\nclass XmlInput\n{\n public static Void main ()\n {\n // create the XML parser\n parser := XParser(File(\"sample-xml.xml\".toUri).in)\n // parse the document, creating an XML document\n XDoc doc := parser.parseDoc\n // walk through each child element from the root of the document\n doc.root.elems.each |elem|\n {\n // printing the Name attribute of all Students\n if (elem.name == \"Student\") { echo (elem.get(\"Name\")) }\n }\n }\n}\n", "language": "Fantom" }, { "code": "include ffl/est.fs\ninclude ffl/str.fs\ninclude ffl/xis.fs\n\n\\ Build input string\nstr-create xmlstr\n: x+ xmlstr str-append-string ;\n\ns\\\" <Students>\\n\" x+\ns\\\" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\" x+\ns\\\" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\" x+\ns\\\" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\" x+\ns\\\" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\" x+\ns\\\" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\" x+\ns\\\" </Student>\\n\" x+\ns\\\" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\" x+\ns\\\" </Students>\\n\" x+\n\n\\ Setup xml parser\nxis-create xmlparser\nxmlstr str-get xmlparser xis-set-string\n\n\\ Parse the xml\n: xmlparse\n BEGIN\n xmlparser xis-read dup xis.error <> over xis.done <> AND\n WHILE\n dup xis.start-tag = over xis.empty-element = OR IF\n drop\n s\" Student\" compare 0= IF\n 0 ?DO\n 2swap s\" Name\" compare 0= IF\n type cr\n ELSE\n 2drop\n THEN\n LOOP\n ELSE\n xis+remove-attribute-parameters\n THEN\n ELSE\n xis+remove-read-parameters\n THEN\n REPEAT\n drop\n;\n\nxmlparse\n", "language": "Forth" }, { "code": "program tixi_rosetta\n use tixi\n implicit none\n integer :: i\n character (len=100) :: xml_file_name\n integer :: handle\n integer :: error\t\n character(len=100) :: name, xml_attr\n xml_file_name = 'rosetta.xml'\n\n call tixi_open_document( xml_file_name, handle, error )\n i = 1\n do\n xml_attr = '/Students/Student['//int2char(i)//']'\n call tixi_get_text_attribute( handle, xml_attr,'Name', name, error )\n if(error /= 0) exit\n write(*,*) name\n i = i + 1\n enddo\n\n call tixi_close_document( handle, error )\n\n contains\n\n function int2char(i) result(res)\n character(:),allocatable :: res\n integer,intent(in) :: i\n character(range(i)+2) :: tmp\n write(tmp,'(i0)') i\n res = trim(tmp)\n end function int2char\n\nend program tixi_rosetta\n", "language": "Fortran" }, { "code": "program fox_rosetta\n use FoX_dom\n use FoX_sax\n implicit none\n integer :: i\n type(Node), pointer :: doc => null()\n type(Node), pointer :: p1 => null()\n type(Node), pointer :: p2 => null()\n type(NodeList), pointer :: pointList => null()\n character(len=100) :: name\n\n doc => parseFile(\"rosetta.xml\")\n if(.not. associated(doc)) stop \"error doc\"\n\n p1 => item(getElementsByTagName(doc, \"Students\"), 0)\n if(.not. associated(p1)) stop \"error p1\"\n ! write(*,*) getNodeName(p1)\n\n pointList => getElementsByTagname(p1, \"Student\")\n ! write(*,*) getLength(pointList), \"Student elements\"\n\n do i = 0, getLength(pointList) - 1\n p2 => item(pointList, i)\n call extractDataAttribute(p2, \"Name\", name)\n write(*,*) name\n enddo\n\n call destroy(doc)\nend program fox_rosetta\n", "language": "Fortran" }, { "code": "Data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238\nData 248, 241, 253, 252, 239, 230, 244, 250, 247, 251, 167, 175, 172, 171, 243, 168\nData 183, 181, 182, 199, 142, 143, 146, 128, 212, 144, 210, 211, 222, 214, 215, 216\nData 209, 165, 227, 224, 226, 229, 153, 158, 157, 235, 233, 234, 154, 237, 232, 225\nData 133, 160, 131, 198, 132, 134, 145, 135, 138, 130, 136, 137, 141, 161, 140, 139\nData 208, 164, 149, 162, 147, 228, 148, 246, 155, 151, 163, 150, 129, 236, 231, 152\n\nDim Shared As Integer numCodes, initCode\ninitCode = 160\nnumCodes = 255 - initCode + 1\n\nDim Shared As Integer codes(numCodes)\nFor i As Integer = 0 To numCodes - 1 : Read codes(i)\nNext i\n\nFunction codeConversion(charcode As Integer, tocode As Integer = False) As Integer\n If tocode Then\n For i As Integer = 0 To numCodes - 1\n If codes(i) = charcode Then Return i + initCode\n Next i\n Else\n Return codes(charcode - initCode)\n End If\nEnd Function\n\nFunction convASCII(nombre As String, mark As String) As String\n Dim As Integer p, c, lm = Len(mark)\n\n Do\n p = Instr(p, nombre, mark)\n If p = 0 Then Exit Do\n c = Valint(Mid(nombre, p + lm, 4))\n c = codeConversion(c)\n nombre = Left(nombre, p-1) + Chr(c) + Right(nombre, Len(nombre) - (p + lm + 4))\n p += 1\n Loop\n Return nombre\nEnd Function\n\nDim As String strXml = \"<Students>\"\nstrXml += \" <Student Name=\\'April\\' Gender=\\'F\\' DateOfBirth=\\'1989-01-02\\' />\"\nstrXml += \" <Student Name=\\'Bob\\' Gender=\\'M\\' DateOfBirth=\\'1990-03-04\\' />\"\nstrXml += \" <Student Name=\\'Chad\\' Gender=\\'M\\' DateOfBirth=\\'1991-05-06\\' />\"\nstrXml += \" <Student Name=\\'Dave\\' Gender=\\'M\\' DateOfBirth=\\'1992-07-08\\'>\"\nstrXml += \" <Pet Type=\\'dog\\' Name=\\'Rover\\' />\"\nstrXml += \" </Student>\"\nstrXml += \" <Student DateOfBirth=\\'1993-09-10\\' Gender=\\'F\\' Name=\\'&#x00C9;mily\\' />\"\nstrXml += \"</Students>\"\n\nDim As String tag1 = \"<Student\"\nDim As String tag2 = \"Name=\\'\", nombre\nDim As Integer ltag = Len(tag2), p = 1, p2\n\nDo\n p = Instr(p, strXml, tag1)\n If p = 0 Then Exit Do\n p = Instr(p, strXml, tag2)\n p += ltag\n p2 = Instr(p, strXml, \"\\'\")\n nombre = convASCII(Mid(strXml, p, p2 - p), \"&#x\")\n Print nombre\nLoop\n\nSleep\n", "language": "FreeBASIC" }, { "code": "include \"NSLog.incl\"\ninclude \"Tlbx XML.incl\"\n\n#define STUDENTS_KEY @\"Students\"\n#define STUDENT_KEY @\"Student\"\n#define NAME_KEY @\"Name\"\n\nvoid local fn MyParserDelegateCallback( ev as long, parser as XMLParserRef, userData as ptr )\n static BOOL studentsFlag = NO\n CFDictionaryRef attributes\n CFStringRef name\n\n select ( ev )\n case _xmlParserDidStartElement\n select ( fn XMLParserDelegateElementName(parser) )\n case STUDENTS_KEY\n studentsFlag = YES\n\n case STUDENT_KEY\n if ( studentsFlag )\n attributes = fn XMLParserDelegateAttributes(parser)\n name = fn DictionaryObjectForKey( attributes, NAME_KEY )\n if ( name ) then NSLog(@\"%@\",name)\n end if\n end select\n end select\nend fn\n\nvoid local fn ParseXMLFile\n CFStringRef xmlString = @\"<Students>\\n\"\n xmlString = fn StringByAppendingFormat( xmlString, @\"%@\\n\",@\"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"<Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"</Student>\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\" )\n xmlString = fn StringByAppendingFormat( xmlString, @\"</Students>\" )\n\n CFDataRef xmlData = fn StringData( xmlString, NSUTF8StringEncoding )\n XMLParserRef parser = fn XMLParserWithData( xmlData )\n XMLParserSetDelegateCallback( parser, @fn MyParserDelegateCallback, NULL )\n fn XMLParserParse( parser )\nend fn\n\nfn ParseXMLFile\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "package main\n\nimport (\n \"encoding/xml\"\n \"fmt\"\n)\n\nconst XML_Data = `\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n`\n\ntype Students struct {\n Student []Student\n}\n\ntype Student struct {\n Name string `xml:\",attr\"`\n // Gender string `xml:\",attr\"`\n // DateOfBirth string `xml:\",attr\"`\n // Pets []Pet `xml:\"Pet\"`\n}\n\ntype Pet struct {\n Type string `xml:\",attr\"`\n Name string `xml:\",attr\"`\n}\n\n// xml.Unmarshal quietly skips well formed input with no corresponding\n// member in the output data structure. With Gender, DateOfBirth, and\n// Pets commented out of the Student struct, as above, Student contains\n// only Name, and this is the only value extracted from the input XML_Data.\nfunc main() {\n var data Students\n err := xml.Unmarshal([]byte(XML_Data), &data)\n if err != nil {\n fmt.Println(err)\n return\n }\n for _, s := range data.Student {\n fmt.Println(s.Name)\n }\n}\n", "language": "Go" }, { "code": "def input = \"\"\"<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\"\"\"\n\ndef students = new XmlParser().parseText(input)\nstudents.each { println it.'@Name' }\n", "language": "Groovy" }, { "code": "import Data.Maybe\nimport Text.XML.Light\n\nstudents=\"<Students>\"++\n \" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\"++\n \" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\"++\n \" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\"/>\"++\n \" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\"++\n \" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" /> </Student>\"++\n \" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\"++\n \"</Students>\"\n\nxmlRead elm name = mapM_ putStrLn\n . concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm))\n . onlyElems. parseXML\n", "language": "Haskell" }, { "code": "*Main> xmlRead \"Student\" \"Name\" students\nApril\nBob\nChad\nDave\nÉmily\n", "language": "Haskell" }, { "code": "CHARACTER in*1000, out*100\n\nREAD(ClipBoard) in\nEDIT(Text=in, SPR='\"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)\n", "language": "HicEst" }, { "code": "load'xml/sax'\n\nsaxclass 'Students'\nstartElement =: ([: smoutput 'Name' getAttribute~ [)^:('Student'-:])\ncocurrent'base'\n\nprocess_Students_ XML\n", "language": "J" }, { "code": "XML=: noun define\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n)\n", "language": "J" }, { "code": "import java.io.IOException;\nimport java.io.StringReader;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\nimport org.xml.sax.helpers.DefaultHandler;\nimport org.xml.sax.helpers.XMLReaderFactory;\n\npublic class StudentHandler extends DefaultHandler {\n public static void main(String[] args)throws Exception{\n String xml = \"<Students>\\n\"+\n \"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"+\n \"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"+\n \"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"+\n \"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"+\n \" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"+\n \"</Student>\\n\"+\n \"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"+\n \"</Students>\";\n StudentHandler handler = new StudentHandler();\n handler.parse(new InputSource(new StringReader(xml)));\n }\n\n public void parse(InputSource src) throws SAXException, IOException {\n\t\tXMLReader parser = XMLReaderFactory.createXMLReader();\n parser.setContentHandler(this);\n parser.parse(src);\n }\n\n @Override\n public void characters(char[] ch, int start, int length) throws SAXException {\n //if there were text as part of the elements, we would deal with it here\n //by adding it to a StringBuffer, but we don't have to for this task\n super.characters(ch, start, length);\n }\n\n @Override\n public void endElement(String uri, String localName, String qName) throws SAXException {\n //this is where we would get the info from the StringBuffer if we had to,\n //but all we need is attributes\n super.endElement(uri, localName, qName);\n }\n\n @Override\n public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n if(qName.equals(\"Student\")){\n System.out.println(attributes.getValue(\"Name\"));\n }\n }\n}\n", "language": "Java" }, { "code": "var xmlstr = '<Students>' +\n '<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />' +\n '<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />' +\n '<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />' +\n '<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">' +\n '<Pet Type=\"dog\" Name=\"Rover\" />' +\n '</Student>' +\n '<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />' +\n'</Students>';\n\nif (window.DOMParser)\n {\n parser=new DOMParser();\n xmlDoc=parser.parseFromString(xmlstr,\"text/xml\");\n }\nelse // Internet Explorer\n {\n xmlDoc=new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlDoc.async=false;\n xmlDoc.loadXML(xmlstr);\n }\n\nvar students=xmlDoc.getElementsByTagName('Student');\nfor(var e=0; e<=students.length-1; e++) {\n console.log(students[e].attributes.Name.value);\n}\n", "language": "JavaScript" }, { "code": "var parseString = require('xml2js').parseString;\nvar xmlstr = '<Students>' +\n '<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />' +\n '<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />' +\n '<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />' +\n '<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">' +\n '<Pet Type=\"dog\" Name=\"Rover\" />' +\n '</Student>' +\n '<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />' +\n'</Students>';\n\nparseString(xmlstr, function (err, result) {\n if (!err) {\n result.Students.Student.forEach( function(student) {\n console.log(student.$.Name);\n } );\n }\n});\n", "language": "JavaScript" }, { "code": "var xmlstr = '<Students>' +\n '<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />' +\n '<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />' +\n '<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />' +\n '<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">' +\n '<Pet Type=\"dog\" Name=\"Rover\" />' +\n '</Student>' +\n '<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />' +\n'</Students>';\nvar xml = XML(xmlstr);\nvar list = xml.Student.@Name;\nvar output = '';\nfor (var i = 0; i < list.length(); i++) {\n if (i > 0) {\n output += ', ';\n }\n output += list[i];\n}\n\nalert(output);\n", "language": "JavaScript" }, { "code": "xq -r '.Students.Student[].\"@Name\"' students.xml\n", "language": "Jq" }, { "code": "include \"peg\" {search: \".\"};\n", "language": "Jq" }, { "code": "def XML:\n def String : ((consume(\"\\\"\") | parse(\"[^\\\"]*\") | consume(\"\\\"\")) //\n (consume(\"'\") | parse(\"[^']*\") | consume(\"'\")));\n\n def CDataSec : box(\"@CDATA\"; q(\"<![CDATA[\") | string_except(\"]]>\") | q(\"]]>\") ) | ws;\n def PROLOG : box(\"@PROLOG\"; q(\"<?xml\") | string_except(\"\\\\?>\") | q(\"?>\"));\n def DTD : box(\"@DTD\"; q(\"<!\") | parse(\"[^>]\") | q(\">\"));\n # The XML spec specifically disallows double-hyphen within comments\n def COMMENT : box(\"@COMMENT\"; q(\"<!--\") | string_except(\"--\") | q(\"-->\"));\n\n def CharData : parse(\"[^<]+\"); # only `<` is disallowed\n\n # This is more permissive than required:\n def Name : parse(\"[A-Za-z:_][^/=<>\\n\\r\\t ]*\");\n\n def Attribute : keyvalue(Name | ws | q(\"=\") | ws | String | ws);\n def Attributes: box( plus(Attribute) ) | .result[-1] |= {\"@attributes\": add} ;\n\n # <foo> must be matched with </foo>\n def Element :\n def Content : star(Element // CDataSec // CharData // COMMENT);\n objectify( q(\"<\")\n | Name\n | .result[-1] as $name\n\t | ws\n | (Attributes // ws)\n | ( (q(\"/>\")\n\t // (q(\">\") | Content | q(\"</\") | q($name) | ws | q(\">\")))\n | ws) ) ;\n\n {remainder: . }\n | ws\n | optional(PROLOG) | ws\n | optional(DTD) | ws\n | star(COMMENT | ws)\n | Element | ws # for HTML, one would use star(Element) here\n | star(COMMENT | ws)\n | .result;\n", "language": "Jq" }, { "code": "# For handling hex character codes &#x\ndef hex2i:\n def toi: if . >= 87 then .-87 else . - 48 end;\n reduce ( ascii_downcase | explode | map(toi) | reverse[]) as $i ([1, 0]; # [power, sum]\n .[1] += $i * .[0]\n | .[0] *= 16 )\n | .[1];\n\ndef hexcode2json:\n gsub(\"&#x(?<x>....);\" ; .x | [hex2i] | implode) ;\n\ndef jsonify:\n walk( if type == \"array\"\n then map(select(type == \"string\" and test(\"^\\n *$\") | not))\n\telif type == \"string\" then hexcode2json\n\telse . end);\n\n# First convert to JSON ...\nXML | jsonify\n# ... and then extract Student Names\n| .[]\n| (.Students[].Student[][\"@attributes\"] // empty).Name\n", "language": "Jq" }, { "code": "using LightXML\n\nlet docstr = \"\"\"<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n </Students>\"\"\"\n\n doc = parse_string(docstr)\n xroot = root(doc)\n for elem in xroot[\"Student\"]\n println(attribute(elem, \"Name\"))\n end\nend\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport org.xml.sax.InputSource\nimport java.io.StringReader\nimport org.w3c.dom.Node\nimport org.w3c.dom.Element\n\nval xml =\n\"\"\"\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"\"\"\n\nfun main(args: Array<String>) {\n val dbFactory = DocumentBuilderFactory.newInstance()\n val dBuilder = dbFactory.newDocumentBuilder()\n val xmlInput = InputSource(StringReader(xml))\n val doc = dBuilder.parse(xmlInput)\n val nList = doc.getElementsByTagName(\"Student\")\n for (i in 0 until nList.length) {\n val node = nList.item(i)\n if (node.nodeType == Node.ELEMENT_NODE) {\n val element = node as Element\n val name = element.getAttribute(\"Name\")\n println(name)\n }\n }\n}\n", "language": "Kotlin" }, { "code": "// makes extracting attribute values easier\ndefine xml_attrmap(in::xml_namedNodeMap_attr) => {\n\tlocal(out = map)\n\twith attr in #in\n\t\tdo #out->insert(#attr->name = #attr->value)\n\treturn #out\n}\n\nlocal(\n\ttext = '<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n',\nxml = xml(#text)\n)\n\nlocal(\n\tstudents\t= #xml -> extract('//Student'),\n\tnames\t\t= array\n)\nwith student in #students do {\n\t#names -> insert(xml_attrmap(#student -> attributes) -> find('Name'))\n}\n#names -> join('<br />')\n", "language": "Lasso" }, { "code": "// not using XML or Xpath\n'<hr />'\nlocal(\n\tregexp\t= regexp(-find = `<Student.*?Name=\"(.*?)\"`, -input = #text, -ignoreCase),\n\tnames\t= array\n)\n\nwhile( #regexp -> find) => {\n\t#names -> insert(#regexp -> matchstring(1))\n}\n#names -> join('<br />')\n", "language": "Lasso" }, { "code": "q = QUOTE\nr = RETURN\nxml = \"<Students>\"&r&\\\n\" <Student Name=\"&q&\"April\"&q&\" Gender=\"&q&\"F\"&q&\" DateOfBirth=\"&q&\"1989-01-02\"&q&\" />\"&r&\\\n\" <Student Name=\"&q&\"Bob\"&q&\" Gender=\"&q&\"M\"&q&\" DateOfBirth=\"&q&\"1990-03-04\"&q&\" />\"&r&\\\n\" <Student Name=\"&q&\"Chad\"&q&\" Gender=\"&q&\"M\"&q&\" DateOfBirth=\"&q&\"1991-05-06\"&q&\" />\"&r&\\\n\" <Student Name=\"&q&\"Dave\"&q&\" Gender=\"&q&\"M\"&q&\" DateOfBirth=\"&q&\"1992-07-08\"&q&\">\"&r&\\\n\" <Pet Type=\"&q&\"dog\"&q&\" Name=\"&q&\"Rover\"&q&\" />\"&r&\\\n\" </Student>\"&r&\\\n\" <Student DateOfBirth=\"&q&\"1993-09-10\"&q&\" Gender=\"&q&\"F\"&q&\" Name=\"&q&\"&#x00C9;mily\"&q&\" />\"&r&\\\n\"</Students>\"\n\nparser = xtra(\"xmlparser\").new()\nparser.parseString(xml)\nres = parser.makePropList()\t\nrepeat with c in res.child\n put c.attributes.name\nend repeat\n", "language": "Lingo" }, { "code": "put revXMLCreateTree(fld \"FieldXML\",true,true,false) into currTree\nput revXMLAttributeValues(currTree,\"Students\",\"Student\",\"Name\",return,-1)\n", "language": "LiveCode" }, { "code": "require 'lxp'\ndata = [[<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>]]\n\np = lxp.new({StartElement = function (parser, name, attr)\n\tif name == 'Student' and attr.Name then\n\t\tprint(attr.Name)\n\tend\nend})\n\np:parse(data)\np:close()\n", "language": "Lua" }, { "code": "Module CheckIt {\n Const Enumerator=-4&\n xml$={<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n </Students>\n }\n Declare Dom \"Msxml2.DOMDocument\"\n Method Dom, \"LoadXML\", xml$\n Method Dom, \"getElementsByTagName\", \"Student\" as Students\n\n With Students, Enumerator as Student\n While Student {\n Method Student, \"getAttribute\", \"Name\" as Student.Name$\n Print Student.Name$\n }\n Declare Student Nothing\n Declare Students Nothing\n Declare DOM Nothing\n}\nCheckIt\n", "language": "M2000-Interpreter" }, { "code": "Module Checkit {\n\tdeclare databank xmldata\n\tmethod databank, \"NumericCharactersEntities\", true\n\twith databank, \"xml\" as doc$, \"beautify\" as beautify\n\tdoc$={<?xml?>\n\t<Students>\n\t\t<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n\t\t<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n\t\t<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n\t\t<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n\t\t\t<Pet Type=\"dog\" Name=\"Rover\" />\n\t\t</Student>\n\t\t<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n\t</Students>\n\t}\n\tbeautify=-4\n\tReport 3, doc$\n\tMethod databank, \"GetListByTag\", \"Student\", -1 as Result\n\tc=1 // Result is type of M2000 stack.\n\tIf len(Result)>0 then\n\t\tStack Result {\n\t\t\tRead fieldsNo : With fieldsNo, \"Attr\" as fieldsno.tag$()\n\t\t}\n\t\tStack Result {\n\t\t\tPrint c, \" \"+fieldsno.tag$(\"Name\")\n\t\t\tc++\n\t\t\t// Loop raise a flag for this block,\n\t\t\t// which interpreter read at the end of block, and then clear it\n\t\t\tif empty else loop\n\t\t\tRead fieldsNo\n\t\t}\n // this place hexadecimal value for char É\n // this object offer by default 5 escaped characters: quot, amp, apos, lt, gt\n // inner local function conv$() can be used to escape characters above 127.\n fieldsno.tag$(\"Name\")=@conv$(\"Émily\")\n\t Report 3, doc$\n\tend if\n\n\tdeclare databank Nothing\n Function Conv$(a$)\n\t\tif len(a$)=0 then exit function\n\t\tlocal b$, c$, k\n\t\tfor i=1 to len(a$)\n\t\t\tc$=mid$(a$, i,1)\n\t\t\tk=uint(chrcode(c$))\n\t\t\tif k>127 then b$+=\"&#x\"+hex$(k,2)+\";\" else b$+=c$\n\t\tnext\n\t\t=b$\n\tEnd Function\n}\nCheckIt\n", "language": "M2000-Interpreter" }, { "code": "Column[Cases[Import[\"test.xml\",\"XML\"],Rule[\"Name\", n_ ] -> n,Infinity]]\n", "language": "Mathematica" }, { "code": "RootXML = com.mathworks.xml.XMLUtils.createDocument('Students');\ndocRootNode = RootXML.getDocumentElement;\nthisElement = RootXML.createElement('Student');\nthisElement.setAttribute('Name','April')\nthisElement.setAttribute('Gender','F')\nthisElement.setAttribute('DateOfBirth','1989-01-02')\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Student');\nthisElement.setAttribute('Name','Bob')\nthisElement.setAttribute('Gender','M')\nthisElement.setAttribute('DateOfBirth','1990-03-04')\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Student');\nthisElement.setAttribute('Name','Chad')\nthisElement.setAttribute('Gender','M')\nthisElement.setAttribute('DateOfBirth','1991-05-06')\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Student');\nthisElement.setAttribute('Name','Dave')\nthisElement.setAttribute('Gender','M')\nthisElement.setAttribute('DateOfBirth','1992-07-08')\nnode = RootXML.createElement('Pet');\nnode.setAttribute('Type','dog')\nnode.setAttribute('name','Rover')\nthisElement.appendChild(node);\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Student');\nthisElement.setAttribute('Name','Émily')\nthisElement.setAttribute('Gender','F')\nthisElement.setAttribute('DateOfBirth','1993-09-10')\ndocRootNode.appendChild(thisElement);\nclearvars -except RootXML\n\nfor I=0:1:RootXML.getElementsByTagName('Student').item(0).getAttributes.getLength-1\n if strcmp(RootXML.getElementsByTagName('Student').item(0).getAttributes.item(I).getName,'Name')\n tag=I;\n break\n end\nend\n\nfor I=0:1:RootXML.getElementsByTagName('Student').getLength-1\n disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue)\nend\n", "language": "MATLAB" }, { "code": "/**\n XML/Input in Neko\n Tectonics:\n nekoc xml-input.neko\n neko xml-input | recode html\n*/\n\n/* Get the Neko XML parser function */\nvar parse_xml = $loader.loadprim(\"std@parse_xml\", 2);\n\n/* Load the student.xml file as string */\nvar file_contents = $loader.loadprim(\"std@file_contents\", 1);\nvar xmlString = file_contents(\"students.xml\");\n\n/* Build up a (very specific) XML event processor object */\n/* Needs functions for xml, done, pcdata, cdata and comment */\nvar events = $new(null);\nevents.xml = function(name, attributes) {\n if name == \"Student\" {\n $print(attributes.Name, \"\\n\");\n }\n}\nevents.done = function() { }\nevents.pcdata = function(x) { }\nevents.cdata = function(x) { }\nevents.comment = function(x) { }\n\nparse_xml(xmlString, events);\n\n/* Entities are not converted, use external recode program for that */\n", "language": "Neko" }, { "code": "April\nBob\nChad\nDave\n&#x00C9;mily\n", "language": "Neko" }, { "code": "(set 'xml-input \"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\")\n\n(set 'sexp (xml-parse xml-input))\n\n(dolist (x (ref-all \"Name\" sexp))\t\n\t(if (= (length x) 6)\n\t\t(println (last (sexp (chop x))))))\n", "language": "NewLISP" }, { "code": "import xmlparser, xmltree, streams\n\nlet doc = newStringStream \"\"\"<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\"\"\"\n\nfor i in doc.parseXml.findAll \"Student\":\n echo i.attr \"Name\"\n", "language": "Nim" }, { "code": "use XML;\n\nbundle Default {\n class Test {\n function : Main(args : String[]) ~ Nil {\n in := String->New();\n in->Append(\"<Students>\");\n in->Append(\"<Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\");\n in->Append(\"<Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\");\n in->Append(\"<Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\");\n in->Append(\"<Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\");\n in->Append(\"<Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\");\n in->Append(\"</Student>\");\n in->Append(\"<Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" /></Students>\");\n\n parser := XmlParser->New(in);\n if(parser->Parse()) {\n root := parser->GetRoot();\n children := root->GetChildren(\"Student\");\n each(i : children) {\n child : XMLElement := children->Get(i)->As(XMLElement);\n XMLElement->DecodeString(child->GetAttribute(\"Name\"))->PrintLine();\n };\n };\n }\n }\n}\n", "language": "Objeck" }, { "code": "# #directory \"+xml-light\" (* or maybe \"+site-lib/xml-light\" *) ;;\n# #load \"xml-light.cma\" ;;\n\n# let x = Xml.parse_string \"\n <Students>\n <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />\n <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />\n <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />\n <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>\n <Pet Type='dog' Name='Rover' />\n </Student>\n <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />\n </Students>\"\n in\n Xml.iter (function\n Xml.Element (\"Student\", attrs, _) ->\n List.iter (function (\"Name\", name) -> print_endline name | _ -> ()) attrs\n | _ -> ()) x\n ;;\nApril\nBob\nChad\nDave\n&#x00C9;mily\n- : unit = ()\n", "language": "OCaml" }, { "code": "#directory \"+xmlm\"\n#load \"xmlm.cmo\"\nopen Xmlm\n\nlet str = \"\n <Students>\n <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />\n <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />\n <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />\n <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>\n <Pet Type='dog' Name='Rover' />\n </Student>\n <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />\n </Students>\"\n\n\nlet xi = make_input(`String(0, str))\n\nlet () =\n while not(eoi xi) do\n match Xmlm.input xi with\n | `El_start ((_, \"Student\"), attrs) ->\n List.iter (function ((_, \"Name\"), name) -> print_endline name | _ -> ()) attrs\n | _ -> ()\n done\n", "language": "OCaml" }, { "code": "open Expat\n\nlet xml_str = \"\n <Students>\n <Student Name='April' Gender='F' DateOfBirth='1989-01-02' />\n <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />\n <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />\n <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>\n <Pet Type='dog' Name='Rover' />\n </Student>\n <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />\n </Students>\"\n\nlet () =\n let p = parser_create None in\n set_start_element_handler p\n (fun tag attrs ->\n if tag = \"Student\" then\n List.iter (function (\"Name\", name) -> print_endline name | _ -> ()) attrs\n );\n parse p xml_str;\n final p;\n", "language": "OCaml" }, { "code": "DEF VAR lcc AS LONGCHAR.\nDEF VAR hxdoc AS HANDLE.\nDEF VAR hxstudents AS HANDLE.\nDEF VAR hxstudent AS HANDLE.\nDEF VAR hxname AS HANDLE.\nDEF VAR ii AS INTEGER EXTENT 2.\nDEF VAR cstudents AS CHARACTER.\n\nlcc = '<Students>'\n + '<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />'\n + '<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />'\n + '<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />'\n + '<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">'\n + '<Pet Type=\"dog\" Name=\"Rover\" />'\n + '</Student>'\n + '<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />'\n + '</Students>'.\n\nCREATE X-DOCUMENT hxdoc.\nhxdoc:LOAD( 'LONGCHAR', lcc, FALSE ).\n\nDO ii[1] = 1 TO hxdoc:NUM-CHILDREN:\n CREATE X-NODEREF hxstudents.\n hxdoc:GET-CHILD( hxstudents, ii[1] ).\n IF hxstudents:NAME = 'Students' THEN DO ii[2] = 1 TO hxstudents:NUM-CHILDREN:\n CREATE X-NODEREF hxstudent.\n hxstudents:GET-CHILD( hxstudent, ii[2] ).\n IF hxstudent:NAME = 'Student' THEN\n cstudents = cstudents + hxstudent:GET-ATTRIBUTE( 'Name' ) + '~n'.\n DELETE OBJECT hxstudent.\n END.\n DELETE OBJECT hxstudents.\nEND.\nDELETE OBJECT hxdoc.\n\nMESSAGE cstudents VIEW-AS ALERT-BOX.\n", "language": "OpenEdge-Progress" }, { "code": "declare\n [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}\n Parser = {New XMLParser.parser init}\n\n Data =\n \"<Students>\"\n #\" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\"\n #\" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\"\n #\" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\"\n #\" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\"\n #\" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\"\n #\" </Student>\"\n #\" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\"\n #\"</Students>\"\n\n fun {IsStudentElement X}\n case X of element(name:'Student' ...) then true\n else false\n end\n end\n\n fun {GetStudentName element(attributes:As ...)}\n [NameAttr] = {Filter As fun {$ attribute(name:N ...)} N == 'Name' end}\n in\n NameAttr.value\n end\n\n [StudentsDoc] = {Parser parseVS(Data $)}\n Students = {Filter StudentsDoc.children IsStudentElement}\n StudentNames = {Map Students GetStudentName}\nin\n {ForAll StudentNames System.showInfo}\n", "language": "Oz" }, { "code": "use utf8;\nuse XML::Simple;\n\nmy $ref = XMLin('<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>');\n\nprint join( \"\\n\", map { $_->{'Name'} } @{$ref->{'Student'}});\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">xml</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">xml</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n &lt;Students&gt;\n &lt;Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /&gt;\n &lt;Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /&gt;\n &lt;Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /&gt;\n &lt;Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\"&gt;\n &lt;Pet Type=\"dog\" Name=\"Rover\" /&gt;\n &lt;/Student&gt;\n &lt;Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" /&gt;\n &lt;/Students&gt;\n \"\"\"</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xml_parse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xml</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">traverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">XML_TAGNAME</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #008000;\">\"Student\"</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xml_get_attribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Name\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">XML_CONTENTS</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #004080;\">string</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">traverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n <span style=\"color: #000000;\">traverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">XML_CONTENTS</span><span style=\"color: #0000FF;\">])</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n$data = '<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>';\n$xml = new XMLReader();\n$xml->xml( $data );\nwhile ( $xml->read() )\n\tif ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' )\n\t\techo $xml->getAttribute('Name') . \"\\n\";\n?>\n", "language": "PHP" }, { "code": "(load \"@lib/xm.l\")\n\n(mapcar\n '((L) (attr L 'Name))\n (body (in \"file.xml\" (xml))) )\n", "language": "PicoLisp" }, { "code": "string in = \"<Students>\\n\"\n \" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\n \" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\n \" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\n \" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\n \" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\n \" </Student>\\n\"\n \" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\n \"</Students>\\n\";\n\nobject s = Parser.XML.Tree.simple_parse_input(in);\n\narray collect = ({});\ns->walk_inorder(lambda(object node)\n {\n if (node->get_tag_name() == \"Student\")\n collect += ({ node->get_attributes()->Name });\n });\nwrite(\"%{%s\\n%}\", collect);\n", "language": "Pike" }, { "code": "[xml]$xml = @'\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n'@\n\nforeach ($node in $xml.DocumentElement.ChildNodes) {$node.Name}\n", "language": "PowerShell" }, { "code": "Define studentNames.String, src$\n\nsrc$ = \"<Students>\"\nsrc$ + \"<Student Name='April' Gender='F' DateOfBirth='1989-01-02' />\"\nsrc$ + \"<Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' />\"\nsrc$ + \"<Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' />\"\nsrc$ + \"<Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'>\"\nsrc$ + \"<Pet Type='dog' Name='Rover' />\"\nsrc$ + \"</Student>\"\nsrc$ + \"<Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' />\"\nsrc$ + \"</Students>\"\n\n;This procedure is generalized to match any attribute of any normal element's node name\n;i.e. get_values(MainXMLNode(0),\"Pet\",\"Type\",@petName.String) and displaying petName\\s\n;would display \"dog\".\nProcedure get_values(*cur_node, nodeName$, attribute$, *valueResults.String)\n ;If nodeName$ and attribute$ are matched then the value\n ;will be added to the string structure pointed to by *valueResults .\n Protected result$\n\n While *cur_node\n If XMLNodeType(*cur_node) = #PB_XML_Normal\n\n result$ = GetXMLNodeName(*cur_node)\n If result$ = nodeName$\n If ExamineXMLAttributes(*cur_node)\n While NextXMLAttribute(*cur_node)\n If XMLAttributeName(*cur_node) = attribute$\n If *valueResults <> #Null\n *valueResults\\s + XMLAttributeValue(*cur_node) + Chr(13) ;value + carriage-return\n EndIf\n EndIf\n Wend\n EndIf\n EndIf\n\n EndIf\n\n get_values(ChildXMLNode(*cur_node), nodeName$, attribute$, *valueResults)\n *cur_node = NextXMLNode(*cur_node)\n Wend\nEndProcedure\n\nCatchXML(0,@src$,Len(src$))\n\nIf IsXML(0)\n get_values(MainXMLNode(0), \"Student\", \"Name\",@studentNames)\n MessageRequester(\"Student Names\", studentNames\\s)\n FreeXML(0)\nEndIf\n", "language": "PureBasic" }, { "code": "import xml.dom.minidom\n\ndoc = \"\"\"<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\"\"\"\n\ndoc = xml.dom.minidom.parseString(doc)\n\nfor i in doc.getElementsByTagName(\"Student\"):\n print i.getAttribute(\"Name\")\n", "language": "Python" }, { "code": "library(XML)\n#Read in XML string\nstr <- readLines(tc <- textConnection('<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>'))\nclose(tc)\nstr\n", "language": "R" }, { "code": "#Convert to an XML tree\nxmltree <- xmlTreeParse(str)\n\n#Retrieve the students, and how many there are\nstudents <- xmltree$doc$children$Students\nnstudents <- length(students)\n\n#Get each of their names\nstudentsnames <- character(nstudents)\nfor(i in 1:nstudents)\n{\n this.student <- students$children[i]$Student\n studentsnames[i] <- this.student$attributes[\"Name\"]\n}\n\n#Change the encoding so that Emily displays correctly\nEncoding(studentsnames) <- \"UTF-8\"\nstudentsnames\n", "language": "R" }, { "code": "#lang racket\n(require xml xml/path)\n\n(define input\n#<<END\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\nEND\n )\n\n(define students\n (xml->xexpr\n (document-element\n (read-xml (open-input-string input)))))\n\n(se-path*/list '(Student #:Name) students)\n", "language": "Racket" }, { "code": "use XML;\n\nmy $xml = from-xml '<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>';\n\nsay .<Name> for $xml.nodes.grep(/Student/)\n", "language": "Raku" }, { "code": "import lang::xml::DOM;\n\npublic void getNames(loc a){\n\tD = parseXMLDOM(readFile(a));\n\tvisit(D){\n\t\tcase element(_,\"Student\",[_*,attribute(_,\"Name\", x),_*]): println(x);\n\t};\n}\n", "language": "Rascal" }, { "code": "rascal>getNames(|file:///Users/.../Desktop/xmlinput.xml|)\nApril\nBob\nChad\nDave\nÉmily\nok\n", "language": "Rascal" }, { "code": "REBOL [\n\tTitle: \"XML Reading\"\n\tURL: http://rosettacode.org/wiki/XML_Reading\n]\n\nxml: {\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n}\n\n; REBOL has a simple built-in XML parser. It's not terribly fancy, but\n; it's easy to use. It converts the XML into a nested list of blocks\n; which can be accessed using standard REBOL path operators. The only\n; annoying part (in this case) is that it does try to preserve\n; whitespace, so some of the parsed elements are just things like line\n; endings and whatnot, which I need to ignore.\n\n; Once I have drilled down to the individual student records, I can\n; just use the standard REBOL 'select' to locate the requested\n; property.\n\ndata: parse-xml xml\nstudents: data/3/1/3 ; Drill down to student records.\nforeach student students [\n\tif block! = type? student [ ; Ignore whitespace elements.\n\t\tprint select student/2 \"Name\"\n\t]\n]\n", "language": "REBOL" }, { "code": "/*REXX program extracts student names from an XML string(s). */\ng.=\ng.1 = '<Students> '\ng.2 = ' <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /> '\ng.3 = ' <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /> '\ng.4 = ' <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /> '\ng.5 = ' <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\"> '\ng.6 = ' <Pet Type=\"dog\" Name=\"Rover\" /> '\ng.7 = ' </Student> '\ng.8 = ' <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" /> '\ng.9 = '</Students> '\n\n do j=1 while g.j\\==''\n g.j=space(g.j)\n parse var g.j 'Name=\"' studname '\"'\n if studname\\=='' then say studname\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program extracts student names from an XML string(s). */\ng.=\ng.1 = '<Students> '\ng.2 = ' <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" /> '\ng.3 = ' <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" /> '\ng.4 = ' <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" /> '\ng.5 = ' <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\"> '\ng.6 = ' <Pet Type=\"dog\" Name=\"Rover\" / > '\ng.7 = ' </Student> '\ng.8 = ' <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00c9;mily\" /> '\ng.9 = '</Students> '\n\n do j=1 while g.j\\==''\n g.j=space(g.j)\n parse var g.j 'Name=\"' studname '\"'\n if studname=='' then iterate\n if pos('&', studname)\\==0 then studname=xmlTranE(studname)\n say studname\n end /*j*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nxml_: parse arg ,_ /*transkate an XML entity (&xxxx;) */\n xmlEntity! = '&'_\";\"\n if pos(xmlEntity!, $)\\==0 then $=changestr(xmlEntity!, $, arg(1) )\n if left(_, 2)=='#x' then do\n xmlEntity!='&'left(_, 3)translate( substr(_, 4) )\";\"\n $=changestr(xmlEntity!, $, arg(1) )\n end\n return $\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nxmlTranE: procedure; parse arg $ /*Following are most of the chars in */\n /*the DOS (under Windows) codepage. */\n$=XML_('â',\"ETH\") ; $=XML_('ƒ',\"fnof\") ; $=XML_('═',\"boxH\") ; $=XML_('♥',\"hearts\")\n$=XML_('â','#x00e2') ; $=XML_('á',\"aacute\"); $=XML_('╬',\"boxVH\") ; $=XML_('♦',\"diams\")\n$=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',\"boxHu\") ; $=XML_('♣',\"clubs\")\n$=XML_('ä',\"auml\") ; $=XML_('í',\"iacute\"); $=XML_('╨',\"boxhU\") ; $=XML_('♠',\"spades\")\n$=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',\"boxHd\") ; $=XML_('♂',\"male\")\n$=XML_('à',\"agrave\") ; $=XML_('ó',\"oacute\"); $=XML_('╥',\"boxhD\") ; $=XML_('♀',\"female\")\n$=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',\"boxUr\") ; $=XML_('☼',\"#x263c\")\n$=XML_('å',\"aring\") ; $=XML_('ú',\"uacute\"); $=XML_('╘',\"boxuR\") ; $=XML_('↕',\"UpDownArrow\")\n$=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',\"boxdR\") ; $=XML_('¶',\"para\")\n$=XML_('ç',\"ccedil\") ; $=XML_('ñ',\"ntilde\"); $=XML_('╓',\"boxDr\") ; $=XML_('§',\"sect\")\n$=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',\"boxVh\") ; $=XML_('↑',\"uarr\")\n$=XML_('ê',\"ecirc\") ; $=XML_('Ñ',\"Ntilde\"); $=XML_('╪',\"boxvH\") ; $=XML_('↑',\"uparrow\")\n$=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',\"boxul\") ; $=XML_('↑',\"ShortUpArrow\")\n$=XML_('ë',\"euml\") ; $=XML_('¿',\"iquest\"); $=XML_('┌',\"boxdr\") ; $=XML_('↓',\"darr\")\n$=XML_('ë','#x00eb') ; $=XML_('⌐',\"bnot\") ; $=XML_('█',\"block\") ; $=XML_('↓',\"downarrow\")\n$=XML_('è',\"egrave\") ; $=XML_('¬',\"not\") ; $=XML_('▄',\"lhblk\") ; $=XML_('↓',\"ShortDownArrow\")\n$=XML_('è','#x00e8') ; $=XML_('½',\"frac12\"); $=XML_('▀',\"uhblk\") ; $=XML_('←',\"larr\")\n$=XML_('ï',\"iuml\") ; $=XML_('½',\"half\") ; $=XML_('α',\"alpha\") ; $=XML_('←',\"leftarrow\")\n$=XML_('ï','#x00ef') ; $=XML_('¼',\"frac14\"); $=XML_('ß',\"beta\") ; $=XML_('←',\"ShortLeftArrow\")\n$=XML_('î',\"icirc\") ; $=XML_('¡',\"iexcl\") ; $=XML_('ß',\"szlig\") ; $=XML_('1c'x,\"rarr\")\n$=XML_('î','#x00ee') ; $=XML_('«',\"laqru\") ; $=XML_('ß','#x00df') ; $=XML_('1c'x,\"rightarrow\")\n$=XML_('ì',\"igrave\") ; $=XML_('»',\"raqru\") ; $=XML_('Γ',\"Gamma\") ; $=XML_('1c'x,\"ShortRightArrow\")\n$=XML_('ì','#x00ec') ; $=XML_('░',\"blk12\") ; $=XML_('π',\"pi\") ; $=XML_('!',\"excl\")\n$=XML_('Ä',\"Auml\") ; $=XML_('▒',\"blk14\") ; $=XML_('Σ',\"Sigma\") ; $=XML_('\"',\"apos\")\n$=XML_('Ä','#x00c4') ; $=XML_('▓',\"blk34\") ; $=XML_('σ',\"sigma\") ; $=XML_('$',\"dollar\")\n$=XML_('Å',\"Aring\") ; $=XML_('│',\"boxv\") ; $=XML_('µ',\"mu\") ; $=XML_(\"'\",\"quot\")\n$=XML_('Å','#x00c5') ; $=XML_('┤',\"boxvl\") ; $=XML_('τ',\"tau\") ; $=XML_('*',\"ast\")\n$=XML_('É',\"Eacute\") ; $=XML_('╡',\"boxvL\") ; $=XML_('Φ',\"phi\") ; $=XML_('/',\"sol\")\n$=XML_('É','#x00c9') ; $=XML_('╢',\"boxVl\") ; $=XML_('Θ',\"Theta\") ; $=XML_(':',\"colon\")\n$=XML_('æ',\"aelig\") ; $=XML_('╖',\"boxDl\") ; $=XML_('δ',\"delta\") ; $=XML_('<',\"lt\")\n$=XML_('æ','#x00e6') ; $=XML_('╕',\"boxdL\") ; $=XML_('∞',\"infin\") ; $=XML_('=',\"equals\")\n$=XML_('Æ',\"AElig\") ; $=XML_('╣',\"boxVL\") ; $=XML_('φ',\"Phi\") ; $=XML_('>',\"gt\")\n$=XML_('Æ','#x00c6') ; $=XML_('║',\"boxV\") ; $=XML_('ε',\"epsilon\") ; $=XML_('?',\"quest\")\n$=XML_('ô',\"ocirc\") ; $=XML_('╗',\"boxDL\") ; $=XML_('∩',\"cap\") ; $=XML_('_',\"commat\")\n$=XML_('ô','#x00f4') ; $=XML_('╝',\"boxUL\") ; $=XML_('≡',\"equiv\") ; $=XML_('[',\"lbrack\")\n$=XML_('ö',\"ouml\") ; $=XML_('╜',\"boxUl\") ; $=XML_('±',\"plusmn\") ; $=XML_('\\',\"bsol\")\n$=XML_('ö','#x00f6') ; $=XML_('╛',\"boxuL\") ; $=XML_('±',\"pm\") ; $=XML_(']',\"rbrack\")\n$=XML_('ò',\"ograve\") ; $=XML_('┐',\"boxdl\") ; $=XML_('±',\"PlusMinus\") ; $=XML_('^',\"Hat\")\n$=XML_('ò','#x00f2') ; $=XML_('└',\"boxur\") ; $=XML_('≥',\"ge\") ; $=XML_('`',\"grave\")\n$=XML_('û',\"ucirc\") ; $=XML_('┴',\"bottom\"); $=XML_('≤',\"le\") ; $=XML_('{',\"lbrace\")\n$=XML_('û','#x00fb') ; $=XML_('┴',\"boxhu\") ; $=XML_('÷',\"div\") ; $=XML_('{',\"lcub\")\n$=XML_('ù',\"ugrave\") ; $=XML_('┬',\"boxhd\") ; $=XML_('÷',\"divide\") ; $=XML_('|',\"vert\")\n$=XML_('ù','#x00f9') ; $=XML_('├',\"boxvr\") ; $=XML_('≈',\"approx\") ; $=XML_('|',\"verbar\")\n$=XML_('ÿ',\"yuml\") ; $=XML_('─',\"boxh\") ; $=XML_('∙',\"bull\") ; $=XML_('}',\"rbrace\")\n$=XML_('ÿ','#x00ff') ; $=XML_('┼',\"boxvh\") ; $=XML_('°',\"deg\") ; $=XML_('}',\"rcub\")\n$=XML_('Ö',\"Ouml\") ; $=XML_('╞',\"boxvR\") ; $=XML_('·',\"middot\") ; $=XML_('Ç',\"Ccedil\")\n$=XML_('Ö','#x00d6') ; $=XML_('╟',\"boxVr\") ; $=XML_('·',\"middledot\") ; $=XML_('Ç','#x00c7')\n$=XML_('Ü',\"Uuml\") ; $=XML_('╚',\"boxUR\") ; $=XML_('·',\"centerdot\") ; $=XML_('ü',\"uuml\")\n$=XML_('Ü','#x00dc') ; $=XML_('╔',\"boxDR\") ; $=XML_('·',\"CenterDot\") ; $=XML_('ü','#x00fc')\n$=XML_('¢',\"cent\") ; $=XML_('╩',\"boxHU\") ; $=XML_('√',\"radic\") ; $=XML_('é',\"eacute\")\n$=XML_('£',\"pound\") ; $=XML_('╦',\"boxHD\") ; $=XML_('²',\"sup2\") ; $=XML_('é','#x00e9')\n$=XML_('¥',\"yen\") ; $=XML_('╠',\"boxVR\") ; $=XML_('■',\"square \") ; $=XML_('â',\"acirc\")\nreturn $\n", "language": "REXX" }, { "code": "require 'rexml/document'\ninclude REXML\n\ndoc = Document.new(File.new(\"sample.xml\"))\n# or\n# doc = Document.new(xml_string)\n\n# without using xpath\ndoc.each_recursive do |node|\n puts node.attributes[\"Name\"] if node.name == \"Student\"\nend\n\n# using xpath\ndoc.each_element(\"*/Student\") {|node| puts node.attributes[\"Name\"]}\n", "language": "Ruby" }, { "code": "' ------------------------------------------------------------------------\n'XMLPARSER methods\n\n'#handle ELEMENTCOUNT() - Return the number of child XML elements\n'#handle KEY$() \t- Return the key as a string from an XML expression like <key>value</key>\n'#handle VALUE$() \t- Return the value as a string from an XML expression like <key>value</key>\n'#handle VALUEFORKEY$(keyExpr$) - Return the value for the specified tag key in keyExpr$\n'#handle #ELEMENT(n) \t- Return the nth child-element XML element\n'#handle #ELEMENT(nameExpr$) - Return the child-element XML element named by nameExpr$\n'#handle ATTRIBCOUNT() \t- Return a count of attribute pairs; <a attrA=\"abc\" attrB=\"def\"> has two pairs\n'#handle ATTRIBKEY$(n) \t- Return the key string of the nth attribute\n'#handle ATTRIBVALUE$(n) - Return the value string of the nth attribute\n'#handle ATTRIBVALUE$(n$) - Return the value string of the attribute with the key n$, or an empty string if it doesn't exist.\n'#handle ISNULL() \t- Returns zero (or false)\n'#handle DEBUG$() \t- Returns the string \"Xmlparser\"\n' ------------------------------------------------------------------------\n\n' The xml string\nxml$ = \"\n<Students>\n <Student Name=\"\"April\"\" Gender=\"\"F\"\" DateOfBirth=\"\"1989-01-02\"\" />\n <Student Name=\"\"Bob\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1990-03-04\"\" />\n <Student Name=\"\"Chad\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1991-05-06\"\" />\n <Student Name=\"\"Dave\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1992-07-08\"\">\n <Pet Type=\"\"dog\"\" Name=\"\"Rover\"\" />\n </Student>\n <Student DateOfBirth=\"\"1993-09-10\"\" Gender=\"\"F\"\" Name=\"\"&#x00C9;mily\"\" />\n</Students>\"\n\n\n' Creates the xml handler, using the string\nxmlparser #spies, xml$\n\n' Uses elementCount() to know how many elements are in betweeb <spies>...</spies>\nfor count = 1 to #spies elementCount()\n\n ' Uses \"count\" to work through the elements, and assigns the element to the\n ' handle \"#spy\"\n #spy = #spies #element(count)\n\n ' Prints the value, or inner text, of \"#spy\": Sam, Clover, & Alex\n print count;\" \";#spy value$();\" ->\";#spy ATTRIBVALUE$(1)\n\nnext count\n", "language": "Run-BASIC" }, { "code": "extern crate xml; // provided by the xml-rs crate\nuse xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};\n\nconst DOCUMENT: &str = r#\"\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"#;\n\nfn main() -> Result<(), xml::reader::Error> {\n let parser = EventReader::new(DOCUMENT.as_bytes());\n\n let tag_name = OwnedName::local(\"Student\");\n let attribute_name = OwnedName::local(\"Name\");\n\n for event in parser {\n match event? {\n XmlEvent::StartElement {\n name,\n attributes,\n ..\n } if name == tag_name => {\n if let Some(attribute) = attributes.iter().find(|&attr| attr.name == attribute_name) {\n println!(\"{}\", attribute.value);\n }\n }\n _ => (),\n }\n }\n Ok(())\n}\n", "language": "Rust" }, { "code": "extern crate roxmltree;\n\nconst DOCUMENT: &str = r#\"\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"#;\n\nfn main() -> Result<(), roxmltree::Error> {\n let doc = roxmltree::Document::parse(DOCUMENT)?;\n for node in doc\n .root()\n .descendants()\n .filter(|&child| child.has_tag_name(\"Student\"))\n {\n if let Some(name) = node.attribute(\"Name\") {\n println!(\"{}\", name);\n }\n }\n Ok(())\n}\n", "language": "Rust" }, { "code": "val students =\n <Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n </Students>\n\nstudents \\ \"Student\" \\\\ \"@Name\" foreach println\n", "language": "Scala" }, { "code": "require('XML::Simple');\n\nvar ref = %S'XML::Simple'.XMLin('<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>');\n\nref{:Student}.each { say _{:Name} };\n", "language": "Sidef" }, { "code": "slate[1]> [ |tree|\n\n tree: (Xml SimpleParser newOn: '<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n </Students>') parse.\n tree name = 'Students' ifTrue: [(tree children select: #is: `er <- Xml Element)\n do: [|:child| child name = 'Student' ifTrue: [inform: (child attributes at: 'Name' ifAbsent: ['Noname'])]]].\n\n] do.\nApril\nBob\nChad\nDave\n&#x00C9;mily\nNil\n", "language": "Slate" }, { "code": "import Foundation\n\nlet xmlString = \"\"\"\n<Students>\n\t<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n\t<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n\t<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n\t<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n\t\t<Pet Type=\"dog\" Name=\"Rover\" />\n\t</Student>\n\t<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"\"\"\nif let xmlData = xmlString.data(using: .utf8) {\n\tdo {\n\t\tlet doc = try XMLDocument(data: xmlData)\n\t\tprint(\"Using XPath:\")\n\t\tfor node in try doc.nodes(forXPath: \"/Students/Student/@Name\") {\n\t\t\tguard let name = node.stringValue else { continue }\n\t\t\tprint(name)\n\t\t}\n\t\tprint(\"Using node walk\")\n\t\tif let root = doc.rootElement() {\n\t\t\tfor child in root.elements(forName: \"Student\") {\n\t\t\t\tguard let name = child.attribute(forName: \"Name\")?.stringValue else { continue }\n\t\t\t\tprint(name)\n\t\t\t}\n\t\t}\n\t} catch {\n\t\tdebugPrint(error)\n\t}\n}\n", "language": "Swift" }, { "code": "~ % ./XMLInput\nUsing XPath:\nApril\nBob\nChad\nDave\nÉmily\nUsing node walk\nApril\nBob\nChad\nDave\nÉmily\n", "language": "Swift" }, { "code": "package require tdom\nset tree [dom parse $xml]\nset studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes]\n\nforeach node $studentNodes {\n puts [$node getAttribute Name]\n}\n", "language": "Tcl" }, { "code": "package require xml\nset parser [xml::parser -elementstartcommand elem]\nproc elem {name attlist args} {\n if {$name eq \"Student\"} {\n puts [dict get $attlist Name]\n }\n}\n$parser parse $xml\n", "language": "Tcl" }, { "code": "proc xml2list xml {\n regsub -all {>\\s*<} [string trim $xml \" \\n\\t<>\"] \"\\} \\{\" xml\n set xml [string map {> \"\\} \\{#text \\{\" < \"\\}\\} \\{\"} $xml]\n set res \"\" ;# string to collect the result\n set stack {} ;# track open tags\n set rest {}\n foreach item \"{$xml}\" {\n switch -regexp -- $item {\n\t ^# {append res \"{[lrange $item 0 end]} \" ; #text item}\n\t ^/ {\n\t\tregexp {/(.+)} $item -> tagname ;# end tag\n\t\tset expected [lindex $stack end]\n\t\tset stack [lrange $stack 0 end-1]\n\t\tappend res \"\\}\\} \"\n }\n\t /$ { # singleton - start and end in one <> group\n regexp {([^ ]+)( (.+))?/$} $item -> tagname - rest\n set rest [lrange [string map {= \" \"} $rest] 0 end]\n append res \"{$tagname [list $rest] {}} \"\n\t }\n\t default {\n set tagname [lindex $item 0] ;# start tag\n set rest [lrange [string map {= \" \"} $item] 1 end]\n lappend stack $tagname\n append res \"\\{$tagname [list $rest] \\{\"\n\t }\n }\n }\n string map {\"\\} \\}\" \"\\}\\}\"} [lindex $res 0] ;#\"\n}\nproc deent str {\n regsub -all {&\\#x(.+?);} $str {\\\\u\\1} str\n subst -nocommands -novar $str\n}\n#----------------------- Testing the whole thing:\nset xml {<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" /></Students>\n}\nforeach i [lindex [xml2list $xml] 2] {\n if {[lindex $i 0] eq \"Student\"} {\n foreach {att val} [lindex $i 1] {\n if {$att eq \"Name\"} {puts [deent $val]}\n }\n }\n}\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT\nMODE DATA\n$$ SET xmldata =*\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Emily\" />\n</Students>\n$$ MODE TUSCRIPT\nCOMPILE\nLOOP x = xmldata\nSET name=GET_TAG_NAME (x)\nIF (name!=\"student\") CYCLE\n studentname=GET_ATTRIBUTE (x,\"Name\")\n IF (studentname!=\"\") PRINT studentname\nENDLOOP\nENDCOMPILE\n", "language": "TUSCRIPT" }, { "code": "<Students>\n@(collect :vars (NAME GENDER YEAR MONTH DAY (PET_TYPE \"none\") (PET_NAME \"\")))\n@ (cases)\n <Student Name=\"@NAME\" Gender=\"@GENDER\" DateOfBirth=\"@YEAR-@MONTH-@DAY\"@(skip)\n@ (or)\n <Student DateOfBirth=\"@YEAR-@MONTH-@DAY\" Gender=\"@GENDER\" Name=\"@NAME\"@(skip)\n@ (end)\n@ (maybe)\n <Pet Type=\"@PET_TYPE\" Name=\"@PET_NAME\" />\n@ (end)\n@(until)\n</Students>\n@(end)\n@(output :filter :from_html)\nNAME G DOB PET\n@ (repeat)\n@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME\n@ (end)\n@(end)\n", "language": "TXR" }, { "code": "@(output :filter :from_html)\n@NAME\n@(end)\n", "language": "TXR" }, { "code": "Option Explicit\n\nConst strXml As String = \"\" & _\n\"<Students>\" & _\n \"<Student Name=\"\"April\"\" Gender=\"\"F\"\" DateOfBirth=\"\"1989-01-02\"\" />\" & _\n \"<Student Name=\"\"Bob\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1990-03-04\"\" />\" & _\n \"<Student Name=\"\"Chad\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1991-05-06\"\" />\" & _\n \"<Student Name=\"\"Dave\"\" Gender=\"\"M\"\" DateOfBirth=\"\"1992-07-08\"\">\" & _\n \"<Pet Type=\"\"dog\"\" Name=\"\"Rover\"\" />\" & _\n \"</Student>\" & _\n \"<Student DateOfBirth=\"\"1993-09-10\"\" Gender=\"\"F\"\" Name=\"\"&#x00C9;mily\"\" />\" & _\n\"</Students>\"\n\nSub Main_Xml()\nDim MyXml As Object\nDim myNodes, myNode\n\n With CreateObject(\"MSXML2.DOMDocument\")\n .LoadXML strXml\n Set myNodes = .getElementsByTagName(\"Student\")\n End With\n If Not myNodes Is Nothing Then\n For Each myNode In myNodes\n Debug.Print myNode.getAttribute(\"Name\")\n Next\n End If\n Set myNodes = Nothing\nEnd Sub\n", "language": "VBA" }, { "code": "Repeat(ALL) {\n Search(\"<Student|X\", ERRBREAK)\n #1 = Cur_Pos\n Match_Paren()\n if (Search_Block(/Name=|{\",'}/, #1, Cur_Pos, BEGIN+ADVANCE+NOERR+NORESTORE)==0) { Continue }\n #2 = Cur_Pos\n Search(/|{\",'}/)\n Type_Block(#2, Cur_Pos)\n Type_Newline\n}\n", "language": "Vedit-macro-language" }, { "code": "Dim xml = <Students>\n <Student Name=\"April\"/>\n <Student Name=\"Bob\"/>\n <Student Name=\"Chad\"/>\n <Student Name=\"Dave\"/>\n <Student Name=\"Emily\"/>\n </Students>\n\nDim names = (From node In xml...<Student> Select node.@Name).ToArray\n\nFor Each name In names\n Console.WriteLine(name)\nNext\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./pattern\" for Pattern\nimport \"./fmt\" for Conv\n\nvar xml =\n\"<Students>\n <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\n <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\n <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\n <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\n <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\n </Student>\n <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\n</Students>\"\n\nvar p = Pattern.new(\"<+1^>>\")\nvar p2 = Pattern.new(\" Name/=\\\"[+1^\\\"]\\\"\")\nvar p3 = Pattern.new(\"/&/#x[+1/h];\")\nvar matches = p.findAll(xml)\nfor (m in matches) {\n var text = m.text\n if (text.startsWith(\"<Student \")) {\n var match = p2.find(m.text)\n if (match) {\n var name = match.captures[0].text\n var escapes = p3.findAll(name)\n for (esc in escapes) {\n var hd = esc.captures[0].text\n var char = String.fromCodePoint(Conv.atoi(hd, 16))\n name = name.replace(esc.text, char)\n }\n System.print(name)\n }\n }\n}\n", "language": "Wren" }, { "code": "import \"./xsequence\" for XDocument\n\nvar xml = \"\"\"\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\"\"\"\nvar doc = XDocument.parse(xml)\nvar names = doc.root.elements(\"Student\").map { |el| el.attribute(\"Name\").value }.toList\nSystem.print(names.join(\"\\n\"))\n", "language": "Wren" }, { "code": "code ChOut=8, CrLf=9; \\intrinsic routines\nstring 0; \\use zero-terminated strings\n\nfunc StrLen(A); \\Return number of characters in an ASCIIZ string\nchar A;\nint I;\nfor I:= 0 to -1>>1-1 do\n if A(I) = 0 then return I;\n\nfunc StrFind(A, B); \\Search for ASCIIZ string A in string B\n\\Returns address of first occurrence of string A in B, or zero if A is not found\nchar A, B; \\strings to be compared\nint LA, LB, I, J;\n[LA:= StrLen(A);\nLB:= StrLen(B);\nfor I:= 0 to LB-LA do\n [for J:= 0 to LA-1 do\n if A(J) # B(J+I) then J:= LA+1;\n if J = LA then return B+I; \\found\n ];\nreturn 0;\n];\n\nchar XML, P;\n[XML:= \"<Students>\n <Student Name=^\"April^\" Gender=^\"F^\" DateOfBirth=^\"1989-01-02^\" />\n <Student Name=^\"Bob^\" Gender=^\"M^\" DateOfBirth=^\"1990-03-04^\" />\n <Student Name=^\"Chad^\" Gender=^\"M^\" DateOfBirth=^\"1991-05-06^\" />\n <Student Name=^\"Dave^\" Gender=^\"M^\" DateOfBirth=^\"1992-07-08^\">\n <Pet Type=^\"dog^\" Name=^\"Rover^\" />\n </Student>\n <Student DateOfBirth=^\"1993-09-10^\" Gender=^\"F^\" Name=^\"&#x00C9;mily^\" />\n </Students>\";\nP:= XML;\nloop [P:= StrFind(\"<Student \", P);\n if P=0 then quit;\n P:= StrFind(\"Name=\", P);\n if P=0 then quit;\n P:= P + StrLen(\"Name=x\");\n repeat ChOut(0, P(0));\n P:= P+1;\n until P(0) = ^\";\n CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "// ========== routine for set code conversion ================\n\ndata 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238\ndata 248, 241, 253, 252, 239, 230, 244, 250, 247, 251, 167, 175, 172, 171, 243, 168\ndata 183, 181, 182, 199, 142, 143, 146, 128, 212, 144, 210, 211, 222, 214, 215, 216\ndata 209, 165, 227, 224, 226, 229, 153, 158, 157, 235, 233, 234, 154, 237, 232, 225\ndata 133, 160, 131, 198, 132, 134, 145, 135, 138, 130, 136, 137, 141, 161, 140, 139\ndata 208, 164, 149, 162, 147, 228, 148, 246, 155, 151, 163, 150, 129, 236, 231, 152\n\ninitCode = 160 : TOASCII = 0 : TOUNICODE = 1 : numCodes = 255 - initCode + 1\n\ndim codes(numCodes)\n\nfor i = 0 to numCodes - 1 : read codes(i) : next\n\nsub codeConversion(charcode, tocode)\n local i\n\n if tocode then\n for i = 0 to numCodes - 1\n if codes(i) = charcode return i + initCode\n next\n else\n return codes(charcode - initCode)\n end if\nend sub\n\n// ========== end routine for set code conversion ============\n\nxml$ = \"<Students>\\n\"\nxml$ = xml$ + \" <Student Name=\\\"April\\\" Gender=\\\"F\\\" DateOfBirth=\\\"1989-01-02\\\" />\\n\"\nxml$ = xml$ + \" <Student Name=\\\"Bob\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1990-03-04\\\" />\\n\"\nxml$ = xml$ + \" <Student Name=\\\"Chad\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1991-05-06\\\" />\\n\"\nxml$ = xml$ + \" <Student Name=\\\"Dave\\\" Gender=\\\"M\\\" DateOfBirth=\\\"1992-07-08\\\">\\n\"\nxml$ = xml$ + \" <Pet Type=\\\"dog\\\" Name=\\\"Rover\\\" />\\n\"\nxml$ = xml$ + \" </Student>\\n\"\nxml$ = xml$ + \" <Student DateOfBirth=\\\"1993-09-10\\\" Gender=\\\"F\\\" Name=\\\"&#x00C9;mily\\\" />\\n\"\nxml$ = xml$ + \"</Students>\\n\"\n\ntag1$ = \"<Student\"\ntag2$ = \"Name=\\\"\"\nltag = len(tag2$)\n\nsub convASCII$(name$, mark$)\n local p, c, lm\n\n lm = len(mark$)\n\n do\n p = instr(name$, mark$, p)\n if not p break\n c = dec(mid$(name$, p + lm, 4))\n c = codeConversion(c)\n name$ = left$(name$, p-1) + chr$(c) + right$(name$, len(name$) - (p + lm + 4))\n p = p + 1\n loop\n return name$\nend sub\n\ndo\n p = instr(xml$, tag1$, p)\n if not p break\n p = instr(xml$, tag2$, p)\n p = p + ltag\n p2 = instr(xml$, \"\\\"\", p)\n name$ = convASCII$(mid$(xml$, p, p2 - p), \"&#x\")\n print name$\nloop\n", "language": "Yabasic" }, { "code": "student:=RegExp(0'|.*<Student\\s*.+Name\\s*=\\s*\"([^\"]+)\"|);\nunicode:=RegExp(0'|.*(&#x[0-9a-fA-F]+;)|);\nxml:=File(\"foo.xml\").read();\n\nstudents:=xml.pump(List,'wrap(line){\n if(student.search(line)){\n s:=student.matched[1]; // ( (match start,len),group text )\n while(unicode.search(s)){ // convert \"&#x00C9;\" to 0xc9 to UTF-8\n\t c:=unicode.matched[1];\n\t uc:=c[3,-1].toInt(16).toString(-8);\n \t s=s.replace(c,uc);\n }\n s\n }\n else Void.Skip; // line doesn't contain <Student ... Name ...\n});\n\nstudents.println();\n", "language": "Zkl" } ]
XML-Input
[ { "code": "---\nfrom: http://rosettacode.org/wiki/XML/Output\nnote: XML\n", "language": "00-META" }, { "code": "Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <code><Character></code> elements each with a name attributes and each enclosing its remarks. \nAll <code><Character></code> elements are to be enclosed in turn, in an outer <code><CharacterRemarks></code> element. \n\nAs an example, calling the function with the three names of: \n<pre>\nApril\nTam O'Shanter\nEmily</pre>\nAnd three remarks of:\n<pre>\nBubbly: I'm > Tam and <= Emily\nBurns: \"When chapman billies leave the street ...\"\nShort & shrift</pre>\nShould produce the XML (but not necessarily with the indentation):\n<syntaxhighlight lang=\"xml\"><CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks></syntaxhighlight>\n\nThe document may include an <tt><?xml?></tt> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation ''must'' include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.\n\nNote: the example is chosen to show correct escaping of XML strings.\nNote too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.\n\n'''Note to editors:''' Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See [[Talk:XML_Creation#Escaping_Escapes|this]]). \nAlternately, output can be placed in <nowiki><syntaxhighlight lang=\"xml\"></syntaxhighlight></nowiki> tags without any special treatment.\n\n", "language": "00-TASK" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program outputXml64.s */\n/* use special library libxml2 */\n/* special link gcc with options -I/usr/include/libxml2 -lxml2 */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"Normal end of program.\\n\"\nszFileName: .asciz \"file2.xml\"\nszFileMode: .asciz \"w\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszName1: .asciz \"April\"\nszName2: .asciz \"Tam O'Shanter\"\nszName3: .asciz \"Emily\"\nszRemark1: .asciz \"Bubbly: I'm > Tam and <= Emily\"\nszRemark2: .asciz \"Burns: \\\"When chapman billies leave the street ...\\\"\"\nszRemark3: .asciz \"Short & shrift\"\nszVersDoc: .asciz \"1.0\"\nszLibCharRem: .asciz \"CharacterRemarks\"\nszLibChar: .asciz \"Character\"\n\nszLibName: .asciz \"Name\"\nszCarriageReturn: .asciz \"\\n\"\n\ntbNames: .quad szName1 // area of pointer string name\n .quad szName2\n .quad szName3\n .quad 0 // area end\ntbRemarks: .quad szRemark1 // area of pointer string remark\n .quad szRemark2\n .quad szRemark3\n .quad 0 // area end\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrszVersDoc\n bl xmlNewDoc // create doc\n mov x19,x0 // doc address\n mov x0,#0\n ldr x1,qAdrszLibCharRem\n bl xmlNewNode // create root node\n mov x20,x0 // node characterisation address\n mov x0,x19 // doc\n mov x1,x20 // node root\n bl xmlDocSetRootElement\n ldr x22,qAdrtbNames\n ldr x23,qAdrtbRemarks\n mov x24,#0 // loop counter\n1: // start loop\n mov x0,#0\n ldr x1,qAdrszLibChar // create node\n bl xmlNewNode\n mov x21,x0 // node character\n // x0 = node address\n ldr x1,qAdrszLibName\n ldr x2,[x22,x24,lsl #3] // load name string address\n bl xmlNewProp\n ldr x0,[x23,x24,lsl #3] // load remark string address\n bl xmlNewText\n mov x1,x0\n mov x0,x21\n bl xmlAddChild\n mov x0,x20\n mov x1,x21\n bl xmlAddChild\n add x24,x24,#1\n ldr x2,[x22,x24,lsl #3] // load name string address\n cmp x2,#0 // = zero ?\n bne 1b // no -> loop\n\n ldr x0,qAdrszFileName\n ldr x1,qAdrszFileMode\n bl fopen // file open\n cmp x0,#0\n blt 99f\n mov x24,x0 //FD\n mov x1,x19\n mov x2,x20\n bl xmlDocDump // write doc on the file\n\n mov x0,x24 // close file\n bl fclose\n mov x0,x19 // close document\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr x0,qAdrszMessEndpgm\n bl affichageMess\n b 100f\n99: // error\n ldr x0,qAdrszMessError\n bl affichageMess\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n\nqAdrszMessError: .quad szMessError\nqAdrszMessEndpgm: .quad szMessEndpgm\nqAdrszVersDoc: .quad szVersDoc\nqAdrszLibCharRem: .quad szLibCharRem\nqAdrszLibChar: .quad szLibChar\nqAdrszLibName: .quad szLibName\nqAdrtbNames: .quad tbNames\nqAdrtbRemarks: .quad tbRemarks\nqAdrszCarriageReturn: .quad szCarriageReturn\nqStdout: .quad STDOUT\nqAdrszFileName: .quad szFileName\nqAdrszFileMode: .quad szFileMode\n\n/************************************/\n/* Strings comparaison */\n/************************************/\n/* x0 et x1 contains strings addresses */\n/* x0 return 0 dans x0 if equal */\n/* return -1 if string x0 < string x1 */\n/* return 1 if string x0 > string x1 */\ncomparString:\n stp x2,lr,[sp,-16]! // save registers\n stp x3,x4,[sp,-16]! // save registers\n mov x2,#0 // indice\n1:\n ldrb w3,[x0,x2] // one byte string 1\n ldrb w4,[x1,x2] // one byte string 2\n cmp w3,w4\n blt 2f // less\n bgt 3f // greather\n cmp w3,#0 // 0 final\n beq 4f // equal and end\n add x2,x2,#1 //\n b 1b // else loop\n2:\n mov x0,#-1 // less\n b 100f\n3:\n mov x0,#1 // greather\n b 100f\n4:\n mov x0,#0 // equal\n b 100f\n100:\n ldp x3,x4,[sp],16 // restaur 2 registers\n ldp x2,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "DEFINE PTR=\"CARD\"\nDEFINE CHARACTER_SIZE=\"4\"\nTYPE Character=[PTR name,remark]\n\nPTR FUNC GetCharacterPointer(BYTE ARRAY d INT index)\nRETURN (d+index*CHARACTER_SIZE)\n\nPROC SetCharacter(BYTE ARRAY d INT index CHAR ARRAY n,r)\n Character POINTER ch\n\n ch=GetCharacterPointer(d,index)\n ch.name=n\n ch.remark=r\nRETURN\n\nPROC PrintEscaped(CHAR ARRAY s)\n INT i\n CHAR c\n\n FOR i=1 TO s(0)\n DO\n c=s(i)\n IF c='< THEN\n Print(\"&lt;\")\n ELSEIF c='> THEN\n Print(\"&gt;\")\n ELSEIF c='& THEN\n Print(\"&amp;\")\n ELSE\n Put(c)\n FI\n OD\nRETURN\n\nPROC OutputNode(CHAR ARRAY node,tagName,tagValue BYTE closing)\n Put('<)\n IF closing THEN Put('/) FI\n Print(node)\n IF tagName(0)>0 THEN\n PrintF(\" %S=\"\"\",tagName)\n PrintEscaped(tagValue) Put('\")\n FI\n Put('>)\nRETURN\n\nPROC OutputCharacter(Character POINTER ch)\n CHAR ARRAY node=\"Character\"\n\n OutputNode(node,\"name\",ch.name,0)\n PrintEscaped(ch.remark)\n OutputNode(node,\"\",\"\",1)\nRETURN\n\nPROC OutputCharacters(BYTE ARRAY d INT count)\n CHAR ARRAY node=\"CharacterRemarks\"\n Character POINTER ch\n INT i\n\n OutputNode(node,\"\",\"\",0) PutE()\n FOR i=0 TO count-1\n DO\n ch=GetCharacterPointer(d,i)\n OutputCharacter(ch) PutE()\n OD\n OutputNode(node,\"\",\"\",1) PutE()\nRETURN\n\nPROC Main()\n BYTE count=[3]\n BYTE ARRAY d(12)\n\n SetCharacter(d,0,\"April\",\"Bubbly: I'm > Tam and <= Emily\")\n SetCharacter(d,1,\"Tam O'Shanter\",\"Burns: \"\"When chapman billies leave the street ...\"\"\")\n SetCharacter(d,2,\"Emily\",\"Short & shrift\")\n\n OutputCharacters(d,count)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Strings.Unbounded;\nwith Ada.Text_IO.Text_Streams;\nwith DOM.Core.Documents;\nwith DOM.Core.Elements;\nwith DOM.Core.Nodes;\n\nprocedure Character_Remarks is\n package DC renames DOM.Core;\n package IO renames Ada.Text_IO;\n package US renames Ada.Strings.Unbounded;\n type Remarks is record\n Name : US.Unbounded_String;\n Text : US.Unbounded_String;\n end record;\n type Remark_List is array (Positive range <>) of Remarks;\n My_Remarks : Remark_List :=\n ((US.To_Unbounded_String (\"April\"),\n US.To_Unbounded_String (\"Bubbly: I'm > Tam and <= Emily\")),\n (US.To_Unbounded_String (\"Tam O'Shanter\"),\n US.To_Unbounded_String (\"Burns: \"\"When chapman billies leave the street ...\"\"\")),\n (US.To_Unbounded_String (\"Emily\"),\n US.To_Unbounded_String (\"Short & shrift\")));\n My_Implementation : DC.DOM_Implementation;\n My_Document : DC.Document := DC.Create_Document (My_Implementation);\n My_Root_Node : DC.Element := DC.Nodes.Append_Child (My_Document,\n DC.Documents.Create_Element (My_Document, \"CharacterRemarks\"));\n My_Element_Node : DC.Element;\n My_Text_Node : DC.Text;\nbegin\n for I in My_Remarks'Range loop\n My_Element_Node := DC.Nodes.Append_Child (My_Root_Node,\n DC.Documents.Create_Element (My_Document, \"Character\"));\n DC.Elements.Set_Attribute (My_Element_Node, \"Name\", US.To_String (My_Remarks (I).Name));\n My_Text_Node := DC.Nodes.Append_Child (My_Element_Node,\n DC.Documents.Create_Text_Node (My_Document, US.To_String (My_Remarks (I).Text)));\n end loop;\n DC.Nodes.Write (IO.Text_Streams.Stream (IO.Standard_Output),\n N => My_Document,\n Pretty_Print => True);\nend Character_Remarks;\n", "language": "Ada" }, { "code": "with Ada.Wide_Wide_Text_IO;\n\nwith League.Strings;\nwith XML.SAX.Attributes;\nwith XML.SAX.Pretty_Writers;\n\nprocedure Main is\n\n function \"+\"\n (Item : Wide_Wide_String) return League.Strings.Universal_String\n renames League.Strings.To_Universal_String;\n\n type Remarks is record\n Name : League.Strings.Universal_String;\n Remark : League.Strings.Universal_String;\n end record;\n\n type Remarks_Array is array (Positive range <>) of Remarks;\n\n ------------\n -- Output --\n ------------\n\n procedure Output (Remarks : Remarks_Array) is\n Writer : XML.SAX.Pretty_Writers.SAX_Pretty_Writer;\n Attributes : XML.SAX.Attributes.SAX_Attributes;\n\n begin\n Writer.Set_Offset (2);\n Writer.Start_Document;\n Writer.Start_Element (Qualified_Name => +\"CharacterRemarks\");\n\n for J in Remarks'Range loop\n Attributes.Clear;\n Attributes.Set_Value (+\"name\", Remarks (J).Name);\n Writer.Start_Element\n (Qualified_Name => +\"Character\", Attributes => Attributes);\n Writer.Characters (Remarks (J).Remark);\n Writer.End_Element (Qualified_Name => +\"Character\");\n end loop;\n\n Writer.End_Element (Qualified_Name => +\"CharacterRemarks\");\n Writer.End_Document;\n\n Ada.Wide_Wide_Text_IO.Put_Line (Writer.Text.To_Wide_Wide_String);\n end Output;\n\nbegin\n Output\n (((+\"April\", +\"Bubbly: I'm > Tam and <= Emily\"),\n (+\"Tam O'Shanter\", +\"Burns: \"\"When chapman billies leave the street ...\"\"\"),\n (+\"Emily\", +\"Short & shrift\")));\nend Main;\n", "language": "Ada" }, { "code": "# returns a translation of str suitable for attribute values and content in an XML document #\nOP TOXMLSTRING = ( STRING str )STRING:\n BEGIN\n STRING result := \"\";\n FOR pos FROM LWB str TO UPB str DO\n CHAR c = str[ pos ];\n result +:= IF c = \"<\" THEN \"&lt;\"\n ELIF c = \">\" THEN \"&gt;\"\n ELIF c = \"&\" THEN \"&amp;\"\n ELIF c = \"'\" THEN \"&apos;\"\n ELIF c = \"\"\"\" THEN \"&quot;\"\n ELSE c\n FI\n OD;\n result\n END; # TOXMLSTRING #\n\n# generate a CharacterRemarks XML document from the characters and remarks #\n# the number of elements in characters and remrks must be equal - this is not checked #\n# the <?xml?> element is not generated #\nPROC generate character remarks document = ( []STRING characters, remarks )STRING:\n BEGIN\n STRING result := \"<CharacterRemarks>\";\n INT remark pos := LWB remarks;\n FOR char pos FROM LWB characters TO UPB characters DO\n result +:= \"<Character name=\"\"\" + TOXMLSTRING characters[ char pos ] + \"\"\">\"\n + TOXMLSTRING remarks[ remark pos ]\n + \"</Character>\"\n + REPR 10\n ;\n remark pos +:= 1\n OD;\n result +:= \"</CharacterRemarks>\";\n result\n END; # generate character remarks document #\n\n# test the generation #\nprint( ( generate character remarks document( ( \"April\", \"Tam O'Shanter\", \"Emily\" )\n , ( \"Bubbly: I'm > Tam and <= Emily\"\n , \"Burns: \"\"When chapman billies leave the street ...\"\n , \"Short & shrift\"\n )\n )\n , newline\n )\n )\n", "language": "ALGOL-68" }, { "code": "<CharacterRemarks><Character name=\"April\">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O&apos;Shanter\">Burns: &quot;When chapman billies leave the street ...</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "ALGOL-68" }, { "code": "100 Q$ = CHR$(34)\n110 DE$(0) = \"April\"\n120 RE$(0) = \"Bubbly: I'm > Tam and <= Emily\"\n130 DE$(1) = \"Tam O'Shanter\"\n140 RE$(1) = \"Burns: \" + Q$ + \"When chapman billies leave the street ...\" + Q$\n150 DE$(2) = \"Emily\"\n160 RE$(2) = \"Short & shrift\"\n\n200 Print \"<CharacterRemarks>\"\n210 For I = 0 to 2\n220 Print \" <Character name=\"Q$;\n230 X$=DE$(I) : GOSUB 300xmlquote\n240 PRINT Q$\">\";\n250 X$=RE$(I) : GOSUB 300xmlquote\n260 PRINT \"</Character>\"\n270 Next\n280 Print \"</CharacterRemarks>\"\n290 End\n\n300 For n = 1 To Len(X$)\n310 c$ = Mid$(X$,n,1)\n320 IF C$ = \"<\" THEN C$ = \"&lt;\"\n330 IF C$ = \">\" THEN C$ = \"&gt;\"\n340 IF C$ = \"&\" THEN C$ = \"&amp;\"\n350 IF C$ = Q$ THEN C$ = \"&quot;\"\n360 IF C$ = \"'\" THEN C$ = \"&apos;\"\n370 PRINT C$;\n380 NEXT N\n390 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program outputXml.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"Normal end of program.\\n\"\nszFileName: .asciz \"file2.xml\"\nszFileMode: .asciz \"w\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\nszName1: .asciz \"April\"\nszName2: .asciz \"Tam O'Shanter\"\nszName3: .asciz \"Emily\"\nszRemark1: .asciz \"Bubbly: I'm > Tam and <= Emily\"\nszRemark2: .asciz \"Burns: \\\"When chapman billies leave the street ...\\\"\"\nszRemark3: .asciz \"Short & shrift\"\nszVersDoc: .asciz \"1.0\"\nszLibCharRem: .asciz \"CharacterRemarks\"\nszLibChar: .asciz \"Character\"\n\n//szLibExtract: .asciz \"Student\"\nszLibName: .asciz \"Name\"\nszCarriageReturn: .asciz \"\\n\"\n\ntbNames: .int szName1 @ area of pointer string name\n .int szName2\n .int szName3\n .int 0 @ area end\ntbRemarks: .int szRemark1 @ area of pointer string remark\n .int szRemark2\n .int szRemark3\n .int 0 @ area end\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\n\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrszVersDoc\n bl xmlNewDoc @ create doc\n mov r9,r0 @ doc address\n mov r0,#0\n ldr r1,iAdrszLibCharRem\n bl xmlNewNode @ create root node\n mov r8,r0 @ node characterisation address\n mov r0,r9 @ doc\n mov r1,r8 @ node root\n bl xmlDocSetRootElement\n ldr r4,iAdrtbNames\n ldr r5,iAdrtbRemarks\n mov r6,#0 @ loop counter\n1: @ start loop\n mov r0,#0\n ldr r1,iAdrszLibChar @ create node\n bl xmlNewNode\n mov r7,r0 @ node character\n @ r0 = node address\n ldr r1,iAdrszLibName\n ldr r2,[r4,r6,lsl #2] @ load name string address\n bl xmlNewProp\n ldr r0,[r5,r6,lsl #2] @ load remark string address\n bl xmlNewText\n mov r1,r0\n mov r0,r7\n bl xmlAddChild\n mov r0,r8\n mov r1,r7\n bl xmlAddChild\n add r6,#1\n ldr r2,[r4,r6,lsl #2] @ load name string address\n cmp r2,#0 @ = zero ?\n bne 1b @ no -> loop\n\n ldr r0,iAdrszFileName\n ldr r1,iAdrszFileMode\n bl fopen @ file open\n cmp r0,#0\n blt 99f\n mov r6,r0 @FD\n mov r1,r9\n mov r2,r8\n bl xmlDocDump @ write doc on the file\n\n mov r0,r6\n bl fclose\n mov r0,r9\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr r0,iAdrszMessEndpgm\n bl affichageMess\n b 100f\n99:\n @ error\n ldr r0,iAdrszMessError\n bl affichageMess\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrszMessEndpgm: .int szMessEndpgm\niAdrszVersDoc: .int szVersDoc\niAdrszLibCharRem: .int szLibCharRem\niAdrszLibChar: .int szLibChar\niAdrszLibName: .int szLibName\niAdrtbNames: .int tbNames\niAdrtbRemarks: .int tbRemarks\niAdrszCarriageReturn: .int szCarriageReturn\niStdout: .int STDOUT\niAdrszFileName: .int szFileName\niAdrszFileMode: .int szFileMode\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur registers */\n bx lr @ return\n/******************************************************************/\n/* Converting a register to a decimal */\n/******************************************************************/\n/* r0 contains value and r1 address area */\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers\n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0\n subne r2,#1 @ previous position\n bne 1b @ else loop\n @ end replaces digit in front of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4] @ store in area begin\n add r4,#1\n add r2,#1 @ previous position\n cmp r2,#LGZONECAL @ end\n ble 2b @ loop\n mov r1,#' '\n3:\n strb r1,[r3,r4]\n add r4,#1\n cmp r4,#LGZONECAL @ end\n ble 3b\n100:\n pop {r1-r4,lr} @ restaur registres\n bx lr @return\n/***************************************************/\n/* division par 10 signé */\n/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*\n/* and http://www.hackersdelight.org/ */\n/***************************************************/\n/* r0 dividende */\n/* r0 quotient */\n/* r1 remainder */\ndivisionpar10:\n /* r0 contains the argument to be divided by 10 */\n push {r2-r4} @ save registers */\n mov r4,r0\n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)\n mov r2, r2, ASR #2 @ r2 <- r2 >> 2\n mov r1, r0, LSR #31 @ r1 <- r0 >> 31\n add r0, r2, r1 @ r0 <- r2 + r1\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5\n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2-r4}\n bx lr @ return\n", "language": "ARM-Assembly" }, { "code": "gosub constants\nnames := xmlescape(names)\nremarks := xmlescape(remarks)\n\nstringsplit, remarks, remarks, `n\nxml = \"<CharacterRemarks>\"\n\nloop, parse, names, `n\n xml .= \"<Character name=\" . A_LoopField . \">\" . remarks%A_Index%\n . \"</Character>`n\"\n\nxml .= \"</CharacterRemarks>\"\n\nmsgbox % xml\nreturn\n\nxmlescape(string)\n{\n static\n punc = \",>,<,<=,>=,',& ; \"\n xmlpunc = &quot;,&gt;,&lt;,&lt;=,&gt;=,&apos;,&amp;\n if !punc1\n {\n\tStringSplit, punc, punc, `,\n\tStringSplit, xmlpunc, xmlpunc, `,\n }\n escaped := string\n loop, parse, punc, `,\n {\n StringReplace, escaped, escaped, % A_LoopField, % xmlpunc%A_Index%, All\n }\n Return escaped\n}\n\nconstants:\n#LTrim\nnames =\n(\n April\n Tam O'Shanter\n Emily\n)\n\nremarks =\n(\n Bubbly: I'm > Tam and <= Emily\n Burns: \"When chapman billies leave the street ...\"\n Short & shrift\n)\nreturn\n", "language": "AutoHotkey" }, { "code": "( ( 2XML\n = PCDATAentities attributeValueEntities doAll doAttributes\n , xml\n . ( attributeValueEntities\n = a c\n . @( !arg\n : ?a\n ((\"<\"|\"&\"|\\\"):?c)\n ?arg\n )\n & !a\n \"&\"\n ( !c:\"<\"&lt\n | !c:\"&\"&amp\n | quot\n )\n \";\"\n attributeValueEntities$!arg\n | !arg\n )\n & ( PCDATAentities\n = a c\n . @( !arg\n : ?a\n ((\"<\"|\"&\"|\">\"):?c)\n ?arg\n )\n & !a\n \"&\"\n ( !c:\"<\"&lt\n | !c:\"&\"&amp\n | gt\n )\n \";\"\n PCDATAentities$!arg\n | !arg\n )\n & ( doAttributes\n = a v\n . !arg:(?a.?v) ?arg\n & \" \"\n PCDATAentities$!a\n \"=\\\"\"\n attributeValueEntities$!v\n \\\"\n doAttributes$!arg\n |\n )\n & ( doAll\n = xml first A B C att XML\n . !arg:?xml\n & :?XML\n & whl\n ' ( !xml:%?first ?xml\n & ( !first:(?A.?B)\n & ( !B:(?att,?C)\n & !XML\n ( !C:\n & \"<\" !A doAttributes$!att \" />\\n\"\n | \"<\"\n !A\n doAttributes$!att\n \">\"\n doAll$!C\n \"</\"\n !A\n \">\\n\"\n )\n : ?XML\n | !A\n : ( \"!\"&!XML \"<!\" !B \">\":?XML\n | \"!--\"\n & !XML \"<!--\" !B \"-->\":?XML\n | \"?\"&!XML \"<?\" !B \"?>\\n\":?XML\n | \"![CDATA[\"\n & !XML \"<![CDATA[\" !B \"]]>\":?XML\n | \"!DOCTYPE\"\n & !XML \"<!DOCTYPE\" !B \">\":?XML\n | ?\n & !XML \"<\" !A doAttributes$!B \">\":?XML\n )\n )\n | !XML PCDATAentities$!first:?XML\n )\n )\n & str$!XML\n )\n & doAll$!arg\n )\n& ( makeList\n = characters name names remark remarks\n . !arg:(?names.?remarks)\n & :?characters\n & whl\n ' ( (!names.!remarks)\n : (%?name ?names.%?remark ?remarks)\n & !characters (Character.(name.!name),!remark)\n : ?characters\n )\n & (\"?\".xml) (CharacterRemarks.,!characters)\n )\n& put\n $ ( 2XML\n $ ( makeList\n $ ( April \"Tam O'Shanter\" Emily\n . \"Bubbly: I'm > Tam and <= Emily\"\n \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n \"Short & shrift\"\n )\n )\n )\n)\n", "language": "Bracmat" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\nconst char *names[] = {\n \"April\", \"Tam O'Shanter\", \"Emily\", NULL\n};\nconst char *remarks[] = {\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\", NULL\n};\n\nint main()\n{\n xmlDoc *doc = NULL;\n xmlNode *root = NULL, *node;\n const char **next;\n int a;\n\n doc = xmlNewDoc(\"1.0\");\n root = xmlNewNode(NULL, \"CharacterRemarks\");\n xmlDocSetRootElement(doc, root);\n\n for(next = names, a = 0; *next != NULL; next++, a++) {\n node = xmlNewNode(NULL, \"Character\");\n (void)xmlNewProp(node, \"name\", *next);\n xmlAddChild(node, xmlNewText(remarks[a]));\n xmlAddChild(root, node);\n }\n\n xmlElemDump(stdout, doc, root);\n\n xmlFreeDoc(doc);\n xmlCleanupParser();\n\n return EXIT_SUCCESS;\n}\n", "language": "C" }, { "code": "#include <gadget/gadget.h>\n\nLIB_GADGET_START\n\nconst char* codes[] = {\"&amp;\",\"&gt;\",\"&lt;\"};\nconst char* repl[] = {\"&\",\">\",\"<\"};\n\nchar* change_codes( const char* xml_line )\n{\n int i;\n String xml;\n Let( xml, xml_line );\n Iterator up i [0:1:3]{\n Get_fn_let( xml, Str_tran( xml, repl[i], codes[i] ) );\n }\n return xml;\n}\nchar* generate_xml( const char* names[], int lnames, const char* remarks[] )\n{\n String xml;\n char attrib[100];\n int i;\n Iterator up i [0:1:lnames]{\n String remk;\n Get_fn_let ( remk, change_codes( remarks[i] ) );\n sprintf(attrib,\"name=\\\"%s\\\"\",names[i]);\n if(!i) {\n Get_fn_let ( xml, Parser(\"Character\", attrib, remk, NORMAL_TAG ));\n }else{\n Get_fn_cat ( xml, Parser(\"Character\", attrib, remk, NORMAL_TAG ));\n }\n Free secure remk;\n }\n Get_fn_let ( xml, Parser(\"CharacterRemarks\", \"\", xml, NORMAL_TAG ));\n Get_fn_let ( xml, Str_tran(xml,\"><\",\">\\n<\") );\n\n return xml;\n}\n\n#define alen(_X_) ( sizeof(_X_) / sizeof(const char*) )\nMain\n const char *names[] = {\n \"April\", \"Tam O'Shanter\", \"Emily\"\n };\n const char *remarks[] = {\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\n };\n char* xml = generate_xml( names, alen(names), remarks );\n Print \"%s\\n\", xml;\n Free secure xml;\nEnd\n", "language": "C" }, { "code": "<CharacterRemarks>\n<Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "C" }, { "code": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <boost/algorithm/string.hpp>\n\nstd::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;\n\nint main( ) {\n std::vector<std::string> names , remarks ;\n names.push_back( \"April\" ) ;\n names.push_back( \"Tam O'Shantor\" ) ;\n names.push_back ( \"Emily\" ) ;\n remarks.push_back( \"Bubbly, I'm > Tam and <= Emily\" ) ;\n remarks.push_back( \"Burns: \\\"When chapman billies leave the street ...\\\"\" ) ;\n remarks.push_back( \"Short & shrift\" ) ;\n std::cout << \"This is in XML:\\n\" ;\n std::cout << create_xml( names , remarks ) << std::endl ;\n return 0 ;\n}\n\nstd::string create_xml( std::vector<std::string> & names ,\n std::vector<std::string> & remarks ) {\n std::vector<std::pair<std::string , std::string> > entities ;\n entities.push_back( std::make_pair( \"&\" , \"&amp;\" ) ) ;\n entities.push_back( std::make_pair( \"<\" , \"&lt;\" ) ) ;\n entities.push_back( std::make_pair( \">\" , \"&gt;\" ) ) ;\n std::string xmlstring ( \"<CharacterRemarks>\\n\" ) ;\n std::vector<std::string>::iterator vsi = names.begin( ) ;\n typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;\n for ( ; vsi != names.end( ) ; vsi++ ) {\n for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n }\n }\n for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {\n for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {\n\t boost::replace_all ( *vsi , vs->first , vs->second ) ;\n }\n }\n for ( int i = 0 ; i < names.size( ) ; i++ ) {\n xmlstring.append( \"\\t<Character name=\\\"\").append( names[ i ] ).append( \"\\\">\")\n\t .append( remarks[ i ] ).append( \"</Character>\\n\" ) ;\n }\n xmlstring.append( \"</CharacterRemarks>\" ) ;\n return xmlstring ;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Program\n{\n static string CreateXML(Dictionary<string, string> characterRemarks)\n {\n var remarks = characterRemarks.Select(r => new XElement(\"Character\", r.Value, new XAttribute(\"Name\", r.Key)));\n var xml = new XElement(\"CharacterRemarks\", remarks);\n return xml.ToString();\n }\n\n static void Main(string[] args)\n {\n var characterRemarks = new Dictionary<string, string>\n {\n { \"April\", \"Bubbly: I'm > Tam and <= Emily\" },\n { \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" },\n { \"Emily\", \"Short & shrift\" }\n };\n\n string xml = CreateXML(characterRemarks);\n Console.WriteLine(xml);\n }\n}\n", "language": "C-sharp" }, { "code": "(use 'clojure.xml)\n(defn character-remarks-xml [characters remarks]\n (with-out-str (emit-element\n {:tag :CharacterRemarks,\n :attrs nil,\n :content (vec (for [item (map vector characters remarks)]\n {:tag :Character,\n :attrs {:name (item 0)},\n :content [(item 1)]}) )})))\n", "language": "Clojure" }, { "code": "1 rem xml/output - commodore basic\n2 rem rosetta code\n5 print chr$(147);chr$(14):gosub 900\n10 rem set up array structure for data\n11 rem we'll use a multi-dimensional array:\n12 rem c$(x,y) where x is the rows and y is the fields\n13 rem two fields: 0 = character name, 1 = remarks\n15 dim c$(10,1):x=0:q$=chr$(34)\n19 rem now read the data to populate the structure\n20 for y=0 to 1\n25 read t$\n30 if t$=\"[end]\" then x=x-1:goto 45\n35 c$(x,y)=t$:print t$\n40 next y:x=x+1:print:goto 20\n45 rem need to sanitize for html entities\n50 gosub 500\n55 rem now we parse it out to xml format\n60 print:print:gosub 150\n70 end\n75 :\n150 print \"<CharacterRemarks>\"\n155 for i=0 to x\n160 t$=\"<Character name=\"+q$+c$(i,0)+q$+\">\"\n165 t$=t$+c$(i,1)+\"</Character>\"\n170 print \" \";t$\n175 next i\n180 print \"</CharacterRemarks>\"\n185 print\n190 return\n195 :\n500 rem code html entities\n505 for i=0 to x\n510 for j=0 to 1\n515 tm$=c$(i,j):tl=len(tm$):zz$=\"\"\n520 for tc=1 to tl\n525 tc$=mid$(tm$,tc,1):cv=asc(tc$) and 127\n530 zz$=zz$+et$(cv)\n535 next tc\n540 c$(i,j)=zz$\n545 next j,i\n550 return\n555 :\n900 rem set up entity lookup table\n905 dim et$(127):for i=0 to 127:et$(i)=chr$(i):next\n910 for i=1 to 15:read ci,et$(ci):next i:return\n915 data 34,\"&quot;\",63,\"&quest;\",35,\"&num;\",64,\"&commat;\",47,\"&sol;\"\n920 data 60,\"&lt;\",62,\"&gt;\",91,\"&lsqb;\",93,\"rsqb;\",92,\"&pound;\"\n925 data 36,\"&dollar;\",37,\"&percnt;\",94,\"&uarr;\",95,\"&larr;\"\n930 data 38,\"&amp;\"\n935 :\n1000 data \"April\",\"Bubble: I'm > Tam and <= Emily\"\n1005 data \"Tam O'Shanter\",\"Burns: 'When chapman billies leave the street...'\"\n1010 data \"Emily\",\"Short & shrift\"\n1015 data \"Joey\",\"Always look ^.\"\n1999 data \"[end]\",\"[end]\"\n", "language": "Commodore-BASIC" }, { "code": "(defun write-xml (characters lines &optional (out *standard-output*))\n (let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))\n (chars (dom:append-child doc (dom:create-element doc \"Characters\"))))\n (map nil (lambda (character line)\n (let ((c (dom:create-element doc \"Character\")))\n (dom:set-attribute c \"name\" character)\n (dom:append-child c (dom:create-text-node doc line))\n (dom:append-child chars c)))\n characters lines)\n (write-string (dom:map-document (cxml:make-rod-sink) doc) out)))\n", "language": "Common-Lisp" }, { "code": "(write-xml '(\"April\" \"Tam O'Shanter\" \"Emily\")\n '(\"Bubbly: I'm > Tam and <= Emily\"\n \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n \"Short & shrift\"))\n", "language": "Common-Lisp" }, { "code": "import kxml.xml;\nchar[][][]characters =\n [[\"April\",\"Bubbly: I'm > Tam and <= Emily\"],\n [\"Tam O'Shanter\",\"Burns: \\\"When chapman billies leave the street ...\\\"\"],\n [\"Emily\",\"Short & shrift\"]];\nvoid addChars(XmlNode root,char[][][]info) {\n auto remarks = new XmlNode(\"CharacterRemarks\");\n root.addChild(remarks);\n foreach(set;info) {\n remarks.addChild((new XmlNode(\"Character\")).setAttribute(\"name\",set[0]).addCData(set[1]));\n }\n}\nvoid main() {\n auto root = new XmlNode(\"\");\n root.addChild(new XmlPI(\"xml\"));\n addChars(root,characters);\n std.stdio.writefln(\"%s\",root.write);\n}\n", "language": "D" }, { "code": "//You need to use these units\nuses\n Classes,\n Dialogs,\n XMLIntf,\n XMLDoc;\n\n//..............................................\n\n//This function creates the XML\nfunction CreateXML(aNames, aRemarks: TStringList): string;\nvar\n XMLDoc: IXMLDocument;\n Root: IXMLNode;\n i: Integer;\nbegin\n //Input check\n if (aNames = nil) or\n (aRemarks = nil) then\n begin\n Result:= '<CharacterRemarks />';\n Exit;\n end;\n\n //Creating the TXMLDocument instance\n XMLDoc:= TXMLDocument.Create(nil);\n\n //Activating the document\n XMLDoc.Active:= True;\n\n //Creating the Root element\n Root:= XMLDoc.AddChild('CharacterRemarks');\n\n //Creating the inner nodes\n for i:=0 to Min(aNames.Count, aRemarks.Count) - 1 do\n with Root.AddChild('Character') do\n begin\n Attributes['name']:= aNames[i];\n Text:= aRemarks[i];\n end;\n\n //Outputting the XML as a string\n Result:= XMLDoc.XML.Text;\nend;\n\n//..............................................\n\n//Consuming code example (fragment)\nvar\n Names,\n Remarks: TStringList;\nbegin\n //Creating the lists objects\n Names:= TStringList.Create;\n Remarks:= TStringList.Create;\n try\n //Filling the list with names\n Names.Add('April');\n Names.Add('Tam O''Shanter');\n Names.Add('Emily');\n\n //Filling the list with remarks\n Remarks.Add('Bubbly: I''m > Tam and <= Emily');\n Remarks.Add('Burns: \"When chapman billies leave the street ...\"');\n Remarks.Add('Short & shrift');\n\n //Constructing and showing the XML\n Showmessage(CreateXML(Names, Remarks));\n\n finally\n //Freeing the list objects\n Names.Free;\n Remarks.Free;\n end;\nend;\n", "language": "Delphi" }, { "code": "-module( xml_output ).\n\n-export( [task/0] ).\n\n-include_lib(\"xmerl/include/xmerl.hrl\").\n\ntask() ->\n Data = {'CharacterRemarks', [], [{'Character', [{name, X}], [[Y]]} || {X, Y} <- contents()]},\n lists:flatten( xmerl:export_simple([Data], xmerl_xml) ).\n\n\ncontents() -> [{\"April\", \"Bubbly: I'm > Tam and <= Emily\"}, {\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\"}, {\"Emily\", \"Short & shrift\"}].\n", "language": "Erlang" }, { "code": "function xmlquote(sequence s)\n sequence r\n r = \"\"\n for i = 1 to length(s) do\n if s[i] = '<' then\n r &= \"&lt;\"\n elsif s[i] = '>' then\n r &= \"&gt;\"\n elsif s[i] = '&' then\n r &= \"&amp;\"\n elsif s[i] = '\"' then\n r &= \"&quot;\"\n elsif s[i] = '\\'' then\n r &= \"&apos;\"\n else\n r &= s[i]\n end if\n end for\n return r\nend function\n\nconstant CharacterRemarks = {\n {\"April\", \"Bubbly: I'm > Tam and <= Emily\"},\n {\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\"},\n {\"Emily\", \"Short & shrift\"}\n}\n\nputs(1,\"<CharacterRemarks>\\n\")\nfor i = 1 to length(CharacterRemarks) do\n printf(1,\" <CharacterName=\\\"%s\\\">\",{xmlquote(CharacterRemarks[i][1])})\n puts(1,xmlquote(CharacterRemarks[i][2]))\n puts(1,\"</Character>\\n\")\nend for\nputs(1,\"</CharacterRemarks>\\n\")\n", "language": "Euphoria" }, { "code": "#light\n\nopen System.Xml\ntype Character = {name : string; comment : string }\n\nlet data = [\n { name = \"April\"; comment = \"Bubbly: I'm > Tam and <= Emily\"}\n { name = \"Tam O'Shanter\"; comment = \"Burns: \\\"When chapman billies leave the street ...\\\"\"}\n { name = \"Emily\"; comment = \"Short & shrift\"} ]\n\nlet doxml (characters : Character list) =\n let doc = new XmlDocument()\n let root = doc.CreateElement(\"CharacterRemarks\")\n doc.AppendChild root |> ignore\n Seq.iter (fun who ->\n let node = doc.CreateElement(\"Character\")\n node.SetAttribute(\"name\", who.name)\n doc.CreateTextNode(who.comment)\n |> node.AppendChild |> ignore\n root.AppendChild node |> ignore\n ) characters\n doc.OuterXml\n", "language": "F-Sharp" }, { "code": "USING: sequences xml.syntax xml.writer ;\n\n: print-character-remarks ( names remarks -- )\n [ [XML <Character name=<-> ><-></Character> XML] ] 2map\n [XML <CharacterRemarks><-></CharacterRemarks> XML] pprint-xml ;\n", "language": "Factor" }, { "code": "{ \"April\" \"Tam O'Shanter\" \"Emily\" } {\n \"Bubbly: I'm > Tam and <= Emily\"\n \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n \"Short & shrift\"\n} print-remarks\n", "language": "Factor" }, { "code": "using xml\n\nclass XmlOutput\n{\n public static Void main ()\n {\n Str[] names := [\"April\", \"Tam O'Shanter\", \"Emily\"]\n Str[] remarks := [\"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"]\n\n doc := XDoc()\n root := XElem(\"CharacterRemarks\")\n doc.add (root)\n\n names.each |Str name, Int i|\n {\n child := XElem(\"Character\")\n child.addAttr(\"Name\", name)\n child.add(XText(remarks[i]))\n root.add (child)\n }\n\n doc.write(Env.cur.out)\n }\n}\n", "language": "Fantom" }, { "code": "include ffl/est.fs\ninclude ffl/xos.fs\n\n\\ Input lists\n0 value names\nhere ,\" Emily\"\nhere ,\" Tam O'Shanter\"\nhere ,\" April\"\nhere to names\n, , ,\n\n0 value remarks\nhere ,\" Short & shrift\"\nhere ,\\\" Burns: \\\"When chapman billies leave the street ...\\\"\"\nhere ,\" Bubbly: I'm > Tam and <= Emily\"\nhere to remarks\n, , ,\n\n: s++ ( c-addr1 -- c-addr2 c-addr3 u3 )\n dup cell+ swap @ count\n;\n\n\\ Create xml writer\ntos-create xml\n\n: create-xml ( c-addr1 c-addr2 -- )\n 0 s\" CharacterRemarks\" xml xos-write-start-tag\n 3 0 DO\n swap s++ s\" name\" 2swap 1\n s\" Character\" xml xos-write-start-tag\n swap s++ xml xos-write-text\n s\" Character\" xml xos-write-end-tag\n LOOP\n drop drop\n s\" CharacterRemarks\" xml xos-write-end-tag\n;\n\nnames remarks create-xml\n\n\\ Output xml string\nxml str-get type cr\n", "language": "Forth" }, { "code": "Data \"April\", \"Bubbly: I'm > Tam and <= Emily\", _\n \"Tam O'Shanter\", \"Burns: \"\"When chapman billies leave the street ...\"\"\", _\n \"Emily\", \"Short & shrift\"\n\nDeclare Function xmlquote(ByRef s As String) As String\nDim n As Integer, dev As String, remark As String\n\nPrint \"<CharacterRemarks>\"\nFor n = 0 to 2\n Read dev, remark\n Print \" <Character name=\"\"\"; xmlquote(dev); \"\"\">\"; _\n xmlquote(remark); \"</Character>\"\nNext\nPrint \"</CharacterRemarks>\"\n\nEnd\n\nFunction xmlquote(ByRef s As String) As String\n Dim n As Integer\n Dim r As String\n For n = 0 To Len(s)\n Dim c As String\n c = Mid(s,n,1)\n Select Case As Const Asc(c)\n Case Asc(\"<\")\n r = r + \"&lt;\"\n Case Asc(\">\")\n r = r + \"&gt;\"\n Case Asc(\"&\")\n r = r + \"&amp;\"\n Case Asc(\"\"\"\")\n r = r + \"&quot;\"\n Case Asc(\"'\")\n r = r + \"&apos;\"\n Case Else\n r = r + c\n End Select\n Next\n Function = r\nEnd Function\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"encoding/xml\"\n \"fmt\"\n)\n\n// Function required by task description.\nfunc xRemarks(r CharacterRemarks) (string, error) {\n b, err := xml.MarshalIndent(r, \"\", \" \")\n return string(b), err\n}\n\n// Task description allows the function to take \"a single mapping...\"\n// This data structure represents a mapping.\ntype CharacterRemarks struct {\n Character []crm\n}\n\ntype crm struct {\n Name string `xml:\"name,attr\"`\n Remark string `xml:\",chardata\"`\n}\n\nfunc main() {\n x, err := xRemarks(CharacterRemarks{[]crm{\n {`April`, `Bubbly: I'm > Tam and <= Emily`},\n {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n {`Emily`, `Short & shrift`},\n }})\n if err != nil {\n x = err.Error()\n }\n fmt.Println(x)\n}\n", "language": "Go" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&#39;m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O&#39;Shanter\">Burns: &#34;When chapman billies leave the street ...&#34;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"encoding/xml\"\n \"fmt\"\n \"strings\"\n \"text/template\"\n)\n\ntype crm struct {\n Char, Rem string\n}\n\nvar tmpl = `<CharacterRemarks>\n{{range .}} <Character name=\"{{xml .Char}}\">{{xml .Rem}}</Character>\n{{end}}</CharacterRemarks>\n`\n\nfunc xmlEscapeString(s string) string {\n var b strings.Builder\n xml.Escape(&b, []byte(s))\n return b.String()\n}\n\nfunc main() {\n xt := template.New(\"\").Funcs(template.FuncMap{\"xml\": xmlEscapeString})\n template.Must(xt.Parse(tmpl))\n\n // Define function required by task description.\n xRemarks := func(crms []crm) (string, error) {\n var b strings.Builder\n err := xt.Execute(&b, crms)\n return b.String(), err\n }\n\n // Call the function with example data. The data is represented as\n // a \"single mapping\" as allowed by the task, rather than two lists.\n x, err := xRemarks([]crm{\n {`April`, `Bubbly: I'm > Tam and <= Emily`},\n {`Tam O'Shanter`, `Burns: \"When chapman billies leave the street ...\"`},\n {`Emily`, `Short & shrift`}})\n if err != nil {\n x = err.Error()\n }\n fmt.Println(x)\n}\n", "language": "Go" }, { "code": "def writer = new StringWriter()\ndef builder = new groovy.xml.MarkupBuilder(writer)\ndef names = [\"April\", \"Tam O'Shanter\", \"Emily\"]\ndef remarks = [\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"', \"Short & shrift\"]\n\nbuilder.CharacterRemarks() {\n names.eachWithIndex() { n, i -> Character(name:n, remarks[i]) };\n}\n\nprintln writer.toString()\n", "language": "Groovy" }, { "code": "import Text.XML.Light\n\ncharacterRemarks :: [String] -> [String] -> String\ncharacterRemarks names remarks = showElement $ Element\n (unqual \"CharacterRemarks\")\n []\n (zipWith character names remarks)\n Nothing\n where character name remark = Elem $ Element\n (unqual \"Character\")\n [Attr (unqual \"name\") name]\n [Text $ CData CDataText remark Nothing]\n Nothing\n", "language": "Haskell" }, { "code": "CHARACTER names=\"April~Tam O'Shanter~Emily~\"\nCHARACTER remarks*200/%Bubbly: I'm > Tam and <= Emily~Burns: \"When chapman billies leave the street ...\"~Short & shrift~%/\nCHARACTER XML*1000\n\nEDIT(Text=remarks, Right='&', RePLaceby='&amp;', DO)\nEDIT(Text=remarks, Right='>', RePLaceby='&gt;', DO)\nEDIT(Text=remarks, Right='<', RePLaceby='&lt;', DO)\n\nXML = \"<CharacterRemarks>\" // $CRLF\nDO i = 1, 3\n EDIT(Text=names, SePaRators='~', ITeM=i, Parse=name)\n EDIT(Text=remarks, SePaRators='~', ITeM=i, Parse=remark)\n XML = TRIM(XML) // '<Character name=\"' // name // '\">' // remark // '</Character>' // $CRLF\nENDDO\nXML = TRIM(XML) // \"</CharacterRemarks>\"\n", "language": "HicEst" }, { "code": "tbl=: ('&quote;'; '&amp;'; '&lt;'; '&gt;') (a.i.'\"&<>')} <\"0 a.\nesc=: [:; {&tbl@:i.~&a.\n", "language": "J" }, { "code": "cmb=: [:; dyad define &.>\n '<Character name=\"', (esc x), '\">', (esc y), '</Character>', LF\n)\n", "language": "J" }, { "code": "xmlify=: '<CharacterRemarks>', LF, cmb, '</CharacterRemarks>'\"_\n", "language": "J" }, { "code": "names=: 'April'; 'Tam O''Shanter'; 'Emily'\n\nremarks=: <;._2]0 :0\n I'm > Tam and <= Emily\n Burns: \"When chapman billies leave the street ...\"\n Short & shrift\n)\n", "language": "J" }, { "code": " names xmlify remarks\n<CharacterRemarks>\n<Character name=\"April\"> I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\"> Burns: &quote;When chapman billies leave the street ...&quote;</Character>\n<Character name=\"Emily\"> Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "J" }, { "code": "import java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class XmlCreation {\n\n private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"};\n\n public static void main(String[] args) {\n try {\n // Create a new XML document\n final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();\n\n // Append the root element\n final Element root = doc.createElement(\"CharacterRemarks\");\n doc.appendChild(root);\n\n // Read input data and create a new <Character> element for each name.\n for(int i = 0; i < names.length; i++) {\n final Element character = doc.createElement(\"Character\");\n root.appendChild(character);\n character.setAttribute(\"name\", names[i]);\n character.appendChild(doc.createTextNode(remarks[i]));\n }\n\n // Serializing XML in Java is unnecessary complicated\n // Create a Source from the document.\n final Source source = new DOMSource(doc);\n\n // This StringWriter acts as a buffer\n final StringWriter buffer = new StringWriter();\n\n // Create a Result as a transformer target.\n final Result result = new StreamResult(buffer);\n\n // The Transformer is used to copy the Source to the Result object.\n final Transformer transformer = TransformerFactory.newInstance().newTransformer();\n transformer.setOutputProperty(\"indent\", \"yes\");\n transformer.transform(source, result);\n\n // Now the buffer is filled with the serialized XML and we can print it\n // to the console.\n System.out.println(buffer.toString());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n", "language": "Java" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<CharacterRemarks>\n<Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n", "language": "Java" }, { "code": "import java.io.StringWriter;\n\nimport javax.xml.stream.XMLOutputFactory;\nimport javax.xml.stream.XMLStreamWriter;\n\npublic class XmlCreationStax {\n\n private static final String[] names = {\"April\", \"Tam O'Shanter\", \"Emily\"};\n private static final String[] remarks = {\"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"};\n\n public static void main(String[] args) {\n try {\n final StringWriter buffer = new StringWriter();\n\n final XMLStreamWriter out = XMLOutputFactory.newInstance()\n .createXMLStreamWriter(buffer);\n\n out.writeStartDocument(\"UTF-8\", \"1.0\");\n out.writeStartElement(\"CharacterRemarks\");\n\n for(int i = 0; i < names.length; i++) {\n out.writeStartElement(\"Character\");\n out.writeAttribute(\"name\", names[i]);\n out.writeCharacters(remarks[i]);\n out.writeEndElement();\n }\n\n out.writeEndElement();\n out.writeEndDocument();\n\n System.out.println(buffer);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n", "language": "Java" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CharacterRemarks><Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character><Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character><Character name=\"Emily\">Short &amp; shrift</Character></CharacterRemarks>\n", "language": "Java" }, { "code": "DEFINE subst ==\n[[['< \"&lt;\" putchars]\n ['> \"&gt;\" putchars]\n ['& \"&amp;\" putchars]\n [putch]] case] step;\n\nXMLOutput ==\n\"<CharacterRemarks>\\n\" putchars\n[\"<Character name=\\\"\" putchars uncons swap putchars \"\\\">\" putchars first subst \"</Character>\\n\" putchars] step\n\"</CharacterRemarks>\\n\" putchars.\n\n[[\"April\" \"Bubbly: I'm > Tam and <= Emily\"]\n [\"Tam O'Shanter\" \"Burns: \\\"When chapman billies leave the street ...\\\"\"]\n [\"Emily\" \"Short & shrift\"]\n] XMLOutput.\n", "language": "Joy" }, { "code": "def escapes: [\n [\"&\" , \"&amp;\"], # must do this one first\n [\"\\\"\", \"&quot;\"],\n [\"'\" , \"&apos;\"],\n [\"<\" , \"&lt;\"],\n [\">\" , \"&gt;\"]\n];\n\ndef xmlEscape:\n reduce escapes[] as $esc (.; gsub($esc[0]; $esc[1]));\n\ndef xmlDoc(names; remarks):\n reduce range(0;names|length) as $i (\"<CharacterRemarks>\\n\";\n (names[$i]|xmlEscape) as $name\n | (remarks[$i]|xmlEscape) as $remark\n | . + \" <Character name=\\\"\\($name)\\\">\\($remark)</Character>\\n\")\n + \"</CharacterRemarks>\" ;\n\ndef names: [\"April\", \"Tam O'Shanter\", \"Emily\"];\ndef remarks: [\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\n];\n\nxmlDoc(names; remarks)\n", "language": "Jq" }, { "code": "using LightXML\n\ndialog = [(\"April\", \"Bubbly: I'm > Tam and <= Emily\"),\n (\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\"),\n (\"Emily\", \"Short & shrift\")]\n\nconst xdoc = XMLDocument()\nconst xroot = create_root(xdoc, \"CharacterRemarks\")\n\nfor (name, remarks) in dialog\n xs1 = new_child(xroot, \"Character\")\n set_attribute(xs1, \"name\", name)\n add_text(xs1, remarks)\nend\n\nprintln(xdoc)\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport javax.xml.transform.dom.DOMSource\nimport java.io.StringWriter\nimport javax.xml.transform.stream.StreamResult\nimport javax.xml.transform.TransformerFactory\n\nfun main(args: Array<String>) {\n val names = listOf(\"April\", \"Tam O'Shanter\", \"Emily\")\n\n val remarks = listOf(\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\n )\n\n val dbFactory = DocumentBuilderFactory.newInstance()\n val dBuilder = dbFactory.newDocumentBuilder()\n val doc = dBuilder.newDocument()\n val root = doc.createElement(\"CharacterRemarks\") // create root node\n doc.appendChild(root)\n\n // now create Character elements\n for (i in 0 until names.size) {\n val character = doc.createElement(\"Character\")\n character.setAttribute(\"name\", names[i])\n val remark = doc.createTextNode(remarks[i])\n character.appendChild(remark)\n root.appendChild(character)\n }\n\n val source = DOMSource(doc)\n val sw = StringWriter()\n val result = StreamResult(sw)\n val tFactory = TransformerFactory.newInstance()\n tFactory.newTransformer().apply {\n setOutputProperty(\"omit-xml-declaration\", \"yes\")\n setOutputProperty(\"indent\", \"yes\")\n setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"4\")\n transform(source, result)\n }\n println(sw)\n}\n", "language": "Kotlin" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Kotlin" }, { "code": "define character2xml(names::array, remarks::array) => {\n\n\tfail_if(#names -> size != #remarks -> size, -1, 'Input arrays not of same size')\n\n\tlocal(\n\t\tdomimpl = xml_domimplementation,\n\t\tdoctype = #domimpl -> createdocumenttype(\n\t\t\t'svg:svg',\n\t\t\t'-//W3C//DTD SVG 1.1//EN',\n\t\t\t'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'\n\t\t),\n\t\tcharacter_xml = #domimpl -> createdocument(\n\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t'svg:svg',\n\t\t\t#docType\n\t\t),\n\t\tcsnode = #character_xml -> createelement('CharacterRemarks'),\n\t\tcharnode\n\t)\n\n\t#character_xml -> appendChild(#csnode)\n\n\tloop(#names -> size) => {\n\t\t#charnode = #character_xml -> createelement('Character')\n\t\t#charnode -> setAttribute('name', #names -> get(loop_count))\n\t\t#charnode -> nodeValue = encode_xml(#remarks -> get(loop_count))\n\t\t#csnode -> appendChild(#charnode)\n\t}\n\treturn #character_xml\n\n}\n\ncharacter2xml(\n\tarray(`April`, `Tam O'Shanter`, `Emily`),\n\tarray(`Bubbly: I'm > Tam and <= Emily`, `Burns: \"When chapman billies leave the street ...\"`, `Short & shrift`)\n)\n", "language": "Lasso" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE svg:svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:svg=\"http://www.w3.org/2000/svg\"/>\n<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Lasso" }, { "code": "require(\"LuaXML\")\n\nfunction addNode(parent, nodeName, key, value, content)\n local node = xml.new(nodeName)\n table.insert(node, content)\n parent:append(node)[key] = value\nend\n\nroot = xml.new(\"CharacterRemarks\")\naddNode(root, \"Character\", \"name\", \"April\", \"Bubbly: I'm > Tam and <= Emily\")\naddNode(root, \"Character\", \"name\", \"Tam O'Shanter\", 'Burns: \"When chapman billies leave the street ...\"')\naddNode(root, \"Character\", \"name\", \"Emily\", \"Short & shrift\")\nprint(root)\n", "language": "Lua" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O&apos;Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Lua" }, { "code": "xmlStr = xml.str(root):gsub(\"&apos;\", \"'\"):gsub(\"&quot;\", '\"')\nprint(xmlStr)\n", "language": "Lua" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Lua" }, { "code": "Module CheckIt {\n\tFlush\n\tData \"April\", {Bubbly: I'm > Tam and <= Emily}\n\tData \"Tam O'Shanter\", {Burns: \"When chapman billies leave the street ...\"}\n\tData \"Emily\", {Short & shrift}\n\t\n\tdeclare xml xmlData\n\t\n\twith xml, \"xml\" as doc$, \"beautify\" as beautify\n\t\n\tmethod xml, \"PrepareNode\", \"CharacterRemarks\" as Node\n\tmethod xml, \"InsertNode\", Node\n\twhile not empty\n\t\tread name$, text$\n\t\tmethod xml, \"PrepareNode\", \"Character\", text$ as Node1\n\t\tmethod xml, \"PlaceAttributeToNode\", Node1, \"name\", name$\n\t\tmethod xml, \"AppendChild\", Node1\n\tend while\n\tbeautify=-4\n\tReport doc$\n}\nCheckIt\n", "language": "M2000-Interpreter" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&apos;m &qt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "M2000-Interpreter" }, { "code": "c = {\"April\", \"Tam O'Shanter\",\"Emily\"};\nr = {\"Bubbly:I'm > Tam and <= Emily\" ,\nStringReplace[\"Burns:\\\"When chapman billies leave the street ...\\\"\", \"\\\"\" -> \"\"], \"Short & shrift\"};\nExportString[ XMLElement[ \"CharacterRemarks\", {},\n{XMLElement[\"Character\", {\"name\" -> c[[1]]}, {r[[1]]}],\n XMLElement[\"Character\", {\"name\" -> c[[2]]}, {r[[2]]}],\n XMLElement[\"Character\", {\"name\" -> c[[3]]}, {r[[3]]}]\n}], \"XML\", \"AttributeQuoting\" -> \"\\\"\"]\n", "language": "Mathematica" }, { "code": "RootXML = com.mathworks.xml.XMLUtils.createDocument('CharacterRemarks');\ndocRootNode = RootXML.getDocumentElement;\nthisElement = RootXML.createElement('Character');\nthisElement.setAttribute('Name','April')\nthisElement.setTextContent('Bubbly: I''m > Tam and <= Emily');\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Character');\nthisElement.setAttribute('Name','Tam O''Shanter')\nthisElement.setTextContent('Burns: \"When chapman billies leave the street ...\"');\ndocRootNode.appendChild(thisElement);\nthisElement = RootXML.createElement('Character');\nthisElement.setAttribute('Name','Emily')\nthisElement.setTextContent('Short & shrift');\ndocRootNode.appendChild(thisElement);\n", "language": "MATLAB" }, { "code": "/* NetRexx */\n\noptions replace format comments java crossref savelog symbols nobinary\n\nimport java.io.StringWriter\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport javax.xml.transform.Result\nimport javax.xml.transform.Source\nimport javax.xml.transform.Transformer\nimport javax.xml.transform.TransformerFactory\nimport javax.xml.transform.dom.DOMSource\nimport javax.xml.transform.stream.StreamResult\n\nimport org.w3c.dom.Document\nimport org.w3c.dom.Element\n\nnames = [String -\n \"April\", \"Tam O'Shanter\", \"Emily\" -\n]\n\nremarks = [ String -\n \"Bubbly: I'm > Tam and <= Emily\" -\n , 'Burns: \"When chapman billies leave the street ...\"' -\n , 'Short & shrift' -\n]\n\ndo\n -- Create a new XML document\n doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()\n\n -- Append the root element\n root = doc.createElement(\"CharacterRemarks\")\n doc.appendChild(root)\n\n -- Read input data and create a new <Character> element for each name.\n loop i_ = 0 to names.length - 1\n character = doc.createElement(\"Character\")\n root.appendChild(character)\n character.setAttribute(\"name\", names[i_])\n character.appendChild(doc.createTextNode(remarks[i_]))\n end i_\n\n -- Serializing XML in Java is unnecessary complicated\n -- Create a Source from the document.\n source = DOMSource(doc)\n\n -- This StringWriter acts as a buffer\n buffer = StringWriter()\n\n -- Create a Result as a transformer target.\n result = StreamResult(buffer)\n\n -- The Transformer is used to copy the Source to the Result object.\n transformer = TransformerFactory.newInstance().newTransformer()\n transformer.setOutputProperty(\"indent\", \"yes\")\n transformer.transform(source, result)\n\n -- Now the buffer is filled with the serialized XML and we can print it to the console.\n say buffer.toString\ncatch ex = Exception\n ex.printStackTrace\nend\n\nreturn\n", "language": "NetRexx" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<CharacterRemarks>\n<Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "NetRexx" }, { "code": "/* NetRexx */\n\noptions replace format comments java crossref savelog symbols nobinary\n\nimport java.io.StringWriter\n\nimport javax.xml.stream.XMLOutputFactory\nimport javax.xml.stream.XMLStreamWriter\n\nnames = [String -\n \"April\", \"Tam O'Shanter\", \"Emily\" -\n]\n\nremarks = [ String -\n \"Bubbly: I'm > Tam and <= Emily\" -\n , 'Burns: \"When chapman billies leave the street ...\"' -\n , 'Short & shrift' -\n]\n\ndo\n buffer = StringWriter()\n\n out = XMLOutputFactory.newInstance().createXMLStreamWriter(buffer)\n\n out.writeStartDocument(\"UTF-8\", \"1.0\")\n out.writeCharacters('\\n')\n\n out.writeStartElement(\"CharacterRemarks\")\n out.writeCharacters('\\n')\n\n loop i_ = 0 to names.length - 1\n out.writeStartElement(\"Character\")\n out.writeAttribute(\"name\", names[i_])\n out.writeCharacters(remarks[i_])\n out.writeEndElement()\n out.writeCharacters('\\n')\n end i_\n\n out.writeEndElement()\n out.writeEndDocument()\n out.writeCharacters('\\n')\n\n say buffer.toString\ncatch ex = Exception\n ex.printStackTrace\nend\n\nreturn\n", "language": "NetRexx" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CharacterRemarks>\n<Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "NetRexx" }, { "code": "import xmltree, strtabs, sequtils\n\nproc charsToXML(names, remarks: seq[string]): XmlNode =\n result = <>CharacterRemarks()\n for name, remark in items zip(names, remarks):\n result.add <>Character(name=name, remark.newText)\n\necho charsToXML(@[\"April\", \"Tam O'Shanter\", \"Emily\"],\n @[\"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"])\n", "language": "Nim" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Nim" }, { "code": "use Data.XML;\nuse Collection.Generic;\n\nclass Test {\n function : Main(args : String[]) ~ Nil {\n # list of name\n names := Vector->New()<String>;\n names->AddBack(\"April\");\n names->AddBack(\"Tam O'Shanter\");\n names->AddBack(\"Emily\");\n # list of comments\n comments := Vector->New()<String>;\n comments->AddBack(\"Bubbly: I'm > Tam and <= Emily\");\n comments->AddBack(\"Burns: \\\"When chapman billies leave the street ...\\\"\");\n comments->AddBack(XmlElement->EncodeString(\"Short & shrift\");\n # build XML document\n builder := XmlBuilder->New(\"CharacterRemarks\");\n root := builder->GetRoot();\n if(names->Size() = comments->Size()) {\n each(i : names) {\n element := XmlElement->New(XmlElement->Type->ELEMENT, \"Character\");\n element->AddAttribute(XmlAttribute->New(\"name\", names->Get(i)));\n element->SetContent(XmlElement->EncodeString(comments->Get(i)));\n root->AddChild(element);\n };\n };\n builder->ToString()->PrintLine();\n }\n}\n", "language": "Objeck" }, { "code": "# #directory \"+xml-light\" (* or maybe \"+site-lib/xml-light\" *) ;;\n\n# #load \"xml-light.cma\" ;;\n\n# let data = [\n (\"April\", \"Bubbly: I'm > Tam and <= Emily\");\n (\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\");\n (\"Emily\", \"Short & shrift\");\n ] in\n let tags =\n List.map (fun (name, comment) ->\n Xml.Element (\"Character\", [(\"name\", name)], [(Xml.PCData comment)])\n ) data\n in\n print_endline (\n Xml.to_string_fmt (Xml.Element (\"CharacterRemarks\", [], tags)))\n ;;\n<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n- : unit = ()\n", "language": "OCaml" }, { "code": "#directory \"+xmlm\"\n#load \"xmlm.cmo\"\nopen Xmlm\n\nlet datas = [\n (\"April\", \"Bubbly: I'm > Tam and <= Emily\");\n (\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\");\n (\"Emily\", \"Short & shrift\");\n ]\n\nlet xo = make_output (`Channel stdout)\n\nlet () =\n output xo (`Dtd None);\n output xo (`El_start ((\"\", \"CharacterRemarks\"), []));\n List.iter (fun (name, content) ->\n output xo (`El_start ((\"\", \"Character\"), [((\"\", \"name\"), name)]));\n output xo (`Data content);\n output xo (`El_end);\n ) datas;\n output xo (`El_end);\n print_newline()\n", "language": "OCaml" }, { "code": "declare\n proc {Main}\n Names = [\"April\"\n\t \"Tam O'Shanter\"\n\t \"Emily\"]\n\n Remarks = [\"Bubbly: I'm > Tam and <= Emily\"\n\t\t\"Burns: \\\"When chapman billies leave the street ...\\\"\"\n\t\t\"Short & shrift\"]\n\n Characters = {List.zip Names Remarks\n\t\t fun {$ N R}\n\t\t 'Character'(name:N R)\n\t\t end}\n\n DOM = {List.toTuple 'CharacterRemarks' Characters}\n in\n {System.showInfo {Serialize DOM}}\n end\n\n fun {Serialize DOM}\n \"<?xml version=\\\"1.0\\\" ?>\\n\"#\n {SerializeElement DOM 0}\n end\n\n fun {SerializeElement El Indent}\n Name = {Label El}\n Attributes ChildElements Contents\n {DestructureElement El ?Attributes ?ChildElements ?Contents}\n EscContents = {Map Contents Escape}\n Spaces = {List.make Indent} for S in Spaces do S = & end\n in\n Spaces#\"<\"#Name#\n {VSConcatMap Attributes SerializeAttribute}#\">\"#\n {VSConcat EscContents}#{When ChildElements\\=nil \"\\n\"}#\n {VSConcatMap ChildElements fun {$ E} {SerializeElement E Indent+4} end}#\n {When ChildElements\\=nil Spaces}#\"</\"#Name#\">\\n\"\n end\n\n proc {DestructureElement El ?Attrs ?ChildElements ?Contents}\n SubelementRec AttributeRec\n {Record.partitionInd El fun {$ I _} {Int.is I} end\n ?SubelementRec ?AttributeRec}\n Subelements = {Record.toList SubelementRec}\n in\n {List.partition Subelements VirtualString.is ?Contents ?ChildElements}\n Attrs = {Record.toListInd AttributeRec}\n end\n\n fun {SerializeAttribute Name#Value}\n \" \"#Name#\"=\\\"\"#{EscapeAttribute Value}#\"\\\"\"\n end\n\n fun {Escape VS}\n {Flatten {Map {VirtualString.toString VS} EscapeChar}}\n end\n\n fun {EscapeAttribute VS}\n {Flatten {Map {VirtualString.toString VS} EscapeAttributeChar}}\n end\n\n fun {EscapeChar X}\n case X of 60 then \"&lt;\"\n [] 62 then \"&gt;\"\n [] 38 then \"&amp;\"\n else X\n end\n end\n\n fun {EscapeAttributeChar X}\n case X of 34 then \"&quot;\"\n else {EscapeChar X}\n end\n end\n\n %% concatenates a list to a virtual string\n fun {VSConcat Xs}\n {List.toTuple '#' Xs}\n end\n\n fun {VSConcatMap Xs F}\n {VSConcat {Map Xs F}}\n end\n\n fun {When Cond X}\n if Cond then X else nil end\n end\nin\n {Main}\n", "language": "Oz" }, { "code": "<?xml version=\"1.0\" ?>\n<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Oz" }, { "code": "#! /usr/bin/perl\nuse strict;\nuse XML::Mini::Document;\n\nmy @students = ( [ \"April\", \"Bubbly: I'm > Tam and <= Emily\" ],\n [ \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\" ],\n\t\t [ \"Emily\", \"Short & shrift\" ]\n );\n\nmy $doc = XML::Mini::Document->new();\nmy $root = $doc->getRoot();\nmy $studs = $root->createChild(\"CharacterRemarks\");\nforeach my $s (@students)\n{\n my $stud = $studs->createChild(\"Character\");\n $stud->attribute(\"name\", $s->[0]);\n $stud->text($s->[1]);\n}\nprint $doc->toString();\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">hchars</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hsubs</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">({{</span><span style=\"color: #008000;\">\"&lt;\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;lt;\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"&gt;\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;gt;\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"&\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;amp;\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\\\"\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;quot;\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\\'\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&amp;apos;\"</span><span style=\"color: #0000FF;\">}})</span>\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">xmlquote_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #000000;\">hchars</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">hsubs</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">s</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">xml_CharacterRemarks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">data</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"&lt;CharacterRemarks&gt;\\n\"</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">data</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\" &lt;CharacterName=\\\"%s\\\"&gt;%s&lt;/Character&gt;\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xmlquote_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">data</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">&</span> <span style=\"color: #008000;\">\"&lt;/CharacterRemarks&gt;\\n\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">testset</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"April\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Bubbly: I'm &gt; Tam and &lt;= Emily\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Tam O'Shanter\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Burns: \\\"When chapman billies leave the street ...\\\"\"</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"Emily\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"Short & shrift\"</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xml_CharacterRemarks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">testset</span><span style=\"color: #0000FF;\">))</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- Sample output:\n -- &lt;CharacterRemarks&gt;\n -- &lt;CharacterName=\"April\"&gt;Bubbly: I&amp;apos;m &amp;gt; Tam and &amp;lt;= Emily&lt;/Character&gt;\n -- &lt;CharacterName=\"Tam O&amp;apos;Shanter\"&gt;Burns: &amp;quot;When chapman billies leave the street ...&amp;quot;&lt;/Character&gt;\n -- &lt;CharacterName=\"Emily\"&gt;Short &amp;amp; shrift&lt;/Character&gt;\n -- &lt;/CharacterRemarks&gt;</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"@lib/xml.l\")\n\n(de characterRemarks (Names Remarks)\n (xml\n (cons\n 'CharacterRemarks\n NIL\n (mapcar\n '((Name Remark)\n (list 'Character (list (cons 'name Name)) Remark) )\n Names\n Remarks ) ) ) )\n\n(characterRemarks\n '(\"April\" \"Tam O'Shanter\" \"Emily\")\n (quote\n \"I'm > Tam and <= Emily\"\n \"Burns: \\\"When chapman billies leave the street ...\"\n \"Short & shrift\" ) )\n", "language": "PicoLisp" }, { "code": "DataSection\n dataItemCount:\n Data.i 3\n\n names:\n Data.s \"April\", \"Tam O'Shanter\", \"Emily\"\n\n remarks:\n Data.s \"Bubbly: I'm > Tam and <= Emily\",\n ~\"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\nEndDataSection\n\nStructure characteristic\n name.s\n remark.s\nEndStructure\n\nNewList didel.characteristic()\nDefine item.s, numberOfItems, i\n\nRestore dataItemCount\nRead.i numberOfItems\n\n;add names\nRestore names\nFor i = 1 To numberOfItems\n AddElement(didel())\n Read.s item\n didel()\\name = item\nNext\n\n;add remarks\nResetList(didel())\nFirstElement(didel())\nRestore remarks:\nFor i = 1 To numberOfItems\n Read.s item\n didel()\\remark = item\n NextElement(didel())\nNext\n\nDefine xml, mainNode, itemNode\nResetList(didel())\nFirstElement(didel())\nxml = CreateXML(#PB_Any)\nmainNode = CreateXMLNode(RootXMLNode(xml), \"CharacterRemarks\")\nForEach didel()\n itemNode = CreateXMLNode(mainNode, \"Character\")\n SetXMLAttribute(itemNode, \"name\", didel()\\name)\n SetXMLNodeText(itemNode, didel()\\remark)\nNext\nFormatXML(xml, #PB_XML_ReFormat | #PB_XML_WindowsNewline | #PB_XML_ReIndent)\n\nIf OpenConsole()\n PrintN(ComposeXML(xml, #PB_XML_NoDeclaration))\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\"): Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": ">>> from xml.etree import ElementTree as ET\n>>> from itertools import izip\n>>> def characterstoxml(names, remarks):\n\troot = ET.Element(\"CharacterRemarks\")\n\tfor name, remark in izip(names, remarks):\n\t\tc = ET.SubElement(root, \"Character\", {'name': name})\n\t\tc.text = remark\n\treturn ET.tostring(root)\n\n>>> print characterstoxml(\n\tnames = [\"April\", \"Tam O'Shanter\", \"Emily\"],\n\tremarks = [ \"Bubbly: I'm > Tam and <= Emily\",\n\t\t 'Burns: \"When chapman billies leave the street ...\"',\n\t\t 'Short & shrift' ] ).replace('><','>\\n<')\n", "language": "Python" }, { "code": "<CharacterRemarks>\n<Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Python" }, { "code": "library(XML)\nchar2xml <- function(names, remarks){\n\ttt <- xmlHashTree()\n\thead <- addNode(xmlNode(\"CharacterRemarks\"), character(), tt)\n\tnode <- list()\n\tfor (i in 1:length(names)){\n\t\tnode[[i]] <- addNode(xmlNode(\"Character\", attrs=c(name=names[i])), head, tt)\n\t\taddNode(xmlTextNode(remarks[i]), node[[i]], tt)\n\t}\n\treturn(tt)\n}\noutput <- char2xml( names=c(\"April\",\"Tam O'Shanter\",\"Emily\"),\nremarks=c(\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"', \"Short & shrift\") )\n", "language": "R" }, { "code": "#lang racket\n(require xml)\n\n(define (make-character-xexpr characters remarks)\n `(CharacterRemarks\n ,@(for/list ([character characters]\n [remark remarks])\n `(Character ((name ,character)) ,remark))))\n\n(display-xml/content\n (xexpr->xml\n (make-character-xexpr\n '(\"April\" \"Tam O'Shanter\" \"Emily\")\n '(\"Bubbly: I'm > Tam and <= Emily\"\n \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n \"Short & shrift\"))))\n", "language": "Racket" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">\n Bubbly: I'm &gt; Tam and &lt;= Emily\n </Character>\n <Character name=\"Tam O'Shanter\">\n Burns: \"When chapman billies leave the street ...\"\n </Character>\n <Character name=\"Emily\">\n Short &amp; shrift\n </Character>\n</CharacterRemarks>\n", "language": "Racket" }, { "code": "use XML::Writer;\n\nmy @students =\n [ Q[April], Q[Bubbly: I'm > Tam and <= Emily] ],\n [ Q[Tam O'Shanter], Q[Burns: \"When chapman billies leave the street ...\"] ],\n [ Q[Emily], Q[Short & shrift] ]\n;\n\nmy @lines = map { :Character[:name(.[0]), .[1]] }, @students;\n\nsay XML::Writer.serialize( CharacterRemarks => @lines );\n", "language": "Raku" }, { "code": "<CharacterRemarks><Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character></CharacterRemarks>\n", "language": "Raku" }, { "code": "import Prelude;\nimport lang::xml::DOM;\n\nlist[str] charnames = [\"April\", \"Tam O\\'Shanter\", \"Emily\"];\nlist[str] remarks = [\"Bubbly: I\\'m \\> Tam and \\<= Emily\", \"Burns: \\\"When chapman billies leave the street ...\\\"\", \"Short & shrift\"];\n\npublic void xmloutput(list[str] n,list[str] r){\n\tif(size(n) != size(r)){\n\t\tthrow \"n and r should be of the same size\";\n }\n\telse{\n\t\tcharacters = [element(none(),\"Character\",[attribute(none(),\"name\",n[i]), charData(r[i])]),charData(\"\\n\")| i <- [0..size(n)-1]];\n\t\tx = document(element(none(),\"CharacterRemarks\",characters));\n\t\treturn println(xmlPretty(x));\n }\n}\n", "language": "Rascal" }, { "code": "rascal>xmloutput(charnames, remarks)\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'\\m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'\\Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n\n\nok\n", "language": "Rascal" }, { "code": "/*REXX program creates an HTML (XML) list of character names and corresponding remarks. */\ncharname. =\ncharname.1 = \"April\"\ncharname.2 = \"Tam O'Shanter\"\ncharname.3 = \"Emily\"\n do i=1 while charname.i\\==''\n say 'charname' i '=' charname.i\n end /*i*/; say\nremark. =\nremark.1 = \"I'm > Tam and <= Emily\"\nremark.2 = \"When chapman billies leave the street ...\"\nremark.3 = \"Short & shift\"\n do k=1 while remark.k\\==''\n say ' remark' k '=' remark.k\n end /*k*/; say\nitems = 0\nheader = 'CharacterRemarks'\nheader = header'>'\n\n do j=1 while charname.j\\==''\n _=charname.j\n if j==1 then call create '<'header\n call create ' <Character name=\"' ||,\n char2xml(_)'\">\"' ||,\n char2xml(remark.j)'\"</Character>'\n end /*j*/\n\nif create.0\\==0 then call create '</'header\n\n do m=1 for create.0\n say create.m /*display the Mth entry to terminal. */\n end /*m*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nchar2xml: procedure; parse arg $\n amper = pos('&', $)\\==0 /* & has to be treated special. */\n semi = pos(';', $)\\==0 /* ; \" \" \" \" \" */\n #=0 /* [↓] find a free/unused character···*/\n if amper then do /* ··· and translate freely. */\n do j=0 for 255; ?=d2c(j); if pos(?, $)==0 then leave\n end /*j*/\n $=translate($, ?, \"&\"); #= j + 1\n end\n /* [↓] find a free/unused character···*/\n if semi then do /* ··· and translate freely. */\n do k=# for 255; ?=d2c(k); if pos(?, $)==0 then leave\n end /*k*/\n $=translate($, ?, \";\")\n end\n\n/*───── Following are most of the characters in the DOS (or DOS Windows) codepage 437 ──────────*/\n\n$=XML_('â',\"ETH\") ; $=XML_('ƒ',\"fnof\") ; $=XML_('═',\"boxH\") ; $=XML_('♥',\"hearts\")\n$=XML_('â','#x00e2') ; $=XML_('á',\"aacute\"); $=XML_('╬',\"boxVH\") ; $=XML_('♦',\"diams\")\n$=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',\"boxHu\") ; $=XML_('♣',\"clubs\")\n$=XML_('ä',\"auml\") ; $=XML_('í',\"iacute\"); $=XML_('╨',\"boxhU\") ; $=XML_('♠',\"spades\")\n$=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',\"boxHd\") ; $=XML_('♂',\"male\")\n$=XML_('à',\"agrave\") ; $=XML_('ó',\"oacute\"); $=XML_('╥',\"boxhD\") ; $=XML_('♀',\"female\")\n$=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',\"boxUr\") ; $=XML_('☼',\"#x263c\")\n$=XML_('å',\"aring\") ; $=XML_('ú',\"uacute\"); $=XML_('╘',\"boxuR\") ; $=XML_('↕',\"UpDownArrow\")\n$=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',\"boxdR\") ; $=XML_('¶',\"para\")\n$=XML_('ç',\"ccedil\") ; $=XML_('ñ',\"ntilde\"); $=XML_('╓',\"boxDr\") ; $=XML_('§',\"sect\")\n$=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',\"boxVh\") ; $=XML_('↑',\"uarr\")\n$=XML_('ê',\"ecirc\") ; $=XML_('Ñ',\"Ntilde\"); $=XML_('╪',\"boxvH\") ; $=XML_('↑',\"uparrow\")\n$=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',\"boxul\") ; $=XML_('↑',\"ShortUpArrow\")\n$=XML_('ë',\"euml\") ; $=XML_('¿',\"iquest\"); $=XML_('┌',\"boxdr\") ; $=XML_('↓',\"darr\")\n$=XML_('ë','#x00eb') ; $=XML_('⌐',\"bnot\") ; $=XML_('█',\"block\") ; $=XML_('↓',\"downarrow\")\n$=XML_('è',\"egrave\") ; $=XML_('¬',\"not\") ; $=XML_('▄',\"lhblk\") ; $=XML_('↓',\"ShortDownArrow\")\n$=XML_('è','#x00e8') ; $=XML_('½',\"frac12\"); $=XML_('▀',\"uhblk\") ; $=XML_('←',\"larr\")\n$=XML_('ï',\"iuml\") ; $=XML_('½',\"half\") ; $=XML_('α',\"alpha\") ; $=XML_('←',\"leftarrow\")\n$=XML_('ï','#x00ef') ; $=XML_('¼',\"frac14\"); $=XML_('ß',\"beta\") ; $=XML_('←',\"ShortLeftArrow\")\n$=XML_('î',\"icirc\") ; $=XML_('¡',\"iexcl\") ; $=XML_('ß',\"szlig\") ; $=XML_('1c'x,\"rarr\")\n$=XML_('î','#x00ee') ; $=XML_('«',\"laqru\") ; $=XML_('ß','#x00df') ; $=XML_('1c'x,\"rightarrow\")\n$=XML_('ì',\"igrave\") ; $=XML_('»',\"raqru\") ; $=XML_('Γ',\"Gamma\") ; $=XML_('1c'x,\"ShortRightArrow\")\n$=XML_('ì','#x00ec') ; $=XML_('░',\"blk12\") ; $=XML_('π',\"pi\") ; $=XML_('!',\"excl\")\n$=XML_('Ä',\"Auml\") ; $=XML_('▒',\"blk14\") ; $=XML_('Σ',\"Sigma\") ; $=XML_('\"',\"apos\")\n$=XML_('Ä','#x00c4') ; $=XML_('▓',\"blk34\") ; $=XML_('σ',\"sigma\") ; $=XML_('$',\"dollar\")\n$=XML_('Å',\"Aring\") ; $=XML_('│',\"boxv\") ; $=XML_('µ',\"mu\") ; $=XML_(\"'\",\"quot\")\n$=XML_('Å','#x00c5') ; $=XML_('┤',\"boxvl\") ; $=XML_('τ',\"tau\") ; $=XML_('*',\"ast\")\n$=XML_('É',\"Eacute\") ; $=XML_('╡',\"boxvL\") ; $=XML_('Φ',\"phi\") ; $=XML_('/',\"sol\")\n$=XML_('É','#x00c9') ; $=XML_('╢',\"boxVl\") ; $=XML_('Θ',\"Theta\") ; $=XML_(':',\"colon\")\n$=XML_('æ',\"aelig\") ; $=XML_('╖',\"boxDl\") ; $=XML_('δ',\"delta\") ; $=XML_('<',\"lt\")\n$=XML_('æ','#x00e6') ; $=XML_('╕',\"boxdL\") ; $=XML_('∞',\"infin\") ; $=XML_('=',\"equals\")\n$=XML_('Æ',\"AElig\") ; $=XML_('╣',\"boxVL\") ; $=XML_('φ',\"Phi\") ; $=XML_('>',\"gt\")\n$=XML_('Æ','#x00c6') ; $=XML_('║',\"boxV\") ; $=XML_('ε',\"epsilon\") ; $=XML_('?',\"quest\")\n$=XML_('ô',\"ocirc\") ; $=XML_('╗',\"boxDL\") ; $=XML_('∩',\"cap\") ; $=XML_('_',\"commat\")\n$=XML_('ô','#x00f4') ; $=XML_('╝',\"boxUL\") ; $=XML_('≡',\"equiv\") ; $=XML_('[',\"lbrack\")\n$=XML_('ö',\"ouml\") ; $=XML_('╜',\"boxUl\") ; $=XML_('±',\"plusmn\") ; $=XML_('\\',\"bsol\")\n$=XML_('ö','#x00f6') ; $=XML_('╛',\"boxuL\") ; $=XML_('±',\"pm\") ; $=XML_(']',\"rbrack\")\n$=XML_('ò',\"ograve\") ; $=XML_('┐',\"boxdl\") ; $=XML_('±',\"PlusMinus\") ; $=XML_('^',\"Hat\")\n$=XML_('ò','#x00f2') ; $=XML_('└',\"boxur\") ; $=XML_('≥',\"ge\") ; $=XML_('`',\"grave\")\n$=XML_('û',\"ucirc\") ; $=XML_('┴',\"bottom\"); $=XML_('≤',\"le\") ; $=XML_('{',\"lbrace\")\n$=XML_('û','#x00fb') ; $=XML_('┴',\"boxhu\") ; $=XML_('÷',\"div\") ; $=XML_('{',\"lcub\")\n$=XML_('ù',\"ugrave\") ; $=XML_('┬',\"boxhd\") ; $=XML_('÷',\"divide\") ; $=XML_('|',\"vert\")\n$=XML_('ù','#x00f9') ; $=XML_('├',\"boxvr\") ; $=XML_('≈',\"approx\") ; $=XML_('|',\"verbar\")\n$=XML_('ÿ',\"yuml\") ; $=XML_('─',\"boxh\") ; $=XML_('∙',\"bull\") ; $=XML_('}',\"rbrace\")\n$=XML_('ÿ','#x00ff') ; $=XML_('┼',\"boxvh\") ; $=XML_('°',\"deg\") ; $=XML_('}',\"rcub\")\n$=XML_('Ö',\"Ouml\") ; $=XML_('╞',\"boxvR\") ; $=XML_('·',\"middot\") ; $=XML_('Ç',\"Ccedil\")\n$=XML_('Ö','#x00d6') ; $=XML_('╟',\"boxVr\") ; $=XML_('·',\"middledot\") ; $=XML_('Ç','#x00c7')\n$=XML_('Ü',\"Uuml\") ; $=XML_('╚',\"boxUR\") ; $=XML_('·',\"centerdot\") ; $=XML_('ü',\"uuml\")\n$=XML_('Ü','#x00dc') ; $=XML_('╔',\"boxDR\") ; $=XML_('·',\"CenterDot\") ; $=XML_('ü','#x00fc')\n$=XML_('¢',\"cent\") ; $=XML_('╩',\"boxHU\") ; $=XML_('√',\"radic\") ; $=XML_('é',\"eacute\")\n$=XML_('£',\"pound\") ; $=XML_('╦',\"boxHD\") ; $=XML_('²',\"sup2\") ; $=XML_('é','#x00e9')\n$=XML_('¥',\"yen\") ; $=XML_('╠',\"boxVR\") ; $=XML_('■',\"square \") ; $=XML_('â',\"acirc\")\n\n if amper then $=xml_(?, \"amp\") /*Was there an ampersand? Translate it*/\n if semi then $=xml_(??, \"semi\") /* \" \" \" semicolon? \" \"*/\n return $\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ncreate: items= items + 1 /*bump the count of items in the list. */\n create.items= arg(1) /*add item to the CREATE list. */\n create.0 = items /*indicate how many items in the list. */\n return\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nxml_: parse arg _ /*make an XML entity (&xxxx;) */\n if pos(_, $)\\==0 then return changestr(_, $, \"&\"arg(2)\";\")\n return $\n", "language": "REXX" }, { "code": "require 'rexml/document'\ninclude REXML\n\nremarks = {\n %q(April) => %q(Bubbly: I'm > Tam and <= Emily),\n %q(Tam O'Shanter) => %q(Burns: \"When chapman billies leave the street ...\"),\n %q(Emily) => %q(Short & shrift),\n}\n\ndoc = Document.new\nroot = doc.add_element(\"CharacterRemarks\")\n\nremarks.each do |name, remark|\n root.add_element(\"Character\", {'Name' => name}).add_text(remark)\nend\n\n# output with indentation\ndoc.write($stdout, 2)\n", "language": "Ruby" }, { "code": "extern crate xml;\n\nuse std::collections::HashMap;\nuse std::str;\n\nuse xml::writer::{EmitterConfig, XmlEvent};\n\nfn characters_to_xml(characters: HashMap<String, String>) -> String {\n let mut output: Vec<u8> = Vec::new();\n let mut writer = EmitterConfig::new()\n .perform_indent(true)\n .create_writer(&mut output);\n\n writer\n .write(XmlEvent::start_element(\"CharacterRemarks\"))\n .unwrap();\n\n for (character, line) in &characters {\n let element = XmlEvent::start_element(\"Character\").attr(\"name\", character);\n writer.write(element).unwrap();\n writer.write(XmlEvent::characters(line)).unwrap();\n writer.write(XmlEvent::end_element()).unwrap();\n }\n\n writer.write(XmlEvent::end_element()).unwrap();\n str::from_utf8(&output).unwrap().to_string()\n}\n\n#[cfg(test)]\nmod tests {\n use super::characters_to_xml;\n use std::collections::HashMap;\n\n #[test]\n fn test_xml_output() {\n let mut input = HashMap::new();\n input.insert(\n \"April\".to_string(),\n \"Bubbly: I'm > Tam and <= Emily\".to_string(),\n );\n input.insert(\n \"Tam O'Shanter\".to_string(),\n \"Burns: \\\"When chapman billies leave the street ...\\\"\".to_string(),\n );\n input.insert(\"Emily\".to_string(), \"Short & shrift\".to_string());\n\n let output = characters_to_xml(input);\n\n println!(\"{}\", output);\n assert!(output.contains(\n \"<Character name=\\\"Tam O&apos;Shanter\\\">Burns: \\\"When chapman \\\n billies leave the street ...\\\"</Character>\"\n ));\n assert!(output\n .contains(\"<Character name=\\\"April\\\">Bubbly: I'm > Tam and &lt;= Emily</Character>\"));\n assert!(output.contains(\"<Character name=\\\"Emily\\\">Short &amp; shrift</Character>\"));\n }\n}\n", "language": "Rust" }, { "code": "val names = List(\"April\", \"Tam O'Shanter\", \"Emily\")\n\nval remarks = List(\"Bubbly: I'm > Tam and <= Emily\", \"\"\"Burns: \"When chapman billies leave the street ...\"\"\"\", \"Short & shrift\")\n\ndef characterRemarks(names: List[String], remarks: List[String]) = <CharacterRemarks>\n { names zip remarks map { case (name, remark) => <Character name={name}>{remark}</Character> } }\n</CharacterRemarks>\n\ncharacterRemarks(names, remarks)\n", "language": "Scala" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character><Character name=\"Tam O'Shanter\">Burns:\n&quot;When chapman billies leave the street ...&quot;</Character><Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Scala" }, { "code": "put (\"April\", \"Tam O'Shanter\", \"Emily\") into names\nput (\"Bubbly: I'm > Tam and <= Emily\", <<Burns: \"When chapman billies leave the street ...\">>, \"Short & shrift\") into remarks\nput (_tag: \"CharacterRemarks\") as tree into document\nrepeat for each item name in names\n\tinsert (_tag: \"Character\", name: name, _children: item the counter of remarks) as tree into document's _children\nend repeat\nput document\n", "language": "SenseTalk" }, { "code": "require('XML::Mini::Document');\n\nvar students = [\n [\"April\", \"Bubbly: I'm > Tam and <= Emily\"],\n [\"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\"],\n [\"Emily\", \"Short & shrift\"]\n ];\n\nvar doc = %s'XML::Mini::Document'.new;\nvar root = doc.getRoot;\nvar studs = root.createChild(\"CharacterRemarks\");\n\nstudents.each { |s|\n var stud = studs.createChild(\"Character\");\n stud.attribute(\"name\", s[0]);\n stud.text(s[1]);\n};\n\nprint doc.toString;\n", "language": "Sidef" }, { "code": "lobby define: #remarks -> (\n{'April' -> 'Bubbly: I\\'m > Tam and <= Emily'.\n'Tam O\\'Shanter' -> 'Burns: \"When chapman billies leave the street ...\"'.\n'Emily' -> 'Short & shrift'.\n} as: Dictionary).\n\ndefine: #writer -> (Xml Writer newOn: '' new writer).\nwriter inTag: 'CharacterRemarks' do:\n [| :w |\n lobby remarks keysAndValuesDo:\n [| :name :remark | w inTag: 'Character' do: [| :w | w ; remark] &attributes: {'name' -> name}].\n ].\n\ninform: writer contents\n", "language": "Slate" }, { "code": "proc xquote string {\n list [string map \"' &apos; \\\\\\\" &quot; < &gt; > &lt; & &amp;\" $string]\n}\nproc < {name attl args} {\n set res <$name\n foreach {att val} $attl {\n append res \" $att='$val'\"\n }\n if {[llength $args]} {\n append res >\n set sep \"\"\n foreach a $args {\n append res $sep $a\n set sep \\n\n }\n append res </$name>\n } else {append res />}\n return $res\n}\nset cmd {< CharacterRemarks {}}\nforeach {name comment} {\n April \"Bubbly: I'm > Tam and <= Emily\"\n \"Tam O'Shanter\" \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n Emily \"Short & shrift\"\n} {\n append cmd \" \\[< Character {Name [xquote $name]} [xquote $comment]\\]\"\n}\nputs [eval $cmd]\n", "language": "Tcl" }, { "code": "package require tdom\nset xml [dom createDocument CharacterRemarks]\nforeach {name comment} {\n April \"Bubbly: I'm > Tam and <= Emily\"\n \"Tam O'Shanter\" \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n Emily \"Short & shrift\"\n} {\n set elem [$xml createElement Character]\n $elem setAttribute name $name\n $elem appendChild [$xml createTextNode $comment]\n [$xml documentElement] appendChild $elem\n}\n$xml asXML\n", "language": "Tcl" }, { "code": "package require dom\nset xml [dom::DOMImplementation create]\nset root [dom::document createElement $xml CharacterRemarks]\nforeach {name comment} {\n April \"Bubbly: I'm > Tam and <= Emily\"\n \"Tam O'Shanter\" \"Burns: \\\"When chapman billies leave the street ...\\\"\"\n Emily \"Short & shrift\"\n} {\n set element [dom::document createElement $root Character]\n dom::element setAttribute $element name $name\n dom::document createTextNode $element $comment\n}\ndom::DOMImplementation serialize $xml -indent 1\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT\nSTRUCTURE xmloutput\nDATA '<CharacterRemarks>'\nDATA * ' <Character name=\"' names +'\">' remarks +'</Character>'\nDATA = '</CharacterRemarks>'\nENDSTRUCTURE\nBUILD X_TABLE entitysubst=\" >> &gt; << &lt; & &amp; \"\nERROR/STOP CREATE (\"dest\",seq-o,-std-)\nACCESS d: WRITE/ERASE/STRUCTURE \"dest\" num,str\nstr=\"xmloutput\"\n names=*\n DATA April\n DATA Tam O'Shanter\n DATA Emily\n remarks=*\n DATA Bubbly: I'm > Tam and <= Emily\n DATA Burns: \"When chapman billies leave the street ...\"\n DATA Short & shrift\n remarks=EXCHANGE(remarks,entitysubst)\nWRITE/NEXT d\nENDACCESS d\n", "language": "TUSCRIPT" }, { "code": "Set objXMLDoc = CreateObject(\"msxml2.domdocument\")\n\nSet objRoot = objXMLDoc.createElement(\"CharacterRemarks\")\nobjXMLDoc.appendChild objRoot\n\nCall CreateNode(\"April\",\"Bubbly: I'm > Tam and <= Emily\")\nCall CreateNode(\"Tam O'Shanter\",\"Burns: \"\"When chapman billies leave the street ...\"\"\")\nCall CreateNode(\"Emily\",\"Short & shrift\")\n\nobjXMLDoc.save(\"C:\\Temp\\Test.xml\")\n\nFunction CreateNode(attrib_value,node_value)\n\tSet objNode = objXMLDoc.createElement(\"Character\")\n\tobjNode.setAttribute \"name\", attrib_value\n\tobjNode.text = node_value\n\tobjRoot.appendChild objNode\nEnd Function\n", "language": "VBScript" }, { "code": "// Replace special characters with entities:\nReplace(\"&\", \"&amp;\", BEGIN+ALL+NOERR) // this must be the first replace!\nReplace(\"<\", \"&lt;\", BEGIN+ALL+NOERR)\nReplace(\">\", \"&gt;\", BEGIN+ALL+NOERR)\nReplace(\"'\", \"&apos;\", BEGIN+ALL+NOERR)\nReplace('\"', \"&quot;\", BEGIN+ALL+NOERR)\n\n// Insert XML marking\nBOF\nIT(\"<CharacterRemarks>\") IN\nRepeat(ALL) {\n Search(\"^.\", REGEXP+ERRBREAK)\n IT(' <Character name=\"')\n Replace('|T', '\">')\n EOL IT('</Character>')\n}\nEOF\nIT(\"</CharacterRemarks>\") IN\n", "language": "Vedit-macro-language" }, { "code": "Module XMLOutput\n Sub Main()\n Dim charRemarks As New Dictionary(Of String, String)\n charRemarks.Add(\"April\", \"Bubbly: I'm > Tam and <= Emily\")\n charRemarks.Add(\"Tam O'Shanter\", \"Burns: \"\"When chapman billies leave the street ...\"\"\")\n charRemarks.Add(\"Emily\", \"Short & shrift\")\n\n Dim xml = <CharacterRemarks>\n <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>\n </CharacterRemarks>\n\n Console.WriteLine(xml)\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "var escapes = [\n [\"&\" , \"&amp;\"], // must do this one first\n [\"\\\"\", \"&quot;\"],\n [\"'\" , \"&apos;\"],\n [\"<\" , \"&lt;\"],\n [\">\" , \"&gt;\"]\n]\n\nvar xmlEscape = Fn.new { |s|\n for (esc in escapes) s = s.replace(esc[0], esc[1])\n return s\n}\n\nvar xmlDoc = Fn.new { |names, remarks|\n var xml = \"<CharacterRemarks>\\n\"\n for (i in 0...names.count) {\n var name = xmlEscape.call(names[i])\n var remark = xmlEscape.call(remarks[i])\n xml = xml + \" <Character name=\\\"%(name)\\\">%(remark)</Character>\\n\"\n }\n xml = xml + \"</CharacterRemarks>\"\n System.print(xml)\n}\n\nvar names = [\"April\", \"Tam O'Shanter\", \"Emily\"]\nvar remarks = [\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\n]\nxmlDoc.call(names, remarks)\n", "language": "Wren" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O&apos;Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "Wren" }, { "code": "import \"./xsequence\" for XDocument, XElement, XAttribute\n\nvar createXmlDoc = Fn.new { |names, remarks|\n var root = XElement.new(\"CharacterRemarks\")\n for (i in 0...names.count) {\n var xe = XElement.new(\"Character\", remarks[i])\n xe.add(XAttribute.new(\"name\", names[i]))\n root.add(xe)\n }\n return XDocument.new(root)\n}\n\nvar names = [\"April\", \"Tam O'Shanter\", \"Emily\"]\nvar remarks = [\n \"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: \\\"When chapman billies leave the street ...\\\"\",\n \"Short & shrift\"\n]\nvar doc = createXmlDoc.call(names, remarks)\nSystem.print(doc)\n", "language": "Wren" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n", "language": "Wren" }, { "code": "code ChOut=8, CrLf=9, Text=12;\nstring 0; \\use zero-terminated strings\n\nproc XmlOut(S); \\Output string in XML format\nchar S;\nrepeat case S(0) of \\character entity substitutions\n ^<: Text(0, \"&lt;\");\n ^>: Text(0, \"&gt;\");\n ^&: Text(0, \"&amp;\");\n ^\": Text(0, \"&quot;\");\n ^': Text(0, \"&apos;\")\n other ChOut(0, S(0));\n S:= S+1;\nuntil S(0) = 0;\n\nint Name, Remark, I;\n[Name:= [\"April\", \"Tam O'Shanter\", \"Emily\"];\nRemark:= [\"Bubbly: I'm > Tam and <= Emily\",\n \"Burns: ^\"When chapman billies leave the street ...^\"\",\n \"Short & shrift\"];\nText(0, \"<CharacterRemarks>\"); CrLf(0);\nfor I:= 0 to 3-1 do\n [Text(0, \" <Character name=^\"\");\n XmlOut(Name(I));\n Text(0, \"^\">\");\n XmlOut(Remark(I));\n Text(0, \"</Character>\"); CrLf(0);\n ];\nText(0, \"</CharacterRemarks>\"); CrLf(0);\n]\n", "language": "XPL0" }, { "code": "let $names := (\"April\",\"Tam O'Shanter\",\"Emily\")\nlet $remarks := (\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"',\"Short &amp; shrift\")\nreturn element CharacterRemarks {\n for $name at $count in $names\n return element Character {\n attribute name { $name }\n ,text { $remarks[$count] }\n }\n }\n", "language": "XQuery" }, { "code": "let $names := (\"April\",\"Tam O'Shanter\",\"Emily\")\nlet $remarks := (\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"',\"Short &amp; shrift\")\nreturn <CharacterRemarks>\n {\n for $name at $count in $names\n return <Character name='{$name}'> {$remarks[$count]} </Character>\n }\n </CharacterRemarks>\n", "language": "XQuery" }, { "code": "xquery version \"3.1\";\n\nlet $names := (\"April\",\"Tam O'Shanter\",\"Emily\")\nlet $remarks := (\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"',\"Short &amp; shrift\")\nreturn element CharacterRemarks {\n for-each-pair($names, $remarks, function($name, $remark) {\n element Character {\n attribute name { $name }\n ,text { $remark }\n }\n })\n }\n", "language": "XQuery" }, { "code": "xquery version \"3.1\";\n\nlet $names := (\"April\",\"Tam O'Shanter\",\"Emily\")\nlet $remarks := (\"Bubbly: I'm > Tam and <= Emily\", 'Burns: \"When chapman billies leave the street ...\"',\"Short &amp; shrift\")\nreturn <CharacterRemarks>\n {\n for-each-pair($names, $remarks, function($name, $remark) {\n <Character name='{$name}'> {$remark} </Character>\n })\n }\n </CharacterRemarks>\n", "language": "XQuery" }, { "code": "<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n", "language": "XQuery" }, { "code": "sign$ = \"<,&lt;,>,&gt;,&,&amp;\"\ndim sign$(1)\nlong = token(sign$, sign$(), \",\")\n\nsub substitute_all$(s$)\n local i\n\n for i = 1 to long step 2\n if s$ = sign$(i) return sign$(i + 1)\n next i\n return s$\nend sub\n\nsub xmlquote_all$(s$)\n local i, res$\n\n for i = 1 to len(s$)\n res$ = res$ + substitute_all$(mid$(s$, i, 1))\n next i\n return res$\nend sub\n\nsub xml_CharacterRemarks$(datos$())\n local res$, i, long\n\n long = arraysize(datos$(), 1)\n\n res$ = \"<CharacterRemarks>\\n\"\n\n for i = 1 to long\n res$ = res$ + \" <CharacterName=\\\"\" + xmlquote_all$(datos$(i, 1)) + \"\\\">\" + xmlquote_all$(datos$(i, 2)) + \"</Character>\\n\"\n next i\n return res$ + \"</CharacterRemarks>\\n\"\nend sub\n\ndata \"April\", \"Bubbly: I'm > Tam and <= Emily\"\ndata \"Tam O'Shanter\", \"Burns: \\\"When chapman billies leave the street ...\\\"\"\ndata \"Emily\", \"Short & shrift\"\n\ndim testset$(3, 2)\n\nfor i = 1 to 3\n read testset$(i, 1), testset$(i, 2)\nnext i\n\nprint xml_CharacterRemarks$(testset$())\n", "language": "Yabasic" }, { "code": "fcn xmlEscape(text){\n text.replace(\" &\",\" &amp;\") .replace(\" \\\"\",\" &quot;\")\n .replace(\" '\",\" &apos;\") .replace(\" <\",\" &lt;\") .replace(\" >\",\" &gt;\")\n}\nfcn toXML(as,bs){\n xml:=Sink(\"<CharacterRemarks>\\n\");\n as.zipWith('wrap(a,b){\n xml.write(\" <Character name=\\\"\",xmlEscape(a),\"\\\">\",\n\t\txmlEscape(b),\"</Character>\\n\");\n },bs);\n xml.write(\"</CharacterRemarks>\\n\").close();\n}\n\ntoXML(T(\"April\", \"Tam O'Shanter\", \"Emily\"),\n T(\"Bubbly: I'm > Tam and <= Emily\",\n 0'|Burns: \"When chapman billies leave the street ...\"|,\n\t \"Short & shrift\"))\n.print();\n", "language": "Zkl" } ]
XML-Output
[ { "code": "---\nfrom: http://rosettacode.org/wiki/XML/XPath\nnote: XML\n", "language": "00-META" }, { "code": "Perform the following three XPath queries on the XML Document below:\n* '''//item[1]''': Retrieve the first \"item\" element \n* '''//price/text()''': Perform an action on each \"price\" element (print it out)\n* '''//name''': Get an array of all the \"name\" elements\n\nXML Document:\n <inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n </inventory>\n\n", "language": "00-TASK" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program xpathXml64.s */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBMAXELEMENTS, 100\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structure xmlNode*/\n .struct 0\nxmlNode_private: // application data\n .struct xmlNode_private + 8\nxmlNode_type: // type number, must be second !\n .struct xmlNode_type + 8\nxmlNode_name: // the name of the node, or the entity\n .struct xmlNode_name + 8\nxmlNode_children: // parent->childs link\n .struct xmlNode_children + 8\nxmlNode_last: // last child link\n .struct xmlNode_last + 8\nxmlNode_parent: // child->parent link\n .struct xmlNode_parent + 8\nxmlNode_next: // next sibling link\n .struct xmlNode_next + 8\nxmlNode_prev: // previous sibling link\n .struct xmlNode_prev + 8\nxmlNode_doc: // the containing document\n .struct xmlNode_doc + 8\nxmlNode_ns: // pointer to the associated namespace\n .struct xmlNode_ns + 8\nxmlNode_content: // the content\n .struct xmlNode_content + 8\nxmlNode_properties: // properties list\n .struct xmlNode_properties + 8\nxmlNode_nsDef: // namespace definitions on this node\n .struct xmlNode_nsDef + 8\nxmlNode_psvi: // for type/PSVI informations\n .struct xmlNode_psvi + 8\nxmlNode_line: // line number\n .struct xmlNode_line + 4\nxmlNode_extra: // extra data for XPath/XSLT\n .struct xmlNode_extra + 4\nxmlNode_fin:\n/********************************************/\n/* structure xmlNodeSet*/\n .struct 0\nxmlNodeSet_nodeNr: // number of nodes in the set\n .struct xmlNodeSet_nodeNr + 4\nxmlNodeSet_nodeMax: // size of the array as allocated\n .struct xmlNodeSet_nodeMax + 4\nxmlNodeSet_nodeTab: // array of nodes in no particular order\n .struct xmlNodeSet_nodeTab + 8\nxmlNodeSet_fin:\n/********************************************/\n/* structure xmlXPathObject*/\n .struct 0\nxmlPathObj_type: //\n .struct xmlPathObj_type + 8\nxmlPathObj_nodesetval: //\n .struct xmlPathObj_nodesetval + 8\nxmlPathObj_boolval: //\n .struct xmlPathObj_boolval + 8\nxmlPathObj_floatval: //\n .struct xmlPathObj_floatval + 8\nxmlPathObj_stringval: //\n .struct xmlPathObj_stringval + 8\nxmlPathObj_user: //\n .struct xmlPathObj_user + 8\nxmlPathObj_index: //\n .struct xmlPathObj_index + 8\nxmlPathObj_usex2: //\n .struct xmlPathObj_usex2 + 8\nxmlPathObj_index2: //\n .struct xmlPathObj_index2 + 8\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"\\nNormal end of program.\\n\"\nszMessDisVal: .asciz \"\\nDisplay set values.\\n\"\nszMessDisArea: .asciz \"\\nDisplay area values.\\n\"\nszFileName: .asciz \"testXml.xml\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\n\n\nszLibName: .asciz \"name\"\nszLibPrice: .asciz \"//price\"\nszLibExtName: .asciz \"//name\"\nszCarriageReturn: .asciz \"\\n\"\n\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\ntbExtract: .skip 8 * NBMAXELEMENTS // result extract area\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: // entry of program\n ldr x0,qAdrszFileName\n bl xmlParseFile // create doc\n cbz x0,99f // error ?\n mov x19,x0 // doc address\n mov x0,x19 // doc\n bl xmlDocGetRootElement // get root\n bl xmlFirstElementChild // get first section\n bl xmlFirstElementChild // get first item\n bl xmlFirstElementChild // get first name\n bl xmlNodeGetContent // extract content\n bl affichageMess // for display\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n\n ldr x0,qAdrszMessDisVal\n bl affichageMess\n mov x0,x19\n ldr x1,qAdrszLibPrice // extract prices\n bl extractValue\n mov x0,x19\n ldr x1,qAdrszLibExtName // extract names\n bl extractValue\n ldr x0,qAdrszMessDisArea\n bl affichageMess\n mov x4,#0 // display string result area\n ldr x5,qAdrtbExtract\n1:\n ldr x0,[x5,x4,lsl #3]\n cbz x0,2f\n bl affichageMess\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n add x4,x4,1\n b 1b\n2:\n mov x0,x19\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr x0,qAdrszMessEndpgm\n bl affichageMess\n b 100f\n99: // error\n ldr x0,qAdrszMessError\n bl affichageMess\n100: // standard end of the program\n mov x0,0 // return code\n mov x8,EXIT // request to exit program\n svc 0 // perform the system call\n\nqAdrszMessError: .quad szMessError\nqAdrszMessEndpgm: .quad szMessEndpgm\nqAdrszLibName: .quad szLibName\nqAdrszLibPrice: .quad szLibPrice\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrszFileName: .quad szFileName\nqAdrszLibExtName: .quad szLibExtName\nqAdrtbExtract: .quad tbExtract\nqAdrszMessDisVal: .quad szMessDisVal\nqAdrszMessDisArea: .quad szMessDisArea\n/******************************************************************/\n/* extract value of set */\n/******************************************************************/\n/* x0 contains the doc address\n/* x1 contains the address of the libel to extract */\nextractValue:\n stp x19,lr,[sp,-16]! // save registers\n stp x20,x21,[sp,-16]! // save registers\n stp x22,x23,[sp,-16]! // save registers\n mov x20,x1 // save address libel\n mov x19,x0 // save doc\n bl xmlXPathNewContext // create context\n mov x23,x0 // save context\n mov x1,x0\n mov x0,x20\n bl xmlXPathEvalExpression\n mov x21,x0\n mov x0,x23\n bl xmlXPathFreeContext // free context\n cmp x21,#0\n beq 100f\n ldr x14,[x21,#xmlPathObj_nodesetval] // values set\n ldr w23,[x14,#xmlNodeSet_nodeNr] // set size\n mov x22,#0 // index\n ldr x20,[x14,#xmlNodeSet_nodeTab] // area of nodes\n ldr x21,qAdrtbExtract\n1: // start loop\n ldr x3,[x20,x22,lsl #3] // load node\n mov x0,x19\n ldr x1,[x3,#xmlNode_children] // load string value\n mov x2,#1\n bl xmlNodeListGetString\n str x0,[x21,x22,lsl #3] // store string pointer in area\n bl affichageMess // and display string result\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n add x22,x22,1\n cmp x22,x23\n blt 1b\n100:\n ldp x22,x23,[sp],16 // restaur 2 registers\n ldp x20,x21,[sp],16 // restaur 2 registers\n ldp x19,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "set theXMLdata to \"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\n <section name=\\\"health\\\">\n <item upc=\\\"123456789\\\" stock=\\\"12\\\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\\\"445322344\\\" stock=\\\"18\\\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\\\"food\\\">\n <item upc=\\\"485672034\\\" stock=\\\"653\\\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\\\"132957764\\\" stock=\\\"44\\\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\"\n\non getElementValuesByName(theXML, theNameToFind)\n\tset R to {}\n\ttell application \"System Events\"\n\t\trepeat with i in theXML\n\t\t\tset {theName, theElements} to {i's name, i's XML elements}\n\t\t\tif (count of theElements) > 0 then set R to R & my getElementValuesByName(theElements, theNameToFind)\n\t\t\tif theName = theNameToFind then set R to R & i's value\n\t\tend repeat\n\tend tell\n\treturn R\nend getElementValuesByName\n\non getBlock(theXML, theItem, theInstance)\n\tset text item delimiters to \"\"\n\trepeat with i from 1 to theInstance\n\t\tset {R, blockStart, blockEnd} to {{}, \"<\" & theItem & space, \"</\" & theItem & \">\"}\n\t\tset x to offset of blockStart in theXML\n\t\tif x = 0 then exit repeat\n\t\tset y to offset of blockEnd in (characters x thru -1 of theXML as string)\n\t\tif y = 0 then exit repeat\n\t\tset R to characters x thru (x + y + (length of blockEnd) - 2) of theXML as string\n\t\tset theXML to characters (y + (length of blockEnd)) thru -1 of theXML as string\n\tend repeat\n\treturn R\nend getBlock\n\ntell application \"System Events\"\n\tset xmlData to make new XML data with properties {name:\"xmldata\", text:theXMLdata}\n\t\n\treturn my getBlock(xmlData's text, \"item\", 1) -- Solution to part 1 of problem.\n\treturn my getElementValuesByName(xmlData's contents, \"name\") -- Solution to part 2 of problem.\n\treturn my getElementValuesByName(xmlData's contents, \"price\") -- Solution to part 3 of problem.\n\t\nend tell\n", "language": "AppleScript" }, { "code": "\"<item upc=\\\"123456789\\\" stock=\\\"12\\\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\"\n\n{\"Invisibility Cream\", \"Levitation Salve\", \"Blork and Freen Instameal\", \"Grob winglets\"}\n\n{\"14.50\", \"23.99\", \"4.95\", \"3.56\"}\n", "language": "AppleScript" }, { "code": "/* ARM assembly Raspberry PI */\n/* program xpathXml.s */\n\n/* Constantes */\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ NBMAXELEMENTS, 100\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structure xmlNode*/\n .struct 0\nxmlNode_private: @ application data\n .struct xmlNode_private + 4\nxmlNode_type: @ type number, must be second !\n .struct xmlNode_type + 4\nxmlNode_name: @ the name of the node, or the entity\n .struct xmlNode_name + 4\nxmlNode_children: @ parent->childs link\n .struct xmlNode_children + 4\nxmlNode_last: @ last child link\n .struct xmlNode_last + 4\nxmlNode_parent: @ child->parent link\n .struct xmlNode_parent + 4\nxmlNode_next: @ next sibling link\n .struct xmlNode_next + 4\nxmlNode_prev: @ previous sibling link\n .struct xmlNode_prev + 4\nxmlNode_doc: @ the containing document\n .struct xmlNode_doc + 4\nxmlNode_ns: @ pointer to the associated namespace\n .struct xmlNode_ns + 4\nxmlNode_content: @ the content\n .struct xmlNode_content + 4\nxmlNode_properties: @ properties list\n .struct xmlNode_properties + 4\nxmlNode_nsDef: @ namespace definitions on this node\n .struct xmlNode_nsDef + 4\nxmlNode_psvi: @ for type/PSVI informations\n .struct xmlNode_psvi + 4\nxmlNode_line: @ line number\n .struct xmlNode_line + 4\nxmlNode_extra: @ extra data for XPath/XSLT\n .struct xmlNode_extra + 4\nxmlNode_fin:\n/********************************************/\n/* structure xmlNodeSet*/\n .struct 0\nxmlNodeSet_nodeNr: @ number of nodes in the set\n .struct xmlNodeSet_nodeNr + 4\nxmlNodeSet_nodeMax: @ size of the array as allocated\n .struct xmlNodeSet_nodeMax + 4\nxmlNodeSet_nodeTab: @ array of nodes in no particular order\n .struct xmlNodeSet_nodeTab + 4\nxmlNodeSet_fin:\n/********************************************/\n/* structure xmlXPathObject*/\n .struct 0\nxmlPathObj_type: @\n .struct xmlPathObj_type + 4\nxmlPathObj_nodesetval: @\n .struct xmlPathObj_nodesetval + 4\nxmlPathObj_boolval: @\n .struct xmlPathObj_boolval + 4\nxmlPathObj_floatval: @\n .struct xmlPathObj_floatval + 4\nxmlPathObj_stringval: @\n .struct xmlPathObj_stringval + 4\nxmlPathObj_user: @\n .struct xmlPathObj_user + 4\nxmlPathObj_index: @\n .struct xmlPathObj_index + 4\nxmlPathObj_user2: @\n .struct xmlPathObj_user2 + 4\nxmlPathObj_index2: @\n .struct xmlPathObj_index2 + 4\n\n\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessEndpgm: .asciz \"\\nNormal end of program.\\n\"\nszMessDisVal: .asciz \"\\nDisplay set values.\\n\"\nszMessDisArea: .asciz \"\\nDisplay area values.\\n\"\nszFileName: .asciz \"testXml.xml\"\nszMessError: .asciz \"Error detected !!!!. \\n\"\n\n\nszLibName: .asciz \"name\"\nszLibPrice: .asciz \"//price\"\nszLibExtName: .asciz \"//name\"\nszCarriageReturn: .asciz \"\\n\"\n\n\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\ntbExtract: .skip 4 * NBMAXELEMENTS @ result extract area\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain: @ entry of program\n ldr r0,iAdrszFileName\n bl xmlParseFile @ create doc\n mov r9,r0 @ doc address\n mov r0,r9 @ doc\n bl xmlDocGetRootElement @ get root\n bl xmlFirstElementChild @ get first section\n bl xmlFirstElementChild @ get first item\n bl xmlFirstElementChild @ get first name\n bl xmlNodeGetContent @ extract content\n bl affichageMess @ for display\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n\n ldr r0,iAdrszMessDisVal\n bl affichageMess\n mov r0,r9\n ldr r1,iAdrszLibPrice @ extract prices\n bl extractValue\n mov r0,r9\n ldr r1,iAdrszLibExtName @ extact names\n bl extractValue\n ldr r0,iAdrszMessDisArea\n bl affichageMess\n mov r4,#0 @ display string result area\n ldr r5,iAdrtbExtract\n1:\n ldr r0,[r5,r4,lsl #2]\n cmp r0,#0\n beq 2f\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n add r4,#1\n b 1b\n\n2:\n mov r0,r9\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr r0,iAdrszMessEndpgm\n bl affichageMess\n b 100f\n99:\n @ error\n ldr r0,iAdrszMessError\n bl affichageMess\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrszMessEndpgm: .int szMessEndpgm\niAdrszLibName: .int szLibName\niAdrszLibPrice: .int szLibPrice\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszFileName: .int szFileName\niAdrszLibExtName: .int szLibExtName\niAdrtbExtract: .int tbExtract\niAdrszMessDisVal: .int szMessDisVal\niAdrszMessDisArea: .int szMessDisArea\n/******************************************************************/\n/* extract value of set */\n/******************************************************************/\n/* r0 contains the doc address\n/* r1 contains the address of the libel to extract */\nextractValue:\n push {r1-r10,lr} @ save registres\n mov r4,r1 @ save address libel\n mov r9,r0 @ save doc\n ldr r8,iAdrtbExtract\n bl xmlXPathNewContext @ create context\n mov r10,r0\n mov r1,r0\n mov r0,r4\n bl xmlXPathEvalExpression\n mov r5,r0\n mov r0,r10\n bl xmlXPathFreeContext @ free context\n cmp r5,#0\n beq 100f\n ldr r4,[r5,#xmlPathObj_nodesetval] @ values set\n ldr r6,[r4,#xmlNodeSet_nodeNr] @ set size\n mov r7,#0 @ index\n ldr r4,[r4,#xmlNodeSet_nodeTab] @ area of nods\n1: @ start loop\n ldr r3,[r4,r7,lsl #2] @ load node\n mov r0,r9\n ldr r1,[r3,#xmlNode_children] @ load string value\n mov r2,#1\n bl xmlNodeListGetString\n str r0,[r8,r7,lsl #2] @ store string pointer in area\n bl affichageMess @ and display string result\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n add r7,#1\n cmp r7,r6\n blt 1b\n100:\n pop {r1-r10,lr} @ restaur registers */\n bx lr @ return\n\n/******************************************************************/\n/* display text with size calculation */\n/******************************************************************/\n/* r0 contains the address of the message */\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index\n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop\n @ so here r2 contains the length of the message\n mov r1,r0 @ address message in r1\n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\"\n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur registers */\n bx lr @ return\n", "language": "ARM-Assembly" }, { "code": "FileRead, inventory, xmlfile.xml\n\nRegExMatch(inventory, \"<item.*?</item>\", item1)\nMsgBox % item1\n\npos = 1\nWhile, pos := RegExMatch(inventory, \"<price>(.*?)</price>\", price, pos + 1)\n MsgBox % price1\n\nWhile, pos := RegExMatch(inventory, \"<name>.*?</name>\", name, pos + 1)\n names .= name . \"`n\"\nMsgBox % names\n", "language": "AutoHotkey" }, { "code": "#Include xpath.ahk\n\nxpath_load(doc, \"xmlfile.xml\")\n\n; Retrieve the first \"item\" element\nMsgBox % xpath(doc, \"/inventory/section[1]/item[1]/text()\")\n\n; Perform an action on each \"price\" element (print it out)\nprices := xpath(doc, \"/inventory/section/item/price/text()\")\nLoop, Parse, prices,`,\n reordered .= A_LoopField \"`n\"\nMsgBox % reordered\n\n; Get an array of all the \"name\" elements\nMsgBox % xpath(doc, \"/inventory/section/item/name\")\n", "language": "AutoHotkey" }, { "code": "{Retrieve the first \"item\" element}\n( nestML$(get$(\"doc.xml\",X,ML))\n : ?\n ( inventory\n . ?,? (section.?,? ((item.?):?item) ?) ?\n )\n ?\n& out$(toML$!item)\n)\n\n{Perform an action on each \"price\" element (print it out)}\n( nestML$(get$(\"doc.xml\",X,ML))\n : ?\n ( inventory\n . ?\n , ?\n ( section\n . ?\n , ?\n ( item\n . ?\n , ?\n ( price\n . ?\n , ?price\n & out$!price\n & ~\n )\n ?\n )\n ?\n )\n ?\n )\n ?\n|\n)\n\n{Get an array of all the \"name\" elements}\n( :?anArray\n & nestML$(get$(\"doc.xml\",X,ML))\n : ?\n ( inventory\n . ?\n , ?\n ( section\n . ?\n , ?\n ( item\n . ?\n , ?\n ( name\n . ?\n , ?name\n & !anArray !name:?anArray\n & ~\n )\n ?\n )\n ?\n )\n ?\n )\n ?\n| out$!anArray {Not truly an array, but a list.}\n);\n", "language": "Bracmat" }, { "code": "#include <libxml/parser.h>\n#include <libxml/xpath.h>\n\nxmlDocPtr getdoc (char *docname) {\n\txmlDocPtr doc;\n\tdoc = xmlParseFile(docname);\n\n\treturn doc;\n}\n\nxmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){\n\t\n\txmlXPathContextPtr context;\n\txmlXPathObjectPtr result;\n\n\tcontext = xmlXPathNewContext(doc);\n\n\tresult = xmlXPathEvalExpression(xpath, context);\n\txmlXPathFreeContext(context);\n\n\treturn result;\n}\n\nint main(int argc, char **argv) {\n\n\tif (argc <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XPath expression>\\n\", argv[0]);\n\t\treturn 0;\n\t}\n\t\n\tchar *docname;\n\txmlDocPtr doc;\n\txmlChar *xpath = (xmlChar*) argv[2];\n\txmlNodeSetPtr nodeset;\n\txmlXPathObjectPtr result;\n\tint i;\n\txmlChar *keyword;\n\n\tdocname = argv[1];\n\tdoc = getdoc(docname);\n\tresult = getnodeset (doc, xpath);\n\tif (result) {\n\t\tnodeset = result->nodesetval;\n\t\tfor (i=0; i < nodeset->nodeNr; i++) {\n\t\txmlNodePtr titleNode = nodeset->nodeTab[i];\n\t\tkeyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);\n\t\tprintf(\"Value %d: %s\\n\",i+1, keyword);\n\t\txmlFree(keyword);\n\t\t}\n\t\txmlXPathFreeObject (result);\n\t}\n\txmlFreeDoc(doc);\n\txmlCleanupParser();\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n#include <libxml/xmlerror.h>\n#include <libxml/xmlstring.h>\n#include <libxml/xmlversion.h>\n#include <libxml/xpath.h>\n\n#ifndef LIBXML_XPATH_ENABLED\n# error libxml was not configured with XPath support\n#endif\n\n// Because libxml2 is a C library, we need a couple things to make it work\n// well with modern C++:\n// 1) a ScopeGuard-like type to handle cleanup functions; and\n// 2) an exception type that transforms the library's errors.\n\n// ScopeGuard-like type to handle C library cleanup functions.\ntemplate <typename F>\nclass [[nodiscard]] scope_exit\n{\npublic:\n // C++20: Constructor can (and should) be [[nodiscard]].\n /*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :\n f_{std::move(f)}\n {}\n\n ~scope_exit()\n {\n f_();\n }\n\n // Non-copyable, non-movable.\n scope_exit(scope_exit const&) = delete;\n scope_exit(scope_exit&&) = delete;\n auto operator=(scope_exit const&) -> scope_exit& = delete;\n auto operator=(scope_exit&&) -> scope_exit& = delete;\n\nprivate:\n F f_;\n};\n\n// Exception that gets last libxml2 error.\nclass libxml_error : public std::runtime_error\n{\npublic:\n libxml_error() : libxml_error(std::string{}) {}\n\n explicit libxml_error(std::string message) :\n std::runtime_error{make_message_(std::move(message))}\n {}\n\nprivate:\n static auto make_message_(std::string message) -> std::string\n {\n if (auto const last_error = ::xmlGetLastError(); last_error)\n {\n if (not message.empty())\n message += \": \";\n message += last_error->message;\n }\n\n return message;\n }\n};\n\nauto main() -> int\n{\n try\n {\n // Initialize libxml.\n ::xmlInitParser();\n LIBXML_TEST_VERSION\n auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};\n\n // Load and parse XML document.\n auto const doc = ::xmlParseFile(\"test.xml\");\n if (not doc)\n throw libxml_error{\"failed to load document\"};\n auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};\n\n // Create XPath context for document.\n auto const xpath_context = ::xmlXPathNewContext(doc);\n if (not xpath_context)\n throw libxml_error{\"failed to create XPath context\"};\n auto const xpath_context_cleanup = scope_exit{[xpath_context]\n { ::xmlXPathFreeContext(xpath_context); }};\n\n // Task 1 ============================================================\n {\n std::cout << \"Task 1:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"//item[1]\");\n\n // Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n // 'result' a xmlNode* to the desired node, or nullptr if it\n // doesn't exist. If not nullptr, the node is owned by 'doc'.\n auto const result = xmlXPathNodeSetItem(xpath_obj->nodesetval, 0);\n if (result)\n std::cout << '\\t' << \"node found\" << '\\n';\n else\n std::cout << '\\t' << \"node not found\" << '\\n';\n }\n\n // Task 2 ============================================================\n {\n std::cout << \"Task 2:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"//price/text()\");\n\n // Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n // Printing the results.\n auto const count =\n xmlXPathNodeSetGetLength(xpath_obj->nodesetval);\n for (auto i = decltype(count){0}; i < count; ++i)\n {\n auto const node =\n xmlXPathNodeSetItem(xpath_obj->nodesetval, i);\n assert(node);\n\n auto const content = XML_GET_CONTENT(node);\n assert(content);\n\n // Note that reinterpret_cast here is a Bad Idea, because\n // 'content' is UTF-8 encoded, which may or may not be the\n // encoding cout expects. A *PROPER* solution would translate\n // content to the correct encoding (or at least verify that\n // UTF-8 *is* the correct encoding).\n //\n // But this \"works\" well enough for illustration.\n std::cout << \"\\n\\t\" << reinterpret_cast<char const*>(content);\n }\n\n std::cout << '\\n';\n }\n\n // Task 3 ============================================================\n {\n std::cout << \"Task 3:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"//name\");\n\n // Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n // 'results' is a vector of pointers to the result nodes. The\n // nodes pointed to are owned by 'doc'.\n auto const results = [ns=xpath_obj->nodesetval]()\n {\n auto v = std::vector<::xmlNode*>{};\n if (ns && ns->nodeTab)\n v.assign(ns->nodeTab, ns->nodeTab + ns->nodeNr);\n return v;\n }();\n std::cout << '\\t' << \"set of \" << results.size()\n << \" node(s) found\" << '\\n';\n }\n }\n catch (std::exception const& x)\n {\n std::cerr << \"ERROR: \" << x.what() << '\\n';\n return EXIT_FAILURE;\n }\n}\n", "language": "C++" }, { "code": "XmlReader XReader;\n\n// Either read the xml from a string ...\nXReader = XmlReader.Create(new StringReader(\"<inventory title=... </inventory>\"));\n\n// ... or read it from the file system.\nXReader = XmlReader.Create(\"xmlfile.xml\");\n\n// Create a XPathDocument object (which implements the IXPathNavigable interface)\n// which is optimized for XPath operation. (very fast).\nIXPathNavigable XDocument = new XPathDocument(XReader);\n\n// Create a Navigator to navigate through the document.\nXPathNavigator Nav = XDocument.CreateNavigator();\nNav = Nav.SelectSingleNode(\"//item\");\n\n// Move to the first element of the selection. (if available).\nif(Nav.MoveToFirst())\n{\n Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.\n}\n\n// Get an iterator to loop over multiple selected nodes.\nXPathNodeIterator Iterator = XDocument.CreateNavigator().Select(\"//price\");\n\nwhile (Iterator.MoveNext())\n{\n Console.WriteLine(Iterator.Current.Value);\n}\n\nIterator = XDocument.CreateNavigator().Select(\"//name\");\n\n// Use a generic list.\nList<string> NodesValues = new List<string>();\n\nwhile (Iterator.MoveNext())\n{\n NodesValues.Add(Iterator.Current.Value);\n}\n\n// Convert the generic list to an array and output the count of items.\nConsole.WriteLine(NodesValues.ToArray().Length);\n", "language": "C-sharp" }, { "code": "doc = new DOMParser().parseFromString '\n <inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n </inventory>\n', 'text/xml'\n", "language": "CoffeeScript" }, { "code": "# Retrieve the first \"item\" element\ndoc.evaluate('//item', doc, {}, 7, {}).snapshotItem 0\n\n# Perform an action on each \"price\" element (print it out)\nprices = doc.evaluate \"//price\", doc, {}, 7, {}\nfor i in [0...prices.snapshotLength] by 1\n console.log prices.snapshotItem(i).textContent\n\n# Get an array of all the \"name\" elements\nnames = doc.evaluate \"//name\", doc, {}, 7, {}\nnames = for i in [0...names.snapshotLength] by 1\n names.snapshotItem i\n", "language": "CoffeeScript" }, { "code": "<cfsavecontent variable=\"xmlString\">\n<inventory\n...\n</inventory>\n</cfsavecontent>\n<cfset xml = xmlParse(xmlString)>\n<!--- First Task --->\n<cfset itemSearch = xmlSearch(xml, \"//item\")>\n<!--- item = the first Item (xml element object) --->\n<cfset item = itemSearch[1]>\n<!--- Second Task --->\n<cfset priceSearch = xmlSearch(xml, \"//price\")>\n<!--- loop and print each price --->\n<cfloop from=\"1\" to=\"#arrayLen(priceSearch)#\" index=\"i\">\n #priceSearch[i].xmlText#<br/>\n</cfloop>\n<!--- Third Task --->\n<!--- array of all the name elements --->\n<cfset names = xmlSearch(xml, \"//name\")>\n<!--- visualize the results --->\n<cfdump var=\"#variables#\">\n", "language": "ColdFusion" }, { "code": "(dolist (system '(:xpath :cxml-stp :cxml))\n (asdf:oos 'asdf:load-op system))\n\n(defparameter *doc* (cxml:parse-file \"xml\" (stp:make-builder)))\n\n(xpath:first-node (xpath:evaluate \"/inventory/section[1]/item[1]\" *doc*))\n\n(xpath:do-node-set (node (xpath:evaluate \"/inventory/section/item/price/text()\" *doc*))\n (format t \"~A~%\" (stp:data node)))\n\n(defun node-array (node-set)\n (coerce (xpath:all-nodes node-set) 'vector))\n\n(node-array\n (xpath:evaluate \"/inventory/section/item/name\" *doc*))\n", "language": "Common-Lisp" }, { "code": "import kxml.xml;\nchar[]xmlinput =\n\"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\n <section name=\\\"health\\\">\n <item upc=\\\"123456789\\\" stock=\\\"12\\\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\\\"445322344\\\" stock=\\\"18\\\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\\\"food\\\">\n <item upc=\\\"485672034\\\" stock=\\\"653\\\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\\\"132957764\\\" stock=\\\"44\\\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\";\nvoid main() {\n auto root = readDocument(xmlinput);\n auto firstitem = root.parseXPath(\"inventory/section/item\")[0];\n foreach(price;root.parseXPath(\"inventory/section/item/price\")) {\n std.stdio.writefln(\"%s\",price.getCData);\n }\n auto namearray = root.parseXPath(\"inventory/section/item/name\");\n}\n", "language": "D" }, { "code": "program XMLXPath;\n\n{$APPTYPE CONSOLE}\n\nuses ActiveX, MSXML;\n\nconst\n XML =\n '<inventory title=\"OmniCorp Store #45x10^3\">' +\n ' <section name=\"health\">' +\n ' <item upc=\"123456789\" stock=\"12\">' +\n ' <name>Invisibility Cream</name>' +\n ' <price>14.50</price>' +\n ' <description>Makes you invisible</description>' +\n ' </item>' +\n ' <item upc=\"445322344\" stock=\"18\">' +\n ' <name>Levitation Salve</name>' +\n ' <price>23.99</price>' +\n ' <description>Levitate yourself for up to 3 hours per application</description>' +\n ' </item>' +\n ' </section>' +\n ' <section name=\"food\">' +\n ' <item upc=\"485672034\" stock=\"653\">' +\n ' <name>Blork and Freen Instameal</name>' +\n ' <price>4.95</price>' +\n ' <description>A tasty meal in a tablet; just add water</description>' +\n ' </item>' +\n ' <item upc=\"132957764\" stock=\"44\">' +\n ' <name>Grob winglets</name>' +\n ' <price>3.56</price>' +\n ' <description>Tender winglets of Grob. Just add water</description>' +\n ' </item>' +\n ' </section>' +\n '</inventory>';\n\nvar\n i: Integer;\n s: string;\n lXMLDoc: IXMLDOMDocument2;\n lNodeList: IXMLDOMNodeList;\n lNode: IXMLDOMNode;\n lItemNames: array of string;\nbegin\n CoInitialize(nil);\n lXMLDoc := CoDOMDocument.Create;\n lXMLDoc.setProperty('SelectionLanguage', 'XPath');\n lXMLDoc.loadXML(XML);\n\n Writeln('First item node:');\n lNode := lXMLDoc.selectNodes('//item')[0];\n Writeln(lNode.xml);\n Writeln('');\n\n lNodeList := lXMLDoc.selectNodes('//price');\n for i := 0 to lNodeList.length - 1 do\n Writeln('Price = ' + lNodeList[i].text);\n Writeln('');\n\n lNodeList := lXMLDoc.selectNodes('//item/name');\n SetLength(lItemNames, lNodeList.length);\n for i := 0 to lNodeList.length - 1 do\n lItemNames[i] := lNodeList[i].text;\n for s in lItemNames do\n Writeln('Item name = ' + s);\nend.\n", "language": "Delphi" }, { "code": "First item node:\n<item upc=\"123456789\" stock=\"12\">\n\t<name>Invisibility Cream</name>\n\t<price>14.50</price>\n\t<description>Makes you invisible</description>\n</item>\n\nPrice = 14.50\nPrice = 23.99\nPrice = 4.95\nPrice = 3.56\n\nItem name = Invisibility Cream\nItem name = Levitation Salve\nItem name = Blork and Freen Instameal\nItem name = Grob winglets\n", "language": "Delphi" }, { "code": "? def xml__quasiParser := <import:org.switchb.e.xml.makeXMLQuasiParser>()\n> def xpath__quasiParser := xml__quasiParser.xPathQuasiParser()\n> null\n\n? def doc := xml`<inventory title=\"OmniCorp Store #45x10^3\">\n> <section name=\"health\">\n> <item upc=\"123456789\" stock=\"12\">\n> <name>Invisibility Cream</name>\n> <price>14.50</price>\n> <description>Makes you invisible</description>\n> </item>\n> <item upc=\"445322344\" stock=\"18\">\n> <name>Levitation Salve</name>\n> <price>23.99</price>\n> <description>Levitate yourself for up to 3 hours per application</description>n>\n> </item>\n> </section>\n> <section name=\"food\">\n> <item upc=\"485672034\" stock=\"653\">\n> <name>Blork and Freen Instameal</name>\n> <price>4.95</price>\n> <description>A tasty meal in a tablet; just add water</description>\n> </item>\n> <item upc=\"132957764\" stock=\"44\">\n> <name>Grob winglets</name>\n> <price>3.56</price>\n> <description>Tender winglets of Grob. Just add water</description>\n> </item>\n> </section>\n> </inventory>`\n# value: xml`...`\n\n? doc[xpath`inventory/section/item`][0]\n# value: xml`<item stock=\"12\" upc=\"123456789\">\n# <name>Invisibility Cream</name>\n# <price>14.50</price>\n# <description>Makes you invisible</description>\n# </item>`\n\n? for price in doc[xpath`inventory/section/item/price/text()`] { println(price :String) }\n14.50\n23.99\n4.95\n3.56\n\n? doc[xpath`inventory/section/item/name`]\n# value: [xml`<name>Invisibility Cream</name>`,\n# xml`<name>Levitation Salve</name>`,\n# xml`<name>Blork and Freen Instameal</name>`,\n# xml`<name>Grob winglets</name>`]\n", "language": "E" }, { "code": "-module(xml_xpath).\n-include_lib(\"xmerl/include/xmerl.hrl\").\n\n-export([main/0]).\n\nmain() ->\n XMLDocument =\n \"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\n <section name=\\\"health\\\">\n <item upc=\\\"123456789\\\" stock=\\\"12\\\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\\\"445322344\\\" stock=\\\"18\\\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\\\"food\\\">\n <item upc=\\\"485672034\\\" stock=\\\"653\\\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\\\"132957764\\\" stock=\\\"44\\\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n </inventory>\",\n {Document,_} = xmerl_scan:string(XMLDocument),\n\n io:format(\"First item:\\n~s\\n\",\n [lists:flatten(\n xmerl:export_simple(\n [hd(xmerl_xpath:string(\"//item[1]\", Document))],\n xmerl_xml, [{prolog, \"\"}]))]),\n\n io:format(\"Prices:\\n\"),\n [ io:format(\"~s\\n\",[Content#xmlText.value])\n || #xmlElement{content = [Content|_]} <- xmerl_xpath:string(\"//price\", Document)],\n\n io:format(\"Names:\\n\"),\n [ Content#xmlText.value\n || #xmlElement{content = [Content|_]} <- xmerl_xpath:string(\"//name\", Document)].\n", "language": "Erlang" }, { "code": "open System.IO\nopen System.Xml.XPath\n\nlet xml = new StringReader(\"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\"\"\")\n\nlet nav = XPathDocument(xml).CreateNavigator()\n\n// first \"item\"; throws if none exists\nlet item = nav.SelectSingleNode(@\"//item[1]\")\n\n// apply a operation (print text value) to all price elements\nfor price in nav.Select(@\"//price\") do\n printfn \"%s\" (price.ToString())\n\n// array of all name elements\nlet names = seq { for name in nav.Select(@\"//name\") do yield name } |> Seq.toArray\n", "language": "F-Sharp" }, { "code": "! Get first item element\n\"\"\"<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\"\"\" string>xml \"item\" deep-tag-named\n\n! Print out prices\n\"\"\"<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\"\"\" string>xml \"price\" deep-tags-named [ children>> first ] map\n\n! Array of all name elements\n\"\"\"<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\"\"\" string>xml \"name\" deep-tags-named\n", "language": "Factor" }, { "code": "Dim As String XML, item, price, nombre\nDim As Integer P1, P2\n\n'' Read the XML file\nOpen \"test3.xml\" For Input As #1\nXML = Input(Lof(1), #1)\nClose #1\n\n'' Find the first 'item' element\nP1 = Instr(XML, \"<item \")\nP2 = Instr(XML, \"</item>\")\nitem = Mid(XML, P1, P2-P1+7)\nPrint \"The first 'item' element is:\"\nPrint item\n\n'' Find all 'price' elements\nPrint \"The 'prices' are:\"\nP1 = 1\nDo\n P1 = Instr(P1, XML, \"<price>\")\n If P1 = 0 Then Exit Do\n P2 = Instr(P1, XML, \"</price>\")\n price = Mid(XML, P1+7, P2-P1-7)\n Print price\n P1 = P2 + 1\nLoop\n\n'' Find all 'nombre' elements\nPrint !\"\\nThe 'names' are:\"\nP1 = 1\nDo\n P1 = Instr(P1, XML, \"<name>\")\n If P1 = 0 Then Exit Do\n P2 = Instr(P1, XML, \"</name>\")\n nombre = Mid(XML, P1+6, P2-P1-6)\n Print nombre\n P1 = P2 + 1\nLoop\n\nSleep\n", "language": "FreeBASIC" }, { "code": "#javaj#\n\n <frames> oSal, XML Path sample, 300, 400\n\n#data#\n\n <xml>\n //<inventory title=\"OmniCorp Store #45x10^3\">\n // <section name=\"health\">\n // <item upc=\"123456789\" stock=\"12\">\n // <name>Invisibility Cream</name>\n // <price>14.50</price>\n // <description>Makes you invisible</description>\n // </item>\n // <item upc=\"445322344\" stock=\"18\">\n // <name>Levitation Salve</name>\n // <price>23.99</price>\n // <description>Levitate yourself for up to 3 hours per application</description>\n // </item>\n // </section>\n // <section name=\"food\">\n // <item upc=\"485672034\" stock=\"653\">\n // <name>Blork and Freen Instameal</name>\n // <price>4.95</price>\n // <description>A tasty meal in a tablet; just add water</description>\n // </item>\n // <item upc=\"132957764\" stock=\"44\">\n // <name>Grob winglets</name>\n // <price>3.56</price>\n // <description>Tender winglets of Grob. Just add water</description>\n // </item>\n // </section>\n //</inventory>\n\n <DEEP_SQL_XML>\n DEEP DB, SELECT, xmelon_data\n ,, path pathStr\n ,, tag tagStr\n ,, patCnt\n ,, dataPlace\n ,, value\n\n#listix#\n\n <main>\n //parsing xml data ...\n GEN, :mem datos, xml\n XMELON, FILE2DB, :mem datos\n //\n //first item ...\n //\n //\n LOOP, SQL,, //SELECT patCnt AS patITEM1 FROM (@<DEEP_SQL_XML>) WHERE path_pathStr == '/inventory/section/item' LIMIT 1\n ,HEAD, //<item\n ,, LOOP, SQL,, //SELECT * FROM (@<DEEP_SQL_XML>) WHERE patCnt == @<patITEM1> AND dataPlace == 'A'\n ,, , LINK, \"\"\n ,, ,, // @<tag_tagStr>=\"@<value>\"\n ,, //>\n ,, //\n ,, LOOP, SQL,, //SELECT * FROM (@<DEEP_SQL_XML>) WHERE patCnt == @<patITEM1> AND dataPlace != 'A'\n ,, ,, // <@<tag_tagStr>>@<value></@<tag_tagStr>>\n ,TAIL, //\n ,TAIL, //</item>\n //\n //\n //report prices ...\n //\n LOOP, SQL,, //SELECT value FROM (@<DEEP_SQL_XML>) WHERE tag_tagStr == 'price'\n , LINK, \", \"\n ,, @<value>\n //\n //put names into a variable\n //\n VAR=, tabnames, \"name\"\n LOOP, SQL,, //SELECT value FROM (@<DEEP_SQL_XML>) WHERE tag_tagStr == 'name'\n , LINK, \"\"\n ,, VAR+, tabnames, @<value>\n DUMP, data,, tabnames\n", "language": "Gastona" }, { "code": "package main\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\ntype Inventory struct {\n\tXMLName xml.Name `xml:\"inventory\"`\n\tTitle string `xml:\"title,attr\"`\n\tSections []struct {\n\t\tXMLName xml.Name `xml:\"section\"`\n\t\tName string `xml:\"name,attr\"`\n\t\tItems []struct {\n\t\t\tXMLName xml.Name `xml:\"item\"`\n\t\t\tName string `xml:\"name\"`\n\t\t\tUPC string `xml:\"upc,attr\"`\n\t\t\tStock int `xml:\"stock,attr\"`\n\t\t\tPrice float64 `xml:\"price\"`\n\t\t\tDescription string `xml:\"description\"`\n\t\t} `xml:\"item\"`\n\t} `xml:\"section\"`\n}\n\n// To simplify main's error handling\nfunc printXML(s string, v interface{}) {\n\tfmt.Println(s)\n\tb, err := xml.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(string(b))\n\tfmt.Println()\n}\n\nfunc main() {\n\tfmt.Println(\"Reading XML from standard input...\")\n\n\tvar inv Inventory\n\tdec := xml.NewDecoder(os.Stdin)\n\tif err := dec.Decode(&inv); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// At this point, inv is Go struct with all the fields filled\n\t// in from the XML data. Well-formed XML input that doesn't\n\t// match the specification of the fields in the Go struct are\n\t// discarded without error.\n\n\t// We can reformat the parts we parsed:\n\t//printXML(\"Got:\", inv)\n\n\t// 1. Retrieve first item:\n\titem := inv.Sections[0].Items[0]\n\tfmt.Println(\"item variable:\", item)\n\tprintXML(\"As XML:\", item)\n\n\t// 2. Action on each price:\n\tfmt.Println(\"Prices:\")\n\tvar totalValue float64\n\tfor _, s := range inv.Sections {\n\t\tfor _, i := range s.Items {\n\t\t\tfmt.Println(i.Price)\n\t\t\ttotalValue += i.Price * float64(i.Stock)\n\t\t}\n\t}\n\tfmt.Println(\"Total inventory value:\", totalValue)\n\tfmt.Println()\n\n\t// 3. Slice of all the names:\n\tvar names []string\n\tfor _, s := range inv.Sections {\n\t\tfor _, i := range s.Items {\n\t\t\tnames = append(names, i.Name)\n\t\t}\n\t}\n\tfmt.Printf(\"names: %q\\n\", names)\n}\n", "language": "Go" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n\n \"launchpad.net/xmlpath\"\n)\n\nfunc main() {\n f, err := os.Open(\"test3.xml\")\n if err != nil {\n fmt.Println(err)\n return\n }\n n, err := xmlpath.Parse(f)\n f.Close()\n if err != nil {\n fmt.Println(err)\n return\n }\n q1 := xmlpath.MustCompile(\"//item\")\n if _, ok := q1.String(n); !ok {\n fmt.Println(\"no item\")\n }\n q2 := xmlpath.MustCompile(\"//price\")\n for it := q2.Iter(n); it.Next(); {\n fmt.Println(it.Node())\n }\n q3 := xmlpath.MustCompile(\"//name\")\n names := []*xmlpath.Node{}\n for it := q3.Iter(n); it.Next(); {\n names = append(names, it.Node())\n }\n if len(names) == 0 {\n fmt.Println(\"no names\")\n }\n}\n", "language": "Go" }, { "code": "def inventory = new XmlSlurper().parseText(\"<inventory...\") //optionally parseText(new File(\"inv.xml\").text)\ndef firstItem = inventory.section.item[0] //1. first item\ninventory.section.item.price.each { println it } //2. print each price\ndef allNamesArray = inventory.section.item.name.collect {it} //3. collect item names into an array\n", "language": "Groovy" }, { "code": "import Data.List\nimport Control.Arrow\nimport Control.Monad\n\ntakeWhileIncl :: (a -> Bool) -> [a] -> [a]\ntakeWhileIncl _ [] = []\ntakeWhileIncl p (x:xs)\n | p x = x : takeWhileIncl p xs\n | otherwise = [x]\n\ngetmultiLineItem n = takeWhileIncl(not.isInfixOf (\"</\" ++ n)). dropWhile(not.isInfixOf ('<': n))\ngetsingleLineItems n = map (takeWhile(/='<'). drop 1. dropWhile(/='>')). filter (isInfixOf ('<': n))\n\nmain = do\n xml <- readFile \"./Rosetta/xmlpath.xml\"\n let xmlText = lines xml\n\n putStrLn \"\\n== First item ==\\n\"\n mapM_ putStrLn $ head $ unfoldr (Just. liftM2 (id &&&) (\\\\) (getmultiLineItem \"item\")) xmlText\n\n putStrLn \"\\n== Prices ==\\n\"\n mapM_ putStrLn $ getsingleLineItems \"price\" xmlText\n\n putStrLn \"\\n== Names ==\\n\"\n print $ getsingleLineItems \"name\" xmlText\n", "language": "Haskell" }, { "code": "{-# LANGUAGE Arrows #-}\nimport Text.XML.HXT.Arrow\n{- For HXT version >= 9.0, use instead:\nimport Text.XML.HXT.Core\n-}\n\ndeepElem name = deep (isElem >>> hasName name)\n\nprocess = proc doc -> do\n item <- single (deepElem \"item\") -< doc\n _ <- listA (arrIO print <<< deepElem \"price\") -< doc\n names <- listA (deepElem \"name\") -< doc\n returnA -< (item, names)\n\nmain = do\n [(item, names)] <- runX (readDocument [] \"xmlpath.xml\" >>> process)\n print item\n print names\n", "language": "Haskell" }, { "code": "CHARACTER xml*1000, output*1000\n READ(ClipBoard) xml\n\n EDIT(Text=xml, Right='<item', Right=5, GetPosition=a, Right='</item>', Left, GetPosition=z)\n WRITE(Text=output) xml( a : z), $CRLF\n\n i = 1\n1 EDIT(Text=xml, SetPosition=i, SePaRators='<>', Right='<price>', Word=1, Parse=price, GetPosition=i, ERror=99)\n IF(i > 0) THEN\n WRITE(Text=output, APPend) 'Price element = ', price, $CRLF\n GOTO 1 ! HicEst does not have a \"WHILE\"\n ENDIF\n\n EDIT(Text=xml, SPR='<>', R='<name>', W=1, WordEnd=$CR, APpendTo=output, DO=999)\n WRITE(ClipBoard) TRIM(output)\n", "language": "HicEst" }, { "code": " upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n\nPrice element = 14.50\nPrice element = 23.99\nPrice element = 4.95\nPrice element = 3.56\nInvisibility Cream\n Levitation Salve\n Blork and Freen Instameal\n Grob winglets\n", "language": "HicEst" }, { "code": "import java.io.StringReader;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.InputSource;\n\npublic class XMLParser {\n\tfinal static String xmlStr =\n\t\t\t \"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\"\n\t\t\t+ \" <section name=\\\"health\\\">\"\n\t\t\t+ \" <item upc=\\\"123456789\\\" stock=\\\"12\\\">\"\n\t\t\t+ \" <name>Invisibility Cream</name>\"\n\t\t\t+ \" <price>14.50</price>\"\n\t\t\t+ \" <description>Makes you invisible</description>\"\n\t\t\t+ \" </item>\"\n\t\t\t+ \" <item upc=\\\"445322344\\\" stock=\\\"18\\\">\"\n\t\t\t+ \" <name>Levitation Salve</name>\"\n\t\t\t+ \" <price>23.99</price>\"\n\t\t\t+ \" <description>Levitate yourself for up to 3 hours per application</description>\"\n\t\t\t+ \" </item>\"\n\t\t\t+ \" </section>\"\n\t\t\t+ \" <section name=\\\"food\\\">\"\n\t\t\t+ \" <item upc=\\\"485672034\\\" stock=\\\"653\\\">\"\n\t\t\t+ \" <name>Blork and Freen Instameal</name>\"\n\t\t\t+ \" <price>4.95</price>\"\n\t\t\t+ \" <description>A tasty meal in a tablet; just add water</description>\"\n\t\t\t+ \" </item>\"\n\t\t\t+ \" <item upc=\\\"132957764\\\" stock=\\\"44\\\">\"\n\t\t\t+ \" <name>Grob winglets</name>\"\n\t\t\t+ \" <price>3.56</price>\"\n\t\t\t+ \" <description>Tender winglets of Grob. Just add priwater</description>\"\n\t\t\t+ \" </item>\"\n\t\t\t+ \" </section>\"\n\t\t\t+ \"</inventory>\";\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tDocument doc = DocumentBuilderFactory.newInstance()\n\t\t\t\t\t.newDocumentBuilder()\n\t\t\t\t\t.parse(new InputSource(new StringReader(xmlStr)));\n\t\t\tXPath xpath = XPathFactory.newInstance().newXPath();\n\t\t\t// 1\n\t\t\tSystem.out.println(((Node) xpath.evaluate(\n\t\t\t\t\t\"/inventory/section/item[1]\", doc, XPathConstants.NODE))\n\t\t\t\t\t.getAttributes().getNamedItem(\"upc\"));\n\t\t\t// 2, 3\n\t\t\tNodeList nodes = (NodeList) xpath.evaluate(\n\t\t\t\t\t\"/inventory/section/item/price\", doc,\n\t\t\t\t\tXPathConstants.NODESET);\n\t\t\tfor (int i = 0; i < nodes.getLength(); i++)\n\t\t\t\tSystem.out.println(nodes.item(i).getTextContent());\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"Error ocurred while parsing XML.\");\n\t\t}\n\t}\n}\n", "language": "Java" }, { "code": "//create XMLDocument object from file\nvar xhr = new XMLHttpRequest();\nxhr.open('GET', 'file.xml', false);\nxhr.send(null);\nvar doc = xhr.responseXML;\n\n//get first <item> element\nvar firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;\nalert( firstItem.textContent );\n\n//output contents of <price> elements\nvar prices = doc.evaluate( '//price', doc, null, XPathResult.ANY_TYPE, null );\nfor( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) {\n alert( price.textContent );\n}\n\n//add <name> elements to array\nvar names = doc.evaluate( '//name', doc, null, XPathResult.ANY_TYPE, null);\nvar namesArray = [];\nfor( var name = names.iterateNext(); name != null; name = names.iterateNext() ) {\n namesArray.push( name );\n}\nalert( namesArray );\n", "language": "JavaScript" }, { "code": "//create XML object from file\nvar xhr = new XMLHttpRequest();\nxhr.open('GET', 'file.xml', false);\nxhr.send(null);\nvar doc = new XML(xhr.responseText);\n\n//get first <item> element\nvar firstItem = doc..item[0];\nalert( firstItem );\n\n//output contents of <price> elements\nfor each( var price in doc..price ) {\n alert( price );\n}\n\n//add <name> elements to array\nvar names = [];\nfor each( var name in doc..name ) {\n names.push( name );\n}\nalert( names );\n", "language": "JavaScript" }, { "code": "using LibExpat\n\nxdoc = raw\"\"\"<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\"\"\"\n\ndebracket(s) = replace(s, r\".+\\>(.+)\\<.+\" => s\"\\1\")\n\netree = xp_parse(xdoc)\nfirstshow = LibExpat.find(etree, \"//item\")[1]\nprintln(\"The first item's node XML entry is:\\n\", firstshow, \"\\n\\n\")\n\nprices = LibExpat.find(etree, \"//price\")\nprintln(\"Prices:\")\nfor p in prices\n println(\"\\t\", debracket(string(p)))\nend\nprintln(\"\\n\")\n\nnamearray = LibExpat.find(etree, \"//name\")\nprintln(\"Array of names of items:\\n\\t\", map(s -> debracket(string(s)), namearray))\n", "language": "Julia" }, { "code": "// version 1.1.3\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport org.xml.sax.InputSource\nimport java.io.StringReader\nimport javax.xml.xpath.XPathFactory\nimport javax.xml.xpath.XPathConstants\nimport org.w3c.dom.Node\nimport org.w3c.dom.NodeList\n\nval xml =\n\"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\"\"\"\n\nfun main(args: Array<String>) {\n val dbFactory = DocumentBuilderFactory.newInstance()\n val dBuilder = dbFactory.newDocumentBuilder()\n val xmlInput = InputSource(StringReader(xml))\n val doc = dBuilder.parse(xmlInput)\n val xpFactory = XPathFactory.newInstance()\n val xPath = xpFactory.newXPath()\n\n val qNode = xPath.evaluate(\"/inventory/section/item[1]\", doc, XPathConstants.NODE) as Node\n val upc = qNode.attributes.getNamedItem(\"upc\")\n val stock = qNode.attributes.getNamedItem(\"stock\")\n println(\"For the first item : upc = ${upc.textContent} and stock = ${stock.textContent}\")\n\n val qNodes = xPath.evaluate(\"/inventory/section/item/price\", doc, XPathConstants.NODESET) as NodeList\n print(\"\\nThe prices of each item are : \")\n for (i in 0 until qNodes.length) print(\"${qNodes.item(i).textContent} \")\n println()\n\n val qNodes2 = xPath.evaluate(\"/inventory/section/item/name\", doc, XPathConstants.NODESET) as NodeList\n val names = Array<String>(qNodes2.length) { qNodes2.item(it).textContent }\n println(\"\\nThe names of each item are as follows :\")\n println(\" ${names.joinToString(\"\\n \")}\")\n}\n", "language": "Kotlin" }, { "code": "#!/bin/ksh\n\n# Perform XPath queries on a XML Document\n\n#\t# Variables:\n#\ntypeset -T Xml_t=(\n\ttypeset -h\t\t'UPC'\t\t\tupc\n\ttypeset -i -h\t'num in stock'\tstock=0\n\ttypeset -h\t\t'name'\t\t\tname\n\ttypeset -F2 -h\t'price'\t\t\tprice\n\ttypeset -h\t\t'description'\tdescription\n\n\tfunction init_item {\n\t\ttypeset key ; key=\"$1\"\n\t\ttypeset val ; val=\"${2%\\<\\/${key}*}\"\n\n\t\tcase ${key} in\n\t\t\tupc)\t\t\t_.upc=\"${val//@(\\D)/}\"\n\t\t\t\t;;\n\t\t\tstock)\t\t\t_.stock=\"${val//@(\\D)/}\"\n\t\t\t\t;;\n\t\t\tname)\t\t\t_.name=\"${val%\\<\\/${key}*}\"\n\t\t\t\t;;\n\t\t\tprice)\t\t\t_.price=\"${val}\"\n\t\t\t\t;;\n\t\t\tdescription)\t_.description=$(echo ${val})\n\t\t\t\t;;\n\t\tesac\n\t}\n\n\tfunction prt_item {\n\t\tprint \"upc= ${_.upc}\"\n\t\tprint \"stock= ${_.stock}\"\n\t\tprint \"name= ${_.name}\"\n\t\tprint \"price= ${_.price}\"\n\t\tprint \"description= ${_.description}\"\n\t}\n)\n\n#\t# Functions:\n#\n\n\n ######\n# main #\n ######\ninteger i=0\ntypeset -a Item_t\n\nbuff=$(< xmldoc)\t# read xmldoc\nitem=${buff%%'</item>'*} ; buff=${.sh.match}\n\nwhile [[ -n ${item} ]]; do\n\tXml_t Item_t[i]\n\titem=${item#*'<item'} ; item=$(echo ${item})\n\tfor word in ${item}; do\n\t\tif [[ ${word} == *=* ]]; then\n\t\t\tItem_t[i].init_item ${word%\\=*} ${word#*\\=}\n\t\telse\n\t\t\tif [[ ${word} == \\<* ]]; then\t\t# Beginning\n\t\t\t\tkey=${word%%\\>*} ; key=${key#*\\<}\n\t\t\t\tval=${word#*\\>}\n\t\t\tfi\n\n\t\t\t[[ ${word} != \\<* && ${word} != *\\> ]] && val+=\" ${word} \"\n\n\t\t\tif [[ ${word} == *\\> ]]; then\t\t# End\n\t\t\t\tval+=\" ${word%\\<${key}\\>*}\"\n\t\t\t\tItem_t[i].init_item \"${key}\" \"${val}\"\n\t\t\tfi\n\t\tfi\n\tdone\n\t(( i++ ))\n\titem=${buff#*'</item>'} ; item=${item%%'</item>'*} ; buff=${.sh.match}\ndone\n\nprint \"First Item element:\"\nItem_t[0].prt_item\n\ntypeset -a names\nprintf \"\\nList of prices:\\n\"\nfor ((i=0; i<${#Item_t[*]}-1; i++)); do\n\tprint ${Item_t[i].price}\n\tnames[i]=${Item_t[i].name}\ndone\n\nprintf \"\\nArray of names:\\n\"\nfor (( i=0; i<${#names[*]}; i++)); do\n\tprint \"names[$i] = ${names[i]}\"\ndone\n", "language": "Ksh" }, { "code": "// makes extracting attribute values easier\ndefine xml_attrmap(in::xml_namedNodeMap_attr) => {\n\tlocal(out = map)\n\twith attr in #in\n\t\tdo #out->insert(#attr->name = #attr->value)\n\treturn #out\n}\n\nlocal(\n\ttext = '<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n',\nxml = xml(#text)\n)\n\nlocal(\n\titems\t\t= #xml -> extract('//item'),\n\tfirstitem\t= #items -> first,\n\titemattr\t= xml_attrmap(#firstitem -> attributes),\n\tnewprices\t= array\n)\n\n'<strong>First item:</strong><br />\nUPC: '\n#itemattr -> find('upc')\n' (stock: '\n#itemattr -> find('stock')\n')<br />'\n#firstitem -> extractone('name') -> nodevalue\n' ['\n#firstitem -> extractone('price') -> nodevalue\n'] ('\n#firstitem -> extractone('description') -> nodevalue\n')<br /><br />'\n\nwith item in #items\nlet name = #item -> extractone('name') -> nodevalue\nlet price = #item -> extractone('price') -> nodevalue\ndo {\n\t#newprices -> insert(#name + ': ' + (decimal(#price) * 1.10) -> asstring(-precision = 2) + ' (' + #price + ')')\n}\n'<strong>Adjusted prices:</strong><br />'\n#newprices -> join('<br />')\n'<br /><br />'\n'<strong>Array with all names:</strong><br />'\n#xml -> extract('//name') -> asstaticarray\n", "language": "Lasso" }, { "code": "put revXMLCreateTree(fld \"FieldXML\",true,true,false) into xmltree\n\n// task 1\nput revXMLEvaluateXPath(xmltree,\"//item[1]\") into nodepath\nput revXMLText(xmltree,nodepath,true)\n\n// task 2\nput revXMLDataFromXPathQuery(xmltree,\"//item/price\",,comma)\n\n// task 3\nput revXMLDataFromXPathQuery(xmltree,\"//name\") into namenodes\nfilter namenodes without empty\nsplit namenodes using cr\nput namenodes is an array\n", "language": "LiveCode" }, { "code": "require 'lxp'\ndata = [[<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>]]\nlocal first = true\nlocal names, prices = {}, {}\np = lxp.new({StartElement = function (parser, name)\n\tlocal a, b, c = parser:pos() --line, offset, pos\n\tif name == 'item' and first then\n\t\tprint(data:match('.-</item>', c - b + 1))\n\t\tfirst = false\n\tend\n\tif name == 'name' then names[#names+1] = data:match('>(.-)<', c) end\n\tif name == 'price' then prices[#prices+1] = data:match('>(.-)<', c) end\nend})\n\np:parse(data)\np:close()\n\nprint('Name: ', table.concat(names, ', '))\nprint('Price: ', table.concat(prices, ', '))\n", "language": "Lua" }, { "code": "example = Import[\"test.txt\", \"XML\"];\nCases[example, XMLElement[\"item\", _ , _] , Infinity] // First\nCases[example, XMLElement[\"price\", _, List[n_]] -> n, Infinity] // Column\nCases[example, XMLElement[\"name\", _, List[n_]] -> n, Infinity] // Column\n", "language": "Mathematica" }, { "code": "/* NetRexx */\noptions replace format comments java symbols binary\n\nimport javax.xml.parsers.\nimport javax.xml.xpath.\nimport org.w3c.dom.\nimport org.w3c.dom.Node\nimport org.xml.sax.\n\nxmlStr = '' -\n || '<inventory title=\"OmniCorp Store #45x10^3\">' -\n || ' <section name=\"health\">' -\n || ' <item upc=\"123456789\" stock=\"12\">' -\n || ' <name>Invisibility Cream</name>' -\n || ' <price>14.50</price>' -\n || ' <description>Makes you invisible</description>' -\n || ' </item>' -\n || ' <item upc=\"445322344\" stock=\"18\">' -\n || ' <name>Levitation Salve</name>' -\n || ' <price>23.99</price>' -\n || ' <description>Levitate yourself for up to 3 hours per application</description>' -\n || ' </item>' -\n || ' </section>' -\n || ' <section name=\"food\">' -\n || ' <item upc=\"485672034\" stock=\"653\">' -\n || ' <name>Blork and Freen Instameal</name>' -\n || ' <price>4.95</price>' -\n || ' <description>A tasty meal in a tablet; just add water</description>' -\n || ' </item>' -\n || ' <item upc=\"132957764\" stock=\"44\">' -\n || ' <name>Grob winglets</name>' -\n || ' <price>3.56</price>' -\n || ' <description>Tender winglets of Grob. Just add priwater</description>' -\n || ' </item>' -\n || ' </section>' -\n || '</inventory>'\n\nexpr1 = '/inventory/section/item[1]'\nexpr2 = '/inventory/section/item/price'\nexpr3 = '/inventory/section/item/name'\nattr1 = 'upc'\n\ndo\n doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(xmlStr)))\n xpath = XPathFactory.newInstance().newXPath()\n\n -- Extract attribute from 1st item element\n say expr1\n say \" \"(Node xpath.evaluate(expr1, doc, XPathConstants.NODE)).getAttributes().getNamedItem(attr1)\n say\n\n -- Extract and display all price elments\n nodes = NodeList xpath.evaluate(expr2, doc, XPathConstants.NODESET)\n say expr2\n loop i_ = 0 to nodes.getLength() - 1\n say Rexx(nodes.item(i_).getTextContent()).format(10, 2)\n end i_\n say\n\n -- Extract elements and store in an ArrayList\n nameList = java.util.List\n nameList = ArrayList()\n nodes = NodeList xpath.evaluate(expr3, doc, XPathConstants.NODESET)\n loop i_ = 0 to nodes.getLength() - 1\n nameList.add(nodes.item(i_).getTextContent())\n end i_\n\n -- display contents of ArrayList\n say expr3\n loop n_ = 0 to nameList.size() - 1\n say \" \"nameList.get(n_)\n end n_\n say\n\ncatch ex = Exception\n ex.printStackTrace()\nend\n\nreturn\n", "language": "NetRexx" }, { "code": "import sequtils, strutils\n\nconst LibXml = \"libxml2.so\"\n\ntype\n\n XmlDocPtr = pointer\n\n XmlXPathContextPtr = pointer\n\n XmlElementKind = enum\n xmlElementNode = 1\n xmlAttributeNode = 2\n xmlTextNode = 3\n xmlCdataSectionNode = 4\n xmlEntityRefNode = 5\n xmlEntityNode = 6\n xmlPiNode = 7\n xmlCommentNode = 8\n xmlDocumentNode = 9\n xmlDocumentTypeNode = 10\n xmlDocumentFragNode = 11\n xmlNotationNode = 12\n xmlHtmlDocumentNode = 13\n xmlDtdNode = 14\n xmlElementDecl = 15\n xmlAttributeDecl = 16\n xmlEntityDecl = 17\n xmlNamespaceDecl = 18\n xmlXincludeStart = 19\n xmlXincludeEnd = 20\n\n XmlNsKind = XmlElementKind\n\n XmlNsPtr = ptr XmlNs\n XmlNs = object\n next: XmlNsPtr\n kind: XmlNsKind\n href: cstring\n prefix: cstring\n private: pointer\n context: XmlDocPtr\n\n XmlAttrPtr = pointer\n\n XmlNodePtr = ptr XmlNode\n XmlNode = object\n private: pointer\n kind: XmlElementKind\n name: cstring\n children: XmlNodePtr\n last: XmlNodePtr\n parent: XmlNodePtr\n next: XmlNodePtr\n prev: XmlNodePtr\n doc: XmlDocPtr\n ns: XmlNsPtr\n content: cstring\n properties: XmlAttrPtr\n nsDef: XmlNsPtr\n psvi: pointer\n line: cushort\n extra: cushort\n\n XmlNodeSetPtr = ptr XmlNodeSet\n XmlNodeSet = object\n nodeNr: cint\n nodeMax: cint\n nodeTab: ptr UncheckedArray[XmlNodePtr]\n\n XmlPathObjectKind = enum\n xpathUndefined\n xpathNodeset\n xpathBoolean\n xpathNumber\n xpathString\n xpathPoint\n xpathRange\n xpathLocationset\n xpathUsers\n xpathXsltTree\n\n XmlXPathObjectPtr = ptr XmlXPathObject\n XmlXPathObject = object\n kind: XmlPathObjectKind\n nodeSetVal: XmlNodeSetPtr\n boolVal: cint\n floatVal: cdouble\n stringVal: cstring\n user: pointer\n index: cint\n user2: pointer\n index2: cint\n\n XmlSaveCtxtPtr = pointer\n\n XmlBufferPtr = pointer\n\n\n# Declaration of needed \"libxml2\" procedures.\nproc xmlParseFile(docName: cstring): XmlDocPtr\n {.cdecl, dynlib: LibXml, importc: \"xmlParseFile\".}\n\nproc xmlXPathNewContext(doc: XmlDocPtr): XmlXPathContextPtr\n {.cdecl, dynlib: LibXml, importc: \"xmlXPathNewContext\".}\n\nproc xmlXPathEvalExpression(str: cstring; ctxt: XmlXPathContextPtr): XmlXPathObjectPtr\n {.cdecl, dynlib: LibXml, importc: \"xmlXPathEvalExpression\".}\n\nproc xmlXPathFreeContext(ctxt: XmlXPathContextPtr)\n {.cdecl, dynlib: LibXml, importc: \"xmlXPathFreeContext\".}\n\nproc xmlXPathFreeObject(obj: XmlXPathObjectPtr)\n {.cdecl, dynlib: LibXml, importc: \"xmlXPathFreeObject\".}\n\nproc xmlSaveToBuffer(vuffer: XmlBufferPtr; encoding: cstring; options: cint): XmlSaveCtxtPtr\n {.cdecl, dynlib: LibXml, importc: \"xmlSaveToBuffer\".}\n\nproc xmlBufferCreate(): XmlBufferPtr\n {.cdecl, dynlib: LibXml, importc: \"xmlBufferCreate\".}\n\nproc xmlBufferFree(buf: XmlBufferPtr)\n {.cdecl, dynlib: LibXml, importc: \"xmlBufferCreate\".}\n\nproc xmlBufferContent(buf: XmlBufferPtr): cstring\n {.cdecl, dynlib: LibXml, importc: \"xmlBufferContent\".}\n\nproc xmlSaveTree(ctxt: XmlSaveCtxtPtr; cur: XmlNodePtr): clong\n {.cdecl, dynlib: LibXml, importc: \"xmlSaveTree\".}\n\nproc xmlSaveClose(ctxt: XmlSaveCtxtPtr)\n {.cdecl, dynlib: LibXml, importc: \"xmlSaveClose\".}\n\n\nproc `$`(node: XmlNodePtr): string =\n ## Return the representation of a node.\n let buffer = xmlBufferCreate()\n let saveContext = xmlSaveToBuffer(buffer, nil, 0)\n discard saveContext.xmlSaveTree(node)\n saveContext.xmlSaveClose()\n result = $buffer.xmlBufferContent()\n xmlBufferFree(buffer)\n\n\niterator nodes(xpath: string; context: XmlXPathContextPtr): XmlNodePtr =\n ## Yield the nodes which fit the XPath request.\n let xpathObj = xmlXPathEvalExpression(xpath, context)\n if xpathObj.isNil:\n quit \"Failed to evaluate XPath: \" & xpath, QuitFailure\n assert xpathObj.kind == xpathNodeset\n let nodeSet = xpathObj.nodeSetVal\n if not nodeSet.isNil:\n for i in 0..<nodeSet.nodeNr:\n yield nodeSet.nodeTab[i]\n xmlXPathFreeObject(xpathObj)\n\n\n# Load and parse XML file.\nlet doc = xmlParseFile(\"xpath_test.xml\")\nif doc.isNil:\n quit \"Unable to load and parse document\", QuitFailure\n\n# Create an XPath context.\nlet context = xmlXPathNewContext(doc)\nif context.isNil:\n quit \"Failed to create XPath context\", QuitFailure\n\nvar xpath = \"//section[1]/item[1]\"\necho \"Request $#:\".format(xpath)\nfor node in nodes(xpath, context):\n echo node\necho()\n\nxpath = \"//price/text()\"\necho \"Request $#:\".format(xpath)\nfor node in nodes(xpath, context):\n echo node.content\necho()\n\nxpath = \"//name\"\necho \"Request $#:\".format(xpath)\nlet names = toSeq(nodes(xpath, context)).mapIt(it.children.content)\necho names\n\nxmlXPathFreeContext(context)\n", "language": "Nim" }, { "code": "use XML;\n\nbundle Default {\n class Test {\n function : Main(args : String[]) ~ Nil {\n in := String->New();\n in->Append(\"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\");\n in->Append(\"<section name=\\\"health\\\">\");\n in->Append(\"<item upc=\\\"123456789\\\" stock=\\\"12\\\">\");\n in->Append(\"<name>Invisibility Cream</name>\");\n in->Append(\"<price>14.50</price>\");\n in->Append(\"<description>Makes you invisible</description>\");\n in->Append(\"</item>\");\n in->Append(\"<item upc=\\\"445322344\\\" stock=\\\"18\\\">\");\n in->Append(\"<name>Levitation Salve</name>\");\n in->Append(\"<price>23.99</price>\");\n in->Append(\"<description>Levitate yourself for up to 3 hours per application</description>\");\n in->Append(\"</item>\");\n in->Append(\"</section>\");\n in->Append(\"<section name=\\\"food\\\">\");\n in->Append(\"<item upc=\\\"485672034\\\" stock=\\\"653\\\">\");\n in->Append(\"<name>Blork and Freen Instameal</name>\");\n in->Append(\"<price>4.95</price>\");\n in->Append(\"<description>A tasty meal in a tablet; just add water</description>\");\n in->Append(\"</item>\");\n in->Append(\"<item upc=\\\"132957764\\\" stock=\\\"44\\\">\");\n in->Append(\"<name>Grob winglets</name>\");\n in->Append(\"<price>3.56</price>\");\n in->Append(\"<description>Tender winglets of Grob. Just add water</description>\");\n in->Append(\"</item>\");\n in->Append(\"</section>\");\n in->Append(\"</inventory>\");\n\n parser := XmlParser->New(in);\n if(parser->Parse()) {\n # get first item\n results := parser->FindElements(\"//inventory/section[1]/item[1]\");\n if(results <> Nil) {\n IO.Console->Instance()->Print(\"items: \")->PrintLine(results->Size());\n };\n # get all prices\n results := parser->FindElements(\"//inventory/section/item/price\");\n if(results <> Nil) {\n each(i : results) {\n element := results->Get(i)->As(XMLElement);\n element->GetContent()->PrintLine();\n };\n };\n # get names\n results := parser->FindElements(\"//inventory/section/item/name\");\n if(results <> Nil) {\n IO.Console->Instance()->Print(\"names: \")->PrintLine(results->Size());\n };\n };\n }\n }\n}\n", "language": "Objeck" }, { "code": "declare\n [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}\n\n proc {Main Data}\n Parser = {New XMLParser.parser init}\n [Doc] = {Parser parseVS(Data $)}\n\n FirstItem = {XPath Doc [inventory section item]}.1\n\n Prices = {XPath Doc [inventory section item price Text]}\n\n Names = {XPath Doc [inventory section item name]}\n in\n {ForAll Prices System.showInfo}\n end\n\n %%\n %% Emulation of some XPath functionality:\n %%\n\n fun {XPath Doc Path}\n P|Pr = Path\n in\n Doc.name = P %% assert\n {FoldL Pr XPathStep [Doc]}\n end\n\n fun {XPathStep Elements P}\n if {IsProcedure P} then\n {Map Elements P}\n else\n {FilteredChildren Elements P}\n end\n end\n\n %% A flat list of all Type-children of all Elements.\n fun {FilteredChildren Elements Type}\n {Flatten\n {Map Elements\n fun {$ E}\n\t {Filter E.children\n\t fun {$ X}\n\t case X of element(name:!Type ...) then true\n\t else false\n\t end\n\t end}\n end}}\n end\n\n %% PCDATA of an element as a ByteString\n fun {Text Element}\n Texts = for Child in Element.children collect:C do\n\t\tcase Child of text(data:BS ...) then {C BS} end\n\t end\n in\n {FoldR Texts ByteString.append {ByteString.make nil}}\n end\n\n Data =\n \"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\"\n #\" <section name=\\\"health\\\">\"\n #\" <item upc=\\\"123456789\\\" stock=\\\"12\\\">\"\n #\" <name>Invisibility Cream</name>\"\n #\" <price>14.50</price>\"\n #\" <description>Makes you invisible</description>\"\n #\" </item>\"\n #\" <item upc=\\\"445322344\\\" stock=\\\"18\\\">\"\n #\" <name>Levitation Salve</name>\"\n #\" <price>23.99</price>\"\n #\" <description>Levitate yourself for up to 3 hours per application</description>\"\n #\" </item>\"\n #\" </section>\"\n #\" <section name=\\\"food\\\">\"\n #\" <item upc=\\\"485672034\\\" stock=\\\"653\\\">\"\n #\" <name>Blork and Freen Instameal</name>\"\n #\" <price>4.95</price>\"\n #\" <description>A tasty meal in a tablet; just add water</description>\"\n #\" </item>\"\n #\" <item upc=\\\"132957764\\\" stock=\\\"44\\\">\"\n #\" <name>Grob winglets</name>\"\n #\" <price>3.56</price>\"\n #\" <description>Tender winglets of Grob. Just add water</description>\"\n #\" </item>\"\n #\" </section>\"\n #\"</inventory>\"\nin\n {Main Data}\n", "language": "Oz" }, { "code": "use XML::XPath qw();\n\nmy $x = XML::XPath->new('<inventory ... </inventory>');\n\n[$x->findnodes('//item[1]')->get_nodelist]->[0];\nprint $x->findnodes_as_string('//price');\n$x->findnodes('//name')->get_nodelist;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">xml</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">xml_txt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"\"\n &lt;inventory title=\"OmniCorp Store #45x10^3\"&gt;\n &lt;section name=\"health\"&gt;\n &lt;item upc=\"123456789\" stock=\"12\"&gt;\n &lt;name&gt;Invisibility Cream&lt;/name&gt;\n &lt;price&gt;14.50&lt;/price&gt;\n &lt;description&gt;Makes you invisible&lt;/description&gt;\n &lt;/item&gt;\n &lt;item upc=\"445322344\" stock=\"18\"&gt;\n &lt;name&gt;Levitation Salve&lt;/name&gt;\n &lt;price&gt;23.99&lt;/price&gt;\n &lt;description&gt;Levitate yourself for up to 3 hours per application&lt;/description&gt;\n &lt;/item&gt;\n &lt;/section&gt;\n &lt;section name=\"food\"&gt;\n &lt;item upc=\"485672034\" stock=\"653\"&gt;\n &lt;name&gt;Blork and Freen Instameal&lt;/name&gt;\n &lt;price&gt;4.95&lt;/price&gt;\n &lt;description&gt;A tasty meal in a tablet; just add water&lt;/description&gt;\n &lt;/item&gt;\n &lt;item upc=\"132957764\" stock=\"44\"&gt;\n &lt;name&gt;Grob winglets&lt;/name&gt;\n &lt;price&gt;3.56&lt;/price&gt;\n &lt;description&gt;Tender winglets of Grob. Just add water&lt;/description&gt;\n &lt;/item&gt;\n &lt;/section&gt;\n &lt;/inventory&gt;\n \"\"\"</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000080;font-style:italic;\">-- or, of course, xml_txt = get_text(\"input.xml\")</span>\n <span style=\"color: #000000;\">xml</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xml_parse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xml_txt</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">sections</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xml_get_nodes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">xml</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">XML_CONTENTS</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"section\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">item1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">prices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{},</span>\n <span style=\"color: #000000;\">names</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sections</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">items</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">xml_get_nodes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sections</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">s</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"item\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">item1</span><span style=\"color: #0000FF;\">={}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">item1</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">items</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">items</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">prices</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">prices</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xml_get_nodes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">items</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"price\"</span><span style=\"color: #0000FF;\">)[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">XML_CONTENTS</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #000000;\">names</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">names</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">xml_get_nodes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">items</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">],</span><span style=\"color: #008000;\">\"name\"</span><span style=\"color: #0000FF;\">)[</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">XML_CONTENTS</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"===item[1]===\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">tmp</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">xml_new_doc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">item1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">xml_sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tmp</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"===prices===\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">prices</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"===names===\\n\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">pp</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">names</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #004600;\">pp_Maxlen</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">90</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "<?php\n//PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0)\n$doc = DOMDocument::loadXML('<inventory title=\"OmniCorp Store #45x10^3\">...</inventory>');\n//Load from file instead with $doc = DOMDocument::load('filename');\n$xpath = new DOMXPath($doc);\n/*\n 1st Task: Retrieve the first \"item\" element\n*/\n$nodelist = $xpath->query('//item');\n$result = $nodelist->item(0);\n/*\n 2nd task: Perform an action on each \"price\" element (print it out)\n*/\n$nodelist = $xpath->query('//price');\nfor($i = 0; $i < $nodelist->length; $i++)\n{\n //print each price element in the DOMNodeList instance, $nodelist, as text/xml followed by a newline\n print $doc->saveXML($nodelist->item($i)).\"\\n\";\n}\n/*\n 3rd Task: Get an array of all the \"name\" elements\n*/\n$nodelist = $xpath->query('//name');\n//our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList\n$result = array();\n//a different way of iterating through the DOMNodeList\nforeach($nodelist as $node)\n{\n $result[] = $node;\n}\n", "language": "PHP" }, { "code": "(load \"@lib/xm.l\")\n\n(let Sections (body (in \"file.xml\" (xml)))\n (pretty (car (body (car Sections))))\n (prinl)\n (for S Sections\n (for L (body S)\n (prinl (car (body L 'price))) ) )\n (make\n (for S Sections\n (for L (body S)\n (link (car (body L 'name))) ) ) ) )\n", "language": "PicoLisp" }, { "code": "$document = [xml]@'\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n'@\n\n$query = \"/inventory/section/item\"\n$items = $document.SelectNodes($query)\n", "language": "PowerShell" }, { "code": "$items[0]\n", "language": "PowerShell" }, { "code": "$namesAndPrices = $items | Select-Object -Property name, price\n$namesAndPrices\n", "language": "PowerShell" }, { "code": "$items.price\n", "language": "PowerShell" }, { "code": "$items.name\n", "language": "PowerShell" }, { "code": "# Python has basic xml parsing built in\n\nfrom xml.dom import minidom\n\nxmlfile = file(\"test3.xml\") # load xml document from file\nxmldoc = minidom.parse(xmlfile).documentElement # parse from file stream or...\nxmldoc = minidom.parseString(\"<inventory title=\"OmniCorp Store #45x10^3\">...</inventory>\").documentElement # alternatively, parse a string\n\t\n# 1st Task: Retrieve the first \"item\" element\ni = xmldoc.getElementsByTagName(\"item\") # get a list of all \"item\" tags\nfirstItemElement = i[0] # get the first element\n\n# 2nd task: Perform an action on each \"price\" element (print it out)\nfor j in xmldoc.getElementsByTagName(\"price\"): # get a list of all \"price\" tags\n\tprint j.childNodes[0].data # XML Element . TextNode . data of textnode\n\n# 3rd Task: Get an array of all the \"name\" elements\nnamesArray = xmldoc.getElementsByTagName(\"name\")\n", "language": "Python" }, { "code": "import xml.etree.ElementTree as ET\n\nxml = open('inventory.xml').read()\ndoc = ET.fromstring(xml)\n\ndoc = ET.parse('inventory.xml') # or load it directly\n\n# Note, ElementTree's root is the top level element. So you need \".//\" to really start searching from top\n\n# Return first Item\nitem1 = doc.find(\"section/item\") # or \".//item\"\n\n# Print each price\nfor p in doc.findall(\"section/item/price\"): # or \".//price\"\n print \"{0:0.2f}\".format(float(p.text)) # could raise exception on missing text or invalid float() conversion\n\n# list of names\nnames = doc.findall(\"section/item/name\") # or \".//name\"\n", "language": "Python" }, { "code": "from lxml import etree\n\nxml = open('inventory.xml').read()\ndoc = etree.fromstring(xml)\n\ndoc = etree.parse('inventory.xml') # or load it directly\n\n# Return first item\nitem1 = doc.xpath(\"//section[1]/item[1]\")\n\n# Print each price\nfor p in doc.xpath(\"//price\"):\n print \"{0:0.2f}\".format(float(p.text)) # could raise exception on missing text or invalid float() conversion\n\nnames = doc.xpath(\"//name\") # list of names\n", "language": "Python" }, { "code": "library(\"XML\")\ndoc <- xmlInternalTreeParse(\"test3.xml\")\n\n# Retrieve the first \"item\" element\ngetNodeSet(doc, \"//item\")[[1]]\n\n# Perform an action on each \"price\" element\nsapply(getNodeSet(doc, \"//price\"), xmlValue)\n\n# Get an array of all the \"name\" elements\nsapply(getNodeSet(doc, \"//name\"), xmlValue)\n", "language": "R" }, { "code": "#lang at-exp racket\n\n(define input @~a{\n <inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n </inventory>})\n\n(require xml xml/path)\n\n(define data (xml->xexpr\n ((eliminate-whitespace '(inventory section item))\n (read-xml/element (open-input-string input)))))\n\n;; Retrieve the first \"item\" element\n(displayln (xexpr->string (se-path* '(item) data)))\n;; => <name>Invisibility Cream</name>\n\n;; Perform an action on each \"price\" element (print it out)\n(printf \"Prices: ~a\\n\" (string-join (se-path*/list '(item price) data) \", \"))\n;; => Prices: 14.50, 23.99, 4.95, 3.56\n\n;; Get an array of all the \"name\" elements\n(se-path*/list '(item name) data)\n;; => '(\"Invisibility Cream\" \"Levitation Salve\" \"Blork and Freen Instameal\" \"Grob winglets\")\n", "language": "Racket" }, { "code": "use XML::XPath;\n\nmy $XML = XML::XPath.new(xml => q:to/END/);\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\nEND\n\nput \"First item:\\n\", $XML.find('//item[1]')[0];\n\nput \"\\nPrice elements:\";\n.contents.put for $XML.find('//price').List;\n\nput \"\\nName elements:\\n\", $XML.find('//name')».contents.join: ', ';\n", "language": "Raku" }, { "code": "import lang::xml::DOM;\nimport Prelude;\n\npublic void get_first_item(loc a){\n\tD = parseXMLDOM(readFile(a));\n\ttop-down-break visit(D){\n\t\tcase E:element(_,\"item\",_): return println(xmlPretty(E));\n\t};\n}\n\npublic void print_prices(loc a){\n\tD = parseXMLDOM(readFile(a));\n\tfor(/element(_,\"price\",[charData(/str p)]) := D)\n\t\tprintln(p);\n}\n\npublic list[str] get_names(loc a){\n\tD = parseXMLDOM(readFile(a));\n\tL = [];\n\tfor(/element(_,\"name\",[charData(/str n)]) := D)\n\t\tL += n;\n\treturn L;\n}\n", "language": "Rascal" }, { "code": "rascal>get_first_item(|file:///Users/.../Desktop/xmlpath.xml|)\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<item stock=\"12\" upc=\"123456789\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n</item>\n\n\nok\n\nrascal>print_prices(|file:///Users/.../Desktop/xmlpath.xml|)\n14.50\n23.99\n4.95\n3.56\nok\n\nrascal>get_names(|file:///Users/.../Desktop/xmlpath.xml|)\nlist[str]: [\"Invisibility Cream\",\"Levitation Salve\",\"Blork and Freen Instameal\",\"Grob winglets\"]\n", "language": "Rascal" }, { "code": "/*REXX program to parse various queries on an XML document (from a file). */\niFID='XPATH.XML' /*name of the input XML file (doc). */\n$= /*string will contain the file's text. */\n do j=1 while lines(iFID)\\==0 /*read the entire file into a string. */\n $=$ linein(iFID) /*append the line to the $ string. */\n end /*j*/\n /* [↓] show 1st ITEM in the document*/\nparse var $ '<item ' item \"</item>\"\nsay center('first item:',length(space(item)),'─') /*display a nice header.*/\nsay space(item)\n /* [↓] show all PRICES in the document*/\nprices= /*nullify the list and add/append to it*/\n$$=$ /*start with a fresh copy of document. */\n do until $$='' /* [↓] keep parsing string until done.*/\n parse var $$ '<price>' price '</price>' $$\n prices=prices price /*add/append the price to the list. */\n end /*until*/\nsay\nsay center('prices:',length(space(prices)),'─') /*display a nice header.*/\nsay space(prices)\n /* [↓] show all NAMES in the document*/\nnames.= /*nullify the list and add/append to it*/\nL=length(' names: ') /*maximum length of any one list name. */\n$$=$ /*start with a fresh copy of document. */\n do #=1 until $$='' /* [↓] keep parsing string until done.*/\n parse var $$ '<name>' names.# '</name>' $$\n L=max(L,length(names.#)) /*L: is used to find the widest name. */\n end /*#*/\n\nnames.0=#-1; say /*adjust the number of names (DO loop).*/\nsay center('names:',L,'─') /*display a nicely formatted header. */\n do k=1 for names.0 /*display all the names in the list. */\n say names.k /*display a name from the NAMES list.*/\n end /*k*/\n /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program to parse various queries on an XML document (from a file). */\niFID='XPATH.XML' /*name of the input XML file (doc). */\n$= /*string will contain the file's text. */\n do j=1 while lines(iFID)\\==0 /*read the entire file into a string. */\n $=$ linein(iFID) /*append the line to the $ string. */\n end /*j*/\n /* [↓] display 1st ITEM in document. */\ncall parser 'item', 0 /*go and parse the all the ITEMs. */\nsay center('first item:',@L.1,'─') /*display a nicely formatted header. */\nsay @.1; say /*display the first ITEM found. */\n\ncall parser 'price' /*go and parse all the PRICEs. */\nsay center('prices:',length(@@@),'─') /*display a nicely formatted header. */\nsay @@@; say /*display a list of all the prices. */\n\ncall parser 'name'\nsay center('names:',@L,'─') /*display a nicely formatted header. */\n do k=1 for # /*display all the names in the list. */\n say @.k /*display a name from the NAMES list.*/\n end /*k*/\nexit /*stick a fork in it, we're all done. */\n/*────────────────────────────────────────────────────────────────────────────*/\nparser: parse arg yy,tail,,@. @@. @@@; $$=$; @L=9; yb='<'yy; ye='</'yy\">\"\ntail=word(tail 1, 1) /*use a tail \">\" or not?*/\n do #=1 until $$='' /*parse complete XML doc. */\n if tail then parse var $$ (yb) '>' @@.# (ye) $$ /*find meat.*/\n else parse var $$ (yb) @@.# (ye) $$ /* \" \" */\n @.#=space(@@.#); @@@=space(@@@ @.#) /*shrink; @@@=list of YY.*/\n @L.#=length(@.#); @L=max(@L,@L.#) /*length; maximum length. */\n end /*#*/\n#=#-1 /*adjust # of thing found.*/\nreturn\n", "language": "REXX" }, { "code": "#Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html)\nrequire \"rexml/document\"\ninclude REXML\n#create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string)\ndoc = Document.new(\n %q@<inventory title=\"OmniCorp Store #45x10^3\">\n ...\n </inventory>\n @\n )\n# The invisibility cream is the first <item>\ninvisibility = XPath.first( doc, \"//item\" )\n# Prints out all of the prices\nXPath.each( doc, \"//price\") { |element| puts element.text }\n# Gets an array of all of the \"name\" elements in the document.\nnames = XPath.match( doc, \"//name\" )\n", "language": "Ruby" }, { "code": "scala> val xml: scala.xml.Elem =\n | <inventory title=\"OmniCorp Store #45x10^3\">\n | <section name=\"health\">\n | <item upc=\"123456789\" stock=\"12\">\n | <name>Invisibility Cream</name>\n | <price>14.50</price>\n | <description>Makes you invisible</description>\n | </item>\n | <item upc=\"445322344\" stock=\"18\">\n | <name>Levitation Salve</name>\n | <price>23.99</price>\n | <description>Levitate yourself for up to 3 hours per application</description>\n | </item>\n | </section>\n | <section name=\"food\">\n | <item upc=\"485672034\" stock=\"653\">\n | <name>Blork and Freen Instameal</name>\n | <price>4.95</price>\n | <description>A tasty meal in a tablet; just add water</description>\n | </item>\n | <item upc=\"132957764\" stock=\"44\">\n | <name>Grob winglets</name>\n | <price>3.56</price>\n | <description>Tender winglets of Grob. Just add water</description>\n | </item>\n | </section>\n | </inventory>\n\nscala> val firstItem = xml \\\\ \"item\" take 1\nfirstItem: scala.xml.NodeSeq =\nNodeSeq(<item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>)\n\nscala> xml \\\\ \"price\" map (_.text) foreach println\n14.50\n23.99\n4.95\n3.56\n\nscala> val names = (xml \\\\ \"name\").toArray\nnames: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>)\n", "language": "Scala" }, { "code": "Set XMLSource to {{\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n}}\n\nput node \"//item[1]\" of XMLSource\nput node \"//price/text()\" of XMLSource\nput all nodes \"//name\" of XMLSource\n", "language": "SenseTalk" }, { "code": "require('XML::XPath');\n\nvar x = %s'XML::XPath'.new(ARGF.slurp);\n\n[x.findnodes('//item[1]')][0];\nsay [x.findnodes('//price')].map{x.getNodeText(_)};\n[x.findnodes('//name')];\n", "language": "Sidef" }, { "code": "# assume $xml holds the XML data\npackage require tdom\nset doc [dom parse $xml]\nset root [$doc documentElement]\n\nset allNames [$root selectNodes //name]\nputs [llength $allNames] ;# ==> 4\n\nset firstItem [lindex [$root selectNodes //item] 0]\nputs [$firstItem @upc] ;# ==> 123456789\n\nforeach node [$root selectNodes //price] {\n puts [$node text]\n}\n", "language": "Tcl" }, { "code": "$$ MODE TUSCRIPT,{}\nMODE DATA\n$$ XML=*\n<inventory title=\"OmniCorp Store #45x10³\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n$$ MODE TUSCRIPT\n\nFILE = \"test.xml\"\nERROR/STOP CREATE (file,fdf-o,-std-)\nFILE/ERASE/UTF8 $FILE = xml\n\nBUILD S_TABLE beg=\":<item*>:<name>:<price>:\"\nBUILD S_TABLE end=\":</item>:</name>:</price>:\"\nBUILD S_TABLE modifiedbeg=\":<name>:<price>:\"\nBUILD S_TABLE modifiedend=\":</name>:</price>:\"\nfirstitem=names=\"\",countitem=0\nACCESS q: READ/STREAM/UTF8 $FILE s,a/beg+t+e/end\nLOOP\nREAD/EXIT q\nIF (a==\"<name>\") names=APPEND(names,t)\nIF (a==\"<price>\") PRINT t\nIF (a.sw.\"<item\") countitem=1\nIF (countitem==1) THEN\nfirstitem=CONCAT(firstitem,a)\nfirstitem=CONCAT(firstitem,t)\nfirstitem=CONCAT(firstitem,e)\n IF (e==\"</item>\") THEN\n COUNTITEM=0\n MODIFY ACCESS q s_TABLE modifiedbeg,-,modifiedend\n ENDIF\nENDIF\nENDLOOP\nENDACCESS q\nERROR/STOP CLOSE (file)\nfirstitem=EXCHANGE (firstitem,\":{2-00} ::\")\nfirstitem=INDENT_TAGS (firstitem,-,\" \")\nnames=SPLIT(names)\nTRACE *firstitem,names\n", "language": "TUSCRIPT" }, { "code": "Set objXMLDoc = CreateObject(\"msxml2.domdocument\")\n\nobjXMLDoc.load(\"In.xml\")\n\nSet item_nodes = objXMLDoc.selectNodes(\"//item\")\ni = 1\nFor Each item In item_nodes\n\tIf i = 1 Then\n\t\tWScript.StdOut.Write item.xml\n\t\tWScript.StdOut.WriteBlankLines(2)\n\t\tExit For\n\tEnd If\nNext\n\nSet price_nodes = objXMLDoc.selectNodes(\"//price\")\nlist_price = \"\"\nFor Each price In price_nodes\n\tlist_price = list_price & price.text & \", \"\nNext\nWScript.StdOut.Write list_price\nWScript.StdOut.WriteBlankLines(2)\n\nSet name_nodes = objXMLDoc.selectNodes(\"//name\")\nlist_name = \"\"\nFor Each name In name_nodes\n\tlist_name = list_name & name.text & \", \"\nNext\nWScript.StdOut.Write list_name\nWScript.StdOut.WriteBlankLines(2)\n", "language": "VBScript" }, { "code": "Dim first_item = xml.XPathSelectElement(\"//item\")\nConsole.WriteLine(first_item)\n\nFor Each price In xml.XPathSelectElements(\"//price\")\n Console.WriteLine(price.Value)\nNext\n\nDim names = (From item In xml.XPathSelectElements(\"//name\") Select item.Value).ToArray\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./pattern\" for Pattern\n\nvar doc = \"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\"\"\"\n\nvar p1 = Pattern.new(\"<item \")\nvar match1 = p1.find(doc)\nvar p2 = Pattern.new(\"<//item>\")\nvar match2 = p2.find(doc)\nSystem.print(\"The first 'item' element is:\")\nSystem.print(\" \" + doc[match1.index..match2.index + 6])\n\nvar p3 = Pattern.new(\"<price>[+1^<]<//price>\")\nvar matches = p3.findAll(doc)\nSystem.print(\"\\nThe 'prices' are:\")\nfor (m in matches) System.print(m.captures[0].text)\n\nvar p4 = Pattern.new(\"<name>[+1^<]<//name>\")\nvar matches2 = p4.findAll(doc)\nvar names = matches2.map { |m| m.captures[0].text }.toList\nSystem.print(\"\\nThe 'names' are:\")\nSystem.print(names.join(\"\\n\"))\n", "language": "Wren" }, { "code": "import \"./xsequence\" for XDocument\n\nvar xml = \"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\n\"\"\"\n\nvar doc = XDocument.parse(xml)\nSystem.print(\"The first 'item' element is:\")\nSystem.print(doc.root.element(\"section\").element(\"item\"))\n\nvar prices = []\nvar names = []\nfor (el in doc.root.elements) {\n for (el2 in el.elements) {\n prices.add(el2.element(\"price\").value)\n names.add(el2.element(\"name\").value)\n }\n}\nSystem.print(\"\\nThe 'prices' are:\\n%(prices.join(\"\\n\"))\")\nSystem.print(\"\\nThe 'names' are:\\n%(names.join(\"\\n\"))\")\n", "language": "Wren" }, { "code": "include xpllib; \\for StrFind\n\nchar XML(1000000), P, P1, P2, Addr;\nint I, Ch;\n[I:= 0;\nloop [Ch:= ChIn(1);\n XML(I):= Ch;\n if Ch = $1A \\EOF\\ then quit;\n I:= I+1;\n ];\nXML(I):= 0;\n\nP1:= StrFind(XML, \"<item \");\nP2:= StrFind(XML, \"</item>\");\nText(0, \"The first 'item' element is:^m^j\");\nfor P:= P1 to P2+6 do ChOut(0, P(0));\nCrLf(0);\n\nText(0, \"^m^jThe 'prices' are:^m^j\");\nAddr:= XML;\nloop [P1:= StrFind(Addr, \"<price>\");\n if P1 = 0 then quit;\n P2:= StrFind(Addr, \"</price>\");\n if P2 = 0 then quit;\n for P:= P1+7 to P2-1 do ChOut(0, P(0));\n CrLf(0);\n Addr:= P2+1;\n ];\nText(0, \"^m^jThe 'names' are:^m^j\");\nAddr:= XML;\nloop [P1:= StrFind(Addr, \"<name>\");\n if P1 = 0 then quit;\n P2:= StrFind(Addr, \"</name>\");\n if P2 = 0 then quit;\n for P:= P1+6 to P2-1 do ChOut(0, P(0));\n CrLf(0);\n Addr:= P2+1;\n ];\n]\n", "language": "XPL0" }, { "code": "<p:pipeline xmlns:p=\"http://www.w3.org/ns/xproc\"\n name=\"one-two-three\"\n version=\"1.0\">\n <p:identity>\n <p:input port=\"source\">\n <p:inline>\n <root>\n <first/>\n <prices/>\n <names/>\n </root>\n </p:inline>\n </p:input>\n </p:identity>\n <p:insert match=\"/root/first\" position=\"first-child\">\n <p:input port=\"insertion\" select=\"(//item)[1]\">\n <p:pipe port=\"source\" step=\"one-two-three\"/>\n </p:input>\n </p:insert>\n <p:insert match=\"/root/prices\" position=\"first-child\">\n <p:input port=\"insertion\" select=\"//price\">\n <p:pipe port=\"source\" step=\"one-two-three\"/>\n </p:input>\n </p:insert>\n <p:insert match=\"/root/names\" position=\"first-child\">\n <p:input port=\"insertion\" select=\"//name\">\n <p:pipe port=\"source\" step=\"one-two-three\"/>\n </p:input>\n </p:insert>\n</p:pipeline>\n", "language": "XProc" }, { "code": "(:\n 1. Retrieve the first \"item\" element\n Notice the braces around //item. This evaluates first all item elements and then retrieving the first one.\n Whithout the braces you get the first item for every section.\n:)\nlet $firstItem := (//item)[1]\n\n(: 2. Perform an action on each \"price\" element (print it out) :)\nlet $price := //price/data(.)\n\n(: 3. Get an array of all the \"name\" elements :)\nlet $names := //name\n\nreturn\n <result>\n <firstItem>{$firstItem}</firstItem>\n <prices>{$price}</prices>\n <names>{$names}</names>\n </result>\n", "language": "XQuery" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<result>\n <firstItem>\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n </firstItem>\n <prices>14.50 23.99 4.95 3.56</prices>\n <names>\n <name>Invisibility Cream</name>\n <name>Levitation Salve</name>\n <name>Blork and Freen Instameal</name>\n <name>Grob winglets</name>\n </names>\n</result>\n", "language": "XQuery" }, { "code": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\" />\n <xsl:template match=\"/\">\n\n <!-- 1. first item element -->\n <xsl:text>\nThe first item element is</xsl:text>\n <xsl:value-of select=\"//item[1]\" />\n\n <!-- 2. Print each price element -->\n <xsl:text>\nThe prices are: </xsl:text>\n <xsl:for-each select=\"//price\">\n <xsl:text>\n </xsl:text>\n <xsl:copy-of select=\".\" />\n </xsl:for-each>\n\n <!-- 3. Collect all the name elements -->\n <xsl:text>\nThe names are: </xsl:text>\n <xsl:copy-of select=\"//name\" />\n </xsl:template>\n</xsl:stylesheet>\n", "language": "XSLT" } ]
XML-XPath
[ { "code": "---\ncategory:\n- Networking and Web Interaction\nfrom: http://rosettacode.org/wiki/Yahoo!_search_interface\nnote: Programming environment operations\n", "language": "00-META" }, { "code": "Create a class for searching Yahoo! results.\n\nIt must implement a '''Next Page''' method, and read URL, Title and Content from results.\n<br><br>\n", "language": "00-TASK" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program yahoosearch64.s */\n\n/* access RosettaCode.org and data extract */\n/* use openssl for access to port 443 */\n/* test openssl : package libssl-dev */\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ TAILLEBUFFER, 500\n\n.equ SSL_OP_NO_SSLv3, 0x02000000\n.equ SSL_OP_NO_COMPRESSION, 0x00020000\n.equ SSL_MODE_AUTO_RETRY, 0x00000004\n.equ SSL_CTRL_MODE, 33\n\n.equ BIO_C_SET_CONNECT, 100\n.equ BIO_C_DO_STATE_MACHINE, 101\n.equ BIO_C_SET_SSL, 109\n.equ BIO_C_GET_SSL, 110\n\n.equ LGBUFFERREQ, 512001\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessDebutPgm: .asciz \"Début du programme. \\n\"\nszRetourLigne: .asciz \"\\n\"\nszMessFinOK: .asciz \"Fin normale du programme. \\n\"\nszMessErreur: .asciz \"Erreur !!!\"\nszMessExtractArea: .asciz \"Extraction = \"\nszNomSite1: .asciz \"search.yahoo.com:443\" // host name and port\nszLibStart: .asciz \">Rosetta Code\" // search string\nszNomrepCertif: .asciz \"/pi/certificats\"\nszRequete1: .asciz \"GET /search?p=\\\"Rosettacode.org\\\"&b=1 HTTP/1.1 \\r\\nHost: search.yahoo.com\\r\\nConnection: keep-alive\\r\\nContent-Type: text/plain\\r\\n\\r\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nsBufferreq: .skip LGBUFFERREQ\nszExtractArea: .skip TAILLEBUFFER\nstNewSSL: .skip 200\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain:\n ldr x0,qAdrszMessDebutPgm\n bl affichageMess // start message\n\n /* connexion host port 443 and send query */\n bl envoiRequete\n cmp x0,#-1\n beq 99f // error ?\n\n bl analyseReponse\n\n ldr x0,qAdrszMessFinOK // end message\n bl affichageMess\n mov x0, #0 // return code ok\n b 100f\n99:\n ldr x0,qAdrszMessErreur // error\n bl affichageMess\n mov x0, #1 // return code error\n b 100f\n100:\n mov x8,EXIT // program end\n svc 0 // system call\nqAdrszMessDebutPgm: .quad szMessDebutPgm\nqAdrszMessFinOK: .quad szMessFinOK\nqAdrszMessErreur: .quad szMessErreur\n\n/*********************************************************/\n/* connexion host port 443 and send query */\n/*********************************************************/\nenvoiRequete:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n //*************************************\n // openSsl functions use *\n //*************************************\n //init ssl\n bl OPENSSL_init_crypto\n bl ERR_load_BIO_strings\n mov x2, #0\n mov x1, #0\n mov x0, #2\n bl OPENSSL_init_crypto\n mov x2, #0\n mov x1, #0\n mov x0, #0\n bl OPENSSL_init_ssl\n cmp x0,#0\n blt erreur\n bl TLS_client_method\n bl SSL_CTX_new\n cmp x0,#0\n ble erreur\n mov x20,x0 // save contex\n ldr x1,iFlag\n bl SSL_CTX_set_options\n mov x0,x20 // contex\n mov x1,#0\n ldr x2,qAdrszNomrepCertif\n bl SSL_CTX_load_verify_locations\n cmp x0,#0\n ble erreur\n mov x0,x20 // contex\n bl BIO_new_ssl_connect\n cmp x0,#0\n ble erreur\n mov x21,x0 // save bio\n mov x1,#BIO_C_GET_SSL\n mov x2,#0\n ldr x3,qAdrstNewSSL\n bl BIO_ctrl\n ldr x0,qAdrstNewSSL\n ldr x0,[x0]\n mov x1,#SSL_CTRL_MODE\n mov x2,#SSL_MODE_AUTO_RETRY\n mov x3,#0\n bl SSL_ctrl\n mov x0,x21 // bio\n mov x1,#BIO_C_SET_CONNECT\n mov x2,#0\n ldr x3,qAdrszNomSite1\n bl BIO_ctrl\n mov x0,x21 // bio\n mov x1,#BIO_C_DO_STATE_MACHINE\n mov x2,#0\n mov x3,#0\n bl BIO_ctrl\n // compute query length\n mov x2,#0\n ldr x1,qAdrszRequete1 // query\n1:\n ldrb w0,[x1,x2]\n cmp x0,#0\n add x8,x2,1\n csel x2,x8,x2,ne\n bne 1b\n // send query\n mov x0,x21 // bio\n // x1 = address query\n // x2 = length query\n mov x3,#0\n bl BIO_write // send query\n cmp x0,#0\n blt erreur\n ldr x22,qAdrsBufferreq // buffer address\n2: // begin loop to read datas\n mov x0,x21 // bio\n mov x1,x22 // buffer address\n ldr x2,qLgBuffer\n mov x3,#0\n bl BIO_read\n cmp x0,#0\n ble 4f // error ou pb server\n add x22,x22,x0\n sub x2,x22,#8\n ldr x2,[x2]\n ldr x3,qCharEnd\n cmp x2,x3 // text end ?\n beq 4f\n mov x1,#0xFFFFFF // delay loop\n3:\n subs x1,x1,1\n bgt 3b\n b 2b // loop read other chunk\n4: // read end\n //ldr x0,qAdrsBufferreq // to display buffer response of the query\n //bl affichageMess\n mov x0, x21 // close bio\n bl BIO_free_all\n mov x0,#0\n b 100f\nerreur: // error display\n ldr x1,qAdrszMessErreur\n bl afficheErreur\n mov x0,#-1 // error code\n b 100f\n100:\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszRequete1: .quad szRequete1\nqAdrsBufferreq: .quad sBufferreq\niFlag: .quad SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION\nqAdrstNewSSL: .quad stNewSSL\nqAdrszNomSite1: .quad szNomSite1\nqAdrszNomrepCertif: .quad szNomrepCertif\nqCharEnd: .quad 0x0A0D0A0D300A0D0A\nqLgBuffer: .quad LGBUFFERREQ - 1\n/*********************************************************/\n/* response analyze */\n/*********************************************************/\nanalyseReponse:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n ldr x0,qAdrsBufferreq // buffer address\n ldr x1,qAdrszLibStart // key text address\n mov x2,#2 // occurence key text\n mov x3,#-11 // offset\n ldr x4,qAdrszExtractArea // address result area\n bl extChaine\n cmp x0,#-1\n beq 99f\n ldr x0,qAdrszMessExtractArea\n bl affichageMess\n ldr x0,qAdrszExtractArea // résult display\n bl affichageMess\n ldr x0,qAdrszRetourLigne\n bl affichageMess\n b 100f\n99:\n ldr x0,qAdrszMessErreur // error\n bl affichageMess\n mov x0, #-1 // error return code\n b 100f\n100:\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrszLibStart: .quad szLibStart\nqAdrszExtractArea: .quad szExtractArea\nqAdrszMessExtractArea: .quad szMessExtractArea\nqAdrszRetourLigne: .quad szRetourLigne\n/*********************************************************/\n/* Text Extraction behind text key */\n/*********************************************************/\n/* x0 buffer address */\n/* x1 key text to search */\n/* x2 number occurences to key text */\n/* x3 offset */\n/* x4 result address */\nextChaine:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n mov x5,x0 // save buffer address\n mov x6,x1 // save key text\n // compute text length\n mov x8,#0\n1: // loop\n ldrb w0,[x5,x8] // load a byte\n cmp x0,#0 // end ?\n add x9,x8,1\n csel x8,x9,x8,ne\n bne 1b // no -> loop\n add x8,x8,x5 // compute text end\n\n mov x7,#0\n2: // compute length text key\n ldrb w0,[x6,x7]\n cmp x0,#0\n add x9,x7,1\n csel x7,x9,x7,ne\n bne 2b\n\n3: // loop to search niéme(x2) key text\n mov x0,x5\n mov x1,x6\n bl rechercheSousChaine\n cmp x0,#0\n blt 100f\n subs x2,x2,1\n ble 31f\n add x5,x5,x0\n add x5,x5,x7\n b 3b\n31:\n add x0,x0,x5 // add address text to index\n add x3,x3,x0 // add offset\n sub x3,x3,1\n // and add length key text\n add x3,x3,x7\n cmp x3,x8 // > at text end\n bge 98f\n mov x0,0\n4: // character loop copy\n ldrb w2,[x3,x0]\n strb w2,[x4,x0]\n cbz x2,99f // text end ? return zero\n cmp x0,48 // extraction length\n beq 5f\n add x0,x0,1\n b 4b // and loop\n5:\n mov x2,0 // store final zéro\n strb w2,[x4,x0]\n add x0,x0,1\n add x0,x0,x3 // x0 return the last position of extraction\n // it is possible o search another text\n b 100f\n98:\n mov x0,-1 // error\n b 100f\n99:\n mov x0,0\n100:\n ldp x6,x7,[sp],16 // restaur 2 registers\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/******************************************************************/\n/* search substring in string */\n/******************************************************************/\n/* x0 contains address string */\n/* x1 contains address substring */\n/* x0 return start index substring or -1 if not find */\nrechercheSousChaine:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n mov x2,#0 // index position string\n mov x3,#0 // index position substring\n mov x6,#-1 // search index\n ldrb w4,[x1,x3] // load first byte substring\n cbz x4,99f // zero final ? error\n1:\n ldrb w5,[x0,x2] // load string byte\n cbz x5,99f // zero final ? yes -> not found\n cmp x5,x4 // compare character two strings\n beq 2f\n mov x6,-1 // not equal - > raz index\n mov x3,0 // and raz byte counter\n ldrb w4,[x1,x3] // and load byte\n add x2,x2,1 // and increment byte counter\n b 1b // and loop\n2: // characters equal\n cmp x6,-1 // first character equal ?\n csel x6,x2,x6,eq // yes -> start index in x6\n add x3,x3,1 // increment substring counter\n ldrb w4,[x1,x3] // and load next byte\n cbz x4,3f // zero final ? yes -> search end\n add x2,x2,1 // else increment string index\n b 1b // and loop\n3:\n mov x0,x6 // return start index substring in the string\n b 100f\n99:\n mov x0,-1 // not found\n100:\n ldp x6,x7,[sp],16 // restaur 2 registers\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "/* ARM assembly Raspberry PI */\n/* program yahoosearch.s */\n/* access RosettaCode.org and data extract */\n/* use openssl for access to port 443 */\n/* test openssl : package libssl-dev */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n\n/*******************************************/\n/* Constantes */\n/*******************************************/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ EXIT, 1\n.equ TAILLEBUFFER, 500\n\n.equ SSL_OP_NO_SSLv3, 0x02000000\n.equ SSL_OP_NO_COMPRESSION, 0x00020000\n.equ SSL_MODE_AUTO_RETRY, 0x00000004\n.equ SSL_CTRL_MODE, 33\n\n.equ BIO_C_SET_CONNECT, 100\n.equ BIO_C_DO_STATE_MACHINE, 101\n.equ BIO_C_SET_SSL, 109\n.equ BIO_C_GET_SSL, 110\n\n.equ LGBUFFERREQ, 512001\n.equ LGBUFFER2, 128001\n\n/*********************************/\n/* Initialized data */\n/*********************************/\n.data\nszMessDebutPgm: .asciz \"Début du programme. \\n\"\nszRetourLigne: .asciz \"\\n\"\nszMessFinOK: .asciz \"Fin normale du programme. \\n\"\nszMessErreur: .asciz \"Erreur !!!\"\nszMessExtractArea: .asciz \"Extraction = \"\nszNomSite1: .asciz \"search.yahoo.com:443\" @ host name and port\nszLibStart: .asciz \">Rosetta Code\" @ search string\nszNomrepCertif: .asciz \"/pi/certificats\"\nszRequete1: .asciz \"GET /search?p=\\\"Rosettacode.org\\\"&b=1 HTTP/1.1 \\r\\nHost: search.yahoo.com\\r\\nConnection: keep-alive\\r\\nContent-Type: text/plain\\r\\n\\r\\n\"\n/*********************************/\n/* UnInitialized data */\n/*********************************/\n.bss\n.align 4\nsBufferreq: .skip LGBUFFERREQ\nszExtractArea: .skip TAILLEBUFFER\nstNewSSL: .skip 200\n/*********************************/\n/* code section */\n/*********************************/\n.text\n.global main\nmain:\n ldr r0,iAdrszMessDebutPgm\n bl affichageMess @ start message\n\n /* connexion host port 443 and send query */\n bl envoiRequete\n cmp r0,#-1\n beq 99f @ error ?\n\n bl analyseReponse\n\n ldr r0,iAdrszMessFinOK @ end message\n bl affichageMess\n mov r0, #0 @ return code ok\n b 100f\n99:\n ldr r0,iAdrszMessErreur @ error\n bl affichageMess\n mov r0, #1 @ return code error\n b 100f\n100:\n mov r7,#EXIT @ program end\n svc #0 @ system call\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessFinOK: .int szMessFinOK\niAdrszMessErreur: .int szMessErreur\n\n/*********************************************************/\n/* connexion host port 443 and send query */\n/*********************************************************/\nenvoiRequete:\n push {r2-r8,lr} @ save registers\n @*************************************\n @ openSsl functions use *\n @*************************************\n @init ssl\n bl OPENSSL_init_crypto\n bl ERR_load_BIO_strings\n mov r2, #0\n mov r1, #0\n mov r0, #2\n bl OPENSSL_init_crypto\n mov r2, #0\n mov r1, #0\n mov r0, #0\n bl OPENSSL_init_ssl\n cmp r0,#0\n blt erreur\n bl TLS_client_method\n bl SSL_CTX_new\n cmp r0,#0\n ble erreur\n mov r6,r0 @ save ctx\n ldr r1,iFlag\n bl SSL_CTX_set_options\n mov r0,r6\n mov r1,#0\n ldr r2,iAdrszNomrepCertif\n bl SSL_CTX_load_verify_locations\n cmp r0,#0\n ble erreur\n mov r0,r6\n bl BIO_new_ssl_connect\n cmp r0,#0\n ble erreur\n mov r5,r0 @ save bio\n mov r1,#BIO_C_GET_SSL\n mov r2,#0\n ldr r3,iAdrstNewSSL\n bl BIO_ctrl\n ldr r0,iAdrstNewSSL\n ldr r0,[r0]\n mov r1,#SSL_CTRL_MODE\n mov r2,#SSL_MODE_AUTO_RETRY\n mov r3,#0\n bl SSL_ctrl\n mov r0,r5 @ bio\n mov r1,#BIO_C_SET_CONNECT\n mov r2,#0\n ldr r3,iAdrszNomSite1\n bl BIO_ctrl\n mov r0,r5 @ bio\n mov r1,#BIO_C_DO_STATE_MACHINE\n mov r2,#0\n mov r3,#0\n bl BIO_ctrl\n @ compute query length\n mov r2,#0\n ldr r1,iAdrszRequete1 @ query\n1:\n ldrb r0,[r1,r2]\n cmp r0,#0\n addne r2,#1\n bne 1b\n @ send query\n mov r0,r5 @ bio\n @ r1 = address query\n @ r2 = length query\n mov r3,#0\n bl BIO_write @ send query\n cmp r0,#0\n blt erreur\n ldr r7,iAdrsBufferreq @ buffer address\n2: @ begin loop to read datas\n mov r0,r5 @ bio\n mov r1,r7 @ buffer address\n mov r2,#LGBUFFERREQ - 1\n mov r3,#0\n bl BIO_read\n cmp r0,#0\n ble 4f @ error ou pb server\n add r7,r0\n sub r2,r7,#6\n ldr r2,[r2]\n ldr r3,iCharEnd\n cmp r2,r3 @ text end ?\n beq 4f\n mov r1,#0xFFFFFF @ delay loop\n3:\n subs r1,#1\n bgt 3b\n b 2b @ loop read other chunk\n4: @ read end\n //ldr r0,iAdrsBufferreq @ to display buffer response of the query\n //bl affichageMess\n mov r0, r5 @ close bio\n bl BIO_free_all\n mov r0,#0\n b 100f\nerreur: @ error display\n ldr r1,iAdrszMessErreur\n bl afficheerreur\n mov r0,#-1 @ error code\n b 100f\n100:\n pop {r2-r8,lr} @ restaur registers\n bx lr\niAdrszRequete1: .int szRequete1\niAdrsBufferreq: .int sBufferreq\niFlag: .int SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION\niAdrstNewSSL: .int stNewSSL\niAdrszNomSite1: .int szNomSite1\niAdrszNomrepCertif: .int szNomrepCertif\niCharEnd: .int 0x0A0D300A\n/*********************************************************/\n/* response analyze */\n/*********************************************************/\nanalyseReponse:\n push {r1-r4,lr} @ save registers\n ldr r0,iAdrsBufferreq @ buffer address\n ldr r1,iAdrszLibStart @ key text address\n mov r2,#2 @ occurence key text\n mov r3,#-11 @ offset\n ldr r4,iAdrszExtractArea @ address result area\n bl extChaine\n cmp r0,#-1\n beq 99f\n ldr r0,iAdrszMessExtractArea\n bl affichageMess\n ldr r0,iAdrszExtractArea @ résult display\n bl affichageMess\n ldr r0,iAdrszRetourLigne\n bl affichageMess\n b 100f\n99:\n ldr r0,iAdrszMessErreur @ error\n bl affichageMess\n mov r0, #-1 @ error return code\n b 100f\n100:\n pop {r1-r4,lr} @ restaur registers\n bx lr\niAdrszLibStart: .int szLibStart\niAdrszExtractArea: .int szExtractArea\niAdrszMessExtractArea: .int szMessExtractArea\niAdrszRetourLigne: .int szRetourLigne\n/*********************************************************/\n/* Text Extraction behind text key */\n/*********************************************************/\n/* r0 buffer address */\n/* r1 key text to search */\n/* r2 number occurences to key text */\n/* r3 offset */\n/* r4 result address */\nextChaine:\n push {r2-r8,lr} @ save registers\n mov r5,r0 @ save buffer address\n mov r6,r1 @ save key text\n @ compute text length\n mov r7,#0\n1: @ loop\n ldrb r0,[r5,r7] @ load a byte\n cmp r0,#0 @ end ?\n addne r7,#1 @ no -> loop\n bne 1b\n add r7,r5 @ compute text end\n\n mov r8,#0\n2: @ compute length text key\n ldrb r0,[r6,r8]\n cmp r0,#0\n addne r8,#1\n bne 2b\n\n3: @ loop to search nième(r2) key text\n mov r0,r5\n mov r1,r6\n bl rechercheSousChaine\n cmp r0,#0\n blt 100f\n subs r2,#1\n addgt r5,r0\n addgt r5,r8\n bgt 3b\n add r0,r5 @ add address text to index\n add r3,r0 @ add offset\n sub r3,#1\n @ and add length key text\n add r3,r8\n cmp r3,r7 @ > at text end\n movge r0,#-1 @ yes -> error\n bge 100f\n mov r0,#0\n4: @ character loop copy\n ldrb r2,[r3,r0]\n strb r2,[r4,r0]\n cmp r2,#0 @ text end ?\n moveq r0,#0 @ return zero\n beq 100f\n cmp r0,#48 @ extraction length\n beq 5f\n add r0,#1\n b 4b @ and loop\n5:\n mov r2,#0 @ store final zéro\n strb r2,[r4,r0]\n add r0,#1\n add r0,r3 @ r0 return the last position of extraction\n @ it is possible o search another text\n100:\n \tpop {r2-r8,lr} @ restaur registers\n bx lr\n\n/******************************************************************/\n/* search substring in string */\n/******************************************************************/\n/* r0 contains address string */\n/* r1 contains address substring */\n/* r0 return start index substring or -1 if not find */\nrechercheSousChaine:\n push {r1-r6,lr} @ save registers\n mov r2,#0 @ index position string\n mov r3,#0 @ index position substring\n mov r6,#-1 @ search index\n ldrb r4,[r1,r3] @ load first byte substring\n cmp r4,#0 @ zero final ?\n moveq r0,#-1 @ error\n beq 100f\n1:\n ldrb r5,[r0,r2] @ load string byte\n cmp r5,#0 @ zero final ?\n moveq r0,#-1 @ yes -> not find\n beq 100f\n cmp r5,r4 @ compare character two strings\n beq 2f\n mov r6,#-1 @ not equal - > raz index\n mov r3,#0 @ and raz byte counter\n ldrb r4,[r1,r3] @ and load byte\n add r2,#1 @ and increment byte counter\n b 1b @ and loop\n2: @ characters equal\n cmp r6,#-1 @ first character equal ?\n moveq r6,r2 @ yes -> start index in r6\n add r3,#1 @ increment substring counter\n ldrb r4,[r1,r3] @ and load next byte\n cmp r4,#0 @ zero final ?\n beq 3f @ yes -> search end\n add r2,#1 @ else increment string index\n b 1b @ and loop\n3:\n mov r0,r6 @ return start index substring in the string\n100:\n pop {r1-r6,lr} @ restaur registres\n bx lr\n\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "test:\nyahooSearch(\"test\", 1)\nyahooSearch(\"test\", 2)\nreturn\n\nyahooSearch(query, page)\n{\n global\n start := ((page - 1) * 10) + 1\n filedelete, search.txt\n urldownloadtofile, % \"http://search.yahoo.com/search?p=\" . query\n . \"&b=\" . start, search.txt\n fileread, content, search.txt\n reg = <a class=\"yschttl spt\" href=\".+?\" >(.+?)</a></h3></div><div class=\"abstr\">(.+?)</div><span class=url>(.+?)</span>\n\n index := found := 1\n while (found := regexmatch(content, reg, self, found + 1))\n {\n msgbox % title%A_Index% := fix(self1)\n content%A_Index% := fix(self2)\n url%A_Index% := fix(self3)\n }\n}\n\nfix(url)\n{\nif pos := instr(url, \"</a></h3></div>\")\nStringLeft, url, url, pos - 1\nurl := regexreplace(url, \"<.*?>\")\nreturn url\n}\n", "language": "AutoHotkey" }, { "code": "using System;\nusing System.Net;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nclass YahooSearch {\n private string query;\n private string content;\n private int page;\n\n const string yahoo = \"http://search.yahoo.com/search?\";\n\n public YahooSearch(string query) : this(query, 0) { }\n\n public YahooSearch(string query, int page) {\n this.query = query;\n this.page = page;\n this.content = new WebClient()\n .DownloadString(\n string.Format(yahoo + \"p={0}&b={1}\", query, this.page * 10 + 1)\n );\n }\n\n public YahooResult[] Results {\n get {\n List<YahooResult> results = new List<YahooResult>();\n\n Func<string, string, string> substringBefore = (str, before) =>\n {\n int iHref = str.IndexOf(before);\n return iHref < 0 ? \"\" : str.Substring(0, iHref);\n };\n Func<string, string, string> substringAfter = (str, after) =>\n {\n int iHref = str.IndexOf(after);\n return iHref < 0 ? \"\" : str.Substring(iHref + after.Length);\n };\n Converter<string, string> getText = p =>\n Regex.Replace(p, \"<[^>]*>\", x => \"\");\n\n Regex rx = new Regex(@\"\n <li>\n <div \\s class=\"\"res\"\">\n <div>\n <h3>\n <a \\s (?'LinkAttributes'[^>]+)>\n (?'LinkText' .*?)\n (?></a>)\n </h3>\n </div>\n <div \\s class=\"\"abstr\"\">\n (?'Abstract' .*?)\n (?></div>)\n .*?\n (?></div>)\n </li>\",\n RegexOptions.IgnorePatternWhitespace\n | RegexOptions.ExplicitCapture\n );\n foreach (Match e in rx.Matches(this.content)) {\n string rurl = getText(substringBefore(substringAfter(\n e.Groups[\"LinkAttributes\"].Value, @\"href=\"\"\"), @\"\"\"\"));\n string rtitle = getText(e.Groups[\"LinkText\"].Value);\n string rcontent = getText(e.Groups[\"Abstract\"].Value);\n\n results.Add(new YahooResult(rurl, rtitle, rcontent));\n }\n return results.ToArray();\n }\n }\n\n public YahooSearch NextPage() {\n return new YahooSearch(this.query, this.page + 1);\n }\n\n public YahooSearch GetPage(int page) {\n return new YahooSearch(this.query, page);\n }\n}\n\nclass YahooResult {\n public string URL { get; set; }\n public string Title { get; set; }\n public string Content { get; set; }\n\n public YahooResult(string url, string title, string content) {\n this.URL = url;\n this.Title = title;\n this.Content = content;\n }\n\n public override string ToString()\n {\n return string.Format(\"\\nTitle: {0}\\nLink: {1}\\nText: {2}\",\n Title, URL, Content);\n }\n}\n\n// Usage:\n\nclass Prog {\n static void Main() {\n foreach (int page in new[] { 0, 1 })\n {\n YahooSearch x = new YahooSearch(\"test\", page);\n\n foreach (YahooResult result in x.Results)\n {\n Console.WriteLine(result);\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.stdio, std.exception, std.regex, std.algorithm, std.string,\n std.net.curl;\n\nstruct YahooResult {\n string url, title, content;\n\n string toString() const {\n return \"\\nTitle: %s\\nLink: %s\\nText: %s\"\n .format(title, url, content);\n }\n}\n\nstruct YahooSearch {\n private string query, content;\n private uint page;\n\n this(in string query_, in uint page_ = 0) {\n this.query = query_;\n this.page = page_;\n this.content = \"http://search.yahoo.com/search?p=%s&b=%d\"\n .format(query, page * 10 + 1).get.assumeUnique;\n }\n\n @property results() const {\n immutable re = `<li>\n <div \\s class=\"res\">\n <div>\n <h3>\n <a \\s (?P<linkAttributes> [^>]+)>\n (?P<linkText> .*?)\n </a>\n </h3>\n </div>\n <div \\s class=\"abstr\">\n (?P<abstract> .*?)\n </div>\n .*?\n </div>\n </li>`;\n\n const clean = (string s) => s.replace(\"<[^>]*>\".regex(\"g\"),\"\");\n\n return content.match(re.regex(\"gx\")).map!(m => YahooResult(\n clean(m.captures[\"linkAttributes\"]\n .findSplitAfter(`href=\"`)[1]\n .findSplitBefore(`\"`)[0]),\n clean(m.captures[\"linkText\"]),\n clean(m.captures[\"abstract\"])\n ));\n }\n\n YahooSearch nextPage() const {\n return YahooSearch(query, page + 1);\n }\n}\n\nvoid main() {\n writefln(\"%(%s\\n%)\", \"test\".YahooSearch.results);\n}\n", "language": "D" }, { "code": "Public Sub Form_Open()\nDim hWebView As WebView\n\nMe.Arrangement = Arrange.Fill\nMe.Maximized = True\nMe.Title = \"Yahoo! search interface\"\n\nhWebView = New WebView(Me)\nhWebView.Expand = True\nhWebView.URL = \"https://www.yahoo.com\"\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"golang.org/x/net/html\"\n \"io/ioutil\"\n \"net/http\"\n \"regexp\"\n \"strings\"\n)\n\nvar (\n expr = `<h3 class=\"title\"><a class=.*?href=\"(.*?)\".*?>(.*?)</a></h3>` +\n `.*?<div class=\"compText aAbs\" ><p class=.*?>(.*?)</p></div>`\n rx = regexp.MustCompile(expr)\n)\n\ntype YahooResult struct {\n title, url, content string\n}\n\nfunc (yr YahooResult) String() string {\n return fmt.Sprintf(\"Title : %s\\nUrl : %s\\nContent: %s\\n\", yr.title, yr.url, yr.content)\n}\n\ntype YahooSearch struct {\n query string\n page int\n}\n\nfunc (ys YahooSearch) results() []YahooResult {\n search := fmt.Sprintf(\"http://search.yahoo.com/search?p=%s&b=%d\", ys.query, ys.page*10+1)\n resp, _ := http.Get(search)\n body, _ := ioutil.ReadAll(resp.Body)\n s := string(body)\n defer resp.Body.Close()\n var results []YahooResult\n for _, f := range rx.FindAllStringSubmatch(s, -1) {\n yr := YahooResult{}\n yr.title = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[2], \"<b>\", \"\"), \"</b>\", \"\"))\n yr.url = f[1]\n yr.content = html.UnescapeString(strings.ReplaceAll(strings.ReplaceAll(f[3], \"<b>\", \"\"), \"</b>\", \"\"))\n results = append(results, yr)\n }\n return results\n}\n\nfunc (ys YahooSearch) nextPage() YahooSearch {\n return YahooSearch{ys.query, ys.page + 1}\n}\n\nfunc main() {\n ys := YahooSearch{\"rosettacode\", 0}\n // Limit output to first 5 entries, say, from pages 1 and 2.\n fmt.Println(\"PAGE 1 =>\\n\")\n for _, res := range ys.results()[0:5] {\n fmt.Println(res)\n }\n fmt.Println(\"PAGE 2 =>\\n\")\n for _, res := range ys.nextPage().results()[0:5] {\n fmt.Println(res)\n }\n}\n", "language": "Go" }, { "code": "Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk,\nButton:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search\n", "language": "GUISS" }, { "code": "import Network.HTTP\nimport Text.Parsec\n\ndata YahooSearchItem = YahooSearchItem {\n itemUrl, itemTitle, itemContent :: String }\n\ndata YahooSearch = YahooSearch {\n searchQuery :: String,\n searchPage :: Int,\n searchItems :: [YahooSearchItem] }\n\n-- URL for Yahoo! searches, without giving a page number\nyahooUrl = \"http://search.yahoo.com/search?p=\"\n\n-- make an HTTP request and return a YahooSearch\nyahoo :: String -> IO YahooSearch\nyahoo q = simpleHTTP (getRequest $ yahooUrl ++ q) >>=\n getResponseBody >>= return . YahooSearch q 1 . items\n\n-- get some results and return the next page of results\nnext :: YahooSearch -> IO YahooSearch\nnext (YahooSearch q p _) =\n simpleHTTP (getRequest $\n -- add the page number to the search\n yahooUrl ++ q ++ \"&b=\" ++ show (p + 1)) >>=\n getResponseBody >>= return . YahooSearch q (p + 1) . items\n\nprintResults :: YahooSearch -> IO ()\nprintResults (YahooSearch q p items) = do\n putStrLn $ \"Showing Yahoo! search results for query: \" ++ q\n putStrLn $ \"Page: \" ++ show p\n putChar '\\n'\n mapM_ printOne items\n where\n printOne (YahooSearchItem itemUrl itemTitle itemContent) = do\n putStrLn $ \"URL : \" ++ itemUrl\n putStrLn $ \"Title : \" ++ itemTitle\n putStrLn $ \"Abstr : \" ++ itemContent\n putChar '\\n'\n\nurlTag, titleTag, contentTag1, contentTag2, ignoreTag,\n ignoreText :: Parsec String () String\n\n-- parse a tag containing the URL of a search result\nurlTag = do { string \"<a id=\\\"link-\";\n many digit; string \"\\\" class=\\\"yschttl spt\\\" href=\\\"\";\n url <- manyTill anyChar (char '\"'); manyTill anyChar (char '>');\n return url }\n\n-- the title comes after the URL tag, so parse it first, discard it\n-- and get the title text\ntitleTag = do { urlTag; manyTill anyChar (try (string \"</a>\")) }\n\n-- parse a tag containing the description of the search result\n-- the tag can be named \"sm-abs\" or \"abstr\"\ncontentTag1 = do { string \"<div class=\\\"sm-abs\\\">\";\n manyTill anyChar (try (string \"</div>\")) }\n\ncontentTag2 = do { string \"<div class=\\\"abstr\\\">\";\n manyTill anyChar (try (string \"</div>\")) }\n\n-- parse a tag and discard it\nignoreTag = do { char ('<'); manyTill anyChar (char '>');\n return \"\" }\n\n-- parse some text and discard it\nignoreText = do { many1 (noneOf \"<\"); return \"\" }\n\n-- return only non-empty strings\nnonempty :: [String] -> Parsec String () [String]\nnonempty xs = return [ x | x <- xs, not (null x) ]\n\n-- a template to parse a whole source file looking for items of the\n-- same class\nparseCategory x = do\n res <- many x\n eof\n nonempty res\n\nurls, titles, contents :: Parsec String () [String]\n\n-- parse HTML source looking for URL tags of the search results\nurls = parseCategory url where\n url = (try urlTag) <|> ignoreTag <|> ignoreText\n\n-- parse HTML source looking for titles of the search results\ntitles = parseCategory title where\n title = (try titleTag) <|> ignoreTag <|> ignoreText\n\n-- parse HTML source looking for descriptions of the search results\ncontents = parseCategory content where\n content = (try contentTag1) <|> (try contentTag2) <|>\n ignoreTag <|> ignoreText\n\n-- parse the HTML source three times looking for URL, title and\n-- description of all search results and return them as a list of\n-- YahooSearchItem\nitems :: String -> [YahooSearchItem]\nitems q =\n let ignoreOrKeep = either (const []) id\n us = ignoreOrKeep $ parse urls \"\" q\n ts = ignoreOrKeep $ parse titles \"\" q\n cs = ignoreOrKeep $ parse contents \"\" q\n in [ YahooSearchItem { itemUrl = u, itemTitle = t, itemContent = c } |\n (u, t, c) <- zip3 us ts cs ]\n", "language": "Haskell" }, { "code": "link printf,strings\n\nprocedure main()\nYS := YahooSearch(\"rosettacode\")\nevery 1 to 2 do { # 2 pages\n YS.readnext()\n YS.showinfo()\n }\nend\n\nclass YahooSearch(urlpat,page,response) #: class for Yahoo Search\n\n method readnext() #: read the next page of search results\n self.page +:= 1 # can't find as w|w/o self\n readurl()\n end\n\n method readurl() #: read the url\n url := sprintf(self.urlpat,(self.page-1)*10+1)\n m := open(url,\"m\") | stop(\"Unable to open : \",url)\n every (self.response := \"\") ||:= |read(m)\n close(m)\n self.response := deletec(self.response,\"\\x00\") # kill stray NULs\n end\n\n method showinfo() #: show the info of interest\n self.response ? repeat {\n (tab(find(\"<\")) & =\"<a class=\\\"yschttl spt\\\" href=\\\"\") | break\n url := tab(find(\"\\\"\")) & tab(find(\">\")+1)\n title := tab(find(\"<\")) & =\"</a></h3></div>\"\n tab(find(\"<\")) & =(\"<div class=\\\"abstr\\\">\" | \"<div class=\\\"sm-abs\\\">\")\n abstr := tab(find(\"<\")) & =\"</div>\"\n\n printf(\"\\nTitle : %i\\n\",title)\n printf(\"URL : %i\\n\",url)\n printf(\"Abstr : %i\\n\",abstr)\n }\n end\n\ninitially(searchtext) #: initialize each instance\n urlpat := sprintf(\"http://search.yahoo.com/search?p=%s&b=%%d\",searchtext)\n page := 0\nend\n", "language": "Haskell" }, { "code": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nclass YahooSearch {\n private String query;\n // Page number\n private int page = 1;\n // Regexp to look for the individual results in the returned page\n private static final Pattern pattern = Pattern.compile(\n \"<a class=\\\"yschttl spt\\\" href=\\\"[^*]+?\\\\*\\\\*([^\\\"]+?)\\\">(.+?)</a></h3>.*?<div class=\\\"(?:sm-abs|abstr)\\\">(.+?)</div>\");\n\n public YahooSearch(String query) {\n this.query = query;\n }\n\n public List<YahooResult> search() throws MalformedURLException, URISyntaxException, IOException {\n // Build the search string, starting with the Yahoo search URL,\n // then appending the query and optionally the page number (if > 1)\n StringBuilder searchUrl = new StringBuilder(\"http://search.yahoo.com/search?\");\n searchUrl.append(\"p=\").append(URLEncoder.encode(query, \"UTF-8\"));\n if (page > 1) {searchUrl.append(\"&b=\").append((page - 1) * 10 + 1);}\n // Query the Yahoo search engine\n URL url = new URL(searchUrl.toString());\n List<YahooResult> result = new ArrayList<YahooResult>();\n StringBuilder sb = new StringBuilder();\n // Get the search results using a buffered reader\n BufferedReader in = null;\n try {\n in = new BufferedReader(new InputStreamReader(url.openStream()));\n // Read the results line by line\n String line = in.readLine();\n while (line != null) {\n sb.append(line);\n line = in.readLine();\n }\n }\n catch (IOException ioe) {\n ioe.printStackTrace();\n }\n finally {\n try {in.close();} catch (Exception ignoreMe) {}\n }\n String searchResult = sb.toString();\n // Look for the individual results by matching the regexp pattern\n Matcher matcher = pattern.matcher(searchResult);\n while (matcher.find()) {\n // Extract the result URL, title and excerpt\n String resultUrl = URLDecoder.decode(matcher.group(1), \"UTF-8\");\n String resultTitle = matcher.group(2).replaceAll(\"</?b>\", \"\").replaceAll(\"<wbr ?/?>\", \"\");\n String resultContent = matcher.group(3).replaceAll(\"</?b>\", \"\").replaceAll(\"<wbr ?/?>\", \"\");\n // Create a new YahooResult and add to the list\n result.add(new YahooResult(resultUrl, resultTitle, resultContent));\n }\n return result;\n }\n\n public List<YahooResult> search(int page) throws MalformedURLException, URISyntaxException, IOException {\n // Set the page number and search\n this.page = page;\n return search();\n }\n\n public List<YahooResult> nextPage() throws MalformedURLException, URISyntaxException, IOException {\n // Increment the page number and search\n page++;\n return search();\n }\n\n public List<YahooResult> previousPage() throws MalformedURLException, URISyntaxException, IOException {\n // Decrement the page number and search; if the page number is 1 return an empty list\n if (page > 1) {\n page--;\n return search();\n } else return new ArrayList<YahooResult>();\n }\n}\n\nclass YahooResult {\n private URL url;\n private String title;\n private String content;\n\n public URL getUrl() {\n return url;\n }\n\n public void setUrl(URL url) {\n this.url = url;\n }\n\n public void setUrl(String url) throws MalformedURLException {\n this.url = new URL(url);\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public YahooResult(URL url, String title, String content) {\n setUrl(url);\n setTitle(title);\n setContent(content);\n }\n\n public YahooResult(String url, String title, String content) throws MalformedURLException {\n setUrl(url);\n setTitle(title);\n setContent(content);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n if (title != null) {\n sb.append(\",title=\").append(title);\n }\n if (url != null) {\n sb.append(\",url=\").append(url);\n }\n return sb.charAt(0) == ',' ? sb.substring(1) : sb.toString();\n }\n}\n\npublic class TestYahooSearch {\n public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException {\n // Create a new search\n YahooSearch search = new YahooSearch(\"Rosetta code\");\n // Get the search results\n List<YahooResult> results = search.search();\n // Show the search results\n for (YahooResult result : results) {\n System.out.println(result.toString());\n }\n }\n}\n", "language": "Java" }, { "code": "\"\"\" Rosetta Code Yahoo search task. https://rosettacode.org/wiki/Yahoo!_search_interface \"\"\"\n\nusing EzXML\nusing HTTP\nusing Logging\n\nconst pagesize = 7\nconst URI = \"https://search.yahoo.com/search?fr=opensearch&pz=$pagesize&\"\n\nstruct SearchResults\n title::String\n content::String\n url::String\nend\n\nmutable struct YahooSearch\n search::String\n yahoourl::String\n currentpage::Int\n usedpages::Vector{Int}\n results::Vector{SearchResults}\nend\nYahooSearch(s, url = URI) = YahooSearch(s, url, 1, Int[], SearchResults[])\n\nfunction NextPage(yah::YahooSearch, link, pagenum)\n oldpage = yah.currentpage\n yah.currentpage = pagenum\n search(yah)\n yah.currentpage = oldpage\nend\n\nfunction search(yah::YahooSearch)\n push!(yah.usedpages, yah.currentpage)\n queryurl = yah.yahoourl * \"b=$(yah.currentpage)&p=\" * HTTP.escapeuri(yah.search)\n req = HTTP.request(\"GET\", queryurl)\n # Yahoo's HTML is nonstandard, so send excess warnings from the parser to NullLogger\n html = with_logger(NullLogger()) do\n parsehtml(String(req.body))\n end\n for div in findall(\"//li/div\", html)\n if haskey(div, \"class\")\n if startswith(div[\"class\"], \"dd algo\") &&\n (a = findfirst(\"div/h3/a\", div)) != nothing &&\n haskey(a, \"href\")\n url, title, content = a[\"href\"], nodecontent(a), \"None\"\n for span in findall(\"div/p/span\", div)\n if haskey(span, \"class\") && occursin(\"fc-falcon\", span[\"class\"])\n content = nodecontent(span)\n end\n end\n push!(yah.results, SearchResults(title, content, url))\n elseif startswith(div[\"class\"], \"dd pagination\")\n for a in findall(\"div/div/a\", div)\n if haskey(a, \"href\")\n lnk, n = a[\"href\"], tryparse(Int, nodecontent(a))\n !isnothing(n) && !(n in yah.usedpages) && NextPage(yah, lnk, n)\n end\n end\n end\n end\n end\nend\n\nysearch = YahooSearch(\"RosettaCode\")\nsearch(ysearch)\nprintln(\"Searching Yahoo for `RosettaCode`:\")\nprintln(\n \"Found \",\n length(ysearch.results),\n \" entries on \",\n length(ysearch.usedpages),\n \" pages.\\n\",\n)\nfor res in ysearch.results\n println(\"Title: \", res.title)\n println(\"Content: \", res.content)\n println(\"URL: \", res.url, \"\\n\")\nend\n", "language": "Julia" }, { "code": "// version 1.2.0\n\nimport java.net.URL\n\nval rx = Regex(\"\"\"<div class=\\\"yst result\\\">.+?<a href=\\\"(.*?)\\\" class=\\\"\\\">(.*?)</a>.+?class=\"abstract ellipsis\">(.*?)</p>\"\"\")\n\nclass YahooResult(var title: String, var link: String, var text: String) {\n\n override fun toString() = \"\\nTitle: $title\\nLink : $link\\nText : $text\"\n}\n\nclass YahooSearch(val query: String, val page: Int = 0) {\n\n private val content: String\n\n init {\n val yahoo = \"http://search.yahoo.com/search?\"\n val url = URL(\"${yahoo}p=$query&b=${page * 10 + 1}\")\n content = url.readText()\n }\n\n val results: MutableList<YahooResult>\n get() {\n val list = mutableListOf<YahooResult>()\n for (mr in rx.findAll(content)) {\n val title = mr.groups[2]!!.value.replace(\"<b>\", \"\").replace(\"</b>\", \"\")\n val link = mr.groups[1]!!.value\n val text = mr.groups[3]!!.value.replace(\"<b>\", \"\").replace(\"</b>\", \"\")\n list.add (YahooResult(title, link, text))\n }\n return list\n }\n\n fun nextPage() = YahooSearch(query, page + 1)\n\n fun getPage(newPage: Int) = YahooSearch(query, newPage)\n}\n\nfun main(args: Array<String>) {\n for (page in 0..1) {\n val x = YahooSearch(\"rosettacode\", page)\n println(\"\\nPAGE ${page + 1} =>\")\n for (result in x.results.take(3)) println(result)\n }\n}\n", "language": "Kotlin" }, { "code": "Manipulate[\n Column[Flatten[\n StringCases[\n StringCases[\n URLFetch[\n \"http://search.yahoo.com/search?p=\" <> query <> \"&b=\" <>\n ToString@page], \"<ol\" ~~ ___ ~~ \"</ol>\"],\n \"<a\" ~~ Shortest[__] ~~ \"class=\\\"yschttl spt\\\" href=\\\"\" ~~\n Shortest[url__] ~~ \"\\\"\" ~~ Shortest[__] ~~ \">\" ~~\n Shortest[title__] ~~\n \"<div class=\\\"abstr\\\">\" | \"<div class=\\\"sm-abs\\\">\" ~~\n Shortest[abstr__] ~~ \"</div>\" :>\n Column[{Hyperlink[Style[#[[1]], Larger], #[[2]]], #[[3]],\n Style[#[[2]], Smaller]} &@\n StringReplace[{title, url,\n abstr}, {\"<\" ~~ Shortest[__] ~~ \">\" -> \"\",\n \"&#\" ~~ n : DigitCharacter ... ~~ \";\" :>\n FromCharacterCode[FromDigits@n], \"&amp;\" -> \"&\",\n \"&quot;\" -> \"\\\"\", \"&lt;\" -> \"<\", \"&gt;\" -> \">\"}]]], 1],\n Spacings -> 2], {{input, \"\", \"Yahoo!\"},\n InputField[Dynamic@input, String] &}, {{query, \"\"},\n ControlType -> None}, {{page, 1}, ControlType -> None},\n Row[{Button[\"Search\", page = 1; query = input],\n Button[\"Prev\", page -= 10, Enabled -> Dynamic[page >= 10]],\n Button[\"Next\", page += 10]}]]\n", "language": "Mathematica" }, { "code": "import httpclient, strutils, htmlparser, xmltree, strtabs\nconst\n PageSize = 7\n YahooURLPattern = \"https://search.yahoo.com/search?fr=opensearch&b=$$#&pz=$#&p=\".format(PageSize)\ntype\n SearchResult = ref object\n url, title, content: string\n SearchInterface = ref object\n client: HttpClient\n urlPattern: string\n page: int\n results: array[PageSize+2, SearchResult]\nproc newSearchInterface(question: string): SearchInterface =\n new result\n result.client = newHttpClient()\n# result.client = newHttpClient(proxy = newProxy(\n# \"http://localhost:40001\")) # only http_proxy supported\n result.urlPattern = YahooURLPattern&question\nproc search(si: SearchInterface) =\n let html = parseHtml(si.client.getContent(si.urlPattern.format(\n si.page*PageSize+1)))\n var\n i: int\n attrs: XmlAttributes\n for d in html.findAll(\"div\"):\n attrs = d.attrs\n if attrs != nil and attrs.getOrDefault(\"class\").startsWith(\"dd algo algo-sr relsrch\"):\n let d_inner = d.child(\"div\")\n for a in d_inner.findAll(\"a\"):\n attrs = a.attrs\n if attrs != nil and attrs.getOrDefault(\"class\") == \" ac-algo fz-l ac-21th lh-24\":\n si.results[i] = SearchResult(url: attrs[\"href\"], title: a.innerText,\n content: d.findAll(\"p\")[0].innerText)\n i+=1\n break\n while i < len(si.results) and si.results[i] != nil:\n si.results[i] = nil\n i+=1\nproc nextPage(si: SearchInterface) =\n si.page+=1\n si.search()\n\nproc echoResult(si: SearchInterface) =\n for res in si.results:\n if res == nil:\n break\n echo(res[])\n\nvar searchInf = newSearchInterface(\"weather\")\nsearchInf.search()\nsearchInf.echoResult()\necho(\"searching for next page...\")\nsearchInf.nextPage()\nsearchInf.echoResult()\n", "language": "Nim" }, { "code": "declare\n [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']}\n [StringX] = {Module.link ['x-oz://system/String.ozf']}\n [Regex] = {Module.link ['x-oz://contrib/regex']}\n\n %% Displays page 1 and 3 of the search results.\n %% The user can request and display more with context menu->Actions->Make Needed.\n proc {ExampleUsage}\n Pages = {YahooSearch \"Rosetta code\"}\n in\n {Inspector.configure widgetShowStrings true}\n {ForAll {Nth Pages 1} Value.makeNeeded}\n {ForAll {Nth Pages 3} Value.makeNeeded}\n %% Display the infinite list of search result pages.\n {Inspect Pages}\n end\n\n %% Returns a lazy list of pages.\n %% A page is a lazy list of entries like this: result(url:U title:T content:C).\n fun {YahooSearch Query}\n FetchURL = {CreateURLFetcher}\n\n fun {Page Nr}\n\tStartResult = (Nr-1)*10+1\n\t%% only retrieve it when really needed\n\tDoc = {Value.byNeed fun {$}\n\t\t\t {FetchURL \"http://search.yahoo.com/search\"\n\t\t\t\t[\"p\"#Query \"b\"#{Int.toString StartResult}]}\n\t\t\t end}\n\tRE = \"<a class=\\\"yschttl spt\\\" href=\"\n in\n\t%% Lazily returns results.\n\t%% In this way it is possible to build the pages list structure\n\t%% without creating the single elements\n\t%% (e.g. retrieve page 1 and 3 but not 2).\n\tfor Match in {Regex.allMatches RE Doc} yield:Yield do\n\t Xs = {List.drop Doc Match.0.2}\n\tin\n\t {Yield {ParseEntry Xs}}\t\n\tend\n end\n in\n for PageNr in 1;PageNr+1 yield:Yield do\n\t{Yield {Page PageNr}}\n end\n end\n\n fun {CreateURLFetcher}\n Client = {New HTTPClient.cgiGET\n\t init(inPrms(toFile:false toStrm:true)\n\t\t httpReqPrms\n\t\t )}\n %% close when no longer used\n {Finalize.register Client proc {$ C} {C closeAll(true)} end}\n\n fun {FetchURL Url Params}\n\tOutParams\n in\n\t{Client getService(Url Params ?OutParams ?_)}\n\tOutParams.sOut\n end\n in\n FetchURL\n end\n\n %% Xs: String containing HtmL\n %% Result: \"result(url:U title:T content:C)\" or \"parseError\"\n fun {ParseEntry Xs}\n proc {Parse Root}\n\tR1 R2 R3 R4 R4 R5 R6 R7\n\tUrl = {Fix {QuotedString Xs R1}}\n\t{Const \">\" R1 R2}\n\tTitle = {Fix {Until \"</a>\" R2 R3}}\n\t{Const \"</h3></div>\" R3 R4}\n\tchoice\n\t %% \"enchanted\" result?\n\t {Const \"<div class=\\\"sm-bd sm-nophoto\\\" id=\\\"sm-bd-4-1\\\">\" R4 R5}\n\t {Until \"</div>\" R5 R6 _}\n\t[] %% result with links into document\n\t {Const \"<div class=\\\"sm-bd sm-r\\\" id=\\\"sm-bd-8-1\\\">\" R4 R5}\n\t {Until \"</ul></div>\" R5 R6 _}\n\t[] %% PDF file\n\t {Const \"<div class=\\\"format\\\">\" R4 R5}\n\t {Until \"</a></div>\" R5 R6 _}\n\t[] %% With Review\n\t {Const \"<div class=\\\"sm-bd sm-r\\\" id=\\\"sm-bd-9-1\\\">\" R4 R5}\n\t R6 = nil %% no nice abstract when a review is there\n\t[] %% normal result\n\t R6 = R4\n\tend\n\tAbstract =\n\tchoice\n\t {Const \"<div class=\\\"abstr\\\">\" R6 R7}\n\t {Fix {Until \"</div>\" R7 _}}\n\t[] {Const \"<div class=\\\"sm-abs\\\">\" R6 R7}\n\t {Fix {Until \"</div>\" R7 _}}\n\t[] \"\"\n\tend\n in\n\tRoot = result(url:Url title:Title content:Abstract)\n end\n in\n {CondSelect {SearchOne Parse} 1 parseError}\n end\n\n %% Result: contents of Xs until M is found.\n %% Xs = {Append M Yr}\n fun {Until M Xs ?Yr}\n L R\n in\n {List.takeDrop Xs {Length M} L R}\n if L == M then Yr = R nil\n elsecase Xs of X|Xr then X|{Until M Xr Yr}\n [] nil then Yr = nil nil\n end\n end\n\n %% Asserts that Xs starts with C. Returns the remainder in Ys.\n proc {Const C Xs ?Ys}\n {List.takeDrop Xs {Length C} C Ys}\n end\n\n %% Assert that a quoted string follows.\n %% Returns the unquoted string and binds Ys to the remainder of Xs.\n fun {QuotedString &\"|Xs ?Ys}\n fun {Loop Xs Ys}\n\tcase Xs of &\\\\|&\"|Xr then &\\\\|&\"|{Loop Xr Ys}\n\t[] &\"|Xr then Ys = Xr nil\n\t[] X|Xr then X|{Loop Xr Ys}\n\tend\n end\n in\n {Loop Xs Ys}\n end\n\n %% Remove formatting tags.\n fun {Fix Xs}\n {Until \"</a></h3>\"\n {FoldL [\"<b>\" \"</b>\" \"<wbr />\" \"<wbr>\" \"<b>...</b>\"]\n fun {$ Ys Z}\n\t {StringX.replace Ys Z \"\"}\n end\n Xs}\n _}\n end\nin\n {ExampleUsage}\n", "language": "Oz" }, { "code": "package YahooSearch;\n\nuse Encode;\nuse HTTP::Cookies;\nuse WWW::Mechanize;\n\n# --- Internals -------------------------------------------------\n\nsub apply (&$)\n {my $f = shift; local $_ = shift; $f->(); return $_;}\n\n# We construct a cookie to get 100 results per page and prevent\n# \"enhanced results\".\nmy $search_prefs = 'v=1&n=100&sm=' .\n apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge}\n join '|',\n map {'!' . $_}\n qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe yCl GP4 FZK yNC mEG niH);\nmy $cookies = HTTP::Cookies->new;\n$cookies->set_cookie(0, 'sB', $search_prefs, '/', 'search.yahoo.com');\n\nmy $mech = new WWW::Mechanize\n (cookie_jar => $cookies,\n stack_depth => 0);\n\nsub read_page\n {my ($next, $page, @results) =\n ($mech->find_link(text => 'Next >')->url,\n decode 'iso-8859-1', $mech->content);\n while ($page =~ m\n {<h3> <a \\s class=\"yschttl \\s spt\" \\s\n href=\" ([^\"]+) \" \\s* > #\"\n (.+?) </a>\n .+?\n <div \\s class=\"abstr\">\n (.+?) </div>}xg)\n {push @results, {url => $1, title => $2, content => $3};\n foreach ( @{$results[-1]}{qw(title content)} )\n {s/<.+?>//g;\n $_ = encode 'utf8', $_;}}\n return $next, \\@results;}\n\n# --- Methods ---------------------------------------------------\n\nsub new\n {my $invocant = shift;\n my $class = ref($invocant) || $invocant;\n $mech->get('http://search.yahoo.com/search?p=' . apply\n {s/([^a-zA-Z0-9 ])/sprintf '%%%02X', ord $1/ge;\n s/ /+/g;}\n shift);\n my ($next, $results) = read_page();\n return bless {link_to_next => $next, results => $results}, $class;}\n\nsub results\n {@{shift()->{results}};}\n\nsub next_page\n {my $invocant = shift;\n my $next = $invocant->{link_to_next};\n unless ($next)\n {$invocant->{results} = [];\n return undef;}\n $mech->get($next);\n ($next, my $results) = read_page();\n $invocant->{link_to_next} = $next;\n $invocant->{results} = $results;\n return 1;}\n", "language": "Perl" }, { "code": "(notonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Yahoo_search_interface.exw\n -- =======================================\n --</span>\n <span style=\"color: #008080;\">without</span> <span style=\"color: #008080;\">js</span> <span style=\"color: #000080;font-style:italic;\">-- (libcurl)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">builtins</span><span style=\"color: #0000FF;\">\\</span><span style=\"color: #000000;\">libcurl</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">constant</span> <span style=\"color: #000000;\">glyphs</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">\"\\xC2\\xB7 \"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #000080;font-style:italic;\">-- bullet point</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"&#39;\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`'`</span><span style=\"color: #0000FF;\">},</span>\t\t\t\t\t <span style=\"color: #000080;font-style:italic;\">-- single quote</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"&quot;\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`\"`</span><span style=\"color: #0000FF;\">},</span>\t\t\t\t\t <span style=\"color: #000080;font-style:italic;\">-- double quote</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"&amp;\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"&\"</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #000080;font-style:italic;\">-- ampersand</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\\xE2\\x94\\xAC\\xC2\\xAB\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"[R]\"</span><span style=\"color: #0000FF;\">},</span> <span style=\"color: #000080;font-style:italic;\">-- registered</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"\\xC2\\xAE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"[R]\"</span><span style=\"color: #0000FF;\">}},</span> <span style=\"color: #000080;font-style:italic;\">-- registered</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">gutf8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gascii</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">columnize</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">glyphs</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">tags</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #008000;\">`&lt;a `</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/a&gt;`</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">`&lt;b&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/b&gt;`</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">`&lt;span class=\" fc-2nd\"&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/span&gt;`</span><span style=\"color: #0000FF;\">}}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">grab</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">tdx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">bool</span> <span style=\"color: #000000;\">crop</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">openidx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">tdx</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">openidx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">closeidx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">openidx</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">txt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">openidx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">)..</span><span style=\"color: #000000;\">closeidx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">tdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">tdx</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">tags</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">tags</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">tdx</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">tdx</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">[$]=</span><span style=\"color: #008000;\">'&gt;'</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">opener</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">'&gt;'</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">match</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"\"</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">txt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">substitute_all</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gutf8</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">gascii</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">crop</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">)></span><span style=\"color: #000000;\">80</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">78</span><span style=\"color: #0000FF;\">..$]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008000;\">\"..\"</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">closeidx</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">closer</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">txt</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">YahooSearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">query</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">page</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"Page %d:\\n=======\\n\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">page</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">url</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"https://search.yahoo.com/search?p=%s&b=%d\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">query</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">page</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)*</span><span style=\"color: #000000;\">10</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #000080;font-style:italic;\">--?url</span>\n <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">curl_easy_perform_ex</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">url</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">--?res</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #008080;\">not</span> <span style=\"color: #004080;\">string</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">?{</span><span style=\"color: #008000;\">\"some error\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">curl_easy_strerror</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #008080;\">return</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">rdx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">link</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">desc</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #004600;\">true</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000080;font-style:italic;\">-- {rdx,title} = grab(res,`&lt;h3 class=\"title ov-h\"&gt;`,`&lt;/h3&gt;`,rdx)\n -- {rdx,title} = grab(res,`&lt;span class=\" d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4\"&gt;`,`&lt;/span&gt;`,rdx)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">grab</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;h3 style=\"display:block;margin-top:24px;margin-bottom:2px;\" class=\"title\"&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/h3&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000080;font-style:italic;\">-- {rdx,title} = grab(res,`&lt;/span&gt;`,`&lt;/a&gt;`,rdx)\n -- title = title[rmatch(`&lt;/span&gt;`,title)+7..rmatch(`&lt;\\a&gt;`,title)]</span>\n <span style=\"color: #000000;\">title</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #7060A8;\">rmatch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">`&lt;/span&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">)+</span><span style=\"color: #000000;\">7</span><span style=\"color: #0000FF;\">..$]</span>\n <span style=\"color: #000080;font-style:italic;\">-- {rdx,link} = grab(res,`&lt;span class=\" fz-ms fw-m fc-12th wr-bw lh-17\"&gt;`,`&lt;/span&gt;`,rdx)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">link</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">grab</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;span&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/span&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- {rdx,desc} = grab(res,`&lt;p class=\"fz-ms lh-1_43x\"&gt;`,`&lt;/p&gt;`,rdx)</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">desc</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">grab</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;span class=\" fc-falcon\"&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`&lt;/span&gt;`</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">rdx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"title:%s\\nlink:%s\\ndesc:%s\\n\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">title</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">link</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">desc</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">YahooSearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"rosettacode\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">YahooSearch</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"rosettacode\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"done\"</span>\n <span style=\"color: #0000FF;\">{}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">wait_key</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "(load \"@lib/http.l\")\n\n(de yahoo (Query Page)\n (default Page 1)\n (client \"search.yahoo.com\" 80\n (pack\n \"search?p=\" (ht:Fmt Query)\n \"&b=\" (inc (* 10 (dec Page))) )\n (make\n (while (from \"<a class=\\\"yschttl spt\\\" href=\\\"\")\n (link\n (make\n (link (till \"\\\"\" T)) # Url\n (from \"<b>\")\n (link (till \"<\" T)) # Title\n (from \"class=\\\"abstr\\\"\")\n (from \">\")\n (link # Content\n (pack\n (make\n (loop\n (link (till \"<\" T))\n (T (eof))\n (T (= \"</div\" (till \">\" T)))\n (char) ) ) ) ) ) ) ) ) ) )\n", "language": "PicoLisp" }, { "code": "import urllib\nimport re\n\ndef fix(x):\n p = re.compile(r'<[^<]*?>')\n return p.sub('', x).replace('&amp;', '&')\n\nclass YahooSearch:\n def __init__(self, query, page=1):\n self.query = query\n self.page = page\n self.url = \"http://search.yahoo.com/search?p=%s&b=%s\" %(self.query, ((self.page - 1) * 10 + 1))\n self.content = urllib.urlopen(self.url).read()\n\n def getresults(self):\n self.results = []\n\n for i in re.findall('<a class=\"yschttl spt\" href=\".+?\">(.+?)</a></h3></div>(.+?)</div>.*?<span class=url>(.+?)</span>', self.content):\n\n title = fix(i[0])\n content = fix(i[1])\n url = fix(i[2])\n\n self.results.append(YahooResult(title, content, url))\n\n return self.results\n\n def getnextpage(self):\n return YahooSearch(self.query, self.page+1)\n\n search_results = property(fget=getresults)\n nextpage = property(fget=getnextpage)\n\nclass YahooResult:\n def __init__(self,title,content,url):\n self.title = title\n self.content = content\n self.url = url\n\n# Usage:\n\nx = YahooSearch(\"test\")\n\nfor result in x.search_results:\n print result.title\n", "language": "Python" }, { "code": "YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE)\n{\n if(!require(RCurl) || !require(XML))\n {\n stop(\"Could not load required packages\")\n }\n\n # Replace \" \" with \"%20\", etc\n query <- curlEscape(query)\n\n # Retrieve page\n b <- 10*(page-1)+1\n theurl <- paste(\"http://uk.search.yahoo.com/search?p=\",\n query, \"&b=\", b, sep=\"\")\n webpage <- getURL(theurl, .opts=.opts)\n\n # Save search for nextpage function\n .Search <- list(query=query, page=page, .opts=.opts,\n ignoreMarkUpErrors=ignoreMarkUpErrors)\n assign(\".Search\", .Search, envir=globalenv())\n\n # Parse HTML; retrieve results block\n webpage <- readLines(tc <- textConnection(webpage)); close(tc)\n if(ignoreMarkUpErrors)\n {\n pagetree <- htmlTreeParse(webpage, error=function(...){})\n } else\n {\n pagetree <- htmlTreeParse(webpage)\n }\n\n\n findbyattr <- function(x, id, type=\"id\")\n {\n ids <- sapply(x, function(x) x$attributes[type])\n x[ids==id]\n }\n\n body <- pagetree$children$html$children$body\n bd <- findbyattr(body$children$div$children, \"bd\")\n left <- findbyattr(bd$div$children$div$children, \"left\")\n web <- findbyattr(left$div$children$div$children, \"web\")\n resol <- web$div$children$ol\n\n #Get url, title, content from results\n gettextfromnode <- function(x)\n {\n un <- unlist(x$children)\n paste(un[grep(\"value\", names(un))], collapse=\" \")\n }\n\n n <- length(resol)\n results <- list()\n length(results) <- n\n for(i in 1:n)\n {\n mainlink <- resol[[i]]$children$div$children[1]$div$children$h3$children$a\n url <- mainlink$attributes[\"href\"]\n title <- gettextfromnode(mainlink)\n\n contenttext <- findbyattr(resol[[i]]$children$div$children[2], \"abstr\", type=\"class\")\n if(length(contenttext)==0)\n {\n contenttext <- findbyattr(resol[[i]]$children$div$children[2]$div$children$div$children,\n \"sm-abs\", type=\"class\")\n }\n\n content <- gettextfromnode(contenttext$div)\n results[[i]] <- list(url=url, title=title, content=content)\n }\n names(results) <- as.character(seq(b, b+n-1))\n results\n}\n\nnextpage <- function()\n{\n if(exists(\".Search\", envir=globalenv()))\n {\n .Search <- get(\".Search\", envir=globalenv())\n .Search$page <- .Search$page + 1L\n do.call(YahooSearch, .Search)\n } else\n {\n message(\"No search has been performed yet\")\n }\n}\n\n#Usage\nYahooSearch(\"rosetta code\")\nnextpage()\n", "language": "R" }, { "code": "#lang racket\n(require net/url)\n(define *yaho-url* \"http://search.yahoo.com/search?p=~a&b=~a\")\n(define *current-page* 0)\n(define *current-query* \"\")\n(define request (compose port->string get-pure-port string->url))\n\n;;strip html tags\n(define (remove-tags text)\n (regexp-replace* #px\"<[^<]+?>\" text \"\"))\n\n;;search, parse and print\n(define (search-yahoo query)\n (unless (string=? *current-query* query) ;different query, go back to page 1\n (set! *current-query* query)\n (set! *current-page* 0))\n (let* ([current-page (number->string (add1 (* 10 *current-page*)))]\n [html (request (format *yaho-url* query current-page))]\n [results (regexp-match* #px\"lass=\\\"yschttl spt\\\" href=\\\".+?\\\">(.+?)<span class=url>(.+?)</span>.+?<div class=\\\"abstr\\\">(.+?)</div>\" html #:match-select cdr)])\n (for ([result (in-list results)])\n (printf \"Title: ~a \\n Link: ~a \\n Text: ~a \\n\\n\"\n (remove-tags (first result))\n (remove-tags (second result) )\n (remove-tags (third result))))))\n\n;;search nexxt page\n(define (next-page)\n (set! *current-page* (add1 *current-page*))\n (search-yahoo *current-query*))\n", "language": "Racket" }, { "code": "use Gumbo;\nuse LWP::Simple;\nuse XML::Text;\n\nclass YahooSearch {\n has $!dom;\n\n submethod BUILD (:$!dom) { }\n\n method new($term) {\n self.bless(\n dom => parse-html(\n LWP::Simple.get(\"http://search.yahoo.com/search?p={ $term }\")\n )\n );\n }\n\n method next {\n $!dom = parse-html(\n LWP::Simple.get(\n $!dom.lookfor( TAG => 'a', class => 'next' ).head.attribs<href>\n )\n );\n self;\n }\n\n method text ($node) {\n return '' unless $node;\n return $node.text if $node ~~ XML::Text;\n\n $node.nodes.map({ self.text($_).trim }).join(' ');\n }\n\n method results {\n state $n = 0;\n for $!dom.lookfor( TAG => 'h3', class => 'title') {\n given .lookfor( TAG => 'a' )[0] {\n next unless $_; # No Link\n next if .attribs<href> ~~ / ^ 'https://r.search.yahoo.com' /; # Ad\n say \"=== #{ ++$n } ===\";\n say \"Title: { .contents[0] ?? self.text( .contents[0] ) !! '' }\";\n say \" URL: { .attribs<href> }\";\n\n my $pt = .parent.parent.parent.elements( TAG => 'div' ).tail;\n say \" Text: { self.text($pt) }\";\n }\n }\n self;\n }\n\n}\n\nsub MAIN (Str $search-term) is export {\n YahooSearch.new($search-term).results.next.results;\n}\n", "language": "Raku" }, { "code": "=== #1 ===\nTitle:\n URL: https://www.speedtest.net/\n Text: At Ookla, we are committed to ensuring that individuals with disabilities can access all of the content at www.speedtest.net. We also strive to make all content in Speedtest apps accessible. If you are having trouble accessing www.speedtest.net or Speedtest apps, please email [email protected] for assistance. Please put \"ADA Inquiry\" in the ...\n=== #2 ===\nTitle: Test | Definition of Test by Merriam-Webster\n URL: https://www.merriam-webster.com/dictionary/test\n Text: Test definition is - a means of testing: such as. How to use test in a sentence.\n=== #3 ===\nTitle: - Video Results\n URL: https://video.search.yahoo.com/search/video?p=test\n Text: More Test videos\n", "language": "Raku" }, { "code": "require 'open-uri'\nrequire 'hpricot'\n\nSearchResult = Struct.new(:url, :title, :content)\n\nclass SearchYahoo\n @@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil]\n\n def initialize(term)\n @term = term\n @page = 1\n @results = nil\n @url = URI::HTTP.build(@@urlinfo)\n end\n\n def next_result\n if not @results\n @results = []\n fetch_results\n elsif @results.empty?\n next_page\n end\n @results.shift\n end\n\n def fetch_results\n @url.query = URI.escape(\"p=%s&b=%d\" % [@term, @page])\n doc = open(@url) { |f| Hpricot(f) }\n parse_html(doc)\n end\n\n def next_page\n @page += 10\n fetch_results\n end\n\n def parse_html(doc)\n doc.search(\"div#main\").search(\"div\").each do |div|\n next unless div.has_attribute?(\"class\") and div.get_attribute(\"class\").index(\"res\") == 0\n result = SearchResult.new\n div.search(\"a\").each do |link|\n next unless link.has_attribute?(\"class\") and link.get_attribute(\"class\") == \"yschttl spt\"\n result.url = link.get_attribute(\"href\")\n result.title = link.inner_text\n end\n div.search(\"div\").each do |abstract|\n next unless abstract.has_attribute?(\"class\") and abstract.get_attribute(\"class\").index(\"abstr\")\n result.content = abstract.inner_text\n end\n @results << result\n end\n end\nend\n\ns = SearchYahoo.new(\"test\")\n15.times do |i|\n result = s.next_result\n puts i+1\n puts result.title\n puts result.url\n puts result.content\n puts\nend\n", "language": "Ruby" }, { "code": "'--------------------------------------------------------------------------\n' send this from the server to the clients browser\n'--------------------------------------------------------------------------\nhtml \"<table border=1 cellpadding=0 cellspacing=0 bgcolor=wheat>\"\nhtml \"<tr><td align=center colspan=2>Yahoo Search</td></tr>\"\nhtml \"<tr><td align=right>Find</td><td>\"\n textbox #find,findThis$,30\n\nhtml \"</td></tr><tr><td align=right>Page</td><td>\"\n textbox #page,findPage$,2\n\nhtml \"</td></tr><tr><td align=center colspan=2>\"\n button #s, \"Search\", [search]\nhtml \" \"\n button #ex, \"Exit\", [exit]\n\nhtml \"</td><td></td></tr></table>\"\nwait\n\n'--------------------------------------------------------------------------\n' get search stuff from the clients browser\n'--------------------------------------------------------------------------\n[search]\nfindThis$ = trim$(#find contents$())\nfindPage$ = trim$(#page contents$())\nfindPage = max(val(findPage$),1) ' must be at least 1\n\n'--------------------------------------------------------------------------\n' sho page but keep user interface at the top by not clearing the page (cls)\n' so they can change the search or page\n' -------------------------------------------------------------------------\nurl$ = \"http://search.yahoo.com/search?p=\";findThis$;\"&b=\";((findPage - 1) * 10) + 1\nhtml httpget$(url$)\nwait\n\n[exit]\ncls ' clear browser screen and get outta here\nwait\n", "language": "Run-BASIC" }, { "code": "package require http\n\nproc fix s {\n string map {<b>...</b> \"\" <b> \"\" </b> \"\" <wbr> \"\" \"<wbr />\" \"\"} \\\n [regsub \"</a></h3></div>.*\" $s \"\"]\n}\nproc YahooSearch {term {page 1}} {\n # Build the (ugly) scraper URL\n append re {<a class=\"yschttl spt\" href=\".+?\" >(.+?)</a></h3>}\n append re {</div><div class=\"abstr\">(.+?)}\n append re {</div><span class=url>(.+?)</span>}\n\n # Perform the query; note that this handles special characters\n # in the query term correctly\n set q [http::formatQuery p $term b [expr {$page*10-9}]]\n set token [http::geturl http://search.yahoo.com/search?$q]\n set data [http::data $token]\n http::cleanup $token\n\n # Assemble the results into a nice list\n set results {}\n foreach {- title content url} [regexp -all -inline $re $data] {\n lappend results [fix $title] [fix $content] [fix $url]\n }\n\n # set up the call for the next page\n interp alias {} Nextpage {} YahooSearch $term [incr page]\n\n return $results\n}\n\n# Usage: get the first two pages of results\nforeach {title content url} [YahooSearch \"test\"] {\n puts $title\n}\nforeach {title content url} [Nextpage] {\n puts $title\n}\n", "language": "Tcl" }, { "code": "package require Tcl 8.6\n\noo::class create WebSearcher {\n variable page term results\n constructor searchTerm {\n set page 0\n set term $searchTerm\n my nextPage\n }\n # This next method *is* a very Tcl-ish way of doing iteration.\n method for {titleVar contentsVar urlVar body} {\n upvar 1 $titleVar t $contentsVar c $urlVar v\n foreach {t c v} $results {\n uplevel 1 $body\n }\n }\n # Reuse the previous code for simplicity rather than writing it anew\n # Of course, if we were serious about this, we'd put the code here properly\n method nextPage {} {\n set results [YahooSearch $term [incr page]]\n return\n }\n}\n\n# How to use. Note the 'foreach' method use below; new \"keywords\" as methods!\nset ytest [WebSearcher new \"test\"]\n$ytest for title - url {\n puts \"\\\"$title\\\" : $url\"\n}\n$ytest nextPage\n$ytest for title - url {\n puts \"\\\"$title\\\" : $url\"\n}\n$ytest delete ;# standard method that deletes the object\n", "language": "Tcl" }, { "code": "package require Tcl 8.6\n\nproc yahoo! term {\n coroutine yahoo![incr ::yahoo] apply {term {\n yield [info coroutine]\n while 1 {\n set results [YahooSearch $term [incr step]]\n if {[llength $results] == 0} {\n return -code break\n }\n foreach {t c u} $results {\n yield [dict create title $t content $c url $u]\n }\n }\n }} $term\n}\n\n# test by getting first fifty titles...\nset it [yahoo! \"test\"]\nfor {set i 50} {$i>0} {incr i -1} {\n puts [dict get [$it] title]\n after 300 ;# Slow the code down... :-)\n}\n", "language": "Tcl" }, { "code": "package require Tcl 8.6\npackage require http\npackage require htmlparse\npackage require textutil::adjust\n\noo::class create yahoosearch {\n\n method search {s} {\n my variable searchterm page baseurl\n set searchterm $s\n set page 1\n set baseurl {http://ca.search.yahoo.com/search}\n }\n\n method getresults {} {\n my variable state results current_data\n set results [list]\n set current_data [dict create]\n set state looking_for_results\n htmlparse::parse -cmd [list [self] html_parser_callback] [my gethtml]\n }\n\n method nextpage {} {\n my variable page\n incr page 10\n my getresults\n }\n\n method nextresult {} {\n my variable results page\n if { ! [info exists results]} {\n my getresults\n } elseif {[llength $results] == 0} {\n my nextpage\n }\n set results [lassign $results result]\n return $result\n }\n\n method gethtml {} {\n my variable searchterm page baseurl\n set url [format {%s?%s} $baseurl [::http::formatQuery p $searchterm b $page]]\n set response [http::geturl $url]\n set html [http::data $response]\n http::cleanup $response\n return $html\n }\n\n method html_parser_callback {tag slash param textBehindTheTag} {\n my variable state results current_data\n switch -exact -- $state {\n looking_for_results {\n if {$tag eq \"div\" && [string first {id=\"main\"} $param] != -1} {\n set state ready\n }\n }\n ready {\n if {($tag eq \"div\" && [string first {class=\"res} $param] != -1) ||\n ($tag eq \"html\" && $slash eq \"/\")\n } { #\" -- unbalanced quote disturbs syntax highlighting\n if {[dict size $current_data] > 0} {lappend results $current_data}\n set current_data [dict create]\n set state getting_url\n }\n }\n getting_url {\n if {$tag eq \"a\" && [string match \"*yschttl spt*\" $param]} {\n if {[regexp {href=\"(.+?)\"} $param - url]} {\n dict set current_data url $url\n } else {\n dict set current_data url \"no href in tag params: '$param'\"\n }\n dict set current_data title $textBehindTheTag\n set state getting_title\n }\n }\n getting_title {\n if {$tag eq \"a\" && $slash eq \"/\"} {\n set state looking_for_abstract\n } else {\n dict append current_data title $textBehindTheTag\n }\n }\n looking_for_abstract {\n if {$tag eq \"span\" && [string first {class=\"url} $param] != -1} {\n set state ready\n } elseif {$tag eq \"div\" && [string first {class=\"abstr} $param] != -1} {\n dict set current_data abstract $textBehindTheTag\n set state getting_abstract\n }\n }\n getting_abstract {\n if {$tag eq \"div\" && $slash eq \"/\"} {\n set state ready\n } else {\n dict append current_data abstract $textBehindTheTag\n }\n }\n }\n }\n}\n\nyahoosearch create searcher\nsearcher search \"search text here\"\n\nfor {set x 1} {$x <= 15} {incr x} {\n set result [searcher nextresult]\n dict with result {\n puts $title\n puts $url\n puts [textutil::adjust::indent [textutil::adjust::adjust $abstract] \" \"]\n puts \"\"\n }\n}\n", "language": "Tcl" }, { "code": "#!/usr/bin/txr -f\n@(next :args)\n@(cases)\n@ QUERY\n@ PAGE\n@(or)\n@ (throw error \"specify query and page# (from zero)\")\n@(end)\n@(next (open-command \"!wget -O - http://search.yahoo.com/search?p=@QUERY\\&b=@{PAGE}1 2> /dev/null\"))\n@(all)\n@ (coll)<a class=\"yschttl spt\" href=\"@URL\" @/[^>]+/>@TITLE</a>@(end)\n@(and)\n@ (coll)<div class=\"@/abstr|sm-abs/\">@ABSTR</div>@(end)\n@(end)\n@(output)\n@ (repeat)\nTITLE: @TITLE\nURL: @URL\nTEXT: @ABSTR\n---\n@ (end)\n@(end)\n", "language": "TXR" }, { "code": "/* Yahoo_search_interface.wren */\n\nimport \"./pattern\" for Pattern\n\nclass YahooSearch {\n construct new(url, title, desc) {\n _url = url\n _title = title\n _desc = desc\n }\n\n toString { \"URL: %(_url)\\nTitle: %(_title)\\nDescription: %(_desc)\\n\" }\n}\n\nvar CURLOPT_URL = 10002\nvar CURLOPT_FOLLOWLOCATION = 52\nvar CURLOPT_WRITEFUNCTION = 20011\nvar CURLOPT_WRITEDATA = 10001\n\nforeign class Buffer {\n construct new() {} // C will allocate buffer of a suitable size\n\n foreign value // returns buffer contents as a string\n}\n\nforeign class Curl {\n construct easyInit() {}\n\n foreign easySetOpt(opt, param)\n\n foreign easyPerform()\n\n foreign easyCleanup()\n}\n\nvar curl = Curl.easyInit()\n\nvar getContent = Fn.new { |url|\n var buffer = Buffer.new()\n curl.easySetOpt(CURLOPT_URL, url)\n curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)\n curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C\n curl.easySetOpt(CURLOPT_WRITEDATA, buffer)\n curl.easyPerform()\n return buffer.value\n}\n\nvar p1 = Pattern.new(\"class/=\\\" d-ib ls-05 fz-20 lh-26 td-hu tc va-bot mxw-100p\\\" href/=\\\"[+1^\\\"]\\\"\")\nvar p2 = Pattern.new(\"class/=\\\" d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4\\\">[+1^<]<\")\nvar p3 = Pattern.new(\"<span class/=\\\" fc-falcon\\\">[+1^<]<\")\n\nvar pageSize = 7\nvar totalCount = 0\n\nvar yahooSearch = Fn.new { |query, page|\n System.print(\"Page %(page):\\n=======\\n\")\n var next = (page - 1) * pageSize + 1\n var url = \"https://search.yahoo.com/search?fr=opensearch&pz=%(pageSize)&p=%(query)&b=%(next)\"\n var content = getContent.call(url).replace(\"<b>\", \"\").replace(\"</b>\", \"\")\n var matches1 = p1.findAll(content)\n var count = matches1.count\n if (count == 0) return false\n var matches2 = p2.findAll(content)\n var matches3 = p3.findAll(content)\n totalCount = totalCount + count\n var ys = List.filled(count, null)\n for (i in 0...count) {\n var url = matches1[i].capsText[0]\n var title = matches2[i].capsText[0]\n var desc = matches3[i].capsText[0].replace(\"&#39;\", \"'\")\n ys[i] = YahooSearch.new(url, title, desc)\n }\n System.print(ys.join(\"\\n\"))\n return true\n}\n\nvar page = 1\nvar limit = 2\nvar query = \"rosettacode\"\nSystem.print(\"Searching for '%(query)' on Yahoo!\\n\")\nwhile (page <= limit && yahooSearch.call(query, page)) {\n page = page + 1\n System.print()\n}\nSystem.print(\"Displayed %(limit) pages with a total of %(totalCount) entries.\")\ncurl.easyCleanup()\n", "language": "Wren" }, { "code": "/* gcc Yahoo_search_interface.c -o Yahoo_search_interface -lcurl -lwren -lm */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <curl/curl.h>\n#include \"wren.h\"\n\nstruct MemoryStruct {\n char *memory;\n size_t size;\n};\n\n/* C <=> Wren interface functions */\n\nstatic size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {\n size_t realsize = size * nmemb;\n struct MemoryStruct *mem = (struct MemoryStruct *)userp;\n\n char *ptr = realloc(mem->memory, mem->size + realsize + 1);\n if(!ptr) {\n /* out of memory! */\n printf(\"not enough memory (realloc returned NULL)\\n\");\n return 0;\n }\n\n mem->memory = ptr;\n memcpy(&(mem->memory[mem->size]), contents, realsize);\n mem->size += realsize;\n mem->memory[mem->size] = 0;\n return realsize;\n}\n\nvoid C_bufferAllocate(WrenVM* vm) {\n struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));\n ms->memory = malloc(1);\n ms->size = 0;\n}\n\nvoid C_bufferFinalize(void* data) {\n struct MemoryStruct *ms = (struct MemoryStruct *)data;\n free(ms->memory);\n}\n\nvoid C_curlAllocate(WrenVM* vm) {\n CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));\n *pcurl = curl_easy_init();\n}\n\nvoid C_value(WrenVM* vm) {\n struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);\n wrenSetSlotString(vm, 0, ms->memory);\n}\n\nvoid C_easyPerform(WrenVM* vm) {\n CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n curl_easy_perform(curl);\n}\n\nvoid C_easyCleanup(WrenVM* vm) {\n CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n curl_easy_cleanup(curl);\n}\n\nvoid C_easySetOpt(WrenVM* vm) {\n CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);\n CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);\n if (opt < 10000) {\n long lparam = (long)wrenGetSlotDouble(vm, 2);\n curl_easy_setopt(curl, opt, lparam);\n } else if (opt < 20000) {\n if (opt == CURLOPT_WRITEDATA) {\n struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);\n curl_easy_setopt(curl, opt, (void *)ms);\n } else if (opt == CURLOPT_URL) {\n const char *url = wrenGetSlotString(vm, 2);\n curl_easy_setopt(curl, opt, url);\n }\n } else if (opt < 30000) {\n if (opt == CURLOPT_WRITEFUNCTION) {\n curl_easy_setopt(curl, opt, &WriteMemoryCallback);\n }\n }\n}\n\nWrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {\n WrenForeignClassMethods methods;\n methods.allocate = NULL;\n methods.finalize = NULL;\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Buffer\") == 0) {\n methods.allocate = C_bufferAllocate;\n methods.finalize = C_bufferFinalize;\n } else if (strcmp(className, \"Curl\") == 0) {\n methods.allocate = C_curlAllocate;\n }\n }\n return methods;\n}\n\nWrenForeignMethodFn bindForeignMethod(\n WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature) {\n if (strcmp(module, \"main\") == 0) {\n if (strcmp(className, \"Buffer\") == 0) {\n if (!isStatic && strcmp(signature, \"value\") == 0) return C_value;\n } else if (strcmp(className, \"Curl\") == 0) {\n if (!isStatic && strcmp(signature, \"easySetOpt(_,_)\") == 0) return C_easySetOpt;\n if (!isStatic && strcmp(signature, \"easyPerform()\") == 0) return C_easyPerform;\n if (!isStatic && strcmp(signature, \"easyCleanup()\") == 0) return C_easyCleanup;\n }\n }\n return NULL;\n}\n\nstatic void writeFn(WrenVM* vm, const char* text) {\n printf(\"%s\", text);\n}\n\nvoid errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {\n switch (errorType) {\n case WREN_ERROR_COMPILE:\n printf(\"[%s line %d] [Error] %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_STACK_TRACE:\n printf(\"[%s line %d] in %s\\n\", module, line, msg);\n break;\n case WREN_ERROR_RUNTIME:\n printf(\"[Runtime Error] %s\\n\", msg);\n break;\n }\n}\n\nchar *readFile(const char *fileName) {\n FILE *f = fopen(fileName, \"r\");\n fseek(f, 0, SEEK_END);\n long fsize = ftell(f);\n rewind(f);\n char *script = malloc(fsize + 1);\n fread(script, 1, fsize, f);\n fclose(f);\n script[fsize] = 0;\n return script;\n}\n\nstatic void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {\n if( result.source) free((void*)result.source);\n}\n\nWrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {\n WrenLoadModuleResult result = {0};\n if (strcmp(name, \"random\") != 0 && strcmp(name, \"meta\") != 0) {\n result.onComplete = loadModuleComplete;\n char fullName[strlen(name) + 6];\n strcpy(fullName, name);\n strcat(fullName, \".wren\");\n result.source = readFile(fullName);\n }\n return result;\n}\n\nint main(int argc, char **argv) {\n WrenConfiguration config;\n wrenInitConfiguration(&config);\n config.writeFn = &writeFn;\n config.errorFn = &errorFn;\n config.bindForeignClassFn = &bindForeignClass;\n config.bindForeignMethodFn = &bindForeignMethod;\n config.loadModuleFn = &loadModule;\n WrenVM* vm = wrenNewVM(&config);\n const char* module = \"main\";\n const char* fileName = \"Yahoo_search_interface.wren\";\n char *script = readFile(fileName);\n WrenInterpretResult result = wrenInterpret(vm, module, script);\n switch (result) {\n case WREN_RESULT_COMPILE_ERROR:\n printf(\"Compile Error!\\n\");\n break;\n case WREN_RESULT_RUNTIME_ERROR:\n printf(\"Runtime Error!\\n\");\n break;\n case WREN_RESULT_SUCCESS:\n break;\n }\n wrenFreeVM(vm);\n free(script);\n return 0;\n}\n", "language": "Wren" } ]
Yahoo-search-interface
[ { "code": "---\ncategory:\n- Prime Numbers\nfrom: http://rosettacode.org/wiki/Yellowstone_sequence\n", "language": "00-META" }, { "code": "The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first &nbsp;'''30'''&nbsp; Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* &nbsp; [https://rosettacode.org/wiki/Greatest_common_divisor Greatest common divisor].\n:* &nbsp; [https://rosettacode.org/wiki/Plot_coordinate_pairs Plot coordinate pairs].\n:* &nbsp; [[EKG sequence convergence]]\n\n\n;See also:\n:* &nbsp; The OEIS entry: &nbsp; [https://oeis.org/A098550 A098550 The Yellowstone permutation].\n:* &nbsp; Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n<br><br>\n\n", "language": "00-TASK" }, { "code": "T YellowstoneGenerator\n min_ = 1\n n_ = 0\n n1_ = 0\n n2_ = 0\n Set[Int] sequence_\n\n F next()\n .n2_ = .n1_\n .n1_ = .n_\n I .n_ < 3\n .n_++\n E\n .n_ = .min_\n L !(.n_ !C .sequence_ & gcd(.n1_, .n_) == 1 & gcd(.n2_, .n_) > 1)\n .n_++\n .sequence_.add(.n_)\n L\n I .min_ !C .sequence_\n L.break\n .sequence_.remove(.min_)\n .min_++\n R .n_\n\nprint(‘First 30 Yellowstone numbers:’)\nV ygen = YellowstoneGenerator()\nprint(ygen.next(), end' ‘’)\nL(i) 1 .< 30\n print(‘ ’ygen.next(), end' ‘’)\nprint()\n", "language": "11l" }, { "code": "F yellow(n)\n V a = [1, 2, 3]\n V b = Set([1, 2, 3])\n V i = 4\n L n > a.len\n I i !C b & gcd(i, a.last) == 1 & gcd(i, a[(len)-2]) > 1\n a.append(i)\n b.add(i)\n i = 4\n i++\n R a\n\nprint(yellow(30))\n", "language": "11l" }, { "code": "BYTE FUNC Gcd(BYTE a,b)\n BYTE tmp\n\n IF a<b THEN\n tmp=a a=b b=tmp\n FI\n\n WHILE b#0\n DO\n tmp=a MOD b\n a=b b=tmp\n OD\nRETURN (a)\n\nBYTE FUNC Contains(BYTE ARRAY a BYTE len,value)\n BYTE i\n\n FOR i=0 TO len-1\n DO\n IF a(i)=value THEN\n RETURN (1)\n FI\n OD\nRETURN (0)\n\nPROC Generate(BYTE ARRAY seq BYTE count)\n BYTE i,x\n\n seq(0)=1 seq(1)=2 seq(2)=3\n FOR i=3 TO COUNT-1\n DO\n x=1\n DO\n IF Contains(seq,i,x)=0 AND\n Gcd(x,seq(i-1))=1 AND Gcd(x,seq(i-2))>1 THEN\n EXIT\n FI\n x==+1\n OD\n seq(i)=x\n OD\nRETURN\n\nPROC Main()\n DEFINE COUNT=\"30\"\n BYTE ARRAY seq(COUNT)\n BYTE i\n\n Generate(seq,COUNT)\n PrintF(\"First %B Yellowstone numbers:%E\",COUNT)\n FOR i=0 TO COUNT-1\n DO\n PrintB(seq(i)) Put(32)\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO;\nwith Ada.Containers.Ordered_Sets;\n\nprocedure Yellowstone_Sequence is\n\n generic -- Allow more than one generator, but must be instantiated\n package Yellowstones is\n function Next return Integer;\n function GCD (Left, Right : Integer) return Integer;\n end Yellowstones;\n\n package body Yellowstones\n is\n package Sequences is\n new Ada.Containers.Ordered_Sets (Integer);\n\n -- Internal package state\n N_0 : Integer := 0;\n N_1 : Integer := 0;\n N_2 : Integer := 0;\n Seq : Sequences.Set;\n Min : Integer := 1;\n\n function GCD (Left, Right : Integer) return Integer\n is (if Right = 0\n then Left\n else GCD (Right, Left mod Right));\n\n function Next return Integer is\n begin\n N_2 := N_1;\n N_1 := N_0;\n if N_0 < 3 then\n N_0 := N_0 + 1;\n else\n N_0 := Min;\n while\n not (not Seq.Contains (N_0)\n and then GCD (N_1, N_0) = 1\n and then GCD (N_2, N_0) > 1)\n loop\n N_0 := N_0 + 1;\n end loop;\n end if;\n Seq.Insert (N_0);\n while Seq.Contains (Min) loop\n Seq.Delete (Min);\n Min := Min + 1;\n end loop;\n return N_0;\n end Next;\n\n end Yellowstones;\n\n procedure First_30 is\n package Yellowstone is new Yellowstones; -- New generator instance\n use Ada.Text_IO;\n begin\n Put_Line (\"First 30 Yellowstone numbers:\");\n for A in 1 .. 30 loop\n Put (Yellowstone.Next'Image); Put (\" \");\n end loop;\n New_Line;\n end First_30;\n\nbegin\n First_30;\nend Yellowstone_Sequence;\n", "language": "Ada" }, { "code": "BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the #\n # subsequent members are the lowest number coprime to the previous one #\n # and not coprime to the one before that, that haven't appeared in the #\n # sequence yet #\n # iterative Greatest Common Divisor routine, returns the gcd of m and n #\n PROC gcd = ( INT m, n )INT:\n BEGIN\n INT a := ABS m, b := ABS n;\n WHILE b /= 0 DO\n INT new a = b;\n b := a MOD b;\n a := new a\n OD;\n a\n END # gcd # ;\n # returns an array of the Yellowstone seuence up to n #\n OP YELLOWSTONE = ( INT n )[]INT:\n BEGIN\n [ 1 : n ]INT result;\n IF n > 0 THEN\n result[ 1 ] := 1;\n IF n > 1 THEN\n result[ 2 ] := 2;\n IF n > 2 THEN\n result[ 3 ] := 3;\n # guess the maximum element will be n, if it is larger, used will be enlarged #\n REF[]BOOL used := HEAP[ 1 : n ]BOOL;\n used[ 1 ] := used[ 2 ] := used[ 3 ] := TRUE;\n FOR i FROM 4 TO UPB used DO used[ i ] := FALSE OD;\n FOR i FROM 4 TO UPB result DO\n INT p1 = result[ i - 1 ];\n INT p2 = result[ i - 2 ];\n BOOL found := FALSE;\n FOR j WHILE NOT found DO\n IF j > UPB used THEN\n # not enough elements in used - enlarge it #\n REF[]BOOL new used := HEAP[ 1 : 2 * UPB used ]BOOL;\n new used[ 1 : UPB used ] := used;\n FOR k FROM UPB used + 1 TO UPB new used DO new used[ k ] := FALSE OD;\n used := new used\n FI;\n IF NOT used[ j ] THEN\n IF found := gcd( j, p1 ) = 1 AND gcd( j, p2 ) /= 1\n THEN\n result[ i ] := j;\n used[ j ] := TRUE\n FI\n FI\n OD\n OD\n FI\n FI\n FI;\n result\n END # YELLOWSTONE # ;\n []INT ys = YELLOWSTONE 30;\n FOR i TO UPB ys DO\n print( ( \" \", whole( ys[ i ], 0 ) ) )\n OD\nEND\n", "language": "ALGOL-68" }, { "code": "yellowstone: function [n][\n result: new [1 2 3]\n present: new [1 2 3]\n start: new 4\n while [n > size result][\n candidate: new start\n while ø [\n if all? @[\n not? contains? present candidate\n 1 = gcd @[candidate last result]\n 1 <> gcd @[candidate get result (size result)-2]\n ][\n 'result ++ candidate\n 'present ++ candidate\n while [contains? present start] -> inc 'start\n break\n ]\n inc 'candidate\n ]\n ]\n return result\n]\n\nprint yellowstone 30\n", "language": "Arturo" }, { "code": "A := [], in_seq := []\nloop 30 {\n n := A_Index\n if n <=3\n A[n] := n, in_seq[n] := true\n else while true\n {\n s := A_Index\n if !in_seq[s] && relatively_prime(s, A[n-1]) && !relatively_prime(s, A[n-2])\n {\n A[n] := s\n in_seq[s] := true\n break\n }\n }\n}\nfor i, v in A\n result .= v \",\"\nMsgBox % result := \"[\" Trim(result, \",\") \"]\"\nreturn\n;--------------------------------------\nrelatively_prime(a, b){\n return (GCD(a, b) = 1)\n}\n;--------------------------------------\nGCD(a, b) {\n while b\n b := Mod(a | 0x0, a := b)\n return a\n}\n", "language": "AutoHotkey" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct lnode_t {\n struct lnode_t *prev;\n struct lnode_t *next;\n int v;\n} Lnode;\n\nLnode *make_list_node(int v) {\n Lnode *node = malloc(sizeof(Lnode));\n if (node == NULL) {\n return NULL;\n }\n node->v = v;\n node->prev = NULL;\n node->next = NULL;\n return node;\n}\n\nvoid free_lnode(Lnode *node) {\n if (node == NULL) {\n return;\n }\n\n node->v = 0;\n node->prev = NULL;\n free_lnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct list_t {\n Lnode *front;\n Lnode *back;\n size_t len;\n} List;\n\nList *make_list() {\n List *list = malloc(sizeof(List));\n if (list == NULL) {\n return NULL;\n }\n list->front = NULL;\n list->back = NULL;\n list->len = 0;\n return list;\n}\n\nvoid free_list(List *list) {\n if (list == NULL) {\n return;\n }\n list->len = 0;\n list->back = NULL;\n free_lnode(list->front);\n list->front = NULL;\n}\n\nvoid list_insert(List *list, int v) {\n Lnode *node;\n\n if (list == NULL) {\n return;\n }\n\n node = make_list_node(v);\n if (list->front == NULL) {\n list->front = node;\n list->back = node;\n list->len = 1;\n } else {\n node->prev = list->back;\n list->back->next = node;\n list->back = node;\n list->len++;\n }\n}\n\nvoid list_print(List *list) {\n Lnode *it;\n\n if (list == NULL) {\n return;\n }\n\n for (it = list->front; it != NULL; it = it->next) {\n printf(\"%d \", it->v);\n }\n}\n\nint list_get(List *list, int idx) {\n Lnode *it = NULL;\n\n if (list != NULL && list->front != NULL) {\n int i;\n if (idx < 0) {\n it = list->back;\n i = -1;\n while (it != NULL && i > idx) {\n it = it->prev;\n i--;\n }\n } else {\n it = list->front;\n i = 0;\n while (it != NULL && i < idx) {\n it = it->next;\n i++;\n }\n }\n }\n\n if (it == NULL) {\n return INT_MIN;\n }\n return it->v;\n}\n\n///////////////////////////////////////\n\ntypedef struct mnode_t {\n int k;\n bool v;\n struct mnode_t *next;\n} Mnode;\n\nMnode *make_map_node(int k, bool v) {\n Mnode *node = malloc(sizeof(Mnode));\n if (node == NULL) {\n return node;\n }\n node->k = k;\n node->v = v;\n node->next = NULL;\n return node;\n}\n\nvoid free_mnode(Mnode *node) {\n if (node == NULL) {\n return;\n }\n node->k = 0;\n node->v = false;\n free_mnode(node->next);\n node->next = NULL;\n}\n\ntypedef struct map_t {\n Mnode *front;\n} Map;\n\nMap *make_map() {\n Map *map = malloc(sizeof(Map));\n if (map == NULL) {\n return NULL;\n }\n map->front = NULL;\n return map;\n}\n\nvoid free_map(Map *map) {\n if (map == NULL) {\n return;\n }\n free_mnode(map->front);\n map->front = NULL;\n}\n\nvoid map_insert(Map *map, int k, bool v) {\n if (map == NULL) {\n return;\n }\n if (map->front == NULL) {\n map->front = make_map_node(k, v);\n } else {\n Mnode *it = map->front;\n while (it->next != NULL) {\n it = it->next;\n }\n it->next = make_map_node(k, v);\n }\n}\n\nbool map_get(Map *map, int k) {\n if (map != NULL) {\n Mnode *it = map->front;\n while (it != NULL && it->k != k) {\n it = it->next;\n }\n if (it != NULL) {\n return it->v;\n }\n }\n return false;\n}\n\n///////////////////////////////////////\n\nint gcd(int u, int v) {\n if (u < 0) u = -u;\n if (v < 0) v = -v;\n if (v) {\n while ((u %= v) && (v %= u));\n }\n return u + v;\n}\n\nList *yellow(size_t n) {\n List *a;\n Map *b;\n int i;\n\n a = make_list();\n list_insert(a, 1);\n list_insert(a, 2);\n list_insert(a, 3);\n\n b = make_map();\n map_insert(b, 1, true);\n map_insert(b, 2, true);\n map_insert(b, 3, true);\n\n i = 4;\n\n while (n > a->len) {\n if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {\n list_insert(a, i);\n map_insert(b, i, true);\n i = 4;\n }\n i++;\n }\n\n free_map(b);\n return a;\n}\n\nint main() {\n List *a = yellow(30);\n list_print(a);\n free_list(a);\n putc('\\n', stdout);\n return 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <numeric>\n#include <set>\n\ntemplate <typename integer>\nclass yellowstone_generator {\npublic:\n integer next() {\n n2_ = n1_;\n n1_ = n_;\n if (n_ < 3) {\n ++n_;\n } else {\n for (n_ = min_; !(sequence_.count(n_) == 0\n && std::gcd(n1_, n_) == 1\n && std::gcd(n2_, n_) > 1); ++n_) {}\n }\n sequence_.insert(n_);\n for (;;) {\n auto it = sequence_.find(min_);\n if (it == sequence_.end())\n break;\n sequence_.erase(it);\n ++min_;\n }\n return n_;\n }\nprivate:\n std::set<integer> sequence_;\n integer min_ = 1;\n integer n_ = 0;\n integer n1_ = 0;\n integer n2_ = 0;\n};\n\nint main() {\n std::cout << \"First 30 Yellowstone numbers:\\n\";\n yellowstone_generator<unsigned int> ygen;\n std::cout << ygen.next();\n for (int i = 1; i < 30; ++i)\n std::cout << ' ' << ygen.next();\n std::cout << '\\n';\n return 0;\n}\n", "language": "C++" }, { "code": "import std.numeric;\nimport std.range;\nimport std.stdio;\n\nclass Yellowstone {\n private bool[int] sequence_;\n private int min_ = 1;\n private int n_ = 0;\n private int n1_ = 0;\n private int n2_ = 0;\n\n public this() {\n popFront();\n }\n\n public bool empty() {\n return false;\n }\n\n public int front() {\n return n_;\n }\n\n public void popFront() {\n n2_ = n1_;\n n1_ = n_;\n if (n_ < 3) {\n ++n_;\n } else {\n for (n_ = min_;\n !(n_ !in sequence_ && gcd(n1_, n_) == 1 && gcd(n2_, n_) > 1);\n ++n_) {\n // empty\n }\n }\n sequence_[n_] = true;\n while (true) {\n if (min_ !in sequence_) {\n break;\n }\n sequence_.remove(min_);\n ++min_;\n }\n }\n}\n\nvoid main() {\n new Yellowstone().take(30).writeln();\n}\n", "language": "D" }, { "code": "program Yellowstone_sequence;\n\n{$APPTYPE CONSOLE}\n\nuses\n System.SysUtils,\n Boost.Generics.Collection,\n Boost.Process;\n\nfunction gdc(x, y: Integer): Integer;\nbegin\n while y <> 0 do\n begin\n var tmp := x;\n x := y;\n y := tmp mod y;\n end;\n Result := x;\nend;\n\nfunction Yellowstone(n: Integer): TArray<Integer>;\nvar\n m: TDictionary<Integer, Boolean>;\n a: TArray<Integer>;\nbegin\n m.Init;\n SetLength(a, n + 1);\n for var i := 1 to 3 do\n begin\n a[i] := i;\n m[i] := True;\n end;\n\n var min := 4;\n\n for var c := 4 to n do\n begin\n var i := min;\n repeat\n if not m[i, false] and (gdc(a[c - 1], i) = 1) and (gdc(a[c - 2], i) > 1) then\n begin\n a[c] := i;\n m[i] := true;\n if i = min then\n inc(min);\n Break;\n end;\n inc(i);\n until false;\n end;\n\n Result := copy(a, 1, length(a));\nend;\n\nbegin\n var x: TArray<Integer>;\n SetLength(x, 100);\n for var i in Range(100) do\n x[i] := i + 1;\n\n var y := yellowstone(High(x));\n\n writeln('The first 30 Yellowstone numbers are:');\n for var i := 0 to 29 do\n Write(y[i], ' ');\n Writeln;\n\n //Plotting\n\n var plot := TPipe.Create('gnuplot -p', True);\n plot.WritelnA('unset key; plot ''-''');\n\n for var i := 0 to High(x) do\n plot.WriteA('%d %d'#10, [x[i], y[i]]);\n plot.WritelnA('e');\n\n writeln('Press enter to close');\n Readln;\n plot.Kill;\n plot.Free;\nend.\n", "language": "Delphi" }, { "code": "func gcd a b .\n if b = 0\n return a\n .\n return gcd b (a mod b)\n.\nproc remove_at i . a[] .\n for j = i + 1 to len a[]\n a[j - 1] = a[j]\n .\n len a[] -1\n.\nproc yellowstone count . yellow[] .\n yellow[] = [ 1 2 3 ]\n num = 4\n while len yellow[] < count\n yell1 = yellow[len yellow[] - 1]\n yell2 = yellow[len yellow[]]\n for i to len notyellow[]\n test = notyellow[i]\n if gcd yell1 test > 1 and gcd yell2 test = 1\n break 1\n .\n .\n if i <= len notyellow[]\n yellow[] &= notyellow[i]\n remove_at i notyellow[]\n else\n while gcd yell1 num <= 1 or gcd yell2 num <> 1\n notyellow[] &= num\n num += 1\n .\n yellow[] &= num\n num += 1\n .\n .\n.\nprint \"First 30 values in the yellowstone sequence:\"\nyellowstone 30 yellow[]\nprint yellow[]\n", "language": "EasyLang" }, { "code": "USING: accessors assocs colors.constants\ncombinators.short-circuit io kernel math prettyprint sequences\nsets ui ui.gadgets ui.gadgets.charts ui.gadgets.charts.lines ;\n\n: yellowstone? ( n hs seq -- ? )\n {\n [ drop in? not ]\n [ nip last gcd nip 1 = ]\n [ nip dup length 2 - swap nth gcd nip 1 > ]\n } 3&& ;\n\n: next-yellowstone ( hs seq -- n )\n [ 4 ] 2dip [ 3dup yellowstone? ] [ [ 1 + ] 2dip ] until\n 2drop ;\n\n: next ( hs seq -- hs' seq' )\n 2dup next-yellowstone [ suffix! ] [ pick adjoin ] bi ;\n\n: <yellowstone> ( n -- seq )\n [ HS{ 1 2 3 } clone dup V{ } set-like ] dip dup 3 <=\n [ head nip ] [ 3 - [ next ] times nip ] if ;\n\n\n! Show first 30 Yellowstone numbers.\n\n\"First 30 Yellowstone numbers:\" print\n30 <yellowstone> [ pprint bl ] each nl\n\n! Plot first 100 Yellowstone numbers.\n\nchart new { { 0 100 } { 0 175 } } >>axes\nline new COLOR: blue >>color\n100 <iota> 100 <yellowstone> zip >>data\nadd-gadget \"Yellowstone numbers\" open-window\n", "language": "Factor" }, { "code": ": array create cells allot ;\n: th cells + ; \\ some helper words\n\n30 constant #yellow \\ number of yellowstones\n\n#yellow array y \\ create array\n ( n1 n2 -- n3)\n: gcd dup if tuck mod recurse exit then drop ;\n: init 3 0 do i 1+ y i th ! loop ; ( --)\n: show cr #yellow 0 do y i th ? loop ; ( --)\n: gcd-y[] - cells y + @ over gcd ; ( k i n -- k gcd )\n: loop1 begin 1+ over 2 gcd-y[] 1 = >r over 1 gcd-y[] 1 > r> or 0= until ;\n: loop2 over true swap 0 ?do over y i th @ = if 0= leave then loop ;\n: yellow #yellow 3 do i 3 begin loop1 loop2 until y rot th ! loop ;\n: main init yellow show ;\n\nmain\n", "language": "Forth" }, { "code": "function gcd(a as uinteger, b as uinteger) as uinteger\n if b = 0 then return a\n return gcd( b, a mod b )\nend function\n\ndim as uinteger i, j, k, Y(1 to 100)\n\nY(1) = 1 : Y(2) = 2: Y(3) = 3\n\nfor i = 4 to 100\n k = 3\n print i\n do\n k += 1\n if gcd( k, Y(i-2) ) = 1 orelse gcd( k, Y(i-1) ) > 1 then continue do\n for j = 1 to i-1\n if Y(j)=k then continue do\n next j\n Y(i) = k\n exit do\n loop\nnext i\n\nfor i = 1 to 30\n print str(Y(i))+\" \";\nnext i\nprint\nscreen 13\nfor i = 1 to 100\n pset (i, 200-Y(i)), 31\nnext i\n\nwhile inkey=\"\"\nwend\nend\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os/exec\"\n)\n\nfunc gcd(x, y int) int {\n for y != 0 {\n x, y = y, x%y\n }\n return x\n}\n\nfunc yellowstone(n int) []int {\n m := make(map[int]bool)\n a := make([]int, n+1)\n for i := 1; i < 4; i++ {\n a[i] = i\n m[i] = true\n }\n min := 4\n for c := 4; c <= n; c++ {\n for i := min; ; i++ {\n if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n a[c] = i\n m[i] = true\n if i == min {\n min++\n }\n break\n }\n }\n }\n return a[1:]\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc main() {\n x := make([]int, 100)\n for i := 0; i < 100; i++ {\n x[i] = i + 1\n }\n y := yellowstone(100)\n fmt.Println(\"The first 30 Yellowstone numbers are:\")\n fmt.Println(y[:30])\n g := exec.Command(\"gnuplot\", \"-persist\")\n w, err := g.StdinPipe()\n check(err)\n check(g.Start())\n fmt.Fprintln(w, \"unset key; plot '-'\")\n for i, xi := range x {\n fmt.Fprintf(w, \"%d %d\\n\", xi, y[i])\n }\n fmt.Fprintln(w, \"e\")\n w.Close()\n g.Wait()\n}\n", "language": "Go" }, { "code": "import Data.List (unfoldr)\n\nyellowstone :: [Integer]\nyellowstone = 1 : 2 : 3 : unfoldr (Just . f) (2, 3, [4 ..])\n where\n f ::\n (Integer, Integer, [Integer]) ->\n (Integer, (Integer, Integer, [Integer]))\n f (p2, p1, rest) = (next, (p1, next, rest_))\n where\n (next, rest_) = select rest\n select :: [Integer] -> (Integer, [Integer])\n select (x : xs)\n | gcd x p1 == 1 && gcd x p2 /= 1 = (x, xs)\n | otherwise = (y, x : ys)\n where\n (y, ys) = select xs\n\nmain :: IO ()\nmain = print $ take 30 yellowstone\n", "language": "Haskell" }, { "code": "import Codec.Picture\nimport Data.Bifunctor (second)\nimport Diagrams.Backend.Rasterific\nimport Diagrams.Prelude\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Graphics.Rendering.Chart.Easy\nimport qualified Graphics.SVGFonts.ReadFont as F\n\n----------------- YELLOWSTONE PERMUTATION ----------------\nyellowstone :: [Integer]\nyellowstone =\n 1 :\n 2 :\n (active <$> iterate nextWindow (2, 3, [4 ..]))\n where\n nextWindow (p2, p1, rest) = (p1, n, residue)\n where\n [rp2, rp1] = relativelyPrime <$> [p2, p1]\n go (x : xs)\n | rp1 x && not (rp2 x) = (x, xs)\n | otherwise = second ((:) x) (go xs)\n (n, residue) = go rest\n active (_, x, _) = x\n\nrelativelyPrime :: Integer -> Integer -> Bool\nrelativelyPrime a b = 1 == gcd a b\n\n---------- 30 FIRST TERMS, AND CHART OF FIRST 100 --------\nmain :: IO (Image PixelRGBA8)\nmain = do\n print $ take 30 yellowstone\n env <- chartEnv\n return $\n chartRender env $\n plot\n ( line\n \"Yellowstone terms\"\n [zip [1 ..] (take 100 yellowstone)]\n )\n\n--------------------- CHART GENERATION -------------------\nchartRender ::\n (Default r, ToRenderable r) =>\n DEnv Double ->\n EC r () ->\n Image PixelRGBA8\nchartRender env ec =\n renderDia\n Rasterific\n ( RasterificOptions\n (mkWidth (fst (envOutputSize env)))\n )\n $ fst $ runBackendR env (toRenderable (execEC ec))\n\n------------------------ LOCAL FONT ----------------------\nchartEnv :: IO (DEnv Double)\nchartEnv = do\n sansR <- F.loadFont \"SourceSansPro_R.svg\"\n sansRB <- F.loadFont \"SourceSansPro_RB.svg\"\n let fontChosen fs =\n case ( _font_name fs,\n _font_slant fs,\n _font_weight fs\n ) of\n ( \"sans-serif\",\n FontSlantNormal,\n FontWeightNormal\n ) -> sansR\n ( \"sans-serif\",\n FontSlantNormal,\n FontWeightBold\n ) -> sansRB\n return $ createEnv vectorAlignmentFns 640 400 fontChosen\n", "language": "Haskell" }, { "code": "Until=: 2 :'u^:(0-:v)^:_'\nassert 44 -: >:Until(>&43) 32 NB. increment until exceeding 43\ngcd=: +.\ncoprime=: 1 = gcd\nprepare=:1 2 3\"_ NB. start with the vector 1 2 3\ncondition=: 0 1 -: (coprime _2&{.) NB. trial coprime most recent 2, nay and yay\nappend=: , NB. concatenate\nnovel=: -.@e. NB. x is not a member of y\nterm=: >:@:]Until((condition *. novel)~) 4:\nys=: (append term)@]^:(0 >. _3+[) prepare\nassert (ys 30) -: 1 2 3 4 9 8 15 14 5 6 25 12 35 16 7 10 21 20 27 22 39 11 13 33 26 45 28 51 32 17\n", "language": "J" }, { "code": "GCD=: +.\nrelatively_prime=: 1 = GCD\n\nyellowstone=: {{\n s=. 1 2 3 NB. initial sequence\n while. y > # s do.\n z=. <./(1+s)-.s NB. lowest positive inteeger not in sequence\n while. if. 0 1 -: z relatively_prime _2{.s do. z e. s end. do.\n z=. z+1\n end. NB. find next value for sequence\n s=. s, z\n end.\n}}\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class YellowstoneSequence {\n\n public static void main(String[] args) {\n System.out.printf(\"First 30 values in the yellowstone sequence:%n%s%n\", yellowstoneSequence(30));\n }\n\n private static List<Integer> yellowstoneSequence(int sequenceCount) {\n List<Integer> yellowstoneList = new ArrayList<Integer>();\n yellowstoneList.add(1);\n yellowstoneList.add(2);\n yellowstoneList.add(3);\n int num = 4;\n List<Integer> notYellowstoneList = new ArrayList<Integer>();\n int yellowSize = 3;\n while ( yellowSize < sequenceCount ) {\n int found = -1;\n for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {\n int test = notYellowstoneList.get(index);\n if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {\n found = index;\n break;\n }\n }\n if ( found >= 0 ) {\n yellowstoneList.add(notYellowstoneList.remove(found));\n yellowSize++;\n }\n else {\n while ( true ) {\n if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {\n yellowstoneList.add(num);\n yellowSize++;\n num++;\n break;\n }\n notYellowstoneList.add(num);\n num++;\n }\n }\n }\n return yellowstoneList;\n }\n\n private static final int gcd(int a, int b) {\n if ( b == 0 ) {\n return a;\n }\n return gcd(b, a%b);\n }\n\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n // yellowstone :: Generator [Int]\n function* yellowstone() {\n // A non finite stream of terms in the\n // Yellowstone permutation of the natural numbers.\n // OEIS A098550\n const nextWindow = ([p2, p1, rest]) => {\n const [rp2, rp1] = [p2, p1].map(\n relativelyPrime\n );\n const go = xxs => {\n const [x, xs] = Array.from(\n uncons(xxs).Just\n );\n return rp1(x) && !rp2(x) ? (\n Tuple(x)(xs)\n ) : secondArrow(cons(x))(\n go(xs)\n );\n };\n return [p1, ...Array.from(go(rest))];\n };\n const A098550 = fmapGen(x => x[1])(\n iterate(nextWindow)(\n [2, 3, enumFrom(4)]\n )\n );\n yield 1\n yield 2\n while (true)(\n yield A098550.next().value\n )\n };\n\n\n // relativelyPrime :: Int -> Int -> Bool\n const relativelyPrime = a =>\n // True if a is relatively prime to b.\n b => 1 === gcd(a)(b);\n\n\n // ------------------------TEST------------------------\n const main = () => console.log(\n take(30)(\n yellowstone()\n )\n );\n\n\n // -----------------GENERIC FUNCTIONS------------------\n\n // Just :: a -> Maybe a\n const Just = x => ({\n type: 'Maybe',\n Nothing: false,\n Just: x\n });\n\n // Nothing :: Maybe a\n const Nothing = () => ({\n type: 'Maybe',\n Nothing: true,\n });\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = a =>\n b => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // abs :: Num -> Num\n const abs =\n // Absolute value of a given number - without the sign.\n Math.abs;\n\n // cons :: a -> [a] -> [a]\n const cons = x =>\n xs => Array.isArray(xs) ? (\n [x].concat(xs)\n ) : 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n x + xs\n ) : ( // cons(x)(Generator)\n function*() {\n yield x;\n let nxt = xs.next()\n while (!nxt.done) {\n yield nxt.value;\n nxt = xs.next();\n }\n }\n )();\n\n // enumFrom :: Enum a => a -> [a]\n function* enumFrom(x) {\n // A non-finite succession of enumerable\n // values, starting with the value x.\n let v = x;\n while (true) {\n yield v;\n v = 1 + v;\n }\n }\n\n // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]\n const fmapGen = f =>\n function*(gen) {\n let v = take(1)(gen);\n while (0 < v.length) {\n yield(f(v[0]))\n v = take(1)(gen)\n }\n };\n\n // gcd :: Int -> Int -> Int\n const gcd = x => y => {\n const\n _gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),\n abs = Math.abs;\n return _gcd(abs(x), abs(y));\n };\n\n // iterate :: (a -> a) -> a -> Gen [a]\n const iterate = f =>\n function*(x) {\n let v = x;\n while (true) {\n yield(v);\n v = f(v);\n }\n };\n\n // length :: [a] -> Int\n const length = xs =>\n // Returns Infinity over objects without finite\n // length. This enables zip and zipWith to choose\n // the shorter argument when one is non-finite,\n // like cycle, repeat etc\n (Array.isArray(xs) || 'string' === typeof xs) ? (\n xs.length\n ) : Infinity;\n\n // secondArrow :: (a -> b) -> ((c, a) -> (c, b))\n const secondArrow = f => xy =>\n // A function over a simple value lifted\n // to a function over a tuple.\n // f (a, b) -> (a, f(b))\n Tuple(xy[0])(\n f(xy[1])\n );\n\n // take :: Int -> [a] -> [a]\n // take :: Int -> String -> String\n const take = n =>\n // The first n elements of a list,\n // string of characters, or stream.\n xs => 'GeneratorFunction' !== xs\n .constructor.constructor.name ? (\n xs.slice(0, n)\n ) : [].concat.apply([], Array.from({\n length: n\n }, () => {\n const x = xs.next();\n return x.done ? [] : [x.value];\n }));\n\n // uncons :: [a] -> Maybe (a, [a])\n const uncons = xs => {\n // Just a tuple of the head of xs and its tail,\n // Or Nothing if xs is an empty list.\n const lng = length(xs);\n return (0 < lng) ? (\n Infinity > lng ? (\n Just(Tuple(xs[0])(xs.slice(1))) // Finite list\n ) : (() => {\n const nxt = take(1)(xs);\n return 0 < nxt.length ? (\n Just(Tuple(nxt[0])(xs))\n ) : Nothing();\n })() // Lazy generator\n ) : Nothing();\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "# jq optimizes the recursive call of _gcd in the following:\ndef gcd(a;b):\n def _gcd:\n if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;\n [a,b] | _gcd ;\n\n# emit the yellowstone sequence as a stream\ndef yellowstone:\n 1,2,3,\n ({ a: [2, 3], # the last two items only\n b: {\"1\": true, \"2\": true, \"3\" : true}, # a record, to avoid having to save the entire history\n start: 4 }\n | foreach range(1; infinite) as $n (.;\n first(\n .b as $b\n \t | .start = first( range(.start;infinite) | select($b[tostring]|not) )\n | foreach range(.start; infinite) as $i (.;\n .emit = null\n | ($i|tostring) as $is\n | if .b[$is] then .\n # \"a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2)\"\n elif (gcd($i; .a[1]) == 1) and (gcd($i; .a[0]) > 1)\n then .emit = $i\n | .a = [.a[1], $i]\n | .b[$is] = true\n else .\n end;\n select(.emit)) );\n .emit ));\n", "language": "Jq" }, { "code": "\"The first 30 entries of the Yellowstone permutation:\",\n[limit(30;yellowstone)]\n", "language": "Jq" }, { "code": "using Plots\n\nfunction yellowstone(N)\n a = [1, 2, 3]\n b = Dict(1 => 1, 2 => 1, 3 => 1)\n start = 4\n while length(a) < N\n inseries = true\n for i in start:typemax(Int)\n if haskey(b, i)\n if inseries\n start += 1\n end\n else\n inseries = false\n end\n if !haskey(b, i) && (gcd(i, a[end]) == 1) && (gcd(i, a[end - 1]) > 1)\n push!(a, i)\n b[i] = 1\n break\n end\n end\n end\n return a\nend\n\nprintln(\"The first 30 entries of the Yellowstone permutation:\\n\", yellowstone(30))\n\nx = 1:100\ny = yellowstone(100)\nplot(x, y)\n", "language": "Julia" }, { "code": "fun main() {\n println(\"First 30 values in the yellowstone sequence:\")\n println(yellowstoneSequence(30))\n}\n\nprivate fun yellowstoneSequence(sequenceCount: Int): List<Int> {\n val yellowstoneList = mutableListOf(1, 2, 3)\n var num = 4\n val notYellowstoneList = mutableListOf<Int>()\n var yellowSize = 3\n while (yellowSize < sequenceCount) {\n var found = -1\n for (index in notYellowstoneList.indices) {\n val test = notYellowstoneList[index]\n if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd(\n yellowstoneList[yellowSize - 1], test\n ) == 1\n ) {\n found = index\n break\n }\n }\n if (found >= 0) {\n yellowstoneList.add(notYellowstoneList.removeAt(found))\n yellowSize++\n } else {\n while (true) {\n if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd(\n yellowstoneList[yellowSize - 1], num\n ) == 1\n ) {\n yellowstoneList.add(num)\n yellowSize++\n num++\n break\n }\n notYellowstoneList.add(num)\n num++\n }\n }\n }\n return yellowstoneList\n}\n\nprivate fun gcd(a: Int, b: Int): Int {\n return if (b == 0) {\n a\n } else gcd(b, a % b)\n}\n", "language": "Kotlin" }, { "code": "function gcd(a, b)\n if b == 0 then\n return a\n end\n return gcd(b, a % b)\nend\n\nfunction printArray(a)\n io.write('[')\n for i,v in pairs(a) do\n if i > 1 then\n io.write(', ')\n end\n io.write(v)\n end\n io.write(']')\n return nil\nend\n\nfunction removeAt(a, i)\n local na = {}\n for j,v in pairs(a) do\n if j ~= i then\n table.insert(na, v)\n end\n end\n return na\nend\n\nfunction yellowstone(sequenceCount)\n local yellow = {1, 2, 3}\n local num = 4\n local notYellow = {}\n local yellowSize = 3\n while yellowSize < sequenceCount do\n local found = -1\n for i,test in pairs(notYellow) do\n if gcd(yellow[yellowSize - 1], test) > 1 and gcd(yellow[yellowSize - 0], test) == 1 then\n found = i\n break\n end\n end\n if found >= 0 then\n table.insert(yellow, notYellow[found])\n notYellow = removeAt(notYellow, found)\n yellowSize = yellowSize + 1\n else\n while true do\n if gcd(yellow[yellowSize - 1], num) > 1 and gcd(yellow[yellowSize - 0], num) == 1 then\n table.insert(yellow, num)\n yellowSize = yellowSize + 1\n num = num + 1\n break\n end\n table.insert(notYellow, num)\n num = num + 1\n end\n end\n end\n return yellow\nend\n\nfunction main()\n print(\"First 30 values in the yellowstone sequence:\")\n printArray(yellowstone(30))\n print()\nend\n\nmain()\n", "language": "Lua" }, { "code": "state = {1, 2, 3};\nMakeNext[state_List] := Module[{i = First[state], done = False, out},\n While[! done,\n If[FreeQ[state, i],\n If[GCD[Last[state], i] == 1,\n If[GCD[state[[-2]], i] > 1,\n out = Append[state, i];\n done = True;\n ]\n ]\n ];\n i++;\n ];\n out\n ]\nNest[MakeNext, state, 30 - 3]\nListPlot[%]\n", "language": "Mathematica" }, { "code": "import math\n\nproc yellowstone(n: int): seq[int] =\n assert n >= 3\n result = @[1, 2, 3]\n var present = {1, 2, 3}\n var start = 4\n while result.len < n:\n var candidate = start\n while true:\n if candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1:\n result.add candidate\n present.incl candidate\n while start in present: inc start\n break\n inc candidate\n\necho yellowstone(30)\n", "language": "Nim" }, { "code": "import math, sets\n\niterator yellowstone(n: int): int =\n assert n >= 3\n for i in 1..3: yield i\n var present = [1, 2, 3].toHashSet\n var prevLast = 2\n var last = 3\n var start = 4\n for _ in 4..n:\n var candidate = start\n while true:\n if candidate notin present and gcd(candidate, last) == 1 and gcd(candidate, prevLast) != 1:\n yield candidate\n present.incl candidate\n prevLast = last\n last = candidate\n while start in present: inc start\n break\n inc candidate\n\nfor n in yellowstone(30):\n stdout.write \" \", n\necho()\n", "language": "Nim" }, { "code": "yellowstone(n) = {\n my(a=3, o=2, u=[]);\n if(n<3, return(n)); \\\\ Base case: return n if it is less than 3\n print1(\"1, 2\"); \\\\ Print initial values\n\n for(i = 4, n, \\\\ Iterate from 4 to n\n print1(\", \"a); \\\\ Print current value of a\n u = setunion(u, Set(a)); \\\\ Add a to the set u\n\n \\\\ Remove consecutive elements from u\n while(#u > 1 && u[2] == u[1] + 1,\n u = vecextract(u, \"^1\")\n );\n\n \\\\ Find next value of a\n for(k = u[1] + 1, 1e10,\n if(gcd(k, o) <= 1, next); \\\\ Skip if gcd(k, o) is greater than 1\n if(setsearch(u, k), next); \\\\ Skip if k is in set u\n if(gcd(k, a) != 1, next); \\\\ Skip if gcd(k, a) is not 1\n o = a; \\\\ Update o to current a\n a = k; \\\\ Update a to k\n break\n )\n );\n\n a \\\\ Return the final value of a\n}\n\nyellowstone(20); \\\\ Call the function with n = 20\n", "language": "PARI-GP" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\n\nuse List::Util qw(first);\nuse GD::Graph::bars;\n\nuse constant Inf => 1e5;\n\nsub gcd {\n my ($u, $v) = @_;\n while ($v) {\n ($u, $v) = ($v, $u % $v);\n }\n return abs($u);\n}\n\nsub yellowstone {\n my($terms) = @_;\n my @s = (1, 2, 3);\n my @used = (1) x 4;\n my $min = 3;\n while (1) {\n my $index = first { not defined $used[$_] and gcd($_,$s[-2]) != 1 and gcd($_,$s[-1]) == 1 } $min .. Inf;\n $used[$index] = 1;\n $min = (first { not defined $used[$_] } 0..@used-1) || @used-1;\n push @s, $index;\n last if @s == $terms;\n }\n @s;\n}\n\nsay \"The first 30 terms in the Yellowstone sequence:\\n\" . join ' ', yellowstone(30);\n\nmy @data = ( [1..500], [yellowstone(500)]);\nmy $graph = GD::Graph::bars->new(800, 600);\n$graph->set(\n title => 'Yellowstone sequence',\n y_max_value => 1400,\n x_tick_number => 5,\n r_margin => 10,\n dclrs => [ 'blue' ],\n) or die $graph->error;\nmy $gd = $graph->plot(\\@data) or die $graph->error;\n\nopen my $fh, '>', 'yellowstone-sequence.png';\nbinmode $fh;\nprint $fh $gd->png();\nclose $fh;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Yellowstone_sequence.exw\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"1.0.2\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">yellowstone</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">N</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">4</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #0000FF;\"><</span> <span style=\"color: #000000;\">N</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">or</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[$])=</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">and</span> <span style=\"color: #7060A8;\">gcd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">])></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">i</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">false</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #004600;\">true</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">4</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">i</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">a</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"The first 30 entries of the Yellowstone permutation:\\n%v\\n\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">yellowstone</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">30</span><span style=\"color: #0000FF;\">)})</span>\n\n <span style=\"color: #000080;font-style:italic;\">-- a simple plot:</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #7060A8;\">IupGraph</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">get_data</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">y500</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">yellowstone</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"XTICK\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">640</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">300</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">50</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #000000;\">20</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YTICK\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">250</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">140</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">120</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">700</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #000000;\">350</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #000000;\">200</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #000000;\">100</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{{</span><span style=\"color: #7060A8;\">tagset</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">500</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">y500</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_RED</span><span style=\"color: #0000FF;\">}}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">graph</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGraph</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">get_data</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"RASTERSIZE=960x600\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`GTITLE=\"Yellowstone Numbers\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"TITLESTYLE\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">CD_ITALIC</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`XNAME=\"n\", YNAME=\"a(n)\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"XTICK=20,XMIN=0,XMAX=500\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"YTICK=100,YMIN=0,YMAX=1400\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">graph</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">`TITLE=\"Yellowstone Names\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttributes</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"MINSIZE=290x140\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n<!--\n", "language": "Phix" }, { "code": "include ..\\Utilitys.pmt\n\ndef gcd /# u v -- n #/\n abs int swap abs int swap\n\n dup\n while\n over over mod rot drop dup\n endwhile\n drop\nenddef\n\ndef test enddef\n\ndef yellow var n\n ( 1 2 3 ) var a\n newd ( 1 true ) setd ( 2 true ) setd ( 3 true ) setd var b\n 4 var i\n test\n while\n b i getd \"Unfound\" == >ps\n a -1 get >ps -2 get\n i gcd 1 > ps> i gcd 1 == ps>\n and and if\n i 0 put var a\n ( i true ) setd var b\n 4 var i\n else\n drop drop\n endif\n i 1 + var i\n test\n endwhile\n a\nenddef\n\ndef test n a len nip > enddef\n\n\"The first 30 entries of the Yellowstone permutation:\" ? 30 yellow ?\n", "language": "Phixmonti" }, { "code": "(load \"@lib/frac.l\")\n(de yellow (N)\n (let (L (list 3 2 1) I 4 C 3 D)\n (while (> N C)\n (when\n (and\n (not (idx 'D I))\n (=1 (gcd I (get L 1)))\n (> (gcd I (get L 2)) 1) )\n (push 'L I)\n (idx 'D I T)\n (setq I 4)\n (inc 'C) )\n (inc 'I) )\n (flip L) ) )\n(println (yellow 30))\n", "language": "PicoLisp" }, { "code": "Procedure.i gcd(x.i,y.i)\n While y<>0 : t=x : x=y : y=t%y : Wend : ProcedureReturn x\nEndProcedure\n\nIf OpenConsole()\n Dim Y.i(100)\n For i=1 To 100\n If i<=3 : Y(i)=i : Continue : EndIf : k=3\n Repeat\n RepLoop:\n k+1\n For j=1 To i-1 : If Y(j)=k : Goto RepLoop : EndIf : Next\n If gcd(k,Y(i-2))=1 Or gcd(k,Y(i-1))>1 : Continue : EndIf\n Y(i)=k : Break\n ForEver\n Next\n For i=1 To 30 : Print(Str(Y(i))+\" \") : Next : Input()\nEndIf\n", "language": "PureBasic" }, { "code": "'''Yellowstone permutation OEIS A098550'''\n\nfrom itertools import chain, count, islice\nfrom operator import itemgetter\nfrom math import gcd\n\nfrom matplotlib import pyplot\n\n\n# yellowstone :: [Int]\ndef yellowstone():\n '''A non-finite stream of terms from\n the Yellowstone permutation.\n OEIS A098550.\n '''\n # relativelyPrime :: Int -> Int -> Bool\n def relativelyPrime(a):\n return lambda b: 1 == gcd(a, b)\n\n # nextWindow :: (Int, Int, [Int]) -> (Int, Int, [Int])\n def nextWindow(triple):\n p2, p1, rest = triple\n [rp2, rp1] = map(relativelyPrime, [p2, p1])\n\n # match :: [Int] -> (Int, [Int])\n def match(xxs):\n x, xs = uncons(xxs)['Just']\n return (x, xs) if rp1(x) and not rp2(x) else (\n second(cons(x))(\n match(xs)\n )\n )\n n, residue = match(rest)\n return (p1, n, residue)\n\n return chain(\n range(1, 3),\n map(\n itemgetter(1),\n iterate(nextWindow)(\n (2, 3, count(4))\n )\n )\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Terms of the Yellowstone permutation.'''\n\n print(showList(\n take(30)(yellowstone())\n ))\n pyplot.plot(\n take(100)(yellowstone())\n )\n pyplot.xlabel(main.__doc__)\n pyplot.show()\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# cons :: a -> [a] -> [a]\ndef cons(x):\n '''Construction of a list from x as head,\n and xs as tail.\n '''\n return lambda xs: [x] + xs if (\n isinstance(xs, list)\n ) else x + xs if (\n isinstance(xs, str)\n ) else chain([x], xs)\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# second :: (a -> b) -> ((c, a) -> (c, b))\ndef second(f):\n '''A simple function lifted to a function over a tuple,\n with f applied only to the second of two values.\n '''\n return lambda xy: (xy[0], f(xy[1]))\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(repr(x) for x in xs) + ']'\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# uncons :: [a] -> Maybe (a, [a])\ndef uncons(xs):\n '''The deconstruction of a non-empty list\n (or generator stream) into two parts:\n a head value, and the remaining values.\n '''\n if isinstance(xs, list):\n return Just((xs[0], xs[1:])) if xs else Nothing()\n else:\n nxt = take(1)(xs)\n return Just((nxt[0], xs)) if nxt else Nothing()\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": " [ stack ] is seqbits ( --> s )\n\n [ bit\n seqbits take |\n seqbits put ] is seqadd ( n --> )\n\n [ bit\n seqbits share & not ] is notinseq ( n --> b )\n\n [ temp put\n ' [ 1 2 3 ]\n 7 seqbits put\n 4\n [ dip\n [ dup -1 peek\n over -2 peek ]\n dup dip\n [ tuck gcd 1 !=\n unrot gcd 1 =\n and ]\n swap if\n [ dup dip join\n seqadd\n 3 ]\n [ 1+\n dup notinseq until ]\n over size temp share\n < not until ]\n drop\n seqbits release\n temp take split drop ] is yellowstones ( n --> [ )\n\n 30 yellowstones echo\n", "language": "Quackery" }, { "code": "#lang racket\n\n(require plot)\n\n(define a098550\n (let ((hsh# (make-hash '((1 . 1) (2 . 2) (3 . 3))))\n (rev# (make-hash '((1 . 1) (2 . 2) (3 . 3)))))\n (λ (n)\n (hash-ref hsh# n\n (λ ()\n (let ((a_n (for/first ((i (in-naturals 4))\n #:unless (hash-has-key? rev# i)\n #:when (and (= (gcd i (a098550 (- n 1))) 1)\n (> (gcd i (a098550 (- n 2))) 1)))\n i)))\n (hash-set! hsh# n a_n)\n (hash-set! rev# a_n n)\n a_n))))))\n\n(map a098550 (range 1 (add1 30)))\n\n(plot (points\n (map (λ (i) (vector i (a098550 i))) (range 1 (add1 100)))))\n", "language": "Racket" }, { "code": "my @yellowstone = 1, 2, 3, -> $q, $p {\n state @used = True xx 4;\n state $min = 3;\n my \\index = ($min .. *).first: { not @used[$_] and $_ gcd $q != 1 and $_ gcd $p == 1 };\n @used[index] = True;\n $min = @used.first(!*, :k) // +@used - 1;\n index\n} … *;\n\nput \"The first 30 terms in the Yellowstone sequence:\\n\", @yellowstone[^30];\n\nuse SVG;\nuse SVG::Plot;\n\nmy @x = ^500;\n\nmy $chart = SVG::Plot.new(\n background => 'white',\n width => 1000,\n height => 600,\n plot-width => 950,\n plot-height => 550,\n x => @x,\n x-tick-step => { 10 },\n y-tick-step => { 50 },\n min-y-axis => 0,\n values => [@yellowstone[@x],],\n title => \"Yellowstone Sequence - First {+@x} values (zero indexed)\",\n);\n\nmy $line = './Yellowstone-sequence-line-perl6.svg'.IO;\nmy $bars = './Yellowstone-sequence-bars-perl6.svg'.IO;\n\n$line.spurt: SVG.serialize: $chart.plot: :lines;\n$bars.spurt: SVG.serialize: $chart.plot: :bars;\n", "language": "Raku" }, { "code": "/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/\nparse arg m . /*obtain optional argument from the CL.*/\nif m=='' | m==\",\" then m= 30 /*Not specified? Then use the default.*/\n!.= 0 /*initialize an array of numbers(used).*/\n# = 0 /*count of Yellowstone numbers in seq. */\n$= /*list \" \" \" \" \" */\n do j=1 until #==m; prev= # - 1\n if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end\n\n do k=1; if !.k then iterate /*Already used? Then skip this number.*/\n if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */\n if gcd(k, @.#) \\==1 then iterate /* \" \" \" \" \" \" */\n #= #+1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/\n leave /*find the next Yellowstone seq. number*/\n end /*k*/\n end /*j*/\nsay $ /*display a list of a Yellowstone seq. */\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x\n", "language": "REXX" }, { "code": "/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/\nparse arg m . /*obtain optional argument from the CL.*/\nif m=='' | m==\",\" then m= 30 /*Not specified? Then use the default.*/\n!.= 0 /*initialize an array of numbers(used).*/\n# = 0 /*count of Yellowstone numbers in seq. */\n$ = /*list \" \" \" \" \" */\n do j=1 until #==m; prev= # - 1\n if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end\n\n do k=1; if !.k then iterate /*Already used? Then skip this number.*/\n if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */\n if gcd(k, @.#) \\==1 then iterate /* \" \" \" \" \" \" */\n #= # + 1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/\n leave /*find the next Yellowstone seq. number*/\n end /*k*/\n end /*j*/\n\ncall $histo $ '(vertical)' /*invoke a REXX vertical histogram plot*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\ngcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x\n", "language": "REXX" }, { "code": "see \"working...\" + nl\nrow = 3\nnum = 2\nnumbers = 1:51\nfirst = 2\nsecond = 3\nsee \"Yellowstone numbers are:\" + nl\nsee \"1 \" + first + \" \" + second + \" \"\n\n for n = 4 to len(numbers)\n flag1 = 1\n flag2 = 1\n if first < numbers[n]\n min = first\n else\n min = numbers[n]\n ok\n for m = 2 to min\n if first%m = 0 and numbers[n]%m = 0\n flag1 = 0\n exit\n ok\n next\n if second < numbers[n]\n min = second\n else\n min = numbers[n]\n ok\n for m = 2 to min\n if second%m = 0 and numbers[n]%m = 0\n flag2 = 0\n exit\n ok\n next\n if flag1 = 0 and flag2 = 1\n see \"\" + numbers[n] + \" \"\n first = second\n second = numbers[n]\n del(numbers,n)\n row = row+1\n if row%10 = 0\n see nl\n ok\n num = num + 1\n if num = 29\n exit\n ok\n n = 3\n ok\n next\n\n see \"Found \" + row + \" Yellowstone numbers\" + nl\n see \"done...\" + nl\n", "language": "Ring" }, { "code": "def yellow(n)\n a = [1, 2, 3]\n b = { 1 => true, 2 => true, 3 => true }\n i = 4\n while n > a.length\n if !b[i] && i.gcd(a[-1]) == 1 && i.gcd(a[-2]) > 1\n a << i\n b[i] = true\n i = 4\n end\n i += 1\n end\n a\nend\n\np yellow(30)\n", "language": "Ruby" }, { "code": "// [dependencies]\n// num = \"0.3\"\n// plotters = \"^0.2.15\"\n\nuse num::integer::gcd;\nuse plotters::prelude::*;\nuse std::collections::HashSet;\n\nfn yellowstone_sequence() -> impl std::iter::Iterator<Item = u32> {\n let mut sequence: HashSet<u32> = HashSet::new();\n let mut min = 1;\n let mut n = 0;\n let mut n1 = 0;\n let mut n2 = 0;\n std::iter::from_fn(move || {\n n2 = n1;\n n1 = n;\n if n < 3 {\n n += 1;\n } else {\n n = min;\n while !(!sequence.contains(&n) && gcd(n1, n) == 1 && gcd(n2, n) > 1) {\n n += 1;\n }\n }\n sequence.insert(n);\n while sequence.contains(&min) {\n sequence.remove(&min);\n min += 1;\n }\n Some(n)\n })\n}\n\n// Based on the example in the \"Quick Start\" section of the README file for\n// the plotters library.\nfn plot_yellowstone(filename: &str) -> Result<(), Box<dyn std::error::Error>> {\n let root = BitMapBackend::new(filename, (800, 600)).into_drawing_area();\n root.fill(&WHITE)?;\n let mut chart = ChartBuilder::on(&root)\n .caption(\"Yellowstone Sequence\", (\"sans-serif\", 24).into_font())\n .margin(10)\n .x_label_area_size(20)\n .y_label_area_size(20)\n .build_ranged(0usize..100usize, 0u32..180u32)?;\n chart.configure_mesh().draw()?;\n chart.draw_series(LineSeries::new(\n yellowstone_sequence().take(100).enumerate(),\n &BLUE,\n ))?;\n Ok(())\n}\n\nfn main() {\n println!(\"First 30 Yellowstone numbers:\");\n for y in yellowstone_sequence().take(30) {\n print!(\"{} \", y);\n }\n println!();\n match plot_yellowstone(\"yellowstone.png\") {\n Ok(()) => {}\n Err(error) => eprintln!(\"Error: {}\", error),\n }\n}\n", "language": "Rust" }, { "code": "import scala.util.control.Breaks._\n\n\nobject YellowstoneSequence extends App {\n\n println(s\"First 30 values in the yellowstone sequence:\\n${yellowstoneSequence(30)}\")\n\n def yellowstoneSequence(sequenceCount: Int): List[Int] = {\n var yellowstoneList = List(1, 2, 3)\n var num = 4\n var notYellowstoneList = List[Int]()\n\n while (yellowstoneList.size < sequenceCount) {\n val foundIndex = notYellowstoneList.indexWhere(test =>\n gcd(yellowstoneList(yellowstoneList.size - 2), test) > 1 &&\n gcd(yellowstoneList.last, test) == 1\n )\n\n if (foundIndex >= 0) {\n yellowstoneList = yellowstoneList :+ notYellowstoneList(foundIndex)\n notYellowstoneList = notYellowstoneList.patch(foundIndex, Nil, 1)\n } else {\n breakable({\n while (true) {\n if (gcd(yellowstoneList(yellowstoneList.size - 2), num) > 1 &&\n gcd(yellowstoneList.last, num) == 1) {\n yellowstoneList = yellowstoneList :+ num\n num += 1\n // break the inner while loop\n break\n }\n notYellowstoneList = notYellowstoneList :+ num\n num += 1\n }\n });\n }\n }\n yellowstoneList\n }\n\n def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n}\n", "language": "Scala" }, { "code": "proc gcd {a b} {\n while {$b} {\n lassign [list $b [expr {$a % $b}]] a b\n }\n return $a\n}\n\nproc gen_yellowstones {{maxN 30}} {\n set r {}\n for {set n 1} {$n <= $maxN} {incr n} {\n if {$n <= 3} {\n lappend r $n\n } else {\n ## NB: list indices start at 0, not 1.\n set pred [lindex $r end ] ;# a(n-1): coprime\n set prepred [lindex $r end-1] ;# a(n-2): not coprime\n for {set k 4} {1} {incr k} {\n if {[lsearch -exact $r $k] >= 0} { continue }\n if {1 != [gcd $k $pred ]} { continue }\n if {1 == [gcd $k $prepred]} { continue }\n ## candidate k survived all tests...\n break\n }\n lappend r $k\n }\n }\n return $r\n}\nputs \"The first 30 Yellowstone numbers are:\"\nputs [gen_yellowstones]\n", "language": "Tcl" }, { "code": "fn gcd(xx int, yy int) int {\n mut x := xx\n mut y := yy\n for y != 0 {\n x, y = y, x%y\n }\n return x\n}\n\nfn yellowstone(n int) []int {\n mut m := map[int]bool{}\n mut a := []int{len: n+1}\n for i in 1..4 {\n a[i] = i\n m[i] = true\n }\n mut min := 4\n for c := 4; c <= n; c++ {\n for i := min; ; i++ {\n if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {\n a[c] = i\n m[i] = true\n if i == min {\n min++\n }\n break\n }\n }\n }\n return a[1..]\n}\n\nfn main() {\n mut x := []int{len: 100}\n for i in 0..100 {\n x[i] = i + 1\n }\n y := yellowstone(100)\n println(\"The first 30 Yellowstone numbers are:\")\n println(y[..30])\n}\n", "language": "V-(Vlang)" }, { "code": "Function gcd(a As Long, b As Long) As Long\n If b = 0 Then\n gcd = a\n Exit Function\n End If\n gcd = gcd(b, a Mod b)\nEnd Function\n\nSub Yellowstone()\nDim i As Long, j As Long, k As Long, Y(1 To 30) As Long\n\nY(1) = 1\nY(2) = 2\nY(3) = 3\n\nFor i = 4 To 30\n k = 3\n Do\n k = k + 1\n If gcd(k, Y(i - 2)) = 1 Or gcd(k, Y(i - 1)) > 1 Then GoTo EndLoop:\n For j = 1 To i - 1\n If Y(j) = k Then GoTo EndLoop:\n Next j\n Y(i) = k\n Exit Do\nEndLoop:\n Loop\nNext i\n\nFor i = 1 To 30\n Debug.Print Y(i) & \" \";\nNext i\nEnd Sub\n", "language": "VBA" }, { "code": "import \"./math\" for Int\n\nvar yellowstone = Fn.new { |n|\n var m = {}\n var a = List.filled(n + 1, 0)\n for (i in 1..3) {\n a[i] = i\n m[i] = true\n }\n var min = 4\n for (c in 4..n) {\n var i = min\n while (true) {\n if (!m[i] && Int.gcd(a[c-1], i) == 1 && Int.gcd(a[c-2], i) > 1) {\n a[c] = i\n m[i] = true\n if (i == min) min = min + 1\n break\n }\n i = i + 1\n }\n }\n return a[1..-1]\n}\n\nvar x = List.filled(30, 0)\nfor (i in 0...30) x[i] = i + 1\nvar y = yellowstone.call(30)\nSystem.print(\"The first 30 Yellowstone numbers are:\")\nSystem.print(y)\n", "language": "Wren" }, { "code": "func GCD(N, D); \\Return the greatest common divisor of N and D\nint N, D, R; \\numerator, denominator, remainder\n[if D > N then\n [R:=D; D:=N; N:=R]; \\swap D and N\nwhile D > 0 do\n [R:= rem(N/D);\n N:= D;\n D:= R;\n ];\nreturn N;\n];\n\nint I, A(30+1), N, T;\n[for I:= 1 to 3 do A(I):= I; \\givens\nN:= 4;\nrepeat T:= 4;\n loop [if GCD(T, A(N-1)) = 1 and \\relatively prime\n GCD(T, A(N-2)) # 1 then \\not relatively prime\n [loop [for I:= 1 to N-1 do \\test if in sequence\n if T = A(I) then quit;\n quit;\n ];\n if I = N then \\T is not in sequence so\n [A(N):= T; \\ add it in\n N:= N+1;\n quit;\n ];\n ];\n T:= T+1; \\next trial\n ];\nuntil N > 30;\nfor N:= 1 to 30 do\n [IntOut(0, A(N)); ChOut(0, ^ )];\n\\\\for N:= 1 to 100 do Point(N, A(N)); \\plot demonstration\n]\n", "language": "XPL0" }, { "code": "fcn yellowstoneW{\t// --> iterator\n Walker.zero().tweak(fcn(a,b){\n foreach i in ([1..]){\n if(not b.holds(i) and i.gcd(a[-1])==1 and i.gcd(a[-2]) >1){\n\t a.del(0).append(i);\t// only keep last two terms\n\t b[i]=True;\n\t return(i);\n\t }\n }\n }.fp(List(2,3), Dictionary(1,True, 2,True, 3,True))).push(1,2,3);\n}\n", "language": "Zkl" }, { "code": "println(\"The first 30 entries of the Yellowstone permutation:\");\nyellowstoneW().walk(30).concat(\", \").println();\n", "language": "Zkl" }, { "code": "gnuplot:=System.popen(\"gnuplot\",\"w\");\ngnuplot.writeln(\"unset key; plot '-'\");\nyellowstoneW().pump(1_000, gnuplot.writeln.fp(\" \")); // \" 1\\n\", \" 2\\n\", ...\ngnuplot.writeln(\"e\");\ngnuplot.flush();\nask(\"Hit return to finish\"); gnuplot.close();\n", "language": "Zkl" } ]
Yellowstone-sequence
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Yin_and_yang\nnote: Graphics\n", "language": "00-META" }, { "code": "One well-known symbol of the philosophy of duality known as [[wp:Yin_and_Yang|yin and yang]] is the [[wp:Taijitu|taijitu]].\n\n\n;Task:\n:* &nbsp; Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.\n:* &nbsp; Generate and display the symbol for two different (small) sizes.\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F yinyang(n = 3)\n V radii = [1, 3, 6].map(i -> i * @n)\n V ranges = radii.map(r -> Array(-r .. r))\n V squares = ranges.map(rnge -> multiloop(rnge, rnge, (x, y) -> (x, y)))\n V circles = zip(squares, radii).map((sqrpoints, radius) -> sqrpoints.filter((x, y) -> x*x + y*y <= @radius^2))\n V m = Dict(squares.last, (x, y) -> ((x, y), ‘ ’))\n L(x, y) circles.last\n m[(x, y)] = ‘*’\n L(x, y) circles.last\n I x > 0\n m[(x, y)] = ‘·’\n L(x, y) circles[(len)-2]\n m[(x, y + 3 * n)] = ‘*’\n m[(x, y - 3 * n)] = ‘·’\n L(x, y) circles[(len)-3]\n m[(x, y + 3 * n)] = ‘·’\n m[(x, y - 3 * n)] = ‘*’\n R ranges.last.map(y -> reversed(@ranges.last).map(x -> @@m[(x, @y)]).join(‘’)).join(\"\\n\")\n\nprint(yinyang(2))\nprint(yinyang(1))\n", "language": "11l" }, { "code": "\tpushall\n\t\tMOVE.W #1,D0\t\t\n\t\t;base sprite number, needed by NEOGEO hardware\n\t\t;the yin-yang is 8 sprites total, it is important that\n\t\t;two different sprite objects do not overlap!\n\n\t\tMOVE.W #$F800,D4\t;x position on screen\n\t\tMOVE.W #$1000,D5\t;y position on screen\n\t\tMOVE.W #$0777,D7\t;size parameter\n\t\tJSR generateOAM\n\tpopall\n\t\n\tpushall\n\t\tMOVE.W #$10,D0\n\t\t;base sprite number, needed by NEOGEO hardware\n\t\tMOVE.W #$F800,D4\t;x position on screen\n\t\tMOVE.W #$6000,D5\t;y position on screen\n\t\tMOVE.W #$0444,D7\t;size parameter\n\t\tJSR generateOAM\n\tpopall\n\t\nforever:\n\tbra forever\t\t\t\t;trap the program counter\n\t\ngenerateOAM:\n ;this is just boilerplate required to show hardware sprites to the screen, it's not really relevant to the task.\n ; all this does is copy the sprite data to video memory.\n\n\t;INPUT: D0 = SPRITENUM.\n\t;\t\tD4 = Y POS\n\t;\t\tD5 = X POS\n\t;\t\tD7 = SHRINK FACTOR (SIZE PARAMETER)\n ; THESE VALUES ARE PASSED IN USING THE ABOVE REGISTERS\n\tpushWord D0\n\t\tADD.W #$8000,D0\t\t ;VRAM OFFSET FOR SPRITE 1\n\t\tLEA YinYang_Data,A0 ;LOAD ADDRESS OF SPRITE METADATA\n\t\tMOVE.B (A0)+,D2\t\t\t;SPRITE WIDTH - 8 SPRITES PER OBJECT\n ; (A NEOGEO SPRITE IS ALWAYS 1 TILE WIDE BUT CAN BE OF ARBITRARY HEIGHT)\n\n\t\tMOVE.B (A0)+,D3\t\t\t;SPRITE HEIGHT - 8 TILES PER SPRITE\n\t\tAND.W #$00FF,D3\t\t\t;BYTE SANITIZE SPRITE HEIGHT\n\n\t\tMOVE.W #$0200,$3C0004\n\t\t;INCREMENT THE VALUE IN $3C0000 BY $200 AFTER EACH WRITE TO\n\t\t;\t$3C0002\t\n\n\t\t\n\t\tMOVE.W D0,$3C0000\t\t;SET DESTINATION ADDRESS OF SIZE PARAMETER\n\t\tMOVE.W D7,$3C0002\t\t;WRITE SIZE PARAMETER TO VRAM\n\t\t\n\t\t;AUTO INCS TO $8201 WHICH IS WHERE Y POS MUST BE STORED.\n\t\t\n\t\tMOVE.W D4,D1\t\t\t;GET Y POS\n\t\tOR.W D3,D1\t\t ;COMBINE WITH SPRITE HEIGHT,SINCE NEOGEO STORES THEM TOGETHER AS ONE UNIT.\n\t\tMOVE.W D1,$3C0002\t\t;STORE IN VRAM\n\t\t\n\t\t;AUTO INCS TO $8401 WHICH IS WHERE X POS MUST BE STORED.\n\t\t\n\t\tMOVE.W D5,D1\t\t\t;GET X POS\n\t\tMOVE.W D1,$3C0002\t\t;STORE IN VRAM\n\t\t\n\t\tCMP.B #1,D2 ;IS THIS SPRITE EXACTLY ONE TILE WIDE?\n\t\tBEQ skipChainedOAM\t\t;A 1-WIDE SPRITE NEEDS NO CHAINED SPRITES.\n ; IN THIS EXAMPLE THE YIN-YANGS ARE 8 TILES WIDE, THIS BRANCH IS NEVER TAKEN.\n\t\n\t\tpushWord D2\n\t\t\tSUBQ.B #2,D2\t\t;WE NEED TO LOOP (SPRITE_WIDTH-2) TIMES.\n\n\nloop_generateChainedOAM:\n\t\t\tADDQ.W #1,D0\t\t\t;NEXT SPRITE\n\t\t\tMOVE.W D0,$3C0000\t\t;SET VRAM DESTINATION.\n\t\t\tMOVE.W D7,$3C0002\t\t;EACH STRIP HAS ITS OWN SHRINK VALUE.\n\t\t\tMOVE.W #$0040,$3C0002\t ;MARK THIS SPRITE AS CHAINED. CHAINED SPRITES MOVE AND SCALE AS ONE UNIT.\n\t\t\tMOVE.W #$0000,$3C0002\t ;DUMMY MOVE FOR PADDING.\n\t\t\tDBRA D2,loop_generateChainedOAM\n\t\tpopWord D2\n\t\nskipChainedOAM:\n;NOW DO TILE DATA:\n\t\tMOVE.W #1,$3C0004\t;SET VRAM INC TO 1.\n\t\tSUBQ.B #1,D2\n\t\tSUBQ.B #1,D3\t\t;DBRA CORRECTION\n\tpopWord D0\t\n\t\n\tMOVE.W D0,D1\n\tLSL.W #6,D1\t\t\t;TILE/PAL OFFSET IS SPRITENUM<<6\n\t\n\tLEA YinYang_Tile,A0\t\t;LOAD ADDRESS OF SOURCE DATA\n\tLEA YinYang_Pal,A1\t\t;LOAD ADDRESS OF SOURCE DATA\n\t\n\tMOVE.W D3,D6\t\t\t\n\t;BACKUP D3, IT WILL GET RESTORED AT THE OUTER LOOP\n\t\t\nloop_sprite_OAM:\n\tMOVE.W D1,$3C0000\t\t;SET VRAM ADDRESS\nloop_tile_OAM:\n\tMOVE.W (A0)+,$3C0002\t\t;SET TILE DATA\n\tMOVE.W (A1)+,$3C0002\t\t;SET PAL DATA\n\tDBRA D3,loop_tile_OAM\t\t;NEXT TILE IN STRIP\n\t\n\tMOVE.W D6,D3\t\t\t;RESTORE D3\n\tADD.W #$0040,D1\t\t\t;NEXT SPRITE\n\tDBRA D2,loop_sprite_OAM\t\t;REPEAT UNTIL ALL SPRITES FINISHED.\n\t\n\tRTS\n\t\nYinYang_Data:\n\tDC.B 8,8\t\t;SPRITE WIDTH,SPRITE HEIGHT\n\nYinYang_Tile:\t;EACH NUMBER REPRESENTS A TILE IN THE CHARACTER ROM\n ;THESE VALUES ARE ARBITRARY AND WILL DIFFER DEPENDING ON HOW THE YIN-YANG PIXEL ART IS STORED IN YOUR CARTRIDGE.\n\tDC.W $0060,$0068,$0070,$0078,$0080,$0088,$0090,$0098\n\tDC.W $0061,$0069,$0071,$0079,$0081,$0089,$0091,$0099\n\tDC.W $0062,$006A,$0072,$007A,$0082,$008A,$0092,$009A\n\tDC.W $0063,$006B,$0073,$007B,$0083,$008B,$0093,$009B\n\tDC.W $0064,$006C,$0074,$007C,$0084,$008C,$0094,$009C\n\tDC.W $0065,$006D,$0075,$007D,$0085,$008D,$0095,$009D\n\tDC.W $0066,$006E,$0076,$007E,$0086,$008E,$0096,$009E\n\tDC.W $0067,$006F,$0077,$007F,$0087,$008F,$0097,$009F\nYinYang_Pal:\t;$0100 = USE PALETTE 1.\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n\tDC.W $0100,$0100,$0100,$0100,$0100,$0100,$0100,$0100\n", "language": "68000-Assembly" }, { "code": "INCLUDE \"H6:REALMATH.ACT\"\nINCLUDE \"D2:CIRCLE.ACT\" ;from the Action! Tool Kit\n\nPROC YinYang(INT x BYTE y BYTE r)\n INT i,a,b,rr,r2,rr2,r5,rr5,y1,y2\n REAL tmp1,tmp2\n\n Circle(x,y,r,1)\n\n rr=r*r\n r2=r/2 rr2=rr/4\n Color=1\n FOR i=0 TO r\n DO\n a=rr-i*i\n IntToReal(a,tmp1)\n Sqrt(tmp1,tmp2)\n a=RealToInt(tmp2)\n\n b=rr2-(i-r2)*(i-r2)\n IntToReal(b,tmp1)\n Sqrt(tmp1,tmp2)\n b=RealToInt(tmp2)\n\n Plot(x+b,y-i) DrawTo(x+a,y-i)\n Plot(x-b,y+i) DrawTo(x+a,y+i)\n OD\n\n r5=r/5\n rr5=rr/25\n y1=y-r2 y2=y+r2\n FOR i=0 TO r5\n DO\n a=rr5-i*i\n IntToReal(a,tmp1)\n Sqrt(tmp1,tmp2)\n a=RealToInt(tmp2)\n\n Color=1\n Plot(x-a,y1-i) DrawTo(x+a,y1-i)\n Plot(x-a,y1+i) DrawTo(x+a,y1+i)\n\n Color=0\n Plot(x-a,y2-i) DrawTo(x+a,y2-i)\n Plot(x-a,y2+i) DrawTo(x+a,y2+i)\n OD\nRETURN\n\nPROC Main()\n BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6\n\n Graphics(8+16)\n MathInit()\n COLOR1=$00\n COLOR2=$0F\n\n YinYang(180,120,60)\n YinYang(100,40,30)\n\n DO UNTIL CH#$FF OD\n CH=$FF\nRETURN\n", "language": "Action-" }, { "code": "with Glib; use Glib;\nwith Cairo; use Cairo;\nwith Cairo.Png; use Cairo.Png;\nwith Cairo.Image_Surface; use Cairo.Image_Surface;\n\nprocedure YinYang is\n subtype Dub is Glib.Gdouble;\n\n procedure Draw (C : Cairo_Context; x : Dub; y : Dub; r : Dub) is begin\n Arc (C, x, y, r + 1.0, 1.571, 7.854);\n Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C);\n Arc_Negative (C, x, y - r / 2.0, r / 2.0, 1.571, 4.712);\n Arc (C, x, y + r / 2.0, r / 2.0, 1.571, 4.712);\n Arc_Negative (C, x, y, r, 4.712, 1.571);\n Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C);\n Arc (C, x, y - r / 2.0, r / 5.0, 1.571, 7.854);\n Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C);\n Arc (C, x, y + r / 2.0, r / 5.0, 1.571, 7.854);\n Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C);\n end Draw;\n\n Surface : Cairo_Surface;\n Context : Cairo_Context;\n Status : Cairo_Status;\nbegin\n Surface := Create (Cairo_Format_ARGB32, 200, 200);\n Context := Create (Surface);\n Draw (Context, 120.0, 120.0, 75.0);\n Draw (Context, 35.0, 35.0, 30.0);\n Status := Write_To_Png (Surface, \"YinYangAda.png\");\n pragma Assert (Status = Cairo_Status_Success);\nend YinYang;\n", "language": "Ada" }, { "code": "INT scale x=2, scale y=1;\nCHAR black=\"#\", white=\".\", clear=\" \";\n\nPROC print yin yang = (REAL radius)VOID:(\n\n PROC in circle = (REAL centre x, centre y, radius, x, y)BOOL:\n (x-centre x)**2+(y-centre y)**2 <= radius**2;\n\n PROC (REAL, REAL)BOOL\n in big circle = in circle(0, 0, radius, , ),\n in white semi circle = in circle(0, +radius/2, radius/2, , ),\n in small black circle = in circle(0, +radius/2, radius/6, , ),\n in black semi circle = in circle(0, -radius/2, radius/2, , ),\n in small white circle = in circle(0, -radius/2, radius/6, , );\n\n FOR sy FROM +ROUND(radius * scale y) BY -1 TO -ROUND(radius * scale y) DO\n FOR sx FROM -ROUND(radius * scale x) TO +ROUND(radius * scale x) DO\n REAL x=sx/scale x, y=sy/scale y;\n print(\n IF in big circle(x, y) THEN\n IF in white semi circle(x, y) THEN\n IF in small black circle(x, y) THEN black ELSE white FI\n ELIF in black semi circle(x, y) THEN\n IF in small white circle(x, y) THEN white ELSE black FI\n ELIF x < 0 THEN white ELSE black FI\n ELSE\n clear\n FI\n )\n OD;\n print(new line)\n OD\n);\n\nmain:(\n print yin yang(17);\n print yin yang(8)\n)\n", "language": "ALGOL-68" }, { "code": "pi=3.141592\ns=.5\n\nxp=320:yp=100:size=150\nGOSUB DrawYY\n\nxp=500:yp=40:size=50\nGOSUB DrawYY\n\nEND\n\nDrawYY:\n CIRCLE (xp,yp),size,,,,s\n CIRCLE (xp,yp+size/4),size/8,,,,s\n CIRCLE (xp,yp-size/4),size/8,,,,s\n CIRCLE (xp,yp+size/4),size/2,,.5*pi,1.5*pi,s\n CIRCLE (xp,yp-size/4),size/2,,1.5*pi,2*pi,s\n CIRCLE (xp,yp-size/4),size/2,,0,.5*pi,s\n PAINT (xp,yp-size/4)\n PSET (xp,yp)\n PAINT (xp+size/4,yp)\n RETURN\n", "language": "AmigaBASIC" }, { "code": "0 GOTO 6\n1Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC-X,YC+YTOXC+X,YC+Y:HPLOTXC-Y,YC+XTOXC+Y,YC+X:HPLOTXC-X,YC-YTOXC+X,YC-Y:HPLOTXC-Y,YC-XTOXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN\n2Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC-X,YC+Y:HPLOTXC+X,YC+Y:HPLOTXC-Y,YC+X:HPLOTXC+Y,YC+X:HPLOTXC-X,YC-Y:HPLOTXC+X,YC-Y:HPLOTXC-Y,YC-X:HPLOTXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN\n3Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC,YC+YTOXC+X,YC+Y:HPLOTXC,YC+XTOXC+Y,YC+X:HPLOTXC,YC-YTOXC+X,YC-Y:HPLOTXC,YC-XTOXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN\n\n6 HGR2 : HCOLOR = 3 : HPLOT 0,0 : CALL 62454\n7 XC = 60 : YC = 60 : R = 30 : GOSUB 100YINYANG\n8 XC = 180 : YC = 80 : R = 60 : GOSUB 100YINYANG\n9 END\n\n100 YP = YC : S = R\n110 HCOLOR = 0: GOSUB 3FILLHALFCIRCLE\n120 HCOLOR = 3:YC = YP - S / 2 : R = S / 2 : GOSUB 1FILLCIRCLE\n130 HCOLOR = 0\n140 YC = YP + S / 2 : GOSUB 1FILLCIRCLE\n150 YC = YP - S / 2 : R = S / 6 : GOSUB 1FILLCIRCLE\n160 HCOLOR = 3\n170 YC = YP + S / 2 : GOSUB 1FILLCIRCLE\n180 HCOLOR = 0 : YC = YP : R = S : GOSUB 2CIRCLE\n190 RETURN\n", "language": "Applesoft-BASIC" }, { "code": "/* ARM assembly Raspberry PI */\n/* program yingyang.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n/***************************************************************/\n/* File Constantes see task Include a file for arm assembly */\n/***************************************************************/\n.include \"../constantes.inc\"\n\n.equ SIZEMAXI, 78\n\n/******************************************/\n/* Initialized data */\n/******************************************/\n.data\nszMessDebutPgm: .asciz \"Start program.\\n\"\nszMessFinPgm: .asciz \"Program End ok.\\n\"\nszRetourLigne: .asciz \"\\n\"\n\nszMessErrComm: .asciz \"Incomplete Command line : yingyang <size> \\n\"\n/******************************************/\n/* UnInitialized data */\n/******************************************/\n.bss\nszLine: .skip SIZEMAXI\n/******************************************/\n/* code section */\n/******************************************/\n.text\n.global main\nmain: @ entry of program\n mov fp,sp // copy stack address register r29 fp\n ldr r0,iAdrszMessDebutPgm\n bl affichageMess\n ldr r0,[fp] // parameter number command line\n cmp r0,#1 // correct ?\n ble erreurCommande // error\n\n add r0,fp,#8 // address parameter 2\n ldr r0,[r0]\n bl conversionAtoD\n cmp r0,#SIZEMAXI / 2\n movgt r0,#(SIZEMAXI / 2) - 1 // limit size\n mov r10,r0 // size\n lsr r11,r10,#1 // R = size / 2 radius great circle\n mul r9,r11,r11 // R^2\n lsr r12,r11,#1 // radius median circle\n lsr r8,r12,#1 // radius little circle\n\n mov r2,#0 // y\n ldr r0,iAdrszLine\n1:\n mov r1,#0 // x\n mov r5,#' '\n mov r3,#SIZEMAXI\n11: // move spaces in display line\n strb r5,[r0,r1]\n add r1,#1\n cmp r1,r3\n blt 11b\n mov r1,#0 // x\n2: // begin loop\n sub r3,r1,r11 // x1 = x - R\n mul r4,r3,r3 // x1^2\n sub r5,r2,r11 // y1 = y - R\n mul r6,r5,r5 // y1^2\n add r6,r4 // add x1^2 y1^2\n cmp r6,r9 // compare R^2\n ble 3f\n mov r5,#' ' // not in great circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n3: // compute quadrant\n cmp r1,r11\n bgt 10f // x > R\n cmp r2,r11\n bgt 5f // y > R\n // quadrant 1 x < R and y < R\n sub r5,r2,r12\n mul r7,r5,r5 // y1^2\n add r7,r4 // y1^2 + x1^2\n mul r6,r8,r8 // little r ^2\n cmp r7,r8\n bgt 4f\n mov r5,#' ' // in little circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n4: // in other part of great circle\n mov r5,#'.'\n strb r5,[r0,r1,lsl #1]\n b 20f\n5: // quadrant 3 x < R and y > R\n mov r5,#3\n mul r5,r10,r5\n lsr r5,#2\n sub r6,r2,r5 // y1 - pos little circle (= (size / 3) * 4\n mul r7,r6,r6 // y1^2\n add r7,r4 // y1^2 + x1^2\n mul r6,r8,r8 // r little\n cmp r7,r8\n bgt 6f\n mov r5,#' ' // in little circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n6:\n mul r6,r12,r12\n cmp r7,r6\n bge 7f\n mov r5,#'#' // in median circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n7:\n mov r5,#'.' // not in median\n strb r5,[r0,r1,lsl #1]\n b 20f\n10:\n cmp r2,r11\n bgt 15f\n // quadrant 2\n sub r5,r2,r12 // y - center little\n mul r6,r5,r5\n add r7,r4,r6\n mul r6,r8,r8\n cmp r7,r6\n bge 11f\n mov r5,#' ' // in little circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n11:\n mul r6,r12,r12\n cmp r7,r6\n bge 12f\n mov r5,#'.' // in median circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n12:\n mov r5,#'#' // in great circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n15:\n // quadrant 4\n mov r5,#3\n mul r5,r10,r5\n lsr r5,#2\n sub r6,r2,r5 // y1 - pos little\n mul r7,r6,r6 // y1^2\n add r7,r4 // y1^2 + x1^2\n mul r6,r8,r8 // little r ^2\n cmp r7,r8\n bgt 16f\n mov r5,#' ' // in little circle\n strb r5,[r0,r1,lsl #1]\n b 20f\n16:\n mov r5,#'#'\n strb r5,[r0,r1,lsl #1]\n b 20f\n20:\n add r1,#1 // increment x\n cmp r1,r10 // size ?\n ble 2b // no -> loop\n lsl r1,#1\n mov r5,#'\\n' // add return line\n strb r5,[r0,r1]\n add r1,#1\n mov r5,#0 // add final zéro\n strb r5,[r0,r1]\n bl affichageMess // and display line\n add r2,r2,#1 // increment y\n cmp r2,r10 // size ?\n ble 1b // no -> loop\n\n ldr r0,iAdrszMessFinPgm\n bl affichageMess\n b 100f\nerreurCommande:\n ldr r0,iAdrszMessErrComm\n bl affichageMess\n mov r0,#1 // error code\n b 100f\n100: // standard end of the program\n mov r0, #0 // return code\n mov r7, #EXIT // request to exit program\n svc 0 // perform the system call\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessFinPgm: .int szMessFinPgm\niAdrszMessErrComm: .int szMessErrComm\niAdrszLine: .int szLine\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "unitsize(1 inch);\n\nfill(scale(6)*unitsquare, invisible);\n\npicture yinyang(pair center, real radius) {\n picture p;\n fill(p, unitcircle, white);\n fill(p, arc(0, S, N) -- cycle, black);\n fill(p, circle(N/2, 1/2), white);\n fill(p, circle(S/2, 1/2), black);\n fill(p, circle(N/2, 1/5), black);\n fill(p, circle(S/2, 1/5), white);\n draw(p, unitcircle, linewidth((1/32) * inch) + gray(0.5));\n return shift(center) * scale(radius) * p;\n}\n\nadd(yinyang((1 + 1/4, 4 + 3/4), 1));\nadd(yinyang((3 + 3/4, 2 + 1/4), 2));\n", "language": "Asymptote" }, { "code": "Yin_and_Yang(50, 50, A_ScriptDir \"\\YinYang1.png\")\nYin_and_Yang(300, 300,A_ScriptDir \"\\YinYang2.png\")\n\nYin_and_Yang(width, height, fileName\n\t, color1=0xFFFFFFFF, color2=0xFF000000, outlineWidth=1){\n\n\tpToken \t := gdip_Startup()\n\tpBitmap\t := gdip_CreateBitmap(w := width, h := height)\n\tw-=1, h-=1\n\tpGraphics:= gdip_GraphicsFromImage(pBitmap)\n\tpBrushW\t := gdip_BrushCreateSolid(color1)\n\tpBrushB\t := gdip_BrushCreateSolid(color2)\n\n\tgdip_SetSmoothingMode(pGraphics, 4) \t\t\t; Antialiasing\n\n\tIf (outlineWidth){\n\t\tpPen := gdip_CreatePen(0xFF000000, outlineWidth)\n\t\tgdip_DrawEllipse(pGraphics, pPen, 0, 0, w, h)\n\t\tgdip_DeletePen(pPen)\n\t}\n\n\tgdip_FillPie(pGraphics, pBrushB, 0, 0, w, h, -90, 180)\n\tgdip_FillPie(pGraphics, pBrushW, 0, 0, w, h, 90, 180)\n\tgdip_FillEllipse(pGraphics, pBrushB, w//4, h//2, w//2, h//2)\n\tgdip_FillEllipse(pGraphics, pBrushW, w//4, 0 , w//2, h//2)\n\tgdip_FillEllipse(pGraphics, pBrushB, 5*w//12, h//6, w//6, h//6)\n\tgdip_FillEllipse(pGraphics, pBrushW, 5*w//12, 4*h//6,w//6,h//6)\n\n\tr := gdip_SaveBitmapToFile(pBitmap, filename)\n\n\t; cleanup:\n\tgdip_DeleteBrush(pBrushW), gdip_deleteBrush(pBrushB)\n\tgdip_DisposeImage(pBitmap)\n\tgdip_DeleteGraphics(pGraphics)\n\tgdip_Shutdown(pToken)\n\treturn r\n}\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f YIN_AND_YANG.AWK\n# converted from PHL\nBEGIN {\n yin_and_yang(16)\n yin_and_yang(8)\n exit(0)\n}\nfunction yin_and_yang(radius, black,white,scale_x,scale_y,sx,sy,x,y) {\n black = \"#\"\n white = \".\"\n scale_x = 2\n scale_y = 1\n for (sy = radius*scale_y; sy >= -(radius*scale_y); sy--) {\n for (sx = -(radius*scale_x); sx <= radius*scale_x; sx++) {\n x = sx / scale_x\n y = sy / scale_y\n if (in_big_circle(radius,x,y)) {\n if (in_white_semi_circle(radius,x,y)) {\n printf(\"%s\",(in_small_black_circle(radius,x,y)) ? black : white)\n }\n else if (in_black_semi_circle(radius,x,y)) {\n printf(\"%s\",(in_small_white_circle(radius,x,y)) ? white : black)\n }\n else {\n printf(\"%s\",(x<0) ? white : black)\n }\n }\n else {\n printf(\" \")\n }\n }\n printf(\"\\n\")\n }\n}\nfunction in_circle(center_x,center_y,radius,x,y) {\n return (x-center_x)*(x-center_x)+(y-center_y)*(y-center_y) <= radius*radius\n}\nfunction in_big_circle(radius,x,y) {\n return in_circle(0,0,radius,x,y)\n}\nfunction in_black_semi_circle(radius,x,y) {\n return in_circle(0,0-radius/2,radius/2,x,y)\n}\nfunction in_white_semi_circle(radius,x,y) {\n return in_circle(0,radius/2,radius/2,x,y)\n}\nfunction in_small_black_circle(radius,x,y) {\n return in_circle(0,radius/2,radius/6,x,y)\n}\nfunction in_small_white_circle(radius,x,y) {\n return in_circle(0,0-radius/2,radius/6,x,y)\n}\n", "language": "AWK" }, { "code": "graphsize 800, 600\nclg\n\nsubroutine Taijitu(x, y, r)\n\tcolor black: circle(x, y, 2*r+1)\n\tchord x-2*r, y-2*r, 4*r, 4*r, radians(0), radians(180)\n\tcolor white\n\tchord x-2*r, y-2*r, 4*r, 4*r, radians(180), radians(180)\n\tcircle(x, y-r, r-1)\n\tcolor black: circle(x, y+r, r-1)\n\tcircle(x, y-r, r/3)\n\tcolor white: circle(x, y+r, r/3)\nend subroutine\n\ncall Taijitu(110, 110, 45)\ncall Taijitu(500, 300, 138)\nend\n", "language": "BASIC256" }, { "code": " PROCyinyang(200, 200, 100)\n PROCyinyang(700, 400, 300)\n END\n\n DEF PROCyinyang(xpos%, ypos%, size%)\n CIRCLE xpos%, ypos%, size%\n LINE xpos%, ypos%+size%, xpos%, ypos%-size%\n FILL xpos%+size%/2, ypos%\n CIRCLE FILL xpos%, ypos%-size%/2, size%/2+2\n GCOL 15\n CIRCLE FILL xpos%, ypos%+size%/2, size%/2+2\n CIRCLE FILL xpos%, ypos%-size%/2, size%/6+2\n GCOL 0\n CIRCLE FILL xpos%, ypos%+size%/2, size%/6+2\n CIRCLE xpos%, ypos%, size%\n ENDPROC\n", "language": "BBC-BASIC" }, { "code": "get \"libhdr\"\n\nlet circle(x, y, c, r) = (r*r) >= (x/2) * (x/2) + (y-c) * (y-c)\n\nlet pixel(x, y, r) =\n circle(x, y, -r/2, r/6) -> '#',\n circle(x, y, r/2, r/6) -> '.',\n circle(x, y, -r/2, r/2) -> '.',\n circle(x, y, r/2, r/2) -> '#',\n circle(x, y, 0, r) -> x<0 -> '.', '#',\n ' '\n\nlet yinyang(r) be\n for y = -r to r\n $( for x = -2*r to 2*r do\n wrch(pixel(x,y,r))\n wrch('*N')\n $)\n\nlet start() be\n$( yinyang(4)\n yinyang(8)\n$)\n", "language": "BCPL" }, { "code": "55+:#. 00p:2*10p:2/20p6/30p01v\n@#!`g01:+1g07,+55$<v0-g010p07_\n0g-20g+:*+30g:*`v ^_:2/:*:70g0\n3+*:-g02-g00g07:_ 0v v!`*:g0\ng-20g+:*+20g:*`>v> ^ v1_:70g00\n2+*:-g02-g00g07:_ 1v v!`*:g0\ng-:*+00g:*`#v_$:0`!0\\v0_:70g00\n0#+g#1,#$< > 2 #^>#g>#04#1+#:\n", "language": "Befunge" }, { "code": "#include <stdio.h>\n\nvoid draw_yinyang(int trans, double scale)\n{\n\tprintf(\"<use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>\",\n\t\ttrans, trans, scale);\n}\n\nint main()\n{\tprintf(\n\t\"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\\n\"\n\t\"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\\n\"\n\t\"\t'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\\n\"\n\t\"<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\\n\"\n\t\"\txmlns:xlink='http://www.w3.org/1999/xlink'\\n\"\n\t\"\t\twidth='30' height='30'>\\n\"\n\t\"\t<defs><g id='y'>\\n\"\n\t\"\t\t<circle cx='0' cy='0' r='200' stroke='black'\\n\"\n\t\"\t\t\tfill='white' stroke-width='1'/>\\n\"\n\t\"\t\t<path d='M0 -200 A 200 200 0 0 0 0 200\\n\"\n\t\"\t\t\t100 100 0 0 0 0 0 100 100 0 0 1 0 -200\\n\"\n\t\"\t\t\tz' fill='black'/>\\n\"\n\t\"\t\t<circle cx='0' cy='100' r='33' fill='white'/>\\n\"\n\t\"\t\t<circle cx='0' cy='-100' r='33' fill='black'/>\\n\"\n\t\"\t</g></defs>\\n\");\n\tdraw_yinyang(20, .05);\n\tdraw_yinyang(8, .02);\n\tprintf(\"</svg>\");\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n\nbool circle(int x, int y, int c, int r) {\n return (r * r) >= ((x = x / 2) * x) + ((y = y - c) * y);\n}\n\nchar pixel(int x, int y, int r) {\n if (circle(x, y, -r / 2, r / 6)) {\n return '#';\n }\n if (circle(x, y, r / 2, r / 6)) {\n return '.';\n }\n if (circle(x, y, -r / 2, r / 2)) {\n return '.';\n }\n if (circle(x, y, r / 2, r / 2)) {\n return '#';\n }\n if (circle(x, y, 0, r)) {\n if (x < 0) {\n return '.';\n } else {\n return '#';\n }\n }\n return ' ';\n}\n\nvoid yinYang(int r) {\n for (int y = -r; y <= r; y++) {\n for (int x = -2 * r; x <= 2 * r; x++) {\n std::cout << pixel(x, y, r);\n }\n std::cout << '\\n';\n }\n}\n\nint main() {\n yinYang(18);\n return 0;\n}\n", "language": "C++" }, { "code": " public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n Paint += Form1_Paint;\n }\n\n private void Form1_Paint(object sender, PaintEventArgs e)\n {\n Graphics g = e.Graphics;\n g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n\n DrawTaijitu(g, new Point(50, 50), 200, true);\n DrawTaijitu(g, new Point(10, 10), 60, true);\n }\n\n private void DrawTaijitu(Graphics g, Point pt, int width, bool hasOutline)\n {\n g.FillPie(Brushes.Black, pt.X, pt.Y, width, width, 90, 180);\n g.FillPie(Brushes.White, pt.X, pt.Y, width, width, 270, 180);\n float headSize = Convert.ToSingle(width * 0.5);\n float headXPosition = Convert.ToSingle(pt.X + (width * 0.25));\n g.FillEllipse(Brushes.Black, headXPosition, Convert.ToSingle(pt.Y), headSize, headSize);\n g.FillEllipse(Brushes.White, headXPosition, Convert.ToSingle(pt.Y + (width * 0.5)), headSize, headSize);\n float headBlobSize = Convert.ToSingle(width * 0.125);\n float headBlobXPosition = Convert.ToSingle(pt.X + (width * 0.4375));\n g.FillEllipse(Brushes.White, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.1875)), headBlobSize, headBlobSize);\n g.FillEllipse(Brushes.Black, headBlobXPosition, Convert.ToSingle(pt.Y + (width * 0.6875)), headBlobSize, headBlobSize);\n if (hasOutline) g.DrawEllipse(Pens.Black, pt.X, pt.Y, width, width);\n }\n }\n", "language": "C-sharp" }, { "code": "taijitu = cluster is make\n rep = null\n\n circle = proc (x,y,c,r: int) returns (bool)\n return (r**2 >= (x/2)**2 + (y-c)**2)\n end circle\n\n pixel = proc (x,y,r: int) returns (char)\n if circle(x,y,-r/2,r/6) then return('#')\n elseif circle(x,y, r/2,r/6) then return('.')\n elseif circle(x,y,-r/2,r/2) then return('.')\n elseif circle(x,y, r/2,r/2) then return('#')\n elseif circle(x,y, 0, r) then\n if x<0 then return('.') else return('#') end\n end\n return(' ')\n end pixel\n\n make = proc (r: int) returns (string)\n chars: array[char] := array[char]$predict(1, r*r*2+r)\n for y: int in int$from_to(-r, r) do\n for x: int in int$from_to(-2*r, 2*r) do\n array[char]$addh(chars, pixel(x,y,r))\n end\n array[char]$addh(chars, '\\n')\n end\n return (string$ac2s(chars))\n end make\nend taijitu\n\nstart_up = proc ()\n po: stream := stream$primary_output()\n stream$putl(po, taijitu$make(4))\n stream$putl(po, taijitu$make(8))\nend start_up\n", "language": "CLU" }, { "code": "0 REM VIC-20 WITH SUPEREXPANDER\n10 GRAPHIC 2\n20 COLOR 0,1,1,1\n30 X=312:Y=500:XR=310:YR=464:GOSUB 100\n40 X=812:Y=750:XR=186:YR=248:GOSUB 100\n50 GET K$:IF K$=\"\" THEN 50\n60 GRAPHIC 0\n70 END\n100 CIRCLE 1,X,Y,XR,YR\n110 CIRCLE 1,X,Y-YR/2,XR/2,YR/2,75,25\n120 CIRCLE 1,X,Y+YR/2,XR/2,YR/2,25,75\n130 CIRCLE 1,X,Y-YR/2,XR/8+1,YR/8+1\n140 CIRCLE 1,X,Y+YR/2,XR/8-1,YR/8-1\n150 PAINT 1,X,Y+YR/2\n160 PAINT 1,X-XR/2,Y\n170 RETURN\n", "language": "Commodore-BASIC" }, { "code": "0 REM C64 WITH SIMONS' BASIC\n10 COLOUR 0,0\n20 HIRES 1,0\n30 X=100:Y=100:XR=98:YR=74:GOSUB 100\n40 X=260:Y=150:XR=48:YR=36:GOSUB 100\n50 GET K$:IF K$=\"\" THEN 50\n60 END\n100 CIRCLE X,Y,XR,YR,1\n110 ARC X,Y+YR/2,180,360,1,XR/2,YR/2+1,1\n120 ARC X,Y-YR/2,0,180,1,XR/2,YR/2+1,1\n130 CIRCLE X,Y-YR/2,XR/8,YR/8,1\n140 CIRCLE X,Y+YR/2,XR/8,YR/8,1\n150 PAINT X,Y+YR/2,1\n160 PAINT X-XR/2,Y,1\n170 RETURN\n", "language": "Commodore-BASIC" }, { "code": "0 REM BASIC 3.5,7.0\n10 COLOR 0,1:COLOR 1,2:COLOR 4,1\n20 GRAPHIC 1,1\n30 X=100:Y=100:XR=98:YR=74:GOSUB 100\n40 X=260:Y=150:XR=48:YR=36:GOSUB 100\n50 GETKEY K$\n60 END\n100 CIRCLE 1,X,Y,XR,YR\n110 CIRCLE 1,X,Y-YR/2,XR/2,YR/2,0,180\n120 CIRCLE 1,X,Y+YR/2,XR/2,YR/2,180,360\n130 CIRCLE 1,X,Y-YR/2,XR/8,YR/8\n140 CIRCLE 1,X,Y+YR/2,XR/8,YR/8\n150 PAINT 1,X,Y+YR/2\n160 PAINT 1,X-XR/2,Y\n170 RETURN\n", "language": "Commodore-BASIC" }, { "code": "import std.stdio, std.algorithm, std.array, std.math, std.range,\n std.conv, std.typecons;\n\nstring yinYang(in int n) pure /*nothrow @safe*/ {\n enum : char { empty = ' ', white = '.', black = '#' }\n\n const radii = [1, 3, 6].map!(i => i * n).array;\n auto ranges = radii.map!(r => iota(-r, r + 1).array).array;\n alias V = Tuple!(int,\"x\", int,\"y\");\n V[][] squares, circles;\n squares = ranges.map!(r => cartesianProduct(r, r).map!V.array).array;\n\n foreach (sqrPoints, const radius; zip(squares, radii))\n circles ~= sqrPoints.filter!(p => p[].hypot <= radius).array;\n auto m = squares[$ - 1].zip(empty.repeat).assocArray;\n foreach (immutable p; circles[$ - 1])\n m[p] = black;\n foreach (immutable p; circles[$ - 1])\n if (p.x > 0)\n m[p] = white;\n foreach (immutable p; circles[$ - 2]) {\n m[V(p.x, p.y + 3 * n)] = black;\n m[V(p.x, p.y - 3 * n)] = white;\n }\n foreach (immutable p; circles[$ - 3]) {\n m[V(p.x, p.y + 3 * n)] = white;\n m[V(p.x, p.y - 3 * n)] = black;\n }\n return ranges[$ - 1]\n .map!(y => ranges[$ - 1].retro.map!(x => m[V(x, y)]).text)\n .join('\\n');\n}\n\nvoid main() {\n 2.yinYang.writeln;\n 1.yinYang.writeln;\n}\n", "language": "D" }, { "code": "void yinYang(in int r) {\n import std.stdio, std.math;\n\n foreach (immutable y; -r .. r + 1) {\n foreach (immutable x; -2 * r .. 2 * r + 1) {\n enum circle = (in int c, in int r) pure nothrow @safe @nogc =>\n r ^^ 2 >= (x / 2) ^^ 2 + (y - c) ^^ 2;\n write(circle(-r / 2, r / 6) ? '#' :\n circle( r / 2, r / 6) ? '.' :\n circle(-r / 2, r / 2) ? '.' :\n circle( r / 2, r / 2) ? '#' :\n circle( 0, r ) ? \"#.\"[x < 0] :\n ' ');\n }\n writeln;\n }\n}\n\nvoid main() {\n 16.yinYang;\n}\n", "language": "D" }, { "code": "/* Imports and Exports */\nimport 'dart:io';\n\n/* Main Block */\nint main() {\n yinYang(18);\n return 0;\n}\n\n/* Function Definitions */\nbool circle(int x, int y, int c, int r) {\n return (r * r) >= ((x = x ~/ 2) * x) + ((y = y - c) * y);\n}\n\nString pixel(int x, int y, int r) {\n if (circle(x, y, -r ~/ 2, r ~/ 6)) {\n return '#';\n }\n if (circle(x, y, r ~/ 2, r ~/ 6)) {\n return '.';\n }\n if (circle(x, y, -r ~/ 2, r ~/ 2)) {\n return '.';\n }\n if (circle(x, y, r ~/ 2, r ~/ 2)) {\n return '#';\n }\n if (circle(x, y, 0, r)) {\n if (x < 0) {\n return '.';\n } else {\n return '#';\n }\n }\n return ' ';\n}\n\nvoid yinYang(int r) {\n for (int y = -r; y <= r; y++) {\n for (int x = -2 * r; x <= 2 * r; x++) {\n stdout.write(pixel(x, y, r));\n }\n stdout.write('\\n');\n }\n}\n", "language": "Dart" }, { "code": "import 'dart:math' show pi;\nimport 'package:flutter/material.dart';\n\nPath yinYang(double r, double x, double y, [double th = 1.0]) {\n cR(double dY, double radius) => Rect.fromCircle(center: Offset(x, y + dY), radius: radius);\n return Path()\n ..fillType = PathFillType.evenOdd\n ..addOval(cR(0, r + th))\n ..addOval(cR(r / 2, r / 6))\n ..addOval(cR(-r / 2, r / 6))\n ..addArc(cR(0, r), -pi / 2, -pi)\n ..addArc(cR(r / 2, r / 2), pi / 2, pi)\n ..addArc(cR(-r / 2, r / 2), pi / 2, -pi);\n}\n\nvoid main() => runApp(CustomPaint(painter: YinYangPainter()));\n\nclass YinYangPainter extends CustomPainter {\n @override\n void paint(Canvas canvas, Size size) {\n final fill = Paint()..style = PaintingStyle.fill;\n canvas\n ..drawColor(Colors.white, BlendMode.src)\n ..drawPath(yinYang(50.0, 60, 60), fill)\n ..drawPath(yinYang(20.0, 140, 30), fill);\n }\n\n @override\n bool shouldRepaint(CustomPainter oldDelegate) => true;\n}\n", "language": "Dart" }, { "code": "import 'package:flutter/material.dart';\n\nconst color = [Colors.black, Colors.white];\n\nWidget cR(int iColor, double r, {Widget? child}) => DecoratedBox(\n decoration: BoxDecoration(color: color[iColor], shape: BoxShape.circle),\n child: SizedBox.square(dimension: r * 2, child: Center(child: child)));\n\nWidget yinYang(double r, [double th = 1.0]) => Padding(\n padding: const EdgeInsets.all(5),\n child: ClipOval(\n child: cR(0, r + th,\n child: cR(1, r,\n child: Stack(alignment: Alignment.center, children: [\n Container(color: color[0], margin: EdgeInsets.only(left: r)),\n Column(children: List.generate(2, (i) => cR(1 - i, r / 2, child: cR(i, r / 6))))\n ])))));\n\nvoid main() => runApp(MaterialApp(\n home: ColoredBox(color: color[1], child: Wrap(children: [yinYang(50), yinYang(20)]))));\n", "language": "Dart" }, { "code": "procedure DrawCircle(Canvas: TCanvas; Center: TPoint; Radius: integer);\n{Draw circle at specified center and size (Radius)}\nvar R: TRect;\nbegin\nR.TopLeft:=Center;\nR.BottomRight:=Center;\nInflateRect(R,Radius,Radius);\nCanvas.Ellipse(R);\nend;\n\nprocedure DrawYinYang(Canvas: TCanvas; Center: TPoint; Radius: integer);\n{Draw Yin-Yang symbol at specified center and size (Radius)}\nvar X1,Y1,X2,Y2,X3,Y3,X4,Y4: integer;\nvar R2,R6: integer;\nbegin\nR2:=Radius div 2;\nR6:=Radius div 6;\nCanvas.Pen.Width:=3;\n\n{Draw outer circle}\nDrawCircle(Canvas,Center,Radius);\n\n{Draw bottom half circle}\nX1:=Center.X - R2; Y1:=Center.Y;\nX2:=Center.X + R2; Y2:=Center.Y + Radius;\nX3:=Center.X; Y3:=Center.Y;\nX4:=Center.X; Y4:=Center.Y + Radius;\nCanvas.Arc(X1,Y1, X2,Y2, X3,Y3, X4, Y4);\n\n{Draw top half circle}\nX1:=Center.X - R2; Y1:=Center.Y;\nX2:=Center.X + R2; Y2:=Center.Y - Radius;\nX3:=Center.X; Y3:=Center.Y;\nX4:=Center.X; Y4:=Center.Y- Radius;\nCanvas.Arc(X1,Y1, X2,Y2, X3,Y3, X4, Y4);\n\n{Fill right half with black}\nCanvas.Brush.Color:=clBlack;\nCanvas.FloodFill(Center.X,Center.Y+5,clWhite, fsSurface);\n\n{Draw top small circle}\nDrawCircle(Canvas, Point(Center.X, Center.Y-R2), R6);\n\n{Draw bottom small circle}\nCanvas.Brush.Color:=clWhite;\nDrawCircle(Canvas, Point(Center.X, Center.Y+R2), R6);\nend;\n\n\nprocedure ShowYinYang(Image: TImage);\nbegin\nDrawYinYang(Image.Canvas,Point(75,75),50);\nDrawYinYang(Image.Canvas,Point(200,200),100);\nImage.Invalidate;\nend;\n", "language": "Delphi" }, { "code": "proc circle(int x, c, y, r) bool:\n r*r >= (x/2)*(x/2) + (y-c)*(y-c)\ncorp\n\nproc pixel(int x, y, r) char:\n if circle(x, y, -r/2, r/6) then '\\#'\n elif circle(x, y, r/2, r/6) then '.'\n elif circle(x, y, -r/2, r/2) then '.'\n elif circle(x, y, r/2, r/2) then '\\#'\n elif circle(x, y, 0, r) then\n if x<0 then '.' else '\\#' fi\n else ' '\n fi\ncorp\n\nproc yinyang(int r) void:\n int x, y;\n for y from -r upto r do\n for x from -2*r upto 2*r do\n write(pixel(x, y, r))\n od;\n writeln()\n od\ncorp\n\nproc main() void:\n yinyang(4);\n yinyang(8)\ncorp\n", "language": "Draco" }, { "code": "type\n TColorFuncX = function (x : Integer) : Integer;\n\ntype\n TSquareBoard = class\n Scale : Integer;\n Pix : array of array of Integer;\n\n constructor Create(aScale : Integer);\n begin\n Scale := aScale;\n Pix := new Integer[aScale*12+1, aScale*12+1];\n end;\n\n method Print;\n begin\n var i, j : Integer;\n for i:=0 to Pix.High do begin\n for j:=0 to Pix.High do begin\n case Pix[j, i] of\n 1 : Print('.');\n 2 : Print('#');\n else\n Print(' ');\n end;\n end;\n PrintLn('');\n end;\n end;\n\n method DrawCircle(cx, cy, cr : Integer; color : TColorFuncX);\n begin\n var rr := Sqr(cr*Scale);\n var x, y : Integer;\n for x := 0 to Pix.High do begin\n for y := 0 to Pix.High do begin\n if Sqr(x-cx*Scale)+Sqr(y-cy*Scale)<=rr then\n Pix[x, y] := color(x);\n end;\n end;\n end;\n\n method ColorHalf(x : Integer) : Integer;\n begin\n if (x<6*Scale) then\n Result:=1\n else Result:=2;\n end;\n\n method ColorYin(x : Integer) : Integer;\n begin\n Result:=2;\n end;\n\n method ColorYang(x : Integer) : Integer;\n begin\n Result:=1;\n end;\n\n method YinYang;\n begin\n DrawCircle(6, 6, 6, ColorHalf);\n DrawCircle(6, 3, 3, ColorYang);\n DrawCircle(6, 9, 3, ColorYin);\n DrawCircle(6, 9, 1, ColorYang);\n DrawCircle(6, 3, 1, ColorYin);\n end;\n\n end;\n\nvar sq := new TSquareBoard(2);\nsq.YinYang;\nsq.Print;\n\nsq := new TSquareBoard(1);\nsq.YinYang;\nsq.Print;\n", "language": "DWScript" }, { "code": "proc circ r c . .\n color c\n circle r\n.\nproc yinyang x y r . .\n move x y\n circ 2 * r 000\n color 999\n circseg 2 * r 90 -90\n move x y - r\n circ r 000\n circ r / 3 999\n move x y + r\n circ r 999\n circ r / 3 000\n.\nbackground 555\nclear\nyinyang 20 20 6\nyinyang 50 60 14\n", "language": "EasyLang" }, { "code": "(x,y,&r,&g,&b) {\n r=255; g=0; b=0;\n // Notice rad is radius square\n YinYang(x-8,y+8,7,r,g,b);\n YinYang(x-25,y+24,15,r,g,b);\n}//main\n\nYinYang(x,y,rad,&r,&g,&b) {\n circ0 = Circle(x, y, rad);\n circ1 = Circle(x, y-rad/2, rad/2);\n circ2 = Circle(x, y-rad/2, rad/6);\n circ3 = Circle(x, y+rad/2, rad/2);\n circ4 = Circle(x, y+rad/2, rad/6);\n if (circ0 <= rad) { if (x<0) { r=g=b=255; } else {r=g=b=0; } }\n if (circ1 <= rad/6) { r=g=b=255; }\n if (circ2 <= rad/6) { r=g=b=0; }\n if (circ3 <= rad/2) { r=g=b=0; }\n if (circ4 <= rad/6) { r=g=b=255; }\n}\n\nCircle(x,y,r) { return (x^2+y^2)-r^2 }\n", "language": "Evaldraw" }, { "code": "()\n{\n cls(0x646464);\n YinYang(80, 80, 70);\n YinYang(240, 240, 150);\n}\n\ncircle(x0, y0, r, col_left, col_right) {\n for(y=-r; y<r; y++)\n for(x=-r; x<r; x++) {\n if (x^2 + y^2 <= r^2) {\n if (x<0) setcol(col_left); else setcol(col_right);\n setpix(x+x0, y+y0);\n }\n }\n}\n\nYinYang(x0, y0, r) {\n white = rgb(255,255,255);\n black = 0;\n circle(x0, y0, r, white, black);\n circle(x0, y0-r/2, r/2, white, white);\n circle(x0, y0-r/2, r/6, black, black);\n circle(x0, y0+r/2, r/2, black, black);\n circle(x0, y0+r/2, r/6, white, white);\n}\n", "language": "Evaldraw" }, { "code": ": circle ( x y r h -- f )\nrot - dup *\nrot dup * +\nswap dup * swap\n< invert\n;\n\n: pixel ( r x y -- r c )\n2dup 4 pick 6 / 5 pick 2 / negate circle if 2drop '#' exit then\n2dup 4 pick 6 / 5 pick 2 / circle if 2drop '.' exit then\n2dup 4 pick 2 / 5 pick 2 / negate circle if 2drop '.' exit then\n2dup 4 pick 2 / 5 pick 2 / circle if 2drop '#' exit then\n2dup 4 pick 0 circle if\n drop 0< if '.' exit else '#' exit then\n then\n2drop bl\n;\n\n: yinyang ( r -- )\ndup dup 1+ swap -1 * do\n cr\n dup dup 2 * 1+ swap -2 * do\n I 2 / J pixel emit\n loop\nloop drop\n;\n", "language": "Forth" }, { "code": "[PRAGMA] usestackflood \\ don't use additional memory for fill\ninclude lib/graphics.4th \\ load the graphics library\ninclude lib/gcircle.4th \\ we need a full circle\ninclude lib/garccirc.4th \\ we need a partial circle\ninclude lib/gflood.4th \\ we need a flood fill\n\n600 pic_width ! 600 pic_height ! \\ set canvas size\ncolor_image 255 whiteout black \\ paint black on white\n\n300 300 296 circle \\ make the large circle\n152 300 49 circle \\ make the top small circle\n448 300 49 circle \\ make the bottom small circle\n\n152 300 149 -15708 31416 arccircle \\ create top teardrop\n448 300 148 15708 31416 arccircle \\ create bottom teardrop\n\n150 300 flood \\ fill the top small circle\n500 300 flood \\ fill the bottom teardrop\n\n300 300 295 circle \\ let's make it a double line width\n\ns\" gyinyang.ppm\" save_image \\ save the image\n", "language": "Forth" }, { "code": "Screen 19\nColor ,7\nCls\n\nSub Taijitu(x As Integer, y As Integer, r As Integer)\n Circle(x, y), 2 * r, 0,,,, F\n Line (x, y - 2 * r) - (x, y + 2 * r), 7, B\n Paint (x - r, y), 15, 7\n Circle(x, y - r), r - 1, 15,,,, F\n Circle(x, y + r), r - 1, 0,,,, F\n Circle(x, y - r), r / 3, 0,,,, F\n Circle(x, y + r), r / 3, 15,,,, F\nEnd Sub\n\nTaijitu(110, 110, 45)\nTaijitu(500, 300, 138)\nEnd\n", "language": "FreeBASIC" }, { "code": "_window = 1\nbegin enum output 1\n _imageView1\n _imageView2\nend enum\n\nlocal fn YinYangImage( size as float ) as ImageRef\n CFDictionaryRef attributes = @{NSFontAttributeName:fn FontWithName( @\"Menlo\", size ), NSBackgroundColorAttributeName:fn ColorClear}\n CFMutableAttributedStringRef aString = fn MutableAttributedStringWithAttributes( @\"\\u262F\", attributes )\n ImageRef image = fn ImageWithSize( fn AttributedStringSize( aString ) )\n ImageLockFocus( image )\n GraphicsContextSaveGraphicsState\n AttributedStringDrawAtPoint( aString, fn CGPointMake( 0, 0 ) )\n GraphicsContextRestoreGraphicsState\n ImageUnlockFocus( image )\nend fn = image\n\nvoid local fn BuildWindow\n CGRect r = fn CGRectMake( 0, 0, 300, 200 )\n window _window, @\"Rosetta Code Yin and Yang\", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable\n WindowSetBackgroundColor( _window, fn ColorWhite )\n\n ImageRef yinyang = fn YinYangImage( 250.0 )\n r = fn CGRectMake( 20, 10, 170, 180 )\n imageview _imageView1, YES, yinyang, r, NSImageScaleNone, NSImageAlignCenter, NSImageFrameNone, _window\n\n r = fn CGRectMake( 190, 90, 100, 100 )\n imageview _imageView2, YES, yinyang, r, NSImageScaleProportionallyDown, NSImageAlignCenter, NSImageFrameNone, _window\nend fn\n\nvoid local fn DoDialog( ev as long, tag as long, wnd as long )\n select ( ev )\n case _windowWillClose : end\n end select\nend fn\n\non dialog fn DoDialog\n\nfn BuildWindow\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Form_Open()\nDim hPictureBox As PictureBox\nDim siCount As Short\n\nWith Me\n .Title = \"Yin and yang\"\n .Padding = 5\n .Height = 210\n .Width = 310\n .Arrangement = Arrange.Row\nEnd With\n\nFor siCount = 2 DownTo 1\n hPictureBox = New PictureBox(Me)\n With hPictureBox\n .Height = siCount * 100\n .Width = siCount * 100\n .Picture = Picture.Load(\"../yinyang.png\")\n .Stretch = True\n End With\nNext\n\nEnd\n", "language": "Gambas" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"text/template\"\n)\n\nvar tmpl = `<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n width=\"210\" height=\"150\">\n<symbol id=\"yy\" viewBox=\"0 0 200 200\">\n<circle stroke=\"black\" stroke-width=\"2\" fill=\"white\"\n cx=\"100\" cy=\"100\" r=\"99\" />\n<path fill=\"black\"\n d=\"M100 100 a49 49 0 0 0 0 -98\n v-1 a99 99 0 0 1 0 198\n v-1 a49 49 0 0 1 0 -98\" />\n<circle fill=\"black\" cx=\"100\" cy=\"51\" r=\"17\" />\n<circle fill=\"white\" cx=\"100\" cy=\"149\" r=\"17\" />\n</symbol>\n{{range .}}<use xlink:href=\"#yy\"\n x=\"{{.X}}\" y=\"{{.Y}}\" width=\"{{.Sz}}\" height=\"{{.Sz}}\"/>\n{{end}}</svg>\n`\n\n// structure specifies position and size to draw symbol\ntype xysz struct {\n X, Y, Sz int\n}\n\n// example data to specify drawing the symbol twice,\n// with different position and size.\nvar yys = []xysz{\n {20, 20, 100},\n {140, 30, 60},\n}\n\nfunc main() {\n xt := template.New(\"\")\n template.Must(xt.Parse(tmpl))\n f, err := os.Create(\"yy.svg\")\n if err != nil {\n fmt.Println(err)\n return\n }\n if err := xt.Execute(f, yys); err != nil {\n fmt.Println(err)\n }\n f.Close()\n}\n", "language": "Go" }, { "code": "{-# LANGUAGE NoMonomorphismRestriction #-}\n\nimport Diagrams.Prelude\nimport Diagrams.Backend.Cairo.CmdLine\n\nyinyang = lw 0 $\n perim # lw 0.003 <>\n torus white black # xform id <>\n torus black white # xform negate <>\n clipBy perim base\n where perim = arc 0 (360 :: Deg) # scale (1/2)\n torus c c' = circle (1/3) # fc c' <> circle 1 # fc c\n xform f = translateY (f (1/4)) . scale (1/4)\n base = rect (1/2) 1 # fc white ||| rect (1/2) 1 # fc black\n\nmain = defaultMain $\n pad 1.1 $\n beside (2,-1) yinyang (yinyang # scale (1/4))\n", "language": "Haskell" }, { "code": "link graphics\n\nprocedure main()\nYinYang(100)\nYinYang(40,\"blue\",\"yellow\",\"white\")\nWDone() # quit on Q/q\nend\n\nprocedure YinYang(R,lhs,rhs,bg) # draw YinYang with radius of R pixels and ...\n/lhs := \"white\" # left hand side\n/rhs := \"black\" # right hand side\n/bg := \"grey\" # background\n\nwsize := 2*(C := R + (margin := R/5))\n\nW := WOpen(\"size=\"||wsize||\",\"||wsize,\"bg=\"||bg) | stop(\"Unable to open Window\")\nWAttrib(W,\"fg=\"||lhs) & FillCircle(W,C,C,R,+dtor(90),dtor(180)) # main halves\nWAttrib(W,\"fg=\"||rhs) & FillCircle(W,C,C,R,-dtor(90),dtor(180))\nWAttrib(W,\"fg=\"||lhs) & FillCircle(W,C,C+R/2,R/2,-dtor(90),dtor(180)) # sub halves\nWAttrib(W,\"fg=\"||rhs) & FillCircle(W,C,C-R/2,R/2,dtor(90),dtor(180))\nWAttrib(W,\"fg=\"||lhs) & FillCircle(W,C,C-R/2,R/8) # dots\nWAttrib(W,\"fg=\"||rhs) & FillCircle(W,C,C+R/2,R/8)\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"YinYang.bas\"\n110 GRAPHICS HIRES 2\n120 SET PALETTE WHITE,BLACK\n130 CALL YINYANG(200,400,150)\n140 CALL YINYANG(800,340,300)\n150 DEF YINYANG(X,Y,R)\n160 PLOT X,Y,ELLIPSE R,R,\n170 PLOT X,Y+R/2,ELLIPSE R/2,R/2,ELLIPSE R/6,R/6,PAINT\n180 PLOT X,Y-R/2,ELLIPSE R/2,R/2,ELLIPSE R/6,R/6,\n190 PLOT X,Y-6,PAINT,X+R/2,Y,PAINT\n200 SET INK 0:PLOT X,Y+R/2,ELLIPSE R/2,R/2,\n210 SET INK 1:PLOT X,Y,ELLIPSE R,R,\n220 END DEF\n", "language": "IS-BASIC" }, { "code": "yinyang=:3 :0\n radii=. y*1 3 6\n ranges=. i:each radii\n squares=. ,\"0/~each ranges\n circles=. radii ([ >: +/\"1&.:*:@])each squares\n cInds=. ({:radii) +each circles #&(,/)each squares\n\n M=. ' *.' {~ circles (* 1 + 0 >: {:\"1)&(_1&{::) squares\n offset=. 3*y,0\n M=. '*' ((_2 {:: cInds) <@:+\"1 offset)} M\n M=. '.' ((_2 {:: cInds) <@:-\"1 offset)} M\n M=. '.' ((_3 {:: cInds) <@:+\"1 offset)} M\n M=. '*' ((_3 {:: cInds) <@:-\"1 offset)} M\n)\n", "language": "J" }, { "code": " yinyang 1\n .\n ......*\n ....*..**\n ....***..**\n .....*..***\n ........***\n.......******\n ...********\n ...**.*****\n ..**...****\n ..**.****\n .******\n *\n yinyang 2\n .\n ........*\n ...........**\n .............**\n ........*.....***\n ........***....****\n ........*****....****\n .........***....*****\n ...........*.....******\n .................******\n ................*******\n ...............********\n.............************\n ........***************\n .......****************\n ......*****************\n ......*****.***********\n .....****...*********\n ....****.....********\n ....****...********\n ...*****.********\n ..*************\n ..***********\n .********\n *\n", "language": "J" }, { "code": "package org.rosettacode.yinandyang;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\n\npublic class YinYangGenerator\n{\n private final int size;\n\n public YinYangGenerator(final int size)\n {\n this.size = size;\n }\n\n /**\n * Draw a yin yang symbol on the given graphics context.\n */\n public void drawYinYang(final Graphics graphics)\n {\n // Preserve the color for the caller\n final Color colorSave = graphics.getColor();\n\n graphics.setColor(Color.WHITE);\n // Use fillOval to draw a filled in circle\n graphics.fillOval(0, 0, size-1, size-1);\n\n graphics.setColor(Color.BLACK);\n // Use fillArc to draw part of a filled in circle\n graphics.fillArc(0, 0, size-1, size-1, 270, 180);\n graphics.fillOval(size/4, size/2, size/2, size/2);\n\n graphics.setColor(Color.WHITE);\n graphics.fillOval(size/4, 0, size/2, size/2);\n graphics.fillOval(7*size/16, 11*size/16, size/8, size/8);\n\n graphics.setColor(Color.BLACK);\n graphics.fillOval(7*size/16, 3*size/16, size/8, size/8);\n // Use drawOval to draw an empty circle for the outside border\n graphics.drawOval(0, 0, size-1, size-1);\n\n // Restore the color for the caller\n graphics.setColor(colorSave);\n }\n\n /**\n * Create an image containing a yin yang symbol.\n */\n public Image createImage(final Color bg)\n {\n // A BufferedImage creates the image in memory\n final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);\n // Get the graphics object for the image; note in many\n // applications you actually use Graphics2D for the\n // additional API calls\n final Graphics graphics = image.getGraphics();\n // Color in the background of the image\n graphics.setColor(bg);\n graphics.fillRect(0,0,size,size);\n drawYinYang(graphics);\n return image;\n }\n\n public static void main(final String args[])\n {\n final int size = Integer.parseInt(args[0]);\n final YinYangGenerator generator = new YinYangGenerator(size);\n\n final JFrame frame = new JFrame(\"Yin Yang Generator\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n final Image yinYang = generator.createImage(frame.getBackground());\n // Use JLabel to display an image\n frame.add(new JLabel(new ImageIcon(yinYang)));\n frame.pack();\n frame.setVisible(true);\n }\n}\n", "language": "Java" }, { "code": "import java.util.Collection;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.function.BooleanSupplier;\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\nimport static java.util.Collections.singletonMap;\n\npublic interface YinYang {\n public static boolean circle(\n int x,\n int y,\n int c,\n int r\n ) {\n return\n (r * r) >=\n ((x = x / 2) * x)\n + ((y = y - c) * y)\n ;\n }\n\n public static String pixel(int x, int y, int r) {\n return Stream.<Map<BooleanSupplier, Supplier<String>>>of(\n singletonMap(\n () -> circle(x, y, -r / 2, r / 6),\n () -> \"#\"\n ),\n singletonMap(\n () -> circle(x, y, r / 2, r / 6),\n () -> \".\"\n ),\n singletonMap(\n () -> circle(x, y, -r / 2, r / 2),\n () -> \".\"\n ),\n singletonMap(\n () -> circle(x, y, r / 2, r / 2),\n () -> \"#\"\n ),\n singletonMap(\n () -> circle(x, y, 0, r),\n () -> x < 0 ? \".\" : \"#\"\n )\n )\n .sequential()\n .map(Map::entrySet)\n .flatMap(Collection::stream)\n .filter(e -> e.getKey().getAsBoolean())\n .map(Map.Entry::getValue)\n .map(Supplier::get)\n .findAny()\n .orElse(\" \")\n ;\n }\n\n public static void yinYang(int r) {\n IntStream.rangeClosed(-r, r)\n .mapToObj(\n y ->\n IntStream.rangeClosed(\n 0 - r - r,\n r + r\n )\n .mapToObj(x -> pixel(x, y, r))\n .reduce(\"\", String::concat)\n )\n .forEach(System.out::println)\n ;\n }\n\n public static void main(String... arguments) {\n Optional.of(arguments)\n .filter(a -> a.length == 1)\n .map(a -> a[0])\n .map(Integer::parseInt)\n .ifPresent(YinYang::yinYang)\n ;\n }\n}\n", "language": "Java" }, { "code": "function Arc(posX,posY,radius,startAngle,endAngle,color){//Angle in radians.\nthis.posX=posX;\nthis.posY=posY;\nthis.radius=radius;\nthis.startAngle=startAngle;\nthis.endAngle=endAngle;\nthis.color=color;\n}\n//0,0 is the top left of the screen\nvar YingYang=[\nnew Arc(0.5,0.5,1,0.5*Math.PI,1.5*Math.PI,\"white\"),//Half white semi-circle\nnew Arc(0.5,0.5,1,1.5*Math.PI,0.5*Math.PI,\"black\"),//Half black semi-circle\nnew Arc(0.5,0.25,.5,0,2*Math.PI,\"black\"),//black circle\nnew Arc(0.5,0.75,.5,0,2*Math.PI,\"white\"),//white circle\nnew Arc(0.5,0.25,1/6,0,2*Math.PI,\"white\"),//small white circle\nnew Arc(0.5,0.75,1/6,0,2*Math.PI,\"black\")//small black circle\n]\n//Ying Yang is DONE!\n//Now we'll have to draw it.\n//We'll draw it in a matrix that way we can get results graphically or by text!\nfunction Array2D(width,height){\nthis.height=height;\nthis.width=width;\nthis.array2d=[];\nfor(var i=0;i<this.height;i++){\nthis.array2d.push(new Array(this.width));\n}\n}\nArray2D.prototype.resize=function(width,height){//This is expensive\n//nheight and nwidth is the difference of the new and old height\nvar nheight=height-this.height,nwidth=width-this.width;\nif(nwidth>0){\nfor(var i=0;i<this.height;i++){\nif(i<height)\nArray.prototype.push.apply(this.array2d[i],new Array(nwidth));\n}\n}\nelse if(nwidth<0){\nfor(var i=0;i<this.height;i++){\nif(i<height)\n this.array2d[i].splice(width,nwidth);\n}\n}\nif(nheight>0){\n Array.prototype.push.apply(this.array2d,new Array(width));\n}\nelse if(nheight<0){\n this.array2d.splice(height,nheight)\n}\n}\nArray2D.prototype.loop=function(callback){\nfor(var i=0;i<this.height;i++)\n for(var i2=0;i2<this.width;i++)\n callback.call(this,this.array2d[i][i2],i,i2);\n\n}\nvar mat=new Array2D(100,100);//this sounds fine;\nYingYang[0];\n//In construction.\n", "language": "JavaScript" }, { "code": "YinYang = (function () {\n var scale_x = 2,\n scale_y = 1,\n black = \"#\",\n white = \".\",\n clear = \" \",\n out = \"\";\n\n function draw(radius) {\n function inCircle(centre_x, centre_y, radius, x, y) {\n return Math.pow(x - centre_x, 2) + Math.pow(y - centre_y, 2) <= Math.pow(radius, 2)\n }\n var bigCircle = function (x, y) {\n return inCircle(0, 0, radius, x, y)\n }, whiteSemiCircle = function (x, y) {\n return inCircle(0, radius / 2, radius / 2, x, y)\n }, smallBlackCircle = function (x, y) {\n return inCircle(0, radius / 2, radius / 6, x, y)\n }, blackSemiCircle = function (x, y) {\n return inCircle(0, -radius / 2, radius / 2, x, y)\n }, smallWhiteCircle = function (x, y) {\n return inCircle(0, -radius / 2, radius / 6, x, y)\n };\n i = 0\n for (var sy = Math.round(radius * scale_y); sy >= -Math.round(radius * scale_y); sy--) {\n //console.log(sy)\n for (var sx = -Math.round(radius * scale_x); sx <= Math.round(radius * scale_x); sx++) {\n\n var x = sx / scale_x,\n y = sy / scale_y;\n //out+=sx\n //console.log(sx,bigCircle(x,y))\n if (bigCircle(x, y)) {\n //out+=\"\";\n if (whiteSemiCircle(x, y)) {\n //console.log(x,y)\n if (smallBlackCircle(x, y)) {\n out += black\n } else {\n out += white\n }\n } else if (blackSemiCircle(x, y)) {\n if (smallWhiteCircle(x, y)) {\n out += white\n } else {\n out += black\n }\n } else if (x < 0) {\n out += white\n } else {\n out += black\n }\n\n } else {\n out += clear;\n }\n\n }\n out += \"\\n\";\n }\n return out;\n }\n return draw\n})()\nconsole.log(YinYang(17))\nconsole.log(YinYang(8))\n", "language": "JavaScript" }, { "code": "<!DOCTYPE html>\n<html>\n\n<head>\n\n <body>\n <svg\n id=\"svg\"\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n version=\"1.1\"\n width=\"100%\"\n height=\"100%\">\n </svg>\n <script>\nfunction makeElem(elemName, attribs) { //atribs must be an Object\n var e = document.createElementNS(\"http://www.w3.org/2000/svg\", elemName),\n a, b, d = attribs.style;\n for (a in attribs) {\n if (attribs.hasOwnProperty(a)) {\n\n if (a == 'style') {\n for (b in d) {\n if (d.hasOwnProperty(b)) {\n e.style[b] = d[b];\n }\n }\n continue;\n }\n e.setAttributeNS(null, a, attribs[a]);\n }\n }\n return e;\n}\nvar svg = document.getElementById(\"svg\");\n\nfunction drawYingYang(n, x, y) {\n var d = n / 10;\n h = d * 5, q = h / 2, t = q * 3;\n //A white circle, for the bulk of the left-hand part\n svg.appendChild(makeElem(\"circle\", {\n cx: h,\n cy: h,\n r: h,\n fill: \"white\"\n }));\n //A black semicircle, for the bulk of the right-hand part\n svg.appendChild(makeElem(\"path\", {\n d: \"M \" + (h + x) + \",\" + y + \" A \" + q + \",\" + q + \" -\" + d * 3 + \" 0,1 \" + (h + x) + \",\" + (n + y) + \" z\",\n fill: \"black\"\n }));\n //Circles to extend each part\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: q + y,\n r: q,\n fill: \"white\"\n }));\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: t + y,\n r: q,\n fill: \"black\"\n }));\n //The spots\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: q + y,\n r: d,\n fill: \"black\"\n }));\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: t + y,\n r: q,\n fill: \"black\"\n }));\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: t + y,\n r: d,\n fill: \"white\"\n }));\n //An outline for the whole shape\n svg.appendChild(makeElem(\"circle\", {\n cx: h + x,\n cy: h + y,\n r: h,\n fill: \"none\",\n stroke: \"gray\",\n \"stroke-width\": d / 3\n }));\n if (svg.height.baseVal.valueInSpecifiedUnits < n) {\n svg.setAttributeNS(null, \"height\", y * 1.25 + n + \"px\")\n }\n //svg.appendChild(makeElem(\"circle\",{cx:\"100\", cy:h, r:\"40\", stroke:\"black\", \"stroke-width\":\"2\", fill:\"red\"}))\n}\ndrawYingYang(100, 30, 30);\ndrawYingYang(1000, 200, 200);\n </script>\n </body>\n</head>\n\n</html>\n", "language": "JavaScript" }, { "code": "function svgEl(tagName, attrs) {\n const el = document.createElementNS('http://www.w3.org/2000/svg', tagName);\n for (const key in attrs) el.setAttribute(key, attrs[key]);\n return el;\n}\n\nfunction yinYang(r, x, y, th = 1) {\n const cR = (dY, rad) => `M${x},${y + dY + rad} a${rad},${rad},0,1,1,.1,0z `;\n const arc = (dY, rad, cw = 1) => `A${rad},${rad},0,0,${cw},${x},${y + dY} `;\n const d = cR(0, r + th) + cR(r / 2, r / 6) + cR(-r / 2, r / 6)\n + `M${x},${y} ` + arc(r, r / 2, 0) + arc(-r, r) + arc(0, r / 2);\n return svgEl('path', {d, 'fill-rule': 'evenodd'});\n}\n\nconst dialog = document.body.appendChild(document.createElement('dialog'));\nconst svg = dialog.appendChild(svgEl('svg', {width: 170, height: 120}));\n\nsvg.appendChild(yinYang(50.0, 60, 60));\nsvg.appendChild(yinYang(20.0, 140, 30));\ndialog.showModal();\n", "language": "JavaScript" }, { "code": "function yinYang(r, x, y, th = 1) {\n const PI = Math.PI;\n const path = new Path2D();\n const cR = (dY, radius) => { path.arc(x, y + dY, radius, 0, PI * 2); path.closePath() };\n cR(0, r + th);\n cR(r / 2, r / 6);\n cR(-r / 2, r / 6);\n path.arc(x, y, r, PI / 2, -PI / 2);\n path.arc(x, y - r / 2, r / 2, -PI / 2, PI / 2);\n path.arc(x, y + r / 2, r / 2, -PI / 2, PI / 2, true);\n return path;\n}\n\ndocument.documentElement.innerHTML = '<canvas width=\"170\" height=\"120\"/>';\nconst canvasCtx = document.querySelector('canvas').getContext('2d');\n\ncanvasCtx.fill(yinYang(50.0, 60, 60), 'evenodd');\ncanvasCtx.fill(yinYang(20.0, 140, 30), 'evenodd');\n", "language": "JavaScript" }, { "code": "def svg:\n \"<svg width='100%' height='100%' version='1.1'\n xmlns='http://www.w3.org/2000/svg'\n\txmlns:xlink='http://www.w3.org/1999/xlink'>\" ;\n\ndef draw_yinyang(x; scale):\n \"<use xlink:href='#y' transform='translate(\\(x),\\(x)) scale(\\(scale))'/>\";\n\ndef define_yinyang:\n \"<defs>\n <g id='y'>\n <circle cx='0' cy='0' r='200' stroke='black'\n fill='white' stroke-width='1'/>\n <path d='M0 -200 A 200 200 0 0 0 0 200\n 100 100 0 0 0 0 0 100 100 0 0 1 0 -200\n \t\t z' fill='black'/>\n <circle cx='0' cy='100' r='33' fill='white'/>\n <circle cx='0' cy='-100' r='33' fill='black'/>\n </g>\n </defs>\" ;\n\ndef draw:\n svg,\n define_yinyang,\n draw_yinyang(20; .05),\n draw_yinyang(8 ; .02),\n \"</svg>\" ;\n\ndraw\n", "language": "Jq" }, { "code": "$ jq -M -r -n -f yin_and_yang.jq > yin_and_yang.svg\n", "language": "Jq" }, { "code": "function yinyang(n::Int=3)\n radii = (i * n for i in (1, 3, 6))\n ranges = collect(collect(-r:r) for r in radii)\n squares = collect(collect((x, y) for x in rnge, y in rnge) for rnge in ranges)\n circles = collect(collect((x, y) for (x,y) in sqrpoints if hypot(x, y) ≤ radius)\n for (sqrpoints, radius) in zip(squares, radii))\n m = Dict((x, y) => ' ' for (x, y) in squares[end])\n for (x, y) in circles[end] m[(x, y)] = x > 0 ? '·' : '*' end\n for (x, y) in circles[end-1]\n m[(x, y + 3n)] = '*'\n\t\tm[(x, y - 3n)] = '·'\n end\n for (x, y) in circles[end-2]\n m[(x, y + 3n)] = '·'\n\t\tm[(x, y - 3n)] = '*'\n end\n return join((join(m[(x, y)] for x in reverse(ranges[end])) for y in ranges[end]), '\\n')\nend\n\nprintln(yinyang(4))\n", "language": "Julia" }, { "code": "// version 1.1.2\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.Image\nimport java.awt.image.BufferedImage\nimport javax.swing.ImageIcon\nimport javax.swing.JFrame\nimport javax.swing.JPanel\nimport javax.swing.JLabel\n\nclass YinYangGenerator {\n private fun drawYinYang(size: Int, g: Graphics) {\n with(g) {\n // Preserve the color for the caller\n val colorSave = color\n color = Color.WHITE\n\n // Use fillOval to draw a filled in circle\n fillOval(0, 0, size - 1, size - 1)\n color = Color.BLACK\n\n // Use fillArc to draw part of a filled in circle\n fillArc(0, 0, size - 1, size - 1, 270, 180)\n fillOval(size / 4, size / 2, size / 2, size / 2)\n color = Color.WHITE\n fillOval(size / 4, 0, size / 2, size / 2)\n fillOval(7 * size / 16, 11 * size / 16, size /8, size / 8)\n color = Color.BLACK\n fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8)\n\n // Use drawOval to draw an empty circle for the outside border\n drawOval(0, 0, size - 1, size - 1)\n\n // Restore the color for the caller\n color = colorSave\n }\n }\n\n fun createImage(size: Int, bg: Color): Image {\n // A BufferedImage creates the image in memory\n val image = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)\n\n // Get the graphics object for the image\n val g = image.graphics\n\n // Color in the background of the image\n g.color = bg\n g.fillRect(0, 0, size, size)\n drawYinYang(size, g)\n return image\n }\n}\n\nfun main(args: Array<String>) {\n val gen = YinYangGenerator()\n val size = 400 // say\n val p = JPanel()\n val yinYang = gen.createImage(size, p.background)\n p.add(JLabel(ImageIcon(yinYang)))\n\n val size2 = size / 2 // say\n val yinYang2 = gen.createImage(size2, p.background)\n p.add(JLabel(ImageIcon(yinYang2)))\n\n val f = JFrame(\"Big and Small Yin Yang\")\n with (f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n add(p)\n pack()\n isVisible = true\n }\n}\n", "language": "Kotlin" }, { "code": "{{SVG 580 580}\n {YY 145 145 300}\n {YY 270 195 50}\n {YY 270 345 50}\n}\n\n{def YY\n {lambda {:x :y :s}\n {{G :x :y :s}\n {CIRCLE 0.5 0.5 0.5 black 0 0}\n {{G 0.5 0 1} {HALF_CIRCLE}}\n {CIRCLE 0.5 0.25 0.25 black 0 0}\n {CIRCLE 0.5 0.75 0.25 white 0 0}\n {CIRCLE 0.5 0.25 0.1 white 0 0}\n {CIRCLE 0.5 0.75 0.1 black 0 0}\n {CIRCLE 0.5 0.5 0.5 none gray 0.01} }}}\n\n{def CIRCLE\n {lambda {:x :y :r :f :s :w}\n {circle {@ cx=\":x\" cy=\":y\" r=\":r\"\n fill=\":f\" stroke=\":s\" stroke-width=\":w\"}}}}\n\n{def HALF_CIRCLE\n {path {@ d=\"M 0 0 A 0.5 0.5 0 0 0 0 1\" fill=\"white\"}}}\n\n{def SVG\n {lambda {:w :h}\n svg {@ width=\":w\" height=\":h\"\n style=\"box-shadow:0 0 8px #888;\"}}}\n\n{def G\n {lambda {:x :y :s}\n g {@ transform=\"translate(:x,:y) scale(:s,:s)\"}}}\n\nOutput: Sorry, I was unable to upload the following PNG picture (45kb). Need help.\n\nhttp://lambdaway.free.fr/lambdawalks/data/lambdatalk_yinyang.png\n", "language": "Lambdatalk" }, { "code": " WindowWidth =410\n WindowHeight =440\n\n open \"Yin & Yang\" for graphics_nf_nsb as #w\n\n #w \"trapclose [quit]\"\n\n call YinYang 200, 200, 200\n call YinYang 120, 50, 50\n\n wait\n\n sub YinYang x, y, size\n\n #w \"up ; goto \"; x; \" \"; y\n #w \"backcolor black ; color black\"\n #w \"down ; circlefilled \"; size /2\n\n #w \"color 255 255 255 ; backcolor 255 255 255\"\n #w \"up ; goto \"; x -size /2; \" \"; y -size /2\n #w \"down ; boxfilled \"; x; \" \"; y +size /2\n\n #w \"up ; goto \"; x; \" \"; y -size /4\n #w \"down ; backcolor black ; color black ; circlefilled \"; size /4\n #w \"up ; goto \"; x; \" \"; y -size /4\n #w \"down ; backcolor white ; color white ; circlefilled \"; size /12\n\n #w \"up ; goto \"; x; \" \"; y +size /4\n #w \"down ; backcolor white ; color white ; circlefilled \"; size /4\n #w \"up ; goto \"; x; \" \"; y +size /4\n #w \"down ; backcolor black ; color black ; circlefilled \"; size /12\n\n #w \"up ; goto \"; x; \" \"; y\n #w \"down ; color black ; circle \"; size /2\n\n #w \"flush\"\n\n end sub\n\n scan\n\n wait\n\n [quit]\n close #w\n end\n", "language": "Liberty-BASIC" }, { "code": "10 mode 2:deg:defint a-z:ink 0,26:ink 1,0:border 26\n20 xp=320:yp=200:size=150:gosub 100\n30 xp=550:yp=350:size=40:gosub 100\n40 while inkey$=\"\":wend\n50 end\n100 cx=xp:cy=yp:cr=size:gosub 1000\n110 cy=yp+size/2:cr=size/8:gosub 1000\n120 cr=size/2:half=0:gosub 2000\n130 cy=yp-size/2:cr=size/8:gosub 1000\n140 cr=size/2:half=1:gosub 2000\n150 move xp, yp+size/2:fill 1\n160 move xp+size/2, yp:fill 1\n170 return\n1000 plot cx,cy+cr\n1010 for i=0 to 360 step 10\n1020 draw cx+cr*sin(i),cy+cr*cos(i)\n1030 next\n1040 return\n2000 p=180*half\n2010 plot cx+cr*sin(p),cy+cr*cos(p)\n2020 for i=p to p+180 step 10\n2030 draw cx+cr*sin(i),cy+cr*cos(i)\n2040 next\n2050 return\n", "language": "Locomotive-Basic" }, { "code": "to taijitu :r\n ; Draw a classic Taoist taijitu of the given radius centered on the current\n ; turtle position. The \"eyes\" are placed along the turtle's heading, the\n ; filled one in front, the open one behind.\n\n ; don't bother doing anything if the pen is not down\n if not pendown? [stop]\n\n ; useful derivative values\n localmake \"r2 (ashift :r -1)\n localmake \"r4 (ashift :r2 -1)\n localmake \"r8 (ashift :r4 -1)\n\n ; remember where we started\n localmake \"start pos\n\n ; draw outer circle\n pendown\n arc 360 :r\n\n ; draw upper half of S\n penup\n forward :r2\n pendown\n arc 180 :r2\n\n ; and filled inner eye\n arc 360 :r8\n fill\n\n ; draw lower half of S\n penup\n back :r\n pendown\n arc -180 :r2\n\n ; other inner eye\n arc 360 :r8\n\n ; fill this half of the symbol\n penup\n forward :r4\n fill\n\n ; put the turtle back where it started\n setpos :start\n pendown\nend\n\n; demo code to produce image at right\nclearscreen\npendown\nhideturtle\ntaijitu 100\npenup\nforward 150\nleft 90\nforward 150\npendown\ntaijitu 75\n", "language": "Logo" }, { "code": "function circle(x, y, c, r)\n return (r * r) >= (x * x) / 4 + ((y - c) * (y - c))\nend\n\nfunction pixel(x, y, r)\n if circle(x, y, -r / 2, r / 6) then\n return '#'\n end\n if circle(x, y, r / 2, r / 6) then\n return '.'\n end\n if circle(x, y, -r / 2, r / 2) then\n return '.'\n end\n if circle(x, y, r / 2, r / 2) then\n return '#'\n end\n if circle(x, y, 0, r) then\n if x < 0 then\n return '.'\n else\n return '#'\n end\n end\n return ' '\nend\n\nfunction yinYang(r)\n for y=-r,r do\n for x=-2*r,2*r do\n io.write(pixel(x, y, r))\n end\n print()\n end\nend\n\nyinYang(18)\n", "language": "Lua" }, { "code": "Module YinYang {\n\tcls 5,0\n\tGradient 0, 5\n\tDouble\n\tPrint Over\n\tCursor 0,0\n\tReport 2, \"阴阳 Yin and yang 음양\"\n\tNormal\n\tDrawing {\n\tcircle fill 0, 3000,1, 0\n\tcircle fill 15, 3000,1,0, pi/2, -pi/2\n\tstep 0, -1500\n\tcircle fill 15, 1500,1,15\n\twidth 4 {\n\t\tcircle fill 0, 500,1,0\n\t}\n\tstep 0, 3000\n\tcircle fill 0, 1500,1,0\n\twidth 4 {\n\t\tcircle fill 15, 500,1,15\n\t\tstep 0, -1500\n\t\tcircle 3000,1,0\n\t}\n\t} as A\n\tMove 6000, 5000-1500\n\tImage A, 6000\n\tMove 2000, 5000\n\tImage A, 3000\n\tMove 2000+1500, 5000+1500\n\thold // hold surface to release by statement release\n\tMouse.Icon Hide\n\ti=0\n\tevery 10 {\n\t\tif inkey$=\" \" or mouse=2 then exit\n\t\trelease\n\t\tmove mouse.x, mouse.y\n\t\tImage A, 3000, ,i : i+=5:if i>355 then i=0\n\t\tRefresh 20\n\t\tif mouse=1 then hold\n\t}\n\tMouse.Icon Show\n\tfilename$=\"yin and yang.emf\"\n\t// save to file\n\tOpen filename$ for output as #f\n\tPut #f, A, 1\n\tClose #f\n\t// open mspaing\n\twin \"mspaint\", quote$(dir$+filename$)\n}\nYinYang\n", "language": "M2000-Interpreter" }, { "code": "with(plottools):\nwith(plots):\nyingyang := r -> display(\n circle([0, 0], r),\n disk([0, 1/2*r], 1/10*r, colour = black),\n disk([0, -1/2*r], 1/10*r, colour = white),\n disk([0, -1/2*r], 1/2*r, colour = black),\n inequal({1/4*r^2 <= x^2 + (y - 1/2*r)^2, 1/4*r^2 <= x^2 + (y + 1/2*r)^2, x^2 + y^2 <=\n r^2}, x = 0 .. r, y = -r .. r, grid = [100, 100], colour = black),\n scaling = constrained, axes = none\n );\n", "language": "Maple" }, { "code": "YinYang[size_] :=\n Graphics[{{Circle[{0, 0}, 2]}, {Disk[{0, 0},\n 2, {90 Degree, -90 Degree}]}, {White, Disk[{0, 1}, 1]}, {Black,\n Disk[{0, -1}, 1]}, {Black, Disk[{0, 1}, 1/4]}, {White,\n Disk[{0, -1}, 1/4]}}, ImageSize -> 40 size]\n", "language": "Mathematica" }, { "code": "vardef yinyang(expr u) =\n picture pic_;\n path p_;\n p_ := halfcircle scaled 2u rotated -90 --\n halfcircle scaled u rotated 90 shifted (0, 1/2u) reflectedabout ((0,1), (0,-1)) --\n halfcircle scaled u rotated -270 shifted (0, -1/2u) -- cycle;\n\n pic_ := nullpicture;\n addto pic_ contour fullcircle scaled 2u withcolor black;\n addto pic_ contour p_ withcolor white;\n addto pic_ doublepath p_ withcolor black withpen pencircle scaled 0.5mm;\n addto pic_ contour fullcircle scaled 1/3u shifted (0, 1/2u) withcolor white;\n addto pic_ contour fullcircle scaled 1/3u shifted (0, -1/2u) withcolor black;\n pic_\nenddef;\n\nbeginfig(1)\n % let's create a Yin Yang symbol with a radius of 5cm\n draw yinyang(5cm) shifted (5cm, 5cm);\n % and another one, radius 2.5cm, rotated 180 degrees and translated\n draw yinyang(2.5cm) rotated 180 shifted (11cm, 11cm);\nendfig;\n\nend.\n", "language": "Metapost" }, { "code": "MODULE Taijitu;\nFROM InOut IMPORT Write, WriteLn;\n\nPROCEDURE YinYang(r: INTEGER);\n VAR x, y: INTEGER;\n\n PROCEDURE circle(x, y, c, r: INTEGER): BOOLEAN;\n BEGIN\n RETURN r*r >= (x DIV 2) * (x DIV 2) + (y-c) * (y-c);\n END circle;\n\n PROCEDURE pixel(x, y, r: INTEGER): CHAR;\n BEGIN\n IF circle(x, y, -r DIV 2, r DIV 6) THEN RETURN '#';\n ELSIF circle(x, y, r DIV 2, r DIV 6) THEN RETURN '.';\n ELSIF circle(x, y, -r DIV 2, r DIV 2) THEN RETURN '.';\n ELSIF circle(x, y, r DIV 2, r DIV 2) THEN RETURN '#';\n ELSIF circle(x, y, 0, r) THEN\n IF x<0 THEN RETURN '.';\n ELSE RETURN '#';\n END;\n ELSE RETURN ' ';\n END;\n END pixel;\nBEGIN\n FOR y := -r TO r DO\n FOR x := -2*r TO 2*r DO\n Write(pixel(x,y,r));\n END;\n WriteLn();\n END;\nEND YinYang;\n\nBEGIN\n YinYang(4);\n WriteLn();\n YinYang(8);\nEND Taijitu.\n", "language": "Modula-2" }, { "code": "/* NetRexx */\n\noptions replace format comments java crossref savelog symbols binary\n\nsay \"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\"\nsay \"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\"\nsay \" 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\"\nsay \"<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\"\nsay \" xmlns:xlink='http://www.w3.org/1999/xlink'\"\nsay \" width='30' height='30'>\"\nsay \" <defs><g id='y'>\"\nsay \" <circle cx='0' cy='0' r='200' stroke='black'\"\nsay \" fill='white' stroke-width='1'/>\"\nsay \" <path d='M0 -200 A 200 200 0 0 0 0 200\"\nsay \" 100 100 0 0 0 0 0 100 100 0 0 1 0 -200\"\nsay \" z' fill='black'/>\"\nsay \" <circle cx='0' cy='100' r='33' fill='white'/>\"\nsay \" <circle cx='0' cy='-100' r='33' fill='black'/>\"\nsay \" </g></defs>\"\n\nsay draw_yinyang(20, 0.05)\nsay draw_yinyang(8, 0.02)\n\nsay \"</svg>\"\n\nreturn\n\nmethod draw_yinyang(trans = int, scale = double) inheritable static returns String\n yy = String.format(\" <use xlink:href='#y' transform='translate(%d,%d) scale(%g)'/>\", -\n [Object Integer(trans), Integer(trans), Double(scale)])\n return yy\n", "language": "NetRexx" }, { "code": "import gintro/cairo\n\nproc draw(ctx: Context; x, y, r: float) =\n ctx.arc(x, y, r + 1, 1.571, 7.854)\n ctx.setSource(0.0, 0.0, 0.0)\n ctx.fill()\n ctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712)\n ctx.arc(x, y + r / 2, r / 2, 1.571, 4.712)\n ctx.arcNegative(x, y, r, 4.712, 1.571)\n ctx.setSource(1.0, 1.0, 1.0)\n ctx.fill()\n ctx.arc(x, y - r / 2, r / 5, 1.571, 7.854)\n ctx.setSource(0.0, 0.0, 0.0)\n ctx.fill()\n ctx.arc(x, y + r / 2, r / 5, 1.571, 7.854)\n ctx.setSource(1.0, 1.0, 1.0)\n ctx.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", "language": "Nim" }, { "code": "open Graphics\n\nlet draw_yinyang x y radius black white =\n let hr = radius / 2 in\n let sr = radius / 6 in\n set_color black;\n set_line_width 6;\n draw_circle x y radius;\n set_line_width 0;\n set_color black;\n fill_arc x y radius radius 270 450;\n set_color white;\n fill_arc x y radius radius 90 270;\n fill_arc x (y + hr) hr hr 270 450;\n set_color black;\n fill_arc x (y - hr) hr hr 90 270;\n fill_circle x (y + hr) sr;\n set_color white;\n fill_circle x (y - hr) sr\n\nlet () =\n open_graph \"\";\n let width = size_x()\n and height = size_y() in\n set_color (rgb 200 200 200);\n fill_rect 0 0 width height;\n let w = width / 3\n and h = height / 3 in\n let r = (min w h) / 3 in\n draw_yinyang w (h*2) (r*2) black white;\n draw_yinyang (w*2) h r blue magenta;\n ignore(read_key())\n", "language": "OCaml" }, { "code": "YinYang(r)={ for(y=-r,r, print(concat(apply( x->\n if( x^2+y^2>r^2, \" \",\n [y<0,y>0,x>0][logint((x^2+(abs(y)-r/2)^2)<<8\\r^2+1,2)\\3+1], \"#\", \".\"\n ), [-r..r]\n ))))\n}\n", "language": "PARI-GP" }, { "code": "//Written for TU Berlin\n//Compiled with fpc\nProgram yingyang;\nUses Math;\nconst\n scale_x=2;\n scale_y=1;\n black='#';\n white='.';\n clear=' ';\n\nfunction inCircle(centre_x:Integer;centre_y:Integer;radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\ninCircle:=power(x-centre_x,2)+power(y-centre_y,2)<=power(radius,2);\nend;\n\nfunction bigCircle(radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\nbigCircle:=inCircle(0,0,radius,x,y);\nend;\n\nfunction whiteSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\nwhiteSemiCircle:=inCircle(0,radius div 2 ,radius div 2,x,y);\nend;\n\n\nfunction smallBlackCircle(radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\nsmallBlackCircle:=inCircle(0,radius div 2 ,radius div 6,x,y);\nend;\n\nfunction blackSemiCircle(radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\nblackSemiCircle:=inCircle(0,-radius div 2 ,radius div 2,x,y);\nend;\n\nfunction smallWhiteCircle(radius:Integer;x:Integer;y:Integer):Boolean ;\nbegin\nsmallWhiteCircle:=inCircle(0,-radius div 2 ,radius div 6,x,y);\nend;\n\nvar\nradius,sy,sx,x,y:Integer;\nbegin\n writeln('Please type a radius:');\n readln(radius);\n if radius<3 then begin writeln('A radius bigger than 3');halt end;\n sy:=round(radius*scale_y);\n while(sy>=-round(radius*scale_y)) do begin\n sx:=-round(radius*scale_x);\n while(sx<=round(radius*scale_x)) do begin\n x:=sx div scale_x;\n y:=sy div scale_y;\n if bigCircle(radius,x,y) then begin\n if (whiteSemiCircle(radius,x,y)) then if smallblackCircle(radius,x,y) then write(black) else write(white) else if blackSemiCircle(radius,x,y) then if smallWhiteCircle(radius,x,y) then write(white) else write(black) else if x>0 then write(white) else write(black);\n end\n else write(clear);\n sx:=sx+1\n end;\n writeln;\n sy:=sy-1;\n end;\nend.\n", "language": "Pascal" }, { "code": "sub circle {\n my ($radius, $cx, $cy, $fill, $stroke) = @_;\n print \"<circle cx='$cx' cy='$cy' r='$radius' \",\n \"fill='$fill' stroke='$stroke' stroke-width='1'/>\\n\";\n}\n\nsub yin_yang {\n my ($rad, $cx, $cy, %opt) = @_;\n my ($c, $w) = (1, 0);\n $opt{fill} //= 'white';\n $opt{stroke} //= 'black';\n $opt{recurangle} //= 0;\n\n print \"<g transform='rotate($opt{angle}, $cx, $cy)'>\"\n if $opt{angle};\n\n if ($opt{flip}) { ($c, $w) = ($w, $c) };\n\n circle($rad, $cx, $cy, $opt{fill}, $opt{stroke});\n\n print \"<path d='M $cx \", $cy + $rad, \"A \",\n $rad/2, \" \", $rad/2, \" 0 0 $c $cx $cy \",\n $rad/2, \" \", $rad/2, \" 0 0 $w $cx \", $cy - $rad, \" \",\n $rad, \" \", $rad, \" 0 0 $c $cx \", $cy + $rad, \" \",\n \"z' fill='$opt{stroke}' stroke='none' />\";\n\n if ($opt{recur} and $rad > 1) {\n # recursive \"eyes\" are slightly larger\n yin_yang($rad/4, $cx, $cy + $rad/2, %opt,\n angle => $opt{recurangle},\n fill => $opt{stroke},\n stroke => $opt{fill} );\n yin_yang($rad/4, $cx, $cy - $rad/2, %opt,\n angle => 180 + $opt{recurangle});\n } else {\n circle($rad/5, $cx, $cy + $rad/2, $opt{fill}, $opt{stroke});\n circle($rad/5, $cx, $cy - $rad/2, $opt{stroke}, $opt{fill});\n }\n print \"</g>\" if $opt{angle};\n}\n\nprint <<'HEAD';\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\">\nHEAD\n\nyin_yang(200, 250, 250, recur=>1,\n angle=>0, recurangle=>90, fill=>'white', stroke=>'black');\nyin_yang(100, 500, 500);\n\nprint \"</svg>\"\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #000080;font-style:italic;\">--\n -- demo\\rosetta\\Yin_and_yang.exw\n -- =============================\n --</span>\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #000000;\">pGUI</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n\n <span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span>\n <span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">cd_canvas</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">cdCanvas</span> <span style=\"color: #000000;\">hCdCanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">xc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">yc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- cdCanvasSector does not draw anti-aliased edges, but cdCanvasArc does, so over-draw...</span>\n <span style=\"color: #7060A8;\">cdCanvasSector</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hCdCanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">yc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasArc</span> <span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">hCdCanvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">xc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">yc</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">w</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">h</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">angle2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">yinyang</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">270</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">90</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">cdCanvasSecArc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">4</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">8</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">360</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">redraw_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*ih*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">min</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">40</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">cx</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">width</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">cy</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">height</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasActivate</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasClear</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">yinyang</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">*.</span><span style=\"color: #000000;\">43</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">*.</span><span style=\"color: #000000;\">43</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">6</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">yinyang</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cx</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">cy</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasFlush</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">map_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000000;\">ih</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupGLMakeCurrent</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">cd_canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_IUP</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetDouble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SCREENDPI\"</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">25.4</span>\n <span style=\"color: #000000;\">cd_canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">cdCreateCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">CD_GL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"10x10 %g\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #7060A8;\">cdCanvasSetBackground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_WHITE</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">cdCanvasSetForeground</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">CD_BLACK</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">canvas_resize_cb</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">Ihandle</span> <span style=\"color: #000080;font-style:italic;\">/*canvas*/</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">canvas_width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas_height</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetIntInt</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"DRAWSIZE\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGetDouble</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SCREENDPI\"</span><span style=\"color: #0000FF;\">)/</span><span style=\"color: #000000;\">25.4</span>\n <span style=\"color: #7060A8;\">cdCanvasSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">cd_canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"SIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"%dx%d %g\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">canvas_width</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">canvas_height</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #004600;\">IUP_DEFAULT</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupOpen</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #000000;\">canvas</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupGLCanvas</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"RASTERSIZE=340x340\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetCallbacks</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #008000;\">\"MAP_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"map_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"RESIZE_CB\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"canvas_resize_cb\"</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #008000;\">\"ACTION\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #7060A8;\">Icallback</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"redraw_cb\"</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #000000;\">dlg</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">IupDialog</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">`TITLE=\"Yin and Yang\"`</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupShow</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">dlg</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">IupSetAttribute</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">canvas</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #008000;\">\"RASTERSIZE\"</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004600;\">NULL</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- release the minimum limitation</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">platform</span><span style=\"color: #0000FF;\">()!=</span><span style=\"color: #004600;\">JS</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #7060A8;\">IupMainLoop</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #7060A8;\">IupClose</span><span style=\"color: #0000FF;\">()</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">main</span><span style=\"color: #0000FF;\">()</span>\n<!--\n", "language": "Phix" }, { "code": "module circles;\n\nextern printf;\n\n@Boolean in_circle(@Integer centre_x, @Integer centre_y, @Integer radius, @Integer x, @Integer y) [\n\treturn (x-centre_x)*(x-centre_x)+(y-centre_y)*(y-centre_y) <= radius*radius;\n]\n\n@Boolean in_big_circle (@Integer radius, @Integer x, @Integer y) [\n\treturn in_circle(0, 0, radius, x, y);\n]\n\n@Boolean in_while_semi_circle (@Integer radius, @Integer x, @Integer y) [\n\treturn in_circle(0, radius/2, radius/2, x, y);\n]\n\n@Boolean in_small_white_circle (@Integer radius, @Integer x, @Integer y) [\n\treturn in_circle(0, 0-radius/2, radius/6, x, y);\n]\n\n@Boolean in_black_semi_circle (@Integer radius, @Integer x, @Integer y) [\n\treturn in_circle(0, 0-radius/2, radius/2, x, y);\n]\n\n@Boolean in_small_black_circle (@Integer radius, @Integer x, @Integer y) [\n\treturn in_circle(0, radius/2, radius/6, x, y);\n]\n\n@Void print_yin_yang(@Integer radius) [\n\tvar white = '.';\n\tvar black = '#';\n\tvar clear = ' ';\n\n\tvar scale_y = 1;\n\tvar scale_x = 2;\n\tfor (var sy = radius*scale_y; sy >= -(radius*scale_y); sy=sy-1) {\n\t\tfor (var sx = -(radius*scale_x); sx <= radius*scale_x; sx=sx+1) {\n\t\t\tvar x = sx/(scale_x);\n\t\t\tvar y = sy/(scale_y);\n\t\t\t\n\t\t\tif (in_big_circle(radius, x, y)) {\n\t\t\t\tif (in_while_semi_circle(radius, x, y))\n\t\t\t\t\tif (in_small_black_circle(radius, x, y))\n\t\t\t\t\t\tprintf(\"%c\", black);\n\t\t\t\t\telse\n\t\t\t\t\t\tprintf(\"%c\", white);\n\t\t\t\telse if (in_black_semi_circle(radius, x, y))\n\t\t\t\t\tif (in_small_white_circle(radius, x, y))\n\t\t\t\t\t\tprintf(\"%c\", white);\n\t\t\t\t\telse\n\t\t\t\t\t\tprintf(\"%c\", black);\n\t\t\t\telse \tif (x < 0)\n\t\t\t\t\t\tprintf(\"%c\", white);\n\t\t\t\t\telse\n\t\t\t\t\t\tprintf(\"%c\", black);\n\t\t\t} else printf(\"%c\", clear);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n]\n\n@Integer main [\n\tprint_yin_yang(17);\n\tprint_yin_yang(8);\n\treturn 0;\n]\n", "language": "PHL" }, { "code": "(de circle (X Y C R)\n (>=\n (* R R)\n (+\n (* (setq X (/ X 2)) X)\n (* (dec 'Y C) Y) ) ) )\n\n(de yinYang (R)\n (for Y (range (- R) R)\n (for X (range (- 0 R R) (+ R R))\n (prin\n (cond\n ((circle X Y (- (/ R 2)) (/ R 6))\n \"#\" )\n ((circle X Y (/ R 2) (/ R 6))\n \".\" )\n ((circle X Y (- (/ R 2)) (/ R 2))\n \".\" )\n ((circle X Y (/ R 2) (/ R 2))\n \"#\" )\n ((circle X Y 0 R)\n (if (lt0 X) \".\" \"#\") )\n (T \" \") ) ) )\n (prinl) ) )\n", "language": "PicoLisp" }, { "code": "yinyang: procedure options(main);\n yinyang: procedure(r);\n circle: procedure(x, y, c, r) returns(bit);\n declare (x, y, c, r) fixed;\n return( r*r >= (x/2) * (x/2) + (y-c) * (y-c) );\n end circle;\n\n pixel: procedure(x, y, r) returns(char);\n declare (x, y, r) fixed;\n if circle(x, y, -r/2, r/6) then return('#');\n if circle(x, y, r/2, r/6) then return('.');\n if circle(x, y, -r/2, r/2) then return('.');\n if circle(x, y, r/2, r/2) then return('#');\n if circle(x, y, 0, r) then do;\n if x<0 then return('.');\n else return('#');\n end;\n return(' ');\n end pixel;\n\n declare (x, y, r) fixed;\n do y=-r to r;\n do x=-2*r to 2*r;\n put edit(pixel(x, y, r)) (A(1));\n end;\n put skip;\n end;\n end yinyang;\n\n call yinyang(4);\n put skip;\n call yinyang(8);\nend yinyang;\n", "language": "PL-I" }, { "code": "To run:\nStart up.\nClear the screen to the gray color.\nDraw the Taijitu symbol 4 inches wide at the screen's center.\nPut the screen's center into a spot. Move the spot 4 inches right.\nDraw the Taijitu symbol 2 inches wide at the spot.\nRefresh the screen.\nWait for the escape key.\nShut down.\n\nTo draw the Taijitu symbol some twips wide at a spot:\nImagine a box the twips high by the twips wide.\nImagine an ellipse given the box.\nCenter the ellipse on the spot.\nMask outside the ellipse.\nImagine a left half box with the screen's left and the screen's top and the spot's x coord and the screen's bottom.\nFill the left half with the white color.\nImagine a right half box with the spot's x coord and the screen's top and the screen's right and the screen's bottom.\nFill the right half with the black color.\nImagine a swirl ellipse given the box.\nScale the swirl given 1/2.\nPut the spot into an upper spot. Move the upper spot up the twips divided by 4.\nPut the spot into a lower spot. Move the lower spot down the twips divided by 4.\nFill the swirl on the upper spot with the white color.\nFill the swirl on the lower spot with the black color.\nPut the swirl into a dot.\nScale the dot given 1/4.\nFill the dot on the lower spot with the white color.\nFill the dot on the upper spot with the black color.\nUnmask everything.\nUse the fat pen.\nDraw the ellipse.\n", "language": "Plain-English" }, { "code": "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 400 400\n\n/fs 10 def\n/ed { exch def } def\n/dist { 3 -1 roll sub dup mul 3 1 roll sub dup mul add sqrt } def\n/circ {\n /r exch def\n [r neg 1 r {\n /y exch def\n [ r 2 mul neg 1 r 2 mul {\n /x ed x 2 div y 0 0 dist r .05 add gt {( )}{\n x 2 div y 0 r 2 div dist dup\n r 5 div le { pop (.) } {\n r 2 div le { (@) }{\n x 2 div y 0 r 2 div neg dist dup\n r 5 div le { pop (@)} {\n r 2 div le {(.)}{\n x 0 le {(.)}{(@)}ifelse\n } ifelse\n } ifelse\n } ifelse\n } ifelse\n } ifelse\n } for]\n } for]\n} def\n\n/dis { moveto gsave\n { grestore 0 fs 1.15 mul neg rmoveto gsave\n {show} forall\n } forall grestore\n} def\n\n/Courier findfont fs scalefont setfont\n\n11 circ 10 390 dis\n6 circ 220 180 dis\nshowpage\n%%EOF\n", "language": "PostScript" }, { "code": "// ====== General Scene setup ======\n#version 3.7;\nglobal_settings { assumed_gamma 2.2 }\n\ncamera{ location <0,2.7,4> look_at <0,.1,0> right x*1.6\n aperture .2 focal_point <1,0,0> blur_samples 200 variance 1/10000 }\nlight_source{<2,4,8>, 1 spotlight point_at 0 radius 10}\nsky_sphere {pigment {granite scale <1,.1,1> color_map {[0 rgb 1][1 rgb <0,.4,.6>]}}}\n#default {finish {diffuse .9 reflection {.1 metallic} ambient .3}\n normal {granite scale .2}}\nplane { y, -1 pigment {hexagon color rgb .7 color rgb .75 color rgb .65}\n normal {hexagon scale 5}}\n\n// ====== Declare one side of the symbol as a sum and difference of discs ======\n\n#declare yang =\ndifference {\n merge {\n difference {\n cylinder {0 <0,.1,0> 1} // flat disk\n box {-1 <1,1,0>} // cut in half\n cylinder {<.5,-.1,0> <.5,.2,0> .5} // remove half-cicle on one side\n }\n cylinder {<-.5,0,0> <-.5,.1,0> .5} // add on the other side\n cylinder {<.5,0,0> <.5,.1,0> .15} // also add a little dot\n }\n cylinder {<-.5,-.1,0> <-.5,.2,0> .15} // and carve out a hole\n pigment{color rgb 0.1}\n}\n\n// ====== The other side is white and 180-degree turned ======\n\n#declare yin =\nobject {\n yang\n rotate <0,180,0>\n pigment{color rgb 1}\n}\n\n// ====== Here we put the two together: ======\n\n#macro yinyang( ysize )\n union {\n object {yin}\n object {yang}\n scale ysize\n }\n#end\n\n// ====== Here we put one into a scene: ======\n\nobject { yinyang(1)\n translate -y*1.08 }\n\n// ====== And a bunch more just for fun: ======\n\n#declare scl=1.1;\n#while (scl > 0.01)\n\n object { yinyang(scl)\n rotate <0,180,0> translate <-scl*4,scl*2-1,0>\n rotate <0,scl*360,0> translate <-.5,0,0>}\n\n object { yinyang(scl)\n translate <-scl*4,scl*2-1,0>\n rotate <0,scl*360+180,0> translate <.5,0,0>}\n\n #declare scl = scl*0.85;\n#end\n", "language": "POV-Ray" }, { "code": "ying_yang(N) :-\n\tR is N * 100,\n\tsformat(Title, 'Yin Yang ~w', [N]),\n\tnew(W, window(Title)),\n\tnew(Wh, colour(@default, 255*255, 255*255, 255*255)),\n\tnew(Bl, colour(@default, 0, 0, 0)),\n\tCX is R + 50,\n\tCY is R + 50,\n\tR1 is R / 2,\n\tR2 is R / 8,\n\tCY1 is R1 + 50,\n\tCY2 is 3 * R1 + 50,\n\n\tnew(E, semi_disk(point(CX, CY), R, w, Bl)),\n\tnew(F, semi_disk(point(CX, CY), R, e, Wh)),\n\tnew(D1, disk(point(CX, CY1), R, Bl)),\n\tnew(D2, disk(point(CX, CY2), R, Wh)),\n\tnew(D3, disk(point(CX, CY1), R2, Wh)),\n\tnew(D4, disk(point(CX, CY2), R2, Bl)),\n\n\tsend_list(W, display, [E, F, D1, D2, D3, D4]),\n\n\tWD is 2 * R + 100,\n\tsend(W, size, size(WD, WD )),\n\tsend(W, open).\n\n:- pce_begin_class(semi_disk, path, \"Semi disk with color \").\n\ninitialise(P, C, R, O, Col) :->\n send(P, send_super, initialise),\n\tget(C, x, CX),\n\tget(C, y, CY),\n\tchoose(O, Deb, End),\n\tforall(between(Deb, End, I),\n\t ( X is R * cos(I * pi/180) + CX,\n\t\t Y is R * sin(I * pi/180) + CY,\n\t send(P, append, point(X,Y)))),\n\tsend(P, closed, @on),\n\tsend(P, fill_pattern, Col).\n\n:- pce_end_class.\n\nchoose(s, 0, 180).\nchoose(n, 180, 360).\nchoose(w, 90, 270).\nchoose(e, -90, 90).\n\n:- pce_begin_class(disk, ellipse, \"disk with color \").\n\ninitialise(P, C, R, Col) :->\n send(P, send_super, initialise, R, R),\n\tsend(P, center, C),\n\tsend(P, pen, 0),\n\tsend(P, fill_pattern, Col).\n\n:- pce_end_class.\n", "language": "Prolog" }, { "code": "Procedure Yin_And_Yang(x, y, radius)\n DrawingMode(#PB_2DDrawing_Outlined)\n Circle(x, y, 2 * radius, #Black) ;outer circle\n DrawingMode(#PB_2DDrawing_Default)\n LineXY(x, y - 2 * radius, x, y + 2 * radius, #Black)\n FillArea(x + 1, y, #Black, #Black)\n Circle(x, y - radius, radius - 1, #White)\n Circle(x, y + radius, radius - 1, #Black)\n Circle(x, y - radius, radius / 3, #Black) ;small contrasting inner circles\n Circle(x, y + radius, radius / 3, #White)\nEndProcedure\n\nIf CreateImage(0, 700, 700) And StartDrawing(ImageOutput(0))\n FillArea(1, 1, -1, #White)\n Yin_And_Yang(105, 105, 50)\n Yin_And_Yang(400, 400, 148)\n StopDrawing()\n ;\n UsePNGImageEncoder()\n path$ = SaveFileRequester(\"Save image\", \"Yin And yang.png\", \"*.png\", 0)\n If path$ <> \"\": SaveImage(0, path$, #PB_ImagePlugin_PNG, 0, 2): EndIf\nEndIf\n", "language": "PureBasic" }, { "code": "import math\ndef yinyang(n=3):\n\tradii = [i * n for i in (1, 3, 6)]\n\tranges = [list(range(-r, r+1)) for r in radii]\n\tsquares = [[ (x,y) for x in rnge for y in rnge]\n\t\t for rnge in ranges]\n\tcircles = [[ (x,y) for x,y in sqrpoints\n\t\t if math.hypot(x,y) <= radius ]\n\t\t for sqrpoints, radius in zip(squares, radii)]\n\tm = {(x,y):' ' for x,y in squares[-1]}\n\tfor x,y in circles[-1]:\n\t\tm[x,y] = '*'\n\tfor x,y in circles[-1]:\n\t\tif x>0: m[(x,y)] = '·'\n\tfor x,y in circles[-2]:\n\t\tm[(x,y+3*n)] = '*'\n\t\tm[(x,y-3*n)] = '·'\n\tfor x,y in circles[-3]:\n\t\tm[(x,y+3*n)] = '·'\n\t\tm[(x,y-3*n)] = '*'\n\treturn '\\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1])\n", "language": "Python" }, { "code": "from turtle import *\n\nmode('logo')\n\ndef taijitu(r):\n '''\\\n Draw a classic Taoist taijitu of the given radius centered on the current\n turtle position. The \"eyes\" are placed along the turtle's heading, the\n filled one in front, the open one behind.\n '''\n\n # useful derivative values\n r2, r4, r8 = (r >> s for s in (1, 2, 3))\n\n # remember where we started\n x0, y0 = start = pos()\n startcolour = color()\n startheading = heading()\n color('black', 'black')\n\n # draw outer circle\n pendown()\n circle(r)\n\n # draw two 'fishes'\n begin_fill(); circle(r, 180); circle(r2, 180); circle(-r2, 180); end_fill()\n\n # black 'eye'\n setheading(0); penup(); goto(-(r4 + r8) + x0, y0); pendown()\n begin_fill(); circle(r8); end_fill()\n\n # white 'eye'\n color('white', 'white'); setheading(0); penup(); goto(-(r+r4+r8) + x0, y0); pendown()\n begin_fill(); circle(r8); end_fill()\n\n # put the turtle back where it started\n penup()\n setpos(start)\n setheading(startheading)\n color(*startcolour)\n\n\nif __name__ == '__main__':\n # demo code to produce image at right\n reset()\n #hideturtle()\n penup()\n goto(300, 200)\n taijitu(200)\n penup()\n goto(-150, -150)\n taijitu(100)\n hideturtle()\n", "language": "Python" }, { "code": "[ $ \"turtleduck.qky\" loadfile ] now!\n\n [ -1 4 turn\n 2dup -v fly\n 1 4 turn\n 4 wide\n ' [ 0 0 0 ] colour\n ' [ 0 0 0 ] fill\n [ 2dup 2 1 v/ 1 2 arc\n 2dup -2 1 v/ 1 2 arc\n 2dup -v 1 2 arc ]\n 2dup -v 1 2 arc\n 1 4 turn\n 2dup 2 1 v/ fly\n ' [ 0 0 0 ] colour\n 1 wide\n ' [ 255 255 255 ] fill\n [ 2dup 7 1 v/ circle ]\n 2dup fly\n ' [ 255 255 255 ] colour\n ' [ 0 0 0 ] fill\n [ 2dup 7 1 v/ circle ]\n -2 1 v/ fly\n -1 4 turn ] is yinyang ( n/d --> )\n\n turtle\n -110 1 fly\n 100 1 yinyang\n 420 1 fly\n 300 1 yinyang\n", "language": "Quackery" }, { "code": "plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){\n\tsuppressMessages(require(\"plotrix\"))\n\tif(!add) plot(1:10, type=\"n\", xlim=c(0,s), ylim=c(0,s), xlab=\"\", ylab=\"\", xaxt=\"n\", yaxt=\"n\", bty=\"n\", asp=1)\n\tdraw.circle(x, y, r, border=\"white\", col= \"black\")\n\tdraw.ellipse(x, y, r, r, col=\"white\", angle=0, segment=c(90,270), arc.only=F)\n\tdraw.ellipse(x, y - r * 0.5, r * 0.5, r * 0.5, col=\"black\", border=\"black\", angle=0, segment=c(90,270), arc.only=F)\n\tdraw.circle(x, y - r * 0.5, r * 0.125, border=\"white\", col= \"white\")\n\tdraw.circle(x, y + r * 0.5, r * 0.5, col=\"white\", border=\"white\")\n\tdraw.circle(x, y + r * 0.5, r * 0.125, border=\"black\", lty=1, col= \"black\")\n\tdraw.circle(x, y, r, border=\"black\")\n}\npng(\"yin_yang.png\")\nplot.yin.yang()\nplot.yin.yang(1,7,1, add=T)\ndev.off()\n", "language": "R" }, { "code": "#lang racket\n(require slideshow/pict)\n\n(define (yin-yang d)\n (define base\n (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0)\n (inset/clip (disk d) (- (/ d 2)) 0 0 0)))\n (define with-top\n (ct-superimpose\n base\n (cc-superimpose (colorize (disk (/ d 2)) \"white\")\n (disk (/ d 8)))))\n (define with-bottom\n (cb-superimpose\n with-top\n (cc-superimpose (disk (/ d 2))\n (colorize (disk (/ d 8)) \"white\"))))\n (cc-superimpose with-bottom (circle d)))\n\n(yin-yang 200)\n", "language": "Racket" }, { "code": "sub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){\n say \"<circle cx='$cx' cy='$cy' r='$rad' fill='$fill' stroke='$stroke' stroke-width='1'/>\";\n}\n\nsub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) {\n my ($c, $w) = (1, 0);\n say \"<g transform='rotate($angle, $cx, $cy)'>\" if $angle;\n circle($rad, $cx, $cy, $fill, $stroke);\n say \"<path d='M $cx {$cy + $rad}A {$rad/2} {$rad/2} 0 0 $c $cx $cy \",\n \"{$rad/2} {$rad/2} 0 0 $w $cx {$cy - $rad} $rad $rad 0 0 $c $cx \",\n \"{$cy + $rad} z' fill='$stroke' stroke='none' />\";\n circle($rad/5, $cx, $cy + $rad/2, $fill, $stroke);\n circle($rad/5, $cx, $cy - $rad/2, $stroke, $fill);\n say \"</g>\" if $angle;\n}\n\nsay '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg height=\"400\" width=\"400\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\">';\n\nyin_yang(100, 130, 130);\nyin_yang(50, 300, 300);\n\nsay '</svg>';\n", "language": "Raku" }, { "code": "sub cheat_harder ($scale) { \"<span style=\\\"font-size:$scale%;\\\">&#x262f;</span>\"; }\n\nsay '<div>', cheat_harder(700), cheat_harder(350), '</div>';\n", "language": "Raku" }, { "code": "import util::Math;\nimport vis::Render;\nimport vis::Figure;\n\npublic void yinyang(){\n\ttemplate = ellipse(fillColor(\"white\"));\n\t\n\tsmallWhite = ellipse(fillColor(\"white\"), shrink(0.1), valign(0.75));\n\tsmallBlack = ellipse(fillColor(\"black\"), shrink(0.1), valign(0.25));\n\t\n\tdots= [ellipse(fillColor(\"white\"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/4, 0.25 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]];\n\tdots2 = [ellipse(fillColor(\"black\"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/-4, 0.75 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]];\n\tdots3= [ellipse(fillColor(\"black\"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/2, 0.5-cos(0.0031415*n)/-2)) | n <- [1 .. 1000]];\n\t\n\tblack= overlay([*dots, *dots2, *dots3], shapeConnected(true), shapeClosed(true), shapeCurved(true), fillColor(\"black\"));\n\t\n\trender(hcat([vcat([overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0)), space(), space()]),\n\t overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0))]));\n}\n", "language": "Rascal" }, { "code": "/*REXX program creates & displays an ASCII art version of the Yin─Yang (taijitu) symbol.*/\nparse arg s1 s2 . /*obtain optional arguments from the CL*/\nif s1=='' | s1==\",\" then s1= 17 /*Not defined? Then use the default. */\nif s2=='' | s2==\",\" then s2= s1 % 2 /* \" \" \" \" \" \" */\nif s1>0 then call Yin_Yang s1 /*create & display 1st Yin-Yang symbol.*/\nif s2>0 then call Yin_Yang s2 /* \" \" \" 2nd \" \" */\nexit 0 /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nin@: procedure; parse arg cy,r,x,y; return x**2 + (y-cy)**2 <= r**2\nbig@: /*in big circle. */ return in@( 0 , r , x, y )\nsemi@: /*in semi circle. */ return in@( r/2, r/2, x, y )\nsB@: /*in small black circle. */ return in@( r/2, r/6, x, y )\nsW@: /*in small white circle. */ return in@(-r/2, r/6, x, y )\nBsemi@: /*in black semi circle. */ return in@(-r/2, r/2, x, y )\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nYin_Yang: procedure; parse arg r; mX= 2; mY= 1 /*aspect multiplier for the X,Y axis.*/\n do sy= r*mY to -r*mY by -1; $= /*$ ≡ an output line*/\n do sx=-r*mX to r*mX; x= sx / mX; y= sy / mY /*apply aspect ratio*/\n if big@() then if semi@() then if sB@() then $= $'Θ'; else $= $\"°\"\n else if Bsemi@() then if sW@() then $= $'°'; else $= $\"Θ\"\n else if x<0 then $= $'°'; else $= $\"Θ\"\n else $= $' '\n end /*sy*/\n say strip($, 'T') /*display one line of a Yin─Yang symbol*/\n end /*sx*/; return\n", "language": "REXX" }, { "code": "Shoes.app(:width => 470, :height => 380) do\n PI = Shoes::TWO_PI/2\n\n strokewidth 1\n\n def yin_yang(x, y, radius)\n fill black; stroke black\n arc x, y, radius, radius, -PI/2, PI/2\n\n fill white; stroke white\n arc x, y, radius, radius, PI/2, -PI/2\n oval x-radius/4, y-radius/2, radius/2-1\n\n fill black; stroke black\n oval x-radius/4, y, radius/2-1\n oval x-radius/12, y-radius/4-radius/12, radius/6-1\n\n fill white; stroke white\n oval x-radius/12, y+radius/4-radius/12, radius/6-1\n\n nofill\n stroke black\n oval x-radius/2, y-radius/2, radius\n end\n\n yin_yang 190, 190, 360\n yin_yang 410, 90, 90\nend\n", "language": "Ruby" }, { "code": "use svg::node::element::Path;\n\nfn main() {\n let doc = svg::Document::new()\n .add(yin_yang(15.0, 1.0))\n .add(yin_yang(6.0, 0.7).set(\"transform\", \"translate(30)\"));\n svg::save(\"YinYang_rust.svg\", &doc.set(\"viewBox\", (-20, -20, 60, 40))).unwrap();\n}\n/// th - the thickness of the outline around yang\nfn yin_yang(r: f32, th: f32) -> Path {\n let (cr, cw, ccw) = (\",0,1,1,.1,0z\", \",0,0,1,0,\", \",0,0,0,0,\");\n let d = format!(\"M0,{0} a{0},{0}{cr} M0,{1} \", r + th, -r / 3.0) // main_circle\n + &format!(\"a{0},{0}{cr} m0,{r} a{0},{0}{cr} M0,0 \", r / 6.0) // eyes\n + &format!(\"A{0},{0}{ccw}{r} A{r},{r}{cw}-{r} A{0},{0}{cw}0\", r / 2.0); // yang\n Path::new().set(\"d\", d).set(\"fill-rule\", \"evenodd\")\n}\n", "language": "Rust" }, { "code": "import scala.swing.Swing.pair2Dimension\nimport scala.swing.{ MainFrame, Panel }\nimport java.awt.{ Color, Graphics2D }\n\nobject YinYang extends scala.swing.SimpleSwingApplication {\n var preferedSize = 500\n\n /** Draw a Taijitu symbol on the given graphics context.\n */\n def drawTaijitu(g: Graphics2D, size: Int) {\n val sizeMinsOne = size - 1\n // Preserve the color for the caller\n val colorSave = g.getColor()\n\n g.setColor(Color.WHITE)\n // Use fillOval to draw a filled in circle\n g.fillOval(0, 0, sizeMinsOne, sizeMinsOne)\n\n g.setColor(Color.BLACK)\n // Use fillArc to draw part of a filled in circle\n g.fillArc(0, 0, sizeMinsOne, sizeMinsOne, 270, 180)\n g.fillOval(size / 4, size / 2, size / 2, size / 2)\n\n g.setColor(Color.WHITE)\n g.fillOval(size / 4, 0, size / 2, size / 2)\n g.fillOval(7 * size / 16, 11 * size / 16, size / 8, size / 8)\n\n g.setColor(Color.BLACK)\n g.fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8)\n // Use drawOval to draw an empty circle for the outside border\n g.drawOval(0, 0, sizeMinsOne, sizeMinsOne)\n\n // Restore the color for the caller\n g.setColor(colorSave)\n }\n\n def top = new MainFrame {\n title = \"Rosetta Code >>> Yin Yang Generator | Language: Scala\"\n contents = gui(preferedSize)\n\n def gui(sizeInterior: Int) = new Panel() {\n preferredSize = (sizeInterior, sizeInterior)\n\n /** Draw a Taijitu symbol in this graphics context.\n */\n override def paintComponent(graphics: Graphics2D) = {\n super.paintComponent(graphics)\n\n // Color in the background of the image\n background = Color.RED\n drawTaijitu(graphics, sizeInterior)\n }\n } // def gui(\n }\n\n override def main(args: Array[String]) = {\n preferedSize = args.headOption.map(_.toInt).getOrElse(preferedSize)\n super.main(args)\n }\n}\n", "language": "Scala" }, { "code": "R = 1; //outer radius of first image\nscale = 0.5; //scale of the second image\n\nscf(0); clf();\nset(gca(),'isoview','on');\nxname('Yin and Yang');\n\n//First one\nn_p = 100; //number of points per arc\nangles = []; //angles for each arc\nangles = linspace(%pi/2, 3*%pi/2, n_p);\nArcs = zeros(7,n_p);\n\n Arcs(1,:) = R * exp(%i * angles);\n plot2d(real(Arcs(1,:)),imag(Arcs(1,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\n Arcs(2,:) = -%i*R/2 + R/2 * exp(%i * angles);\n plot2d(real(Arcs(2,:)),imag(Arcs(2,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\nangles = [];\nangles = linspace(-%pi/2, %pi/2, n_p);\n\n Arcs(3,:) = R * exp(%i * angles);\n plot2d(real(Arcs(3,:)), imag(Arcs(3,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\n Arcs(4,:) = %i*R/2 + R/2 * exp(%i * angles);\n plot2d(real(Arcs(4,:)),imag(Arcs(4,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\nangles = [];\nangles = linspace(0, 2*%pi, n_p);\n\n Arcs(5,:) = %i*R/2 + R/8 * exp(%i * angles);\n plot2d(real(Arcs(5,:)),imag(Arcs(5,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\n Arcs(6,:) = -%i*R/2 + R/8 * exp(%i * angles);\n plot2d(real(Arcs(6,:)),imag(Arcs(6,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\n Arcs(7,:) = R * exp(%i * angles);\n plot2d(real(Arcs(7,:)),imag(Arcs(7,:)));\n set(gca(),'axes_visible',['off','off','off']);\n\n//Scaling\nnew_pos = R + 2*R*scale;\nArcs = new_pos + Arcs .* scale;\n\n plot2d(real(Arcs(1,:)),imag(Arcs(1,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\n plot2d(real(Arcs(2,:)),imag(Arcs(2,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\n plot2d(real(Arcs(3,:)), imag(Arcs(3,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\n plot2d(real(Arcs(4,:)),imag(Arcs(4,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\n plot2d(real(Arcs(5,:)),imag(Arcs(5,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n\n plot2d(real(Arcs(6,:)),imag(Arcs(6,:)));\n line = gce();\n set(line.children,'polyline_style',5);\n set(line.children,'foreground',8);\n\n plot2d(real(Arcs(7,:)),imag(Arcs(7,:)));\n set(gca(),'axes_visible',['off','off','off']);\n", "language": "Scilab" }, { "code": "$ include \"seed7_05.s7i\";\n include \"float.s7i\";\n include \"math.s7i\";\n include \"draw.s7i\";\n include \"keybd.s7i\";\n\nconst proc: yinYang (in integer: xPos, in integer: yPos, in integer: size) is func\n begin\n pieslice(xPos, yPos, size, 3.0 * PI / 2.0, PI, black);\n pieslice(xPos, yPos, size, PI / 2.0, PI, white);\n fcircle(xPos, yPos - size div 2, size div 2, white);\n fcircle(xPos, yPos + size div 2, size div 2, black);\n fcircle(xPos, yPos - size div 2, size div 6, black);\n fcircle(xPos, yPos + size div 2, size div 6, white);\n circle(xPos, yPos, size, black);\n end func;\n\nconst proc: main is func\n begin\n screen(640, 480);\n clear(white);\n KEYBOARD := GRAPH_KEYBOARD;\n yinYang(100, 100, 80);\n yinYang(400, 250, 200);\n readln(KEYBOARD);\n end func;\n", "language": "Seed7" }, { "code": "program yin_yang;\n print(taijitu 4);\n print(taijitu 8);\n\n op taijitu(r);\n return +/[+/[pixel(x,y,r) : x in [-2*r..2*r]] + \"\\n\" : y in [-r..r]];\n end op;\n\n proc pixel(x,y,r);\n return if circle(x,y,-r/2,r/6) then '#'\n elseif circle(x,y,r/2,r/6) then '.'\n elseif circle(x,y,-r/2,r/2) then '.'\n elseif circle(x,y,r/2,r/2) then '#'\n elseif circle(x,y,0,r) then\n if x<0 then '.' else '#' end\n else ' '\n end;\n end proc;\n\n proc circle(x,c,y,r);\n return r*r >= (x/2)**2 + (y-c)**2;\n end proc;\nend program;\n", "language": "SETL" }, { "code": "func circle (rad, cx, cy, fill='white', stroke='black') {\n say \"<circle cx='#{cx}' cy='#{cy}' r='#{rad}' fill='#{fill}' stroke='#{stroke}' stroke-width='1'/>\";\n}\n\nfunc yin_yang (rad, cx, cy, fill='white', stroke='black', angle=90) {\n var (c, w) = (1, 0);\n angle != 0 && say \"<g transform='rotate(#{angle}, #{cx}, #{cy})'>\";\n circle(rad, cx, cy, fill, stroke);\n say(\"<path d='M #{cx} #{cy + rad}A #{rad/2} #{rad/2} 0 0 #{c} #{cx} #{cy} \",\n \"#{rad/2} #{rad/2} 0 0 #{w} #{cx} #{cy - rad} #{rad} #{rad} 0 0 #{c} #{cx} \",\n \"#{cy + rad} z' fill='#{stroke}' stroke='none' />\");\n circle(rad/5, cx, cy + rad/2, fill, stroke);\n circle(rad/5, cx, cy - rad/2, stroke, fill);\n angle != 0 && say \"</g>\";\n}\n\nsay '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">';\n\nyin_yang(40, 50, 50);\nyin_yang(20, 120, 120);\n\nsay '</svg>';\n", "language": "Sidef" }, { "code": "package require Tcl 8.5\npackage require Tk\n\nnamespace import tcl::mathop::\\[-+\\] ;# Shorter coordinate math\nproc yinyang {c x y r {colors {white black}}} {\n lassign $colors a b\n set tt [expr {$r * 2 / 3.0}]\n set h [expr {$r / 2.0}]\n set t [expr {$r / 3.0}]\n set s [expr {$r / 6.0}]\n $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \\\n\t-fill $a -outline {} -extent 180 -start 90\n $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \\\n\t-fill $b -outline {} -extent 180 -start 270\n $c create oval [- $x $h] [- $y $r] [+ $x $h] $y \\\n\t-fill $a -outline {}\n $c create oval [- $x $h] [+ $y $r] [+ $x $h] $y \\\n\t-fill $b -outline {}\n $c create oval [- $x $s] [- $y $tt] [+ $x $s] [- $y $t] \\\n\t-fill $b -outline {}\n $c create oval [- $x $s] [+ $y $tt] [+ $x $s] [+ $y $t] \\\n\t-fill $a -outline {}\n}\n\npack [canvas .c -width 300 -height 300 -background gray50]\nyinyang .c 110 110 90\nyinyang .c 240 240 40\n", "language": "Tcl" }, { "code": "#!/usr/bin/env bash\nin_circle() { #(cx, cy, r, x y)\n # return true if the point (x,y) lies within the circle of radius r centered\n # on (cx,cy)\n # (but really scaled to an ellipse with vertical minor semiaxis r and\n # horizontal major semiaxis 2r)\n local -i cx=$1 cy=$2 r=$3 x=$4 y=$5\n local -i dx dy\n (( dx=(x-cx)/2, dy=y-cy, dx*dx + dy*dy <= r*r ))\n}\n\ntaijitu() { #radius\n local -i radius=${1:-17}\n local -i x1=0 y1=0 r1=radius # outer circle\n local -i x2=0 y2=-radius/2 r2=radius/6 # upper eye\n local -i x3=0 y3=-radius/2 r3=radius/2 # upper half\n local -i x4=0 y4=+radius/2 r4=radius/6 # lower eye\n local -i x5=0 y5=+radius/2 r5=radius/2 # lower half\n local -i x y\n for (( y=radius; y>=-radius; --y )); do\n for (( x=-2*radius; x<=2*radius; ++x)); do\n if ! in_circle $x1 $y1 $r1 $x $y; then\n printf ' '\n elif in_circle $x2 $y2 $r2 $x $y; then\n printf '#'\n elif in_circle $x3 $y3 $r3 $x $y; then\n printf '.'\n elif in_circle $x4 $y4 $r4 $x $y; then\n printf '.'\n elif in_circle $x5 $y5 $r5 $x $y; then\n printf '#'\n elif (( x <= 0 )); then\n printf '.'\n else\n printf '#'\n fi\n done\n printf '\\n'\n done\n}\n", "language": "UNIX-Shell" }, { "code": "Private Sub yinyang(Top As Integer, Left As Integer, Size As Integer)\n ActiveSheet.Shapes.AddShape(msoShapeChord, Top, Left, Size, Size).Select\n With Selection.ShapeRange\n .Adjustments.Item(1) = 90\n .Fill.ForeColor.RGB = RGB(255, 255, 255)\n .Line.ForeColor.RGB = RGB(0, 0, 0)\n End With\n ActiveSheet.Shapes.AddShape(msoShapeChord, Top, Left, Size, Size).Select\n With Selection.ShapeRange\n .Adjustments.Item(1) = 90\n .IncrementRotation 180\n .Fill.ForeColor.RGB = RGB(0, 0, 0)\n .Line.ForeColor.RGB = RGB(0, 0, 0)\n End With\n ActiveSheet.Shapes.AddShape(msoShapeOval, Top + Size \\ 4, Left, Size \\ 2, Size \\ 2).Select\n With Selection.ShapeRange\n .Fill.ForeColor.RGB = RGB(255, 255, 255)\n .Line.ForeColor.RGB = RGB(255, 255, 255)\n End With\n ActiveSheet.Shapes.AddShape(msoShapeOval, Top + Size \\ 4, Left + Size \\ 2, Size \\ 2, Size \\ 2).Select\n With Selection.ShapeRange\n .Fill.ForeColor.RGB = RGB(0, 0, 0)\n .Line.ForeColor.RGB = RGB(0, 0, 0)\n End With\n ActiveSheet.Shapes.AddShape(msoShapeOval, Top + 5 * Size \\ 12, Left + Size \\ 6, Size \\ 6, Size \\ 6).Select\n With Selection.ShapeRange\n .Fill.ForeColor.RGB = RGB(0, 0, 0)\n .Line.ForeColor.RGB = RGB(0, 0, 0)\n End With\n ActiveSheet.Shapes.AddShape(msoShapeOval, Top + 5 * Size \\ 12, Left + 2 * Size \\ 3, Size \\ 6, Size \\ 6).Select\n With Selection.ShapeRange\n .Fill.ForeColor.RGB = RGB(255, 255, 255)\n .Line.ForeColor.RGB = RGB(255, 255, 255)\n End With\n ActiveSheet.Shapes.SelectAll\n Selection.ShapeRange.Group\nEnd Sub\nPublic Sub draw()\n yinyang 200, 100, 100\n yinyang 275, 175, 25\nEnd Sub\n", "language": "VBA" }, { "code": "Imports System.Drawing\nImports System.Windows.Forms\n\nModule Program\n ''' <summary>\n ''' Draws a Taijitu symbol on the specified <see cref=\"Graphics\" /> surface at a specified location with a specified size.\n ''' </summary>\n ''' <param name=\"g\">The <see cref=\"Graphics\" /> surface to draw on.</param>\n ''' <param name=\"location\">The coordinates of the upper-left corner of the bounding rectangle that defines the symbol.</param>\n ''' <param name=\"diameter\">The diameter of the symbol, or the width and height of its bounding rectangle.</param>\n ''' <param name=\"drawOutline\">Whether to draw an outline around the symbol.</param>\n Sub DrawTaijitu(g As Graphics, location As PointF, diameter As Single, drawOutline As Boolean)\n Const sixth = 1 / 6\n\n g.ResetTransform()\n g.TranslateTransform(location.X, location.Y)\n g.ScaleTransform(diameter, diameter)\n\n g.FillPie(Brushes.Black, x:=0, y:=0, width:=1, height:=1, startAngle:=90, sweepAngle:=180) ' Left half.\n g.FillPie(Brushes.White, x:=0, y:=0, width:=1, height:=1, startAngle:=270, sweepAngle:=180) ' Right half.\n g.FillEllipse(Brushes.Black, x:=0.25, y:=0, width:=0.5, height:=0.5) ' Upper ball.\n g.FillEllipse(Brushes.White, x:=0.25, y:=0.5, width:=0.5, height:=0.5) ' Lower ball.\n g.FillEllipse(Brushes.White, x:=0.5 - sixth / 2, y:=sixth, width:=sixth, height:=sixth) ' Upper dot.\n g.FillEllipse(Brushes.Black, x:=0.5 - sixth / 2, y:=4 * sixth, width:=sixth, height:=sixth) ' Lower dot.\n\n If drawOutline Then\n Using p As New Pen(Color.Black, width:=2 / diameter)\n g.DrawEllipse(p, x:=0, y:=0, width:=1, height:=1)\n End Using\n End If\n End Sub\n\n ''' <summary>\n ''' Draws one large and one small Taijitu symbol on the specified <see cref=\"Graphics\" /> surface.\n ''' </summary>\n ''' <param name=\"g\">The <see cref=\"Graphics\" /> surface to draw on.</param>\n ''' <param name=\"bounds\">The width and height of the area to draw in.</param>\n Sub DrawDemo(g As Graphics, bounds As Single)\n Const PADDING = 10\n Dim ACTUAL = bounds - (PADDING * 2)\n\n g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias\n\n DrawTaijitu(g, location:=New PointF(PADDING, PADDING), diameter:=ACTUAL / 4, drawOutline:=True)\n DrawTaijitu(g, location:=New PointF(PADDING + (bounds / 5), PADDING + (ACTUAL / 5)), diameter:=ACTUAL * 4 / 5, drawOutline:=True)\n End Sub\n\n Sub Main(args As String())\n If args.Length = 0 Then\n Using frm As New YinYangForm()\n frm.ShowDialog()\n End Using\n\n Else\n Dim imageSize = Integer.Parse(args(0), Globalization.CultureInfo.InvariantCulture)\n\n Using bmp As New Bitmap(imageSize, imageSize),\n g = Graphics.FromImage(bmp),\n output = Console.OpenStandardOutput()\n\n Try\n DrawDemo(g, imageSize)\n bmp.Save(output, Imaging.ImageFormat.Png)\n Catch ex As Exception\n MessageBox.Show(\"Specified size is too small\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n End Try\n End Using\n End If\n End Sub\n\n Private Class YinYangForm\n Inherits Form\n\n Sub Form_Paint() Handles Me.Paint\n Dim availableSize = Math.Min(Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)\n Dim g As Graphics\n Try\n g = Me.CreateGraphics()\n DrawDemo(g, availableSize)\n Catch ex As Exception\n MessageBox.Show(\"Window size too small.\", \"Exception thrown\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n Finally\n If g IsNot Nothing Then g.Dispose()\n End Try\n End Sub\n End Class\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "Imports System.IO\n\n' Yep, VB.NET can import XML namespaces. All literals have xmlns changed, while xmlns:xlink is only\n' declared in literals that use it directly (e.g. the output of this program has it defined in both\n' of the <use /> tags and not the root, <svg />).\nImports <xmlns=\"http://www.w3.org/2000/svg\">\nImports <xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n\nModule Program\n Sub Main()\n Dim doc =\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<svg version=\"1.1\" width=\"30\" height=\"30\">\n <defs>\n <g id=\"y\">\n <circle cx=\"0\" cy=\"0\" r=\"200\" stroke=\"black\"\n fill=\"white\" stroke-width=\"1\"/>\n <path d=\"M0 -200 A 200 200 0 0 0 0 200 100 100 0 0 0 0 0 100 100 0 0 1 0 -200 z\" fill=\"black\"/>\n <circle cx=\"0\" cy=\"100\" r=\"33\" fill=\"white\"/>\n <circle cx=\"0\" cy=\"-100\" r=\"33\" fill=\"black\"/>\n </g>\n </defs>\n</svg>\n\n ' XML literals don't support DTDs.\n Dim type As New XDocumentType(name:=\"svg\", publicId:=\"-//W3C//DTD SVG 1.1//EN\", systemId:=\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\", internalSubset:=Nothing)\n doc.AddFirst(type)\n\n Dim draw_yinyang =\n Sub(trans As Double, scale As Double) doc.Root.Add(<use xlink:href=\"#y\" transform=<%= $\"translate({trans},{trans}) scale({scale})\" %>/>)\n\n draw_yinyang(20, 0.05)\n draw_yinyang(8, 0.02)\n\n Using s = Console.OpenStandardOutput(),\n sw As New StreamWriter(s)\n doc.Save(sw, SaveOptions.OmitDuplicateNamespaces)\n sw.WriteLine()\n End Using\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg version=\"1.1\" width=\"30\" height=\"30\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <g id=\"y\">\n <circle cx=\"0\" cy=\"0\" r=\"200\" stroke=\"black\" fill=\"white\" stroke-width=\"1\" />\n <path d=\"M0 -200 A 200 200 0 0 0 0 200 100 100 0 0 0 0 0 100 100 0 0 1 0 -200 z\" fill=\"black\" />\n <circle cx=\"0\" cy=\"100\" r=\"33\" fill=\"white\" />\n <circle cx=\"0\" cy=\"-100\" r=\"33\" fill=\"black\" />\n </g>\n </defs>\n <use xlink:href=\"#y\" transform=\"translate(20,20) scale(0.05)\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" />\n <use xlink:href=\"#y\" transform=\"translate(8,8) scale(0.02)\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" />\n</svg>\n", "language": "Visual-Basic-.NET" }, { "code": "Module Program\n Sub Main()\n Console.OutputEncoding = Text.Encoding.Unicode\n Dim cheat_harder = Function(scale As Integer) <span style=<%= $\"font-size:{scale}%;\" %>>&#x262f;</span>\n Console.WriteLine(<div><%= cheat_harder(700) %><%= cheat_harder(350) %></div>)\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "<div>\n <span style=\"font-size:700%;\">☯</span>\n <span style=\"font-size:350%;\">☯</span>\n</div>\n", "language": "Visual-Basic-.NET" }, { "code": "var inCircle = Fn.new { |centerX, centerY, radius, x, y|\n return (x-centerX)*(x-centerX)+(y-centerY)*(y-centerY) <= radius*radius\n}\n\nvar inBigCircle = Fn.new { |radius, x, y| inCircle.call(0, 0, radius, x, y) }\n\nvar inBlackSemiCircle = Fn.new { |radius, x, y| inCircle.call(0, -radius/2, radius/2, x, y) }\n\nvar inWhiteSemiCircle = Fn.new { |radius, x, y| inCircle.call(0, radius/2, radius/2, x, y) }\n\nvar inSmallBlackCircle = Fn.new { |radius, x, y| inCircle.call(0, radius/2, radius/6, x, y) }\n\nvar inSmallWhiteCircle = Fn.new { |radius, x, y| inCircle.call(0, -radius/2, radius/6, x, y) }\n\nvar yinAndYang = Fn.new { |radius|\n var black = \"#\"\n var white = \".\"\n var scaleX = 2\n var scaleY = 1\n for (sy in radius*scaleY..-(radius*scaleY)) {\n for (sx in -(radius*scaleX)..(radius*scaleX)) {\n var x = sx / scaleX\n var y = sy / scaleY\n if (inBigCircle.call(radius, x, y)) {\n if (inWhiteSemiCircle.call(radius, x, y)) {\n System.write(inSmallBlackCircle.call(radius, x, y) ? black : white)\n } else if (inBlackSemiCircle.call(radius, x, y)) {\n System.write(inSmallWhiteCircle.call(radius, x, y) ? white : black)\n } else {\n System.write((x < 0) ? white : black)\n }\n } else {\n System.write(\" \")\n }\n }\n System.print()\n }\n}\n\nyinAndYang.call(16)\nyinAndYang.call(8)\n", "language": "Wren" }, { "code": "import \"dome\" for Window\nimport \"graphics\" for Canvas, Color\n\nclass YinAndYang {\n construct new(width, height) {\n Window.title = \"Yin and Yang\"\n Window.resize(width, height)\n Canvas.resize(width, height)\n }\n\n init() {\n Canvas.cls(Color.yellow)\n yinAndYang(200, 220, 220)\n yinAndYang(100, 460, 460)\n }\n\n inCircle(centerX, centerY, radius, x, y) {\n return (x-centerX)*(x-centerX)+(y-centerY)*(y-centerY) <= radius*radius\n }\n\n inBigCircle(radius, x, y) { inCircle(0, 0, radius, x, y) }\n\n inBlackSemiCircle(radius, x, y) { inCircle(0, radius/2, radius/2, x, y) }\n\n inWhiteSemiCircle(radius, x, y) { inCircle(0, -radius/2, radius/2, x, y) }\n\n inSmallBlackCircle(radius, x, y) { inCircle(0, -radius/2, radius/6, x, y) }\n\n inSmallWhiteCircle(radius, x, y) { inCircle(0, radius/2, radius/6, x, y) }\n\n yinAndYang(radius, ox, oy) {\n Canvas.offset(ox, oy)\n var scaleX = 2\n var scaleY = 1\n for (sy in radius*scaleY..-(radius*scaleY)) {\n for (sx in -(radius*scaleX)..(radius*scaleX)) {\n var x = sx / scaleX\n var y = sy / scaleY\n if (inBigCircle(radius, x, y)) {\n if (inWhiteSemiCircle(radius, x, y)) {\n var c = inSmallBlackCircle(radius, x, y) ? Color.black : Color.white\n Canvas.pset(x, y, c)\n } else if (inBlackSemiCircle(radius, x, y)) {\n var c = inSmallWhiteCircle(radius, x, y) ? Color.white : Color.black\n Canvas.pset(x, y, c)\n } else {\n var c = (x < 0) ? Color.white : Color.black\n Canvas.pset(x, y, c)\n }\n }\n }\n }\n }\n\n update() {}\n\n draw(alpha) {}\n}\n\nvar Game = YinAndYang.new(600, 600)\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\n\ndef Black=0, Red=4, White=$F;\n\nproc Circle(X0, Y0, R, CL, CR); \\Show a filled circle\nint X0, Y0, R, CL, CR; \\left and right half colors\nint X, Y;\n[for Y:= -R to R do\n for X:= -R to R do\n if X*X + Y*Y <= R*R then\n Point(X+X0, Y+Y0, if X<0 then CL else CR);\n]; \\Circle\n\nproc YinYang(X0, Y0, R);\nint X0, Y0, R;\n[Circle(X0, Y0, R, White, Black);\n Circle(X0, Y0-R/2, R/2, White, White);\n Circle(X0, Y0-R/2, R/6, Black, Black);\n Circle(X0, Y0+R/2, R/2, Black, Black);\n Circle(X0, Y0+R/2, R/6, White, White);\n]; \\YinYang\n\n[SetVid($101); \\640x480 graphics\nCircle(320, 240, 400, Red, Red);\\fill screen with background color\nYinYang(80, 80, 70);\nYinYang(240, 240, 150);\nif ChIn(1) then []; \\wait for keystroke\nSetVid(3); \\restore normal text mode\n]\n", "language": "XPL0" }, { "code": "open window 640, 480\n\ncolor 0,0,0\nclear window\n\ntaijitu(640/2, 480/2, 480/4)\ntaijitu(100,100,50)\n\nsub taijitu(x,y,r)\n\tfill circle x,y,r\n\tcolor 255,255,255\n\tfill circle x,y,r-4\n\tcolor 0,0,0\n\tline x, y-r to x, y+r\n\tinfill(x-2, y-2)\n\tfill circle x,y-r/2,r/2\t\n\tcolor 255,255,255\n\tfill circle x,y+r/2-2,r/2-1\n\tfill circle x,y-r/2-2,r/8-1\n\tcolor 0,0,0\n\tfill circle x,y+r/2-2,r/8-1\nend sub\n\nsub infill(x,y)\n\tlocal oy,lx,rx,nx,i,m,t,l$,r$,a$,test$\n\ttest$=getbit$(x,y,x,y)\t\t// get a sample of fill area\n\toy=y-1 : lx=x : rx=x : m=1\t// m=1 makes go downwards\n\tfor t=1 to 2\n\t\trepeat\n\t\t\trepeat\n\t\t\t\tl$=getbit$(lx,y,lx,y)\n\t\t\t\tlx=lx-1 : if lx<0 break \t// test how far left to go\n\t\t\tuntil (l$<>test$)\n\t\t\trepeat\n\t\t\t\t r$=getbit$(rx,y,rx,y)\n\t\t\t\t rx=rx+1 : if rx>peek(\"winwidth\") break \t// test how far right to go\n\t\t\tuntil (r$<>test$)\n\t\t\tlx=lx+2 : rx=rx-2 : line lx,y to rx,y \t\t\t// draw line across fill area\n\t\t\tnx=0\n\t\t\tfor i=lx to rx\n\t\t\t\ta$=getbit$(i,y+m,i,y+m)\t\t\t\t// get sample for next line\n\t\t\t\tif a$=test$ let nx=i : break\t\t\t// test if new cycle reqd\n\t\t\tnext i\n\t\t\tlx=nx : rx=nx\n\t\t\ty=y+m : if (y<0 or y>peek(\"winheight\")) break\t\t// test how far up or down to go\n\t\tuntil (nx=0)\n\t\tlx=x : rx=x : y=oy : m=-1\t\t\t\t\t// m=-1 makes go upwards\t\t\t\t\t\t\n\tnext t\nend sub\n", "language": "Yabasic" }, { "code": "open window 640, 480\nbackcolor 255,0,0\ncolor 0,0,0\nclear window\n\ntaijitu(640/2, 480/2, 480/4)\ntaijitu(100,100,50)\n\nsub taijitu(x,y,r)\n\tlocal n, x1, x2, y1, y2\n\t\n\tfor n = 0 to pi*1.5 step pi/r\n\t\tx1 = x + (r / 2) * cos(n) : y1 = y + (r / 2) * sin(n)\n\t\tx2 = x - (r / 2) * cos(n) : y2 = y - (r / 2) * sin(n)\n\t\tcolor 0, 0, 0 : fill circle x1, y1, r/2\n\t\tcolor 255, 255, 255 : fill circle x1, y1, r/4\n\t\tcolor 255, 255, 255 : fill circle x2, y2, r/2\n\t\tcolor 0, 0, 0 : fill circle x2, y2, r/4\n\t\tpause .025\n\tnext n\nend sub\n", "language": "Yabasic" }, { "code": "fcn draw_yinyang(trans,scale){\n 0'|<use xlink:href=\"#y\" transform=\"translate(%d,%d) scale(%g)\"/>|\n .fmt(trans,trans,scale).print();\n}\n\nprint(\n\"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\\n\"\n\"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\\n\"\n\"\t'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\\n\"\n\"<svg xmlns='http://www.w3.org/2000/svg' version='1.1'\\n\"\n\"\txmlns:xlink='http://www.w3.org/1999/xlink'\\n\"\n\"\t\twidth='30' height='30'>\\n\"\n\"\t<defs><g id='y'>\\n\"\n\"\t\t<circle cx='0' cy='0' r='200' stroke='black'\\n\"\n\"\t\t\tfill='white' stroke-width='1'/>\\n\"\n\"\t\t<path d='M0 -200 A 200 200 0 0 0 0 200\\n\"\n\"\t\t\t100 100 0 0 0 0 0 100 100 0 0 1 0 -200\\n\"\n\"\t\t\tz' fill='black'/>\\n\"\n\"\t\t<circle cx='0' cy='100' r='33' fill='white'/>\\n\"\n\"\t\t<circle cx='0' cy='-100' r='33' fill='black'/>\\n\"\n\"\t</g></defs>\\n\");\n\ndraw_yinyang(20, 0.05);\ndraw_yinyang( 8, 0.02);\nprint(\"</svg>\");\n", "language": "Zkl" }, { "code": "10 CLS\n20 LET i=0\n30 PRINT \"Recommended size is a multiple of 4 between 40 and 80\": REM smaller sizes don't render properly and larger ones don't fit\n40 INPUT \"Size? \";s\n50 IF size>87 THEN GOTO 50: REM size check\n60 INPUT \"Position?\";t\n70 IF t<s OR t+s>254 THEN GOTO 60\n80 INK i\n90 CIRCLE t,s/2,s/2\n100 CIRCLE t,s*1.5,s/2\n110 CIRCLE t,s*1.5,s/4\n120 CIRCLE t,s/2,s/4: REM we draw the big circle later\n130 LET bxl=t-s/4: REM these four variables define the bounding box for the fill routine\n140 LET bxr=t+s/4\n150 LET byb=s*1.25+1\n160 LET byt=s*1.75-1\n170 GOSUB 9000: REM fill top small circle first\n180 LET bxl=t-s/2\n190 LET bxr=t+s/2\n200 LET byb=1\n210 LET byt=s-1\n220 GOSUB 9000: REM lower ring\n230 PLOT t,s*.75\n240 DRAW OVER 1;s/2,0\n250 PLOT t,s*.25\n260 DRAW OVER 1;s/2,0: REM fix top and bottom edges of lower circle - the top and bottom of a ZX Basic circle are horizontal lines, which screws with the parity fill\n270 CIRCLE t,s/2,s/4\n280 CIRCLE t,s,s: REM now draw the big circle - it would have clashed with the ring bounding box earlier\n290 LET bxl=t\n300 LET bxr=t+s\n310 LET byb=s+1\n320 LET byt=s*1.25-1\n330 GOSUB 9000: REM right half, top, lower quadrant - we have to fill it in three goes\n340 LET bxl=t+s*.25+1\n350 LET byb=byt+1\n360 LET byt=s*1.75\n370 GOSUB 9000: REM right half, top, right of spot - we move bxl to the right of the spot to make sure it doesn't clash\n380 LET bxl=t\n390 LET byb=byt+1\n400 LET byt=s*2-2\n410 GOSUB 9000: REM finish top right - bounding box stops two pixels short to prevent parity faults\n420 LET byb=2\n430 LET byt=s/4\n440 GOSUB 9000: REM bottom of right side done in similar manner\n450 LET bxl=t+s/4+1\n460 LET byb=byt+1\n470 LET byt=s*.75\n480 GOSUB 9000\n490 LET bxl=t\n500 LET byb=byt+1\n510 LET byt=s-1\n520 GOSUB 9000\n530 PLOT t,s\n540 DRAW s-1,0: REM missing line in right side - would have messed up during the fill cycle\n550 CIRCLE OVER 1;t,s*1.5,s/2: REM remove top wide circle to clear left loop\n560 CIRCLE t,s,s: REM repair big circle, done!\n570 INPUT \"Again? \";a$\n580 IF a$=\"y\" THEN LET i=i+1: GO TO 40\n590 INK 0\n600 STOP\n\n8999 REM area fill; checks along each pixel line and starts and stops PLOTting if it hits a boundary\n9000 FOR y=byb TO byt\n9010 LET p=0: REM parity\n9020 FOR x=bxl TO bxr\n9030 LET r1=POINT (x,y): REM POINT is 1 if the pixel at (x,y) is filled (INK), otherwise 0\n9040 LET r2=POINT (x+1,y): REM test next point as well, in case of edges rendered as multiple pixels\n9050 IF r1=1 AND r2=0 THEN LET p=p+1: IF p=2 THEN LET p=0: REM boundary check\n9060 IF p=1 THEN PLOT x,y\n9070 NEXT x\n9080 NEXT y\n9090 RETURN\n", "language": "ZX-Spectrum-Basic" } ]
Yin-and-yang
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Zeckendorf_arithmetic\nnote: Arithmetic operations\n", "language": "00-META" }, { "code": "This task is a ''total immersion'' zeckendorf task; using decimal numbers will attract serious disapprobation.\n\nThe task is to implement addition, subtraction, multiplication, and division using [[Zeckendorf number representation]]. [[Zeckendorf number representation#Using_a_C.2B.2B11_User_Defined_Literal|Optionally]] provide decrement, increment and comparitive operation functions.\n\n;Addition\nLike binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case. \n\nOccurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;\n\n;Subtraction\n10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:\n<pre>\n abcde\n 10100 -\n 1000\n _____\n 100 borrow 1 from a leaves 100\n + 100 add the carry\n _____\n 1001\n</pre>\nA larger example:\n<pre>\n abcdef\n 100100 -\n 1000\n ______\n 1*0100 borrow 1 from b\n + 100 add the carry\n ______\n 1*1001\n\nSadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:\n\n 1001\n + 1000 add the carry\n ____\n 10100\n</pre>\n\n;Multiplication\nHere you teach your computer its zeckendorf tables. eg. 101 * 1001:\n<pre>\n a = 1 * 101 = 101\n b = 10 * 101 = a + a = 10000\n c = 100 * 101 = b + a = 10101\n d = 1000 * 101 = c + b = 101010\n\n 1001 = d + a therefore 101 * 1001 =\n \n 101010\n + 101\n ______\n 1000100\n</pre>\n\n;Division\nLets try 1000101 divided by 101, so we can use the same table used for multiplication.\n<pre>\n 1000101 -\n 101010 subtract d (1000 * 101)\n _______\n 1000 -\n 101 b and c are too large to subtract, so subtract a\n ____\n 1 so 1000101 divided by 101 is d + a (1001) remainder 1\n</pre>\n\n[http://arxiv.org/pdf/1207.4497.pdf Efficient algorithms for Zeckendorf arithmetic] is interesting. The sections on addition and subtraction are particularly relevant for this task.\n\n", "language": "00-TASK" }, { "code": "T Zeckendorf\n Int dLen\n dVal = 0\n\n F (x = ‘0’)\n V q = 1\n V i = x.len - 1\n .dLen = i I/ 2\n L i >= 0\n .dVal = .dVal + (x[i].code - ‘0’.code) * q\n q = q * 2\n i = i - 1\n\n F a(n)\n V i = n\n L\n I .dLen < i\n .dLen = i\n V j = (.dVal >> (i * 2)) [&] 3\n I j == 0 | j == 1\n R\n I j == 2\n I (.dVal >> ((i + 1) * 2) [&] 1) != 1\n R\n .dVal = .dVal + (1 << (i * 2 + 1))\n R\n I j == 3\n V temp = 3 << (i * 2)\n temp = temp (+) -1\n .dVal = .dVal [&] temp\n .b((i + 1) * 2)\n i = i + 1\n\n F b(pos)\n I pos == 0\n .inc()\n R\n I (.dVal >> pos) [&] 1 == 0\n .dVal = .dVal + (1 << pos)\n .a(Int(pos / 2))\n I pos > 1\n .a(Int(pos / 2) - 1)\n E\n V temp = 1 << pos\n temp = temp (+) -1\n .dVal = .dVal [&] temp\n .b(pos + 1)\n .b(pos - (I pos > 1 {2} E 1))\n\n F c(pos)\n I (.dVal >> pos) [&] 1 == 1\n V temp = 1 << pos\n temp = temp (+) -1\n .dVal = .dVal [&] temp\n R\n .c(pos + 1)\n I pos > 0\n .b(pos - 1)\n E\n .inc()\n\n F inc() -> N\n .dVal = .dVal + 1\n .a(0)\n\n F +(rhs)\n V copy = (.)\n V rhs_dVal = rhs.dVal\n V limit = (rhs.dLen + 1) * 2\n L(gn) 0 .< limit\n I ((rhs_dVal >> gn) [&] 1) == 1\n copy.b(gn)\n R copy\n\n F -(rhs)\n V copy = (.)\n V rhs_dVal = rhs.dVal\n V limit = (rhs.dLen + 1) * 2\n L(gn) 0 .< limit\n I (rhs_dVal >> gn) [&] 1 == 1\n copy.c(gn)\n L (((copy.dVal >> ((copy.dLen * 2) [&] 31)) [&] 3) == 0) | (copy.dLen == 0)\n copy.dLen = copy.dLen - 1\n R copy\n\n F *(rhs)\n V na = copy(rhs)\n V nb = copy(rhs)\n V nr = Zeckendorf()\n V dVal = .dVal\n L(i) 0 .< (.dLen + 1) * 2\n I ((dVal >> i) [&] 1) > 0\n nr = nr + nb\n V nt = copy(nb)\n nb = nb + na\n na = copy(nt)\n R nr\n\n F String()\n V dig = [‘00’, ‘01’, ‘10’]\n V dig1 = [‘’, ‘1’, ‘10’]\n\n I .dVal == 0\n R ‘0’\n V idx = (.dVal >> ((.dLen * 2) [&] 31)) [&] 3\n String sb = dig1[idx]\n V i = .dLen - 1\n L i >= 0\n idx = (.dVal >> (i * 2)) [&] 3\n sb ‘’= dig[idx]\n i = i - 1\n R sb\n\nprint(‘Addition:’)\nV g = Zeckendorf(‘10’)\ng = g + Zeckendorf(‘10’)\nprint(g)\ng = g + Zeckendorf(‘10’)\nprint(g)\ng = g + Zeckendorf(‘1001’)\nprint(g)\ng = g + Zeckendorf(‘1000’)\nprint(g)\ng = g + Zeckendorf(‘10101’)\nprint(g)\nprint()\n\nprint(‘Subtraction:’)\ng = Zeckendorf(‘1000’)\ng = g - Zeckendorf(‘101’)\nprint(g)\ng = Zeckendorf(‘10101010’)\ng = g - Zeckendorf(‘1010101’)\nprint(g)\nprint()\n\nprint(‘Multiplication:’)\ng = Zeckendorf(‘1001’)\ng = g * Zeckendorf(‘101’)\nprint(g)\ng = Zeckendorf(‘101010’)\ng = g + Zeckendorf(‘101’)\nprint(g)\n", "language": "11l" }, { "code": "#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nint inv(int a) {\n return a ^ -1;\n}\n\nstruct Zeckendorf {\n int dVal, dLen;\n};\n\nvoid a(struct Zeckendorf *self, int n) {\n void b(struct Zeckendorf *, int); // forward declare\n\n int i = n;\n while (true) {\n if (self->dLen < i) self->dLen = i;\n int j = (self->dVal >> (i * 2)) & 3;\n switch (j) {\n case 0:\n case 1:\n return;\n case 2:\n if (((self->dVal >> ((i + 1) * 2)) & 1) != 1) return;\n self->dVal += 1 << (i * 2 + 1);\n return;\n case 3:\n self->dVal = self->dVal & inv(3 << (i * 2));\n b(self, (i + 1) * 2);\n break;\n default:\n break;\n }\n i++;\n }\n}\n\nvoid b(struct Zeckendorf *self, int pos) {\n void increment(struct Zeckendorf *); // forward declare\n\n if (pos == 0) {\n increment(self);\n return;\n }\n if (((self->dVal >> pos) & 1) == 0) {\n self->dVal += 1 << pos;\n a(self, pos / 2);\n if (pos > 1) a(self, pos / 2 - 1);\n } else {\n self->dVal = self->dVal & inv(1 << pos);\n b(self, pos + 1);\n b(self, pos - (pos > 1 ? 2 : 1));\n }\n}\n\nvoid c(struct Zeckendorf *self, int pos) {\n if (((self->dVal >> pos) & 1) == 1) {\n self->dVal = self->dVal & inv(1 << pos);\n return;\n }\n c(self, pos + 1);\n if (pos > 0) {\n b(self, pos - 1);\n } else {\n increment(self);\n }\n}\n\nstruct Zeckendorf makeZeckendorf(char *x) {\n struct Zeckendorf z = { 0, 0 };\n int i = strlen(x) - 1;\n int q = 1;\n\n z.dLen = i / 2;\n while (i >= 0) {\n z.dVal += (x[i] - '0') * q;\n q *= 2;\n i--;\n }\n\n return z;\n}\n\nvoid increment(struct Zeckendorf *self) {\n self->dVal++;\n a(self, 0);\n}\n\nvoid addAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {\n int gn;\n for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) {\n if (((rhs.dVal >> gn) & 1) == 1) {\n b(self, gn);\n }\n }\n}\n\nvoid subAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {\n int gn;\n for (gn = 0; gn < (rhs.dLen + 1) * 2; gn++) {\n if (((rhs.dVal >> gn) & 1) == 1) {\n c(self, gn);\n }\n }\n while ((((self->dVal >> self->dLen * 2) & 3) == 0) || (self->dLen == 0)) {\n self->dLen--;\n }\n}\n\nvoid mulAssign(struct Zeckendorf *self, struct Zeckendorf rhs) {\n struct Zeckendorf na = rhs;\n struct Zeckendorf nb = rhs;\n struct Zeckendorf nr = makeZeckendorf(\"0\");\n struct Zeckendorf nt;\n int i;\n\n for (i = 0; i < (self->dLen + 1) * 2; i++) {\n if (((self->dVal >> i) & 1) > 0) addAssign(&nr, nb);\n nt = nb;\n addAssign(&nb, na);\n na = nt;\n }\n\n *self = nr;\n}\n\nvoid printZeckendorf(struct Zeckendorf z) {\n static const char *const dig[3] = { \"00\", \"01\", \"10\" };\n static const char *const dig1[3] = { \"\", \"1\", \"10\" };\n\n if (z.dVal == 0) {\n printf(\"0\");\n return;\n } else {\n int idx = (z.dVal >> (z.dLen * 2)) & 3;\n int i;\n\n printf(dig1[idx]);\n for (i = z.dLen - 1; i >= 0; i--) {\n idx = (z.dVal >> (i * 2)) & 3;\n printf(dig[idx]);\n }\n }\n}\n\nint main() {\n struct Zeckendorf g;\n\n printf(\"Addition:\\n\");\n g = makeZeckendorf(\"10\");\n addAssign(&g, makeZeckendorf(\"10\"));\n printZeckendorf(g);\n printf(\"\\n\");\n addAssign(&g, makeZeckendorf(\"10\"));\n printZeckendorf(g);\n printf(\"\\n\");\n addAssign(&g, makeZeckendorf(\"1001\"));\n printZeckendorf(g);\n printf(\"\\n\");\n addAssign(&g, makeZeckendorf(\"1000\"));\n printZeckendorf(g);\n printf(\"\\n\");\n addAssign(&g, makeZeckendorf(\"10101\"));\n printZeckendorf(g);\n printf(\"\\n\\n\");\n\n printf(\"Subtraction:\\n\");\n g = makeZeckendorf(\"1000\");\n subAssign(&g, makeZeckendorf(\"101\"));\n printZeckendorf(g);\n printf(\"\\n\");\n g = makeZeckendorf(\"10101010\");\n subAssign(&g, makeZeckendorf(\"1010101\"));\n printZeckendorf(g);\n printf(\"\\n\\n\");\n\n printf(\"Multiplication:\\n\");\n g = makeZeckendorf(\"1001\");\n mulAssign(&g, makeZeckendorf(\"101\"));\n printZeckendorf(g);\n printf(\"\\n\");\n g = makeZeckendorf(\"101010\");\n addAssign(&g, makeZeckendorf(\"101\"));\n printZeckendorf(g);\n printf(\"\\n\");\n\n return 0;\n}\n", "language": "C" }, { "code": "// For a class N which implements Zeckendorf numbers:\n// I define an increment operation ++()\n// I define a comparison operation <=(other N)\n// I define an addition operation +=(other N)\n// I define a subtraction operation -=(other N)\n// Nigel Galloway October 28th., 2012\n#include <iostream>\nenum class zd {N00,N01,N10,N11};\nclass N {\nprivate:\n int dVal = 0, dLen;\n void _a(int i) {\n for (;; i++) {\n if (dLen < i) dLen = i;\n switch ((zd)((dVal >> (i*2)) & 3)) {\n case zd::N00: case zd::N01: return;\n case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return;\n dVal += (1 << (i*2+1)); return;\n case zd::N11: dVal &= ~(3 << (i*2)); _b((i+1)*2);\n }}}\n void _b(int pos) {\n if (pos == 0) {++*this; return;}\n if (((dVal >> pos) & 1) == 0) {\n dVal += 1 << pos;\n _a(pos/2);\n if (pos > 1) _a((pos/2)-1);\n } else {\n dVal &= ~(1 << pos);\n _b(pos + 1);\n _b(pos - ((pos > 1)? 2:1));\n }}\n void _c(int pos) {\n if (((dVal >> pos) & 1) == 1) {dVal &= ~(1 << pos); return;}\n _c(pos + 1);\n if (pos > 0) _b(pos - 1); else ++*this;\n return;\n }\npublic:\n N(char const* x = \"0\") {\n int i = 0, q = 1;\n for (; x[i] > 0; i++);\n for (dLen = --i/2; i >= 0; i--) {dVal+=(x[i]-48)*q; q*=2;\n }}\n const N& operator++() {dVal += 1; _a(0); return *this;}\n const N& operator+=(const N& other) {\n for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _b(GN);\n return *this;\n }\n const N& operator-=(const N& other) {\n for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _c(GN);\n for (;((dVal >> dLen*2) & 3) == 0 or dLen == 0; dLen--);\n return *this;\n }\n const N& operator*=(const N& other) {\n N Na = other, Nb = other, Nt, Nr;\n for (int i = 0; i <= (dLen + 1) * 2; i++) {\n if (((dVal >> i) & 1) > 0) Nr += Nb;\n Nt = Nb; Nb += Na; Na = Nt;\n }\n return *this = Nr;\n }\n const bool operator<=(const N& other) const {return dVal <= other.dVal;}\n friend std::ostream& operator<<(std::ostream&, const N&);\n};\nN operator \"\" N(char const* x) {return N(x);}\nstd::ostream &operator<<(std::ostream &os, const N &G) {\n const static std::string dig[] {\"00\",\"01\",\"10\"}, dig1[] {\"\",\"1\",\"10\"};\n if (G.dVal == 0) return os << \"0\";\n os << dig1[(G.dVal >> (G.dLen*2)) & 3];\n for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];\n return os;\n}\n", "language": "C++" }, { "code": "int main(void) {\n N G;\n G = 10N;\n G += 10N;\n std::cout << G << std::endl;\n G += 10N;\n std::cout << G << std::endl;\n G += 1001N;\n std::cout << G << std::endl;\n G += 1000N;\n std::cout << G << std::endl;\n G += 10101N;\n std::cout << G << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "int main(void) {\n N G;\n G = 1000N;\n G -= 101N;\n std::cout << G << std::endl;\n G = 10101010N;\n G -= 1010101N;\n std::cout << G << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "int main(void) {\n N G = 1001N;\n G *= 101N;\n std::cout << G << std::endl;\n\n G = 101010N;\n G += 101N;\n std::cout << G << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Text;\n\nnamespace ZeckendorfArithmetic {\n class Zeckendorf : IComparable<Zeckendorf> {\n private static readonly string[] dig = { \"00\", \"01\", \"10\" };\n private static readonly string[] dig1 = { \"\", \"1\", \"10\" };\n\n private int dVal = 0;\n private int dLen = 0;\n\n public Zeckendorf() : this(\"0\") {\n // empty\n }\n\n public Zeckendorf(string x) {\n int q = 1;\n int i = x.Length - 1;\n dLen = i / 2;\n while (i >= 0) {\n dVal += (x[i] - '0') * q;\n q *= 2;\n i--;\n }\n }\n\n private void A(int n) {\n int i = n;\n while (true) {\n if (dLen < i) dLen = i;\n int j = (dVal >> (i * 2)) & 3;\n switch (j) {\n case 0:\n case 1:\n return;\n case 2:\n if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;\n dVal += 1 << (i * 2 + 1);\n return;\n case 3:\n int temp = 3 << (i * 2);\n temp ^= -1;\n dVal = dVal & temp;\n B((i + 1) * 2);\n break;\n }\n i++;\n }\n }\n\n private void B(int pos) {\n if (pos == 0) {\n Inc();\n return;\n }\n if (((dVal >> pos) & 1) == 0) {\n dVal += 1 << pos;\n A(pos / 2);\n if (pos > 1) A(pos / 2 - 1);\n }\n else {\n int temp = 1 << pos;\n temp ^= -1;\n dVal = dVal & temp;\n B(pos + 1);\n B(pos - (pos > 1 ? 2 : 1));\n }\n }\n\n private void C(int pos) {\n if (((dVal >> pos) & 1) == 1) {\n int temp = 1 << pos;\n temp ^= -1;\n dVal = dVal & temp;\n return;\n }\n C(pos + 1);\n if (pos > 0) {\n B(pos - 1);\n }\n else {\n Inc();\n }\n }\n\n public Zeckendorf Inc() {\n dVal++;\n A(0);\n return this;\n }\n\n public Zeckendorf Copy() {\n Zeckendorf z = new Zeckendorf {\n dVal = dVal,\n dLen = dLen\n };\n return z;\n }\n\n public void PlusAssign(Zeckendorf other) {\n for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) {\n B(gn);\n }\n }\n }\n\n public void MinusAssign(Zeckendorf other) {\n for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) {\n C(gn);\n }\n }\n while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {\n dLen--;\n }\n }\n\n public void TimesAssign(Zeckendorf other) {\n Zeckendorf na = other.Copy();\n Zeckendorf nb = other.Copy();\n Zeckendorf nt;\n Zeckendorf nr = new Zeckendorf();\n for (int i = 0; i < (dLen + 1) * 2; i++) {\n if (((dVal >> i) & 1) > 0) {\n nr.PlusAssign(nb);\n }\n nt = nb.Copy();\n nb.PlusAssign(na);\n na = nt.Copy();\n }\n dVal = nr.dVal;\n dLen = nr.dLen;\n }\n\n public int CompareTo(Zeckendorf other) {\n return dVal.CompareTo(other.dVal);\n }\n\n public override string ToString() {\n if (dVal == 0) {\n return \"0\";\n }\n\n int idx = (dVal >> (dLen * 2)) & 3;\n StringBuilder sb = new StringBuilder(dig1[idx]);\n for (int i = dLen - 1; i >= 0; i--) {\n idx = (dVal >> (i * 2)) & 3;\n sb.Append(dig[idx]);\n }\n return sb.ToString();\n }\n }\n\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Addition:\");\n Zeckendorf g = new Zeckendorf(\"10\");\n g.PlusAssign(new Zeckendorf(\"10\"));\n Console.WriteLine(g);\n g.PlusAssign(new Zeckendorf(\"10\"));\n Console.WriteLine(g);\n g.PlusAssign(new Zeckendorf(\"1001\"));\n Console.WriteLine(g);\n g.PlusAssign(new Zeckendorf(\"1000\"));\n Console.WriteLine(g);\n g.PlusAssign(new Zeckendorf(\"10101\"));\n Console.WriteLine(g);\n Console.WriteLine();\n\n Console.WriteLine(\"Subtraction:\");\n g = new Zeckendorf(\"1000\");\n g.MinusAssign(new Zeckendorf(\"101\"));\n Console.WriteLine(g);\n g = new Zeckendorf(\"10101010\");\n g.MinusAssign(new Zeckendorf(\"1010101\"));\n Console.WriteLine(g);\n Console.WriteLine();\n\n Console.WriteLine(\"Multiplication:\");\n g = new Zeckendorf(\"1001\");\n g.TimesAssign(new Zeckendorf(\"101\"));\n Console.WriteLine(g);\n g = new Zeckendorf(\"101010\");\n g.PlusAssign(new Zeckendorf(\"101\"));\n Console.WriteLine(g);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.stdio;\n\nint inv(int a) {\n return a ^ -1;\n}\n\nclass Zeckendorf {\n private int dVal;\n private int dLen;\n\n private void a(int n) {\n auto i = n;\n while (true) {\n if (dLen < i) dLen = i;\n auto j = (dVal >> (i * 2)) & 3;\n switch(j) {\n case 0:\n case 1:\n return;\n case 2:\n if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;\n dVal += 1 << (i * 2 + 1);\n return;\n case 3:\n dVal = dVal & (3 << (i * 2)).inv();\n b((i + 1) * 2);\n break;\n default:\n assert(false);\n }\n i++;\n }\n }\n\n private void b(int pos) {\n if (pos == 0) {\n this++;\n return;\n }\n if (((dVal >> pos) & 1) == 0) {\n dVal += 1 << pos;\n a(pos / 2);\n if (pos > 1) a(pos / 2 - 1);\n } else {\n dVal = dVal & (1 << pos).inv();\n b(pos + 1);\n b(pos - (pos > 1 ? 2 : 1));\n }\n }\n\n private void c(int pos) {\n if (((dVal >> pos) & 1) == 1) {\n dVal = dVal & (1 << pos).inv();\n return;\n }\n c(pos + 1);\n if (pos > 0) {\n b(pos - 1);\n } else {\n ++this;\n }\n }\n\n this(string x = \"0\") {\n int q = 1;\n int i = x.length - 1;\n dLen = i / 2;\n while (i >= 0) {\n dVal += (x[i] - '0') * q;\n q *= 2;\n i--;\n }\n }\n\n auto opUnary(string op : \"++\")() {\n dVal += 1;\n a(0);\n return this;\n }\n\n void opOpAssign(string op : \"+\")(Zeckendorf rhs) {\n foreach (gn; 0..(rhs.dLen + 1) * 2) {\n if (((rhs.dVal >> gn) & 1) == 1) {\n b(gn);\n }\n }\n }\n\n void opOpAssign(string op : \"-\")(Zeckendorf rhs) {\n foreach (gn; 0..(rhs.dLen + 1) * 2) {\n if (((rhs.dVal >> gn) & 1) == 1) {\n c(gn);\n }\n }\n while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {\n dLen--;\n }\n }\n\n void opOpAssign(string op : \"*\")(Zeckendorf rhs) {\n auto na = rhs.dup;\n auto nb = rhs.dup;\n Zeckendorf nt;\n auto nr = \"0\".Z;\n foreach (i; 0..(dLen + 1) * 2) {\n if (((dVal >> i) & 1) > 0) nr += nb;\n nt = nb.dup;\n nb += na;\n na = nt.dup;\n }\n dVal = nr.dVal;\n dLen = nr.dLen;\n }\n\n void toString(scope void delegate(const(char)[]) sink) const {\n if (dVal == 0) {\n sink(\"0\");\n return;\n }\n sink(dig1[(dVal >> (dLen * 2)) & 3]);\n foreach_reverse (i; 0..dLen) {\n sink(dig[(dVal >> (i * 2)) & 3]);\n }\n }\n\n Zeckendorf dup() {\n auto z = \"0\".Z;\n z.dVal = dVal;\n z.dLen = dLen;\n return z;\n }\n\n enum dig = [\"00\", \"01\", \"10\"];\n enum dig1 = [\"\", \"1\", \"10\"];\n}\n\nauto Z(string val) {\n return new Zeckendorf(val);\n}\n\nvoid main() {\n writeln(\"Addition:\");\n auto g = \"10\".Z;\n g += \"10\".Z;\n writeln(g);\n g += \"10\".Z;\n writeln(g);\n g += \"1001\".Z;\n writeln(g);\n g += \"1000\".Z;\n writeln(g);\n g += \"10101\".Z;\n writeln(g);\n writeln();\n\n writeln(\"Subtraction:\");\n g = \"1000\".Z;\n g -= \"101\".Z;\n writeln(g);\n g = \"10101010\".Z;\n g -= \"1010101\".Z;\n writeln(g);\n writeln();\n\n writeln(\"Multiplication:\");\n g = \"1001\".Z;\n g *= \"101\".Z;\n writeln(g);\n g = \"101010\".Z;\n g += \"101\".Z;\n writeln(g);\n}\n", "language": "D" }, { "code": "class Zeckendorf {\n int dVal = 0;\n int dLen = 0;\n\n Zeckendorf(String x) {\n var q = 1;\n var i = x.length - 1;\n dLen = i ~/ 2;\n while (i >= 0) {\n dVal += (x[i].codeUnitAt(0) - '0'.codeUnitAt(0)) * q;\n q *= 2;\n i--;\n }\n }\n\n void a(int n) {\n var i = n;\n while (true) {\n if (dLen < i) dLen = i;\n var j = (dVal >> (i * 2)) & 3;\n switch (j) {\n case 0:\n case 1:\n return;\n case 2:\n if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;\n dVal += 1 << (i * 2 + 1);\n return;\n case 3:\n dVal &= ~(3 << (i * 2));\n b((i + 1) * 2);\n break;\n }\n i++;\n }\n }\n\n void b(int pos) {\n if (pos == 0) {\n this.increment();\n return;\n }\n if (((dVal >> pos) & 1) == 0) {\n dVal += 1 << pos;\n a(pos ~/ 2);\n if (pos > 1) a(pos ~/ 2 - 1);\n } else {\n dVal &= ~(1 << pos);\n b(pos + 1);\n b(pos - (pos > 1 ? 2 : 1));\n }\n }\n\n void c(int pos) {\n if (((dVal >> pos) & 1) == 1) {\n dVal &= ~(1 << pos);\n return;\n }\n c(pos + 1);\n if (pos > 0)\n b(pos - 1);\n else\n this.increment();\n }\n\n Zeckendorf increment() {\n dVal += 1;\n a(0);\n return this;\n }\n\n void operator + (Zeckendorf other) {\n for (var gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) b(gn);\n }\n }\n\n void operator - (Zeckendorf other) {\n for (var gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) c(gn);\n }\n while (dLen > 0 && (((dVal >> dLen * 2) & 3) == 0)) dLen--;\n }\n\n\n void operator * (Zeckendorf other) {\n var na = other.copy();\n var nb = other.copy();\n Zeckendorf nt;\n var nr = Zeckendorf(\"0\");\n for (var i = 0; i <= (dLen + 1) * 2; i++) {\n if (((dVal >> i) & 1) > 0) nr + nb;\n nt = nb.copy();\n nb + na;\n na = nt.copy();\n }\n dVal = nr.dVal;\n dLen = nr.dLen;\n }\n\n int compareTo(Zeckendorf other) {\n return dVal.compareTo(other.dVal);\n }\n\n @override\n String toString() {\n if (dVal == 0) return \"0\";\n var sb = StringBuffer(dig1[(dVal >> (dLen * 2)) & 3]);\n for (var i = dLen - 1; i >= 0; i--) {\n sb.write(dig[(dVal >> (i * 2)) & 3]);\n }\n return sb.toString();\n }\n\n Zeckendorf copy() {\n var z = Zeckendorf(\"0\");\n z.dVal = dVal;\n z.dLen = dLen;\n return z;\n }\n\n static final List<String> dig = [\"00\", \"01\", \"10\"];\n static final List<String> dig1 = [\"\", \"1\", \"10\"];\n}\n\nvoid main() {\n print(\"Addition:\");\n var g = Zeckendorf(\"10\");\n g + Zeckendorf(\"10\");\n print(g);\n g + Zeckendorf(\"10\");\n print(g);\n g + Zeckendorf(\"1001\");\n print(g);\n g + Zeckendorf(\"1000\");\n print(g);\n g + Zeckendorf(\"10101\");\n print(g);\n\n print(\"\\nSubtraction:\");\n g = Zeckendorf(\"1000\");\n g - Zeckendorf(\"101\");\n print(g);\n g = Zeckendorf(\"10101010\");\n g - Zeckendorf(\"1010101\");\n print(g);\n\n print(\"\\nMultiplication:\");\n g = Zeckendorf(\"1001\");\n g * Zeckendorf(\"101\");\n print(g);\n g = Zeckendorf(\"101010\");\n g + Zeckendorf(\"101\");\n print(g);\n}\n", "language": "Dart" }, { "code": "import extensions;\n\nconst dig = new string[]{\"00\",\"01\",\"10\"};\nconst dig1 = new string[]{\"\",\"1\",\"10\"};\n\nsealed struct ZeckendorfNumber\n{\n int dVal;\n int dLen;\n\n clone()\n = ZeckendorfNumber.newInternal(dVal,dLen);\n\n cast n(string s)\n {\n int i := s.Length - 1;\n int q := 1;\n\n dLen := i / 2;\n dVal := 0;\n\n while (i >= 0)\n {\n dVal += ((intConvertor.convert(s[i]) - 48) * q);\n q *= 2;\n\n i -= 1\n }\n }\n\n internal readContent(ref int val, ref int len)\n {\n val := dVal;\n len := dLen;\n }\n\n private a(int n)\n {\n int i := n;\n\n while (true)\n {\n if (dLen < i)\n {\n dLen := i\n };\n\n int v := (dVal $shr (i * 2)) & 3;\n v =>\n 0 { ^ self }\n 1 { ^ self }\n 2 {\n ifnot ((dVal $shr ((i + 1) * 2)).allMask(1))\n {\n ^ self\n };\n\n dVal += (1 $shl (i*2 + 1));\n\n ^ self\n }\n 3 {\n int tmp := 3 $shl (i * 2);\n tmp := tmp.bxor(-1);\n dVal := dVal & tmp;\n\n self.b((i+1)*2)\n };\n\n i += 1\n }\n }\n\n inc()\n {\n dVal += 1;\n self.a(0)\n }\n\n private b(int pos)\n {\n if (pos == 0) { ^ self.inc() };\n\n ifnot((dVal $shr pos).allMask(1))\n {\n dVal += (1 $shl pos);\n self.a(pos / 2);\n if (pos > 1) { self.a((pos / 2) - 1) }\n }\n else\n {\n dVal := dVal & (1 $shl pos).BInverted;\n self.b(pos + 1);\n int arg := pos - ((pos > 1) ? 2 : 1);\n self.b(/*pos - ((pos > 1) ? 2 : 1)*/arg)\n }\n }\n\n private c(int pos)\n {\n if ((dVal $shr pos).allMask(1))\n {\n int tmp := 1 $shl pos;\n tmp := tmp.bxor(-1);\n\n dVal := dVal & tmp;\n\n ^ self\n };\n\n self.c(pos + 1);\n\n if (pos > 0)\n {\n self.b(pos - 1)\n }\n else\n {\n self.inc()\n }\n }\n\n internal constructor sum(ZeckendorfNumber n, ZeckendorfNumber m)\n {\n int mVal := 0;\n int mLen := 0;\n\n n.readContent(ref int v, ref int l);\n m.readContent(ref mVal, ref mLen);\n\n dVal := v;\n dLen := l;\n\n for(int GN := 0; GN < (mLen + 1) * 2; GN += 1)\n {\n if ((mVal $shr GN).allMask(1))\n {\n self.b(GN)\n }\n }\n }\n\n internal constructor difference(ZeckendorfNumber n, ZeckendorfNumber m)\n {\n int mVal := 0;\n int mLen := 0;\n\n n.readContent(ref int v, ref int l);\n m.readContent(ref mVal, ref mLen);\n\n dVal := v;\n dLen := l;\n\n for(int GN := 0; GN < (mLen + 1) * 2; GN += 1)\n {\n if ((mVal $shr GN).allMask(1))\n {\n self.c(GN)\n }\n };\n\n while (((dVal $shr (dLen*2)) & 3) == 0 || dLen == 0)\n {\n dLen -= 1\n }\n }\n\n internal constructor product(ZeckendorfNumber n, ZeckendorfNumber m)\n {\n n.readContent(ref int v, ref int l);\n\n dVal := v;\n dLen := l;\n\n ZeckendorfNumber Na := m;\n ZeckendorfNumber Nb := m;\n ZeckendorfNumber Nr := 0n;\n ZeckendorfNumber Nt := 0n;\n\n for(int i := 0; i < (dLen + 1) * 2; i += 1)\n {\n if (((dVal $shr i) & 1) > 0)\n {\n Nr += Nb\n };\n Nt := Nb;\n Nb += Na;\n Na := Nt\n };\n\n Nr.readContent(ref v, ref l);\n\n dVal := v;\n dLen := l;\n }\n\n internal constructor newInternal(int v, int l)\n {\n dVal := v;\n dLen := l\n }\n\n string toPrintable()\n {\n if (dVal == 0)\n { ^ \"0\" };\n\n string s := dig1[(dVal $shr (dLen * 2)) & 3];\n int i := dLen - 1;\n while (i >= 0)\n {\n s := s + dig[(dVal $shr (i * 2)) & 3];\n\n i-=1\n };\n\n ^ s\n }\n\n add(ZeckendorfNumber n)\n = ZeckendorfNumber.sum(self, n);\n\n subtract(ZeckendorfNumber n)\n = ZeckendorfNumber.difference(self, n);\n\n multiply(ZeckendorfNumber n)\n = ZeckendorfNumber.product(self, n);\n}\n\npublic program()\n{\n console.printLine(\"Addition:\");\n var n := 10n;\n\n n += 10n;\n console.printLine(n);\n n += 10n;\n console.printLine(n);\n n += 1001n;\n console.printLine(n);\n n += 1000n;\n console.printLine(n);\n n += 10101n;\n console.printLine(n);\n\n console.printLine(\"Subtraction:\");\n n := 1000n;\n n -= 101n;\n console.printLine(n);\n n := 10101010n;\n n -= 1010101n;\n console.printLine(n);\n\n console.printLine(\"Multiplication:\");\n n := 1001n;\n n *= 101n;\n console.printLine(n);\n n := 101010n;\n n += 101n;\n console.printLine(n)\n}\n", "language": "Elena" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar (\n dig = [3]string{\"00\", \"01\", \"10\"}\n dig1 = [3]string{\"\", \"1\", \"10\"}\n)\n\ntype Zeckendorf struct{ dVal, dLen int }\n\nfunc NewZeck(x string) *Zeckendorf {\n z := new(Zeckendorf)\n if x == \"\" {\n x = \"0\"\n }\n q := 1\n i := len(x) - 1\n z.dLen = i / 2\n for ; i >= 0; i-- {\n z.dVal += int(x[i]-'0') * q\n q *= 2\n }\n return z\n}\n\nfunc (z *Zeckendorf) a(i int) {\n for ; ; i++ {\n if z.dLen < i {\n z.dLen = i\n }\n j := (z.dVal >> uint(i*2)) & 3\n switch j {\n case 0, 1:\n return\n case 2:\n if ((z.dVal >> (uint(i+1) * 2)) & 1) != 1 {\n return\n }\n z.dVal += 1 << uint(i*2+1)\n return\n case 3:\n z.dVal &= ^(3 << uint(i*2))\n z.b((i + 1) * 2)\n }\n }\n}\n\nfunc (z *Zeckendorf) b(pos int) {\n if pos == 0 {\n z.Inc()\n return\n }\n if ((z.dVal >> uint(pos)) & 1) == 0 {\n z.dVal += 1 << uint(pos)\n z.a(pos / 2)\n if pos > 1 {\n z.a(pos/2 - 1)\n }\n } else {\n z.dVal &= ^(1 << uint(pos))\n z.b(pos + 1)\n temp := 1\n if pos > 1 {\n temp = 2\n }\n z.b(pos - temp)\n }\n}\n\nfunc (z *Zeckendorf) c(pos int) {\n if ((z.dVal >> uint(pos)) & 1) == 1 {\n z.dVal &= ^(1 << uint(pos))\n return\n }\n z.c(pos + 1)\n if pos > 0 {\n z.b(pos - 1)\n } else {\n z.Inc()\n }\n}\n\nfunc (z *Zeckendorf) Inc() {\n z.dVal++\n z.a(0)\n}\n\nfunc (z1 *Zeckendorf) PlusAssign(z2 *Zeckendorf) {\n for gn := 0; gn < (z2.dLen+1)*2; gn++ {\n if ((z2.dVal >> uint(gn)) & 1) == 1 {\n z1.b(gn)\n }\n }\n}\n\nfunc (z1 *Zeckendorf) MinusAssign(z2 *Zeckendorf) {\n for gn := 0; gn < (z2.dLen+1)*2; gn++ {\n if ((z2.dVal >> uint(gn)) & 1) == 1 {\n z1.c(gn)\n }\n }\n\n for z1.dLen > 0 && ((z1.dVal>>uint(z1.dLen*2))&3) == 0 {\n z1.dLen--\n }\n}\n\nfunc (z1 *Zeckendorf) TimesAssign(z2 *Zeckendorf) {\n na := z2.Copy()\n nb := z2.Copy()\n nr := new(Zeckendorf)\n for i := 0; i <= (z1.dLen+1)*2; i++ {\n if ((z1.dVal >> uint(i)) & 1) > 0 {\n nr.PlusAssign(nb)\n }\n nt := nb.Copy()\n nb.PlusAssign(na)\n na = nt.Copy()\n }\n z1.dVal = nr.dVal\n z1.dLen = nr.dLen\n}\n\nfunc (z *Zeckendorf) Copy() *Zeckendorf {\n return &Zeckendorf{z.dVal, z.dLen}\n}\n\nfunc (z1 *Zeckendorf) Compare(z2 *Zeckendorf) int {\n switch {\n case z1.dVal < z2.dVal:\n return -1\n case z1.dVal > z2.dVal:\n return 1\n default:\n return 0\n }\n}\n\nfunc (z *Zeckendorf) String() string {\n if z.dVal == 0 {\n return \"0\"\n }\n var sb strings.Builder\n sb.WriteString(dig1[(z.dVal>>uint(z.dLen*2))&3])\n for i := z.dLen - 1; i >= 0; i-- {\n sb.WriteString(dig[(z.dVal>>uint(i*2))&3])\n }\n return sb.String()\n}\n\nfunc main() {\n fmt.Println(\"Addition:\")\n g := NewZeck(\"10\")\n g.PlusAssign(NewZeck(\"10\"))\n fmt.Println(g)\n g.PlusAssign(NewZeck(\"10\"))\n fmt.Println(g)\n g.PlusAssign(NewZeck(\"1001\"))\n fmt.Println(g)\n g.PlusAssign(NewZeck(\"1000\"))\n fmt.Println(g)\n g.PlusAssign(NewZeck(\"10101\"))\n fmt.Println(g)\n\n fmt.Println(\"\\nSubtraction:\")\n g = NewZeck(\"1000\")\n g.MinusAssign(NewZeck(\"101\"))\n fmt.Println(g)\n g = NewZeck(\"10101010\")\n g.MinusAssign(NewZeck(\"1010101\"))\n fmt.Println(g)\n\n fmt.Println(\"\\nMultiplication:\")\n g = NewZeck(\"1001\")\n g.TimesAssign(NewZeck(\"101\"))\n fmt.Println(g)\n g = NewZeck(\"101010\")\n g.PlusAssign(NewZeck(\"101\"))\n fmt.Println(g)\n}\n", "language": "Go" }, { "code": "{-# LANGUAGE LambdaCase #-}\nimport Data.List (find, mapAccumL)\nimport Control.Arrow (first, second)\n\n-- Generalized Fibonacci series defined for any Num instance, and for Zeckendorf numbers as well.\n-- Used to build Zeckendorf tables.\nfibs :: Num a => a -> a -> [a]\nfibs a b = res\n where\n res = a : b : zipWith (+) res (tail res)\n\ndata Fib = Fib { sign :: Int, digits :: [Int]}\n\n-- smart constructor\nmkFib s ds =\n case dropWhile (==0) ds of\n [] -> 0\n ds -> Fib s (reverse ds)\n\n-- Textual representation\ninstance Show Fib where\n show (Fib s ds) = sig s ++ foldMap show (reverse ds)\n where sig = \\case { -1 -> \"-\"; s -> \"\" }\n\n-- Equivalence relation\ninstance Eq Fib where\n Fib sa a == Fib sb b = sa == sb && a == b\n\n-- Order relation\ninstance Ord Fib where\n a `compare` b =\n sign a `compare` sign b <>\n case find (/= 0) $ alignWith (-) (digits a) (digits b) of\n Nothing -> EQ\n Just 1 -> if sign a > 0 then GT else LT\n Just (-1) -> if sign a > 0 then LT else GT\n\n-- Arithmetic\ninstance Num Fib where\n negate (Fib s ds) = Fib (negate s) ds\n abs (Fib s ds) = Fib 1 ds\n signum (Fib s _) = fromIntegral s\n\n fromInteger n =\n case compare n 0 of\n LT -> negate $ fromInteger (- n)\n EQ -> Fib 0 [0]\n GT -> Fib 1 . reverse . fst $ divModFib n 1\n\n 0 + a = a\n a + 0 = a\n a + b =\n case (sign a, sign b) of\n ( 1, 1) -> res\n (-1, 1) -> b - (-a)\n ( 1,-1) -> a - (-b)\n (-1,-1) -> - ((- a) + (- b))\n where\n res = mkFib 1 . process $ 0:0:c\n c = alignWith (+) (digits a) (digits b)\n -- use cellular automata\n process =\n runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1\n\n 0 - a = -a\n a - 0 = a\n a - b =\n case (sign a, sign b) of\n ( 1, 1) -> res\n (-1, 1) -> - ((-a) + b)\n ( 1,-1) -> a + (-b)\n (-1,-1) -> - ((-a) - (-b))\n where\n res = case find (/= 0) c of\n Just 1 -> mkFib 1 . process $ c\n Just (-1) -> - (b - a)\n Nothing -> 0\n c = alignWith (-) (digits a) (digits b)\n -- use cellular automata\n process =\n runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1 . runRight 3 r3\n\n 0 * a = 0\n a * 0 = 0\n 1 * a = a\n a * 1 = a\n a * b =\n case (sign a, sign b) of\n (1, 1) -> res\n (-1, 1) -> - ((-a) * b)\n ( 1,-1) -> - (a * (-b))\n (-1,-1) -> ((-a) * (-b))\n where\n -- use Zeckendorf table\n table = fibs a (a + a)\n res = sum $ onlyOnes $ zip (digits b) table\n onlyOnes = map snd . filter ((==1) . fst)\n\n-- Enumeration\ninstance Enum Fib where\n toEnum = fromInteger . fromIntegral\n fromEnum = fromIntegral . toInteger\n\ninstance Real Fib where\n toRational = fromInteger . toInteger\n\n-- Integral division\ninstance Integral Fib where\n toInteger (Fib s ds) = signum (fromIntegral s) * res\n where\n res = sum (zipWith (*) (fibs 1 2) (fromIntegral <$> ds))\n\n quotRem 0 _ = (0, 0)\n quotRem a 0 = error \"divide by zero\"\n quotRem a b = case (sign a, sign b) of\n (1, 1) -> first (mkFib 1) $ divModFib a b\n (-1, 1) -> second negate . first negate $ quotRem (-a) b\n ( 1,-1) -> first negate $ quotRem a (-b)\n (-1,-1) -> second negate $ quotRem (-a) (-b)\n\n------------------------------------------------------------\n-- helper funtions\n\n-- general division using Zeckendorf table\ndivModFib :: (Ord a, Num c, Num a) => a -> a -> ([c], a)\ndivModFib a b = (q, r)\n where\n (r, q) = mapAccumL f a $ reverse $ takeWhile (<= a) table\n table = fibs b (b+b)\n f n x = if n < x then (n, 0) else (n - x, 1)\n\n-- application of rewriting rules\n-- runs window from left to right\nrunRight n f = go\n where\n go [] = []\n go lst = let (w, r) = splitAt n lst\n (h: t) = f w\n in h : go (t ++ r)\n\n-- runs window from left to right and reverses the result\nrunRightR n f = go []\n where\n go res [] = res\n go res lst = let (w, r) = splitAt n lst\n (h: t) = f w\n in go (h : res) (t ++ r)\n\n-- runs reversed window and reverses the result\nrunLeftR n f = runRightR n (reverse . f . reverse)\n\n-- rewriting rules from [C. Ahlbach et. all]\nr1 = \\case [0,3,0] -> [1,1,1]\n [0,2,0] -> [1,0,1]\n [0,1,2] -> [1,0,1]\n [0,2,1] -> [1,1,0]\n [x,0,2] -> [x,1,0]\n [x,0,3] -> [x,1,1]\n [0,1,2,0] -> [1,0,1,0]\n [0,2,0,x] -> [1,0,0,x+1]\n [0,3,0,x] -> [1,1,0,x+1]\n [0,2,1,x] -> [1,1,0,x ]\n [0,1,2,x] -> [1,0,1,x ]\n l -> l\n\nr2 = \\case [0,1,1] -> [1,0,0]\n l -> l\n\nr3 = \\case [1,-1] -> [0,1]\n [2,-1] -> [1,1]\n [1, 0, 0] -> [0,1,1]\n [1,-1, 0] -> [0,0,1]\n [1,-1, 1] -> [0,0,2]\n [1, 0,-1] -> [0,1,0]\n [2, 0, 0] -> [1,1,1]\n [2,-1, 0] -> [1,0,1]\n [2,-1, 1] -> [1,0,2]\n [2, 0,-1] -> [1,1,0]\n l -> l\n\nalignWith :: (Int -> Int -> a) -> [Int] -> [Int] -> [a]\nalignWith f a b = go [] a b\n where\n go res as [] = ((`f` 0) <$> reverse as) ++ res\n go res [] bs = ((0 `f`) <$> reverse bs) ++ res\n go res (a:as) (b:bs) = go (f a b : res) as bs\n", "language": "Haskell" }, { "code": "zform=: {{ 10 |.\"1@(#.inv) y }} :. (10#.|.\"1) NB. use decimal numbers for representation\nzinc=: {{ carry ({.,2}.])carry 1,y }}\nzdec=: {{ (|.k$0 1),y }.~k=. 1+y i.1 }}\nzadd=: {{ x while. 1 e. y do. x=. zinc x [ y=. zdec y end. }}\nzsub=: {{ x while. 1 e. y do. x=. zdec x [ y=. zdec y end. }} NB. intended for unsigned arithmetic\nzmul=: {{ t=. 0 0 while. 1 e. y do. t=. t zadd x [ y=. zdec y end. }}\nzdiv=: {{ t=. 0 0 while. x zge y do. t=. zinc t [ x=. x zsub y end. }} NB. discards remainder\ncarry=: {{\n s=. 0\n for_b. y do.\n if. (1+b) = s=. s-_1^b do. y=. (-.b) (b_index-0,b)} y end.\n end.\n if. 2=s do. y,1 else. y end.\n}}\nzge=: {{ cmp=. x -/@,: y while. (#cmp)*0={:cmp do. cmp=. }:cmp end. 0<:{:cmp }}\n", "language": "J" }, { "code": " 1 zadd&.zform 1\n10\n 10 zadd&.zform 10\n101\n 10100 zadd&.zform 1010\n101000\n 10100 zsub&.zform 1010\n101\n 10100 zmul&.zform 100101\n10010010001\n 10100 zdiv&.zform 1010\n1\n 10100 zdiv&.zform 1000\n10\n 100001000001 zdiv&.zform 100010\n100101\n 100001000001 zdiv&.zform 100101\n100010\n", "language": "J" }, { "code": "import java.util.List;\n\npublic class Zeckendorf implements Comparable<Zeckendorf> {\n private static List<String> dig = List.of(\"00\", \"01\", \"10\");\n private static List<String> dig1 = List.of(\"\", \"1\", \"10\");\n\n private String x;\n private int dVal = 0;\n private int dLen = 0;\n\n public Zeckendorf() {\n this(\"0\");\n }\n\n public Zeckendorf(String x) {\n this.x = x;\n\n int q = 1;\n int i = x.length() - 1;\n dLen = i / 2;\n while (i >= 0) {\n dVal += (x.charAt(i) - '0') * q;\n q *= 2;\n i--;\n }\n }\n\n private void a(int n) {\n int i = n;\n while (true) {\n if (dLen < i) dLen = i;\n int j = (dVal >> (i * 2)) & 3;\n switch (j) {\n case 0:\n case 1:\n return;\n case 2:\n if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;\n dVal += 1 << (i * 2 + 1);\n return;\n case 3:\n int temp = 3 << (i * 2);\n temp ^= -1;\n dVal = dVal & temp;\n b((i + 1) * 2);\n break;\n }\n i++;\n }\n }\n\n private void b(int pos) {\n if (pos == 0) {\n Zeckendorf thiz = this;\n thiz.inc();\n return;\n }\n if (((dVal >> pos) & 1) == 0) {\n dVal += 1 << pos;\n a(pos / 2);\n if (pos > 1) a(pos / 2 - 1);\n } else {\n int temp = 1 << pos;\n temp ^= -1;\n dVal = dVal & temp;\n b(pos + 1);\n b(pos - (pos > 1 ? 2 : 1));\n }\n }\n\n private void c(int pos) {\n if (((dVal >> pos) & 1) == 1) {\n int temp = 1 << pos;\n temp ^= -1;\n dVal = dVal & temp;\n return;\n }\n c(pos + 1);\n if (pos > 0) {\n b(pos - 1);\n } else {\n Zeckendorf thiz = this;\n thiz.inc();\n }\n }\n\n public Zeckendorf inc() {\n dVal++;\n a(0);\n return this;\n }\n\n public void plusAssign(Zeckendorf other) {\n for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) {\n b(gn);\n }\n }\n }\n\n public void minusAssign(Zeckendorf other) {\n for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {\n if (((other.dVal >> gn) & 1) == 1) {\n c(gn);\n }\n }\n while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {\n dLen--;\n }\n }\n\n public void timesAssign(Zeckendorf other) {\n Zeckendorf na = other.copy();\n Zeckendorf nb = other.copy();\n Zeckendorf nt;\n Zeckendorf nr = new Zeckendorf();\n for (int i = 0; i < (dLen + 1) * 2; i++) {\n if (((dVal >> i) & 1) > 0) {\n nr.plusAssign(nb);\n }\n nt = nb.copy();\n nb.plusAssign(na);\n na = nt.copy();\n }\n dVal = nr.dVal;\n dLen = nr.dLen;\n }\n\n private Zeckendorf copy() {\n Zeckendorf z = new Zeckendorf();\n z.dVal = dVal;\n z.dLen = dLen;\n return z;\n }\n\n @Override\n public int compareTo(Zeckendorf other) {\n return ((Integer) dVal).compareTo(other.dVal);\n }\n\n @Override\n public String toString() {\n if (dVal == 0) {\n return \"0\";\n }\n\n int idx = (dVal >> (dLen * 2)) & 3;\n StringBuilder stringBuilder = new StringBuilder(dig1.get(idx));\n for (int i = dLen - 1; i >= 0; i--) {\n idx = (dVal >> (i * 2)) & 3;\n stringBuilder.append(dig.get(idx));\n }\n return stringBuilder.toString();\n }\n\n public static void main(String[] args) {\n System.out.println(\"Addition:\");\n Zeckendorf g = new Zeckendorf(\"10\");\n g.plusAssign(new Zeckendorf(\"10\"));\n System.out.println(g);\n g.plusAssign(new Zeckendorf(\"10\"));\n System.out.println(g);\n g.plusAssign(new Zeckendorf(\"1001\"));\n System.out.println(g);\n g.plusAssign(new Zeckendorf(\"1000\"));\n System.out.println(g);\n g.plusAssign(new Zeckendorf(\"10101\"));\n System.out.println(g);\n\n System.out.println(\"\\nSubtraction:\");\n g = new Zeckendorf(\"1000\");\n g.minusAssign(new Zeckendorf(\"101\"));\n System.out.println(g);\n g = new Zeckendorf(\"10101010\");\n g.minusAssign(new Zeckendorf(\"1010101\"));\n System.out.println(g);\n\n System.out.println(\"\\nMultiplication:\");\n g = new Zeckendorf(\"1001\");\n g.timesAssign(new Zeckendorf(\"101\"));\n System.out.println(g);\n g = new Zeckendorf(\"101010\");\n g.plusAssign(new Zeckendorf(\"101\"));\n System.out.println(g);\n }\n}\n", "language": "Java" }, { "code": "import Base.*, Base.+, Base.-, Base./, Base.show, Base.!=, Base.==, Base.<=, Base.<, Base.>, Base.>=, Base.divrem\n\nconst z0 = \"0\"\nconst z1 = \"1\"\nconst flipordered = (z1 < z0)\n\nmutable struct Z s::String end\nZ() = Z(z0)\nZ(z::Z) = Z(z.s)\n\npairlen(x::Z, y::Z) = max(length(x.s), length(y.s))\ntolen(x::Z, n::Int) = (s = x.s; while length(s) < n s = z0 * s end; s)\n\n<(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) > tolen(y, l) : tolen(x, l) < tolen(y, l))\n>(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) < tolen(y, l) : tolen(x, l) > tolen(y, l))\n==(x::Z, y::Z) = (l = pairlen(x, y); tolen(x, l) == tolen(y, l))\n<=(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) >= tolen(y, l) : tolen(x, l) <= tolen(y, l))\n>=(x::Z, y::Z) = (l = pairlen(x, y); flipordered ? tolen(x, l) <= tolen(y, l) : tolen(x, l) >= tolen(y, l))\n!=(x::Z, y::Z) = (l = pairlen(x, y); tolen(x, l) != tolen(y, l))\n\nfunction tocanonical(z::Z)\n while occursin(z0 * z1 * z1, z.s)\n z.s = replace(z.s, z0 * z1 * z1 => z1 * z0 * z0)\n end\n len = length(z.s)\n if len > 1 && z.s[1:2] == z1 * z1\n z.s = z1 * z0 * z0 * ((len > 2) ? z.s[3:end] : \"\")\n end\n while (len = length(z.s)) > 1 && string(z.s[1]) == z0\n if len == 2\n if z.s == z0 * z0\n z.s = z0\n elseif z.s == z0 * z1\n z.s = z1\n end\n else\n z.s = z.s[2:end]\n end\n end\n z\nend\n\nfunction inc(z)\n if z.s[end] == z0[1]\n z.s = z.s[1:end-1] * z1[1]\n elseif z.s[end] == z1[1]\n if length(z.s) > 1\n if z.s[end-1:end] == z0 * z1\n z.s = z.s[1:end-2] * z1 * z0\n end\n else\n z.s = z1 * z0\n end\n end\n tocanonical(z)\nend\n\nfunction dec(z)\n if z.s[end] == z1[1]\n z.s = z.s[1:end-1] * z0\n else\n if (m = match(Regex(z1 * z0 * '+' * '$'), z.s)) != nothing\n len = length(m.match)\n if iseven(len)\n z.s = z.s[1:end-len] * (z0 * z1) ^ div(len, 2)\n else\n z.s = z.s[1:end-len] * (z0 * z1) ^ div(len, 2) * z0\n end\n end\n end\n tocanonical(z)\n z\nend\n\nfunction +(x::Z, y::Z)\n a = Z(x.s)\n b = Z(y.s)\n while b.s != z0\n inc(a)\n dec(b)\n end\n a\nend\n\nfunction -(x::Z, y::Z)\n a = Z(x.s)\n b = Z(y.s)\n while b.s != z0\n dec(a)\n dec(b)\n end\n a\nend\n\nfunction *(x::Z, y::Z)\n if (x.s == z0) || (y.s == z0)\n return Z(z0)\n elseif x.s == z1\n return Z(y.s)\n elseif y.s == z1\n return Z(x.s)\n end\n a = Z(x.s)\n b = Z(z1)\n while b != y\n c = Z(z0)\n while c != x\n inc(a)\n inc(c)\n end\n inc(b)\n end\n a\nend\n\nfunction divrem(x::Z, y::Z)\n if y.s == z0\n throw(\"Zeckendorf division by 0\")\n elseif (y.s == z1) || (x.s == z0)\n return Z(x.s)\n end\n a = Z(x.s)\n b = Z(y.s)\n c = Z(z0)\n while a > b\n a = a - b\n inc(c)\n end\n tocanonical(c), tocanonical(a)\nend\n\nfunction /(x::Z, y::Z)\n a, _ = divrem(x, y)\n a\nend\n\nshow(io::IO, z::Z) = show(io, parse(BigInt, tocanonical(z).s))\n\nfunction zeckendorftest()\n a = Z(\"10\")\n b = Z(\"1001\")\n c = Z(\"1000\")\n d = Z(\"10101\")\n\n println(\"Addition:\")\n x = a\n println(x += a)\n println(x += a)\n println(x += b)\n println(x += c)\n println(x += d)\n\n println(\"\\nSubtraction:\")\n x = Z(\"1000\")\n println(x - Z(\"101\"))\n x = Z(\"10101010\")\n println(x - Z(\"1010101\"))\n\n println(\"\\nMultiplication:\")\n x = Z(\"1001\")\n y = Z(\"101\")\n println(x * y)\n println(Z(\"101010\") * y)\n\n println(\"\\nDivision:\")\n x = Z(\"1000101\")\n y = Z(\"101\")\n println(x / y)\n println(divrem(x, y))\nend\n\nzeckendorftest()\n", "language": "Julia" }, { "code": "// version 1.1.51\n\nclass Zeckendorf(x: String = \"0\") : Comparable<Zeckendorf> {\n\n var dVal = 0\n var dLen = 0\n\n private fun a(n: Int) {\n var i = n\n while (true) {\n if (dLen < i) dLen = i\n val j = (dVal shr (i * 2)) and 3\n when (j) {\n 0, 1 -> return\n\n 2 -> {\n if (((dVal shr ((i + 1) * 2)) and 1) != 1) return\n dVal += 1 shl (i * 2 + 1)\n return\n }\n\n 3 -> {\n dVal = dVal and (3 shl (i * 2)).inv()\n b((i + 1) * 2)\n }\n }\n i++\n }\n }\n\n private fun b(pos: Int) {\n if (pos == 0) {\n var thiz = this\n ++thiz\n return\n }\n if (((dVal shr pos) and 1) == 0) {\n dVal += 1 shl pos\n a(pos / 2)\n if (pos > 1) a(pos / 2 - 1)\n }\n else {\n dVal = dVal and (1 shl pos).inv()\n b(pos + 1)\n b(pos - (if (pos > 1) 2 else 1))\n }\n }\n\n private fun c(pos: Int) {\n if (((dVal shr pos) and 1) == 1) {\n dVal = dVal and (1 shl pos).inv()\n return\n }\n c(pos + 1)\n if (pos > 0) b(pos - 1) else { var thiz = this; ++thiz }\n }\n\n init {\n var q = 1\n var i = x.length - 1\n dLen = i / 2\n while (i >= 0) {\n dVal += (x[i] - '0').toInt() * q\n q *= 2\n i--\n }\n }\n\n operator fun inc(): Zeckendorf {\n dVal += 1\n a(0)\n return this\n }\n\n operator fun plusAssign(other: Zeckendorf) {\n for (gn in 0 until (other.dLen + 1) * 2) {\n if (((other.dVal shr gn) and 1) == 1) b(gn)\n }\n }\n\n operator fun minusAssign(other: Zeckendorf) {\n for (gn in 0 until (other.dLen + 1) * 2) {\n if (((other.dVal shr gn) and 1) == 1) c(gn)\n }\n while ((((dVal shr dLen * 2) and 3) == 0) || (dLen == 0)) dLen--\n }\n\n operator fun timesAssign(other: Zeckendorf) {\n var na = other.copy()\n var nb = other.copy()\n var nt: Zeckendorf\n var nr = \"0\".Z\n for (i in 0..(dLen + 1) * 2) {\n if (((dVal shr i) and 1) > 0) nr += nb\n nt = nb.copy()\n nb += na\n na = nt.copy()\n }\n dVal = nr.dVal\n dLen = nr.dLen\n }\n\n override operator fun compareTo(other: Zeckendorf) = dVal.compareTo(other.dVal)\n\n override fun toString(): String {\n if (dVal == 0) return \"0\"\n val sb = StringBuilder(dig1[(dVal shr (dLen * 2)) and 3])\n for (i in dLen - 1 downTo 0) {\n sb.append(dig[(dVal shr (i * 2)) and 3])\n }\n return sb.toString()\n }\n\n fun copy(): Zeckendorf {\n val z = \"0\".Z\n z.dVal = dVal\n z.dLen = dLen\n return z\n }\n\n companion object {\n val dig = listOf(\"00\", \"01\", \"10\")\n val dig1 = listOf(\"\", \"1\", \"10\")\n }\n}\n\nval String.Z get() = Zeckendorf(this)\n\nfun main(args: Array<String>) {\n println(\"Addition:\")\n var g = \"10\".Z\n g += \"10\".Z\n println(g)\n g += \"10\".Z\n println(g)\n g += \"1001\".Z\n println(g)\n g += \"1000\".Z\n println(g)\n g += \"10101\".Z\n println(g)\n println(\"\\nSubtraction:\")\n g = \"1000\".Z\n g -= \"101\".Z\n println(g)\n g = \"10101010\".Z\n g -= \"1010101\".Z\n println(g)\n println(\"\\nMultiplication:\")\n g = \"1001\".Z\n g *= \"101\".Z\n println(g)\n g = \"101010\".Z\n g += \"101\".Z\n println(g)\n}\n", "language": "Kotlin" }, { "code": "type Zeckendorf = object\n dVal: Natural\n dLen: Natural\n\nconst\n Dig = [\"00\", \"01\", \"10\"]\n Dig1 = [\"\", \"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 var i = n\n while true:\n\n if z.dLen < i: z.dLen = i\n let j = z.dVal shr (i * 2) and 3\n\n case j\n of 0, 1:\n return\n of 2:\n if (z.dVal shr ((i + 1) * 2) and 1) != 1: return\n z.dVal += 1 shl (i * 2 + 1)\n return\n of 3:\n z.dVal = z.dVal and not (3 shl (i * 2))\n z.b((i + 1) * 2)\n else:\n assert(false)\n\n inc i\n\n\nfunc b(z: var Zeckendorf; pos: Natural) =\n if pos == 0:\n inc z\n return\n\n if (z.dVal shr pos and 1) == 0:\n z.dVal += 1 shl pos\n z.a(pos div 2)\n if pos > 1: z.a(pos div 2 - 1)\n else:\n z.dVal = z.dVal and not(1 shl pos)\n z.b(pos + 1)\n z.b(pos - (if pos > 1: 2 else: 1))\n\n\nfunc c(z: var Zeckendorf; pos: Natural) =\n if (z.dVal shr pos and 1) == 1:\n z.dVal = z.dVal and not(1 shl pos)\n return\n\n z.c(pos + 1)\n if pos > 0:\n z.b(pos - 1)\n else:\n inc z\n\n\nfunc initZeckendorf(s = \"0\"): Zeckendorf =\n var q = 1\n var i = s.high\n result.dLen = i div 2\n while i >= 0:\n result.dVal += (ord(s[i]) - ord('0')) * q\n q *= 2\n dec i\n\n\nfunc inc(z: var Zeckendorf) =\n inc z.dVal\n z.a(0)\n\n\nfunc `+=`(z1: var Zeckendorf; z2: Zeckendorf) =\n for gn in 0 .. (2 * z2.dLen + 1):\n if (z2.dVal shr gn and 1) == 1:\n z1.b(gn)\n\n\nfunc `-=`(z1: var Zeckendorf; z2: Zeckendorf) =\n for gn in 0 .. (2 * z2.dLen + 1):\n if (z2.dVal shr gn and 1) == 1:\n z1.c(gn)\n\n while z1.dLen > 0 and (z1.dVal shr (z1.dLen * 2) and 3) == 0:\n dec z1.dLen\n\n\nfunc `*=`(z1: var Zeckendorf; z2: Zeckendorf) =\n var na, nb = z2\n var nr: Zeckendorf\n for i in 0 .. (z1.dLen + 1) * 2:\n if (z1.dVal shr i and 1) > 0: nr += nb\n let nt = nb\n nb += na\n na = nt\n z1 = nr\n\nfunc`$`(z: var Zeckendorf): string =\n if z.dVal == 0: return \"0\"\n result.add Dig1[z.dVal shr (z.dLen * 2) and 3]\n for i in countdown(z.dLen - 1, 0):\n result.add Dig[z.dVal shr (i * 2) and 3]\n\nwhen isMainModule:\n\n var g: Zeckendorf\n\n echo \"Addition:\"\n g = initZeckendorf(\"10\")\n g += initZeckendorf(\"10\")\n echo g\n g += initZeckendorf(\"10\")\n echo g\n g += initZeckendorf(\"1001\")\n echo g\n g += initZeckendorf(\"1000\")\n echo g\n g += initZeckendorf(\"10101\")\n echo g\n\n\n echo \"\\nSubtraction:\"\n g = initZeckendorf(\"1000\")\n g -= initZeckendorf(\"101\")\n echo g\n g = initZeckendorf(\"10101010\")\n g -= initZeckendorf(\"1010101\")\n echo g\n\n echo \"\\nMultiplication:\"\n g = initZeckendorf(\"1001\")\n g *= initZeckendorf(\"101\")\n echo g\n g = initZeckendorf(\"101010\")\n g += initZeckendorf(\"101\")\n echo g\n", "language": "Nim" }, { "code": "use v5.36;\n\npackage Zeckendorf;\nuse overload qw(\"\" zstring + zadd - zsub ++ zinc -- zdec * zmul / zdiv ge zge);\n\nsub new ($class, $value) {\n bless \\$value, ref $class || $class;\n}\n\nsub zinc ($self, $, $) {\n local $_ = $$self;\n s/0$/1/ or s/(?:^|0)1$/10/;\n 1 while s/(?:^|0)11/100/;\n $$self = $self->new( s/^0+\\B//r )\n}\n\nsub zdec ($self, $, $) {\n local $_ = $$self;\n 1 while s/100(?=0*$)/011/;\n s/1$/0/ || s/10$/01/;\n $$self = $self->new( s/^0+\\B//r )\n}\n\nsub zadd ($self, $other, $) {\n my ($x, $y) = map $self->new($$_), $self, $other;\n $x++, $y-- while $$y;\n $x\n}\n\nsub zsub ($self, $other, $) {\n my ($x, $y) = map $self->new($$_), $self, $other;\n $x--, $y-- while $$y;\n $x\n}\n\nsub zmul ($self, $other, $) {\n my ($x, $y) = map $self->new($$_), $self, $other;\n my $product = Zeckendorf->new(0);\n $product = $product + $x, $y-- while $y;\n $product\n}\n\nsub zdiv ($self, $other, $) {\n my ($x, $y) = map $self->new($$_), $self, $other;\n my $quotient = Zeckendorf->new(0);\n $quotient++, $x = $x - $y while $x ge $y;\n $quotient\n}\n\nsub zge ($self, $other, $) {\n my $l; $l = length $$other if length $other > ($l = length $$self);\n 0 x ($l - length $$self) . $$self ge 0 x ($l - length $$other) . $$other;\n}\n\nsub asdecimal ($self) {\n my($aa, $bb, $n) = (1, 1, 0);\n for ( reverse split '', $$self ) {\n $n += $bb * $_;\n ($aa, $bb) = ($bb, $aa + $bb);\n }\n $n\n}\n\nsub fromdecimal ($self, $value) {\n my $z = $self->new(0);\n $z++ for 1 .. $value;\n $z\n}\n\nsub zstring { ${ shift() } }\n\npackage main;\n\nfor ( split /\\n/, <<END ) # test cases\n 1 + 1\n 10 + 10\n 10100 + 1010\n 10100 - 1010\n 10100 * 1010\n 100010 * 100101\n 10100 / 1010\n 101000 / 1000\n 100001000001 / 100010\n 100001000001 / 100101\nEND\n {\n my ($left, $op, $right) = split;\n my ($x, $y) = map Zeckendorf->new($_), $left, $right;\n my $answer =\n $op eq '+' ? $x + $y :\n $op eq '-' ? $x - $y :\n $op eq '*' ? $x * $y :\n $op eq '/' ? $x / $y :\n die \"bad op <$op>\";\n printf \"%12s %s %-9s => %12s in Zeckendorf\\n\", $x, $op, $y, $answer;\n printf \"%12d %s %-9d => %12d in decimal\\n\\n\",\n $x->asdecimal, $op, $y->asdecimal, $answer->asdecimal;\n }\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">fib</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zeckendorf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Same as [[Zeckendorf_number_representation#Phix]]</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$]<</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">fib</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">and</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">k</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">k</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">k</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">c</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Convert Zeckendorf number(s) to decimal</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">dec</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">bit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">z</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">dec</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bit</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">bit</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">bit</span><span style=\"color: #0000FF;\">></span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">fib</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">z</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">dec</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">to_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Simplified copy of int_to_bits(), but in reverse order,\n -- and +ve only but (also only) as many bits as needed, and\n -- ensures there are *two* trailing 0 (most significant)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- sanity/avoid infinite loop</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">remainder</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">0</span> <span style=\"color: #000080;font-style:italic;\">-- (since eg 101+101 -&gt; 10000)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">bits</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">to_bits2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Apply to_bits() to a and b, and pad to the same length</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">sa</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">to_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">sb</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">to_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">diff</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">diff</span><span style=\"color: #0000FF;\">!=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">diff</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">sa</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">diff</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">sb</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,+</span><span style=\"color: #000000;\">diff</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">to_int</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- Copy of bits_to_int(), but in reverse order (lsb last)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">val</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">val</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">p</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">p</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">p</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">val</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #004080;\">sequence</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%b\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">z</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">was</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">wth</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- helper for cleanup, validates replacements </span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">de</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">was</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">de</span><span style=\"color: #0000FF;\">]!=</span><span style=\"color: #000000;\">was</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">was</span><span style=\"color: #0000FF;\">)!=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">wth</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">ds</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">de</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">wth</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zcleanup</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- (shared by zadd and zsub)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">l</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">deep_copy</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000080;font-style:italic;\">-- first stage, left to right, {020x -&gt; 100x', 030x -&gt; 110x', 021x-&gt;110x, 012x-&gt;101x}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- first stage cleanup</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 030 -&gt; 111</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 020 -&gt; 101</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 0120 -&gt; 1010</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">3</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">3</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 03 -&gt; 11</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 02 -&gt; 10</span>\n <span style=\"color: #008080;\">else</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">rep</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">l</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">},{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span> <span style=\"color: #000080;font-style:italic;\">-- 012 -&gt; 101</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000080;font-style:italic;\">-- second stage, pass 1, right to left, 011 -&gt; 100</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- second stage, pass 2, left to right, 011 -&gt; 100</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]={</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">to_int</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">to_bits2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">zcleanup</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_add</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zinc</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">to_bits2</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">reverse</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sq_sub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">))</span>\n <span style=\"color: #000080;font-style:italic;\">-- (/not/ combined with the first pass of the add routine!)</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s3</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s3</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #000080;font-style:italic;\">-- copied from PicoLisp: {1,-1} -&gt; {0,1} and {2,-1} -&gt; {1,1}</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">s2</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">s2</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">s2</span><span style=\"color: #0000FF;\">={</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">,-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">..</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">find</span><span style=\"color: #0000FF;\">(-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #0000FF;\">?</span><span style=\"color: #000000;\">9</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span> <span style=\"color: #000080;font-style:italic;\">-- sanity check</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">zcleanup</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zdec</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)}</span> <span style=\"color: #000080;font-style:italic;\">-- (as per task desc)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[$],</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span>\n <span style=\"color: #000000;\">bit</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">b</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">and_bits</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">bit</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">bit</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">res</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">)}</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[$]<</span><span style=\"color: #000000;\">a</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">mult</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">append</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[$],</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]))</span>\n <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">*=</span> <span style=\"color: #000000;\">2</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">mi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">mult</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\"><=</span><span style=\"color: #000000;\">a</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">res</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">mi</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">bits</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">floor</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">bits</span><span style=\"color: #0000FF;\">/</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #000080;font-style:italic;\">-- (a is the remainder)</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">20</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">zi</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zeckendorf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">zi</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %7b (%d)\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zi</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">procedure</span> <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">atom</span> <span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">object</span> <span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">expected</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">zres</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">):</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\" rem \"</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">dres</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">atom</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)?</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\"%d rem %d\"</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">res</span><span style=\"color: #0000FF;\">)),</span>\n <span style=\"color: #000000;\">aka</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"aka %d %s %d = %s\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">decimal</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">dres</span><span style=\"color: #0000FF;\">}),</span>\n <span style=\"color: #000000;\">ok</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">zres</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">expected</span><span style=\"color: #0000FF;\">?</span><span style=\"color: #008000;\">\"\"</span><span style=\"color: #0000FF;\">:</span><span style=\"color: #008000;\">\" *** ERROR ***!!\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s %s %s = %s, %s %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">op</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zstr</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">zres</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">aka</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">ok</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">procedure</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b0</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"0\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10000\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1001\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10100\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1000100\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1000101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1000101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1001 rem 1\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1001\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"100101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b10101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1010000\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10101010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10101010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1000000\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1000100\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1000100\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101000\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10100\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100101</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"100001000001\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100001000001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b100001000001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101010001 rem 0\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101000101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101000101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b101001</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101010000010101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101010000010101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b101010000010101</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1001010001001 rem 10\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100010010100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100010010100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"100000000010101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100010010100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100010010100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10010001000010\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1001000001</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10100010010100\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1010001010000001001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100000000100000</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b1010001010000001001</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b100000000100000</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10001 rem 10100001010101\"</span><span style=\"color: #0000FF;\">)</span>\n\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"+\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zadd</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101000\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"-\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zsub</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"*\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"101000001\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"1 rem 101\"</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">zmul</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0b10100</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">test</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"/\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zdiv</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0b1010</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #008000;\">\"10100 rem 0\"</span><span style=\"color: #0000FF;\">)</span>\n<!--\n", "language": "Phix" }, { "code": "(seed (in \"/dev/urandom\" (rd 8)))\n\n(de unpad (Lst)\n (while (=0 (car Lst))\n (pop 'Lst) )\n Lst )\n\n(de numz (N)\n (let Fibs (1 1)\n (while (>= N (+ (car Fibs) (cadr Fibs)))\n (push 'Fibs (+ (car Fibs) (cadr Fibs))) )\n (make\n (for I (uniq Fibs)\n (if (> I N)\n (link 0)\n (link 1)\n (dec 'N I) ) ) ) ) )\n\n(de znum (Lst)\n (let Fibs (1 1)\n (do (dec (length Lst))\n (push 'Fibs (+ (car Fibs) (cadr Fibs))) )\n (sum\n '((X Y) (unless (=0 X) Y))\n Lst\n (uniq Fibs) ) ) )\n\n(de incz (Lst)\n (addz Lst (1)) )\n\n(de decz (Lst)\n (subz Lst (1)) )\n\n(de addz (Lst1 Lst2)\n (let Max (max (length Lst1) (length Lst2))\n (reorg\n (mapcar + (need Max Lst1 0) (need Max Lst2 0)) ) ) )\n\n(de subz (Lst1 Lst2)\n (use (@A @B)\n (let\n (Max (max (length Lst1) (length Lst2))\n Lst (mapcar - (need Max Lst1 0) (need Max Lst2 0)) )\n (loop\n (while (match '(@A 1 0 0 @B) Lst)\n (setq Lst (append @A (0 1 1) @B)) )\n (while (match '(@A 1 -1 0 @B) Lst)\n (setq Lst (append @A (0 0 1) @B)) )\n (while (match '(@A 1 -1 1 @B) Lst)\n (setq Lst (append @A (0 0 2) @B)) )\n (while (match '(@A 1 0 -1 @B) Lst)\n (setq Lst (append @A (0 1 0) @B)) )\n (while (match '(@A 2 0 0 @B) Lst)\n (setq Lst (append @A (1 1 1) @B)) )\n (while (match '(@A 2 -1 0 @B) Lst)\n (setq Lst (append @A (1 0 1) @B)) )\n (while (match '(@A 2 -1 1 @B) Lst)\n (setq Lst (append @A (1 0 2) @B)) )\n (while (match '(@A 2 0 -1 @B) Lst)\n (setq Lst (append @A (1 1 0) @B)) )\n (while (match '(@A 1 -1) Lst)\n (setq Lst (append @A (0 1))) )\n (while (match '(@A 2 -1) Lst)\n (setq Lst (append @A (1 1))) )\n (NIL (match '(@A -1 @B) Lst)) )\n (reorg (unpad Lst)) ) ) )\n\n(de mulz (Lst1 Lst2)\n (let (Sums (list Lst1) Mulz (0))\n (mapc\n '((X)\n (when (= 1 (car X))\n (setq Mulz (addz (cdr X) Mulz)) )\n Mulz )\n (mapcar\n '((X)\n (cons\n X\n (push 'Sums (addz (car Sums) (cadr Sums))) ) )\n (reverse Lst2) ) ) ) )\n\n(de divz (Lst1 Lst2)\n (let Q 0\n (while (lez Lst2 Lst1)\n (setq Lst1 (subz Lst1 Lst2))\n (setq Q (incz Q)) )\n (list Q (or Lst1 (0))) ) )\n\n(de reorg (Lst)\n (use (@A @B)\n (let Lst (reverse Lst)\n (loop\n (while (match '(@A 1 1 @B) Lst)\n (if @B\n (inc (nth @B 1))\n (setq @B (1)) )\n (setq Lst (append @A (0 0) @B) ) )\n (while (match '(@A 2 @B) Lst)\n (inc\n (if (cdr @A)\n (tail 2 @A)\n @A ) )\n (if @B\n (inc (nth @B 1))\n (setq @B (1)) )\n (setq Lst (append @A (0) @B)) )\n (NIL\n (or\n (match '(@A 1 1 @B) Lst)\n (match '(@A 2 @B) Lst) ) ) )\n (reverse Lst) ) ) )\n\n(de lez (Lst1 Lst2)\n (let Max (max (length Lst1) (length Lst2))\n (<= (need Max Lst1 0) (need Max Lst2 0)) ) )\n\n(let (X 0 Y 0)\n (do 1024\n (setq X (rand 1 1024))\n (setq Y (rand 1 1024))\n (test (numz (+ X Y)) (addz (numz X) (numz Y)))\n (test (numz (* X Y)) (mulz (numz X) (numz Y)))\n (test (numz (+ X 1)) (incz (numz X))) )\n\n (do 1024\n (setq X (rand 129 1024))\n (setq Y (rand 1 128))\n (test (numz (- X Y)) (subz (numz X) (numz Y)))\n (test (numz (/ X Y)) (car (divz (numz X) (numz Y))))\n (test (numz (% X Y)) (cadr (divz (numz X) (numz Y))))\n (test (numz (- X 1)) (decz (numz X))) ) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "import copy\n\nclass Zeckendorf:\n def __init__(self, x='0'):\n q = 1\n i = len(x) - 1\n self.dLen = int(i / 2)\n self.dVal = 0\n while i >= 0:\n self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q\n q = q * 2\n i = i -1\n\n def a(self, n):\n i = n\n while True:\n if self.dLen < i:\n self.dLen = i\n j = (self.dVal >> (i * 2)) & 3\n if j == 0 or j == 1:\n return\n if j == 2:\n if (self.dVal >> ((i + 1) * 2) & 1) != 1:\n return\n self.dVal = self.dVal + (1 << (i * 2 + 1))\n return\n if j == 3:\n temp = 3 << (i * 2)\n temp = temp ^ -1\n self.dVal = self.dVal & temp\n self.b((i + 1) * 2)\n i = i + 1\n\n def b(self, pos):\n if pos == 0:\n self.inc()\n return\n if (self.dVal >> pos) & 1 == 0:\n self.dVal = self.dVal + (1 << pos)\n self.a(int(pos / 2))\n if pos > 1:\n self.a(int(pos / 2) - 1)\n else:\n temp = 1 << pos\n temp = temp ^ -1\n self.dVal = self.dVal & temp\n self.b(pos + 1)\n self.b(pos - (2 if pos > 1 else 1))\n\n def c(self, pos):\n if (self.dVal >> pos) & 1 == 1:\n temp = 1 << pos\n temp = temp ^ -1\n self.dVal = self.dVal & temp\n return\n self.c(pos + 1)\n if pos > 0:\n self.b(pos - 1)\n else:\n self.inc()\n\n def inc(self):\n self.dVal = self.dVal + 1\n self.a(0)\n\n def __add__(self, rhs):\n copy = self\n rhs_dVal = rhs.dVal\n limit = (rhs.dLen + 1) * 2\n for gn in range(0, limit):\n if ((rhs_dVal >> gn) & 1) == 1:\n copy.b(gn)\n return copy\n\n def __sub__(self, rhs):\n copy = self\n rhs_dVal = rhs.dVal\n limit = (rhs.dLen + 1) * 2\n for gn in range(0, limit):\n if (rhs_dVal >> gn) & 1 == 1:\n copy.c(gn)\n while (((copy.dVal >> ((copy.dLen * 2) & 31)) & 3) == 0) or (copy.dLen == 0):\n copy.dLen = copy.dLen - 1\n return copy\n\n def __mul__(self, rhs):\n na = copy.deepcopy(rhs)\n nb = copy.deepcopy(rhs)\n nr = Zeckendorf()\n dVal = self.dVal\n for i in range(0, (self.dLen + 1) * 2):\n if ((dVal >> i) & 1) > 0:\n nr = nr + nb\n nt = copy.deepcopy(nb)\n nb = nb + na\n na = copy.deepcopy(nt)\n return nr\n\n def __str__(self):\n dig = [\"00\", \"01\", \"10\"]\n dig1 = [\"\", \"1\", \"10\"]\n\n if self.dVal == 0:\n return '0'\n idx = (self.dVal >> ((self.dLen * 2) & 31)) & 3\n sb = dig1[idx]\n i = self.dLen - 1\n while i >= 0:\n idx = (self.dVal >> (i * 2)) & 3\n sb = sb + dig[idx]\n i = i - 1\n return sb\n\n# main\nprint \"Addition:\"\ng = Zeckendorf(\"10\")\ng = g + Zeckendorf(\"10\")\nprint g\ng = g + Zeckendorf(\"10\")\nprint g\ng = g + Zeckendorf(\"1001\")\nprint g\ng = g + Zeckendorf(\"1000\")\nprint g\ng = g + Zeckendorf(\"10101\")\nprint g\nprint\n\nprint \"Subtraction:\"\ng = Zeckendorf(\"1000\")\ng = g - Zeckendorf(\"101\")\nprint g\ng = Zeckendorf(\"10101010\")\ng = g - Zeckendorf(\"1010101\")\nprint g\nprint\n\nprint \"Multiplication:\"\ng = Zeckendorf(\"1001\")\ng = g * Zeckendorf(\"101\")\nprint g\ng = Zeckendorf(\"101010\")\ng = g + Zeckendorf(\"101\")\nprint g\n", "language": "Python" }, { "code": " [ nextword\n dup $ \"\" = if\n [ $ '\"bin\" needs to be followed by a string.'\n message put bail ]\n dup\n 2 base put\n $->n\n base release\n not if\n [ drop\n $ \" is not a binary number.\"\n join message put\n bail ]\n nip\n swap dip join ] builds bin ( [ $ --> [ $ )\n\n [ ^ not ] is zeq ( z z --> b )\n\n [ zeq not ] is zne ( z z --> b )\n\n [ false unrot\n [ 2dup zne while\n rot drop\n dup 1 & unrot\n 1 >> dip [ 1 >> ]\n again ]\n 2drop ] is zlt ( z z --> b )\n\n [ swap zlt ] is zgt ( z z --> b )\n\n [ zlt not ] is zge ( z z --> b )\n\n [ zgt not ] is zle ( z z --> b )\n\n [ dup 1 << & 0 zeq ] is canonical ( z --> b )\n\n [ [] swap\n [ dup 1 & rot join\n swap 1 >>\n dup not until ]\n drop ] is bits ( z --> [ )\n\n [ dup canonical if done\n 0 0 rot bits\n witheach\n [ |\n [ table\n [ 1 << 0 ]\n [ 1 << 1 | bin 10 ]\n [ 1 << 0 ]\n [ 1 >> 1 |\n bin 10 << 0 ] ]\n do ]\n drop again ] is canonise ( z --> z )\n\n [ dup bin -100\n & swap bin 11 & ] is 2blit ( z --> z z )\n\n [ 2blit bit | canonise ] is zinc ( z --> z )\n\n [ dup 0 zeq if\n [ $ \"Cannot zdec zero.\"\n fail ]\n 1\n [ 2dup & if done\n 1 << again ]\n tuck ^\n swap 1 <<\n [ bin 10 >>\n tuck | swap\n dup 0 zeq until ]\n drop ] is zdec ( z --> z )\n\n forward is zadd ( z --> z )\n\n [ dup 2blit\n [ table\n 0 bin 10 bin 101 ]\n unrot bin 10 >>\n swap 1 <<\n rot | zadd ] is zdouble ( z --> z )\n\n [ 2dup ^ canonise\n unrot &\n dup 0 zeq iff\n drop done\n zdouble again ] resolves zadd ( z z --> z )\n\n [ tuck take zadd swap put ] is ztally ( z s --> )\n\n [ 0 temp put\n dip dup\n [ dup while\n dup 1 & if\n [ over temp ztally ]\n dip [ tuck zadd ]\n 1 >> again ]\n drop 2drop temp take ] is zmult ( z z --> z )\n\n [ 2dup & ~ tuck & dip & ] is exorcise ( z z --> z z )\n\n [ dup\n [ 0 ' [ 0 0 0 ] rot 1\n [ 2dup > while\n 1 << again ]\n 1 <<\n [ dup while\n 2swap 2over & 0 !=\n dip\n [ dup\n ' [ 1 0 0 ]\n = if\n [ drop\n ' [ 0 1 1 ] ] ]\n join\n behead\n rot 1 << | swap\n 2swap 1 >> again ]\n 2drop\n witheach\n [ dip [ 1 << ] | ]\n dup bin 111 &\n bin 100 zeq if\n [ bin -1000 &\n bin 11 | ] ]\n 2dup zeq iff drop done\n nip again ] is defrock ( z --> z )\n\n [ 2dup zlt if swap\n dup 0 zeq iff drop done\n [ exorcise dup while\n dip defrock\n exorcise dup while\n dup dip zadd\n zdouble\n again ]\n drop canonise ] is zdiff ( z z --> z )\n\n [ dup 0 zeq if\n [ $ \"Z-division by zero.\"\n fail ]\n 0 unrot swap\n temp put\n dup nested\n [ dup 0 peek\n tuck dip rot zadd\n temp share\n over zge while\n swap join\n again ]\n drop nip\n temp take\n swap witheach\n [ rot 1 << unrot\n 2dup zge iff\n [ zdiff\n dip [ 1 | ] ]\n else drop ] ] is zdivmod ( z z --> z z )\n\n [ zdivmod drop ] is zdiv ( z z --> z )\n\n [ zdivmod nip ] is zmod ( z z --> z )\n\n [ [ dup while\n tuck zmod again ]\n drop ] is zgcd ( z z --> z )\n\n [ 2dup and iff\n [ 2dup zgcd\n zdiv zmult ]\n else and ] is zlcm ( z z --> z )\n\n 10 times\n [ 10 15 ** random\n 10 15 ** random\n 2dup lcm echo cr\n n->z dip n->z\n zlcm z->n echo cr cr ]\n", "language": "Quackery" }, { "code": "#lang racket (require math)\n\n(define sqrt5 (sqrt 5))\n(define phi (* 0.5 (+ 1 sqrt5)))\n\n;; What is the nth fibonnaci number, shifted by 2 so that\n;; F(0) = 1, F(1) = 2, ...?\n;;\n(define (F n)\n (fibonacci (+ n 2)))\n\n;; What is the largest n such that F(n) <= m?\n;;\n(define (F* m)\n (let ([n (- (inexact->exact (round (/ (log (* m sqrt5)) (log phi)))) 2)])\n (if (<= (F n) m) n (sub1 n))))\n\n(define (zeck->natural z)\n (for/sum ([i (reverse z)]\n [j (in-naturals)])\n (* i (F j))))\n\n(define (natural->zeck n)\n (if (zero? n)\n null\n (for/list ([i (in-range (F* n) -1 -1)])\n (let ([f (F i)])\n (cond [(>= n f) (set! n (- n f))\n 1]\n [else 0])))))\n\n; Extend list to the right to a length of len with repeated padding elements\n;\n(define (pad lst len [padding 0])\n (append lst (make-list (- len (length lst)) padding)))\n\n; Strip padding elements from the left of the list\n;\n(define (unpad lst [padding 0])\n (cond [(null? lst) lst]\n [(equal? (first lst) padding) (unpad (rest lst) padding)]\n [else lst]))\n\n;; Run a filter function across a window in a list from left to right\n;;\n(define (left->right width fn)\n (λ (lst)\n (let F ([a lst])\n (if (< (length a) width)\n a\n (let ([f (fn (take a width))])\n (cons (first f) (F (append (rest f) (drop a width)))))))))\n\n;; Run a function fn across a window in a list from right to left\n;;\n(define (right->left width fn)\n (λ (lst)\n (let F ([a lst])\n (if (< (length a) width)\n a\n (let ([f (fn (take-right a width))])\n (append (F (append (drop-right a width) (drop-right f 1)))\n (list (last f))))))))\n\n;; (a0 a1 a2 ... an) -> (a0 a1 a2 ... (fn ... an))\n;;\n(define (replace-tail width fn)\n (λ (lst)\n (append (drop-right lst width) (fn (take-right lst width)))))\n\n(define (rule-a lst)\n (match lst\n [(list 0 2 0 x) (list 1 0 0 (add1 x))]\n [(list 0 3 0 x) (list 1 1 0 (add1 x))]\n [(list 0 2 1 x) (list 1 1 0 x)]\n [(list 0 1 2 x) (list 1 0 1 x)]\n [else lst]))\n\n(define (rule-a-tail lst)\n (match lst\n [(list x 0 3 0) (list x 1 1 1)]\n [(list x 0 2 0) (list x 1 0 1)]\n [(list 0 1 2 0) (list 1 0 1 0)]\n [(list x y 0 3) (list x y 1 1)]\n [(list x y 0 2) (list x y 1 0)]\n [(list x 0 1 2) (list x 1 0 0)]\n [else lst]))\n\n(define (rule-b lst)\n (match lst\n [(list 0 1 1) (list 1 0 0)]\n [else lst]))\n\n(define (rule-c lst)\n (match lst\n [(list 1 0 0) (list 0 1 1)]\n [(list 1 -1 0) (list 0 0 1)]\n [(list 1 -1 1) (list 0 0 2)]\n [(list 1 0 -1) (list 0 1 0)]\n [(list 2 0 0) (list 1 1 1)]\n [(list 2 -1 0) (list 1 0 1)]\n [(list 2 -1 1) (list 1 0 2)]\n [(list 2 0 -1) (list 1 1 0)]\n [else lst]))\n\n(define (zeck-combine op y z [f identity])\n (let* ([bits (max (add1 (length y)) (add1 (length z)) 4)]\n [f0 (λ (x) (pad (reverse x) bits))]\n [f1 (left->right 4 rule-a)]\n [f2 (replace-tail 4 rule-a-tail)]\n [f3 (right->left 3 rule-b)]\n [f4 (left->right 3 rule-b)])\n ((compose1 unpad f4 f3 f2 f1 f reverse) (map op (f0 y) (f0 z)))))\n\n(define (zeck+ y z)\n (zeck-combine + y z))\n\n(define (zeck- y z)\n (when (zeck< y z) (error (format \"~a\" `(zeck-: cannot subtract since ,y < ,z))))\n (zeck-combine - y z (left->right 3 rule-c)))\n\n(define (zeck* y z)\n (define (M ry Zn Zn_1 [acc null])\n (if (null? ry)\n acc\n (M (rest ry) (zeck+ Zn Zn_1) Zn\n (if (zero? (first ry)) acc (zeck+ acc Zn)))))\n (cond [(zeck< z y) (zeck* z y)]\n [(null? y) null] ; 0 * z -> 0\n [else (M (reverse y) z z)]))\n\n(define (zeck-quotient/remainder y z)\n (define (M Zn acc)\n (if (zeck< y Zn)\n (drop-right acc 1)\n (M (zeck+ Zn (first acc)) (cons Zn acc))))\n (define (D x m [acc null])\n (if (null? m)\n (values (reverse acc) x)\n (let* ([v (first m)]\n [smaller (zeck< v x)]\n [bit (if smaller 1 0)]\n [x_ (if smaller (zeck- x v) x)])\n (D x_ (rest m) (cons bit acc)))))\n (D y (M z (list z))))\n\n(define (zeck-quotient y z)\n (let-values ([(quotient _) (zeck-quotient/remainder y z)])\n quotient))\n\n(define (zeck-remainder y z)\n (let-values ([(_ remainder) (zeck-quotient/remainder y z)])\n remainder))\n\n(define (zeck-add1 z)\n (zeck+ z '(1)))\n\n(define (zeck= y z)\n (equal? (unpad y) (unpad z)))\n\n(define (zeck< y z)\n ; Compare equal-length unpadded zecks\n (define (LT a b)\n (if (null? a)\n #f\n (let ([a0 (first a)] [b0 (first b)])\n (if (= a0 b0)\n (LT (rest a) (rest b))\n (= a0 0)))))\n\n (let* ([a (unpad y)] [len-a (length a)]\n [b (unpad z)] [len-b (length b)])\n (cond [(< len-a len-b) #t]\n [(> len-a len-b) #f]\n [else (LT a b)])))\n\n(define (zeck> y z)\n (not (or (zeck= y z) (zeck< y z))))\n\n\n;; Examples\n;;\n(define (example op-name op a b)\n (let* ([y (natural->zeck a)]\n [z (natural->zeck b)]\n [x (op y z)]\n [c (zeck->natural x)])\n (printf \"~a ~a ~a = ~a ~a ~a = ~a = ~a\\n\"\n a op-name b y op-name z x c)))\n\n(example '+ zeck+ 888 111)\n(example '- zeck- 888 111)\n(example '* zeck* 8 111)\n(example '/ zeck-quotient 9876 1000)\n(example '% zeck-remainder 9876 1000)\n", "language": "Racket" }, { "code": "my $z1 = '1'; # glyph to use for a '1'\nmy $z0 = '0'; # glyph to use for a '0'\n\nsub zorder($a) { ($z0 lt $z1) ?? $a !! $a.trans([$z0, $z1] => [$z1, $z0]) }\n\n######## Zeckendorf comparison operators #########\n\n# less than\nsub infix:<ltz>($a, $b) { $a.&zorder lt $b.&zorder }\n\n# greater than\nsub infix:<gtz>($a, $b) { $a.&zorder gt $b.&zorder }\n\n# equal\nsub infix:<eqz>($a, $b) { $a eq $b }\n\n# not equal\nsub infix:<nez>($a, $b) { $a ne $b }\n\n######## Operators for Zeckendorf arithmetic ########\n\n# post increment\nsub postfix:<++z>($a is rw) {\n $a = (\"$z0$z0\"~$a).subst(/(\"$z0$z0\")($z1+ %% $z0)?$/,\n -> $/ { \"$z0$z1\" ~ ($1 ?? $z0 x $1.chars !! '') });\n $a ~~ s/^$z0+//;\n $a\n}\n\n# post decrement\nsub postfix:<--z>($a is rw) {\n $a.=subst(/$z1($z0*)$/,\n -> $/ {$z0 ~ \"$z1$z0\" x $0.chars div 2 ~ $z1 x $0.chars mod 2});\n $a ~~ s/^$z0+(.+)$/$0/;\n $a\n}\n\n# addition\nsub infix:<+z>($a is copy, $b is copy) { $a++z; $a++z while $b--z nez $z0; $a }\n\n# subtraction\nsub infix:<-z>($a is copy, $b is copy) { $a--z; $a--z while $b--z nez $z0; $a }\n\n# multiplication\nsub infix:<×z>($a, $b) {\n return $z0 if $a eqz $z0 or $b eqz $z0;\n return $a if $b eqz $z1;\n return $b if $a eqz $z1;\n my $c = $a;\n my $d = $z1;\n repeat {\n my $e = $z0;\n repeat { $c++z; $e++z } until $e eqz $a;\n $d++z;\n } until $d eqz $b;\n $c\n}\n\n# division (really more of a div mod)\nsub infix:</z>($a is copy, $b is copy) {\n fail \"Divide by zero\" if $b eqz $z0;\n return $a if $a eqz $z0 or $b eqz $z1;\n my $c = $z0;\n repeat {\n my $d = $b +z ($z1 ~ $z0);\n $c++z;\n $a++z;\n $a--z while $d--z nez $z0\n } until $a ltz $b;\n $c ~= \" remainder $a\" if $a nez $z0;\n $c\n}\n\n###################### Testing ######################\n\n# helper sub to translate constants into the particular glyphs you used\nsub z($a) { $a.trans([<1 0>] => [$z1, $z0]) }\n\nsay \"Using the glyph '$z1' for 1 and '$z0' for 0\\n\";\n\nmy $fmt = \"%-22s = %15s %s\\n\";\n\nmy $zeck = $z1;\n\nprintf( $fmt, \"$zeck++z\", $zeck++z, '# increment' ) for 1 .. 10;\n\nprintf $fmt, \"$zeck +z {z('1010')}\", $zeck +z= z('1010'), '# addition';\n\nprintf $fmt, \"$zeck -z {z('100')}\", $zeck -z= z('100'), '# subtraction';\n\nprintf $fmt, \"$zeck ×z {z('100101')}\", $zeck ×z= z('100101'), '# multiplication';\n\nprintf $fmt, \"$zeck /z {z('100')}\", $zeck /z= z('100'), '# division';\n\nprintf( $fmt, \"$zeck--z\", $zeck--z, '# decrement' ) for 1 .. 5;\n\nprintf $fmt, \"$zeck ×z {z('101001')}\", $zeck ×z= z('101001'), '# multiplication';\n\nprintf $fmt, \"$zeck /z {z('100')}\", $zeck /z= z('100'), '# division';\n", "language": "Raku" }, { "code": "struct Zeckendorf {\n d_val: i32,\n d_len: i32,\n}\n\nimpl Zeckendorf {\n fn new(x: &str) -> Zeckendorf {\n let mut d_val = 0;\n let mut q = 1;\n let mut i = x.len() as i32 - 1;\n let d_len = i / 2;\n while i >= 0 {\n d_val += (x.chars().nth(i as usize).unwrap() as i32 - '0' as i32) * q;\n q *= 2;\n i -= 1;\n }\n\n Zeckendorf { d_val, d_len }\n }\n\n fn a(&mut self, n: i32) {\n let mut i = n;\n loop {\n if self.d_len < i {\n self.d_len = i;\n }\n let j = (self.d_val >> (i * 2)) & 3;\n match j {\n 0 | 1 => return,\n 2 => {\n if ((self.d_val >> ((i + 1) * 2)) & 1) != 1 {\n return;\n }\n self.d_val += 1 << (i * 2 + 1);\n return;\n }\n 3 => {\n let temp = 3 << (i * 2);\n let temp = !temp;\n self.d_val &= temp;\n self.b((i + 1) * 2);\n }\n _ => (),\n }\n i += 1;\n }\n }\n\n fn b(&mut self, pos: i32) {\n if pos == 0 {\n self.inc();\n return;\n }\n if ((self.d_val >> pos) & 1) == 0 {\n self.d_val += 1 << pos;\n self.a(pos / 2);\n if pos > 1 {\n self.a(pos / 2 - 1);\n }\n } else {\n let temp = 1 << pos;\n let temp = !temp;\n self.d_val &= temp;\n self.b(pos + 1);\n self.b(pos - if pos > 1 { 2 } else { 1 });\n }\n }\n\n fn c(&mut self, pos: i32) {\n if ((self.d_val >> pos) & 1) == 1 {\n let temp = 1 << pos;\n let temp = !temp;\n self.d_val &= temp;\n return;\n }\n self.c(pos + 1);\n if pos > 0 {\n self.b(pos - 1);\n } else {\n self.inc();\n }\n }\n\n fn inc(&mut self) -> &mut Self {\n self.d_val += 1;\n self.a(0);\n self\n }\n\n fn copy(&self) -> Zeckendorf {\n Zeckendorf {\n d_val: self.d_val,\n d_len: self.d_len,\n }\n }\n\n fn plus_assign(&mut self, other: &Zeckendorf) {\n for gn in 0..(other.d_len + 1) * 2 {\n if ((other.d_val >> gn) & 1) == 1 {\n self.b(gn);\n }\n }\n }\n\n fn minus_assign(&mut self, other: &Zeckendorf) {\n for gn in 0..(other.d_len + 1) * 2 {\n if ((other.d_val >> gn) & 1) == 1 {\n self.c(gn);\n }\n }\n while (((self.d_val >> self.d_len * 2) & 3) == 0) || (self.d_len == 0) {\n self.d_len -= 1;\n }\n }\n\n fn times_assign(&mut self, other: &Zeckendorf) {\n let mut na = other.copy();\n let mut nb = other.copy();\n let mut nt;\n let mut nr = Zeckendorf::new(\"0\");\n for i in 0..(self.d_len + 1) * 2 {\n if ((self.d_val >> i) & 1) > 0 {\n nr.plus_assign(&nb);\n }\n nt = nb.copy();\n nb.plus_assign(&na);\n na = nt.copy(); // `na` is now mutable, so this reassignment is allowed\n }\n self.d_val = nr.d_val;\n self.d_len = nr.d_len;\n }\n\n fn to_string(&self) -> String {\n if self.d_val == 0 {\n return \"0\".to_string();\n }\n\n let dig = [\"00\", \"01\", \"10\"];\n let dig1 = [\"\", \"1\", \"10\"];\n\n let idx = (self.d_val >> (self.d_len * 2)) & 3;\n let mut sb = String::from(dig1[idx as usize]);\n for i in (0..self.d_len).rev() {\n let idx = (self.d_val >> (i * 2)) & 3;\n sb.push_str(dig[idx as usize]);\n }\n sb\n }\n}\n\nfn main() {\n println!(\"Addition:\");\n let mut g = Zeckendorf::new(\"10\");\n g.plus_assign(&Zeckendorf::new(\"10\"));\n println!(\"{}\", g.to_string());\n g.plus_assign(&Zeckendorf::new(\"10\"));\n println!(\"{}\", g.to_string());\n g.plus_assign(&Zeckendorf::new(\"1001\"));\n println!(\"{}\", g.to_string());\n g.plus_assign(&Zeckendorf::new(\"1000\"));\n println!(\"{}\", g.to_string());\n g.plus_assign(&Zeckendorf::new(\"10101\"));\n println!(\"{}\", g.to_string());\n println!();\n\n println!(\"Subtraction:\");\n g = Zeckendorf::new(\"1000\");\n g.minus_assign(&Zeckendorf::new(\"101\"));\n println!(\"{}\", g.to_string());\n g = Zeckendorf::new(\"10101010\");\n g.minus_assign(&Zeckendorf::new(\"1010101\"));\n println!(\"{}\", g.to_string());\n println!();\n\n println!(\"Multiplication:\");\n g = Zeckendorf::new(\"1001\");\n g.times_assign(&Zeckendorf::new(\"101\"));\n println!(\"{}\", g.to_string());\n g = Zeckendorf::new(\"101010\");\n g.plus_assign(&Zeckendorf::new(\"101\"));\n println!(\"{}\", g.to_string());\n}\n", "language": "Rust" }, { "code": "import scala.collection.mutable.ListBuffer\n\nobject ZeckendorfArithmetic extends App {\n\n\n val elapsed: (=> Unit) => Long = f => {\n val s = System.currentTimeMillis\n\n f\n\n (System.currentTimeMillis - s) / 1000\n }\n val add: (Z, Z) => Z = (z1, z2) => z1 + z2\n val subtract: (Z, Z) => Z = (z1, z2) => z1 - z2\n val multiply: (Z, Z) => Z = (z1, z2) => z1 * z2\n val divide: (Z, Z) => Option[Z] = (z1, z2) => z1 / z2\n val modulo: (Z, Z) => Option[Z] = (z1, z2) => z1 % z2\n val ops = Map((\"+\", add), (\"-\", subtract), (\"*\", multiply), (\"/\", divide), (\"%\", modulo))\n val calcs = List(\n (Z(\"101\"), \"+\", Z(\"10100\"))\n , (Z(\"101\"), \"-\", Z(\"10100\"))\n , (Z(\"101\"), \"*\", Z(\"10100\"))\n , (Z(\"101\"), \"/\", Z(\"10100\"))\n , (Z(\"-1010101\"), \"+\", Z(\"10100\"))\n , (Z(\"-1010101\"), \"-\", Z(\"10100\"))\n , (Z(\"-1010101\"), \"*\", Z(\"10100\"))\n , (Z(\"-1010101\"), \"/\", Z(\"10100\"))\n , (Z(\"1000101010\"), \"+\", Z(\"10101010\"))\n , (Z(\"1000101010\"), \"-\", Z(\"10101010\"))\n , (Z(\"1000101010\"), \"*\", Z(\"10101010\"))\n , (Z(\"1000101010\"), \"/\", Z(\"10101010\"))\n , (Z(\"10100\"), \"+\", Z(\"1010\"))\n , (Z(\"100101\"), \"-\", Z(\"100\"))\n , (Z(\"1010101010101010101\"), \"+\", Z(\"-1010101010101\"))\n , (Z(\"1010101010101010101\"), \"-\", Z(\"-1010101010101\"))\n , (Z(\"1010101010101010101\"), \"*\", Z(\"-1010101010101\"))\n , (Z(\"1010101010101010101\"), \"/\", Z(\"-1010101010101\"))\n , (Z(\"1010101010101010101\"), \"%\", Z(\"-1010101010101\"))\n , (Z(\"1010101010101010101\"), \"+\", Z(\"101010101010101\"))\n , (Z(\"1010101010101010101\"), \"-\", Z(\"101010101010101\"))\n , (Z(\"1010101010101010101\"), \"*\", Z(\"101010101010101\"))\n , (Z(\"1010101010101010101\"), \"/\", Z(\"101010101010101\"))\n , (Z(\"1010101010101010101\"), \"%\", Z(\"101010101010101\"))\n , (Z(\"10101010101010101010\"), \"+\", Z(\"1010101010101010\"))\n , (Z(\"10101010101010101010\"), \"-\", Z(\"1010101010101010\"))\n , (Z(\"10101010101010101010\"), \"*\", Z(\"1010101010101010\"))\n , (Z(\"10101010101010101010\"), \"/\", Z(\"1010101010101010\"))\n , (Z(\"10101010101010101010\"), \"%\", Z(\"1010101010101010\"))\n , (Z(\"1010\"), \"%\", Z(\"10\"))\n , (Z(\"1010\"), \"%\", Z(\"-10\"))\n , (Z(\"-1010\"), \"%\", Z(\"10\"))\n , (Z(\"-1010\"), \"%\", Z(\"-10\"))\n , (Z(\"100\"), \"/\", Z(\"0\"))\n , (Z(\"100\"), \"%\", Z(\"0\"))\n )\n val iadd: (BigInt, BigInt) => BigInt = (a, b) => a + b\n val isub: (BigInt, BigInt) => BigInt = (a, b) => a - b\n\n // just for result checking:\n\n import Z._\n\n val imul: (BigInt, BigInt) => BigInt = (a, b) => a * b\n val idiv: (BigInt, BigInt) => Option[BigInt] = (a, b) => if (b == 0) None else Some(a / b)\n val imod: (BigInt, BigInt) => Option[BigInt] = (a, b) => if (b == 0) None else Some(a % b)\n val iops = Map((\"+\", iadd), (\"-\", isub), (\"*\", imul), (\"/\", idiv), (\"%\", imod))\n\n case class Z(var zs: String) {\n\n import Z._\n\n require((zs.toSet -- Set('-', '0', '1') == Set()) && (!zs.contains(\"11\")))\n\n //--- fa(summand1.z,summand2.z) --------------------------\n val fa: (BigInt, BigInt) => BigInt = (z1, z2) => {\n val v = z1.toString.toCharArray.map(_.asDigit).reverse.padTo(5, 0).zipAll(z2.toString.toCharArray.map(_.asDigit).reverse, 0, 0)\n val arr1 = (v.map(p => p._1 + p._2) :+ 0).reverse\n (0 to arr1.length - 4) foreach { i => //stage1\n val a = arr1.slice(i, i + 4).toList\n val b = a.foldRight(\"\")(\"\" + _ + _) dropRight 1\n val a1 = b match {\n case \"020\" => List(1, 0, 0, a(3) + 1)\n case \"030\" => List(1, 1, 0, a(3) + 1)\n case \"021\" => List(1, 1, 0, a(3))\n case \"012\" => List(1, 0, 1, a(3))\n case _ => a\n }\n 0 to 3 foreach { j => arr1(j + i) = a1(j) }\n }\n val arr2 = arr1.foldRight(\"\")(\"\" + _ + _)\n .replace(\"0120\", \"1010\").replace(\"030\", \"111\").replace(\"003\", \"100\").replace(\"020\", \"101\")\n .replace(\"003\", \"100\").replace(\"012\", \"101\").replace(\"021\", \"110\")\n .replace(\"02\", \"10\").replace(\"03\", \"11\")\n .reverse.toArray\n (0 to arr2.length - 3) foreach { i => //stage2, step1\n val a = arr2.slice(i, i + 3).toList\n val b = a.foldRight(\"\")(\"\" + _ + _)\n val a1 = b match {\n case \"110\" => List('0', '0', '1')\n case _ => a\n }\n 0 to 2 foreach { j => arr2(j + i) = a1(j) }\n }\n val arr3 = arr2.foldRight(\"\")(\"\" + _ + _).concat(\"0\").reverse.toArray\n (0 to arr3.length - 3) foreach { i => //stage2, step2\n val a = arr3.slice(i, i + 3).toList\n val b = a.foldRight(\"\")(\"\" + _ + _)\n val a1 = b match {\n case \"011\" => List('1', '0', '0')\n case _ => a\n }\n 0 to 2 foreach { j => arr3(j + i) = a1(j) }\n }\n BigInt(arr3.foldRight(\"\")(\"\" + _ + _))\n }\n //--- fs(minuend.z,subtrahend.z) -------------------------\n val fs: (BigInt, BigInt) => BigInt = (min, sub) => {\n val zmvr = min.toString.toCharArray.map(_.asDigit).reverse\n val zsvr = sub.toString.toCharArray.map(_.asDigit).reverse.padTo(zmvr.length, 0)\n val v = zmvr.zipAll(zsvr, 0, 0).reverse\n val last = v.length - 1\n val zma = zmvr.reverse.toArray\n\n val zsa = zsvr.reverse.toArray\n for (i <- (0 to last).reverse) {\n val e = zma(i) - zsa(i)\n if (e < 0) {\n zma(i - 1) = zma(i - 1) - 1\n zma(i) = 0\n val part = Z(((i to last).map(zma(_))).foldRight(\"\")(\"\" + _ + _))\n val carry = Z(\"1\".padTo(last - i, \"0\").foldRight(\"\")(\"\" + _ + _))\n val sum = part + carry\n\n val sums = sum.z.toString\n (1 to sum.size) foreach { j => zma(last - sum.size + j) = sums(j - 1).asDigit }\n if (zma(i - 1) < 0) {\n for (j <- (0 until i).reverse) {\n if (zma(j) < 0) {\n zma(j - 1) = zma(j - 1) - 1\n zma(j) = 0\n val part = Z(((j to last).map(zma(_))).foldRight(\"\")(\"\" + _ + _))\n val carry = Z(\"1\".padTo(last - j, \"0\").foldRight(\"\")(\"\" + _ + _))\n val sum = part + carry\n\n val sums = sum.z.toString\n (1 to sum.size) foreach { k => zma(last - sum.size + k) = sums(k - 1).asDigit }\n }\n }\n }\n }\n else zma(i) = e\n zsa(i) = 0\n }\n BigInt(zma.foldRight(\"\")(\"\" + _ + _))\n }\n //--- fm(multiplicand.z,multplier.z) ---------------------\n val fm: (BigInt, BigInt) => BigInt = (mc, mp) => {\n val mct = mt(Z(mc.toString))\n val mpxi = mp.toString.reverse.toCharArray.map(_.asDigit).zipWithIndex.filter(_._1 != 0).map(_._2)\n mpxi.foldRight(Z(\"0\"))((fi, sum) => sum + mct(fi)).z\n }\n //--- fd(dividend.z,divisor.z) ---------------------------\n val fd: (BigInt, BigInt) => BigInt = (dd, ds) => {\n val dst = dt(Z(dd.toString), Z(ds.toString)).reverse\n var diff = Z(dd.toString)\n val zd = ListBuffer[String]()\n 0 until dst.length foreach { i =>\n if (dst(i) > diff) zd += \"0\" else {\n diff = diff - dst(i)\n\n zd += \"1\"\n }\n }\n BigInt(zd.mkString)\n }\n val fasig: (Z, Z) => Int = (z1, z2) => if (z1.z.abs > z2.z.abs) z1.z.signum else z2.z.signum\n val fssig: (Z, Z) => Int = (z1, z2) =>\n if ((z1.z.abs > z2.z.abs && z1.z.signum > 0) || (z1.z.abs < z2.z.abs && z1.z.signum < 0)) 1 else -1\n var z: BigInt = BigInt(zs)\n\n override def toString: String = \"\" + z + \"Z(i:\" + z2i(this) + \")\"\n\n def size: Int = z.abs.toString.length\n\n def ++ : Z = {\n val za = this + Z(\"1\")\n\n this.zs = za.zs\n\n this.z = za.z\n\n this\n }\n\n def +(that: Z): Z =\n if (this == Z(\"0\")) that\n else if (that == Z(\"0\")) this\n else if (this.z.signum == that.z.signum) Z((fa(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum).toString)\n else if (this.z.abs == that.z.abs) Z(\"0\")\n else Z((fs(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * fasig(this, that)).toString)\n\n def -- : Z = {\n val zs = this - Z(\"1\")\n\n this.zs = zs.zs\n\n this.z = zs.z\n\n this\n }\n\n def -(that: Z): Z =\n if (this == Z(\"0\")) Z((that.z * (-1)).toString)\n else if (that == Z(\"0\")) this\n else if (this.z.signum != that.z.signum) Z((fa(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum).toString)\n else if (this.z.abs == that.z.abs) Z(\"0\")\n else Z((fs(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * fssig(this, that)).toString)\n\n def %(that: Z): Option[Z] =\n if (that == Z(\"0\")) None\n else if (this == Z(\"0\")) Some(Z(\"0\"))\n else if (that == Z(\"1\")) Some(Z(\"0\"))\n else if (this.z.abs < that.z.abs) Some(this)\n else if (this.z == that.z) Some(Z(\"0\"))\n else this / that match {\n case None => None\n\n case Some(z) => Some(this - z * that)\n }\n\n def *(that: Z): Z =\n if (this == Z(\"0\") || that == Z(\"0\")) Z(\"0\")\n else if (this == Z(\"1\")) that\n else if (that == Z(\"1\")) this\n else Z((fm(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum * that.z.signum).toString)\n\n def /(that: Z): Option[Z] =\n if (that == Z(\"0\")) None\n else if (this == Z(\"0\")) Some(Z(\"0\"))\n else if (that == Z(\"1\")) Some(Z(\"1\"))\n else if (this.z.abs < that.z.abs) Some(Z(\"0\"))\n else if (this.z == that.z) Some(Z(\"1\"))\n else Some(Z((fd(this.z.abs.max(that.z.abs), this.z.abs.min(that.z.abs)) * this.z.signum * that.z.signum).toString))\n\n def <(that: Z): Boolean = this.z < that.z\n\n def <=(that: Z): Boolean = this.z <= that.z\n\n def >(that: Z): Boolean = this.z > that.z\n\n def >=(that: Z): Boolean = this.z >= that.z\n\n }\n\n object Z {\n // only for comfort and result checking:\n val fibs: LazyList[BigInt] = {\n def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)\n\n series(1, 0).tail.tail.tail\n }\n val z2i: Z => BigInt = z => z.z.abs.toString.toCharArray.map(_.asDigit).reverse.zipWithIndex.map { case (v, i) => v * fibs(i) }.foldRight(BigInt(0))(_ + _) * z.z.signum\n\n var fmts: Map[Z, List[Z]] = Map(Z(\"0\") -> List[Z](Z(\"0\"))) //map of Fibonacci multiples table of divisors\n\n // get division table (division weight vector)\n def dt(dd: Z, ds: Z): List[Z] = {\n val wv = new ListBuffer[Z]\n wv ++= mt(ds)\n var zs = ds.z.abs.toString\n val upper = dd.z.abs.toString\n while ((zs.length < upper.length)) {\n wv += (wv.toList.last + wv.toList.reverse.tail.head)\n\n zs = \"1\" + zs\n }\n wv.toList\n }\n\n // get multiply table from fmts\n def mt(z: Z): List[Z] = {\n fmts.getOrElse(z, Nil) match {\n case Nil =>\n val e = mwv(z)\n fmts = fmts + (z -> e)\n e\n case l => l\n }\n }\n\n // multiply weight vector\n def mwv(z: Z): List[Z] = {\n val wv = new ListBuffer[Z]\n wv += z\n wv += (z + z)\n var zs = \"11\"\n val upper = z.z.abs.toString\n while ((zs.length < upper.length)) {\n wv += (wv.toList.last + wv.toList.reverse.tail.head)\n\n zs = \"1\" + zs\n }\n wv.toList\n }\n }\n\n println(\"elapsed time: \" + elapsed {\n calcs foreach { case (op1, op, op2) => println(\"\" + op1 + \" \" + op + \" \" + op2 + \" = \"\n + {\n (ops(op)) (op1, op2) match {\n case None => None\n\n case Some(z) => z\n\n case z => z\n }\n }\n .ensuring { x =>\n (iops(op)) (z2i(op1), z2i(op2)) match {\n case None => None == x\n\n case Some(i) => i == z2i(x.asInstanceOf[Z])\n\n case i => i == z2i(x.asInstanceOf[Z])\n }\n })\n }\n } + \" sec\"\n )\n\n}\n", "language": "Scala" }, { "code": "namespace eval zeckendorf {\n # Want to use alternate symbols? Change these\n variable zero \"0\"\n variable one \"1\"\n\n # Base operations: increment and decrement\n proc zincr var {\n\tupvar 1 $var a\n\tnamespace upvar [namespace current] zero 0 one 1\n\tif {![regsub \"$0$\" $a $1$0 a]} {append a $1}\n\twhile {[regsub \"$0$1$1\" $a \"$1$0$0\" a]\n\t\t|| [regsub \"^$1$1\" $a \"$1$0$0\" a]} {}\n\tregsub \".$\" $a \"\" a\n\treturn $a\n }\n proc zdecr var {\n\tupvar 1 $var a\n\tnamespace upvar [namespace current] zero 0 one 1\n\tregsub \"^$0+(.+)$\" [subst [regsub \"${1}($0*)$\" $a \"$0\\[\n\t\tstring repeat {$1$0} \\[regsub -all .. {\\\\1} {} x]]\\[\n\t\tstring repeat {$1} \\[expr {\\$x ne {}}]]\"]\n\t ] {\\1} a\n\treturn $a\n }\n\n # Exported operations\n proc eq {a b} {\n\texpr {$a eq $b}\n }\n proc add {a b} {\n\tvariable zero\n\twhile {![eq $b $zero]} {\n\t zincr a\n\t zdecr b\n\t}\n\treturn $a\n }\n proc sub {a b} {\n\tvariable zero\n\twhile {![eq $b $zero]} {\n\t zdecr a\n\t zdecr b\n\t}\n\treturn $a\n }\n proc mul {a b} {\n\tvariable zero\n\tvariable one\n\tif {[eq $a $zero] || [eq $b $zero]} {return $zero}\n\tif {[eq $a $one]} {return $b}\n\tif {[eq $b $one]} {return $a}\n\tset c $a\n\twhile {![eq [zdecr b] $zero]} {\n\t set c [add $c $a]\n\t}\n\treturn $c\n }\n proc div {a b} {\n\tvariable zero\n\tvariable one\n\tif {[eq $b $zero]} {error \"div zero\"}\n\tif {[eq $a $zero] || [eq $b $one]} {return $a}\n\tset r $zero\n\twhile {![eq $a $zero]} {\n\t if {![eq $a [add [set a [sub $a $b]] $b]]} break\n\t zincr r\n\t}\n\treturn $r\n }\n # Note that there aren't any ordering operations in this version\n\n # Assemble into a coherent API\n namespace export \\[a-y\\]*\n namespace ensemble create\n}\n", "language": "Tcl" }, { "code": "puts [zeckendorf add \"10100\" \"1010\"]\nputs [zeckendorf sub \"10100\" \"1010\"]\nputs [zeckendorf mul \"10100\" \"1010\"]\nputs [zeckendorf div \"10100\" \"1010\"]\nputs [zeckendorf div [zeckendorf mul \"10100\" \"1010\"] \"1010\"]\n", "language": "Tcl" }, { "code": "import strings\nconst (\n dig = [\"00\", \"01\", \"10\"]\n dig1 = [\"\", \"1\", \"10\"]\n)\n\nstruct Zeckendorf {\nmut:\n d_val int\n d_len int\n}\n\nfn new_zeck(xx string) Zeckendorf {\n mut z := Zeckendorf{}\n mut x := xx\n if x == \"\" {\n x = \"0\"\n }\n mut q := 1\n mut i := x.len - 1\n z.d_len = i / 2\n for ; i >= 0; i-- {\n z.d_val += int(x[i]-'0'[0]) * q\n q *= 2\n }\n return z\n}\n\nfn (mut z Zeckendorf) a(ii int) {\n mut i:=ii\n for ; ; i++ {\n if z.d_len < i {\n z.d_len = i\n }\n j := (z.d_val >> u32(i*2)) & 3\n if j in [0, 1] {\n return\n } else if j==2 {\n if ((z.d_val >> (u32(i+1) * 2)) & 1) != 1 {\n return\n }\n z.d_val += 1 << u32(i*2+1)\n return\n } else {// 3\n z.d_val &= ~(3 << u32(i*2))\n z.b((i + 1) * 2)\n }\n }\n}\n\nfn (mut z Zeckendorf) b(p int) {\n mut pos := p\n if pos == 0 {\n z.inc()\n return\n }\n if ((z.d_val >> u32(pos)) & 1) == 0 {\n z.d_val += 1 << u32(pos)\n z.a(pos / 2)\n if pos > 1 {\n z.a(pos/2 - 1)\n }\n } else {\n z.d_val &= ~(1 << u32(pos))\n z.b(pos + 1)\n mut temp := 1\n if pos > 1 {\n temp = 2\n }\n z.b(pos - temp)\n }\n}\n\nfn (mut z Zeckendorf) c(p int) {\n mut pos := p\n if ((z.d_val >> u32(pos)) & 1) == 1 {\n z.d_val &= ~(1 << u32(pos))\n return\n }\n z.c(pos + 1)\n if pos > 0 {\n z.b(pos - 1)\n } else {\n z.inc()\n }\n}\n\nfn (mut z Zeckendorf) inc() {\n z.d_val++\n z.a(0)\n}\n\nfn (mut z1 Zeckendorf) plus_assign(z2 Zeckendorf) {\n for gn := 0; gn < (z2.d_len+1)*2; gn++ {\n if ((z2.d_val >> u32(gn)) & 1) == 1 {\n z1.b(gn)\n }\n }\n}\n\nfn (mut z1 Zeckendorf) minus_assign(z2 Zeckendorf) {\n for gn := 0; gn < (z2.d_len+1)*2; gn++ {\n if ((z2.d_val >> u32(gn)) & 1) == 1 {\n z1.c(gn)\n }\n }\n\n for z1.d_len > 0 && ((z1.d_val>>u32(z1.d_len*2))&3) == 0 {\n z1.d_len--\n }\n}\n\nfn (mut z1 Zeckendorf) times_assign(z2 Zeckendorf) {\n mut na := z2.copy()\n mut nb := z2.copy()\n mut nr := Zeckendorf{}\n for i := 0; i <= (z1.d_len+1)*2; i++ {\n if ((z1.d_val >> u32(i)) & 1) > 0 {\n nr.plus_assign(nb)\n }\n nt := nb.copy()\n nb.plus_assign(na)\n na = nt.copy()\n }\n z1.d_val = nr.d_val\n z1.d_len = nr.d_len\n}\n\nfn (z Zeckendorf) copy() Zeckendorf {\n return Zeckendorf{z.d_val, z.d_len}\n}\n\nfn (z1 Zeckendorf) compare(z2 Zeckendorf) int {\n if z1.d_val < z2.d_val {\n return -1\n } else if z1.d_val > z2.d_val {\n return 1\n } else {\n return 0\n }\n}\n\nfn (z Zeckendorf) str() string {\n if z.d_val == 0 {\n return \"0\"\n }\n mut sb := strings.new_builder(128)\n sb.write_string(dig1[(z.d_val>>u32(z.d_len*2))&3])\n for i := z.d_len - 1; i >= 0; i-- {\n sb.write_string(dig[(z.d_val>>u32(i*2))&3])\n }\n return sb.str()\n}\n\nfn main() {\n println(\"Addition:\")\n mut g := new_zeck(\"10\")\n g.plus_assign(new_zeck(\"10\"))\n println(g)\n g.plus_assign(new_zeck(\"10\"))\n println(g)\n g.plus_assign(new_zeck(\"1001\"))\n println(g)\n g.plus_assign(new_zeck(\"1000\"))\n println(g)\n g.plus_assign(new_zeck(\"10101\"))\n println(g)\n\n println(\"\\nSubtraction:\")\n g = new_zeck(\"1000\")\n g.minus_assign(new_zeck(\"101\"))\n println(g)\n g = new_zeck(\"10101010\")\n g.minus_assign(new_zeck(\"1010101\"))\n println(g)\n\n println(\"\\nMultiplication:\")\n g = new_zeck(\"1001\")\n g.times_assign(new_zeck(\"101\"))\n println(g)\n g = new_zeck(\"101010\")\n g.plus_assign(new_zeck(\"101\"))\n println(g)\n}\n", "language": "V-(Vlang)" }, { "code": "Imports System.Text\n\nModule Module1\n\n Class Zeckendorf\n Implements IComparable(Of Zeckendorf)\n\n Private Shared ReadOnly dig As String() = {\"00\", \"01\", \"10\"}\n Private Shared ReadOnly dig1 As String() = {\"\", \"1\", \"10\"}\n\n Private dVal As Integer = 0\n Private dLen As Integer = 0\n\n Public Sub New(Optional x As String = \"0\")\n Dim q = 1\n Dim i = x.Length - 1\n dLen = i \\ 2\n\n Dim z = Asc(\"0\")\n While i >= 0\n Dim a = Asc(x(i))\n dVal += (a - z) * q\n q *= 2\n i -= 1\n End While\n End Sub\n\n Private Sub A(n As Integer)\n Dim i = n\n While True\n If dLen < i Then\n dLen = i\n End If\n Dim j = (dVal >> (i * 2)) And 3\n If j = 0 OrElse j = 1 Then\n Return\n ElseIf j = 2 Then\n If ((dVal >> ((i + 1) * 2)) And 1) <> 1 Then\n Return\n End If\n dVal += 1 << (i * 2 + 1)\n Return\n ElseIf j = 3 Then\n Dim temp = 3 << (i * 2)\n temp = temp Xor -1\n dVal = dVal And temp\n B((i + 1) * 2)\n End If\n i += 1\n End While\n End Sub\n\n Private Sub B(pos As Integer)\n If pos = 0 Then\n Inc()\n Return\n End If\n If ((dVal >> pos) And 1) = 0 Then\n dVal += 1 << pos\n A(pos \\ 2)\n If pos > 1 Then\n A(pos \\ 2 - 1)\n End If\n Else\n Dim temp = 1 << pos\n temp = temp Xor -1\n dVal = dVal And temp\n B(pos + 1)\n B(pos - If(pos > 1, 2, 1))\n End If\n End Sub\n\n Private Sub C(pos As Integer)\n If ((dVal >> pos) And 1) = 1 Then\n Dim temp = 1 << pos\n temp = temp Xor -1\n dVal = dVal And temp\n Return\n End If\n C(pos + 1)\n If pos > 0 Then\n B(pos - 1)\n Else\n Inc()\n End If\n End Sub\n\n Public Function Inc() As Zeckendorf\n dVal += 1\n A(0)\n Return Me\n End Function\n\n Public Function Copy() As Zeckendorf\n Dim z As New Zeckendorf With {\n .dVal = dVal,\n .dLen = dLen\n }\n Return z\n End Function\n\n Public Sub PlusAssign(other As Zeckendorf)\n Dim gn = 0\n While gn < (other.dLen + 1) * 2\n If ((other.dVal >> gn) And 1) = 1 Then\n B(gn)\n End If\n gn += 1\n End While\n End Sub\n\n Public Sub MinusAssign(other As Zeckendorf)\n Dim gn = 0\n While gn < (other.dLen + 1) * 2\n If ((other.dVal >> gn) And 1) = 1 Then\n C(gn)\n End If\n gn += 1\n End While\n While (((dVal >> dLen * 2) And 3) = 0) OrElse dLen = 0\n dLen -= 1\n End While\n End Sub\n\n Public Sub TimesAssign(other As Zeckendorf)\n Dim na = other.Copy\n Dim nb = other.Copy\n Dim nt As Zeckendorf\n Dim nr As New Zeckendorf\n Dim i = 0\n While i < (dLen + 1) * 2\n If ((dVal >> i) And 1) > 0 Then\n nr.PlusAssign(nb)\n End If\n nt = nb.Copy\n nb.PlusAssign(na)\n na = nt.Copy\n i += 1\n End While\n dVal = nr.dVal\n dLen = nr.dLen\n End Sub\n\n Public Function CompareTo(other As Zeckendorf) As Integer Implements IComparable(Of Zeckendorf).CompareTo\n Return dVal.CompareTo(other.dVal)\n End Function\n\n Public Overrides Function ToString() As String\n If dVal = 0 Then\n Return \"0\"\n End If\n\n Dim idx = (dVal >> (dLen * 2)) And 3\n Dim sb As New StringBuilder(dig1(idx))\n Dim i = dLen - 1\n While i >= 0\n idx = (dVal >> (i * 2)) And 3\n sb.Append(dig(idx))\n i -= 1\n End While\n Return sb.ToString\n End Function\n End Class\n\n Sub Main()\n Console.WriteLine(\"Addition:\")\n Dim g As New Zeckendorf(\"10\")\n g.PlusAssign(New Zeckendorf(\"10\"))\n Console.WriteLine(g)\n g.PlusAssign(New Zeckendorf(\"10\"))\n Console.WriteLine(g)\n g.PlusAssign(New Zeckendorf(\"1001\"))\n Console.WriteLine(g)\n g.PlusAssign(New Zeckendorf(\"1000\"))\n Console.WriteLine(g)\n g.PlusAssign(New Zeckendorf(\"10101\"))\n Console.WriteLine(g)\n Console.WriteLine()\n\n Console.WriteLine(\"Subtraction:\")\n g = New Zeckendorf(\"1000\")\n g.MinusAssign(New Zeckendorf(\"101\"))\n Console.WriteLine(g)\n g = New Zeckendorf(\"10101010\")\n g.MinusAssign(New Zeckendorf(\"1010101\"))\n Console.WriteLine(g)\n Console.WriteLine()\n\n Console.WriteLine(\"Multiplication:\")\n g = New Zeckendorf(\"1001\")\n g.TimesAssign(New Zeckendorf(\"101\"))\n Console.WriteLine(g)\n g = New Zeckendorf(\"101010\")\n g.PlusAssign(New Zeckendorf(\"101\"))\n Console.WriteLine(g)\n End Sub\n\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./trait\" for Comparable\n\nclass Zeckendorf is Comparable {\n static dig { [\"00\", \"01\", \"10\"] }\n static dig1 { [\"\", \"1\", \"10\"] }\n\n construct new(x) {\n var q = 1\n var i = x.count - 1\n _dLen = (i / 2).floor\n _dVal = 0\n while (i >= 0) {\n _dVal = _dVal + (x[i].bytes[0] - 48) * q\n q = q * 2\n i = i - 1\n }\n }\n\n dLen { _dLen }\n dVal { _dVal }\n\n dLen=(v) { _dLen = v }\n dVal=(v) { _dVal = v }\n\n a(n) {\n var i = n\n while (true) {\n if (_dLen < i) _dLen = i\n var j = (_dVal >> (i * 2)) & 3\n if (j == 0 || j == 1) return\n if (j == 2) {\n if (((_dVal >> ((i + 1) * 2)) & 1) != 1) return\n _dVal = _dVal + (1 << (i * 2 + 1))\n return\n }\n if (j == 3) {\n _dVal = _dVal & ~(3 << (i * 2))\n b((i + 1) * 2)\n }\n i = i + 1\n }\n }\n\n b(pos) {\n if (pos == 0) {\n var thiz = this\n thiz.inc\n return\n }\n if (((_dVal >> pos) & 1) == 0) {\n _dVal = _dVal + (1 << pos)\n a((pos / 2).floor)\n if (pos > 1) a((pos / 2).floor - 1)\n } else {\n _dVal = _dVal & ~(1 << pos)\n b(pos + 1)\n b(pos - ((pos > 1) ? 2 : 1))\n }\n }\n\n c(pos) {\n if (((_dVal >> pos) & 1) == 1) {\n _dVal = _dVal & ~(1 << pos)\n return\n }\n c(pos + 1)\n if (pos > 0) {\n b(pos - 1)\n } else {\n var thiz = this\n thiz.inc\n }\n }\n\n inc {\n _dVal = _dVal + 1\n a(0)\n return this\n }\n\n plusAssign(other) {\n for (gn in 0...(other.dLen + 1) * 2) {\n if (((other.dVal >> gn) & 1) == 1) b(gn)\n }\n }\n\n minusAssign(other) {\n for (gn in 0...(other.dLen + 1) * 2) {\n if (((other.dVal >> gn) & 1) == 1) c(gn)\n }\n while ((((_dVal >> _dLen * 2) & 3) == 0) || (_dLen == 0)) _dLen = _dLen - 1\n }\n\n timesAssign(other) {\n var na = other.copy()\n var nb = other.copy()\n var nr = Zeckendorf.new(\"0\")\n for (i in 0..(_dLen + 1) * 2) {\n if (((_dVal >> i) & 1) > 0) nr.plusAssign(nb)\n var nt = nb.copy()\n nb.plusAssign(na)\n na = nt.copy()\n }\n _dVal = nr.dVal\n _dLen = nr.dLen\n }\n\n compare(other) { (_dVal - other.dVal).sign }\n\n toString {\n if (_dVal == 0) return \"0\"\n var sb = Zeckendorf.dig1[(_dVal >> (_dLen * 2)) & 3]\n if (_dLen > 0) {\n for (i in _dLen - 1..0) {\n sb = sb + Zeckendorf.dig[(_dVal >> (i * 2)) & 3]\n }\n }\n return sb\n }\n\n copy() {\n var z = Zeckendorf.new(\"0\")\n z.dVal = _dVal\n z.dLen = _dLen\n return z\n }\n}\n\nvar Z = Zeckendorf // type alias\nSystem.print(\"Addition:\")\nvar g = Z.new(\"10\")\ng.plusAssign(Z.new(\"10\"))\nSystem.print(g)\ng.plusAssign(Z.new(\"10\"))\nSystem.print(g)\ng.plusAssign(Z.new(\"1001\"))\nSystem.print(g)\ng.plusAssign(Z.new(\"1000\"))\nSystem.print(g)\ng.plusAssign(Z.new(\"10101\"))\nSystem.print(g)\nSystem.print(\"\\nSubtraction:\")\ng = Z.new(\"1000\")\ng.minusAssign(Z.new(\"101\"))\nSystem.print(g)\ng = Z.new(\"10101010\")\ng.minusAssign(Z.new(\"1010101\"))\nSystem.print(g)\nSystem.print(\"\\nMultiplication:\")\ng = Z.new(\"1001\")\ng.timesAssign(Z.new(\"101\"))\nSystem.print(g)\ng = Z.new(\"101010\")\ng.plusAssign(Z.new(\"101\"))\nSystem.print(g)\n", "language": "Wren" } ]
Zeckendorf-arithmetic
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Zeckendorf_number_representation\n", "language": "00-META" }, { "code": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* &nbsp; [http://oeis.org/A014417 OEIS A014417] &nbsp; for the the sequence of required results.\n* &nbsp; [http://www.youtube.com/watch?v=kQZmZRE0cQY&list=UUoxcjq-8xIDTYp3uz647V5A&index=3&feature=plcp Brown's Criterion - Numberphile]\n\n\n;Related task:\n* &nbsp; [[Fibonacci sequence]]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "V n = 20\nF z(=n)\n I n == 0\n R [0]\n V fib = [2, 1]\n L fib[0] < n\n fib = [sum(fib[0.<2])] [+] fib\n [Int] dig\n L(f) fib\n I f <= n\n dig [+]= 1\n n -= f\n E\n dig [+]= 0\n R I dig[0] {dig} E dig[1..]\n\nL(i) 0..n\n print(‘#3: #8’.format(i, z(i).map(d -> String(d)).join(‘’)))\n", "language": "11l" }, { "code": "* Zeckendorf number representation 04/04/2017\nZECKEN CSECT\n USING ZECKEN,R13 base register\n B 72(R15) skip savearea\n DC 17F'0' savearea\n STM R14,R12,12(R13) save previous context\n ST R13,4(R15) link backward\n ST R15,8(R13) link forward\n LR R13,R15 set addressability\n LA R6,0 i=0\n DO WHILE=(C,R6,LE,=A(20)) do i=0 to 20\n MVC PG,=CL80'xx : ' init buffer\n LA R10,PG pgi=0\n XDECO R6,XDEC i\n MVC 0(2,R10),XDEC+10 output i\n LA R10,5(R10) pgi+=5\n MVC FIB,=A(1) fib(1)=1\n MVC FIB+4,=A(2) fib(2)=2\n LA R7,2 j=2\n LR R1,R7 j\n SLA R1,2 @fib(j)\n DO WHILE=(C,R6,GT,FIB-4(R1) do while fib(j)<i\n LA R7,1(R7) j++\n LR R1,R7 j\n SLA R1,2 ~\n L R2,FIB-8(R1) fib(j-1)\n A R2,FIB-12(R1) fib(j-2)\n ST R2,FIB-4(R1) fib(j)=fib(j-1)+fib(j-2)\n LR R1,R7 j\n SLA R1,2 @fib(j)\n ENDDO , enddo j\n LR R8,R6 k=i\n MVI BB,X'00' bb=false\n DO WHILE=(C,R7,GE,=A(1)) do j=j to 1 by -1\n LR R1,R7 j\n SLA R1,2 ~\n IF C,R8,GE,FIB-4(R1) THEN if fib(j)<=k then\n MVI BB,X'01' bb=true\n MVC 0(1,R10),=C'1' output '1'\n LA R10,1(R10) pgi+=1\n LR R1,R7 j\n SLA R1,2 ~\n S R8,FIB-4(R1) k=k-fib(j)\n ELSE , else\n IF CLI,BB,EQ,X'01' THEN if bb then\n MVC 0(1,R10),=C'0' output '0'\n LA R10,1(R10) pgi+=1\n ENDIF , endif\n ENDIF , endif\n BCTR R7,0 j--\n ENDDO , enddo j\n IF CLI,BB,NE,X'01' THEN if not bb then\n MVC 0(1,R10),=C'0' output '0'\n ENDIF , endif\n XPRNT PG,L'PG print buffer\n LA R6,1(R6) i++\n ENDDO , enddo i\n L R13,4(0,R13) restore previous savearea pointer\n LM R14,R12,12(R13) restore previous context\n XR R15,R15 rc=0\n BR R14 exit\nFIB DS 32F Fibonnacci table\nBB DS X flag\nPG DS CL80 buffer\nXDEC DS CL12 temp\n YREGS\n END ZECKEN\n", "language": "360-Assembly" }, { "code": "PROC Encode(INT x CHAR ARRAY s)\n INT ARRAY fib(22)=\n [1 2 3 5 8 13 21 34 55 89 144 233 377 610\n 987 1597 2584 4181 6765 10946 17711 28657]\n INT i\n BYTE append\n\n IF x=0 THEN\n s(0)=1\n s(1)='0\n RETURN\n FI\n\n i=21 append=0\n s(0)=0\n WHILE i>=0\n DO\n IF x>=fib(i) THEN\n x==-fib(i)\n s(0)==+1\n s(s(0))='1\n append=1\n ELSEIF append THEN\n s(0)==+1\n s(s(0))='0\n FI\n i==-1\n OD\nRETURN\n\nPROC Main()\n INT i\n CHAR ARRAY s(10)\n\n FOR i=0 TO 20\n DO\n Encode(i,s)\n PrintF(\"%I -> %S%E\",i,s)\n OD\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO, Ada.Strings.Unbounded;\n\nprocedure Print_Zeck is\n\n function Zeck_Increment(Z: String) return String is\n begin\n if Z=\"\" then\n\t return \"1\";\n elsif Z(Z'Last) = '1' then\n\t return Zeck_Increment(Z(Z'First .. Z'Last-1)) & '0';\n elsif Z(Z'Last-1) = '0' then\n\t return Z(Z'First .. Z'Last-1) & '1';\n else -- Z has at least two digits and ends with \"10\"\n\t return Zeck_Increment(Z(Z'First .. Z'Last-2)) & \"00\";\n end if;\n end Zeck_Increment;\n\n use Ada.Strings.Unbounded;\n Current: Unbounded_String := Null_Unbounded_String;\n\nbegin\n for I in 1 .. 20 loop\n Current := To_Unbounded_String(Zeck_Increment(To_String(Current)));\n Ada.Text_IO.Put(To_String(Current) & \" \");\n end loop;\nend Print_Zeck;\n", "language": "Ada" }, { "code": "# print some Zeckendorf number representations #\n\n# We handle 32-bit numbers, the maximum fibonacci number that can fit in a #\n# 32 bit number is F(45) #\n\n# build a table of 32-bit fibonacci numbers #\n[ 45 ]INT fibonacci;\nfibonacci[ 1 ] := 1;\nfibonacci[ 2 ] := 2;\nFOR i FROM 3 TO UPB fibonacci DO fibonacci[ i ] := fibonacci[ i - 1 ] + fibonacci[ i - 2 ] OD;\n\n# returns the Zeckendorf representation of n or \"?\" if one cannot be found #\nPROC to zeckendorf = ( INT n )STRING:\n IF n = 0 THEN\n \"0\"\n ELSE\n STRING result := \"\";\n INT f pos := UPB fibonacci;\n INT rest := ABS n;\n # find the first non-zero Zeckendorf digit #\n WHILE f pos > LWB fibonacci AND rest < fibonacci[ f pos ] DO\n f pos -:= 1\n OD;\n # if we found a digit, build the representation #\n IF f pos >= LWB fibonacci THEN\n # have a digit #\n BOOL skip digit := FALSE;\n WHILE f pos >= LWB fibonacci DO\n IF rest <= 0 THEN\n result +:= \"0\"\n ELIF skip digit THEN\n # we used the previous digit #\n skip digit := FALSE;\n result +:= \"0\"\n ELIF rest < fibonacci[ f pos ] THEN\n # can't use the digit at f pos #\n skip digit := FALSE;\n result +:= \"0\"\n ELSE\n # can use this digit #\n skip digit := TRUE;\n result +:= \"1\";\n rest -:= fibonacci[ f pos ]\n FI;\n f pos -:= 1\n OD\n FI;\n IF rest = 0 THEN\n # found a representation #\n result\n ELSE\n # can't find a representation #\n \"?\"\n FI\n FI; # to zeckendorf #\n\nFOR i FROM 0 TO 20 DO\n print( ( whole( i, -3 ), \" \", to zeckendorf( i ), newline ) )\nOD\n", "language": "ALGOL-68" }, { "code": "--------------------- ZECKENDORF NUMBERS -------------------\n\n-- zeckendorf :: Int -> String\non zeckendorf(n)\n script f\n on |λ|(n, x)\n if n < x then\n [n, 0]\n else\n [n - x, 1]\n end if\n end |λ|\n end script\n\n if n = 0 then\n {0} as string\n else\n item 2 of mapAccumL(f, n, |reverse|(just of tailMay(fibUntil(n)))) as string\n end if\nend zeckendorf\n\n-- fibUntil :: Int -> [Int]\non fibUntil(n)\n set xs to {}\n set limit to n\n\n script atLimit\n property ceiling : limit\n on |λ|(x)\n (item 2 of x) > (atLimit's ceiling)\n end |λ|\n end script\n\n script nextPair\n property series : xs\n on |λ|([a, b])\n set nextPair's series to nextPair's series & b\n [b, a + b]\n end |λ|\n end script\n\n |until|(atLimit, nextPair, {0, 1})\n return nextPair's series\nend fibUntil\n\n---------------------------- TEST --------------------------\non run\n\n intercalate(linefeed, ¬\n map(zeckendorf, enumFromTo(0, 20)))\n\nend run\n\n--------------------- GENERIC FUNCTIONS --------------------\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if m > n then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- foldl :: (a -> b -> a) -> a -> [b] -> a\non foldl(f, startValue, xs)\n tell mReturn(f)\n set v to startValue\n set lng to length of xs\n repeat with i from 1 to lng\n set v to |λ|(v, item i of xs, i, xs)\n end repeat\n return v\n end tell\nend foldl\n\n-- 'The mapAccumL function behaves like a combination of map and foldl;\n-- it applies a function to each element of a list, passing an\n-- accumulating parameter from left to right, and returning a final\n-- value of this accumulator together with the new list.' (see Hoogle)\n\n-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\non mapAccumL(f, acc, xs)\n script\n on |λ|(a, x)\n tell mReturn(f) to set pair to |λ|(item 1 of a, x)\n [item 1 of pair, (item 2 of a) & item 2 of pair]\n end |λ|\n end script\n\n foldl(result, [acc, []], xs)\nend mapAccumL\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- intercalate :: Text -> [Text] -> Text\non intercalate(strText, lstText)\n set {dlm, my text item delimiters} to {my text item delimiters, strText}\n set strJoined to lstText as text\n set my text item delimiters to dlm\n return strJoined\nend intercalate\n\n-- reverse :: [a] -> [a]\non |reverse|(xs)\n if class of xs is text then\n (reverse of characters of xs) as text\n else\n reverse of xs\n end if\nend |reverse|\n\n-- tailMay :: [a] -> Maybe [a]\non tailMay(xs)\n if length of xs > 1 then\n {nothing:false, just:items 2 thru -1 of xs}\n else\n {nothing:true}\n end if\nend tailMay\n\n-- until :: (a -> Bool) -> (a -> a) -> a -> a\non |until|(p, f, x)\n set mp to mReturn(p)\n set v to x\n\n tell mReturn(f)\n repeat until mp's |λ|(v)\n set v to |λ|(v)\n end repeat\n end tell\n return v\nend |until|\n", "language": "AppleScript" }, { "code": "Z: function [x][\n if x=0 -> return \"0\"\n fib: new [2 1]\n n: new x\n while -> n > first fib\n -> insert 'fib 0 fib\\0 + fib\\1\n\n result: new \"\"\n loop fib 'f [\n if? f =< n [\n 'result ++ \"1\"\n 'n - f\n ]\n else -> 'result ++ \"0\"\n ]\n if result\\0 = `0` ->\n result: slice result 1 (size result)-1\n return result\n]\n\nloop 0..20 'i ->\n print [pad to :string i 3 pad Z i 8]\n", "language": "Arturo" }, { "code": "Fib := NStepSequence(1, 2, 2, 20)\nLoop, 21 {\n\ti := A_Index - 1\n\t, Out .= i \":`t\", n := \"\"\n\tLoop, % Fib.MaxIndex() {\n\t\tx := Fib.MaxIndex() + 1 - A_Index\n\t\tif (Fib[x] <= i)\n\t\t\tn .= 1, i -= Fib[x]\n\t\telse\n\t\t\tn .= 0\n\t}\n\tOut .= (n ? LTrim(n, \"0\") : 0) \"`n\"\n}\nMsgBox, % Out\n\nNStepSequence(v1, v2, n, k) {\n a := [v1, v2]\n\tLoop, % k - 2 {\n\t\ta[j := A_Index + 2] := 0\n\t\tLoop, % j < n + 2 ? j - 1 : n\n\t\t\ta[j] += a[j - A_Index]\n\t}\n\treturn, a\n}\n", "language": "AutoHotkey" }, { "code": "For $i = 0 To 20\n\tConsoleWrite($i &\": \"& Zeckendorf($i)&@CRLF)\nNext\n\nFunc Zeckendorf($int, $Fibarray = \"\")\n\tIf Not IsArray($Fibarray) Then $Fibarray = Fibonacci($int)\n\tLocal $ret = \"\"\n\tFor $i = UBound($Fibarray) - 1 To 1 Step -1\n\t\tIf $Fibarray[$i] > $int And $ret = \"\" Then ContinueLoop ; dont use Leading Zeros\n\t\tIf $Fibarray[$i] > $int Then\n\t\t\t$ret &= \"0\"\n\t\tElse\n\t\t\tIf StringRight($ret, 1) <> \"1\" Then\n\t\t\t\t$ret &= \"1\"\n\t\t\t\t$int -= $Fibarray[$i]\n\t\t\tElse\n\t\t\t\t$ret &= \"0\"\n\t\t\tEndIf\n\t\tEndIf\n\tNext\n\tIf $ret = \"\" Then $ret = \"0\"\n\tReturn $ret\nEndFunc ;==>Zeckendorf\n\nFunc Fibonacci($max)\n\t$AList = ObjCreate(\"System.Collections.ArrayList\")\n\t$AList.add(\"0\")\n\t$current = 0\n\tWhile True\n\t\tIf $current > 1 Then\n\t\t\t$count = $AList.Count\n\t\t\t$current = $AList.Item($count - 1)\n\t\t\t$current = $current + $AList.Item($count - 2)\n\t\tElse\n\t\t\t$current += 1\n\t\tEndIf\n\t\t$AList.add($current)\n\t\tIf $current > $max Then ExitLoop\n\tWEnd\n\t$Array = $AList.ToArray\n\tReturn $Array\nEndFunc ;==>Fibonacci\n", "language": "AutoIt" }, { "code": " FOR n% = 0 TO 20\n PRINT n% RIGHT$(\" \" + FNzeckendorf(n%), 8)\n NEXT\n PRINT '\"Checking numbers up to 10000...\"\n FOR n% = 21 TO 10000\n IF INSTR(FNzeckendorf(n%), \"11\") STOP\n NEXT\n PRINT \"No Zeckendorf numbers contain consecutive 1's\"\n END\n\n DEF FNzeckendorf(n%)\n LOCAL i%, o$, fib%() : DIM fib%(45)\n fib%(0) = 1 : fib%(1) = 1 : i% = 1\n REPEAT\n i% += 1\n fib%(i%) = fib%(i%-1) + fib%(i%-2)\n UNTIL fib%(i%) > n%\n REPEAT\n i% -= 1\n IF n% >= fib%(i%) THEN\n o$ += \"1\"\n n% -= fib%(i%)\n ELSE\n o$ += \"0\"\n ENDIF\n UNTIL i% = 1\n = o$\n", "language": "BBC-BASIC" }, { "code": "obase = 2\nf[0] = 1\nf[t = 1] = 2\n\ndefine z(n) {\n auto p, r\n\n for (p = t; p >= 0; --p) {\n r += r\n if (n >= f[p]) {\n r += 1\n n -= f[p]\n }\n }\n return(r)\n}\n\nfor (x = 0; x != 21; ++x) {\n if (x > f[t]) {\n t += 1\n f[t] = f[t - 2] + f[t - 1]\n }\n z(x)\n}\n", "language": "Bc" }, { "code": "45*83p0>:::.0`\"0\"v\nv53210p 39+!:,,9+<\n>858+37 *66g\"7Y\":v\n>3g`#@_^ v\\g39$<\n^8:+1,+5_5<>-:0\\`|\nv:-\\g39_^#:<*:p39<\n>0\\`:!\"0\"+#^ ,#$_^\n", "language": "Befunge" }, { "code": "#include <stdio.h>\n\ntypedef unsigned long long u64;\n\n#define FIB_INVALID (~(u64)0)\n\nu64 fib[] = {\n\t1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,\n\t2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418,\n\t317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,\n\t14930352, 24157817, 39088169, 63245986, 102334155, 165580141,\n\t267914296, 433494437, 701408733, 1134903170, 1836311903,\n\t2971215073ULL, 4807526976ULL, 7778742049ULL, 12586269025ULL,\n\t20365011074ULL, 32951280099ULL, 53316291173ULL, 86267571272ULL,\n\t139583862445ULL, 225851433717ULL, 365435296162ULL, 591286729879ULL,\n\t956722026041ULL, 1548008755920ULL, 2504730781961ULL, 4052739537881ULL,\n\t6557470319842ULL, 10610209857723ULL, 17167680177565ULL,\n\n\t27777890035288ULL // this 65-th one is for range check\n};\n\nu64 fibbinary(u64 n)\n{\n\tif (n >= fib[64]) return FIB_INVALID;\n\n\tu64 ret = 0;\n\tint i;\n\tfor (i = 64; i--; )\n\t\tif (n >= fib[i]) {\n\t\t\tret |= 1ULL << i;\n\t\t\tn -= fib[i];\n\t\t}\n\n\treturn ret;\n}\n\nvoid bprint(u64 n, int width)\n{\n\tif (width > 64) width = 64;\n\n\tu64 b;\n\tfor (b = 1ULL << (width - 1); b; b >>= 1)\n\t\tputchar(b == 1 && !n\n\t\t\t? '0'\n\t\t\t: b > n\t? ' '\n\t\t\t\t: b & n ? '1' : '0');\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint i;\n\n\tfor (i = 0; i <= 20; i++)\n\t\tprintf(\"%2d:\", i), bprint(fibbinary(i), 8);\n\n\treturn 0;\n}\n", "language": "C" }, { "code": "// For a class N which implements Zeckendorf numbers:\n// I define an increment operation ++()\n// I define a comparison operation <=(other N)\n// Nigel Galloway October 22nd., 2012\n#include <iostream>\nclass N {\nprivate:\n int dVal = 0, dLen;\npublic:\n N(char const* x = \"0\"){\n int i = 0, q = 1;\n for (; x[i] > 0; i++);\n for (dLen = --i/2; i >= 0; i--) {\n dVal+=(x[i]-48)*q;\n q*=2;\n }}\n const N& operator++() {\n for (int i = 0;;i++) {\n if (dLen < i) dLen = i;\n switch ((dVal >> (i*2)) & 3) {\n case 0: dVal += (1 << (i*2)); return *this;\n case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this;\n case 2: dVal &= ~(3 << (i*2));\n }}}\n const bool operator<=(const N& other) const {return dVal <= other.dVal;}\n friend std::ostream& operator<<(std::ostream&, const N&);\n};\nN operator \"\" N(char const* x) {return N(x);}\nstd::ostream &operator<<(std::ostream &os, const N &G) {\n const static std::string dig[] {\"00\",\"01\",\"10\"}, dig1[] {\"\",\"1\",\"10\"};\n if (G.dVal == 0) return os << \"0\";\n os << dig1[(G.dVal >> (G.dLen*2)) & 3];\n for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];\n return os;\n}\n", "language": "C++" }, { "code": "int main(void) {\n//for (N G; G <= 101010N; ++G) std::cout << G << std::endl; // from zero to 101010M\n for (N G(101N); G <= 101010N; ++G) std::cout << G << std::endl; // from 101N to 101010N\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Zeckendorf\n{\n class Program\n {\n private static uint Fibonacci(uint n)\n {\n if (n < 2)\n {\n return n;\n }\n else\n {\n return Fibonacci(n - 1) + Fibonacci(n - 2);\n }\n }\n\n private static string Zeckendorf(uint num)\n {\n IList<uint> fibonacciNumbers = new List<uint>();\n uint fibPosition = 2;\n\n uint currentFibonaciNum = Fibonacci(fibPosition);\n\n do\n {\n fibonacciNumbers.Add(currentFibonaciNum);\n currentFibonaciNum = Fibonacci(++fibPosition);\n } while (currentFibonaciNum <= num);\n\n uint temp = num;\n StringBuilder output = new StringBuilder();\n\n foreach (uint item in fibonacciNumbers.Reverse())\n {\n if (item <= temp)\n {\n output.Append(\"1\");\n temp -= item;\n }\n else\n {\n output.Append(\"0\");\n }\n }\n\n return output.ToString();\n }\n\n static void Main(string[] args)\n {\n for (uint i = 1; i <= 20; i++)\n {\n string zeckendorfRepresentation = Zeckendorf(i);\n Console.WriteLine(string.Format(\"{0} : {1}\", i, zeckendorfRepresentation));\n }\n\n Console.ReadKey();\n }\n }\n}\n", "language": "C-sharp" }, { "code": "(def fibs (lazy-cat [1 1] (map + fibs (rest fibs))))\n\n(defn z [n]\n (if (zero? n)\n \"0\"\n (let [ps (->> fibs (take-while #(<= % n)) rest reverse)\n fz (fn [[s n] p]\n (if (>= n p)\n [(conj s 1) (- n p)]\n [(conj s 0) n]))]\n (->> ps (reduce fz [[] n]) first (apply str)))))\n\n(doseq [n (range 0 21)] (println n (z n)))\n", "language": "Clojure" }, { "code": "% Get list of distinct Fibonacci numbers up to N\nfibonacci = proc (n: int) returns (array[int])\n list: array[int] := array[int]$[]\n a: int := 1\n b: int := 2\n while a <= n do\n array[int]$addh(list,a)\n a, b := b, a+b\n end\n return(list)\nend fibonacci\n\n% Find the Zeckendorf representation of N\nzeckendorf = proc (n: int) returns (string) signals (negative)\n if n<0 then signal negative end\n if n=0 then return(\"0\") end\n\n fibs: array[int] := fibonacci(n)\n result: array[char] := array[char]$[]\n\n while ~array[int]$empty(fibs) do\n fib: int := array[int]$remh(fibs)\n if fib <= n then\n n := n - fib\n array[char]$addh(result,'1')\n else\n array[char]$addh(result,'0')\n end\n end\n return(string$ac2s(result))\nend zeckendorf\n\n% Print the Zeckendorf representations of 0 to 20\nstart_up = proc ()\n po: stream := stream$primary_output()\n for i: int in int$from_to(0,20) do\n stream$putright(po, int$unparse(i), 2)\n stream$puts(po, \": \")\n stream$putl(po, zeckendorf(i))\n end\nend start_up\n", "language": "CLU" }, { "code": "(defun zeckendorf (n)\n \"returns zeckendorf integer of n (see OEIS A003714)\"\n (let ((fib '(2 1)))\n\t;; extend Fibonacci sequence long enough\n\t(loop while (<= (car fib) n) do\n\t (push (+ (car fib) (cadr fib)) fib))\n\t(loop with r = 0 for f in fib do\n\t (setf r (* 2 r))\n\t (when (>= n f) (setf n (- n f))\n\t\t\t (incf r))\n\t finally (return r))))\n\n;;; task requirement\n(loop for i from 0 to 20 do\n (format t \"~2D: ~2R~%\" i (zeckendorf i)))\n", "language": "Common-Lisp" }, { "code": ";; Print Zeckendorf numbers upto 20.\n;; I have implemented this as a state machine.\n;; Nigel Galloway - October 13th., 2012\n;;\n(let ((fibz '(13 8 5 3 2 1))) (dotimes (G 21) (progn (format t \"~S is \" G)\n (let ((z 0) (ng G)) (dolist (N fibz)\n (if (> z 1) (progn (setq z 1) (format t \"~S\" 0))\n (if (>= ng N) (progn (setq z 2) (setq ng (- ng N)) (format t \"~S\" 1))\n (if (= z 1) (format t \"~S\" 0)))))\n (if (= z 0) (format t \"~S~%\" 0) (format t \"~%\"))))))\n", "language": "Common-Lisp" }, { "code": "include \"cowgol.coh\";\n\nsub zeckendorf(n: uint32, buf: [uint8]): (r: [uint8]) is\n var fibs: uint32[] := {\n 0,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,\n 2584,4181,6765,10946,17711,28657,46368,75025,121393,\n 196418,317811,514229,832040,1346269,2178309,3524578,\n 5702887,9227465,14930352,24157817,39088169,63245986,\n 102334155,165580141,267914296,433494437,701408733,\n 1134903170,1836311903,2971215073\n };\n r := buf;\n if n == 0 then\n [r] := '0';\n [@next r] := 0;\n return;\n end if;\n\n var fib: [uint32] := &fibs[1];\n while n >= [fib] loop\n fib := @next fib;\n end loop;\n fib := @prev fib;\n\n while [fib] != 0 loop\n if [fib] <= n then\n n := n - [fib];\n [buf] := '1';\n else\n [buf] := '0';\n end if;\n fib := @prev fib;\n buf := @next buf;\n end loop;\n [buf] := 0;\nend sub;\n\nvar i: uint32 := 0;\nwhile i <= 20 loop\n print_i32(i);\n print(\": \");\n print(zeckendorf(i, LOMEM));\n print_nl();\n i := i + 1;\nend loop;\n", "language": "Cowgol" }, { "code": "def zeckendorf(n)\n return 0 if n.zero?\n fib = [1, 2]\n while fib[-1] < n; fib << fib[-2] + fib[-1] end\n digit = \"\"\n fib.reverse_each do |f|\n if f <= n\n digit, n = digit + \"1\", n - f\n else\n digit += \"0\"\n end\n end\n digit.to_i\nend\n\n(0..20).each { |i| puts \"%3d: %8d\" % [i, zeckendorf(i)] }\n", "language": "Crystal" }, { "code": "class ZeckendorfIterator\n include Iterator(String)\n\n def initialize\n @x = 0\n end\n\n def next\n bin = @x.to_s(2)\n @x += 1\n while bin.includes?(\"11\")\n bin = @x.to_s(2)\n @x += 1\n end\n bin\n end\nend\n\ndef zeckendorf(n)\n ZeckendorfIterator.new.first(n)\nend\n\nzeckendorf(21).each_with_index{ |x,i| puts \"%3d: %8s\"% [i, x] }\n", "language": "Crystal" }, { "code": "def zeckendorf(n)\n 0.step.map(&.to_s(2)).reject(&.includes?(\"11\")).first(n)\nend\n\n# or a little faster\n\ndef zeckendorf(n)\n 0.step.compact_map{ |x| bin = x.to_s(2); bin unless bin.includes?(\"11\") }.first(n)\nend\n\nzeckendorf(21).each_with_index{ |x,i| puts \"%3d: %8s\"% [i, x] }\n", "language": "Crystal" }, { "code": "import std.stdio, std.range, std.algorithm, std.functional;\n\nvoid main() {\n size_t\n .max\n .iota\n .filter!q{ !(a & (a >> 1)) }\n .take(21)\n .binaryReverseArgs!writefln(\"%(%b\\n%)\");\n}\n", "language": "D" }, { "code": "import std.stdio, std.typecons;\n\nint zeckendorf(in int n) pure nothrow {\n Tuple!(int,\"remaining\", int,\"set\")\n zr(in int fib0, in int fib1, in int n, in uint bit) pure nothrow {\n if (fib1 > n)\n return typeof(return)(n, 0);\n auto rs = zr(fib1, fib0 + fib1, n, bit + 1);\n if (fib1 <= rs.remaining) {\n rs.set |= 1 << bit;\n rs.remaining -= fib1;\n }\n return rs;\n }\n\n return zr(1, 1, n, 0)[1];\n}\n\nvoid main() {\n foreach (i; 0 .. 21)\n writefln(\"%2d: %6b\", i, zeckendorf(i));\n}\n", "language": "D" }, { "code": "import std.stdio, std.algorithm, std.range;\n\nstring zeckendorf(size_t n) {\n if (n == 0)\n return \"0\";\n auto fibs = recurrence!q{a[n - 1] + a[n - 2]}(1, 2);\n\n string result;\n foreach_reverse (immutable f; fibs.until!(x => x > n).array) {\n result ~= (f <= n) ? '1' : '0';\n if (f <= n)\n n -= f;\n }\n\n return result;\n}\n\nvoid main() {\n foreach (immutable i; 0 .. 21)\n writefln(\"%2d: %6s\", i, i.zeckendorf);\n}\n", "language": "D" }, { "code": "class Zeckendorf {\n static String getZeckendorf(int n) {\n if (n == 0) {\n return \"0\";\n }\n List<int> fibNumbers = [1];\n int nextFib = 2;\n while (nextFib <= n) {\n fibNumbers.add(nextFib);\n nextFib += fibNumbers[fibNumbers.length - 2];\n }\n StringBuffer sb = StringBuffer();\n for (int i = fibNumbers.length - 1; i >= 0; i--) {\n int fibNumber = fibNumbers[i];\n sb.write((fibNumber <= n) ? \"1\" : \"0\");\n if (fibNumber <= n) {\n n -= fibNumber;\n }\n }\n return sb.toString();\n }\n\n static void main() {\n for (int i = 0; i <= 20; i++) {\n print(\"Z($i)=${getZeckendorf(i)}\");\n }\n }\n}\n\nvoid main() {\n Zeckendorf.main();\n}\n", "language": "Dart" }, { "code": "const FibNums: array [0..21] of integer =\n (1, 2, 3, 5, 8, 13, 21, 34, 55, 89,\n 144, 233, 377, 610, 987, 1597, 2584,\n 4181, 6765, 10946, 17711, 28657);\n\n\nfunction GetZeckNumber(N: integer): string;\n{Returns Zeckendorf number for N as string}\nvar I: integer;\nbegin\nResult:='';\n{Subtract Fibonacci numbers from N}\nfor I:=High(FibNums) downto 0 do\n if (N-FibNums[I])>=0 then\n\tbegin\n\tResult:=Result+'1';\n\tN:=N-FibNums[I];\n\tend\n else if Length(Result)>0 then Result:=Result+'0';\nif Result='' then Result:='0';\nend;\n\n\nprocedure ShowZeckendorfNumbers(Memo: TMemo);\nvar I: integer;\nvar S: string;\nbegin\nS:='';\nfor I:=0 to 20 do\n\tbegin\n\tMemo.Lines.Add(IntToStr(I)+': '+GetZeckNumber(I));\n\tend;\nend;\n", "language": "Delphi" }, { "code": "proc mkfibs n . fib[] .\n fib[] = [ ]\n last = 1\n current = 1\n while current <= n\n fib[] &= current\n nxt = last + current\n last = current\n current = nxt\n .\n.\nfunc$ zeckendorf n .\n mkfibs n fib[]\n for pos = len fib[] downto 1\n if n >= fib[pos]\n zeck$ &= \"1\"\n n -= fib[pos]\n else\n zeck$ &= \"0\"\n .\n .\n if zeck$ = \"\"\n return \"0\"\n .\n return zeck$\n.\nfor n = 0 to 20\n print \" \" & n & \" \" & zeckendorf n\n.\n", "language": "EasyLang" }, { "code": ";; special fib's starting with 1 2 3 5 ...\n(define (fibonacci n)\n (+ (fibonacci (1- n)) (fibonacci (- n 2))))\n(remember 'fibonacci #(1 2))\n\n(define-constant Φ (// (1+ (sqrt 5)) 2))\n(define-constant logΦ (log Φ))\n;; find i : fib(i) >= n\n(define (iFib n)\n (floor (// (log (+ (* n Φ) 0.5)) logΦ)))\n\n;; left trim zeroes\n(string-delimiter \"\")\n(define (zeck->string digits)\n (if (!= 0 (first digits))\n (string-join digits \"\")\n (zeck->string (rest digits))))\n\n(define (Zeck n)\n (cond\n (( < n 0) \"no negative zeck\")\n ((inexact? n) \"no floating zeck\")\n ((zero? n) \"0\")\n (else (zeck->string\n (for/list ((s (reverse (take fibonacci (iFib n)))))\n (if ( > s n) 0\n (begin (-= n s) 1 )))))))\n", "language": "EchoLisp" }, { "code": "import system'routines;\nimport system'collections;\nimport system'text;\nimport extensions;\nextension op\n{\n fibonacci()\n {\n if (self < 2)\n {\n ^ self\n }\n else\n {\n ^ (self - 1).fibonacci() + (self - 2).fibonacci()\n };\n }\n\n zeckendorf()\n {\n var fibonacciNumbers := new List<int>();\n\n int num := self;\n int fibPosition := 2;\n int currentFibonaciNum := fibPosition.fibonacci();\n\n while (currentFibonaciNum <= num)\n {\n fibonacciNumbers.append(currentFibonaciNum);\n\n fibPosition := fibPosition + 1;\n currentFibonaciNum := fibPosition.fibonacci()\n };\n\n auto output := new TextBuilder();\n int temp := num;\n\n fibonacciNumbers.sequenceReverse().forEach::(item)\n {\n if (item <= temp)\n {\n output.write(\"1\");\n temp := temp - item\n }\n else\n {\n output.write(\"0\")\n }\n };\n\n ^ output.Value\n }\n}\n\npublic program()\n{\n for(int i := 1; i <= 20; i += 1)\n {\n console.printFormatted(\"{0} : {1}\",i,i.zeckendorf()).writeLine()\n };\n\n console.readChar()\n}\n", "language": "Elena" }, { "code": "defmodule Zeckendorf do\n def number do\n Stream.unfold(0, fn n -> zn_loop(n) end)\n end\n\n defp zn_loop(n) do\n bin = Integer.to_string(n, 2)\n if String.match?(bin, ~r/11/), do: zn_loop(n+1), else: {bin, n+1}\n end\nend\n\nZeckendorf.number |> Enum.take(21) |> Enum.with_index\n|> Enum.each(fn {zn, i} -> IO.puts \"#{i}: #{zn}\" end)\n", "language": "Elixir" }, { "code": "defmodule Zeckendorf do\n def number(n) do\n fib_loop(n, [2,1])\n |> Enum.reduce({\"\",n}, fn f,{dig,i} ->\n if f <= i, do: {dig<>\"1\", i-f}, else: {dig<>\"0\", i}\n end)\n |> elem(0) |> String.to_integer\n end\n\n defp fib_loop(n, fib) when n < hd(fib), do: fib\n defp fib_loop(n, [a,b|_]=fib), do: fib_loop(n, [a+b | fib])\nend\n\nfor i <- 0..20, do: IO.puts \"#{i}: #{Zeckendorf.number(i)}\"\n", "language": "Elixir" }, { "code": "% Function to generate a list of the first N Zeckendorf numbers\nnumber(N) ->\n number_helper(N, 0, 0, []).\n\nnumber_helper(0, _, _, Acc) ->\n lists:reverse(Acc);\nnumber_helper(N, Curr, Index, Acc) ->\n case zn_loop(Curr) of\n {Bin, Next} ->\n number_helper(N - 1, Next, Index + 1, [{Bin, Index} | Acc])\n end.\n\n% Helper function to find the next Zeckendorf number\nzn_loop(N) ->\n Bin = my_integer_to_binary(N),\n case re:run(Bin, \"11\", [{capture, none}]) of\n match ->\n zn_loop(N + 1);\n nomatch ->\n {Bin, N + 1}\n end.\n\n% Convert an integer to its binary representation as a string\nmy_integer_to_binary(N) ->\n lists:flatten(io_lib:format(\"~.2B\", [N])).\n\n% Test function to output the first 21 Zeckendorf numbers\nmain([]) ->\n ZnNumbers = number(21),\n lists:foreach(\n fun({Zn, I}) ->\n io:format(\"~p: ~s~n\", [I, Zn])\n end, ZnNumbers).\n", "language": "Erlang" }, { "code": "let fib = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (1,2)\n\nlet zeckendorf n =\n if n = 0 then [\"0\"]\n else\n let folder k state =\n let (n, z) = (fst state), (snd state)\n if n >= k then (n - k, \"1\" :: z)\n else (n, \"0\" :: z)\n let fb = fib |> Seq.takeWhile (fun i -> i<=n) |> Seq.toList\n snd (List.foldBack folder fb (n, []))\n |> List.rev\n\nfor i in 0 .. 20 do printfn \"%2d: %8s\" i (String.concat \"\" (zeckendorf i))\n", "language": "F-Sharp" }, { "code": "USING: formatting kernel locals make math sequences ;\n\n:: fib<= ( n -- seq )\n 1 2 [ [ dup n <= ] [ 2dup + [ , ] 2dip ] while drop , ]\n { } make ;\n\n:: zeck ( n -- str )\n 0 :> s! n fib<= <reversed>\n [ dup s + n <= [ s + s! 49 ] [ drop 48 ] if ] \"\" map-as ;\n\n21 <iota> [ dup zeck \"%2d: %6s\\n\" printf ] each\n", "language": "Factor" }, { "code": ": fib<= ( n -- n )\n >r 0 1 BEGIN dup r@ <= WHILE tuck + REPEAT drop rdrop ;\n\n: z. ( n -- )\n dup fib<= dup . -\n BEGIN ?dup WHILE\n dup fib<= dup [char] + emit space . -\n REPEAT ;\n\n: tab 9 emit ;\n\n: zeckendorf ( -- )\n 21 0 DO\n cr i 2 .r tab i z.\n LOOP ;\n", "language": "Forth" }, { "code": "F(N) = ((1 + SQRT(5))**N - (1 - SQRT(5))**N)/(SQRT(5)*2**N)\n", "language": "Fortran" }, { "code": " MODULE ZECKENDORF ARITHMETIC\t!Using the Fibonacci series, rather than powers of some base.\n INTEGER ZLAST\t\t!The standard 32-bit two's complement integers\n PARAMETER (ZLAST = 45)\t!only get so far, just as there's a limit to the highest power.\n INTEGER F1B(ZLAST)\t!I want the Fibonacci series, and, starting with its second one.\nc PARAMETER (F1B = (/1,2,\t!But alas, the compiler doesn't allow\nc 3 F1B(1) + F1B(2),\t\t!for this sort of carpet-unrolling\nc 4 F1B(2) + F1B(3), \t\t!initialisation sequence.\n INTEGER,PRIVATE:: F01,F02,F03,F04,F05,F06,F07,F08,F09,F10,\t!So, not bothering with F00,\n 1 F11,F12,F13,F14,F15,F16,F17,F18,F19,F20,\t!Prepare a horde of simple names,\n 2 F21,F22,F23,F24,F25,F26,F27,F28,F29,F30,\t!which can be initialised\n 3 F31,F32,F33,F34,F35,F36,F37,F38,F39,F40,\t!in a certain way,\n 4 F41,F42,F43,F44,F45\t\t\t\t!without scaring the compiler.\n PARAMETER (F01 = 1, F02 = 2, F03 = F02 + F01, F04 = F03 + F02,\t!Thusly.\n 1 F05=F04+F03,F06=F05+F04,F07=F06+F05,F08=F07+F06,F09=F08+F07,\t!Typing all this\n 2 F10=F09+F08,F11=F10+F09,F12=F11+F10,F13=F12+F11,F14=F13+F12,\t!is an invitation\n 3 F15=F14+F13,F16=F15+F14,F17=F16+F15,F18=F17+F16,F19=F18+F17,\t!for mistypes.\n 4 F20=F19+F18,F21=F20+F19,F22=F21+F20,F23=F22+F21,F24=F23+F22,\t!So a regular layout\n 5 F25=F24+F23,F26=F25+F24,F27=F26+F25,F28=F27+F26,F29=F28+F27,\t!helps a little.\n 6 F30=F29+F28,F31=F30+F29,F32=F31+F30,F33=F32+F31,F34=F33+F32,\t!Otherwise,\n 7 F35=F34+F33,F36=F35+F34,F37=F36+F35,F38=F37+F36,F39=F38+F37,\t!devise a prog.\n 8 F40=F39+F38,F41=F40+F39,F42=F41+F40,F43=F42+F41,F44=F43+F42,\t!to generate these texts...\n 9 F45=F44+F43)\t!The next is 2971215073. Too big for 32-bit two's complement integers.\n PARAMETER (F1B = (/F01,F02,F03,F04,F05,F06,F07,F08,F09,F10,\t!And now,\n 1 F11, F12, F13, F14, F15, F16, F17, F18, F19, F20,\t\t!Here is the desired\n 2 F21, F22, F23, F24, F25, F26, F27, F28, F29, F30,\t\t!array of constants.\n 3 F31, F32, F33, F34, F35, F36, F37, F38, F39, F40,\t\t!And as such, possibly\n 4 F41, F42, F43, F44, F45/))\t\t\t\t\t!protected from alteration.\n CONTAINS\t!After all that, here we go.\n SUBROUTINE ZECK(N,D)\t!Convert N to a \"Zeckendorf\" digit sequence.\nCounts upwards from digit one. D(i) ~ F1B(i). D(0) fingers the high-order digit.\n INTEGER N\t!The normal number, in the computer's base.\n INTEGER D(0:)\t!The digits, to be determined.\n INTEGER R\t!The remnant.\n INTEGER L\t!A finger, similar to the power of the base.\n IF (N.LT.0) STOP \"ZECK! No negative numbers!\"\t!I'm not thinking about them.\n R = N\t\t!Grab a copy that I can mess with.\n D = 0\t\t!Scrub the lot in one go.\n L = ZLAST\t!As if starting with BASE**MAX, rather than BASE**0.\n 10 IF (R.GE.F1B(L)) THEN\t!Has the remnant sufficient for this digit?\n R = R - F1B(L)\t\t!Yes! Remove that amount.\n IF (D(0).EQ.0) THEN\t\t!Is this the first non-zero digit?\n IF (L.GT.UBOUND(D,DIM=1)) STOP \"ZECK! Not enough digits!\"\t!Yes.\n D(0) = L\t\t\t!Remember the location of the high-order digit.\n END IF\t\t\t!Two loops instead, to avoid repeated testing?\n D(L) = 1\t\t\t!Place the digit, knowing a place awaits.\n L = L - 1\t\t\t!Never need a ...11... sequence because F1B(i) + F1B(i+1) = F1B(i+2).\n END IF\t\t!So much for that digit \"power\".\n L = L - 1\t\t!Down a digit.\n IF (L.GT.0 .AND. R.GT.0) GO TO 10\t!Are we there yet?\n IF (N.EQ.0) D(0) = 1\t!Zero has one digit.\n END SUBROUTINE ZECK\t!That was fun.\n\n INTEGER FUNCTION ZECKN(D)\t!Converts a \"Zeckendorf\" digit sequence to a number.\n INTEGER D(0:)\t!The digits. D(0) fingers the high-order digit.\n IF (D(0).LE.0) STOP \"ZECKN! Empty number!\"\t!General paranoia.\n IF (D(0).GT.ZLAST) STOP \"ZECKN! Oversize number!\"\t!I hate array bound hiccoughs.\n ZECKN = SUM(D(1:D(0))*F1B(1:D(0)))\t!This is what positional notation means.\n IF (ZECKN.LT.0) STOP \"ZECKN! Integer overflow!\"\t!Oh for IF OVERFLOW as in First Fortran.\n END FUNCTION ZECKN\t!Overflows by a small amount will produce a negative number.\n END MODULE ZECKENDORF ARITHMETIC\t!Odd stuff.\n\n PROGRAM POKE\n USE ZECKENDORF ARITHMETIC\t!Please.\n INTEGER ZD(0:ZLAST)\t!A scratchpad.\n INTEGER I,J,W\n CHARACTER*1 DIGIT(0:1)\t!Assistance for the output.\n PARAMETER (DIGIT = (/\"0\",\"1\"/), W = 6)\t!This field width suffices.\nc WRITE (6,*) F1B\nc WRITE (6,*) INT8(F1B(44)) + INT8(F1B(45))\n WRITE (6,1) F1B(1:4),ZLAST,ZLAST,F1B(ZLAST),HUGE(I)\t!Show some provenance.\n 1 FORMAT (\"Converts integers to their Zeckendorf digit string \"\n 1 \"using the Fib1nacci sequence (\",4(I0,\",\"),\n 2 \" ...) as the equivalent of powers.\"/\n 3 \"At most, \",I0,\" digits because Fib1nacci(\",I0,\") = \",I0,\n 4 \" and the integer limit is \",I0,\".\",//,\" N ZN\")\t!Ends with a heading.\n\n DO I = 0,20\t!Step through the specified range.\n CALL ZECK(I,ZD)\t\t!Convert I to ZD.\nc WRITE (6,2) I,ZD(ZD(0):1:-1)\t!Show digits from high-order to low.\nc 2 FORMAT (I3,1X,66I1)\t\t!Or, WRITE (6,2) I,(ZD(J), J = ZD(0),1,-1)\n WRITE (6,3) I,(\" \",J = ZD(0) + 1,W),DIGIT(ZD(ZD(0):1:-1))\t!Right-aligned in field width W.\n 3 FORMAT (I3,1X,66A1)\t\t!The digits appear as characters.\n IF (I.NE.ZECKN(ZD)) STOP \"Huh?\"\t!Should never happen...\n END DO\t\t!On to the next.\n\n END\n", "language": "Fortran" }, { "code": "' version 17-10-2016\n' compile with: fbc -s console\n\n#Define max 92 ' max for Fibonacci number\n\nDim Shared As ULongInt fib(max)\n\nfib(0) = 1\nfib(1) = 1\n\nFor x As Integer = 2 To max\n fib(x) = fib(x-1) + fib(x-2)\nNext\n\nFunction num2zeck(n As Integer) As String\n\nIf n < 0 Then\n Print \"Error: no negative numbers allowed\"\n Beep : Sleep 5000,1 : End\nEnd If\n\nIf n < 2 Then Return Str(n)\n\n Dim As String zeckendorf\n\n For x As Integer = max To 1 Step -1\n If fib(x) <= n Then\n zeckendorf = zeckendorf + \"1\"\n n = n - fib(x)\n Else\n zeckendorf = zeckendorf + \"0\"\n End If\n Next\n\n return LTrim(zeckendorf, \"0\") ' get rid of leading zeroes\nEnd Function\n\n' ------=< MAIN >=------\n\nDim As Integer x, e\nDim As String zeckendorf\nPrint \"number zeckendorf\"\n\nFor x = 0 To 200000\n\n zeckendorf = num2zeck(x)\n If x <= 20 Then Print x, zeckendorf\n\n ' check for two consecutive Fibonacci numbers\n If InStr(zeckendorf, \"11\") <> 0 Then\n Print \" Error: two consecutive Fibonacci numbers \"; x, zeckendorf\n e = e +1\n End If\nNext\n\nPrint\nIf e = 0 Then\n Print \" No Zeckendorf numbers with two consecutive Fibonacci numbers found\"\nElse\n Print e; \" error(s) found\"\nEnd If\n\n' empty keyboard buffer\nWhile Inkey <> \"\" : Wend\nPrint : Print \"hit any key to end program\"\nSleep\nEnd\n", "language": "FreeBASIC" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc main() {\n for i := 0; i <= 20; i++ {\n fmt.Printf(\"%2d %7b\\n\", i, zeckendorf(i))\n }\n}\n\nfunc zeckendorf(n int) int {\n // initial arguments of fib0 = 1 and fib1 = 1 will produce\n // the Fibonacci sequence {1, 2, 3,..} on the stack as successive\n // values of fib1.\n _, set := zr(1, 1, n, 0)\n return set\n}\n\nfunc zr(fib0, fib1, n int, bit uint) (remaining, set int) {\n if fib1 > n {\n return n, 0\n }\n // recurse.\n // construct sequence on the way in, construct ZR on the way out.\n remaining, set = zr(fib1, fib0+fib1, n, bit+1)\n if fib1 <= remaining {\n set |= 1 << bit\n remaining -= fib1\n }\n return\n}\n", "language": "Go" }, { "code": "import Data.Bits\nimport Numeric\n\nzeckendorf = map b $ filter ones [0..] where\n\tones :: Int -> Bool\n\tones x = 0 == x .&. (x `shiftR` 1)\n\tb x = showIntAtBase 2 (\"01\"!!) x \"\"\n\nmain = mapM_ putStrLn $ take 21 zeckendorf\n", "language": "Haskell" }, { "code": "zeckendorf = \"0\":\"1\":[s++[d] |\ts <- tail zeckendorf, d <- \"01\",\n\t\t\t\tlast s /= '1' || d /= '1']\n\nmain = mapM putStrLn $ take 21 zeckendorf\n", "language": "Haskell" }, { "code": "import Numeric\n\nfib = 1 : 1 : zipWith (+) fib (tail fib)\npow2 = iterate (2*) 1\n\nzeckendorf = map b z where\n\tz = 0:concat (zipWith f fib pow2)\n\tf x y = map (y+) (take x z)\n\tb x = showIntAtBase 2 (\"01\"!!) x \"\"\n\nmain = mapM_ putStrLn $ take 21 zeckendorf\n", "language": "Haskell" }, { "code": "import Data.List (mapAccumL)\n\nfib :: [Int]\nfib = 1 : 2 : zipWith (+) fib (tail fib)\n\nzeckendorf :: Int -> String\nzeckendorf 0 = \"0\"\nzeckendorf n = snd $ mapAccumL f n $ reverse $ takeWhile (<= n) fib\n where\n f n x\n | n < x = (n, '0')\n | otherwise = (n - x, '1')\n\nmain :: IO ()\nmain = (putStrLn . unlines) $ zeckendorf <$> [0 .. 20]\n", "language": "Haskell" }, { "code": "fib=: 3 : 0 \" 0\n mp=. +/ .*\n {.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x\n)\n\nphi=: -:1+%:5\n\nfi =: 3 : 'n - y<fib n=. 0>.(1=y)-~>.(phi^.%:5)+phi^.y'\n\nfsum=: 3 : 0\n z=. 0$r=. y\n while. 3<r do.\n m=. fib fi r\n z=. z,m\n r=. r-m\n end.\n z,r$~(*r)+.0=y\n)\n\nFilter=: (#~`)(`:6)\n\n' '&~:Filter@:\":@:#:@:#.@:((|. fib 2+i.8) e. fsum)&.>i.3 7\n┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐\n│0 │1 │10 │100 │101 │1000 │1001 │\n├──────┼──────┼──────┼──────┼──────┼──────┼──────┤\n│1010 │10000 │10001 │10010 │10100 │10101 │100000│\n├──────┼──────┼──────┼──────┼──────┼──────┼──────┤\n│100001│100010│100100│100101│101000│101001│101010│\n└──────┴──────┴──────┴──────┴──────┴──────┴──────┘\n", "language": "J" }, { "code": "import java.util.*;\n\nclass Zeckendorf\n{\n public static String getZeckendorf(int n)\n {\n if (n == 0)\n return \"0\";\n List<Integer> fibNumbers = new ArrayList<Integer>();\n fibNumbers.add(1);\n int nextFib = 2;\n while (nextFib <= n)\n {\n fibNumbers.add(nextFib);\n nextFib += fibNumbers.get(fibNumbers.size() - 2);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = fibNumbers.size() - 1; i >= 0; i--)\n {\n int fibNumber = fibNumbers.get(i);\n sb.append((fibNumber <= n) ? \"1\" : \"0\");\n if (fibNumber <= n)\n n -= fibNumber;\n }\n return sb.toString();\n }\n\n public static void main(String[] args)\n {\n for (int i = 0; i <= 20; i++)\n System.out.println(\"Z(\" + i + \")=\" + getZeckendorf(i));\n }\n}\n", "language": "Java" }, { "code": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Zeckendorf {\n\n private List<Integer> getFibList(final int maxNum, final int n1, final int n2, final List<Integer> fibs){\n if(n2 > maxNum) return fibs;\n\n fibs.add(n2);\n\n return getFibList(maxNum, n2, n1 + n2, fibs);\n }\n\n public String getZeckendorf(final int num) {\n if (num <= 0) return \"0\";\n\n final List<Integer> fibs = getFibList(num, 1, 2, new ArrayList<Integer>(){{ add(1); }});\n\n return getZeckString(\"\", num, fibs.size() - 1, fibs);\n }\n\n private String getZeckString(final String zeck, final int num, final int index, final List<Integer> fibs){\n final int curFib = fibs.get(index);\n final boolean placeZeck = num >= curFib;\n\n final String outString = placeZeck ? zeck + \"1\" : zeck + \"0\";\n final int outNum = placeZeck ? num - curFib : num;\n\n if(index == 0) return outString;\n\n return getZeckString(outString, outNum, index - 1, fibs);\n }\n\n public static void main(final String[] args) {\n final Zeckendorf zeckendorf = new Zeckendorf();\n\n for(int i =0; i <= 20; i++){\n System.out.println(\"Z(\"+ i +\"):\\t\" + zeckendorf.getZeckendorf(i));\n }\n }\n}\n", "language": "Java" }, { "code": "(() => {\n 'use strict';\n\n const main = () =>\n unlines(\n map(n => concat(zeckendorf(n)),\n enumFromTo(0, 20)\n )\n );\n\n // zeckendorf :: Int -> String\n const zeckendorf = n => {\n const go = (n, x) =>\n n < x ? (\n Tuple(n, '0')\n ) : Tuple(n - x, '1')\n return 0 < n ? (\n snd(mapAccumL(\n go, n,\n reverse(fibUntil(n))\n ))\n ) : ['0'];\n };\n\n // fibUntil :: Int -> [Int]\n const fibUntil = n =>\n cons(1, takeWhile(x => n >= x,\n map(snd, iterateUntil(\n tpl => n <= fst(tpl),\n tpl => {\n const x = snd(tpl);\n return Tuple(x, x + fst(tpl));\n },\n Tuple(1, 2)\n ))));\n\n // GENERIC FUNCTIONS ----------------------------\n\n // Tuple (,) :: a -> b -> (a, b)\n const Tuple = (a, b) => ({\n type: 'Tuple',\n '0': a,\n '1': b,\n length: 2\n });\n\n // concat :: [[a]] -> [a]\n // concat :: [String] -> String\n const concat = xs =>\n 0 < xs.length ? (() => {\n const unit = 'string' !== typeof xs[0] ? (\n []\n ) : '';\n return unit.concat.apply(unit, xs);\n })() : [];\n\n // cons :: a -> [a] -> [a]\n const cons = (x, xs) =>\n Array.isArray(xs) ? (\n [x].concat(xs)\n ) : (x + xs);\n\n // enumFromTo :: Int -> Int -> [Int]\n const enumFromTo = (m, n) =>\n m <= n ? iterateUntil(\n x => n <= x,\n x => 1 + x,\n m\n ) : [];\n\n // fst :: (a, b) -> a\n const fst = tpl => tpl[0];\n\n // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]\n const iterateUntil = (p, f, x) => {\n const vs = [x];\n let h = x;\n while (!p(h))(h = f(h), vs.push(h));\n return vs;\n };\n\n // map :: (a -> b) -> [a] -> [b]\n const map = (f, xs) => xs.map(f);\n\n // 'The mapAccumL function behaves like a combination of map and foldl;\n // it applies a function to each element of a list, passing an accumulating\n // parameter from left to right, and returning a final value of this\n // accumulator together with the new list.' (See Hoogle)\n\n // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\n const mapAccumL = (f, acc, xs) =>\n xs.reduce((a, x, i) => {\n const pair = f(a[0], x, i);\n return Tuple(pair[0], a[1].concat(pair[1]));\n }, Tuple(acc, []));\n\n // reverse :: [a] -> [a]\n const reverse = xs =>\n 'string' !== typeof xs ? (\n xs.slice(0).reverse()\n ) : xs.split('').reverse().join('');\n\n // snd :: (a, b) -> b\n const snd = tpl => tpl[1];\n\n // tail :: [a] -> [a]\n const tail = xs => 0 < xs.length ? xs.slice(1) : [];\n\n // takeWhile :: (a -> Bool) -> [a] -> [a]\n // takeWhile :: (Char -> Bool) -> String -> String\n const takeWhile = (p, xs) => {\n const lng = xs.length;\n return 0 < lng ? xs.slice(\n 0,\n until(\n i => i === lng || !p(xs[i]),\n i => 1 + i,\n 0\n )\n ) : [];\n };\n\n // unlines :: [String] -> String\n const unlines = xs => xs.join('\\n');\n\n // until :: (a -> Bool) -> (a -> a) -> a -> a\n const until = (p, f, x) => {\n let v = x;\n while (!p(v)) v = f(v);\n return v;\n };\n\n // MAIN ---\n return main();\n})();\n", "language": "JavaScript" }, { "code": "def zeckendorf:\n def fibs($n):\n # input: [f(i-2), f(i-1)]\n [1,1] | [recurse(select(.[1] < $n) | [.[1], add]) | .[1]] ;\n\n # Emit an array of 0s and 1s corresponding to the Zeckendorf encoding\n # $f should be the relevant Fibonacci numbers in increasing order.\n def loop($f):\n [ recurse(. as [$n, $ix]\n | select( $ix > -1 )\n | $f[$ix] as $next\n | if $n >= $next\n\t then [$n - $next, $ix-1, 1]\n else [$n, $ix-1, 0]\n end )\n | .[2] // empty ]\n # remove any superfluous leading 0:\n # remove leading 0 if any unless length==1\n | if length>1 and .[0] == 0 then .[1:] else . end ;\n\n # state: [$n, index_in_fibs, digit ]\n fibs(.) as $f\n | [., ($f|length)-1]\n | loop($f)\n | join(\"\") ;\n", "language": "Jq" }, { "code": "range(0;21) | \"\\(.): \\(zeckendorf)\"\n", "language": "Jq" }, { "code": "$ jq -n -r -f zeckendorf.jq\n0: 0\n1: 1\n2: 10\n3: 100\n4: 101\n5: 1000\n6: 1001\n7: 1010\n8: 10000\n9: 10001\n10: 10010\n11: 10100\n12: 10101\n13: 100000\n14: 100001\n15: 100010\n16: 100100\n17: 100101\n18: 101000\n19: 101001\n20: 101010\n", "language": "Jq" }, { "code": "function zeck(n)\n n <= 0 && return 0\n fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end\n dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end\n return dig[1] == 0 ? dig[2:end] : dig\nend\n", "language": "Julia" }, { "code": "include ..\\Utilitys.tlhy\n\n:listos\n %i$ \"\" !i$\n len [ get tostr $i$ chain !i$ ] for drop\n $i$\n;\n\n\n:Zeckendorf %n !n\n %i 0 !i %c 0 !c\n\n [\n $i 8 itob listos\n \"11\" find not (\n [ ( $c \":\" 9 tochar ) lprint tonum ? $c 1 + !c ]\n [drop]\n ) if\n $i 1 + !i\n ]\n [$c $n >] until\n;\n\n\n20 Zeckendorf\n\nnl \"End \" input\n", "language": "Klingphix" }, { "code": "// version 1.0.6\n\nconst val LIMIT = 46 // to stay within range of signed 32 bit integer\nval fibs = fibonacci(LIMIT)\n\nfun fibonacci(n: Int): IntArray {\n if (n !in 2..LIMIT) throw IllegalArgumentException(\"n must be between 2 and $LIMIT\")\n val fibs = IntArray(n)\n fibs[0] = 1\n fibs[1] = 1\n for (i in 2 until n) fibs[i] = fibs[i - 1] + fibs[i - 2]\n return fibs\n}\n\nfun zeckendorf(n: Int): String {\n if (n < 0) throw IllegalArgumentException(\"n must be non-negative\")\n if (n < 2) return n.toString()\n var lastFibIndex = 1\n for (i in 2..LIMIT)\n if (fibs[i] > n) {\n lastFibIndex = i - 1\n break\n }\n var nn = n - fibs[lastFibIndex--]\n val zr = StringBuilder(\"1\")\n for (i in lastFibIndex downTo 1)\n if (fibs[i] <= nn) {\n zr.append('1')\n nn -= fibs[i]\n } else {\n zr.append('0')\n }\n return zr.toString()\n}\n\nfun main(args: Array<String>) {\n println(\" n z\")\n for (i in 0..20) println(\"${\"%2d\".format(i)} : ${zeckendorf(i)}\")\n}\n", "language": "Kotlin" }, { "code": "samples = 20\ncall zecklist samples\n\nprint \"Decimal\",\"Zeckendorf\"\nfor n = 0 to samples\n print n, zecklist$(n)\nnext n\n\nSub zecklist inDEC\n dim zecklist$(inDEC)\n do\n bin$ = dec2bin$(count)\n if instr(bin$,\"11\") = 0 then\n zecklist$(found) = bin$\n found = found + 1\n end if\n count = count+1\n loop until found = inDEC + 1\nEnd sub\n\nfunction dec2bin$(inDEC)\n do\n bin$ = str$(inDEC mod 2) + bin$\n inDEC = int(inDEC/2)\n loop until inDEC = 0\n dec2bin$ = bin$\nend function\n", "language": "Liberty-BASIC" }, { "code": "-- Return the distinct Fibonacci numbers not greater than 'n'\non fibsUpTo (n)\n fibList = []\n last = 1\n current = 1\n repeat while current <= n\n fibList.add(current)\n nxt = last + current\n last = current\n current = nxt\n end repeat\n return fibList\nend\n\n-- Return the Zeckendorf representation of 'n'\non zeckendorf (n)\n fib = fibsUpTo(n)\n zeck = \"\"\n repeat with pos = fib.count down to 1\n if n >= fib[pos] then\n zeck = zeck & \"1\"\n n = n - fib[pos]\n else\n zeck = zeck & \"0\"\n end if\n end repeat\n if zeck = \"\" then return \"0\"\n return zeck\nend\n", "language": "Lingo" }, { "code": "repeat with n = 0 to 20\n put n & \": \" & zeckendorf(n)\nend repeat\n", "language": "Lingo" }, { "code": "// Little Man Computer, for Rosetta Code.\n// Writes Zeckendorf representations of numbers 0..20.\n// Works with Peter Higginson's LMC simulator, except that\n// user must intervene manually to capture all the output.\n LDA c0 // initialize to N = 0\nloop STA N\n OUT // write N\n LDA equals // then equals sign\n OTC\n BRA wr_zeck // then Zeckendorf rep\nreturn LDA space // then space\n OTC\n LDA N // done maximum N?\n SUB N_max\n BRZ halt // yes, halt\n LDA N // no, inc N and loop back\n ADD c1\n BRA loop\nhalt HLT\nc0 DAT 0\nN_max DAT 20\nequals DAT 61\nspace DAT 32\n\n// Routine to write Zeckendorf representation of number stored in N.\n// Since LMC doesn't support subroutines, returns with \"BRA return\".\nwr_zeck LDA N\n SUB c1\n BRP phase_1\n// N = 0, special case\n LDA ascii_0\n OTC\n BRA done\n// N > 0. Phase 1: find largest Fibonacci number <= N\nphase_1 STA res // res := N - 1\n LDA c1 // initialize Fibonacci terms\n STA a\n STA b\nloop_1 LDA res // here res = N - a (easy proof)\n SUB b // is next Fibonacci a + b > N?\n BRP next_fib // no, continue Fibonacci\n BRA phase_2 // yes, on to phase 2\nnext_fib STA res // res := res - b\n LDA a // (a, b) := (a + b, a)\n ADD b\n STA a\n SUB b\n STA b\n BRA loop_1 // loop to test new (a, b)\n// Phase 2: get Zeckendorf digits by winding Fibonacci back\nphase_2 LDA ascii_1 // first digit must be 1\n OTC\nloop_2 LDA a // done when wound back to a = 1\n SUB c1\n BRZ done\n LDA res // decide next Zeckendorf digit\n SUB b // 0 if res < b, 1 if res >= b\n BRP dig_is_1\n LDA ascii_0\n BRA wr_dig\ndig_is_1 STA res // res := res - b\n LDA ascii_1\nwr_dig OTC // write Zeckendorf digit 0 or 1\n LDA a // (a, b) := (b, a - b)\n SUB b\n STA b\n LDA a\n SUB b\n STA a\n BRA loop_2 // loop to test new (a, b)\ndone BRA return\nN DAT\nres DAT\na DAT\nb DAT\nc1 DAT 1\nascii_0 DAT 48\nascii_1 DAT 49\n// end\n", "language": "Little-Man-Computer" }, { "code": "; return the (N+1)th Fibonacci number (1,2,3,5,8,13,...)\nto fib m\n local \"n\n make \"n sum :m 1\n if [lessequal? :n 0] [output difference fib sum :n 2 fib sum :n 1]\n global \"_fib\n if [not name? \"_fib] [\n make \"_fib [1 1]\n ]\n local \"length\n make \"length count :_fib\n while [greater? :n :length] [\n make \"_fib (lput (sum (last :_fib) (last (butlast :_fib))) :_fib)\n make \"length sum :length 1\n ]\n output item :n :_fib\nend\n\n; return the binary Zeckendorf representation of a nonnegative number\nto zeckendorf n\n if [less? :n 0] [(throw \"error [Number must be nonnegative.])]\n (local \"i \"f \"result)\n make \"i :n\n make \"f fib :i\n while [less? :f :n] [make \"i sum :i 1 make \"f fib :i]\n\n make \"result \"||\n while [greater? :i 0] [\n ifelse [greaterequal? :n :f] [\n make \"result lput 1 :result\n make \"n difference :n :f\n ] [\n if [not empty? :result] [\n make \"result lput 0 :result\n ]\n ]\n make \"i difference :i 1\n make \"f fib :i\n ]\n if [equal? :result \"||] [\n make \"result 0\n ]\n output :result\nend\n\ntype zeckendorf 0\nrepeat 20 [\n type word \"| | zeckendorf repcount\n]\nprint []\nbye\n", "language": "Logo" }, { "code": "-- Return the distinct Fibonacci numbers not greater than 'n'\nfunction fibsUpTo (n)\n local fibList, last, current, nxt = {}, 1, 1\n while current <= n do\n table.insert(fibList, current)\n nxt = last + current\n last = current\n current = nxt\n end\n return fibList\nend\n\n-- Return the Zeckendorf representation of 'n'\nfunction zeckendorf (n)\n local fib, zeck = fibsUpTo(n), \"\"\n for pos = #fib, 1, -1 do\n if n >= fib[pos] then\n zeck = zeck .. \"1\"\n n = n - fib[pos]\n else\n zeck = zeck .. \"0\"\n end\n end\n if zeck == \"\" then return \"0\" end\n return zeck\nend\n\n-- Main procedure\nprint(\" n\\t| Zeckendorf(n)\")\nprint(string.rep(\"-\", 23))\nfor n = 0, 20 do\n print(\" \" .. n, \"| \" .. zeckendorf(n))\nend\n", "language": "Lua" }, { "code": "ZeckendorfRepresentation[0] = 0;\n\nZeckendorfRepresentation[n_Integer?Positive]:=\n NumberDecompose[n, Reverse@Fibonacci@Range[2,1000]] // FromDigits\n\nZeckendorfRepresentation /@ Range[0, 20]\n", "language": "Mathematica" }, { "code": "clear all; close all; clc;\n\n% Print the sequence for numbers from 0 to 20\nfor x = 0:20\n zeckString = arrayfun(@num2str, zeck(x), 'UniformOutput', false);\n zeckString = strjoin(zeckString, '');\n fprintf(\"%d : %s\\n\", x, zeckString);\nend\n\nfunction dig = zeck(n)\n if n <= 0\n dig = 0;\n return;\n end\n\n fib = [1, 2];\n while fib(end) < n\n fib(end + 1) = sum(fib(end-1:end));\n end\n fib = fliplr(fib); % Reverse the order of Fibonacci numbers\n\n dig = [];\n for i = 1:length(fib)\n if fib(i) <= n\n dig(end + 1) = 1;\n n = n - fib(i);\n else\n dig(end + 1) = 0;\n end\n end\n\n if dig(1) == 0\n dig = dig(2:end);\n end\nend\n", "language": "MATLAB" }, { "code": "fibonacci = function(val)\n\tif val < 1 then return []\n\tfib = []\n\ta = 1; b = 2\n\twhile a <= val\n\t\tfib.insert(0, a)\n\t\tnext = a + b\n\t\ta = b\n\t\tb = next\n\tend while\n\treturn fib\nend function\n\nzeckendorf = function(val)\n\tseq = fibonacci(val)\n\ts = \"\"\n\tfor i in seq\n\t\tonOff = val >= i and (s == \"\" or s[-1] == \"0\")\n\t\ts += str(onOff)\n\t\tval -= (i*onOff)\n\tend for\n\treturn s\nend function\n\nfor i in range(1, 20)\n\tprint [i, zeckendorf(i)]\nend for\n", "language": "MiniScript" }, { "code": "import strformat, strutils\n\nproc z(n: Natural): string =\n if n == 0: return \"0\"\n var fib = @[2,1]\n var n = n\n while fib[0] < n: fib.insert(fib[0] + fib[1])\n for f in fib:\n if f <= n:\n result.add '1'\n dec n, f\n else:\n result.add '0'\n if result[0] == '0':\n result = result[1..result.high]\n\nfor i in 0 .. 20:\n echo &\"{i:>3} {z(i):>8}\"\n", "language": "Nim" }, { "code": "let zeck n =\n let rec enc x s = function\n | h :: t when h <= x -> enc (x - h) (s ^ \"1\") t\n | _ :: t -> enc x (s ^ \"0\") t\n | _ -> s\n and fib b a l =\n if b > n\n then enc (n - a) \"1\" l\n else fib (b + a) b (a :: l)\n in\n if n = 0 then \"0\" else fib 2 1 []\n\nlet () =\n for i = 0 to 20 do Printf.printf \"%3u:%8s\\n\" i (zeck i) done\n", "language": "OCaml" }, { "code": "Z(n)=if(!n,print1(0));my(k=2);while(fibonacci(k)<=n,k++); forstep(i=k-1,2,-1,print1(if(fibonacci(i)<=n,n-=fibonacci(i);1,0)));print\nfor(n=0,20,Z(n))\n", "language": "PARI-GP" }, { "code": "program ZeckendorfRep_RC;\n\n{$mode objfpc}{$H+}\n\nuses SysUtils;\n\n// Return Zeckendorf representation of the passed-in cardinal.\nfunction ZeckRep( C : cardinal) : string;\nvar\n a, b, rem : cardinal;\n j, nrDigits: integer;\nbegin\n // Case C = 0 has to be treated specially\n if (C = 0) then begin\n result := '0';\n exit;\n end;\n // Find largest Fibonacci number not exceeding C\n a := 1;\n b := 1;\n nrDigits := 1;\n rem := C - 1;\n while (rem >= b) do begin\n dec( rem, b);\n inc( a, b);\n b := a - b;\n inc( nrDigits);\n end;\n // Fill in digits by reversing Fibonacci back to start\n SetLength( result, nrDigits);\n j := 1;\n result[j] := '1';\n for j := 2 to nrDigits do begin\n if (rem >= b) then begin\n dec( rem, b);\n result[j] := '1';\n end\n else result[j] := '0';\n b := a - b;\n dec( a, b);\n end;\n// Assert((a = 1) and (b = 1)); // optional check\nend;\n\n// Main routine\nvar\n C : cardinal;\nbegin\n for C := 1 to 20 do\n WriteLn( SysUtils.Format( '%2d: %s', [C, ZeckRep(C)]));\nend.\n", "language": "Pascal" }, { "code": "my @fib;\n\nsub fib {\n my $n = shift;\n return 1 if $n < 2;\n return $fib[$n] //= fib($n-1)+fib($n-2);\n}\n\nsub zeckendorf {\n my $n = shift;\n return \"0\" unless $n;\n my $i = 1;\n $i++ while fib($i) <= $n;\n my $z = '';\n while( --$i ) {\n $z .= \"0\", next if fib( $i ) > $n;\n $z .= \"1\";\n $n -= fib( $i );\n }\n return $z;\n}\n\nprintf \"%4d: %8s\\n\", $_, zeckendorf($_) for 0..20;\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">function</span> <span style=\"color: #000000;\">zeckendorf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">c</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">fib</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$]<</span><span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">fib</span> <span style=\"color: #0000FF;\">&=</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$]</span> <span style=\"color: #0000FF;\">+</span> <span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[$-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">2</span> <span style=\"color: #008080;\">by</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">c</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">>=</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #000000;\">r</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">r</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">c</span>\n <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">c</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">fib</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #008080;\">return</span> <span style=\"color: #000000;\">r</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">function</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">20</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%2d: %7b\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zeckendorf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">)})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n<!--\n", "language": "Phix" }, { "code": "def Zeckendorf /# n -- #/\n 0 var i 0 var c 1 1 2 tolist var pattern\n true\n while\n i 8 int>bit reverse\n pattern find\n not if\n c print \":\\t\" print print nl\n dup c == if\n false\n else\n c 1 + var c\n true\n endif\n endif\n i 1 + var i\n endwhile\n drop\nenddef\n\n20 Zeckendorf\n", "language": "Phixmonti" }, { "code": "<?php\n$m = 20;\n\n$F = array(1,1);\nwhile ($F[count($F)-1] <= $m)\n $F[] = $F[count($F)-1] + $F[count($F)-2];\n\nwhile ($n = $m--) {\n while ($F[count($F)-1] > $n) array_pop($F);\n $l = count($F)-1;\n print \"$n: \";\n while ($n) {\n if ($n >= $F[$l]) {\n $n = $n - $F[$l];\n print '1';\n } else print '0';\n --$l;\n }\n print str_repeat('0',$l);\n print \"\\n\";\n}\n?>\n", "language": "PHP" }, { "code": "go =>\n foreach(Num in 0..20)\n zeckendorf_cp(Num,X,F),\n Nums = [F[I] : I in 1..X.length, X[I] = 1],\n printf(\"%2d %6s %w\\n\",Num, rep(X),Nums),\n end,\n nl.\n\nzeckendorf_cp(Num, X,F) =>\n F = get_fibs(Num).reverse(),\n N = F.length,\n X = new_list(N),\n X :: 0..1,\n\n % From the task description:\n % \"\"\"\n % For a true Zeckendorf number there is the added restriction that\n % no two consecutive Fibonacci numbers can be used which leads to\n % the former unique solution.\n % \"\"\"\n foreach(I in 2..N)\n X[I-1] #= 1 #=> X[I] #= 0\n end,\n\n scalar_product(F,X,Num),\n\n solve([ff,split],X).\n\n%\n% Fibonacci numbers\n%\ntable\nfib(0) = 0.\nfib(1) = 1.\nfib(N) = fib(N-1) + fib(N-2).\n\n%\n% Remove leading 0's and stringify it\n%\nrep(X) = Str =>\n First = 1,\n if X.length > 1, X[First] = 0 then\n while (X[First] == 0)\n First := First + 1\n end\n end,\n Str = [X[I].to_string() : I in First..X.length].join('').\n\n%\n% Return a list of fibs <= N\n%\nget_fibs(N) = Fibs =>\n I = 2,\n Fib = fib(I),\n Fibs1 = [Fib],\n while (Fib < N)\n I := I + 1,\n Fib := fib(I),\n Fibs1 := Fibs1 ++ [Fib]\n end,\n Fibs = Fibs1.\n", "language": "Picat" }, { "code": "go2 =>\n foreach(Num in 0..20)\n zeckendorf2(Num,X,F),\n Nums = [F[I] : I in 1..X.length, X[I]= 1],\n printf(\"%2d %6s %w\\n\",Num, rep(X),Nums)\n end,\n nl.\n\nzeckendorf2(0, [0],[0]).\nzeckendorf2(Num, X,F) :-\n Fibs = get_fibs(Num),\n I = Fibs.length,\n N = Num,\n X1 = [],\n while (I > 0)\n Fib := Fibs[I],\n X1 := X1 ++ [cond(Fib > N,0,1)],\n if Fib <= N then\n N := N - Fib\n end,\n I := I - 1\n end,\n X = X1,\n F = Fibs.reverse().\n", "language": "Picat" }, { "code": "(de fib (N)\n (let Fibs (1 1)\n (while (>= N (+ (car Fibs) (cadr Fibs)))\n (push 'Fibs (+ (car Fibs) (cadr Fibs))) )\n (uniq Fibs) ) )\n\n(de zecken1 (N)\n (make\n (for I (fib N)\n (if (> I N)\n (link 0)\n (link 1)\n (dec 'N I) ) ) ) )\n\n(de zecken2 (N)\n (make\n (when (=0 N) (link 0))\n (for I (fib N)\n (when (<= I N)\n (link I)\n (dec 'N I) ) ) ) )\n\n(for (N 0 (> 21 N) (inc N))\n (tab (2 4 6 2 -10)\n N\n \" -> \"\n (zecken1 N)\n \" \"\n (glue \" + \" (zecken2 N)) ) )\n\n(bye)\n", "language": "PicoLisp" }, { "code": "\\def\\genfibolist#1{% #creates the fibo list which sum>=#1\n\t\\let\\fibolist\\empty\\def\\targetsum{#1}\\def\\fibosum{0}%\n\t\\genfibolistaux1,1\\relax\n}\n\\def\\genfibolistaux#1,#2\\relax{%\n\t\\ifnum\\fibosum<\\targetsum\\relax\n\t\t\\edef\\fibosum{\\number\\numexpr\\fibosum+#2}%\n\t\t\\edef\\fibolist{#2,\\fibolist}%\n\t\t\\edef\\tempfibo{\\noexpand\\genfibolistaux#2,\\number\\numexpr#1+#2\\relax\\relax}%\n\t\t\\expandafter\\tempfibo\n\t\\fi\n}\n\\def\\zeckendorf#1{\\expandafter\\zeckendorfaux\\fibolist,\\relax#1\\relax\\relax0}\n\\def\\zeckendorfaux#1,#2\\relax#3\\relax#4\\relax#5{%\n\t\\ifx\\relax#2\\relax\n\t\t#4%\n\t\\else\n\t\t\\ifnum#3<#1\n\t\t\t\\edef\\temp{#2\\relax#3\\relax#4\\ifnum#5=1 0\\fi\\relax#5}%\n\t\t\\else\n\t\t\t\\edef\\temp{#2\\relax\\number\\numexpr#3-#1\\relax\\relax#41\\relax1}%\n\t\t\\fi\n\t\t\\expandafter\\expandafter\\expandafter\\zeckendorfaux\\expandafter\\temp\n\t\\fi\n}\n\\newcount\\ii\n\\def\\listzeckendorf#1{%\n\t\\genfibolist{#1}%\n\t\\ii=0\n\t\\loop\n\t\t\\ifnum\\ii<#1\n\t\t\\advance\\ii1\n\t\t\\number\\ii: \\zeckendorf\\ii\\endgraf\n\t\\repeat\n}\n\\listzeckendorf{20}% any integer accepted\n\\bye\n", "language": "PlainTeX" }, { "code": "function Get-ZeckendorfNumber ( $N )\n {\n # Calculate relevant portation of Fibonacci series\n $Fib = @( 1, 1 )\n While ( $Fib[-1] -lt $N ) { $Fib += $Fib[-1] + $Fib[-2] }\n\n # Start with 0\n $ZeckendorfNumber = 0\n\n # For each number in the relevant portion of Fibonacci series\n For ( $i = $Fib.Count - 1; $i -gt 0; $i-- )\n {\n # If Fibonacci number is less than or equal to remainder of N\n If ( $Fib[$i] -le $N )\n {\n # Double Z number and add 1 (equivalent to adding a '1' to the end of a binary number)\n $ZeckendorfNumber = $ZeckendorfNumber * 2 + 1\n # Reduce N by Fibonacci number, skip next Fibonacci number\n $N -= $Fib[$i--]\n }\n # If were aren't finished yet, double Z number\n # (equivalent to adding a '0' to the end of a binary number)\n If ( $i ) { $ZeckendorfNumber *= 2 }\n }\n return $ZeckendorfNumber\n }\n", "language": "PowerShell" }, { "code": "# Get Zeckendorf numbers through 20, convert to binary for display\n0..20 | ForEach { [convert]::ToString( ( Get-ZeckendorfNumber $_ ), 2 ) }\n", "language": "PowerShell" }, { "code": "Procedure.s zeck(n.i)\n Dim f.i(1) : Define i.i=1, o$\n f(0)=1 : f(1)=1\n While f(i)<n\n i+1 : ReDim f(ArraySize(f())+1) : f(i)=f(i-1)+f(i-2)\n Wend\n For i=i To 1 Step -1\n If n>=f(i) : o$+\"1\" : n-f(i) : Else : o$+\"0\" : EndIf\n Next\n If Len(o$)>1 : o$=LTrim(o$,\"0\") : EndIf\n ProcedureReturn o$\nEndProcedure\n\nDefine n.i, t$\nOpenConsole(\"Zeckendorf number representation\")\nPrintN(~\"\\tNr.\\tZeckendorf\")\nFor n=0 To 20\n t$=zeck(n)\n If FindString(t$,\"11\")\n PrintN(\"Error: n= \"+Str(n)+~\"\\tZeckendorf= \"+t$)\n Break\n Else\n PrintN(~\"\\t\"+RSet(Str(n),3,\" \")+~\"\\t\"+RSet(t$,7,\" \"))\n EndIf\nNext\nInput()\n", "language": "PureBasic" }, { "code": "def fib():\n memo = [1, 2]\n while True:\n memo.append(sum(memo))\n yield memo.pop(0)\n\ndef sequence_down_from_n(n, seq_generator):\n seq = []\n for s in seq_generator():\n seq.append(s)\n if s >= n: break\n return seq[::-1]\n\ndef zeckendorf(n):\n if n == 0: return [0]\n seq = sequence_down_from_n(n, fib)\n digits, nleft = [], n\n for s in seq:\n if s <= nleft:\n digits.append(1)\n nleft -= s\n else:\n digits.append(0)\n assert nleft == 0, 'Check all of n is accounted for'\n assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct'\n while digits[0] == 0:\n # Remove any zeroes padding L.H.S.\n digits.pop(0)\n return digits\n\nn = 20\nprint('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib))\nfor i in range(n + 1):\n print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i))))\n", "language": "Python" }, { "code": "n = 20\ndef z(n):\n if n == 0 : return [0]\n fib = [2,1]\n while fib[0] < n: fib[0:0] = [sum(fib[:2])]\n dig = []\n for f in fib:\n if f <= n:\n dig, n = dig + [1], n - f\n else:\n dig += [0]\n return dig if dig[0] else dig[1:]\n\nfor i in range(n + 1):\n print('%3i: %8s' % (i, ''.join(str(d) for d in z(i))))\n", "language": "Python" }, { "code": " [ 2 base put\n echo\n base release ] is binecho ( n --> )\n\n [ 0 swap ' [ 2 1 ]\n [ 2dup 0 peek < iff\n [ behead drop ]\n done\n dup 0 peek\n over 1 peek\n + swap join again ]\n witheach\n [ rot 1 << unrot\n 2dup < iff drop\n else\n [ -\n dip\n [ 1 | ] ] ]\n drop ] is n->z ( n --> z )\n\n [ 0 temp put\n 1 1 rot\n [ dup while\n dup 1 & if\n [ over\n temp tally ]\n 1 >>\n dip [ tuck + ]\n again ]\n 2drop drop\n temp take ] is z->n ( z --> n )\n\n 21 times\n [ i^ dup echo\n say \" -> \"\n n->z dup binecho\n say \" -> \"\n z->n echo cr ]\n", "language": "Quackery" }, { "code": "' Zeckendorf number representation\nDECLARE FUNCTION ToZeckendorf$ (N%)\n' The maximum Fibonacci number that can fit in a\n' 32 bit number is Fib&(45)\nCONST MAXFIBINDEX% = 45, TRUE% = -1, FALSE% = 0\nDIM SHARED Fib&(1 TO MAXFIBINDEX%)\nFib&(1) = 1: Fib&(2) = 2\nFOR I% = 3 TO MAXFIBINDEX%\n Fib&(I%) = Fib&(I% - 1) + Fib&(I% - 2)\nNEXT I%\nFOR I% = 0 TO 20\n SixChars$ = SPACE$(6)\n RSET SixChars$ = ToZeckendorf$(I%)\n PRINT USING \"### \"; I%; : PRINT SixChars$\nNEXT I%\nEND\n\nFUNCTION ToZeckendorf$ (N%)\n ' returns the Zeckendorf representation of N% or \"?\" if one cannot be found\n IF N% = 0 THEN\n ToZeckendorf$ = \"0\"\n ELSE\n Result$ = \"\"\n FPos% = MAXFIBINDEX%\n Rest% = ABS(N%)\n ' Find the first non-zero Zeckendorf digit\n WHILE FPos% > 1 AND Rest% < Fib&(FPos%)\n FPos% = FPos% - 1\n WEND\n ' If we found a digit, build the representation\n IF FPos% >= 1 THEN ' have a digit\n SkipDigit% = FALSE%\n WHILE FPos% >= 1\n IF Rest% <= 0 THEN\n Result$ = Result$ + \"0\"\n ELSEIF SkipDigit% THEN ' we used the previous digit\n SkipDigit% = FALSE%\n Result$ = Result$ + \"0\"\n ELSEIF Rest% < Fib&(FPos%) THEN ' cannot use the digit at FPos%\n SkipDigit% = FALSE%\n Result$ = Result$ + \"0\"\n ELSE ' can use this digit\n SkipDigit% = TRUE%\n Result$ = Result$ + \"1\"\n Rest% = Rest% - Fib&(FPos%)\n END IF\n FPos% = FPos% - 1\n WEND\n END IF\n IF Rest% = 0 THEN\n ToZeckendorf$ = Result$\n ELSE\n ToZeckendorf$ = \"?\"\n END IF\n END IF\nEND FUNCTION\n", "language": "QuickBASIC" }, { "code": "zeckendorf <- function(number) {\n\n # Get an upper limit on Fibonacci numbers needed to cover number\n indexOfFibonacciNumber <- function(n) {\n if (n < 1) {\n 2\n } else {\n Phi <- (1 + sqrt(5)) / 2\n invertClosedFormula <- log(n * sqrt(5)) / log(Phi)\n ceiling(invertClosedFormula)\n }\n }\n\n upperLimit <- indexOfFibonacciNumber(number)\n\n # Return the sequence as digits, sorted descending\n fibonacciSequenceDigits <- function(n) {\n fibGenerator <- function(f, ...) { c(f[2], sum(f)) }\n fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE)\n\n fibNums <- unlist(lapply(fibSeq, head, n=1))\n\n # drop last F0 and F1 and reverse sequence\n rev(fibNums[-2:-1])\n }\n\n digits <- fibonacciSequenceDigits(upperLimit)\n\n isInNumber <- function(digit) {\n if (number >= digit) {\n number <<- number - digit\n 1\n } else {\n 0\n }\n }\n\n zeckSeq <- Map(isInNumber, digits)\n\n # drop leading 0 and convert to String\n gsub(\"^0+1\", \"1\", paste(zeckSeq, collapse=\"\"))\n}\n\nprint(unlist(lapply(0:20, zeckendorf)))\n", "language": "R" }, { "code": "#lang racket (require math)\n\n(define (fibs n)\n (reverse\n (for/list ([i (in-naturals 2)] #:break (> (fibonacci i) n))\n (fibonacci i))))\n\n(define (zechendorf n)\n (match/values\n (for/fold ([n n] [xs '()]) ([f (fibs n)])\n (if (> f n)\n (values n (cons 0 xs))\n (values (- n f) (cons 1 xs))))\n [(_ xs) (reverse xs)]))\n\n(for/list ([n 21])\n (list n (zechendorf n)))\n", "language": "Racket" }, { "code": "'((0 ())\n (1 (1))\n (2 (1 0))\n (3 (1 0 0))\n (4 (1 0 1))\n (5 (1 0 0 0))\n (6 (1 0 0 1))\n (7 (1 0 1 0))\n (8 (1 0 0 0 0))\n (9 (1 0 0 0 1))\n (10 (1 0 0 1 0))\n (11 (1 0 1 0 0))\n (12 (1 0 1 0 1))\n (13 (1 0 0 0 0 0))\n (14 (1 0 0 0 0 1))\n (15 (1 0 0 0 1 0))\n (16 (1 0 0 1 0 0))\n (17 (1 0 0 1 0 1))\n (18 (1 0 1 0 0 0))\n (19 (1 0 1 0 0 1))\n (20 (1 0 1 0 1 0)))\n", "language": "Racket" }, { "code": "printf \"%2d: %8s\\n\", $_, zeckendorf($_) for 0 .. 20;\n\nmulti zeckendorf(0) { '0' }\nmulti zeckendorf($n is copy) {\n constant FIBS = (1,2, *+* ... *).cache;\n [~] map {\n $n -= $_ if my $digit = $n >= $_;\n +$digit;\n }, reverse FIBS ...^ * > $n;\n}\n", "language": "Raku" }, { "code": "/* REXX ***************************************************************\n* 11.10.2012 Walter Pachl\n**********************************************************************/\nfib='13 8 5 3 2 1'\nDo i=6 To 1 By -1 /* Prepare Fibonacci Numbers */\n Parse Var fib f.i fib /* f.1 ... f.7 */\n End\nDo n=0 To 20 /* for all numbers in the task */\n m=n /* copy of number */\n r='' /* result for n */\n Do i=6 To 1 By -1 /* loop through numbers */\n If m>=f.i Then Do /* f.i must be used */\n r=r||1 /* 1 into result */\n m=m-f.i /* subtract */\n End\n Else /* f.i is larger than the rest */\n r=r||0 /* 0 into result */\n End\n r=strip(r,'L','0') /* strip leading zeros */\n If r='' Then r='0' /* take care of 0 */\n Say right(n,2)': 'right(r,6) /* show result */\n End\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the first N Zeckendorf numbers. */\nnumeric digits 100000 /*just in case user gets real ka─razy. */\nparse arg N . /*let the user specify the upper limit.*/\nif N=='' | N==\",\" then n=20; w= length(N) /*Not specified? Then use the default.*/\[email protected]= 1 /*start the array with 1 and 2. */\[email protected]= 2; do #=3 until #>=N; p= #-1; pp= #-2 /*build a list of Fibonacci numbers. */\n @.#= @.p + @.pp /*sum the last two Fibonacci numbers. */\n end /*#*/ /* [↑] #: contains a Fibonacci list.*/\n\n do j=0 to N; parse var j x z /*task: process zero ──► N numbers.*/\n do k=# by -1 for #; _= @.k /*process all the Fibonacci numbers. */\n if x>=_ then do; z= z'1' /*is X>the next Fibonacci #? Append 1.*/\n x= x - _ /*subtract this Fibonacci # from index.*/\n end\n else z= z'0' /*append zero (0) to the Fibonacci #. */\n end /*k*/\n say ' Zeckendorf' right(j, w) \"=\" right(z+0, 30) /*display a number.*/\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "/*REXX program calculates and displays the first N Zeckendorf numbers. */\nnumeric digits 100000 /*just in case user gets real ka─razy. */\nparse arg N . /*let the user specify the upper limit.*/\nif N=='' | N==\",\" then n=20; w= length(N) /*Not specified? Then use the default.*/\nz=0 /*the index of a Zeckendorf number. */\n do j=0 until z>N; _=x2b( d2x(j) ) /*task: process zero ──► N. */\n if pos(11, _) \\== 0 then iterate /*are there two consecutive ones (1s) ?*/\n say ' Zeckendorf' right(z, w) \"=\" right(_+0, 30) /*display a number.*/\n z= z + 1 /*bump the Zeckendorf number counter.*/\n end /*j*/ /*stick a fork in it, we're all done. */\n", "language": "REXX" }, { "code": "# Project : Zeckendorf number representation\n\nsee \"0 0\" + nl\nfor n = 1 to 20\n see \"\" + n + \" \" + zeckendorf(n) + nl\nnext\n\nfunc zeckendorf(n)\n fib = list(45)\n fib[1] = 1\n fib[2] = 1\n i = 2\n o = \"\"\n while fib[i] <= n\n i = i + 1\n fib[i] = fib[i-1] + fib[i-2]\n end\n while i != 2\n i = i - 1\n if n >= fib[i]\n o = o + \"1\"\n n = n - fib[i]\n else\n o = o + \"0\"\n ok\n end\n return o\n", "language": "Ring" }, { "code": "def zeckendorf\n return to_enum(__method__) unless block_given?\n x = 0\n loop do\n bin = x.to_s(2)\n yield bin unless bin.include?(\"11\")\n x += 1\n end\nend\n\nzeckendorf.take(21).each_with_index{|x,i| puts \"%3d: %8s\"% [i, x]}\n", "language": "Ruby" }, { "code": "def zeckendorf(n)\n return 0 if n.zero?\n fib = [1,2]\n fib << fib[-2] + fib[-1] while fib[-1] < n\n dig = \"\"\n fib.reverse_each do |f|\n if f <= n\n dig, n = dig + \"1\", n - f\n else\n dig += \"0\"\n end\n end\n dig.to_i\nend\n\nfor i in 0..20\n puts '%3d: %8d' % [i, zeckendorf(i)]\nend\n", "language": "Ruby" }, { "code": "def zeckendorf(n)\n 0.step.lazy.map { |x| x.to_s(2) }.reject { |z| z.include?(\"11\") }.first(n)\nend\n\nzeckendorf(21).each_with_index{ |x,i| puts \"%3d: %8s\"% [i, x] }\n", "language": "Ruby" }, { "code": "use std::collections::VecDeque;\n\nfn fibonacci(n: u32) -> u32 {\n match n {\n 0 => 0,\n 1 => 1,\n _ => fibonacci(n - 1) + fibonacci(n - 2),\n }\n}\n\nfn zeckendorf(num: u32) -> String {\n let mut fibonacci_numbers = VecDeque::new();\n let mut fib_position = 2;\n let mut current_fibonacci_num = fibonacci(fib_position);\n\n while current_fibonacci_num <= num {\n fibonacci_numbers.push_front(current_fibonacci_num);\n fib_position += 1;\n current_fibonacci_num = fibonacci(fib_position);\n }\n\n let mut temp = num;\n let mut output = String::new();\n\n for item in fibonacci_numbers {\n if item <= temp {\n output.push('1');\n temp -= item;\n } else {\n output.push('0');\n }\n }\n\n output\n}\n\nfn main() {\n for i in 1..=20 {\n let zeckendorf_representation = zeckendorf(i);\n println!(\"{} : {}\", i, zeckendorf_representation);\n }\n}\n", "language": "Rust" }, { "code": "def zNum( n:BigInt ) : String = {\n\n if( n == 0 ) return \"0\"\t// Short-circuit this and return zero if we were given zero\n\n\n val v = n.abs\n\n val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail.tail }\n\n\n def z( v:BigInt ) : List[BigInt] = if(v == 0) List() else {val m = fibs(fibs.indexWhere(_>v) - 1); m :: z(v-m)}\n\n val zv = z(v)\n\n // Walk the list of fibonacci numbers from the number that matches the most significant down to 1,\n // if the zeckendorf matchs then yield '1' otherwise '0'\n val s = (for( i <- (fibs.indexWhere(_==zv(0)) to 0 by -1) ) yield {\n\n if( zv.contains(fibs(i))) \"1\" else \"0\"\n\t\n }).mkString\n\n if( n < 0 ) \"-\" + s\t\t// Using a negative-sign instead of twos-complement\n else s\n}\n\n\n// A little test...\n(0 to 20) foreach( i => print( zNum(i) + \"\\n\" ) )\n", "language": "Scala" }, { "code": "(import (rnrs))\n\n(define (getFibList maxNum n1 n2 fibs)\n (if (> n2 maxNum)\n fibs\n (getFibList maxNum n2 (+ n1 n2) (cons n2 fibs))))\n\n(define (getZeckendorf num)\n (if (<= num 0)\n \"0\"\n (let ((fibs (getFibList num 1 2 (list 1))))\n (getZeckString \"\" num fibs))))\n\n(define (getZeckString zeck num fibs)\n (let* ((curFib (car fibs))\n (placeZeck (>= num curFib))\n (outString (string-append zeck (if placeZeck \"1\" \"0\")))\n (outNum (if placeZeck (- num curFib) num)))\n (if (null? (cdr fibs))\n outString\n (getZeckString outString outNum (cdr fibs)))))\n\n(let loop ((i 0))\n (when (<= i 20)\n (for-each\n (lambda (item)\n (display item))\n (list \"Z(\" i \"):\\t\" (getZeckendorf i)))\n (newline)\n (loop (+ i 1))))\n", "language": "Scheme" }, { "code": "func fib(n) is cached {\n n < 2 ? 1\n  : (fib(n-1) + fib(n-2))\n}\n\nfunc zeckendorf(n) {\n n == 0 && return '0'\n var i = 1\n ++i while (fib(i) <= n)\n gather {\n while (--i > 0) {\n var f = fib(i)\n f > n ? (take '0')\n  : (take '1'; n -= f)\n }\n }.join\n}\n\nfor n (0..20) {\n printf(\"%4d: %8s\\n\", n, zeckendorf(n))\n}\n", "language": "Sidef" }, { "code": "BEGIN\n INTEGER N, F0, F1, F2, D;\n N := 20;\n COMMENT CALCULATE D FROM ANY GIVEN N ;\n F1 := 1; F2 := 2; F0 := F1 + F2; D := 2;\n WHILE F0 < N DO BEGIN\n F1 := F2; F2 := F0; F0 := F1 + F2; D := D + 1;\n END;\n BEGIN\n COMMENT Sinclair ZX81 BASIC Solution ;\n TEXT Z1, S1;\n INTEGER I, J, Z;\n INTEGER ARRAY F(1:D); ! 10 dim f(6) ;\n F(1) := 1; ! 20 let f(1)=1 ;\n F(2) := 2; ! 30 let f(2)=2 ;\n FOR I := 3 STEP 1 UNTIL D DO BEGIN ! 40 for i=3 to 6 ;\n F(I) := F(I-2) + F(I-1); ! 50 let f(i)=f(i-2)+f(i-1) ;\n END; ! 60 next i ;\n FOR I := 0 STEP 1 UNTIL N DO BEGIN ! 70 for i=0 to 20 ;\n Z1 :- \"\"; ! 80 let z$=\"\" ;\n S1 :- \" \"; ! 90 let s$=\" \" ;\n Z := I; ! 100 let z=i ;\n FOR J := D STEP -1 UNTIL 1 DO BEGIN ! 110 for j=6 to 1 step -1 ;\n IF J=1 THEN S1 :- \"0\"; ! 120 if j=1 then let s$=\"0\" ;\n IF NOT (Z<F(J)) THEN BEGIN ! 130 if z<f(j) then goto 180 ;\n Z1 :- Z1 & \"1\"; ! 140 let z$=z$+\"1\" ;\n Z := Z-F(J); ! 150 let z=z-f(j) ;\n S1 :- \"0\"; ! 160 let s$=\"0\" ;\n END ELSE ! 170 goto 190 ;\n Z1 :- Z1 & S1; ! 180 let z$=z$+s$ ;\n END; ! 190 next j ;\n OUTINT(I, 0); OUTCHAR(' '); ! 200 print i ; !\" \"; !;\n IF I<10 THEN OUTCHAR(' '); ! 210 if i<10 then print \" \"; !;\n OUTTEXT(Z1); OUTIMAGE; ! 220 print z$ ;\n END; ! 230 next i ;\n END;\nEND\n", "language": "Simula" }, { "code": " 10 DIM F(6)\n 20 LET F(1)=1\n 30 LET F(2)=2\n 40 FOR I=3 TO 6\n 50 LET F(I)=F(I-2)+F(I-1)\n 60 NEXT I\n 70 FOR I=0 TO 20\n 80 LET Z$=\"\"\n 90 LET S$=\" \"\n100 LET Z=I\n110 FOR J=6 TO 1 STEP -1\n120 IF J=1 THEN LET S$=\"0\"\n130 IF Z<F(J) THEN GOTO 180\n140 LET Z$=Z$+\"1\"\n150 LET Z=Z-F(J)\n160 LET S$=\"0\"\n170 GOTO 190\n180 LET Z$=Z$+S$\n190 NEXT J\n200 PRINT I;\" \";\n210 IF I<10 THEN PRINT \" \";\n220 PRINT Z$\n230 NEXT I\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "val zeckList = fn from => fn to =>\n\n let\n open IntInf\n\n val rec npow = fn n => fn 0 => fromInt 1 | m => n* (npow n (m-1)) ;\n\n val fib = fn 0 => 1 | 1 => 1 | n => let val rec fb = fn x => fn y => fn 1=>y | n=> fb y (x+y) (n-1) in\n fb 0 1 n\n end;\n\n val argminfi = fn n => (* lowest k with fibonacci number over n *)\n let\n val rec afb = fn k => if fib k > n then k else afb (k+1)\n in\n afb 0\n end;\n\n val Zeck = fn n =>\n let\n val rec calzk = fn (0,z) => (0,z)\n | (n,z) => let val k = argminfi n in\n calzk ( n - fib (k-1) , z + (npow 10 (k-3) ) )\n\t\t\t\t end\n in\n #2 (calzk (n,0))\n end\n\n in\n List.tabulate (toInt ( to - from) ,\n fn i:Int.int => ( from + (fromInt i),\n\t Zeck ( from + (fromInt i) )))\nend;\n", "language": "Standard-ML" }, { "code": "List.app ( fn e => print ( (IntInf.toString (#1 e)) ^\" : \"^ (IntInf.toString (#2 e)) ^ \"\\n\" )) (zeckList 1 21) ;\n1 : 1\n2 : 10\n3 : 100\n4 : 101\n5 : 1000\n6 : 1001\n7 : 1010\n8 : 10000\n9 : 10001\n10 : 10010\n11 : 10100\n12 : 10101\n13 : 100000\n14 : 100001\n15 : 100010\n16 : 100100\n17 : 100101\n18 : 101000\n19 : 101001\n20 : 101010\n\nzeckList 0x21e320a3 0x21e320a4 ;\nval it = [(568533155, 100100100101001001001000000100100010100101)]:\n : (IntInf.int * IntInf.int) list\n", "language": "Standard-ML" }, { "code": "package require Tcl 8.5\n\n# Generates the Fibonacci sequence (starting at 1) up to the largest item that\n# is no larger than the target value. Could use tricks to precompute, but this\n# is actually a pretty cheap linear operation.\nproc fibseq target {\n set seq {}; set prev 1; set fib 1\n for {set n 1;set i 1} {$fib <= $target} {incr n} {\n\tfor {} {$i < $n} {incr i} {\n\t lassign [list $fib [incr fib $prev]] prev fib\n\t}\n\tif {$fib <= $target} {\n\t lappend seq $fib\n\t}\n }\n return $seq\n}\n\n# Produce the given Zeckendorf number.\nproc zeckendorf n {\n # Special case: only value that begins with 0\n if {$n == 0} {return 0}\n set zs {}\n foreach f [lreverse [fibseq $n]] {\n\tlappend zs [set z [expr {$f <= $n}]]\n\tif {$z} {incr n [expr {-$f}]}\n }\n return [join $zs \"\"]\n}\n", "language": "Tcl" }, { "code": "for {set i 0} {$i <= 20} {incr i} {\n puts [format \"%2d:%9s\" $i [zeckendorf $i]]\n}\n", "language": "Tcl" }, { "code": "set -- 2 1\nx=-1\nwhile [ $((x += 1)) -le 20 ]\ndo\n [ $x -gt $1 ] && set -- $(($2 + $1)) \"$@\"\n n=$x zeck=''\n for fib\n do\n zeck=$zeck$((n >= fib && (n -= fib) + 1))\n done\n echo \"$x: ${zeck#0}\"\ndone\n", "language": "UNIX-Shell" }, { "code": "fn main() {\n for i := 0; i <= 20; i++ {\n println(\"${i:2} ${zeckendorf(i):7b}\")\n }\n}\n\nfn zeckendorf(n int) int {\n // initial arguments of fib0 = 1 and fib1 = 1 will produce\n // the Fibonacci sequence {1, 2, 3,..} on the stack as successive\n // values of fib1.\n _, set := zr(1, 1, n, 0)\n return set\n}\n\nfn zr(fib0 int, fib1 int, n int, bit u32) (int, int) {\n mut set := 0\n mut remaining := 0\n if fib1 > n {\n return n, 0\n }\n // recurse.\n // construct sequence on the way in, construct ZR on the way out.\n remaining, set = zr(fib1, fib0+fib1, n, bit+1)\n if fib1 <= remaining {\n set |= 1 << bit\n remaining -= fib1\n }\n return remaining, set\n}\n", "language": "V-(Vlang)" }, { "code": "Private Function zeckendorf(ByVal n As Integer) As Integer\n Dim r As Integer: r = 0\n Dim c As Integer\n Dim fib As New Collection\n fib.Add 1\n fib.Add 1\n Do While fib(fib.Count) < n\n fib.Add fib(fib.Count - 1) + fib(fib.Count)\n Loop\n For i = fib.Count To 2 Step -1\n c = n >= fib(i)\n r = r + r - c\n n = n + c * fib(i)\n Next i\n zeckendorf = r\nEnd Function\n\nPublic Sub main()\n Dim i As Integer\n For i = 0 To 20\n Debug.Print Format(i, \"@@\"); \":\"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), \"@@@@@@@\")\n Next i\nEnd Sub\n", "language": "VBA" }, { "code": "Function Zeckendorf(n)\n\tnum = n\n\tSet fibonacci = CreateObject(\"System.Collections.Arraylist\")\n\tfibonacci.Add 1 : fibonacci.Add 2\n\ti = 1\n\tDo While fibonacci(i) < num\n\t\tfibonacci.Add fibonacci(i) + fibonacci(i-1)\n\t\ti = i + 1\n\tLoop\n\ttmp = \"\"\n\tFor j = fibonacci.Count-1 To 0 Step -1\n\t\tIf fibonacci(j) <= num And (tmp = \"\" Or Left(tmp,1) <> \"1\") Then\n\t\t\ttmp = tmp & \"1\"\n\t\t\tnum = num - fibonacci(j)\n\t\tElse\n\t\t\ttmp = tmp & \"0\"\n\t\tEnd If\n\tNext\n\tZeckendorf = CLng(tmp)\nEnd Function\n\n'testing the function\nFor k = 0 To 20\n\tWScript.StdOut.WriteLine k & \": \" & Zeckendorf(k)\nNext\n", "language": "VBScript" }, { "code": "import \"./fmt\" for Fmt\n\nvar LIMIT = 46 // to stay within range of signed 32 bit integer\n\nvar fibonacci = Fn.new { |n|\n if (n < 2 || n > LIMIT) Fiber.abort(\"n must be between 2 and %(LIMIT)\")\n var fibs = List.filled(n, 1)\n for (i in 2...n) fibs[i] = fibs[i - 1] + fibs[i - 2]\n return fibs\n}\n\nvar fibs = fibonacci.call(LIMIT)\n\nvar zeckendorf = Fn.new { |n|\n if (n < 0) Fiber.abort(\"n must be non-negative\")\n if (n < 2) return n.toString\n var lastFibIndex = 1\n for (i in 2..LIMIT) {\n if (fibs[i] > n) {\n lastFibIndex = i - 1\n break\n }\n }\n n = n - fibs[lastFibIndex]\n lastFibIndex = lastFibIndex - 1\n var zr = \"1\"\n for (i in lastFibIndex..1) {\n if (fibs[i] <= n) {\n zr = zr + \"1\"\n n = n - fibs[i]\n } else {\n zr = zr + \"0\"\n }\n }\n return zr\n}\n\nSystem.print(\" n z\")\nfor (i in 0..20) Fmt.print(\"$2d : $s\", i, zeckendorf.call(i))\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes; \\intrinsic 'code' declarations\n\nproc Zeckendorf(N); \\Display Zeckendorf number (N <= 20)\nint N;\nint Fib, LZ, I;\n[Fib:= [1, 2, 3, 5, 8, 13]; \\Fibonacci sequence\nLZ:= true; \\suppress leading zeros\nfor I:= 5 downto 1 do\n [if N >= Fib(I) then [N:= N-Fib(I); ChOut(0, ^1); LZ:= false]\n else ChOut(0, if LZ then ^ else ^0);\n ];\nChOut(0, N+^0); \\output final digit, which can be 0\n];\n\nint N;\n[for N:= 0 to 20 do\n [if N<10 then ChOut(0,^ ); IntOut(0, N); Text(0, \": \");\n Zeckendorf(N); CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "sub Zeckendorf(n)\n\tlocal i, n$, c\n\t\n\tdo\n\t\tn$ = bin$(i)\n\t\tif not instr(n$,\"11\") then\n\t\t\tprint c,\":\\t\",n$\n\t\t\tif c = n break\n\t\t\tc = c + 1\t\t\t\n\t\tend if\n\t\ti = i + 1\n\tloop\nend sub\n\nZeckendorf(20)\n", "language": "Yabasic" }, { "code": " // return powers (0|1) of fib sequence (1,2,3,5,8...) that sum to n\nfcn zeckendorf(n){ //-->String of 1s & 0s, no consecutive 1's\n if(n<=0) return(\"0\");\n fibs:=fcn(ab){ ab.append(ab.sum()).pop(0) }.fp(L(1,2));\n (0).pump(*,List,fibs,'wrap(fib){ if(fib>n)Void.Stop else fib })\n .reverse()\n .pump(String,fcn(fib,rn){\n if(fib>rn.value)\"0\" else { rn.set(rn.value-fib); \"1\" } }.fp1(Ref(n)))\n}\n", "language": "Zkl" }, { "code": "[0..20].pump(Console.println,fcn(n){ \"%2d: %8s\".fmt(n,zeckendorf(n)) });\n", "language": "Zkl" } ]
Zeckendorf-number-representation
[ { "code": "---\ncategory:\n- Simple\nfrom: http://rosettacode.org/wiki/Zero_to_the_zero_power\n", "language": "00-META" }, { "code": "Some computer programming languages are not exactly consistent &nbsp; (with other computer programming languages) &nbsp; \n<br>when &nbsp; ''raising zero to the zeroth power'': &nbsp; &nbsp; <b><big>0<sup>0</sup></big></b>\n\n\n;Task:\nShow the results of raising &nbsp; zero &nbsp; to the &nbsp; zeroth &nbsp; power.\n\n\nIf your computer language objects to &nbsp; &nbsp; <big> '''0**0''' </big> &nbsp; &nbsp; or &nbsp; &nbsp; <big> '''0^0''' </big> &nbsp; &nbsp; at compile time, &nbsp; you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''<br>\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: [[wp:Zero_to_the_power_of_zero#History|Zero to the power of zero]]. \n* The Wiki entry: [[wp:Zero_to_the_power_of_zero#History|Zero to the power of zero: History]].\n* The MathWorld™ entry: [http://mathworld.wolfram.com/ExponentLaws.html exponent laws].\n** Also, in the above MathWorld™ entry, see formula ('''9'''): <math>x^0=1</math>.\n* The OEIS entry: [https://oeis.org/wiki/The_special_case_of_zero_to_the_zeroth_power The special case of zero to the zeroth power]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "print(0 ^ 0)\n", "language": "11l" }, { "code": "0 0 ^ .\n", "language": "8th" }, { "code": "INCLUDE \"D2:REAL.ACT\" ;from the Action! Tool Kit\n\nPROC Main()\n REAL z,res\n\n Put(125) PutE() ;clear the screen\n\n IntToReal(0,z)\n Power(z,z,res)\n\n PrintR(z) Print(\"^\")\n PrintR(z) Print(\"=\")\n PrintRE(res)\nRETURN\n", "language": "Action-" }, { "code": "with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO,\n Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO,\n Ada.Long_Long_Float_Text_IO;\nuse Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Integer_Text_IO,\n Ada.Long_Long_Integer_Text_IO, Ada.Float_Text_IO, Ada.Long_Float_Text_IO,\n Ada.Long_Long_Float_Text_IO;\n\nprocedure Test5 is\n\n I : Integer := 0;\n LI : Long_Integer := 0;\n LLI : Long_Long_Integer := 0;\n F : Float := 0.0;\n LF : Long_Float := 0.0;\n LLF : Long_Long_Float := 0.0;\n Zero : Natural := 0;\n\nbegin\n Put (\"Integer 0^0 = \");\n Put (I ** Zero, 2); New_Line;\n Put (\"Long Integer 0^0 = \");\n Put (LI ** Zero, 2); New_Line;\n Put (\"Long Long Integer 0^0 = \");\n Put (LLI ** Zero, 2); New_Line;\n Put (\"Float 0.0^0 = \");\n Put (F ** Zero); New_Line;\n Put (\"Long Float 0.0^0 = \");\n Put (LF ** Zero); New_Line;\n Put (\"Long Long Float 0.0^0 = \");\n Put (LLF ** Zero); New_Line;\nend Test5;\n", "language": "Ada" }, { "code": "print( ( 0 ^ 0, newline ) )\n", "language": "ALGOL-68" }, { "code": " 0*0\n1\n", "language": "APL" }, { "code": " return 0 ^ 0\n", "language": "AppleScript" }, { "code": "1.0\n", "language": "AppleScript" }, { "code": "print 0 ^ 0\nprint 0.0 ^ 0\n", "language": "Arturo" }, { "code": "write(\"0 ^ 0 = \", 0 ** 0);\n", "language": "Asymptote" }, { "code": "MsgBox % 0 ** 0\n", "language": "AutoHotkey" }, { "code": "# syntax: GAWK -f ZERO_TO_THE_ZERO_POWER.AWK\nBEGIN {\n print(0 ^ 0)\n exit(0)\n}\n", "language": "AWK" }, { "code": "PRINT POW(0, 0)\n", "language": "BaCon" }, { "code": "print \"0 ^ 0 = \"; 0 ^ 0\n", "language": "BASIC256" }, { "code": " PRINT 0^0\n", "language": "BBC-BASIC" }, { "code": "0 ^ 0\n", "language": "Bc" }, { "code": "\"PDPF\"4#@(0F0FYP)@\n", "language": "Befunge" }, { "code": "0⋆0\n", "language": "BQN" }, { "code": "0^0\n", "language": "Bracmat" }, { "code": "blsq ) 0.0 0.0?^\n1.0\nblsq ) 0 0?^\n1\n", "language": "Burlesque" }, { "code": "#include <stdio.h>\n#include <math.h>\n#include <complex.h>\n\nint main()\n{\n\tprintf(\"0 ^ 0 = %f\\n\", pow(0,0));\n double complex c = cpow(0,0);\n\tprintf(\"0+0i ^ 0+0i = %f+%fi\\n\", creal(c), cimag(c));\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <iostream>\n#include <cmath>\n#include <complex>\n\nint main()\n{\n std::cout << \"0 ^ 0 = \" << std::pow(0,0) << std::endl;\n std::cout << \"0+0i ^ 0+0i = \" <<\n std::pow(std::complex<double>(0),std::complex<double>(0)) << std::endl;\n return 0;\n}\n", "language": "C++" }, { "code": "using System;\n\nnamespace ZeroToTheZeroeth\n{\n class Program\n {\n static void Main(string[] args)\n {\n double k = Math.Pow(0, 0);\n Console.Write(\"0^0 is {0}\", k);\n }\n }\n}\n", "language": "C-sharp" }, { "code": "10 print \"0 ^ 0 = \";0^0\n", "language": "Chipmunk-Basic" }, { "code": "start_up = proc ()\n zz_int: int := 0 ** 0\n zz_real: real := 0.0 ** 0.0\n\n po: stream := stream$primary_output()\n stream$putl(po, \"integer 0**0: \" || int$unparse(zz_int))\n stream$putl(po, \"real 0**0: \" || f_form(zz_real, 1, 1))\nend start_up\n", "language": "CLU" }, { "code": "identification division.\nprogram-id. zero-power-zero-program.\ndata division.\nworking-storage section.\n77 n pic 9.\nprocedure division.\n compute n = 0**0.\n display n upon console.\n stop run.\n", "language": "COBOL" }, { "code": "<cfset zeroPowerTag = 0^0>\n<cfoutput>\"#zeroPowerTag#\"</cfoutput>\n", "language": "ColdFusion" }, { "code": "<cfscript>\n zeroPower = 0^0;\n writeOutput( zeroPower );\n</cfscript>\n", "language": "ColdFusion" }, { "code": "puts \"Int32: #{0_i32**0_i32}\"\nputs \"Negative Int32: #{-0_i32**-0_i32}\"\nputs \"Float32: #{0_f32**0_f32}\"\nputs \"Negative Float32: #{-0_f32**-0_f32}\"\n", "language": "Crystal" }, { "code": "void main() {\n import std.stdio, std.math, std.bigint, std.complex;\n\n writeln(\"Int: \", 0 ^^ 0);\n writeln(\"Ulong: \", 0UL ^^ 0UL);\n writeln(\"Float: \", 0.0f ^^ 0.0f);\n writeln(\"Double: \", 0.0 ^^ 0.0);\n writeln(\"Real: \", 0.0L ^^ 0.0L);\n writeln(\"pow: \", pow(0, 0));\n writeln(\"BigInt: \", 0.BigInt ^^ 0);\n writeln(\"Complex: \", complex(0.0, 0.0) ^^ 0);\n}\n", "language": "D" }, { "code": "import 'dart:math';\n\nvoid main() {\n var resul = pow(0, 0);\n print(\"0 ^ 0 = $resul\");\n}\n", "language": "Dart" }, { "code": "0 0^p\n", "language": "Dc" }, { "code": "print pow 0 0\n", "language": "EasyLang" }, { "code": ";; trying the 16 combinations\n;; all return the integer 1\n\n(lib 'bigint)\n(define zeroes '(integer: 0 inexact=float: 0.000 complex: 0+0i bignum: #0))\n(for* ((z1 zeroes) (z2 zeroes)) (write (expt z1 z2)))\n → 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", "language": "EchoLisp" }, { "code": "print (0^0)\n", "language": "Eiffel" }, { "code": "import extensions;\n\npublic program()\n{\n console.printLine(\"0^0 is \",0.power(0))\n}\n", "language": "Elena" }, { "code": ":math.pow(0,0)\n", "language": "Elixir" }, { "code": "(expt 0 0)\n", "language": "Emacs-Lisp" }, { "code": "writeLine(0 ** 0) # an integer\nwriteLine(0.0 ** 0.0) # a real\n", "language": "EMal" }, { "code": ".....\nPRINT(0^0)\n.....\n", "language": "ERRE" }, { "code": "USING: math.functions.private ; ! ^complex\n0 0 ^\nC{ 0 0 } C{ 0 0 } ^complex\n", "language": "Factor" }, { "code": "/* created by Aykayayciti Earl Lamont Montgomery\nApril 9th, 2018 */\n\nx = 0\ny = 0\nz = x**y\n> \"z=\", z\n", "language": "Falcon" }, { "code": "0^0\n", "language": "Fermat" }, { "code": "0e 0e f** f.\n", "language": "Forth" }, { "code": ": ^0 DROP 1 ;\n", "language": "Forth" }, { "code": "program zero\ndouble precision :: i, j\ndouble complex :: z1, z2\ni = 0.0D0\nj = 0.0D0\nz1 = (0.0D0,0.0D0)\nz2 = (0.0D0,0.0D0)\nwrite(*,*) 'When integers are used, we have 0^0 = ', 0**0\nwrite(*,*) 'When double precision numbers are used, we have 0.0^0.0 = ', i**j\nwrite(*,*) 'When complex numbers are used, we have (0.0+0.0i)^(0.0+0.0i) = ', z1**z2\nend program\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nPrint \"0 ^ 0 =\"; 0 ^ 0\nSleep\n", "language": "FreeBASIC" }, { "code": "println[0^0]\n", "language": "Frink" }, { "code": "window 1\n\nprint 0^0\n\nHandleEvents\n", "language": "FutureBasic" }, { "code": "Public Sub Main()\n\nPrint 0 ^ 0\n\nEnd\n", "language": "Gambas" }, { "code": "0^0;\n", "language": "GAP" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"math/cmplx\"\n)\n\nfunc main() {\n fmt.Println(\"float64: \", math.Pow(0, 0))\n var b big.Int\n fmt.Println(\"big integer:\", b.Exp(&b, &b, nil))\n fmt.Println(\"complex: \", cmplx.Pow(0, 0))\n}\n", "language": "Go" }, { "code": "0 0?\n", "language": "Golfscript" }, { "code": "println 0**0\n", "language": "Groovy" }, { "code": "PRINT 0^0\n", "language": "GW-BASIC" }, { "code": "import Data.Complex ( Complex((:+)) )\n\nmain :: IO ()\nmain = mapM_ print [\n 0 ^ 0,\n 0.0 ^ 0,\n 0 ^^ 0,\n 0 ** 0,\n (0 :+ 0) ^ 0,\n (0 :+ 0) ** (0 :+ 0)\n ]\n", "language": "Haskell" }, { "code": "F64 a = 0 ` 0;\nPrint(\"0 ` 0 = %5.3f\\n\", a);\n", "language": "HolyC" }, { "code": "procedure main()\n write(0^0)\nend\n", "language": "Icon" }, { "code": " 0 ^ 0\n1\n", "language": "J" }, { "code": " */''\n1\n", "language": "J" }, { "code": "System.out.println(Math.pow(0, 0));\n", "language": "Java" }, { "code": "> Math.pow(0, 0);\n1\n", "language": "JavaScript" }, { "code": "> 0**0\n1\n", "language": "JavaScript" }, { "code": "puts(Math.pow(0,0));\n", "language": "Jsish" }, { "code": "using Printf\n\nconst types = (Complex, Float64, Rational, Int, Bool)\n\nfor Tb in types, Te in types\n zb, ze = zero(Tb), zero(Te)\n r = zb ^ ze\n @printf(\"%10s ^ %-10s = %7s ^ %-7s = %-12s (%s)\\n\", Tb, Te, zb, ze, r, typeof(r))\nend\n", "language": "Julia" }, { "code": " 0^0\n1.0\n", "language": "K" }, { "code": ":mypower\n dup not (\n [ drop sign dup 0 equal [ drop 1 ] if ]\n [ power ]\n ) if\n;\n\n0 0 mypower print nl\n\n\"End \" input\n", "language": "Klingphix" }, { "code": "import kotlin.math.pow\n\nfun main() {\n println(0.0.pow(0))\n}\n", "language": "Kotlin" }, { "code": "{pow 0 0}\n-> 1\n{exp 0 0}\n-> 1\n", "language": "Lambdatalk" }, { "code": "data:\nx is number\n\nprocedure:\nraise 0 to 0 in x\ndisplay x lf\n", "language": "LDPL" }, { "code": "'********\nprint 0^0\n'********\n", "language": "Liberty-BASIC" }, { "code": "print 0🠅0\n", "language": "Locomotive-Basic" }, { "code": "print(0^0)\n", "language": "Lua" }, { "code": "Module Checkit {\n x=0\n y=0\n Print x**y=1, x^y=1 ' True True\n}\nCheckit\n", "language": "M2000-Interpreter" }, { "code": "0^0\n", "language": "Maple" }, { "code": "0^0.0\n", "language": "Maple" }, { "code": "0^0\n", "language": "Mathematica" }, { "code": "0^0\ncomplex(0,0)^0\n", "language": "MATLAB" }, { "code": "0^0;\n", "language": "Maxima" }, { "code": ":- module zero_to_the_zero_power.\n:- interface.\n\n:- import_module io.\n\n:- pred main(io::di, io::uo) is det.\n\n:- implementation.\n\n:- import_module float, int, integer, list, string.\n\nmain(!IO) :-\n io.format(\" int.pow(0, 0) = %d\\n\", [i(pow(0, 0))], !IO),\n io.format(\"integer.pow(zero, zero) = %s\\n\",\n [s(to_string(pow(zero, zero)))], !IO),\n io.format(\" float.pow(0.0, 0) = %.1f\\n\", [f(pow(0.0, 0))], !IO).\n\n:- end_module zero_to_the_zero_power.\n", "language": "Mercury" }, { "code": "TextWindow.WriteLine(Math.Power(0,0))\n", "language": "Microsoft-Small-Basic" }, { "code": "0 0 pow puts\n", "language": "Min" }, { "code": "print \"The result of zero to the zero power is \" + 0^0\n", "language": "MiniScript" }, { "code": "10 PRINT \"0 ^ 0 = \"; 0 ^ 0\n", "language": "MSX-Basic" }, { "code": "println 0^0\n", "language": "Nanoquery" }, { "code": "/**\n Zero to the zeroth power, in Neko\n*/\n\nvar math_pow = $loader.loadprim(\"std@math_pow\", 2)\n\n$print(math_pow(0, 0), \"\\n\")\n", "language": "Neko" }, { "code": "x=0\nSay '0**0='||x**x\n", "language": "NetRexx" }, { "code": "(pow 0 0)\n", "language": "NewLISP" }, { "code": " 0 0.0 o outer power 0 0.0 o\n+--+--+--+\n| 1|1.| 1|\n+--+--+--+\n|1.|1.|1.|\n+--+--+--+\n| 1|1.| 1|\n+--+--+--+\n", "language": "Nial" }, { "code": "import math\n\necho pow(0.0, 0.0) # Floating point exponentiation.\necho 0 ^ 0 # Integer exponentiation.\n", "language": "Nim" }, { "code": "0 0 pow println\n", "language": "Oforth" }, { "code": "(print \"0^0: \" (expt 0 0))\n(print \"0.0^0: \" (expt (inexact 0) 0))\n", "language": "Ol" }, { "code": "/**********************************************************************\n* 21.04.2014 Walter Pachl\n**********************************************************************/\nSay 'rxCalcpower(0,0) ->' rxCalcpower(0,0)\nSay '0**0 ->' 0**0\n::requires rxmath library\n", "language": "OoRexx" }, { "code": "echo (0^0);\n", "language": "Openscad" }, { "code": "0^0\n0.^0\n0^0.\n", "language": "PARI-GP" }, { "code": "program ZToZ;\nuses\n math;\nbegin\n write('0.0 ^ 0 :',IntPower(0.0,0):4:2);\n writeln(' 0.0 ^ 0.0 :',Power(0.0,0.0):4:2);\nend.\n", "language": "Pascal" }, { "code": "print 0 ** 0, \"\\n\";\n\nuse Math::Complex;\n\nprint cplx(0,0) ** cplx(0,0), \"\\n\";\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #0000FF;\">?</span><span style=\"color: #7060A8;\">power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">requires</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"0.8.4\"</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #000080;font-style:italic;\">-- (now fixed/crashes on earlier versions)</span>\n <span style=\"color: #008080;\">include</span> <span style=\"color: #004080;\">complex</span><span style=\"color: #0000FF;\">.</span><span style=\"color: #000000;\">e</span>\n <span style=\"color: #004080;\">complex</span> <span style=\"color: #000000;\">a</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_new</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">b</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_power</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">sa</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">a</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">),</span>\n <span style=\"color: #000000;\">sb</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">complex_sprint</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">b</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #004600;\">true</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #7060A8;\">printf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"%s ^ %s = %s\\n\"</span><span style=\"color: #0000FF;\">,{</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sa</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">sb</span><span style=\"color: #0000FF;\">})</span>\n<!--\n", "language": "Phix" }, { "code": "def mypower\n dup not if\n . sign dup 0 == if . 1 endif\n else\n power\n endif\nenddef\n\n0 0 mypower print\n", "language": "Phixmonti" }, { "code": "<?php\necho pow(0,0);\necho 0 ** 0; // PHP 5.6+ only\n?>\n", "language": "PHP" }, { "code": "(** 0 0)\n", "language": "PicoLisp" }, { "code": "write( pow(0, 0) +\"\\n\" );\n", "language": "Pike" }, { "code": " zhz: Proc Options(Main);\n Dcl a dec float(10) Init(1);\n Dcl b dec float(10) Init(0);\n Put skip list('1**0=',a**b);\n Put skip list('0**1=',b**a);\n Put skip list('0**0=',b**b);\n End;\n", "language": "PL-I" }, { "code": "To run:\nStart up.\nPut 0 into a number.\nRaise the number to 0.\nConvert the number to a string.\nWrite the string to the console.\nWait for the escape key.\nShut down.\n", "language": "Plain-English" }, { "code": "Write-Host \"0 ^ 0 = \" ([math]::pow(0,0))\n", "language": "PowerShell" }, { "code": "If OpenConsole()\n PrintN(\"Zero to the zero power is \" + Pow(0,0))\n PrintN(\"\")\n PrintN(\"Press any key to close the console\")\n Repeat: Delay(10) : Until Inkey() <> \"\"\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "num-expt(0, 0)\n", "language": "Pyret" }, { "code": "from decimal import Decimal\nfrom fractions import Fraction\nfrom itertools import product\n\nzeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]\nfor i, j in product(zeroes, repeat=2):\n try:\n ans = i**j\n except:\n ans = '<Exception raised>'\n print(f'{i!r:>15} ** {j!r:<15} = {ans!r}')\n", "language": "Python" }, { "code": "from decimal import Decimal\nfrom fractions import Fraction\nfor n in (Decimal(0), Fraction(0, 1), complex(0), float(0), int(0)):\n\ttry:\n\t\tn1 = n**n\n\texcept:\n\t\tn1 = '<Raised exception>'\n\ttry:\n\t\tn2 = pow(n, n)\n\texcept:\n\t\tn2 = '<Raised exception>'\n\tprint('%8s: ** -> %r; pow -> %r' % (n.__class__.__name__, n1, n2))\n", "language": "Python" }, { "code": "Print 0 ^ 0\n", "language": "QB64" }, { "code": "i% = 0 'Integer\nl& = 0 'Long integer\ns! = 0.0 'Single precision floating point\nd# = 0.0 'Double precision floating point\nb` = 0 '_Bit\nbb%% = 0 '_Byte\nisf&& = 0 '_Integer64\n\nPrint i% ^ i%\nPrint l& ^ l&\nPrint s! ^ s!\nPrint d# ^ d#\nPrint b` ^ b`\nPrint bb%% ^ bb%%\nPrint isf&& ^ isf&&\n", "language": "QB64" }, { "code": "PRINT \"0 ^ 0 =\"; 0 ^ 0\n", "language": "QBasic" }, { "code": "/O> 0 0 **\n...\n\nStack: 1\n", "language": "Quackery" }, { "code": "print(0^0)\n", "language": "R" }, { "code": "#lang racket\n;; as many zeros as I can think of...\n(define zeros (list\n 0 ; unspecified number type\n 0. ; hinted as float\n #e0 ; explicitly exact\n #i0 ; explicitly inexact\n 0+0i ; exact complex\n 0.+0.i ; float inexact\n ))\n(for*((z zeros) (p zeros))\n (printf \"(~a)^(~a) = ~s~%\" z p\n (with-handlers [(exn:fail:contract:divide-by-zero? exn-message)]\n (expt z p))))\n", "language": "Racket" }, { "code": "say ' type n n**n exp(n,n)';\nsay '-------- -------- -------- --------';\n\nfor 0, 0.0, FatRat.new(0), 0e0, 0+0i {\n printf \"%8s %8s %8s %8s\\n\", .^name, $_, $_**$_, exp($_,$_);\n}\n", "language": "Raku" }, { "code": "Red[]\nprint 0 ** 0\nprint power 0 0\nprint math [0 ** 0]\n", "language": "Red" }, { "code": "echo pow(0,0)\n// 1\n", "language": "Relation" }, { "code": "/*REXX program shows the results of raising zero to the zeroth power.*/\nsay '0 ** 0 (zero to the zeroth power) ───► ' 0**0\n", "language": "REXX" }, { "code": "x = 0\ny = 0\nz = pow(x,y)\nsee \"z=\" + z + nl # z=1\n", "language": "Ring" }, { "code": "require 'bigdecimal'\n\n[0, 0.0, Complex(0), Rational(0), BigDecimal(\"0\")].each do |n|\n printf \"%10s: ** -> %s\\n\" % [n.class, n**n]\nend\n", "language": "Ruby" }, { "code": "print \"0 ^ 0 = \"; 0 ^ 0\n", "language": "Run-BASIC" }, { "code": "fn main() {\n println!(\"{}\",0u32.pow(0));\n}\n", "language": "Rust" }, { "code": "print(0^0);\n", "language": "S-lang" }, { "code": " assert(math.pow(0, 0) == 1, \"Scala blunder, should go back to school !\")\n", "language": "Scala" }, { "code": "(display (expt 0 0)) (newline)\n(display (expt 0.0 0.0)) (newline)\n(display (expt 0+0i 0+0i)) (newline)\n", "language": "Scheme" }, { "code": "$ include \"seed7_05.s7i\";\n include \"float.s7i\";\n include \"complex.s7i\";\n\nconst proc: main is func\n begin\n writeln(\"0 ** 0 = \" <& 0 ** 0);\n writeln(\"0.0 ** 0 = \" <& 0.0 ** 0);\n writeln(\"0.0 ** 0.0 = \" <& 0.0 ** 0.0);\n writeln(\"0.0+0i ** 0 = \" <& complex(0.0) ** 0);\n end func;\n", "language": "Seed7" }, { "code": "set a to 0\nset b to 0\n\nput a to the power of b\n// Prints: 1\n", "language": "SenseTalk" }, { "code": "[0, Complex(0, 0)].each {|n|\n say n**n\n}\n", "language": "Sidef" }, { "code": "say 0.root(0).pow(0) # => 1\nsay ((0**(1/0))**0) # => 1\n", "language": "Sidef" }, { "code": "PRINT 0**0\n", "language": "Sinclair-ZX81-BASIC" }, { "code": "0 raisedTo: 0\n0.0 raisedTo: 0.0\n", "language": "Smalltalk" }, { "code": "PRINT 0^0\n", "language": "Smart-BASIC" }, { "code": "\tOUTPUT = (0 ** 0)\nEND\n", "language": "SNOBOL4" }, { "code": "SQL> select power(0,0) from dual;\n", "language": "SQL" }, { "code": ". display 0^0\n1\n", "language": "Stata" }, { "code": "import Darwin\nprint(pow(0.0,0.0))\n", "language": "Swift" }, { "code": " (0^0) []\n", "language": "Symsyn" }, { "code": "% expr 0**0\n1\n% expr 0.0**0.0\n1.0\n", "language": "Tcl" }, { "code": "0 Yx 0 =\n", "language": "TI-SR-56" }, { "code": "PRINT \"0 ^ 0 =\"; 0 ^ 0\nEND\n", "language": "True-BASIC" }, { "code": "> out (pow 0 0) endl console\n1.0\n", "language": "Ursa" }, { "code": "// Zero to the zero power, in V\n// Tectonics: v run zero-to-the-zero-power.v\nmodule main\nimport math\n\n// starts here\n// V does not include an exponentiation operator, but uses a math module\npub fn main() {\n println(math.pow(0, 0))\n}\n", "language": "V-(Vlang)" }, { "code": "Public Sub zero()\n x = 0\n y = 0\n z = 0 ^ 0\n Debug.Print \"z =\"; z\nEnd Sub\n", "language": "VBA" }, { "code": "WScript.Echo 0 ^ 0\n", "language": "VBScript" }, { "code": "module main;\n initial begin\n $display(\"0 ^ 0 = \", 0**0);\n $finish ;\n end\nendmodule\n", "language": "Verilog" }, { "code": "Module Program\n Sub Main()\n Console.Write(0^0)\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "System.print(0.pow(0))\n", "language": "Wren" }, { "code": "PROGRAM\t\"progname\"\nVERSION\t\"0.0000\"\n\nIMPORT\t\"xma\" 'required for POWER\n\nDECLARE FUNCTION Entry ()\n\nFUNCTION Entry ()\n PRINT \"0 ^ 0 = \"; 0 ** 0\n PRINT \"0 ^ 0 = \"; POWER(0, 0)\nEND FUNCTION\nEND PROGRAM\n", "language": "XBasic" }, { "code": "XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz\n[1] (expt 0 0)\n\n1\n[2]\n", "language": "XLISP" }, { "code": "RlOut(0, Pow(0., 0.))\n", "language": "XPL0" }, { "code": "const std = @import(\"std\");\n\npub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n try stdout.print(\"0^0 = {d:.8}\\n\", .{std.math.pow(f32, 0, 0)});\n}\n", "language": "Zig" }, { "code": "(0.0).pow(0) //--> 1.0\nvar BN=Import(\"zklBigNum\"); // big ints\nBN(0).pow(0) //--> 1\n", "language": "Zkl" }, { "code": "PRINT 0↑0\n", "language": "ZX-Spectrum-Basic" } ]
Zero-to-the-zero-power
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Zig-zag_matrix\nnote: Matrices\n", "language": "00-META" }, { "code": ";Task:\nProduce a zig-zag array. \n\n\nA &nbsp; ''zig-zag'' &nbsp; array is a square arrangement of the first &nbsp; <big>N<sup>2</sup></big> &nbsp; natural numbers, &nbsp; where the \n<br>numbers increase sequentially as you zig-zag along the array's &nbsp; [https://en.wiktionary.org/wiki/antidiagonal anti-diagonals]. \n\nFor a graphical representation, see &nbsp; [[wp:Image:JPEG_ZigZag.svg|JPG zigzag]] &nbsp; (JPG uses such arrays to encode images).\n\n\nFor example, given &nbsp; '''5''', &nbsp; produce this array:\n<pre>\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n</pre>\n\n\n;Related tasks:\n* &nbsp; [[Spiral matrix]]\n* &nbsp; [[Identity matrix]]\n* &nbsp; [[Ulam spiral (for primes)]]\n\n\n;See also:\n* &nbsp; Wiktionary entry: &nbsp; [https://en.wiktionary.org/wiki/antidiagonal anti-diagonals]\n<br><br>\n\n", "language": "00-TASK" }, { "code": "F zigzag(n)\n F compare(xy)\n V (x, y) = xy\n R (x + y, I (x + y) % 2 {-y} E y)\n V xs = 0 .< n\n R Dict(enumerate(sorted((multiloop(xs, xs, (x, y) -> (x, y))), key' compare)), (n, index) -> (index, n))\n\nF printzz(myarray)\n V n = Int(myarray.len ^ 0.5 + 0.5)\n V xs = 0 .< n\n print((xs.map(y -> @xs.map(x -> ‘#3’.format(@@myarray[(x, @y)])).join(‘’))).join(\"\\n\"))\n\nprintzz(zigzag(6))\n", "language": "11l" }, { "code": "* Zig-zag matrix 15/08/2015\nZIGZAGMA CSECT\n USING ZIGZAGMA,R12 set base register\n LR R12,R15 establish addressability\n LA R9,N n : matrix size\n LA R6,1 i=1\n LA R7,1 j=1\n LR R11,R9 n\n MR R10,R9 *n\n BCTR R11,0 R11=n**2-1\n SR R8,R8 k=0\nLOOPK CR R8,R11 do k=0 to n**2-1\n BH ELOOPK k>limit\n LR R1,R6 i\n BCTR R1,0 -1\n MR R0,R9 *n\n LR R2,R7 j\n BCTR R2,0 -1\n AR R1,R2 (i-1)*n+(j-1)\n SLA R1,1 index=((i-1)*n+j-1)*2\n STH R8,T(R1) t(i,j)=k\n LR R2,R6 i\n AR R2,R7 i+j\n LA R1,2 2\n SRDA R2,32 shift right r1 to r2\n DR R2,R1 (i+j)/2\n LTR R2,R2 if mod(i+j,2)=0\n BNZ ELSEMOD\n CR R7,R9 if j<n\n BNL ELSE1\n LA R7,1(R7) j=j+1\n B EIF1\nELSE1 LA R6,2(R6) i=i+2\nEIF1 CH R6,=H'1' if i>1\n BNH NOT1\n BCTR R6,0 i=i-1\nNOT1 B NOT2\nELSEMOD CR R6,R9 if i<n\n BNL ELSE2\n LA R6,1(R6) i=i+1\n B EIF2\nELSE2 LA R7,2(R7) j=j+2\nEIF2 CH R7,=H'1' if j>1\n BNH NOT2\n BCTR R7,0 j=j-1\nNOT2 LA R8,1(R8) k=k+1\n B LOOPK\nELOOPK LA R6,1 end k; i=1\nLOOPI CR R6,R9 do i=1 to n\n BH ELOOPI i>n\n LA R10,0 ibuf=0 buffer index\n MVC BUFFER,=CL80' '\n LA R7,1 j=1\nLOOPJ CR R7,R9 do j=1 to n\n BH ELOOPJ j>n\n LR R1,R6 i\n BCTR R1,0 -1\n MR R0,R9 *n\n LR R2,R7 j\n BCTR R2,0 -1\n AR R1,R2 (i-1)*n+(j-1)\n SLA R1,1 index=((i-1)*n+j-1)*2\n LH R2,T(R1) t(i,j)\n LA R3,BUFFER\n AR R3,R10\n XDECO R2,XDEC edit t(i,j) length=12\n MVC 0(4,R3),XDEC+8 move in buffer length=4\n LA R10,4(R10) ibuf=ibuf+1\n LA R7,1(R7) j=j+1\n B LOOPJ\nELOOPJ XPRNT BUFFER,80 end j\n LA R6,1(R6) i=i+1\n B LOOPI\nELOOPI XR R15,R15 end i; return_code=0\n BR R14 return to caller\nN EQU 5 matrix size\nBUFFER DS CL80\nXDEC DS CL12\nT DS (N*N)H t(n,n) matrix\n YREGS\n END ZIGZAGMA\n", "language": "360-Assembly" }, { "code": "DEFINE MAX_SIZE=\"10\"\nDEFINE MAX_MATRIX_SIZE=\"100\"\n\nINT FUNC Index(BYTE size,x,y)\nRETURN (x+y*size)\n\nPROC PrintMatrix(BYTE ARRAY a BYTE size)\n BYTE i,j,v\n\n FOR j=0 TO size-1\n DO\n FOR i=0 TO size-1\n DO\n v=a(Index(size,i,j))\n IF v<10 THEN\n Print(\" \")\n ELSE\n Print(\" \")\n FI\n PrintB(v)\n OD\n PutE()\n OD\nRETURN\n\nPROC FillMatrix(BYTE ARRAY a BYTE size)\n BYTE start,end\n INT dir,i,j\n\n start=0 end=size*size-1\n i=0 j=0 dir=1\n\n DO\n a(Index(size,i,j))=start\n a(Index(size,size-1-i,size-1-j))=end\n start==+1 end==-1\n i==+dir j==-dir\n IF i<0 THEN\n i==+1 dir=-dir\n ELSEIF j<0 THEN\n j==+1 dir=-dir\n FI\n UNTIL start>=end\n OD\n\n IF start=end THEN\n a(Index(size,i,j))=start\n FI\nRETURN\n\nPROC Test(BYTE size)\n BYTE ARRAY mat(MAX_MATRIX_SIZE)\n\n PrintF(\"Matrix size: %B%E\",size)\n FillMatrix(mat,size)\n PrintMatrix(mat,size)\n PutE()\nRETURN\n\nPROC Main()\n Test(5)\n Test(6)\nRETURN\n", "language": "Action-" }, { "code": "package\n{\n public class ZigZagMatrix extends Array\n {\n\n private var height:uint;\n private var width:uint;\n public var mtx:Array = [];\n\n public function ZigZagMatrix(size:uint)\n {\n this.height = size;\n this.width = size;\n\n this.mtx = [];\n for (var i:uint = 0; i < size; i++) {\n this.mtx[i] = [];\n }\n i = 1;\n var j:uint = 1;\n for (var e:uint = 0; e < size*size; e++) {\n this.mtx[i-1][j-1] = e;\n if ((i + j) % 2 == 0) {\n // Even stripes\n if (j < size) j ++;\n else i += 2;\n if (i > 1) i --;\n } else {\n // Odd stripes\n if (i < size) i ++;\n else j += 2;\n if (j > 1) j --;\n }\n }\n }\n }\n}\n", "language": "ActionScript" }, { "code": "with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Zig_Zag is\n\n type Matrix is array (Positive range <>, Positive range <>) of Natural;\n function Zig_Zag (Size : Positive) return Matrix is\n Data : Matrix (1..Size, 1..Size);\n I, J : Integer := 1;\n begin\n Data (1, 1) := 0;\n for Element in 1..Size**2 - 1 loop\n if (I + J) mod 2 = 0 then\n -- Even stripes\n if J < Size then\n J := J + 1;\n else\n I := I + 2;\n end if;\n if I > 1 then\n I := I - 1;\n end if;\n else\n -- Odd stripes\n if I < Size then\n I := I + 1;\n else\n J := J + 2;\n end if;\n if J > 1 then\n J := J - 1;\n end if;\n end if;\n Data (I, J) := Element;\n end loop;\n return Data;\n end Zig_Zag;\n\n procedure Put (Data : Matrix) is\n begin\n for I in Data'Range (1) loop\n for J in Data'Range (2) loop\n Put (Integer'Image (Data (I, J)));\n end loop;\n New_Line;\n end loop;\n end Put;\n\nbegin\n Put (Zig_Zag (5));\nend Test_Zig_Zag;\n", "language": "Ada" }, { "code": "# zig-zag matrix\n\nmakeZigZag := proc( n :: number ) :: table is\n\n local move := proc( x :: number, y :: number, upRight :: boolean ) is\n if y = n then\n upRight := not upRight;\n x := x + 1\n elif x = 1 then\n upRight := not upRight;\n y := y + 1\n else\n x := x - 1;\n y := y + 1\n fi;\n return x, y, upRight\n end ;\n\n # create empty table\n local result := [];\n for i to n do\n result[ i ] := [];\n for j to n do result[ i, j ] := 0 od\n od;\n\n # fill the table\n local x, y, upRight := 1, 1, true;\n for i to n * n do\n result[ x, y ] := i - 1;\n if upRight then\n x, y, upRight := move( x, y, upRight )\n else\n y, x, upRight := move( y, x, upRight )\n fi\n od;\n\n return result\nend;\n\nscope\n local m := makeZigZag( 5 );\n for i to size m do\n for j to size m do\n printf( \" %3d\", m[ i, j ] )\n od;\n print()\n od\nepocs\n", "language": "Agena" }, { "code": "PROC zig zag = (INT n)[,]INT: (\n PROC move = (REF INT i, j)VOID: (\n IF j < n THEN\n i := ( i <= 1 | 1 | i-1 );\n j +:= 1\n ELSE\n i +:= 1\n FI\n );\n\n [n, n]INT a;\n INT x:=LWB a, y:=LWB a;\n\n FOR v FROM 0 TO n**2-1 DO\n a[y, x] := v;\n IF ODD (x + y) THEN\n move(x, y)\n ELSE\n move(y, x)\n FI\n OD;\n a\n);\n\nINT dim = 5;\n#IF formatted transput possible THEN\n FORMAT d = $z-d$;\n FORMAT row = $\"(\"n(dim-1)(f(d)\",\")f(d)\")\"$;\n FORMAT block = $\"(\"n(dim-1)(f(row)\",\"lx)f(row)\")\"l$;\n\n printf((block, zig zag(dim)))\nELSE#\n [,]INT result = zig zag(dim);\n FOR i TO dim DO\n print((IF i = 1 THEN \"((\" ELSE \" (\" FI));\n FOR j TO dim DO\n print(( whole( result[i,j], -3 ), IF j /= dim THEN \",\" ELSE \"\" FI ))\n OD;\n print((IF i = dim THEN \"))\" ELSE \"),\" FI, new line))\n OD\n#FI#\n", "language": "ALGOL-68" }, { "code": "begin % zig-zag matrix %\n % z is returned holding a zig-zag matrix of order n, z must be at least n x n %\n procedure makeZigZag ( integer value n\n ; integer array z( *, * )\n ) ;\n begin\n procedure move ;\n begin\n if y = n then begin\n upRight := not upRight;\n x := x + 1\n end\n else if x = 1 then begin\n upRight := not upRight;\n y := y + 1\n end\n else begin\n x := x - 1;\n y := y + 1\n end\n end move ;\n procedure swapXY ;\n begin\n integer swap;\n swap := x;\n x := y;\n y := swap;\n end swapXY ;\n integer x, y;\n logical upRight;\n % initialise the n x n matrix in z %\n for i := 1 until n do for j := 1 until n do z( i, j ) := 0;\n % fill in the zig-zag matrix %\n x := y := 1;\n upRight := true;\n for i := 1 until n * n do begin\n z( x, y ) := i - 1;\n if upRight then move\n else begin\n swapXY;\n move;\n swapXY\n end;\n end;\n end makeZigZap ;\n\n begin\n integer array zigZag( 1 :: 10, 1 :: 10 );\n for n := 5 do begin\n makeZigZag( n, zigZag );\n for i := 1 until n do begin\n write( i_w := 4, s_w := 1, zigZag( i, 1 ) );\n for j := 2 until n do writeon( i_w := 4, s_w := 1, zigZag( i, j ) );\n end\n end\n end\n\nend.\n", "language": "ALGOL-W" }, { "code": " zz ← {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵} ⍝ General zigzag (any rectangle)\n zzSq ← {zz,⍨⍵} ⍝ Square zigzag\n zzSq 5\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n", "language": "APL" }, { "code": "set n to 5 -- Size of zig-zag matrix (n^2 cells).\n\n-- Create an empty matrix.\nset m to {}\nrepeat with i from 1 to n\n\tset R to {}\n\trepeat with j from 1 to n\n\t\tset end of R to 0\n\tend repeat\n\tset end of m to R\nend repeat\n\n-- Populate the matrix in a zig-zag manner.\nset {x, y, v, d} to {1, 1, 0, 1}\nrepeat while v < (n ^ 2)\n\tif 1 ≤ x and x ≤ n and 1 ≤ y and y ≤ n then\n\t\tset {m's item y's item x, x, y, v} to {v, x + d, y - d, v + 1}\n\telse if x > n then\n\t\tset {x, y, d} to {n, y + 2, -d}\n\telse if y > n then\n\t\tset {x, y, d} to {x + 2, n, -d}\n\telse if x < 1 then\n\t\tset {x, y, d} to {1, y, -d}\n\telse if y < 1 then\n\t\tset {x, y, d} to {x, 1, -d}\n\tend if\nend repeat\n--> R = {{0, 1, 5, 6, 14}, {2, 4, 7, 13, 15}, {3, 8, 12, 16, 21}, {9, 11, 17, 20, 22}, {10, 18, 19, 23, 24}}\n\n-- Reformat the matrix into a table for viewing.\nrepeat with i in m\n\trepeat with j in i\n\t\tset j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (\" \" & j)) as string\n\tend repeat\n\tset end of i to return\nend repeat\nreturn return & m as string\n", "language": "AppleScript" }, { "code": "set n to 5\n\nset m to {}\nrepeat with i from 1 to n\n\tset end of m to {} -- Built a foundation for the matrix out of n empty lists.\nend repeat\n\nset {v, d, i} to {0, -1, 1}\nrepeat while v < n ^ 2\n\tif length of m's item i < n then\n\t\tset {end of m's item i, i, v} to {f(v, n), i + d, v + 1}\n\t\tif i < 1 then\n\t\t\tset {i, d} to {1, -d}\n\t\telse if i > n then\n\t\t\tset {i, d} to {n, -d}\n\t\telse if i > 1 and (count of m's item (i - 1)) = 1 then\n\t\t\tset d to -d\n\t\tend if\n\telse\n\t\tset {i, d} to {i + 1, 1}\n\tend if\nend repeat\n\n-- Handler/function to format the cells on the fly.\non f(v, n)\n\treturn (characters -(length of (n ^ 2 as string)) thru -1 of (\" \" & v)) as string\nend f\n\n-- Reformat the matrix into a table for viewing.\nset text item delimiters to \"\"\nrepeat with i in m\n\tset i's contents to (i as string) & return\nend repeat\nreturn return & m as string\n", "language": "AppleScript" }, { "code": "-- zigzagMatrix\non zigzagMatrix(n)\n\n -- diagonals :: n -> [[n]]\n script diagonals\n on |λ|(n)\n script mf\n on diags(xs, iCol, iRow)\n if (iCol < length of xs) then\n if iRow < n then\n set iNext to iCol + 1\n else\n set iNext to iCol - 1\n end if\n\n set {headList, tail} to splitAt(iCol, xs)\n {headList} & diags(tail, iNext, iRow + 1)\n else\n {xs}\n end if\n end diags\n end script\n\n diags(enumFromTo(0, n * n - 1), 1, 1) of mf\n end |λ|\n end script\n\n -- oddReversed :: [a] -> Int -> [a]\n script oddReversed\n on |λ|(lst, i)\n if i mod 2 = 0 then\n lst\n else\n reverse of lst\n end if\n end |λ|\n end script\n\n rowsFromDiagonals(n, map(oddReversed, |λ|(n) of diagonals))\n\nend zigzagMatrix\n\n-- Rows of given length from list of diagonals\n-- rowsFromDiagonals :: Int -> [[a]] -> [[a]]\non rowsFromDiagonals(n, lst)\n if length of lst > 0 then\n\n -- lengthOverOne :: [a] -> Bool\n script lengthOverOne\n on |λ|(lst)\n length of lst > 1\n end |λ|\n end script\n\n set {edge, residue} to splitAt(n, lst)\n\n {map(my head, edge)} & ¬\n rowsFromDiagonals(n, ¬\n map(my tail, ¬\n filter(lengthOverOne, edge)) & residue)\n else\n {}\n end if\nend rowsFromDiagonals\n\n\n-- TEST -----------------------------------------------------------------------\non run\n\n zigzagMatrix(5)\n\nend run\n\n\n-- GENERIC FUNCTIONS ----------------------------------------------------------\n\n-- enumFromTo :: Int -> Int -> [Int]\non enumFromTo(m, n)\n if n < m then\n set d to -1\n else\n set d to 1\n end if\n set lst to {}\n repeat with i from m to n by d\n set end of lst to i\n end repeat\n return lst\nend enumFromTo\n\n-- filter :: (a -> Bool) -> [a] -> [a]\non filter(f, xs)\n tell mReturn(f)\n set lst to {}\n set lng to length of xs\n repeat with i from 1 to lng\n set v to item i of xs\n if |λ|(v, i, xs) then set end of lst to v\n end repeat\n return lst\n end tell\nend filter\n\n-- head :: [a] -> a\non head(xs)\n if length of xs > 0 then\n item 1 of xs\n else\n missing value\n end if\nend head\n\n-- map :: (a -> b) -> [a] -> [b]\non map(f, xs)\n tell mReturn(f)\n set lng to length of xs\n set lst to {}\n repeat with i from 1 to lng\n set end of lst to |λ|(item i of xs, i, xs)\n end repeat\n return lst\n end tell\nend map\n\n-- Lift 2nd class handler function into 1st class script wrapper\n-- mReturn :: Handler -> Script\non mReturn(f)\n if class of f is script then\n f\n else\n script\n property |λ| : f\n end script\n end if\nend mReturn\n\n-- splitAt:: n -> list -> {n items from start of list, rest of list}\n-- splitAt :: Int -> [a] -> ([a], [a])\non splitAt(n, xs)\n if n > 0 and n < length of xs then\n {items 1 thru n of xs, items (n + 1) thru -1 of xs}\n else\n if n < 1 then\n {{}, xs}\n else\n {xs, {}}\n end if\n end if\nend splitAt\n\n-- tail :: [a] -> [a]\non tail(xs)\n if length of xs > 1 then\n items 2 thru -1 of xs\n else\n {}\n end if\nend tail\n", "language": "AppleScript" }, { "code": "on zigzagMatrix(n)\n script o\n property matrix : {} -- Matrix list.\n property row : missing value -- Row sublist.\n end script\n\n repeat n times\n set end of o's matrix to {} -- Build a foundation for the matrix out of n empty lists.\n end repeat\n\n set {r, d} to {1, -1} -- Row index and direction to next insertion row (negative = row above).\n repeat with v from 0 to (n ^ 2) - 1 -- Values to insert.\n set o's row to o's matrix's item r\n repeat while ((count o's row) = n)\n set r to r + 1\n set d to 1\n set o's row to o's matrix's item r\n end repeat\n set end of o's row to v\n set r to r + d\n if (r < 1) then\n set r to 1\n set d to -d\n else if (r > n) then\n set r to n\n set d to -d\n else if ((r > 1) and ((count o's matrix's item (r - 1)) = 1)) then\n set d to -d\n end if\n end repeat\n\n return o's matrix\nend zigzagMatrix\n\n-- Demo:\non matrixToText(matrix, w)\n script o\n property matrix : missing value\n property row : missing value\n end script\n\n set o's matrix to matrix\n set padding to \" \"\n repeat with r from 1 to (count o's matrix)\n set o's row to o's matrix's item r\n repeat with i from 1 to (count o's row)\n set o's row's item i to text -w thru end of (padding & o's row's item i)\n end repeat\n set o's matrix's item r to join(o's row, \"\")\n end repeat\n\n return join(o's matrix, linefeed)\nend matrixToText\n\non join(lst, delim)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delim\n set txt to lst as text\n set AppleScript's text item delimiters to astid\n return txt\nend join\n\nset n to 5\nset matrix to zigzagMatrix(n)\nlinefeed & matrixToText(matrix, (count (n ^ 2 - 1 as integer as text)) + 2) & linefeed\n", "language": "AppleScript" }, { "code": "100 S = 5\n110 S2 = S ^ 2 : REM SQUARED\n120 H = S2 / 2 : REM HALFWAY\n130 S2 = S2 - 1\n140 DX = 1 : REM INITIAL\n150 DY = 0 : REM DIRECTION\n160 N = S - 1\n170 DIM A%(N, N)\n\n200 FOR I = 0 TO H\n210 A%(X, Y) = I\n220 A%(N - X, N - Y) = S2 - I\n230 X = X + DX\n240 Y = Y + DY\n250 IF Y = 0 THEN DY = DY + 1 : IF DY THEN DX = -DX\n260 IF X = 0 THEN DX = DX + 1 : IF DX THEN DY = -DY\n270 NEXT I\n\n300 FOR Y = 0 TO N\n310 FOR X = 0 TO N\n320 IF X THEN PRINT TAB(X * (LEN(STR$(S2)) + 1) + 1);\n330 PRINT A%(X, Y);\n340 NEXT X\n350 PRINT\n360 NEXT Y\n", "language": "Applesoft-BASIC" }, { "code": "zigzag: function [n][\n result: map 1..n 'x -> map 1..n => 0\n\n x: 1, y: 1, v: 0, d: 1\n\n while [v < n^2][\n if? all? @[1 =< x x =< n 1 =< y y =< n][\n set get result (y-1) (x-1) v\n x: x + d, y: y - d, v: v + 1\n ]\n else[if? x > n [x: n, y: y + 2, d: neg d]\n else[if? y > n [x: x + 2, y: n, d: neg d]\n else[if? x < 1 [x: 1, d: neg d]\n else[if y < 1 [y: 1, d: neg d]\n ]\n ]\n ]\n ]\n ]\n result\n]\n\nzz: zigzag 5\nloop zz 'row -> print map row 'col [pad to :string col 3]\n", "language": "Arturo" }, { "code": "(* ****** ****** *)\n//\n#include\n\"share/atspre_define.hats\" // defines some names\n#include\n\"share/atspre_staload.hats\" // for targeting C\n#include\n\"share/HATS/atspre_staload_libats_ML.hats\" // for ...\n//\n(* ****** ****** *)\n//\nextern\nfun\nZig_zag_matrix(n: int): void\n//\n(* ****** ****** *)\n\nfun max(a: int, b: int): int =\n if a > b then a else b\n\nfun movex(n: int, x: int, y: int): int =\n if y < n-1 then max(0, x-1) else x+1\n\nfun movey(n: int, x: int, y: int): int =\n if y < n-1 then y+1 else y\n\nfun zigzag(n: int, i: int, row: int, x: int, y: int): void =\n if i = n*n then ()\n else\n let\n val () = (if x = row then begin print i; print ','; end else ())\n //val () = (begin print x; print ' '; print y; print ' '; print i; print ' '; end)\n val nextX: int = if ((x+y) % 2) = 0 then movex(n, x, y) else movey(n, y, x)\n val nextY: int = if ((x+y) % 2) = 0 then movey(n, x, y) else movex(n, y, x)\n in\n zigzag(n, i+1, row, nextX, nextY)\n end\n\nimplement\nZig_zag_matrix(n) =\n let\n fun loop(row: int): void =\n if row = n then () else\n let\n val () = zigzag(n, 0, row, 0, 0)\n val () = println!(\" \")\n in\n loop(row + 1)\n end\n in\n loop(0)\n end\n\n(* ****** ****** *)\n\nimplement\nmain0() = () where\n{\n val () = Zig_zag_matrix(5)\n} (* end of [main0] *)\n\n(* ****** ****** *)\n", "language": "ATS" }, { "code": "n = 5 ; size\nv := x := y := 1 ; initial values\nLoop % n*n { ; for every array element\n a_%x%_%y% := v++ ; assign the next index\n If ((x+y)&1) ; odd diagonal\n If (x < n) ; while inside the square\n y -= y<2 ? 0 : 1, x++ ; move right-up\n Else y++ ; on the edge increment y, but not x: to even diagonal\n Else ; even diagonal\n If (y < n) ; while inside the square\n x -= x<2 ? 0 : 1, y++ ; move left-down\n Else x++ ; on the edge increment x, but not y: to odd diagonal\n}\n\nLoop %n% { ; generate printout\n x := A_Index ; for each row\n Loop %n% ; and for each column\n t .= a_%x%_%A_Index% \"`t\" ; attach stored index\n t .= \"`n\" ; row is complete\n}\nMsgBox %t% ; show output\n", "language": "AutoHotkey" }, { "code": "#include <Array.au3>\n$Array = ZigZag(5)\n_ArrayDisplay($Array)\n\nFunc ZigZag($int)\n\tLocal $av_array[$int][$int]\n\tLocal $x = 1, $y = 1\n\tFor $I = 0 To $int ^ 2 -1\n\t\t$av_array[$x-1][$y-1] = $I\n\t\tIf Mod(($x + $y), 2) = 0 Then ;Even\n\t\t\tif ($y < $int) Then\n\t\t\t\t$y += 1\n\t\t\tElse\n\t\t\t\t$x += 2\n\t\t\tEndIf\n\t\t\tif ($x > 1) Then $x -= 1\n\t\tElse ; ODD\n\t\t\tif ($x < $int) Then\n\t\t\t\t$x += 1\n\t\t\tElse\n\t\t\t\t$y += 2\n\t\t\tEndIf\n\t\t\tIf $y > 1 Then $y -= 1\n\t\tEndIf\n\tNext\n\tReturn $av_array\nEndFunc ;==>ZigZag\n", "language": "AutoIt" }, { "code": "# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size]\nBEGIN {\n# offset: \"0\" prints 0 to size^2-1 while \"1\" prints 1 to size^2\n offset = (offset == \"\") ? 0 : offset\n size = (ARGV[1] == \"\") ? 5 : ARGV[1]\n if (offset !~ /^[01]$/) { exit(1) }\n if (size !~ /^[0-9]+$/) { exit(1) }\n width = length(size ^ 2 - 1 + offset) + 1\n i = j = 1\n for (n=0; n<=size^2-1; n++) { # build array\n arr[i-1,j-1] = n + offset\n if ((i+j) % 2 == 0) {\n if (j < size) { j++ } else { i+=2 }\n if (i > 1) { i-- }\n }\n else {\n if (i < size) { i++ } else { j+=2 }\n if (j > 1) { j-- }\n }\n }\n for (row=0; row<size; row++) { # show array\n for (col=0; col<size; col++) {\n printf(\"%*d\",width,arr[row,col])\n }\n printf(\"\\n\")\n }\n exit(0)\n}\n", "language": "AWK" }, { "code": " Size% = 5\n DIM array%(Size%-1,Size%-1)\n\n i% = 1\n j% = 1\n FOR e% = 0 TO Size%^2-1\n array%(i%-1,j%-1) = e%\n IF ((i% + j%) AND 1) = 0 THEN\n IF j% < Size% j% += 1 ELSE i% += 2\n IF i% > 1 i% -= 1\n ELSE\n IF i% < Size% i% += 1 ELSE j% += 2\n IF j% > 1 j% -= 1\n ENDIF\n NEXT\n\n @% = &904\n FOR row% = 0 TO Size%-1\n FOR col% = 0 TO Size%-1\n PRINT array%(row%,col%);\n NEXT\n PRINT\n NEXT row%\n", "language": "BBC-BASIC" }, { "code": "beads 1 program 'Zig-zag Matrix'\n\ncalc main_init\n\tvar test : array^2 of num = create_array(5)\n\tprintMatrix(test)\n\t\t\ncalc create_array(\n\tdimension:num\n\t):array^2 of num\n\tvar\n\t\tresult : array^2 of num\n\t\tlastValue = dimension^2 - 1\n\t\tloopFrom\n\t\tloopTo\n\t\trow\n\t\tcol\n\t\tcurrDiag = 0\n\t\tcurrNum = 0\n\tloop\n\t\tif (currDiag < dimension)\t// if doing the upper-left triangular half\n\t\t\tloopFrom = 1\n\t\t\tloopTo = currDiag + 1\n\t\telse\t// doing the bottom-right triangular half\n\t\t\tloopFrom = currDiag - dimension + 2\n\t\t\tloopTo = dimension\n\t\tloop count:c from:loopFrom to:loopTo\n\t\t\tvar i = loopFrom + c - 1\n\t\t\tif (rem(currDiag, 2) == 0)\t// want to fill upwards\n\t\t\t\trow = loopTo - i + loopFrom\n\t\t\t\tcol = i\n\t\t\telse\t// want to fill downwards\n\t\t\t\trow = i\n\t\t\t\tcol = loopTo - i + loopFrom\n\t\t\tresult[row][col] = currNum\n\t\t\tinc currNum\n\t\tinc currDiag\n\t\tif (currNum > lastValue)\n\t\t\texit\n\treturn result\n\t\t\ncalc printMatrix(\n\tmatrix:array^2 of num\n\t)\n\tvar dimension = tree_count(matrix)\n\tvar maxDigits = 1 + lg((dimension^2-1), base:10)\n\tloop across:matrix ptr:rowp index:row\n\t\tvar tempstr : str\n\t\tloop across:rowp index:col\n\t\t\ttempstr = tempstr & \" \" & to_str(matrix[row][col], min:maxDigits)\n\t\tlog(tempstr)\n", "language": "Beads" }, { "code": ">> 5 >>00p0010p:1:>20p030pv >0g-:0`*:*-:00g:*1-55+/>\\55+/:v v:,*84<\nv:++!\\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\\_$:>55+/\\|\n>55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\\*+1*2g01:g04.$<\n", "language": "Befunge" }, { "code": "Flip ← {m←2|+⌜˜↕≠𝕩 ⋄ (⍉𝕩׬m)+𝕩×m}\nZz ← {Flip ⍋∘⍋⌾⥊+⌜˜↕𝕩}\n", "language": "BQN" }, { "code": "Zz 5\n", "language": "BQN" }, { "code": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(int c, char **v)\n{\n\tint i, j, m, n, *s;\n\n\t/* default size: 5 */\n\tif (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5;\n\n\t/* alloc array*/\n\ts = malloc(sizeof(int) * m * m);\n\n\tfor (i = n = 0; i < m * 2; i++)\n\t\tfor (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++)\n\t\t\ts[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++;\n\n\tfor (i = 0; i < m * m; putchar((++i % m) ? ' ':'\\n'))\n\t\tprintf(\"%3d\", s[i]);\n\n\t/* free(s) */\n\treturn 0;\n}\n", "language": "C" }, { "code": "#include <vector>\n#include <memory>\t// for auto_ptr\n#include <cmath>\t// for the log10 and floor functions\n#include <iostream>\n#include <iomanip>\t// for the setw function\n\nusing namespace std;\n\ntypedef vector< int > IntRow;\ntypedef vector< IntRow > IntTable;\n\nauto_ptr< IntTable > getZigZagArray( int dimension )\n{\n\tauto_ptr< IntTable > zigZagArrayPtr( new IntTable(\n\t\tdimension, IntRow( dimension ) ) );\n\n\t// fill along diagonal stripes (oriented as \"/\")\n\tint lastValue = dimension * dimension - 1;\n\tint currNum = 0;\n\tint currDiag = 0;\n\tint loopFrom;\n\tint loopTo;\n\tint i;\n\tint row;\n\tint col;\n\tdo\n\t{\n\t\tif ( currDiag < dimension ) // if doing the upper-left triangular half\n\t\t{\n\t\t\tloopFrom = 0;\n\t\t\tloopTo = currDiag;\n\t\t}\n\t\telse // doing the bottom-right triangular half\n\t\t{\n\t\t\tloopFrom = currDiag - dimension + 1;\n\t\t\tloopTo = dimension - 1;\n\t\t}\n\n\t\tfor ( i = loopFrom; i <= loopTo; i++ )\n\t\t{\n\t\t\tif ( currDiag % 2 == 0 ) // want to fill upwards\n\t\t\t{\n\t\t\t\trow = loopTo - i + loopFrom;\n\t\t\t\tcol = i;\n\t\t\t}\n\t\t\telse // want to fill downwards\n\t\t\t{\n\t\t\t\trow = i;\n\t\t\t\tcol = loopTo - i + loopFrom;\n\t\t\t}\n\n\t\t\t( *zigZagArrayPtr )[ row ][ col ] = currNum++;\n\t\t}\n\n\t\tcurrDiag++;\n\t}\n\twhile ( currDiag <= lastValue );\n\n\treturn zigZagArrayPtr;\n}\n\nvoid printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )\n{\n\tsize_t dimension = zigZagArrayPtr->size();\n\n\tint fieldWidth = static_cast< int >( floor( log10(\n\t\tstatic_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;\n\n\tsize_t col;\n\tfor ( size_t row = 0; row < dimension; row++ )\n\t{\n\t\tfor ( col = 0; col < dimension; col++ )\n\t\t\tcout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ];\n\t\tcout << endl;\n\t}\n}\n\nint main()\n{\n\tprintZigZagArray( getZigZagArray( 5 ) );\n}\n", "language": "C++" }, { "code": "public static int[,] ZigZag(int n)\n{\n int[,] result = new int[n, n];\n int i = 0, j = 0;\n int d = -1; // -1 for top-right move, +1 for bottom-left move\n int start = 0, end = n * n - 1;\n do\n {\n result[i, j] = start++;\n result[n - i - 1, n - j - 1] = end--;\n\n i += d; j -= d;\n if (i < 0)\n {\n i++; d = -d; // top reached, reverse\n }\n else if (j < 0)\n {\n j++; d = -d; // left reached, reverse\n }\n } while (start < end);\n if (start == end)\n result[i, j] = start;\n return result;\n}\n", "language": "C-sharp" }, { "code": "class ZigZag(Integer size) {\n\t\n\tvalue data = Array {\n\t\tfor (i in 0:size)\n\t\tArray.ofSize(size, 0)\n\t};\n\t\n\tvariable value i = 1;\n\tvariable value j = 1;\n\t\n\tfor (element in 0 : size^2) {\n\t\tdata[j - 1]?.set(i - 1, element);\n\t\tif ((i + j).even) {\n\t\t\tif (j < size) {\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ti += 2;\n\t\t\t}\n\t\t\tif (i > 1) {\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (i < size) {\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tj += 2;\n\t\t\t}\n\t\t\tif (j > 1) {\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tshared void display() {\n\t\tfor (row in data) {\n\t\t\tfor (element in row) {\n\t\t\t\tprocess.write(element.string.pad(3));\n\t\t\t}\n\t\t\tprint(\"\"); //newline\n\t\t}\n\t}\n}\n\nshared void run() {\n\tvalue zz = ZigZag(5);\n\tzz.display();\n}\n", "language": "Ceylon" }, { "code": "(defn partitions [sizes coll]\n (lazy-seq\n (when-let [n (first sizes)]\n (when-let [s (seq coll)]\n (cons (take n coll)\n\t (partitions (next sizes) (drop n coll)))))))\n\n(defn take-from [n colls]\n (lazy-seq\n (when-let [s (seq colls)]\n (let [[first-n rest-n] (split-at n s)]\n (cons (map first first-n)\n\t (take-from n (concat (filter seq (map rest first-n)) rest-n)))))))\n\n(defn zig-zag [n]\n (->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n)))\n (map #(%1 %2) (cycle [reverse identity]) ,)\n (take-from n ,)))\n\nuser> (zig-zag 5)\n(( 0 1 5 6 14)\n ( 2 4 7 13 15)\n ( 3 8 12 16 21)\n ( 9 11 17 20 22)\n (10 18 19 23 24))\n\nuser> (zig-zag 6)\n(( 0 1 5 6 14 15)\n ( 2 4 7 13 16 25)\n ( 3 8 12 17 24 26)\n ( 9 11 18 23 27 32)\n (10 19 22 28 31 33)\n (20 21 29 30 34 35))\n", "language": "Clojure" }, { "code": "# Calculate a zig-zag pattern of numbers like so:\n# 0 1 5\n# 2 4 6\n# 3 7 8\n#\n# There are many interesting ways to solve this; we\n# try for an algebraic approach, calculating triangle\n# areas, so that me minimize space requirements.\n\nzig_zag_value = (x, y, n) ->\n\n upper_triangle_zig_zag = (x, y) ->\n # calculate the area of the triangle from the prior\n # diagonals\n diag = x + y\n triangle_area = diag * (diag+1) / 2\n # then add the offset along the diagonal\n if diag % 2 == 0\n triangle_area + y\n else\n triangle_area + x\n\n if x + y < n\n upper_triangle_zig_zag x, y\n else\n # For the bottom right part of the matrix, we essentially\n # use reflection to count backward.\n bottom_right_cell = n * n - 1\n n -= 1\n v = upper_triangle_zig_zag(n-x, n-y)\n bottom_right_cell - v\n\nzig_zag_matrix = (n) ->\n row = (i) -> (zig_zag_value i, j, n for j in [0...n])\n (row i for i in [0...n])\n\ndo ->\n for n in [4..6]\n console.log \"---- n=#{n}\"\n console.log zig_zag_matrix(n)\n console.log \"\\n\"\n", "language": "CoffeeScript" }, { "code": "(defun zigzag (n)\n (flet ((move (i j)\n (if (< j (1- n))\n (values (max 0 (1- i)) (1+ j))\n (values (1+ i) j))))\n (loop with a = (make-array (list n n) :element-type 'integer)\n with x = 0\n with y = 0\n for v from 0 below (* n n)\n do (setf (aref a x y) v)\n (if (evenp (+ x y))\n (setf (values x y) (move x y))\n (setf (values y x) (move y x)))\n finally (return a))))\n", "language": "Common-Lisp" }, { "code": "; ZigZag\n;\n; Nigel Galloway.\n; June 4th., 2012\n;\n(defun ZigZag (COLS)\n (let ((cs 2) (st '(1 2)) (dx '(-1 1)))\n (defun new_cx (i)\n (setq st (append st (list (setq cs (+ cs (* 2 i))) (setq cs (+ 1 cs))))\n dx (append dx '(-1 1))))\n (do ((i 2 (+ 2 i))) ((>= i COLS)) (new_cx i))\n (do ((i (- COLS 1 (mod COLS 2)) (+ -2 i))) ((<= i 0)) (new_cx i))\n (do ((i 0 (+ 1 i))) ((>= i COLS))\n (format t \"~%\")\n (do ((j i (+ 1 j))) ((>= j (+ COLS i)))\n (format t \"~3d\" (nth j st))\n (setf (nth j st) (+ (nth j st) (nth j dx)))))))\n", "language": "Common-Lisp" }, { "code": "def zigzag(n)\n (seq=(0...n).to_a).product(seq)\n .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}\n .map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a\nend\n\ndef print_matrix(m)\n format = \"%#{m.flatten.max.to_s.size}d \" * m[0].size\n m.each {|row| puts format % row}\nend\n\nprint_matrix zigzag(5)\n", "language": "Crystal" }, { "code": "int[][] zigZag(in int n) pure nothrow @safe {\n static void move(in int n, ref int i, ref int j)\n pure nothrow @safe @nogc {\n if (j < n - 1) {\n if (i > 0) i--;\n j++;\n } else\n i++;\n }\n\n auto a = new int[][](n, n);\n int x, y;\n foreach (v; 0 .. n ^^ 2) {\n a[y][x] = v;\n (x + y) % 2 ? move(n, x, y) : move(n, y, x);\n }\n return a;\n}\n\nvoid main() {\n import std.stdio;\n\n writefln(\"%(%(%2d %)\\n%)\", 5.zigZag);\n}\n", "language": "D" }, { "code": "import std.stdio, std.algorithm, std.range, std.array;\n\nint[][] zigZag(in int n) pure nothrow {\n static struct P2 { int x, y; }\n const L = iota(n ^^ 2).map!(i => P2(i % n, i / n)).array\n .sort!q{ (a.x + a.y == b.x + b.y) ?\n ((a.x + a.y) % 2 ? a.y < b.y : a.x < b.x) :\n (a.x + a.y) < (b.x + b.y) }.release;\n\n auto result = new typeof(return)(n, n);\n foreach (immutable i, immutable p; L)\n result[p.y][p.x] = i;\n return result;\n}\n\nvoid main() {\n writefln(\"%(%(%2d %)\\n%)\", 5.zigZag);\n}\n", "language": "D" }, { "code": "type TMatrix = array of array of double;\n\n\n\nprocedure DisplayMatrix(Memo: TMemo; Mat: TMatrix);\n{Display specified matrix}\nvar X,Y: integer;\nvar S: string;\nbegin\nS:='';\nfor Y:=0 to High(Mat[0]) do\n\tbegin\n\tS:=S+'[';\n\tfor X:=0 to High(Mat) do\n\t S:=S+Format('%4.0f',[Mat[X,Y]]);\n\tS:=S+']'+#$0D#$0A;\n\tend;\nMemo.Lines.Add(S);\nend;\n\nprocedure ZigzagMatrix(Memo: TMemo);\nvar Mat: TMatrix;\nvar X,Y,Inx,Dir: integer;\nconst Size = 10;\n\n\tprocedure Toggle(var I: integer);\n\t{Toggle Direction and increment I}\n\tbegin\n\tDir:=-Dir;\n\tInc(I);\n\tend;\n\n\n\tprocedure Step(var X,Y: integer);\n\t{Take one step \"Dir\" direction}\n\tbegin\n\tX:=X+Dir;\n\tY:=Y-Dir;\n\tend;\n\nbegin\nSetLength(Mat,Size,Size);\nInx:=0; X:=0; Y:=0; Dir:=1;\nrepeat\n\tbegin\n\tMat[X,Y]:=Inx;\n\tif (X+Dir)>=Size then Toggle(Y)\n\telse if (Y-Dir)>=Size then Toggle(X)\n\telse if (X+Dir)<0 then Toggle(Y)\n\telse if (Y-Dir)<0 then Toggle(X)\n\telse Step(X,Y);\n\tInc(Inx);\n\tend\nuntil Inx>=Size*Size;\nDisplayMatrix(Memo,Mat);\nend;\n", "language": "Delphi" }, { "code": "def zigZag(n) {\n def move(&i, &j) {\n if (j < (n - 1)) {\n i := 0.max(i - 1)\n j += 1\n } else {\n i += 1\n }\n }\n\n def array := makeFlex2DArray(n, n)\n var x := 0\n var y := 0\n\n for i in 1..n**2 {\n array[y, x] := i\n if ((x + y) % 2 == 0) {\n move(&x, &y)\n } else {\n move(&y, &x)\n }\n }\n return array\n}\n", "language": "E" }, { "code": "import extensions;\n\nextension op : IntNumber\n{\n zigzagMatrix()\n {\n auto result := IntMatrix.allocate(self, self);\n\n int i := 0;\n int j := 0;\n int d := -1;\n int start := 0;\n int end := self*self - 1;\n\n while (start < end)\n {\n result.setAt(i, j, start); start += 1;\n result.setAt(self - i - 1, self - j - 1, end); end -= 1;\n\n i := i + d;\n j := j - d;\n if (i < 0)\n {\n i:=i+1; d := d.Negative\n }\n else if (j < 0)\n {\n j := j + 1; d := d.Negative\n }\n };\n\n if (start == end)\n {\n result.setAt(i, j, start)\n };\n\n ^ result\n }\n}\n\npublic program()\n{\n console.printLine(5.zigzagMatrix()).readChar()\n}\n", "language": "Elena" }, { "code": "defmodule RC do\n require Integer\n def zigzag(n) do\n fmt = \"~#{to_char_list(n*n-1) |> length}w \"\n (for x <- 1..n, y <- 1..n, do: {x,y})\n |> Enum.sort_by(fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end)\n |> Enum.with_index |> Enum.sort\n |> Enum.each(fn {{_x,y},i} ->\n :io.format fmt, [i]\n if y==n, do: IO.puts \"\"\n end)\n end\nend\n\nRC.zigzag(5)\n", "language": "Elixir" }, { "code": "fun zigzag = List by int n\n List matrix = List[].with(n)\n for int y = 0; y < n; y++ do matrix[y] = int[].with(n) end\n int y, x = 1\n for int value = 0; value < n * n; value++\n matrix[y - 1][x - 1] = value\n if (y + x) % 2 == 0\n if x < n do x++\n else do y += 2 end\n if y > 1 do y-- end\n else\n if y < n do y++\n else do x += 2 end\n if x > 1 do x-- end\n end\n end\n return matrix\nend\nfun dump = void by List matrix\n int max = length(text!(matrix.length ** 2)) + 1\n for each List row in matrix\n for each int value in row\n write(\" \" * (max - length(text!value)) + value)\n end\n writeLine()\n end\nend\ndump(zigzag(5))\nwriteLine()\ndump(zigzag(10))\n", "language": "EMal" }, { "code": "-module( zigzag ).\n\n-export( [matrix/1, task/0] ).\n\nmatrix( N ) ->\n\t{{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ),\n\t[columns( X, Proplist ) || X <- lists:seq(0, N - 1)].\n\ntask() -> matrix( 5 ).\n\n\n\ncolumns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ).\n\nmatrix_as_proplist( N, {{X_Y, Max}, Acc} ) ->\n\tNext = next_indexes( X_Y, Max ),\n\t{{Next, Max}, [{X_Y, N} | Acc]}.\n\nnext_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1};\nnext_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X + 1, Y};\nnext_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X, Y + 1};\nnext_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1};\nnext_indexes( {X, 0}, _Max ) when X rem 2 =:= 0 -> {X + 1, 0};\nnext_indexes( {X, 0}, _Max ) when X rem 2 =:= 1 -> {X - 1, 1};\nnext_indexes( {0, Y}, _Max ) when Y rem 2 =:= 0 -> {1, Y - 1};\nnext_indexes( {0, Y}, _Max ) when Y rem 2 =:= 1 -> {0, Y + 1};\nnext_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1};\nnext_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}.\n", "language": "Erlang" }, { "code": "PROGRAM ZIG_ZAG\n\n!$DYNAMIC\n DIM ARRAY%[0,0]\n\nBEGIN\n SIZE%=5\n !$DIM ARRAY%[SIZE%-1,SIZE%-1]\n\n I%=1\n J%=1\n FOR E%=0 TO SIZE%^2-1 DO\n ARRAY%[I%-1,J%-1]=E%\n IF ((I%+J%) AND 1)=0 THEN\n IF J%<SIZE% THEN J%+=1 ELSE I%+=2 END IF\n IF I%>1 THEN I%-=1 END IF\n ELSE\n IF I%<SIZE% THEN I%+=1 ELSE J%+=2 END IF\n IF J%>1 THEN J%-=1 END IF\n END IF\n END FOR\n\n FOR ROW%=0 TO SIZE%-1 DO\n FOR COL%=0 TO SIZE%-1 DO\n WRITE(\"###\";ARRAY%[ROW%,COL%];)\n END FOR\n PRINT\n END FOR\nEND PROGRAM\n", "language": "ERRE" }, { "code": "function zigzag(integer size)\n sequence s\n integer i, j, d, max\n s = repeat(repeat(0,size),size)\n i = 1 j = 1 d = -1\n max = size*size\n for n = 1 to floor(max/2)+1 do\n s[i][j] = n\n s[size-i+1][size-j+1] = max-n+1\n i += d j-= d\n if i < 1 then\n i += 1 d = -d\n elsif j < 1 then\n j += 1 d = -d\n end if\n end for\n return s\nend function\n\n? zigzag(5)\n", "language": "Euphoria" }, { "code": "//Produce a zig zag matrix - Nigel Galloway: April 7th., 2015\nlet zz l a =\n let N = Array2D.create l a 0\n let rec gng (n, i, g, e) =\n N.[n,i] <- g\n match e with\n | _ when i=a-1 && n=l-1 -> N\n | 1 when n = l-1 -> gng (n, i+1, g+1, 2)\n | 2 when i = a-1 -> gng (n+1, i, g+1, 1)\n | 1 when i = 0 -> gng (n+1, 0, g+1, 2)\n | 2 when n = 0 -> gng (0, i+1, g+1, 1)\n | 1 -> gng (n+1, i-1, g+1, 1)\n | _ -> gng (n-1, i+1, g+1, 2)\n gng (0, 0, 0, 2)\n", "language": "F-Sharp" }, { "code": "zz 5 5\n", "language": "F-Sharp" }, { "code": "zz 8 8\n", "language": "F-Sharp" }, { "code": "zz 5 8\n", "language": "F-Sharp" }, { "code": "USING: columns fry kernel make math math.ranges prettyprint\nsequences sequences.cords sequences.extras ;\nIN: rosetta-code.zig-zag-matrix\n\n: [1,b,1] ( n -- seq )\n [1,b] dup but-last-slice <reversed> cord-append ;\n\n: <reversed-evens> ( seq -- seq' )\n [ even? [ <reversed> ] when ] map-index ;\n\n: diagonals ( n -- seq )\n [ sq <iota> ] [ [1,b,1] ] bi\n [ [ cut [ , ] dip ] each ] { } make nip <reversed-evens> ;\n\n: zig-zag-matrix ( n -- seq )\n [ diagonals ] [ dup ] bi '[\n [\n dup 0 <column> _ head ,\n [ _ < [ rest-slice ] when ] map-index harvest\n ] until-empty\n ] { } make ;\n\n: zig-zag-demo ( -- ) 5 zig-zag-matrix simple-table. ;\n\nMAIN: zig-zag-demo\n", "language": "Factor" }, { "code": "USING: assocs assocs.extras grouping io kernel math\nmath.combinatorics math.matrices prettyprint sequences ;\n\n: <zig-zag-matrix> ( n -- matrix )\n [\n dup [ + ] <matrix-by-indices> concat zip-index\n expand-keys-push-at values [ even? [ reverse ] when ]\n map-index concat inverse-permutation\n ] [ group ] bi ;\n\n5 <zig-zag-matrix> simple-table.\n", "language": "Factor" }, { "code": "using gfx // for Point; convenient x/y wrapper\n\n**\n** A couple methods for generating a 'zigzag' array like\n**\n** 0 1 5 6\n** 2 4 7 12\n** 3 8 11 13\n** 9 10 14 15\n**\nclass ZigZag\n{\n ** return an n x n array of uninitialized Int\n static Int[][] makeSquareArray(Int n)\n {\n Int[][] grid := Int[][,] {it.size=n}\n n.times |i| { grid[i] = Int[,] {it.size=n} }\n return grid\n }\n\n\n Int[][] zig(Int n)\n {\n grid := makeSquareArray(n)\n\n move := |Int i, Int j->Point|\n { return j < n - 1 ? Point(i <= 0 ? 0 : i-1, j+1) : Point(i+1, j) }\n pt := Point(0,0)\n (n*n).times |i| {\n grid[pt.y][pt.x] = i\n if ((pt.x+pt.y)%2 != 0) pt = move(pt.x,pt.y)\n else {tmp:= move(pt.y,pt.x); pt = Point(tmp.y, tmp.x) }\n }\n return grid\n }\n\n public static Int[][] zag(Int size)\n {\n data := makeSquareArray(size)\n\n Int i := 1\n Int j := 1\n for (element:=0; element < size * size; element++)\n {\n data[i - 1][j - 1] = element\n if((i + j) % 2 == 0) {\n // Even stripes\n if (j < size) {\n j++\n } else {\n i += 2\n }\n if (i > 1) {\n i--\n }\n } else {\n // Odd stripes\n if (i < size) {\n i++;\n } else {\n j += 2\n }\n if (j > 1) {\n j--\n }\n }\n }\n return data;\n }\n\n Void print(Int[][] data)\n {\n data.each |row|\n {\n buf := StrBuf()\n row.each |num|\n {\n buf.add(num.toStr.justr(3))\n }\n echo(buf)\n }\n }\n\n Void main()\n {\n echo(\"zig method:\")\n print(zig(8))\n echo(\"\\nzag method:\")\n print(zag(8))\n }\n}\n", "language": "Fan" }, { "code": "0 value diag\n\n: south diag abs + cell+ ;\n\n' cell+ value zig\n' south value zag\n\n: init ( n -- )\n 1- cells negate to diag\n ['] cell+ to zig\n ['] south to zag ;\n\n: swap-diag zig zag to zig to zag ;\n\n: put ( n addr -- n+1 addr )\n 2dup ! swap 1+ swap ;\n\n: turn ( addr -- addr+E/S )\n zig execute swap-diag\n diag negate to diag ;\n\n: zigzag ( matrix n -- )\n { n } n init\n 0 swap\n n 1 ?do\n put turn\n i 0 do put diag + loop\n loop\n swap-diag\n n 1 ?do\n put turn\n n i 1+ ?do put diag + loop\n loop\n ! ;\n\n: .matrix ( n matrix -- )\n over 0 do\n cr\n over 0 do\n dup @ 3 .r cell+\n loop\n loop 2drop ;\n\n: test ( n -- ) here over zigzag here .matrix ;\n5 test\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n 10 18 19 23 24 ok\n", "language": "Forth" }, { "code": "PROGRAM ZIGZAG\n\n IMPLICIT NONE\n INTEGER, PARAMETER :: size = 5\n INTEGER :: zzarray(size,size), x(size*size), y(size*size), i, j\n\n ! index arrays\n x = (/ ((j, i = 1, size), j = 1, size) /)\n y = (/ ((i, i = 1, size), j = 1, size) /)\n\n ! Sort indices\n DO i = 2, size*size\n j = i - 1\n DO WHILE (j>=1 .AND. (x(j)+y(j)) > (x(i)+y(i)))\n j = j - 1\n END DO\n x(j+1:i) = cshift(x(j+1:i),-1)\n y(j+1:i) = cshift(y(j+1:i),-1)\n END DO\n\n ! Create zig zag array\n DO i = 1, size*size\n IF (MOD(x(i)+y(i), 2) == 0) THEN\n zzarray(x(i),y(i)) = i - 1\n ELSE\n zzarray(y(i),x(i)) = i - 1\n END IF\n END DO\n\n ! Print zig zag array\n DO j = 1, size\n DO i = 1, size\n WRITE(*, \"(I5)\", ADVANCE=\"NO\") zzarray(i,j)\n END DO\n WRITE(*,*)\n END DO\n\n END PROGRAM ZIGZAG\n", "language": "Fortran" }, { "code": "' FB 1.05.0 Win64\n\nDim As Integer n\n\nDo\n Input \"Enter size of matrix \"; n\nLoop Until n > 0\n\nDim zigzag(1 To n, 1 To n) As Integer '' all zero by default\n\n' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals\nzigzag(1, 1) = 0\nIf n > 1 Then\n Dim As Integer row = 0, col = 3\n Dim As Boolean down = true, increment = true\n Dim As Integer i = 0, j = 2, k\n Do\n If down Then\n For k = 1 To j\n i += 1\n row += 1\n col -= 1\n zigzag(row, col) = i\n Next\n down = false\n Else\n For k = 1 To j\n i += 1\n row -= 1\n col += 1\n zigzag(row, col) = i\n Next\n down = true\n End If\n If increment Then\n j += 1\n If j > n Then\n j = n - 1\n increment = false\n End If\n Else\n j -= 1\n If j = 0 Then Exit Do\n End If\n If down AndAlso increment Then\n col += 2\n row -= 1\n ElseIf Not Down AndAlso increment Then\n row += 2\n col -= 1\n ElseIf down AndAlso Not increment Then\n col += 1\n Else '' Not down AndAlso NotIncrement\n row += 1\n End If\n Loop\nEnd If\n\n' print zigzag matrix if n < 20\nPrint\nIf n < 20 Then\n For i As Integer = 1 To n\n For j As Integer = 1 To n\n Print Using \"####\"; zigzag(i, j);\n Next j\n Print\n Next i\nElse\n Print \"Matrix is too big to display on 80 column console\"\nEnd If\n\nPrint\nPrint \"Press any key to quit\"\nSleep\n", "language": "FreeBASIC" }, { "code": "ZigZag := function(n)\n local a, i, j, k;\n a := NullMat(n, n);\n i := 1;\n j := 1;\n for k in [0 .. n*n - 1] do\n a[i][j] := k;\n if (i + j) mod 2 = 0 then\n if j < n then\n j := j + 1;\n else\n i := i + 2;\n fi;\n if i > 1 then\n i := i - 1;\n fi;\n else\n if i < n then\n i := i + 1;\n else\n j := j + 2;\n fi;\n if j > 1 then\n j := j - 1;\n fi;\n fi;\n od;\n return a;\nend;\n\nPrintArray(ZigZag(5));\n# [ [ 0, 1, 5, 6, 14 ],\n# [ 2, 4, 7, 13, 15 ],\n# [ 3, 8, 12, 16, 21 ],\n# [ 9, 11, 17, 20, 22 ],\n# [ 10, 18, 19, 23, 24 ] ]\n", "language": "GAP" }, { "code": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc zz(n int) []int {\n r := make([]int, n*n)\n i := 0\n n2 := n * 2\n for d := 1; d <= n2; d++ {\n x := d - n\n if x < 0 {\n x = 0\n }\n y := d - 1\n if y > n-1 {\n y = n - 1\n }\n j := n2 - d\n if j > d {\n j = d\n }\n for k := 0; k < j; k++ {\n if d&1 == 0 {\n r[(x+k)*n+y-k] = i\n } else {\n r[(y-k)*n+x+k] = i\n }\n i++\n }\n }\n\n return r\n}\n\nfunc main() {\n const n = 5\n w := len(strconv.Itoa(n*n - 1))\n for i, e := range zz(n) {\n fmt.Printf(\"%*d \", w, e)\n if i%n == n-1 {\n fmt.Println(\"\")\n }\n }\n}\n", "language": "Go" }, { "code": "def zz = { n ->\n grid = new int[n][n]\n i = 0\n for (d in 1..n*2) {\n (x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)]\n Math.min(d, n*2 - d).times {\n grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++;\n }\n }\n grid\n}\n", "language": "Groovy" }, { "code": "def zz = { n->\n move = { i, j -> j < n - 1 ? [i <= 0 ? 0 : i-1, j+1] : [i+1, j] }\n grid = new int[n][n]\n (x, y) = [0, 0]\n (n**2).times {\n grid[y][x] = it\n if ((x+y)%2) (x,y) = move(x,y)\n else (y,x) = move(y,x)\n }\n grid\n}\n", "language": "Groovy" }, { "code": "def zz = { n ->\n (0..<n*n).collect { [x:it%n,y:(int)(it/n)] }.sort { c->\n [c.x+c.y, (((c.x+c.y)%2) ? c.y : -c.y)]\n }.with { l -> l.inject(new int[n][n]) { a, c -> a[c.y][c.x] = l.indexOf(c); a } }\n}\n", "language": "Groovy" }, { "code": "import Data.Array (Array, array, bounds, range, (!))\nimport Text.Printf (printf)\nimport Data.List (sortBy)\n\ncompZig :: (Int, Int) -> (Int, Int) -> Ordering\ncompZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y\n where\n go x y\n | even (x + y) = compare x x_\n | otherwise = compare y y_\n\nzigZag :: (Int, Int) -> Array (Int, Int) Int\nzigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]\n where\n b = ((0, 0), upper)\n", "language": "Haskell" }, { "code": "-- format a 2d array of integers neatly\nshow2d a =\n unlines\n [ unwords\n [ printf \"%3d\" (a ! (x, y) :: Integer)\n | x <- axis fst ]\n | y <- axis snd ]\n where\n (l, h) = bounds a\n axis f = [f l .. f h]\n\nmain = mapM_ (putStr . ('\\n' :) . show2d . zigZag) [(3, 3), (4, 4), (10, 2)]\n", "language": "Haskell" }, { "code": "import Data.Text (justifyRight, pack, unpack)\nimport Data.List (mapAccumL)\nimport Data.Bool (bool)\n\nzigZag :: Int -> [[Int]]\nzigZag = go <*> diagonals\n where\n go _ [] = []\n go n xss = (head <$> edge) : go n (dropWhile null (tail <$> edge) <> rst)\n where\n (edge, rst) = splitAt n xss\n\ndiagonals :: Int -> [[Int]]\ndiagonals n =\n snd $ mapAccumL go [0 .. (n * n) - 1] (slope <> [n] <> reverse slope)\n where\n slope = [1 .. n - 1]\n go xs h = (rst, bool id reverse (0 /= mod h 2) grp)\n where\n (grp, rst) = splitAt h xs\n\nmain :: IO ()\nmain =\n putStrLn $\n unlines $\n concatMap unpack . fmap (justifyRight 3 ' ' . pack . show) <$> zigZag 5\n", "language": "Haskell" }, { "code": "procedure main(args)\n n := integer(!args) | 5\n every !(A := list(n)) := list(n)\n A := zigzag(A)\n show(A)\nend\n\nprocedure show(A)\n every writes(right(!A,5) | \"\\n\")\nend\n\nprocedure zigzag(A)\n x := [0,0]\n every i := 0 to (*A^2 -1) do {\n x := nextIndices(*A, x)\n A[x[1]][x[2]] := i\n }\n return A\nend\n\nprocedure nextIndices(n, x)\n return if (x[1]+x[2])%2 = 0\n then if x[2] = n then [x[1]+1, x[2]] else [max(1, x[1]-1), x[2]+1]\n else if x[1] = n then [x[1], x[2]+1] else [x[1]+1, max(1, x[2]-1)]\nend\n", "language": "Icon" }, { "code": "100 PROGRAM \"ZigZag.bas\"\n110 LET SIZE=5\n120 NUMERIC A(1 TO SIZE,1 TO SIZE)\n130 LET I,J=1\n140 FOR E=0 TO SIZE^2-1\n150 LET A(I,J)=E\n160 IF ((I+J) BAND 1)=0 THEN\n170 IF J<SIZE THEN\n180 LET J=J+1\n190 ELSE\n200 LET I=I+2\n210 END IF\n220 IF I>1 THEN LET I=I-1\n230 ELSE\n240 IF I<SIZE THEN\n250 LET I=I+1\n260 ELSE\n270 LET J=J+2\n280 END IF\n290 IF J>1 THEN LET J=J-1\n300 END IF\n310 NEXT\n320 FOR ROW=1 TO SIZE\n330 FOR COL=1 TO SIZE\n340 PRINT USING \" ##\":A(ROW,COL);\n350 NEXT\n360 PRINT\n370 NEXT\n", "language": "IS-BASIC" }, { "code": " ($ [: /:@; <@|.`</.@i.)@,~ 5\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n", "language": "J" }, { "code": " ($ [: /:@; [: <@(A.~_2|#)/. i.)@,~ 5\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n", "language": "J" }, { "code": " ($ ([: /:@;@(+/\"1 <@|.`</. ]) (#: i.@(*/))))@,~ 5\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n", "language": "J" }, { "code": " ($ [: /:@; [: <@|.`</. i.) 5 3\n0 1 5\n2 4 6\n3 7 11\n8 10 12\n9 13 14\n", "language": "J" }, { "code": "public static int[][] Zig_Zag(final int size)\n{\n int[][] data = new int[size][size];\n int i = 1;\n int j = 1;\n for (int element = 0; element < size * size; element++)\n {\n data[i - 1][j - 1] = element;\n if ((i + j) % 2 == 0)\n {\n // Even stripes\n if (j < size)\n j++;\n else\n i+= 2;\n if (i > 1)\n i--;\n }\n else\n {\n // Odd stripes\n if (i < size)\n i++;\n else\n j+= 2;\n if (j > 1)\n j--;\n }\n }\n return data;\n}\n", "language": "Java" }, { "code": "function ZigZagMatrix(n) {\n this.height = n;\n this.width = n;\n\n this.mtx = [];\n for (var i = 0; i < n; i++)\n this.mtx[i] = [];\n\n var i=1, j=1;\n for (var e = 0; e < n*n; e++) {\n this.mtx[i-1][j-1] = e;\n if ((i + j) % 2 == 0) {\n // Even stripes\n if (j < n) j ++;\n else i += 2;\n if (i > 1) i --;\n } else {\n // Odd stripes\n if (i < n) i ++;\n else j += 2;\n if (j > 1) j --;\n }\n }\n}\nZigZagMatrix.prototype = Matrix.prototype;\n\nvar z = new ZigZagMatrix(5);\nprint(z);\nprint();\n\nz = new ZigZagMatrix(4);\nprint(z);\n", "language": "JavaScript" }, { "code": "(function (n) {\n\n // Read range of values into a series of 'diagonal rows'\n // for a square of given dimension,\n // starting at diagonal row i.\n // [\n // [0],\n // [1, 2],\n // [3, 4, 5],\n // [6, 7, 8, 9],\n // [10, 11, 12, 13, 14],\n // [15, 16, 17, 18],\n // [19, 20, 21],\n // [22, 23],\n // [24]\n // ]\n\n // diagonals :: n -> [[n]]\n function diagonals(n) {\n function diags(xs, iCol, iRow) {\n if (iCol < xs.length) {\n var xxs = splitAt(iCol, xs);\n\n return [xxs[0]].concat(diags(\n xxs[1],\n (iCol + (iRow < n ? 1 : -1)),\n iRow + 1\n ));\n } else return [xs];\n }\n\n return diags(range(0, n * n - 1), 1, 1);\n }\n\n\n\n // Recursively read off n heads from the diagonals (as rows)\n // n -> [[n]] -> [[n]]\n function nHeads(n, lst) {\n var zipEdge = lst.slice(0, n);\n\n return lst.length ? [zipEdge.map(function (x) {\n return x[0];\n })].concat(nHeads(n, [].concat.apply([], zipEdge.map(function (\n x) {\n return x.length > 1 ? [x.slice(1)] : [];\n }))\n .concat(lst.slice(n)))) : [];\n }\n\n // range(intFrom, intTo, optional intStep)\n // Int -> Int -> Maybe Int -> [Int]\n function range(m, n, delta) {\n var d = delta || 1,\n blnUp = n > m,\n lng = Math.floor((blnUp ? n - m : m - n) / d) + 1,\n a = Array(lng),\n i = lng;\n\n if (blnUp)\n while (i--) a[i] = (d * i) + m;\n else\n while (i--) a[i] = m - (d * i);\n return a;\n }\n\n // splitAt :: Int -> [a] -> ([a],[a])\n function splitAt(n, xs) {\n return [xs.slice(0, n), xs.slice(n)];\n }\n\n // Recursively take n heads from the alternately reversed diagonals\n\n // [ [\n // [0], -> [0, 1, 5, 6, 14] and:\n // [1, 2], [2],\n // [5, 4, 3], [4, 3],\n // [6, 7, 8, 9], [7, 8, 9],\n // [14, 13, 12, 11, 10], [13, 12, 11, 10],\n // [15, 16, 17, 18], [15, 16, 17, 18],\n // [21, 20, 19], [21, 20, 19],\n // [22, 23], [22, 23],\n // [24] [24]\n // ] ]\n //\n // In the next recursion with the remnant on the right, the next\n // 5 heads will be [2, 4, 7, 13, 15] - the second row of our zig zag matrix.\n // (and so forth)\n\n\n return nHeads(n, diagonals(n)\n .map(function (x, i) {\n i % 2 || x.reverse();\n return x;\n }));\n\n})(5);\n", "language": "JavaScript" }, { "code": "(n => {\n\n // diagonals :: n -> [[n]]\n function diagonals(n) {\n let diags = (xs, iCol, iRow) => {\n if (iCol < xs.length) {\n let xxs = splitAt(iCol, xs);\n\n return [xxs[0]].concat(diags(\n xxs[1],\n iCol + (iRow < n ? 1 : -1),\n iRow + 1\n ));\n } else return [xs];\n }\n\n return diags(range(0, n * n - 1), 1, 1);\n }\n\n\n // Recursively read off n heads of diagonal lists\n // rowsFromDiagonals :: n -> [[n]] -> [[n]]\n function rowsFromDiagonals(n, lst) {\n if (lst.length) {\n let [edge, rest] = splitAt(n, lst);\n\n return [edge.map(x => x[0])]\n .concat(rowsFromDiagonals(n,\n edge.filter(x => x.length > 1)\n .map(x => x.slice(1))\n .concat(rest)\n ));\n } else return [];\n }\n\n // GENERIC FUNCTIONS\n\n // splitAt :: Int -> [a] -> ([a],[a])\n function splitAt(n, xs) {\n return [xs.slice(0, n), xs.slice(n)];\n }\n\n // range :: From -> To -> Maybe Step -> [Int]\n // range :: Int -> Int -> Maybe Int -> [Int]\n function range(m, n, step) {\n let d = (step || 1) * (n >= m ? 1 : -1);\n\n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, (_, i) => m + (i * d));\n }\n\n // ZIG-ZAG MATRIX\n\n return rowsFromDiagonals(n,\n diagonals(n)\n .map((x, i) => (i % 2 || x.reverse()) && x)\n );\n\n})(5);\n", "language": "JavaScript" }, { "code": "(*\n From the library.\n*)\nDEFINE reverse == [] swap shunt;\n shunt == [swons] step.\n\n(*\n Split according to the parameter given.\n*)\nDEFINE take-drop == [dup] swap dup [[] cons [take swap] concat concat] dip []\n cons concat [drop] concat.\n\n(*\n Take the first of a list of lists.\n*)\nDEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map\n swap dup] concat swap concat [drop swap] concat swap\n concat [take [rest] step []] concat swap concat [[cons]\n times swap concat 1 drop] concat.\n\nDEFINE zigzag ==\n\n(*\n Use take-drop to generate a list of lists.\n*)\n4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat\nswap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons]\nwhile\n\n(*\n The odd numbers must be modified with reverse.\n*)\n[dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map\n\n(*\n Take the first of the first of n lists.\n*)\nswap dup take-first [i] cons times pop\n\n(*\n Merge the n separate lists.\n*)\n[] [pop list] [cons] while\n\n(*\n And print them.\n*)\nswap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars]\nconcat [step '\\n putch] cons step.\n\n11 zigzag.\n", "language": "Joy" }, { "code": "# Create an m x n matrix\n def matrix(m; n; init):\n if m == 0 then []\n elif m == 1 then [range(0;n)] | map(init)\n elif m > 0 then\n matrix(1;n;init) as $row\n | [range(0;m)] | map( $row )\n else error(\"matrix\\(m);_;_) invalid\")\n end ;\n\n# Print a matrix neatly, each cell occupying n spaces\ndef neatly(n):\n def right: tostring | ( \" \" * (n-length) + .);\n . as $in\n | length as $length\n | reduce range (0;$length) as $i\n (\"\"; . + reduce range(0;$length) as $j\n (\"\"; \"\\(.) \\($in[$i][$j] | right )\" ) + \"\\n\" ) ;\n", "language": "Jq" }, { "code": "def zigzag(n):\n\n # unless m == n*n, place m at (i,j), pointing\n # in the direction d, where d = [drow, dcolumn]:\n def _next(i; j; m; d):\n if m == (n*n) then . else .[i][j] = m end\n | if m == (n*n) - 1 then .\n elif i == n-1 then if j+1 < n then .[i][j+1] = m+1 | _next(i-1; j+2; m+2; [-1, 1]) else . end\n elif i == 0 then if j+1 < n then .[i][j+1] = m+1 | _next(i+1; j ; m+2; [ 1,-1])\n else .[i+1][j] = m+1 | _next(i+2; j-1; m+2; [ 1,-1]) end\n elif j == n-1 then if i+1 < n then .[i+1][j] = m+1 | _next(i+2; j-1; m+2; [ 1,-1]) else . end\n elif j == 0 then if i+1 < n then .[i+1][j] = m+1 | _next(i; j+1; m+2; [-1, 1])\n else .[i][j+1] = m+1 | _next(i-1; j+1; m+2; [-1, 1]) end\n else _next(i+ d[0]; j+ d[1]; m+1; d)\n end ;\n matrix(n;n;-1) | _next(0;0; 0; [0,1]) ;\n\n# Example\nzigzag(5) | neatly(4)\n", "language": "Jq" }, { "code": "#!/usr/bin/env jq -Mnrc -f\n#\n# solve zigzag matrix by constructing list of 2n+1 column \"runs\"\n# and then shifting them into final form.\n#\n# e.g. for n=3 initial runs are [[0],[1,2],[3,4,5],[6,7],[8]]\n# runs below are shown as columns:\n#\n# initial column runs 0 1 3 6 8\n# 2 4 7\n# 5\n#\n# reverse cols 0,2,4 0 1 5 6 8\n# 2 4 7\n# 3\n#\n# shift cols 3,4 down 0 1 5\n# 2 4 6\n# 3 7 8\n#\n# shift rows left 0 1 5\n# to get final zigzag 2 4 6\n# 3 7 8\n\n def N: $n ; # size of matrix\n def NR: 2*N - 1; # number of runs\n def abs: if .<0 then -. else . end ; # absolute value\n def runlen: N-(N-.|abs) ; # length of run\n def makeruns: [\n foreach range(1;NR+1) as $r ( # for each run\n {c:0} # state counter\n ; .l = ($r|runlen) # length of this run\n | .r = [range(.c;.c+.l)] # values in this run\n | .c += .l # increment counter\n ; .r # produce run\n ) ] ; # collect into array\n def even: .%2==0 ; # is input even?\n def reverseruns: # reverse alternate runs\n .[keys|map(select(even))[]] |= reverse ;\n def zeros: [range(.|N-length)|0] ; # array of padding zeros\n def shiftdown:\n def pad($r): # pad run with zeros\n if $r < N # determine where zeros go\n then . = . + zeros # at back for left runs\n else . = zeros + . # at front for right runs\n end ;\n reduce keys[] as $r (.;.[$r] |= pad($r)); # shift rows down with pad\n def shiftleft: [\n range(N) as $r\n | [ range($r;$r+N) as $c\n | .[$c][$r]\n ]\n ] ;\n def width: [.[][]]|max|tostring|1+length; # width of largest value\n def justify($w): (($w-length)*\" \") + . ; # leading spaces\n def format:\n width as $w # compute width\n | map(map(tostring | justify($w)))[] # justify values\n | join(\" \")\n ;\n makeruns # create column runs\n | reverseruns # reverse alternate runs\n | shiftdown # shift right runs down\n | shiftleft # shift rows left\n | format # format final result\n", "language": "Jq" }, { "code": "function zigzag_matrix(n::Int)\n matrix = zeros(Int, n, n)\n x, y = 1, 1\n for i = 0:(n*n-1)\n matrix[y,x] = i\n if (x + y) % 2 == 0\n # Even stripes\n if x < n\n x += 1\n y -= (y > 1)\n else\n y += 1\n end\n else\n # Odd stripes\n if y < n\n x -= (x > 1)\n y += 1\n else\n x += 1\n end\n end\n end\n return matrix\nend\n", "language": "Julia" }, { "code": "immutable ZigZag\n m::Int\n n::Int\n diag::Array{Int,1}\n cmax::Int\n numd::Int\n lohi::(Int,Int)\nend\n\nfunction zigzag(m::Int, n::Int)\n 0<m && 0<n || error(\"The matrix dimensions must be positive.\")\n ZigZag(m, n, [-1,1], m*n, m+n-1, extrema([m,n]))\nend\nzigzag(n::Int) = zigzag(n, n)\n\ntype ZZState\n cnt::Int\n cell::Array{Int,1}\n dir::Int\n dnum::Int\n dlen::Int\n dcnt::Int\nend\n\nBase.length(zz::ZigZag) = zz.cmax\nBase.start(zz::ZigZag) = ZZState(1, [1,1], 1, 1, 1, 1)\nBase.done(zz::ZigZag, zzs::ZZState) = zzs.cnt > zz.cmax\n\nfunction Base.next(zz::ZigZag, zzs::ZZState)\n s = sub2ind((zz.m, zz.n), zzs.cell[1], zzs.cell[2])\n if zzs.dcnt == zzs.dlen\n if isodd(zzs.dnum)\n if zzs.cell[2] < zz.n\n zzs.cell[2] += 1\n else\n zzs.cell[1] += 1\n end\n else\n if zzs.cell[1] < zz.m\n zzs.cell[1] += 1\n else\n zzs.cell[2] += 1\n end\n end\n zzs.dcnt = 1\n zzs.dnum += 1\n zzs.dir = -zzs.dir\n if zzs.dnum <= zz.lohi[1]\n zzs.dlen += 1\n elseif zz.lohi[2] < zzs.dnum\n zzs.dlen -= 1\n end\n else\n zzs.cell += zzs.dir*zz.diag\n zzs.dcnt += 1\n end\n zzs.cnt += 1\n return (s, zzs)\nend\n", "language": "Julia" }, { "code": "using Formatting\n\nfunction width{T<:Integer}(n::T)\n w = ndigits(n)\n n < 0 || return w\n return w + 1\nend\n\nfunction pretty{T<:Integer}(a::Array{T,2}, indent::Int=4)\n lo, hi = extrema(a)\n w = max(width(lo), width(hi))\n id = \" \"^indent\n fe = FormatExpr(@sprintf(\" {:%dd}\", w))\n s = id\n nrow = size(a)[1]\n for i in 1:nrow\n for j in a[i,:]\n s *= format(fe, j)\n end\n i != nrow || continue\n s *= \"\\n\"*id\n end\n return s\nend\n", "language": "Julia" }, { "code": "n = 5\nprintln(\"The n = \", n, \" zig-zag matrix:\")\na = zeros(Int, (n, n))\nfor (i, s) in enumerate(zigzag(n))\n a[s] = i-1\nend\nprintln(pretty(a))\n\nm = 3\nprintln()\nprintln(\"Generalize to a non-square matrix (\", m, \"x\", n, \"):\")\na = zeros(Int, (m, n))\nfor (i, s) in enumerate(zigzag(m, n))\n a[s] = i-1\nend\nprintln(pretty(a))\n\np = primes(10^3)\nn = 7\nprintln()\nprintln(\"An n = \", n, \" prime spiral matrix:\")\na = zeros(Int, (n, n))\nfor (i, s) in enumerate(zigzag(n))\n a[s] = p[i]\nend\nprintln(pretty(a))\n", "language": "Julia" }, { "code": "f:{grid:+x#<<a,'(!#a)*- 2!a:+/!x,:x\n padded:(-#$-1+*/x)$$grid\n `0:\" \"/'padded}\nf 5\n", "language": "K" }, { "code": "include ..\\Utilitys.tlhy\n\n\n%Size 5 !Size\n0 ( $Size dup ) dim\n\n%i 1 !i %j 1 !j\n\n\n$Size 2 power [\n 1 -\n ( $i $j ) set\n $i $j + 1 band 0 == (\n [$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if\n $i 1 > [ $i 1 - !i] if ]\n [$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if\n $j 1 > [ $j 1 - !j] if ]\n ) if\n] for\n\n$Size [\n %row !row\n $Size [\n %col !col\n ( $row $col ) get tostr 32 32 chain chain 1 3 slice print drop\n ] for\n nl\n] for\n\n\nnl \"End \" input\n", "language": "Klingphix" }, { "code": "// version 1.1.3\n\ntypealias Vector = IntArray\ntypealias Matrix = Array<Vector>\n\nfun zigzagMatrix(n: Int): Matrix {\n val result = Matrix(n) { Vector(n) }\n var down = false\n var count = 0\n for (col in 0 until n) {\n if (down)\n for (row in 0..col) result[row][col - row] = count++\n else\n for (row in col downTo 0) result[row][col - row] = count++\n down = !down\n }\n for (row in 1 until n) {\n if (down)\n for (col in n - 1 downTo row) result[row + n - 1 - col][col] = count++\n else\n for (col in row until n) result[row + n - 1 - col][col] = count++\n down = !down\n }\n return result\n}\nfun printMatrix(m: Matrix) {\n for (i in 0 until m.size) {\n for (j in 0 until m.size) print(\"%2d \".format(m[i][j]))\n println()\n }\n println()\n}\n\nfun main(args: Array<String>) {\n printMatrix(zigzagMatrix(5))\n printMatrix(zigzagMatrix(10))\n}\n", "language": "Kotlin" }, { "code": "#!/bin/ksh\n\n# Produce a zig-zag array.\n\n#\t# Variables:\n#\ninteger DEF_SIZE=5\t\t\t# Default size = 5\narr_size=${1:-$DEF_SIZE}\t# $1 = size, or default\n\n #\t# Externals:\n #\n\n#\t# Functions:\n#\n\n\n ######\n# main #\n ######\ninteger i j n\ntypeset -a zzarr\n\nfor (( i=n=0; i<arr_size*2; i++ )); do\n\tfor (( j= (i<arr_size) ? 0 : i-arr_size+1; j<=i && j<arr_size; j++ )); do\n\t\t(( zzarr[(i&1) ? j*(arr_size-1)+i : (i-j)*arr_size+j] = n++ ))\n\tdone\ndone\n\nfor ((i=0; i<arr_size*arr_size; i++)); do\n\tprintf \"%3d \" ${zzarr[i]}\n\t(( (i+1)%arr_size == 0 )) && printf \"\\n\"\ndone\n", "language": "Ksh" }, { "code": "var(\n 'square' = array\n ,'size' = integer( 5 )// for a 5 X 5 square\n ,'row' = array\n ,'x' = integer( 1 )\n ,'y' = integer( 1 )\n ,'counter' = integer( 1 )\n);\n\n// create place-holder matrix\nloop( $size );\n $row = array;\n\n loop( $size );\n $row->insert( 0 );\n\n /loop;\n\n $square->insert( $row );\n\n/loop;\n\nwhile( $counter < $size * $size );\n // check downward diagonal\n if(\n $x > 1\n &&\n $y < $square->size\n &&\n $square->get( $y + 1 )->get( $x - 1 ) == 0\n );\n\n $x -= 1;\n $y += 1;\n\n // check upward diagonal\n else(\n $x < $square->size\n &&\n $y > 1\n &&\n $square->get( $y - 1 )->get( $x + 1 ) == 0\n );\n\n $x += 1;\n $y -= 1;\n\n // check right\n else(\n (\n $y == 1\n ||\n $y == $square->size\n )\n &&\n $x < $square->size\n &&\n $square->get( $y )->get( $x + 1 ) == 0\n );\n\n $x += 1;\n\n // down\n else;\n $y += 1;\n\n /if;\n\n $square->get( $y )->get( $x ) = loop_count;\n\n $counter += 1;\n\n/while;\n\n$square;\n", "language": "Lasso" }, { "code": "local zigzag = {}\n\nfunction zigzag.new(n)\n local a = {}\n local i -- cols\n local j -- rows\n\n a.n = n\n a.val = {}\n\n for j = 1, n do\n a.val[j] = {}\n for i = 1, n do\n a.val[j][i] = 0\n end\n end\n\n i = 1\n j = 1\n\n local di\n local dj\n local k = 0\n\n while k < n * n do\n a.val[j][i] = k\n k = k + 1\n if i == n then\n j = j + 1\n a.val[j][i] = k\n k = k + 1\n di = -1\n dj = 1\n end\n if j == 1 then\n i = i + 1\n a.val[j][i] = k\n k = k + 1\n di = -1\n dj = 1\n end\n if j == n then\n i = i + 1\n a.val[j][i] = k\n k = k + 1\n di = 1\n dj = -1\n end\n if i == 1 then\n j = j + 1\n a.val[j][i] = k\n k = k + 1\n di = 1\n dj = -1\n end\n i = i + di\n j = j + dj\n end\n\n setmetatable(a, {__index = zigzag, __tostring = zigzag.__tostring})\n return a\nend\n\nfunction zigzag:__tostring()\n local s = {}\n for j = 1, self.n do\n local row = {}\n for i = 1, self.n do\n row[i] = string.format('%d', self.val[j][i])\n end\n s[j] = table.concat(row, ' ')\n end\n return table.concat(s, '\\n')\nend\n\nprint(zigzag.new(5))\n", "language": "Lua" }, { "code": "Module Lib1 {\n\tModule Global PrintArray(&Ar()) {\n\t\tif dimension(Ar())<>2 then Error \"This is for 2D arrays\"\n\t\tinteger i, j, n=dimension(Ar(),1), n1=dimension(Ar(),2)\n\t\tfor i=1 to n\n\t\t\tfor j=1 to n1\n\t\t\t\tprint Ar(i, j),\n\t\t\tnext\n\t\t\tprint\n\t\tnext\n\t}\n\tFunction Global MakeArray(n as integer=5) {\n\t\tdim a(1 to n, 1 to n) as integer=0\n\t\tinteger i=1, j=1, z, t1=1\n\t\tboolean ch=true\n\t\tfor z=0 to n*n-1\n\t\t\tif ch then a(i,j)=z else a(j,i)=z\n\t\t\tj++\n\t\t\tif j>t1 then t1++: j=1:i=t1: ch~ else i--\n\t\t\tif i<1 then i=t1 else.if i>n then i=n: j++\n\t\t\tif j>n then j=i+2: i=n:ch~\n\t\tnext\n\t\t=a() // return array (as a pointer)\n\t}\n}\nModule Zig_Zag_Matrix (n as integer=5) {\n\tPen 15 {Report \"matrix \"+n+\"x\"+n}\n\tinteger old_column=tab\n\tPrint $(,4) // set column to 4 chars\n\tif random(1,2)=2 then\n\t\tdim ret()\n\t\tret()=makeArray(n) // this get a copy\n\telse\n\t\tobject a=makeArray(n) // but this get the copy of pointer\n\t\tlink a to ret() // ret() is reference to a, to array\n\tend if\n\tPrintArray &ret()\n\tPrint $(,old_column)\n}\nInline Code Lib1 // just execute the code from module lib1 like was here\nForm 60, 36 \\\\ console 60x36 characters\nReport 2, \"Zig-zag matrix\" // 2 for center\nPen 14 {Zig_Zag_Matrix 1}\nPen 11 {Zig_Zag_Matrix 2}\nPen 14 {Zig_Zag_Matrix 3}\nPen 11 {Zig_Zag_Matrix 4}\nPen 14 {Zig_Zag_Matrix 5}\nPen 11 {Zig_Zag_Matrix 10}\n", "language": "M2000-Interpreter" }, { "code": "divert(-1)\n\ndefine(`set2d',`define(`$1[$2][$3]',`$4')')\ndefine(`get2d',`defn(`$1[$2][$3]')')\ndefine(`for',\n `ifelse($#,0,``$0'',\n `ifelse(eval($2<=$3),1,\n `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')\ndefine(`show2d',\n `for(`x',0,decr($2),\n `for(`y',0,decr($3),`format(`%2d',get2d($1,x,y)) ')\n')')\n\ndnl <name>,<size>\ndefine(`zigzag',\n `define(`j',1)`'define(`k',1)`'for(`e',0,eval($2*$2-1),\n `set2d($1,decr(j),decr(k),e)`'ifelse(eval((j+k)%2),0,\n `ifelse(eval(k<$2),1,\n `define(`k',incr(k))',\n `define(`j',eval(j+2))')`'ifelse(eval(j>1),1,\n `define(`j',decr(j))')',\n `ifelse(eval(j<$2),1,\n `define(`j',incr(j))',\n `define(`k',eval(k+2))')`'ifelse(eval(k>1),1,\n `define(`k',decr(k))')')')')\n\ndivert\n\nzigzag(`a',5)\nshow2d(`a',5,5)\n", "language": "M4" }, { "code": "zigzag1:=proc(n)\n uses ArrayTools;\n local i,u,v,a;\n u:=Replicate(<-1,1>,n):\n v:=Vector[row](1..n,i->i*(2*i-3)):\n v:=Reshape(<v+~1,v+~2>,2*n):\n a:=Matrix(n,n):\n for i to n do\n a[...,i]:=v[i+1..i+n];\n v+=u\n od:\n a\nend:\n\nzigzag2:=proc(n)\n local i,v,a;\n a:=zigzag1(n);\n v:=Vector(1..n-1,i->i^2);\n for i from 2 to n do\n a[n+2-i..n,i]-=v[1..i-1]\n od;\n a\nend:\n", "language": "Maple" }, { "code": "zigzag1(6);\n", "language": "Maple" }, { "code": "zigzag2(6);\n", "language": "Maple" }, { "code": "ZigZag[size_Integer/;size>0]:=Module[{empty=ConstantArray[0,{size,size}]},\n empty=ReplacePart[empty,{i_,j_}:>1/2 (i+j)^2-(i+j)/2-i (1-Mod[i+j,2])-j Mod[i+j,2]];\n ReplacePart[empty,{i_,j_}/;i+j>size+1:> size^2-tmp[[size-i+1,size-j+1]]-1]\n]\n", "language": "Mathematica" }, { "code": "ZigZag2[size_] := Module[{data, i, j, elem},\n data = ConstantArray[0, {size, size}];\n i = j = 1;\n For[elem = 0, elem < size^2, elem++,\n data[[i, j]] = elem;\n If[Mod[i + j, 2] == 0,\n If[j < size, j++, i += 2];\n If[i > 1, i--]\n ,\n If[i < size, i++, j += 2];\n If[j > 1, j--];\n ];\n ];\n data\n ]\n", "language": "Mathematica" }, { "code": "ZigZag[5] // MatrixForm\nZigZag2[6] // MatrixForm\n", "language": "Mathematica" }, { "code": "function matrix = zigZag(n)\n\n %This is very unintiutive. This algorithm parameterizes the\n %zig-zagging movement along the matrix indicies. The easiest way to see\n %what this algorithm does is to go through line-by-line and write out\n %what the algorithm does on a peace of paper.\n\n matrix = zeros(n);\n counter = 1;\n flipCol = true;\n flipRow = false;\n\n %This for loop does the top-diagonal of the matrix\n for i = (2:n)\n row = (1:i);\n column = (1:i);\n\n %Causes the zig-zagging. Without these conditionals,\n %you would end up with a diagonal matrix.\n %To see what happens, comment these conditionals out.\n if flipCol\n column = fliplr(column);\n flipRow = true;\n flipCol = false;\n elseif flipRow\n row = fliplr(row);\n flipRow = false;\n flipCol = true;\n end\n\n %Selects a diagonal of the zig-zag matrix and places the\n %correct integer value in each index along that diagonal\n for j = (1:numel(row))\n matrix(row(j),column(j)) = counter;\n counter = counter + 1;\n end\n end\n\n %This for loop does the bottom-diagonal of the matrix\n for i = (2:n)\n row = (i:n);\n column = (i:n);\n\n %Causes the zig-zagging. Without these conditionals,\n %you would end up with a diagonal matrix.\n %To see what happens comment these conditionals out.\n if flipCol\n column = fliplr(column);\n flipRow = true;\n flipCol = false;\n elseif flipRow\n row = fliplr(row);\n flipRow = false;\n flipCol = true;\n end\n\n %Selects a diagonal of the zig-zag matrix and places the\n %correct integer value in each index along that diagonal\n for j = (1:numel(row))\n matrix(row(j),column(j)) = counter;\n counter = counter + 1;\n end\n end\n\n\nend\n", "language": "MATLAB" }, { "code": "zigzag(n) := block([a, i, j],\na: zeromatrix(n, n),\ni: 1,\nj: 1,\nfor k from 0 thru n*n - 1 do (\n a[i, j]: k,\n if evenp(i + j) then (\n if j < n then j: j + 1 else i: i + 2,\n if i > 1 then i: i - 1\n ) else (\n if i < n then i: i + 1 else j: j + 2,\n if j > 1 then j: j - 1\n )\n),\na)$\n\nzigzag(5);\n/* matrix([ 0, 1, 5, 6, 14],\n [ 2, 4, 7, 13, 15],\n [ 3, 8, 12, 16, 21],\n [ 9, 11, 17, 20, 22],\n [10, 18, 19, 23, 24]) */\n", "language": "Maxima" }, { "code": "%Zigzag Matrix. Nigel Galloway, February 3rd., 2020\nint: Size;\narray [1..Size,1..Size] of var 1..Size*Size: zigzag;\nconstraint zigzag[1,1]=1 /\\ zigzag[Size,Size]=Size*Size;\nconstraint forall(n in {2*g | g in 1..Size div 2})(zigzag[1,n]=zigzag[1,n-1]+1 /\\ forall(g in 2..n)(zigzag[g,n-g+1]=zigzag[g-1,n-g+2]+1));\nconstraint forall(n in {2*g + ((Size-1) mod 2) | g in 1..(Size-1) div 2})(zigzag[n,Size]=zigzag[n-1,Size]+1 /\\ forall(g in 1..Size-n)(zigzag[n+g,Size-g]=zigzag[n+g-1,Size-g+1]+1));\nconstraint forall(n in {2*g+1 | g in 1..(Size-1) div 2})(zigzag[n,1]=zigzag[n-1,1]+1 /\\ forall(g in 2..n)(zigzag[n-g+1,g]=zigzag[n-g+2,g-1]+1));\nconstraint forall(n in {2*g+((Size) mod 2) | g in 1..(Size-1) div 2})(zigzag[Size,n]=zigzag[Size,n-1]+1 /\\ forall(g in 1..Size-n)(zigzag[Size-g,n+g]=zigzag[Size-g+1,n+g-1]+1));\noutput [show2d(zigzag)];\n", "language": "MiniZinc" }, { "code": "MODULE ZigZag EXPORTS Main;\n\nIMPORT IO, Fmt;\n\nTYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL;\n\nPROCEDURE Create(size: CARDINAL): Matrix =\n PROCEDURE move(VAR i, j: INTEGER) =\n BEGIN\n IF j < (size - 1) THEN\n IF (i - 1) < 0 THEN\n i := 0;\n ELSE\n i := i - 1;\n END;\n INC(j);\n ELSE\n INC(i);\n END;\n END move;\n\n VAR data := NEW(Matrix, size, size);\n x, y: INTEGER := 0;\n BEGIN\n FOR v := 0 TO size * size - 1 DO\n data[y, x] := v;\n IF (x + y) MOD 2 = 0 THEN\n move(y, x);\n ELSE\n move(x, y);\n END;\n END;\n RETURN data;\n END Create;\n\nPROCEDURE Print(data: Matrix) =\n BEGIN\n FOR i := FIRST(data^) TO LAST(data^) DO\n FOR j := FIRST(data[0]) TO LAST(data[0]) DO\n IO.Put(Fmt.F(\"%3s\", Fmt.Int(data[i, j])));\n END;\n IO.Put(\"\\n\");\n END;\n END Print;\n\nBEGIN\n Print(Create(5));\nEND ZigZag.\n", "language": "Modula-3" }, { "code": "/* NetRexx */\noptions replace format comments java crossref savelog symbols binary\n\nzigzag(5)\n\nreturn\n\nmethod zigzag(msize) public static\n\n row = 1\n col = 1\n\n ziggy = Rexx(0)\n loop j_ = 0 for msize * msize\n ziggy[row, col] = j_\n if (row + col) // 2 == 0 then do\n if col < msize then -\n col = col + 1\n else row = row + 2\n if row \\== 1 then -\n row = row - 1\n end\n else do\n if row < msize then -\n row = row + 1\n else col = col + 2\n if col \\== 1 then -\n col = col - 1\n end\n end j_\n\n L = (msize * msize - 1).length /*for a constant element width. */\n loop row = 1 for msize /*show all the matrix's rows. */\n rowOut = ''\n loop col = 1 for msize\n rowOut = rowOut ziggy[row, col].right(L)\n end col\n say rowOut\n end row\n\n return\n", "language": "NetRexx" }, { "code": "from algorithm import sort\nfrom strutils import align\nfrom sequtils import newSeqWith\n\ntype Pos = tuple[x, y: int]\n\nproc `<` (a, b: Pos): bool =\n a.x + a.y < b.x + b.y or\n a.x + a.y == b.x + b.y and (a.x < b.x xor (a.x + a.y) mod 2 == 0)\n\nproc zigzagMatrix(n: int): auto =\n var indices = newSeqOfCap[Pos](n*n)\n\n for x in 0 ..< n:\n for y in 0 ..< n:\n indices.add((x,y))\n\n sort(indices)\n\n result = newSeqWith(n, newSeq[int](n))\n for i, p in indices:\n result[p.x][p.y] = i\n\nproc `$`(m: seq[seq[int]]): string =\n let Width = len($m[0][^1]) + 1\n for r in m:\n for c in r:\n result.add align($c, Width)\n result.add \"\\n\"\n\necho zigzagMatrix(6)\n", "language": "Nim" }, { "code": "import strutils\n\nfunc sumTo(n: Natural): Natural = n * (n+1) div 2\n\nfunc coord2num(row, col, N: Natural): Natural =\n var start, offset: Natural\n let diag = col + row\n if diag < N:\n start = sumTo(diag)\n offset = if diag mod 2 == 0: col else: row\n else:\n # N * (2*diag+1-N) - sumTo(diag), but with smaller itermediates\n start = N*N - sumTo(2*N-1-diag)\n offset = N-1 - (if diag mod 2 == 0: row else: col)\n start + offset\n\nlet N = 6\nlet width = (N*N).`$`.len + 1\nfor row in 0 ..< N:\n for col in 0 ..< N:\n stdout.write(coord2num(row, col, N).`$`.align(width))\n stdout.write(\"\\n\")\n", "language": "Nim" }, { "code": "function : native : ZigZag(size : Int) ~ Int[,] {\n data := Int->New[size, size];\n i := 1;\n j := 1;\n\n max := size * size;\n for(element := 0; element < max ; element += 1;) {\n data[i - 1, j - 1] := element;\n\n if((i + j) % 2 = 0) {\n # even stripes\n if(j < size){\n j += 1;\n }\n else{\n i+= 2;\n };\n\n if(i > 1) {\n i -= 1;\n };\n }\n else{\n # ddd stripes\n if(i < size){\n i += 1;\n }\n else{\n j+= 2;\n };\n\n if(j > 1){\n j -= 1;\n };\n };\n };\n\n return data;\n}\n", "language": "Objeck" }, { "code": "let zigzag n =\n (* move takes references and modifies them directly *)\n let move i j =\n if !j < n - 1 then begin\n i := max 0 (!i - 1);\n incr j\n end else\n incr i\n in\n let a = Array.make_matrix n n 0\n and x = ref 0 and y = ref 0 in\n for v = 0 to n * n - 1 do\n a.(!x).(!y) <- v;\n if (!x + !y) mod 2 = 0 then\n move x y\n else\n move y x\n done;\n a\n", "language": "OCaml" }, { "code": "function a = zigzag1(n)\n j = 1:n;\n u = repmat([-1; 1], n, 1);\n v = j.*(2*j-3);\n v = reshape([v; v+1], 2*n, 1);\n a = zeros(n, n);\n for i = 1:n\n a(:, i) = v(i+j);\n v += u;\n endfor\nendfunction\n\nfunction a = zigzag2(n)\n a = zigzag1(n);\n v = (1:n-1)'.^2;\n for i = 2:n\n a(n+2-i:n, i) -= v(1:i-1);\n endfor\nendfunction\n\n>> zigzag2(5)\nans =\n\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n 10 18 19 23 24\n", "language": "Octave" }, { "code": "function a = zigzag3(n)\n a = zeros(n, n);\n for k=1:n\n d = (2*(j = mod(k, 2))-1)*(n-1);\n m = (n-1)*(k-1);\n a(k+(1-j)*m:d:k+j*m) = k*(k-1)/2:k*(k+1)/2-1;\n a(n*(n+1-k)+(1-j)*m:d:n*(n+1-k)+j*m) = n*n-k*(k+1)/2:n*n-k*(k-1)/2-1;\n endfor\nendfunction\n\n>> zigzag3(5)\nans =\n\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n 10 18 19 23 24\n", "language": "Octave" }, { "code": "#{\n Produce a zigzag matrix. Nigel Galloway, January 26th., 2020.\n At the time of writing the Rascal solution is yellow flagged for producing a striped matrix.\n Let me make the same faux pas.\n#}\nn=5; g=1;\nfor e=1:n i=1; for l=e:-1:1 zig(i++,l)=g++; endfor endfor\nfor e=2:n i=e; for l=n:-1:e zig(i++,l)=g++; endfor endfor\n#{\n I then have the following, let me call it zig.\n 1 2 4 7 11\n 3 5 8 12 16\n 6 9 13 17 20\n 10 14 18 21 23\n 15 19 22 24 25\n\n To avoid being yellow flagged I must convert this striped matrix into a zigzag matrix.\n#}\nzag=zig'\n#{\n So zag is the transpose of zig.\n 1 3 6 10 15\n 2 5 9 14 19\n 4 8 13 18 22\n 7 12 17 21 24\n 11 16 20 23 25\n#}\nfor e=1:n for g=1:n if(mod(e+g,2))==0 zagM(e,g)=1; endif endfor endfor; zigM=1-zagM;\n#{\n I now have 2 masks:\n\n zigM =\n\n 0 1 0 1 0\n 1 0 1 0 1\n 0 1 0 1 0\n 1 0 1 0 1\n 0 1 0 1 0\n\n zagM =\n\n 1 0 1 0 1\n 0 1 0 1 0\n 1 0 1 0 1\n 0 1 0 1 0\n 1 0 1 0 1\n#}\nzigzag=zag.*zagM+zig.*zigM;\n#{\n zigzag =\n\n 1 2 6 7 15\n 3 5 8 14 16\n 4 9 13 17 22\n 10 12 18 21 23\n 11 19 20 24 25\n#}\n", "language": "Octave" }, { "code": "call printArray zigzag(3)\nsay\ncall printArray zigzag(4)\nsay\ncall printArray zigzag(5)\n\n::routine zigzag\n use strict arg size\n\n data = .array~new(size, size)\n row = 1\n col = 1\n\n loop element = 0 to (size * size) - 1\n data[row, col] = element\n -- even stripes\n if (row + col) // 2 = 0 then do\n if col < size then col += 1\n else row += 2\n if row > 1 then row -= 1\n end\n -- odd rows\n else do\n if row < size then row += 1\n else col += 2\n if col > 1 then col -= 1\n end\n end\n\n return data\n\n::routine printArray\n use arg array\n dimension = array~dimension(1)\n loop i = 1 to dimension\n line = \"|\"\n loop j = 1 to dimension\n line = line array[i, j]~right(2)\n end\n line = line \"|\"\n say line\n end\n", "language": "OoRexx" }, { "code": "declare\n %% state move success failure\n States = unit(right: [ 1# 0 downLeft downInstead]\n downInstead: [ 0# 1 downLeft terminate]\n downLeft: [~1# 1 downLeft down]\n down: [ 0# 1 topRight rightInstead]\n rightInstead: [ 1# 0 topRight terminate]\n topRight: [ 1#~1 topRight right])\n\n fun {CreateZigZag N}\n ZZ = {Create2DTuple N N}\n\n %% recursively walk through 2D tuple and set values\n proc {Walk Pos=X#Y Count State}\n [Dir Success Failure] = States.State\n NextPos = {Record.zip Pos Dir Number.'+'}\n Valid = {Record.all NextPos fun {$ C} C > 0 andthen C =< N end}\n NewPos = if Valid then NextPos else Pos end\n NewCount = if Valid then Count + 1 else Count end\n NewState = if Valid then Success else Failure end\n in\n ZZ.Y.X = Count\n if NewState \\= terminate then\n {Walk NewPos NewCount NewState}\n end\n end\n in\n {Walk 1#1 0 right}\n ZZ\n end\n\n fun {Create2DTuple W H}\n T = {MakeTuple unit H}\n in\n {Record.forAll T fun {$} {MakeTuple unit W} end}\n T\n end\nin\n {Inspect {CreateZigZag 5}}\n", "language": "Oz" }, { "code": "zz(n)={\n\tmy(M=matrix(n,n),i,j,d=-1,start,end=n^2-1);\n\twhile(ct--,\n\t\tM[i+1,j+1]=start;\n\t\tM[n-i,n-j]=end;\n\t\tstart++;\n\t\tend--;\n\t\ti+=d;\n\t\tj-=d;\n\t\tif(i<0,\n\t\t\ti++;\n\t\t\td=-d\n\t\t,\n\t\t\tif(j<0,\n\t\t\t\tj++;\n\t\t\t\td=-d\n\t\t\t)\n\t\t);\n\t\tif(start>end,return(M))\n\t)\n};\n", "language": "PARI-GP" }, { "code": "Program zigzag( input, output );\n\nconst\n size = 5;\nvar\n zzarray: array [1..size, 1..size] of integer;\n element, i, j: integer;\n direction: integer;\n width, n: integer;\n\nbegin\n i := 1;\n j := 1;\n direction := 1;\n for element := 0 to (size*size) - 1 do\n begin\n zzarray[i,j] := element;\n i := i + direction;\n j := j - direction;\n if (i = 0) then\n begin\n direction := -direction;\n i := 1;\n if (j > size) then\n begin\n j := size;\n i := 2;\n end;\n end\n else if (i > size) then\n begin\n direction := -direction;\n i := size;\n j := j + 2;\n end\n else if (j = 0) then\n begin\n direction := -direction;\n j := 1;\n if (i > size) then\n begin\n j := 2;\n i := size;\n end;\n end\n else if (j > size) then\n begin\n direction := -direction;\n j := size;\n i := i + 2;\n end;\n end;\n\n width := 2;\n n := size;\n while (n > 0) do\n begin\n width := width + 1;\n n := n div 10;\n end;\n for j := 1 to size do\n begin\n for i := 1 to size do\n write(zzarray[i,j]:width);\n writeln;\n end;\nend.\n", "language": "Pascal" }, { "code": "Program zigzag;\n{$APPTYPE CONSOLE}\n\nconst\n size = 5;\n\n var\n s: array [1..size, 1..size] of integer;\n i, j, d, max, n: integer;\n\nbegin\n i := 1;\n j := 1;\n d := -1;\n max := 0;\n n := 0;\n max := size * size;\n\n for n := 1 to (max div 2)+1 do begin\n s[i,j] := n;\n s[size - i + 1,size - j + 1] := max - n + 1;\n i:=i+d;\n j:=j-d;\n if i < 1 then begin\n inc(i);\n d := -d;\n end else if j < 1 then begin\n inc(j);\n d := -d;\n end;\n end;\n\n for j := 1 to size do\n begin\n for i := 1 to size do\n write(s[i,j]:4);\n writeln;\n end;\n\nend.\n", "language": "Pascal" }, { "code": "use 5.010;\n\nsub zig_zag {\n my $n = shift;\n my $max_number = $n**2;\n my @matrix;\n my $number = 0;\n for my $j ( 0 .. --$n ) {\n for my $i (\n $j % 2\n ? 0 .. $j\n : reverse 0 .. $j\n )\n {\n $matrix[$i][ $j - $i ] = $number++;\n #next if $j == $n;\n $matrix[ $n - $i ][ $n - ( $j - $i ) ] = $max_number - $number;\n }\n }\n return @matrix;\n}\n\nmy @zig_zag_matrix = zig_zag(5);\nsay join \"\\t\", @{$_} foreach @zig_zag_matrix;\n", "language": "Perl" }, { "code": "sub zig_zag {\n my ($w, $h, @r, $n) = @_;\n\n $r[ $_->[1] ][ $_->[0] ] = $n++\tfor\n \tsort {\t$a->[0] + $a->[1] <=> $b->[0] + $b->[1]\t or\n\t\t($a->[0] + $a->[1]) % 2\n\t\t\t? $a->[1] <=> $b->[1]\n\t\t\t: $a->[0] <=> $b->[0]\n\t}\n\tmap {\tmy $e = $_;\n\t\tmap{ [$e, $_] } 0 .. $w-1\n\t} 0 .. $h - 1;\n @r\n}\n\nprint map{ \"@$_\\n\" } zig_zag(3, 5);\n", "language": "Perl" }, { "code": "(phixonline)-->\n <span style=\"color: #008080;\">with</span> <span style=\"color: #008080;\">javascript_semantics</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">9</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">zstart</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">0</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">zend</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #000080;font-style:italic;\">--integer zstart = 1, zend = n*n</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%%%dd\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zend</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"??\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">while</span> <span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zstart</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">zstart</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">zend</span> <span style=\"color: #008080;\">then</span> <span style=\"color: #008080;\">exit</span> <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #000000;\">zstart</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">zend</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #000000;\">zend</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">d</span>\n <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">-=</span> <span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">elsif</span> <span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">+=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #000000;\">d</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">d</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">while</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "(phixonline)-->\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">5</span>\n <span style=\"color: #004080;\">string</span> <span style=\"color: #000000;\">fmt</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%%%dd\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">length</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"%d\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)))</span>\n <span style=\"color: #004080;\">sequence</span> <span style=\"color: #000000;\">m</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #7060A8;\">repeat</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #008000;\">\"??\"</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #004080;\">integer</span> <span style=\"color: #000000;\">x</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span> <span style=\"color: #000000;\">y</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #000000;\">1</span>\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">0</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">*</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">-</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">][</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">sprintf</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">fmt</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">d</span><span style=\"color: #0000FF;\">)</span>\n <span style=\"color: #008080;\">if</span> <span style=\"color: #7060A8;\">mod</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">2</span><span style=\"color: #0000FF;\">)</span> <span style=\"color: #008080;\">then</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">),</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">}:{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">else</span>\n <span style=\"color: #0000FF;\">{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">}</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #008080;\">iff</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\"><</span><span style=\"color: #000000;\">n</span><span style=\"color: #0000FF;\">?{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">-(</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">></span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">)}:{</span><span style=\"color: #000000;\">x</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #000000;\">y</span><span style=\"color: #0000FF;\">+</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">})</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">if</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n\n <span style=\"color: #008080;\">for</span> <span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">=</span><span style=\"color: #000000;\">1</span> <span style=\"color: #008080;\">to</span> <span style=\"color: #000000;\">n</span> <span style=\"color: #008080;\">do</span>\n <span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">]</span> <span style=\"color: #0000FF;\">=</span> <span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">[</span><span style=\"color: #000000;\">i</span><span style=\"color: #0000FF;\">])</span>\n <span style=\"color: #008080;\">end</span> <span style=\"color: #008080;\">for</span>\n <span style=\"color: #7060A8;\">puts</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">1</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #7060A8;\">join</span><span style=\"color: #0000FF;\">(</span><span style=\"color: #000000;\">m</span><span style=\"color: #0000FF;\">,</span><span style=\"color: #008000;\">\"\\n\"</span><span style=\"color: #0000FF;\">))</span>\n<!--\n", "language": "Phix" }, { "code": "5 var Size\n0 Size repeat Size repeat\n\n1 var i 1 var j\n\nSize 2 power for\n swap i get rot j set i set\n i j + 1 bitand 0 == IF\n j Size < IF j 1 + var j ELSE i 2 + var i ENDIF\n i 1 > IF i 1 - var i ENDIF\n ELSE\n i Size < IF i 1 + var i ELSE j 2 + var j ENDIF\n j 1 > IF j 1 - var j ENDIF\n ENDIF\nendfor\n\nSize FOR\n var row\n Size FOR\n var col\n row get col get tostr 32 32 chain chain 1 3 slice print drop drop\n ENDFOR\n nl\nENDFOR\n", "language": "Phixmonti" }, { "code": "function ZigZagMatrix($num) {\n $matrix = array();\n for ($i = 0; $i < $num; $i++){\n\t\t$matrix[$i] = array();\n\t}\n\t\n $i=1;\n\t$j=1;\n for ($e = 0; $e < $num*$num; $e++) {\n $matrix[$i-1][$j-1] = $e;\n if (($i + $j) % 2 == 0) {\n if ($j < $num){\n\t\t\t\t$j++;\n\t\t\t}else{\n\t\t\t\t$i += 2;\n\t\t\t}\n if ($i > 1){\n\t\t\t\t$i --;\n\t\t\t}\n } else {\n if ($i < $num){\n\t\t\t\t$i++;\n\t\t\t}else{\n\t\t\t\t$j += 2;\n\t\t\t}\n if ($j > 1){\n\t\t\t\t$j --;\n\t\t\t}\n }\n }\n\treturn $matrix;\n}\n", "language": "PHP" }, { "code": "(load \"@lib/simul.l\")\n\n(de zigzag (N)\n (prog1 (grid N N)\n (let (D '(north west south east .) E '(north east .) This 'a1)\n (for Val (* N N)\n (=: val Val)\n (setq This\n (or\n ((cadr D) ((car D) This))\n (prog\n (setq D (cddr D))\n ((pop 'E) This) )\n ((pop 'E) This) ) ) ) ) ) )\n\n(mapc\n '((L)\n (for This L (prin (align 3 (: val))))\n (prinl) )\n (zigzag 5) )\n", "language": "PicoLisp" }, { "code": "/* Fill a square matrix with the values 0 to N**2-1, */\n/* in a zig-zag fashion. */\n/* N is the length of one side of the square. */\n/* Written 22 February 2010. */\n\n declare n fixed binary;\n\n put skip list ('Please type the size of the matrix:');\n get list (n);\n\nbegin;\n declare A(n,n) fixed binary;\n declare (i, j, inc, q) fixed binary;\n\n on subrg snap begin;\n declare i fixed binary;\n do i = 1 to n;\n put skip edit (a(i,*)) (f(4));\n end;\n stop;\n end;\n\n A = -1;\n inc = -1;\n i, j = 1;\n\nloop:\n do q = 0 to n**2-1;\n a(i,j) = q;\n if q = n**2-1 then leave;\n if i = 1 & j = n then\n if iand(j,1) = 1 then /* odd-sided matrix */\n do; i = i + 1; inc = -inc; iterate loop; end;\n else /* an even-sided matrix */\n do; i = i + inc; j = j - inc; iterate loop; end;\n if inc = -1 then if i+inc < 1 then\n do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end;\n if inc = 1 then if i+inc > n then\n do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end;\n if inc = 1 then if j-inc < 1 then\n do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end;\n if inc = -1 then if j - inc > n then\n do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end;\n i = i + inc; j = j - inc;\n end;\n\n /* Display the square. */\n do i = 1 to n;\n put skip edit (a(i,*)) (f(4));\n end;\nend;\n", "language": "PL-I" }, { "code": "\\long\\def\\antefi#1#2\\fi{#2\\fi#1}\n\\def\\fornum#1=#2to#3(#4){%\n\t\\edef#1{\\number\\numexpr#2}\\edef\\fornumtemp{\\noexpand\\fornumi\\expandafter\\noexpand\\csname fornum\\string#1\\endcsname\n\t\t{\\number\\numexpr#3}{\\ifnum\\numexpr#4<0 <\\else>\\fi}{\\number\\numexpr#4}\\noexpand#1}\\fornumtemp\n}\n\\long\\def\\fornumi#1#2#3#4#5#6{\\def#1{\\unless\\ifnum#5#3#2\\relax\\antefi{#6\\edef#5{\\number\\numexpr#5+(#4)\\relax}#1}\\fi}#1}\n\\def\\elem(#1,#2){\\numexpr(#1+#2)*(#1+#2-1)/2-(\\ifodd\\numexpr#1+#2\\relax#1\\else#2\\fi)\\relax}\n\\def\\zzmat#1{%\n\t\\noindent% quit vertical mode\n\t\\fornum\\yy=1to#1(+1){%\n\t\t\\fornum\\xx=1to#1(+1){%\n\t\t\t\\ifnum\\numexpr\\xx+\\yy\\relax<\\numexpr#1+2\\relax\n\t\t\t\t\\hbox to 2em{\\hfil\\number\\elem(\\xx,\\yy)}%\n\t\t\t\\else\n\t\t\t\t\\hbox to 2em{\\hfil\\number\\numexpr#1*#1-1-\\elem(#1+1-\\xx,#1+1-\\yy)\\relax}%\n\t\t\t\\fi\n\t\t}%\n\t\t\\par\\noindent% next line + quit vertical mode\n\t}\\par\n}\n\\zzmat{5}\n\\bye\n", "language": "PlainTeX" }, { "code": "%!PS\n%%BoundingBox: 0 0 300 200\n/size 9 def % defines row * column (9*9 -> 81 numbers,\n % from 0 to 80)\n/itoa { 2 string cvs } bind def\n% visual bounding box...\n% 0 0 moveto 300 0 lineto 300 200 lineto 0 200 lineto\n% closepath stroke\n20 150 translate\n% it can be easily enhanced to support more columns and\n% rows. This limit is put here just to avoid more than 2\n% digits, mainly because of formatting\nsize size mul 99 le {\n /Helvetica findfont 14 scalefont setfont\n /ulimit size size mul def\n /sizem1 size 1 sub def\n % prepare the number list\n 0 ulimit 1 sub { dup 1 add } repeat\n ulimit array astore\n /di -1 def /dj 1 def\n /ri 1 def /rj 0 def /pus true def\n 0 0 moveto\n /i 0 def /j 0 def\n { % can be rewritten a lot better :)\n 0.8 setgray i 30 mul j 15 mul neg lineto stroke\n 0 setgray i 30 mul j 15 mul neg moveto itoa show\n i 30 mul j 15 mul neg moveto\n pus {\n i ri add size ge {\n /ri 0 def /rj 1 def\n } if\n j rj add size ge {\n /ri 1 def /rj 0 def\n } if\n /pus false def\n /i i ri add def\n /j j rj add def\n /ri rj /rj ri def def\n } {\n i di add dup 0 le\n exch sizem1 ge or\n j dj add dup 0 le\n exch sizem1 ge or\n or {\n /pus true def\n /i i di add def /j j dj add def\n /di di neg def /dj dj neg def\n } {\n /i i di add def /j j dj add def\n } ifelse\n } ifelse\n } forall\n stroke showpage\n} if\n%%EOF\n", "language": "PostScript" }, { "code": "function zigzag( [int] $n ) {\n $zigzag=New-Object 'Object[,]' $n,$n\n $nodd = $n -band 1\n $nm1 = $n - 1\n $i=0;\n $j=0;\n foreach( $k in 0..( $n * $n - 1 ) ) {\n $zigzag[$i,$j] = $k\n $iodd = $i -band 1\n $jodd = $j -band 1\n if( ( $j -eq $nm1 ) -and ( $iodd -ne $nodd ) ) {\n $i++\n } elseif( ( $i -eq $nm1 ) -and ( $jodd -eq $nodd ) ) {\n $j++\n } elseif( ( $i -eq 0 ) -and ( -not $jodd ) ) {\n $j++\n } elseif( ( $j -eq 0 ) -and $iodd ) {\n $i++\n } elseif( $iodd -eq $jodd ) {\n $i--\n $j++\n } else {\n $i++\n $j--\n }\n }\n ,$zigzag\n}\n\nfunction displayZigZag( [int] $n ) {\n $a = zigzag $n\n 0..$n | ForEach-Object {\n $b=$_\n $pad=($n*$n-1).ToString().Length\n \"$(0..$n | ForEach-Object {\n \"{0,$pad}\" -f $a[$b,$_]\n } )\"\n }\n}\n", "language": "PowerShell" }, { "code": "zigzag 5 | Format-Wide {\"{0,2}\" -f $_} -Column 5 -Force\n", "language": "PowerShell" }, { "code": "zig_zag(N) :-\n\tzig_zag(N, N).\n\n% compute zig_zag for a matrix of Lig lines of Col columns\nzig_zag(Lig, Col) :-\n\tlength(M, Lig),\n\tmaplist(init(Col), M),\n\tfill(M, 0, 0, 0, Lig, Col, up),\n\t% display the matrix\n\tmaplist(print_line, M).\n\n\nfill(M, Cur, L, C, NL, NC, _) :-\n\tL is NL - 1,\n\tC is NC - 1,\n\tnth0(L, M, Line),\n\tnth0(C, Line, Cur).\n\nfill(M, Cur, L, C, NL, NC, Sens) :-\n\tnth0(L, M, Line),\n\tnth0(C, Line, Cur),\n\tCur1 is Cur + 1,\n\tcompute_next(NL, NC, L, C, Sens, L1, C1, Sens1),\n\tfill(M, Cur1, L1, C1, NL, NC, Sens1).\n\n\ninit(N, L) :-\n\tlength(L, N).\n\n% compute_next\n% arg1 : Number of lnes of the matrix\n% arg2 : number of columns of the matrix\n% arg3 : current line\n% arg4 : current column\n% arg5 : current direction of movement\n% arg6 : nect line\n% arg7 : next column\n% arg8 : next direction of movement\ncompute_next(_NL, NC, 0, Col, up, 0, Col1, down) :-\n\tCol < NC - 1,\n\tCol1 is Col+1.\n\ncompute_next(_NL, NC, 0, Col, up, 1, Col, down) :-\n\tCol is NC - 1.\n\ncompute_next(NL, _NC, Lig, 0, down, Lig1, 0, up) :-\n\tLig < NL - 1,\n\tLig1 is Lig+1.\n\ncompute_next(NL, _NC, Lig, 0, down, Lig, 1, up) :-\n\tLig is NL - 1.\n\ncompute_next(NL, _NC, Lig, Col, down, Lig1, Col1, down) :-\n\tLig < NL - 1,\n\tLig1 is Lig + 1,\n\tCol1 is Col-1.\n\ncompute_next(NL, _NC, Lig, Col, down, Lig, Col1, up) :-\n\tLig is NL - 1,\n\tCol1 is Col+1.\n\ncompute_next(_NL, NC, Lig, Col, up, Lig1, Col1, up) :-\n\tCol < NC - 1,\n\tLig1 is Lig - 1,\n\tCol1 is Col+1.\n\ncompute_next(_NL, NC, Lig, Col, up, Lig1, Col, down) :-\n\tCol is NC - 1,\n\tLig1 is Lig + 1.\n\n\nprint_line(L) :-\n\tmaplist(print_val, L),\n\tnl.\n\nprint_val(V) :-\n\twritef('%3r ', [V]).\n", "language": "Prolog" }, { "code": "Procedure zigZag(size)\n Protected i, v, x, y\n\n Dim a(size - 1, size - 1)\n\n x = 1\n y = 1\n For i = 1 To size * size ;loop once for each element\n a(x - 1, y - 1) = v ;assign the next index\n\n If (x + y) & 1 = 0 ;even diagonal (zero based count)\n If x < size ;while inside the square\n If y > 1 ;move right-up\n y - 1\n EndIf\n x + 1\n Else\n y + 1 ;on the edge increment y, but not x until diagonal is odd\n EndIf\n Else ;odd diagonal (zero based count)\n If y < size ;while inside the square\n If x > 1 ;move left-down\n x - 1\n EndIf\n y + 1\n Else\n x + 1 ;on the edge increment x, but not y until diagonal is even\n EndIf\n EndIf\n v + 1\n Next\n\n\n ;generate and show printout\n PrintN(\"Zig-zag matrix of size \" + Str(size) + #CRLF$)\n maxDigitCount = Len(Str(size * size)) + 1\n For y = 0 To size - 1\n For x = 0 To size - 1\n Print(RSet(Str(a(x, y)), maxDigitCount, \" \"))\n Next\n PrintN(\"\")\n Next\n PrintN(\"\")\nEndProcedure\n\nIf OpenConsole()\n zigZag(5)\n zigZag(6)\n\n Print(#CRLF$ + #CRLF$ + \"Press ENTER to exit\")\n Input()\n CloseConsole()\nEndIf\n", "language": "PureBasic" }, { "code": "def zigzag(n):\n '''zigzag rows'''\n def compare(xy):\n x, y = xy\n return (x + y, -y if (x + y) % 2 else y)\n xs = range(n)\n return {index: n for n, index in enumerate(sorted(\n ((x, y) for x in xs for y in xs),\n key=compare\n ))}\n\n\ndef printzz(myarray):\n '''show zigzag rows as lines'''\n n = int(len(myarray) ** 0.5 + 0.5)\n xs = range(n)\n print('\\n'.join(\n [''.join(\"%3i\" % myarray[(x, y)] for x in xs) for y in xs]\n ))\n\n\nprintzz(zigzag(6))\n", "language": "Python" }, { "code": "# pylint: disable=invalid-name\n# pylint: disable=unused-argument\n\"ZigZag iterator.\"\nimport sys\n\nif sys.version_info[0] >= 3:\n xrange = range\n\ndef move(x, y, columns, rows):\n \"Tells us what to do next with x and y.\"\n if y < (rows - 1):\n return max(0, x-1), y+1\n return x+1, y\n\ndef zigzag(rows, columns):\n \"ZigZag iterator, yields indices.\"\n x, y = 0, 0\n size = rows * columns\n for _ in xrange(size):\n yield y, x\n if (x + y) & 1:\n x, y = move(x, y, columns, rows)\n else:\n y, x = move(y, x, rows, columns)\n\n# test code\ni, rows, cols = 0, 5, 5\nmat = [[0 for x in range(cols)] for y in range(rows)]\nfor (y, x) in zigzag(rows, cols):\n mat[y][x], i = i, i + 1\n\nfrom pprint import pprint\npprint(mat)\n", "language": "Python" }, { "code": "[[0, 1, 5, 6, 14],\n [2, 4, 7, 13, 15],\n [3, 8, 12, 16, 21],\n [9, 11, 17, 20, 22],\n [10, 18, 19, 23, 24]]\n", "language": "Python" }, { "code": "COLS = 9\ndef CX(x, ran):\n while True:\n x += 2 * next(ran)\n yield x\n x += 1\n yield x\nran = []\nd = -1\nfor V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))):\n ran.append(iter(range(V, V+COLS*d, d)))\n d *= -1\nfor x in range(0,COLS):\n for y in range(x, x+COLS):\n print(repr(next(ran[y])).rjust(3), end = ' ')\n print()\n", "language": "Python" }, { "code": "from __future__ import print_function\n\nimport math\n\n\ndef zigzag( dimension):\n ''' generate the zigzag indexes for a square array\n Exploiting the fact that an array is symmetrical around its\n centre\n '''\n NUMBER_INDEXES = dimension ** 2\n HALFWAY = NUMBER_INDEXES // 2\n KERNEL_ODD = dimension & 1\n\n xy = [0 for _ in range(NUMBER_INDEXES)]\n # start at 0,0\n ix = 0\n iy = 0\n # 'fake' that we are going up and right\n direction = 1\n # the first index is always 0, so start with the second\n # until halfway\n for i in range(1, HALFWAY + KERNEL_ODD):\n if direction > 0:\n # going up and right\n if iy == 0:\n # are at top\n ix += 1\n direction = -1\n else:\n ix += 1\n iy -= 1\n else:\n # going down and left\n if ix == 0:\n # are at left\n iy += 1\n direction = 1\n else:\n ix -= 1\n iy += 1\n # update the index position\n xy[iy * dimension + ix] = i\n\n # have first half, but they are scattered over the list\n # so find the zeros to replace\n for i in range(1, NUMBER_INDEXES):\n if xy[i] == 0 :\n xy[i] = NUMBER_INDEXES - 1 - xy[NUMBER_INDEXES - 1 - i]\n\n return xy\n\n\ndef main(dim):\n zz = zigzag(dim)\n print( 'zigzag of {}:'.format(dim))\n width = int(math.ceil(math.log10(dim**2)))\n for j in range(dim):\n for i in range(dim):\n print('{:{width}}'.format(zz[j * dim + i], width=width), end=' ')\n print()\n\n\nif __name__ == '__main__':\n main(5)\n", "language": "Python" }, { "code": "(define odd? A -> (= 1 (MOD A 2)))\n(define even? A -> (= 0 (MOD A 2)))\n\n(define zigzag-val\n 0 0 N -> 0\n\n X 0 N -> (1+ (zigzag-val (1- X) 0 N)) where (odd? X)\n X 0 N -> (1+ (zigzag-val (1- X) 1 N))\n\n 0 Y N -> (1+ (zigzag-val 1 (1- Y) N)) where (odd? Y)\n 0 Y N -> (1+ (zigzag-val 0 (1- Y) N))\n\n X Y N -> (1+ (zigzag-val (MAX 0 (1- X)) (MIN (1- N) (1+ Y)) N)) where (even? (+ X Y))\n X Y N -> (1+ (zigzag-val (MIN (1- N) (1+ X)) (MAX 0 (1- Y)) N)))\n\n(define range\n E E -> []\n S E -> [S|(range (1+ S) E)])\n\n(define zigzag\n N -> (map (/. Y\n (map (/. X\n (zigzag-val X Y N))\n (range 0 N)))\n (range 0 N)))\n", "language": "Qi" }, { "code": " [ ]'[ tuck do dip do ] is with2 ( x x --> x x )\n\n [ dup temp put\n [] swap\n dup * times [ i^ join ]\n sortwith\n [ with2\n [ temp share /mod\n tuck + 1 &\n if negate ]\n > ]\n sortwith\n [ with2\n [ temp share /mod + ]\n > ]\n dup witheach\n [ i^ unrot poke ]\n [] swap\n temp share times\n [ temp share split\n dip [ nested join ] ]\n drop\n temp release ] is zigzag ( n --> [ )\n\n 10 zigzag\n witheach\n [ witheach\n [ dup 10 < if sp\n echo sp ]\n cr ]\n", "language": "Quackery" }, { "code": " [ stack ] is stepcount ( --> s )\n [ stack ] is position ( --> s )\n [ stack ] is heading ( --> s )\n\n [ heading take\n behead join\n heading put ] is turn ( --> )\n\n [ heading share 0 peek\n unrot times\n [ position share\n stepcount share\n unrot poke\n over position tally\n 1 stepcount tally ]\n nip ] is walk ( [ n --> [ )\n\n [ dip [ temp put [] ]\n temp share times\n [ temp share split\n dip\n [ nested join ] ]\n drop temp release ] is matrixify ( n [ --> [ )\n\n [ 0 stepcount put ( set up... )\n 0 position put\n ' [ 1 ]\n over 1 - join\n over join\n over 1 - negate join\n heading put\n 0 over dup * of\n\n over 1 - times ( turtle draws first half of zigzag )\n [ 1 walk turn\n i^ 1+ walk turn ]\n\n heading take ( reverse the sequence of turns )\n reverse heading put\n\n over 1 - times ( turtle draws second half of zigzag )\n [ turn 1 walk\n turn i walk ]\n 1 walk\n\n matrixify ( ...tidy up )\n heading release\n position release\n stepcount release ] is zigzag ( n --> [ )\n\n 10 zigzag\n witheach\n [ witheach\n [ dup 10 < if sp echo sp ]\n cr ]\n", "language": "Quackery" }, { "code": "zigzag1 <- function(n) {\n j <- seq(n)\n u <- rep(c(-1, 1), n)\n v <- j * (2 * j - 1) - 1\n v <- as.vector(rbind(v, v + 1))\n a <- matrix(0, n, n)\n for (i in seq(n)) {\n a[i, ] <- v[j + i - 1]\n v <- v + u\n }\n a\n}\n\nzigzag1(5)\n", "language": "R" }, { "code": "zigzag2 <- function(n) {\n a <- zigzag1(n)\n v <- seq(n - 1)^2\n for (i in seq(n - 1)) {\n a[n - i + 1, seq(i + 1, n)] <- a[n - i + 1, seq(i + 1, n)] - v[seq(n - i)]\n }\n a\n}\n\nzigzag2(5)\n", "language": "R" }, { "code": "#lang racket\n\n(define/match (compare i j)\n [((list x y) (list a b)) (or (< x a) (and (= x a) (< y b)))])\n\n(define/match (key i)\n [((list x y)) (list (+ x y) (if (even? (+ x y)) (- y) y))])\n\n(define (zigzag-ht n)\n (define indexorder\n (sort (for*/list ([x n] [y n]) (list x y))\n compare #:key key))\n (for/hash ([(n i) (in-indexed indexorder)]) (values n i)))\n\n(define (zigzag n)\n (define ht (zigzag-ht n))\n (for/list ([x n])\n (for/list ([y n])\n (hash-ref ht (list x y)))))\n\n(zigzag 4)\n", "language": "Racket" }, { "code": "class Turtle {\n my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1];\n my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.\n\n has @.loc = 0,0;\n has $.dir = 0;\n has %.world;\n has $.maxegg;\n has $.range-x;\n has $.range-y;\n\n method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; }\n method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; }\n\n method lay-egg($egg) {\n %!world{~@!loc} = $egg;\n $!maxegg max= $egg;\n $!range-x minmax= @!loc[0];\n $!range-y minmax= @!loc[1];\n }\n\n method look($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n %!world{~$there};\n }\n\n method forward($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n @!loc = @($there);\n }\n\n method showmap() {\n my $form = \"%{$!maxegg.chars}s\";\n my $endx = $!range-x.max;\n for $!range-y.list X $!range-x.list -> ($y, $x) {\n print (%!world{\"$x $y\"} // '').fmt($form);\n print $x == $endx ?? \"\\n\" !! ' ';\n }\n }\n}\n\nsub MAIN(Int $size = 5) {\n my $t = Turtle.new(dir => 1);\n my $counter = 0;\n for 1 ..^ $size -> $run {\n\tfor ^$run {\n\t $t.lay-egg($counter++);\n\t $t.forward;\n\t}\n\tmy $yaw = $run %% 2 ?? -1 !! 1;\n\t$t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45);\n }\n for $size ... 1 -> $run {\n\tfor ^$run -> $ {\n\t $t.lay-egg($counter++);\n\t $t.forward;\n\t}\n\t$t.turn-left(180); $t.forward;\n\tmy $yaw = $run %% 2 ?? 1 !! -1;\n\t$t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45);\n }\n $t.showmap;\n}\n", "language": "Raku" }, { "code": "0 (0,0), 1 (0,1), 3 (0,2)\n2 (1,0), 4 (1,1), 6 (1,2)\n5 (2,0), 7 (2,1), 8 (2,2)\n", "language": "Rascal" }, { "code": " 0 (0,0), 1 (0,1), 2 (1,0), 3 (0,2), 4 (1,1), 5 (2,0), 6 (1,2), 7 (2,1), 8 (2,2)\n", "language": "Rascal" }, { "code": "import util::Math;\nimport List;\nimport Set;\nimport IO;\n\nalias cd = tuple[int,int];\n\npublic rel[cd, int] zz(int n){\n\t indexorder = sort([<x,y>| x <- [0..n], y <- [0..n]],\n\t bool (cd a, cd b){\n\t \tif (a[0]+a[1] > b[0]+b[1])\n\t \t\treturn false;\n\t \telseif(a[0] < b[0])\n\t \t\treturn false;\n\t \telse\n\t \t\treturn true;\n\t \t\t;\n\t \t});\n\t return {<indexorder[z] , z> | z <- index(indexorder)};\t \t\n}\n\npublic void printzz(rel[cd, int] myarray){\n n = floor(sqrt(size(myarray)));\n for (x <- [0..n-1]){\n for (y <- [0..n-1]){\n print(\"<myarray[<y,x>]>\\t\");}\n println();}\n}\n", "language": "Rascal" }, { "code": "/*REXX program produces and displays a zig─zag matrix (a square array). */\nparse arg n start inc . /*obtain optional arguments from the CL*/\nif n=='' | n==\",\" then n= 5 /*Not specified? Then use the default.*/\nif start=='' | start==\",\" then start= 0 /* \" \" \" \" \" \" */\nif inc=='' | inc==\",\" then inc= 1 /* \" \" \" \" \" \" */\nrow= 1; col= 1; size= n**2 /*start: 1st row & column; array size.*/\n do j=start by inc for size; @.row.col= j\n if (row+col)//2==0 then do; if col<n then col= col+1; else row= row+2\n if row\\==1 then row= row-1\n end\n else do; if row<n then row= row+1; else col= col+2\n if col\\==1 then col= col-1\n end\n end /*j*/ /* [↑] // is REXX ÷ remainder.*/\ncall show /*display a (square) matrix──►terminal.*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nshow: w= max(length(start), length(start+size*inc)) /*max width of any matrix elements,*/\n do r=1 for n ; _= right(@.r.1, w) /*show the rows of the matrix. */\n do c=2 for n-1; _= _ right(@.r.c, w) /*build a line for output of a row.*/\n end /*c*/; say _ /* [↑] align the matrix elements. */\n end /*r*/; return\n", "language": "REXX" }, { "code": "/*REXX program produces and displays a zig-zag matrix (a square array) */\nParse Arg n start inc . /* obtain optional arguments from command line */\nif n=='' | n==\",\" then n= 5 /*Not specified? use the default*/\nif start=='' | start==\",\" then start= 0 /* \" \" \" \" \" */\nif inc=='' | inc==\",\" then inc= 1 /* \" \" \" \" \" */\nParse Value 1 1 n**2 With row col size\nDo x=start By inc For size\n m.row.col=x\n If (row+col)//2=0 Then do /* moving upward */\n Select\n when row=1 Then Do /* at upper bound */\n If col<n Then\n col=col+1 /* move right */\n Else\n row=2 /* move down */\n End\n when col=n Then /* at right border */\n row=row+1 /* move down */\n Otherwise Do /* in all other cases */\n row=row-1 /* move up */\n col=col+1 /* and to the right */\n End\n End\n End\n Else Do /* moving downward */\n Select\n When col=1 Then Do /* at lower bound */\n If row=n Then /* in bottom row */\n col=2 /* move right */\n Else /* otherwise */\n row=row+1 /* move down */\n End\n When row=n Then /* at lower bound */\n col=col+1 /* move right */\n Otherwise Do /* in all other cases */\n row=row+1 /* move down */\n col=col-1 /* and to the left */\n End\n End\n End\n End\nCall show\nExit\n/*-----------------------------------------------------------------------*/\nshow:\n w=length(start+size*inc) /* max width of any matrix element */\n Do row=1 To n /* loop over rows */\n line=right(m.row.1,w) /* first element */\n Do column=2 To n /* loop over other elements */\n line=line right(m.row.column,w) /* build output line */\n End\n Say line\n End /* display the line */\n Return\n", "language": "REXX" }, { "code": "# Project Zig-zag matrix\n\nload \"guilib.ring\"\nload \"stdlib.ring\"\nnew qapp\n {\n win1 = new qwidget() {\n setwindowtitle(\"Zig-zag matrix\")\n setgeometry(100,100,600,400)\n n = 5\n a = newlist(n,n)\n zigzag = newlist(n,n)\n for j = 1 to n\n for i = 1 to n\n a[j][i] = 0\n next\n next\n i = 1\n j = 1\n k = 1\n while k < n * n\n a[j][i] = k\n k = k + 1\n if i = n\n j = j + 1\n a[j][i] = k\n k = k + 1\n di = -1\n dj = 1\n ok\n if j = 1\n i = i + 1\n a[j][i] = k\n k = k + 1\n di = -1\n dj = 1\n ok\n if j = n\n i = i + 1\n a[j][i] = k\n k = k + 1\n di = 1\n dj = -1\n ok\n if i = 1\n j = j + 1\n a[j][i] = k\n k = k + 1\n di = 1\n dj = -1\n ok\n i = i + di\n j = j + dj\n end\n for p = 1 to n\n for m = 1 to n\n zigzag[p][m] = new qpushbutton(win1) {\n x = 150+m*40\n y = 30 + p*40\n setgeometry(x,y,40,40)\n settext(string(a[p][m]))\n }\n next\n next\n show()\n }\n exec()\n }\n", "language": "Ring" }, { "code": "def zigzag(n)\n (seq=*0...n).product(seq)\n .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]}\n .each_with_index.sort.map(&:last).each_slice(n).to_a\nend\n\ndef print_matrix(m)\n format = \"%#{m.flatten.max.to_s.size}d \" * m[0].size\n puts m.map {|row| format % row}\nend\n\nprint_matrix zigzag(5)\n", "language": "Ruby" }, { "code": "use std::cmp::Ordering;\nuse std::cmp::Ordering::{Equal, Greater, Less};\nuse std::iter::repeat;\n\n#[derive(Debug, PartialEq, Eq)]\nstruct SortIndex {\n x: usize,\n y: usize,\n}\n\nimpl SortIndex {\n fn new(x: usize, y: usize) -> SortIndex {\n SortIndex { x, y }\n }\n}\n\nimpl PartialOrd for SortIndex {\n fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> {\n Some(self.cmp(other))\n }\n}\n\nimpl Ord for SortIndex {\n fn cmp(&self, other: &SortIndex) -> Ordering {\n let lower = if self.x + self.y == other.x + other.y {\n if (self.x + self.y) % 2 == 0 {\n self.x < other.x\n } else {\n self.y < other.y\n }\n } else {\n (self.x + self.y) < (other.x + other.y)\n };\n\n if lower {\n Less\n } else if self == other {\n Equal\n } else {\n Greater\n }\n }\n}\n\nfn zigzag(n: usize) -> Vec<Vec<usize>> {\n let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i % n, i / n)).collect();\n l.sort();\n\n let init_vec = vec![0; n];\n let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect();\n for (i, &SortIndex { x, y }) in l.iter().enumerate() {\n result[y][x] = i\n }\n result\n}\n\nfn main() {\n println!(\"{:?}\", zigzag(5));\n}\n", "language": "Rust" }, { "code": " def zigzag(n: Int): Array[Array[Int]] = {\n val l = for (i <- 0 until n*n) yield (i%n, i/n)\n val lSorted = l.sortWith {\n case ((x,y), (u,v)) =>\n if (x+y == u+v)\n if ((x+y) % 2 == 0) x<u else y<v\n else x+y < u+v\n }\n val res = Array.ofDim[Int](n, n)\n lSorted.zipWithIndex foreach {\n case ((x,y), i) => res(y)(x) = i\n }\n res\n }\n\n zigzag(5).foreach{\n ar => ar.foreach(x => print(\"%3d\".format(x)))\n println\n }\n", "language": "Scala" }, { "code": "function a = zigzag3(n)\n a = zeros(n, n)\n for k=1:n\n j = modulo(k, 2)\n d = (2*j-1)*(n-1)\n m = (n-1)*(k-1)\n a(k+(1-j)*m:d:k+j*m) = k*(k-1)/2:k*(k+1)/2-1\n a(n*(n+1-k)+(1-j)*m:d:n*(n+1-k)+j*m) = n*n-k*(k+1)/2:n*n-k*(k-1)/2-1\n end\nendfunction\n\n-->zigzag3(5)\n ans =\n\n 0. 1. 5. 6. 14.\n 2. 4. 7. 13. 15.\n 3. 8. 12. 16. 21.\n 9. 11. 17. 20. 22.\n 10. 18. 19. 23. 24.\n", "language": "Scilab" }, { "code": "$ include \"seed7_05.s7i\";\n\nconst type: matrix is array array integer;\n\nconst func matrix: zigzag (in integer: size) is func\n result\n var matrix: s is matrix.value;\n local\n var integer: i is 1;\n var integer: j is 1;\n var integer: d is -1;\n var integer: max is 0;\n var integer: n is 0;\n begin\n s := size times size times 0;\n max := size ** 2;\n for n range 1 to max div 2 + 1 do\n s[i][j] := n;\n s[size - i + 1][size - j + 1] := max - n + 1;\n i +:= d;\n j -:= d;\n if i < 1 then\n incr(i);\n d := -d;\n elsif j < 1 then\n incr(j);\n d := -d;\n end if;\n end for;\n end func;\n\nconst proc: main is func\n local\n var matrix: s is matrix.value;\n var integer: i is 0;\n var integer: num is 0;\n begin\n s := zigzag(7);\n for i range 1 to length(s) do\n for num range s[i] do\n write(num lpad 4);\n end for;\n writeln;\n end for;\n end func;\n", "language": "Seed7" }, { "code": "func zig_zag(w, h) {\n\n var r = []\n var n = 0\n\n h.of { |e|\n w.of { |f|\n [e, f]\n }\n }.reduce('+').sort { |a, b|\n (a[0]+a[1] <=> b[0]+b[1]) ||\n (a[0]+a[1] -> is_even ? a[0]<=>b[0]\n : a[1]<=>b[1])\n }.each { |a|\n r[a[1]][a[0]] = n++\n }\n\n return r\n}\n\nzig_zag(5, 5).each { say .join('', {|i| \"%4i\" % i}) }\n", "language": "Sidef" }, { "code": "fun rowprint r = (List.app (fn i => print (StringCvt.padLeft #\" \" 3 (Int.toString i))) r;\n print \"\\n\");\nfun zig lst M = List.app rowprint (lst M);\n\nfun sign t = if t mod 2 = 0 then ~1 else 1;\n\nfun zag n = List.tabulate (n,\n fn i=> rev ( List.tabulate (n,\n fn j =>\n\t\t\t let val t = n-j+i and u = n+j-i in\n\t\t\t if i <= j\n then t*t div 2 + sign t * ( t div 2 - i )\n else n*n - 1 - ( u*u div 2 + sign u * ( u div 2 - n + 1 + i) )\n\t end\n\t\t\t )));\n\nzig zag 5 ;\n", "language": "Standard-ML" }, { "code": "function zigzag1(n) {\n\tj = 0::n-1\n\tu = J(1, n, (-1, 1))\n\tv = (j:*(2:*j:+3))\n\tv = rowshape((v,v:+1), 1)\n\ta = J(n, n, .)\n\tfor (i=1; i<=n; i++) {\n\t\ta[i, .] = v[j:+i]\n\t\tv = v+u\n\t}\n\treturn(a)\n}\n\nzigzag1(5)\n 1 2 3 4 5\n +--------------------------+\n 1 | 0 1 5 6 14 |\n 2 | 2 4 7 13 16 |\n 3 | 3 8 12 17 25 |\n 4 | 9 11 18 24 31 |\n 5 | 10 19 23 32 40 |\n +--------------------------+\n", "language": "Stata" }, { "code": "function zigzag2(n) {\n\ta = zigzag1(n)\n\tv = (1..n-1):^2\n\tfor (i=1; i<n; i++) {\n\t\ta[n-i+1, i+1..n] = a[n-i+1, i+1..n] - v[1..n-i]\n\t}\n\treturn(a)\n}\n\nzigzag2(5)\n 1 2 3 4 5\n +--------------------------+\n 1 | 0 1 5 6 14 |\n 2 | 2 4 7 13 15 |\n 3 | 3 8 12 16 21 |\n 4 | 9 11 17 20 22 |\n 5 | 10 18 19 23 24 |\n +--------------------------+\n", "language": "Stata" }, { "code": "zigzag1(5)-zigzag2(5)\n[symmetric]\n 1 2 3 4 5\n +--------------------------+\n 1 | 0 |\n 2 | 0 0 |\n 3 | 0 0 0 |\n 4 | 0 0 1 4 |\n 5 | 0 1 4 9 16 |\n +--------------------------+\n", "language": "Stata" }, { "code": "proc zigzag {size} {\n set m [lrepeat $size [lrepeat $size .]]\n set x 0; set dx -1\n set y 0; set dy 1\n\n for {set i 0} {$i < $size ** 2} {incr i} {\n if {$x >= $size} {\n incr x -1\n incr y 2\n negate dx dy\n } elseif {$y >= $size} {\n incr x 2\n incr y -1\n negate dx dy\n } elseif {$x < 0 && $y >= 0} {\n incr x\n negate dx dy\n } elseif {$x >= 0 && $y < 0} {\n incr y\n negate dx dy\n }\n lset m $x $y $i\n incr x $dx\n incr y $dy\n }\n return $m\n}\n\nproc negate {args} {\n foreach varname $args {\n upvar 1 $varname var\n set var [expr {-1 * $var}]\n }\n}\n\nprint_matrix [zigzag 5]\n", "language": "Tcl" }, { "code": "#import std\n#import nat\n\nzigzag = ~&mlPK2xnSS+ num+ ==+sum~~|=xK9xSL@iiK0+ iota\n", "language": "Ursala" }, { "code": "#cast %nLLL\n\ntests = zigzag* <4,5,6>\n", "language": "Ursala" }, { "code": "Public Sub zigzag(n)\nDim a() As Integer\n'populate a (1,1) to a(n,n) in zigzag pattern\n\n'check if n too small\nIf n < 1 Then\n Debug.Print \"zigzag: enter a number greater than 1\"\n Exit Sub\nEnd If\n\n'initialize\nReDim a(1 To n, 1 To n)\ni = 1 'i is the row\nj = 1 'j is the column\nP = 0 'P is the next number\na(i, j) = P 'fill in initial value\n\n'now zigzag through the matrix and fill it in\nDo While (i <= n) And (j <= n)\n 'move one position to the right or down the rightmost column, if possible\n If j < n Then\n j = j + 1\n ElseIf i < n Then\n i = i + 1\n Else\n Exit Do\n End If\n 'fill in\n P = P + 1: a(i, j) = P\n 'move down to the left\n While (j > 1) And (i < n)\n i = i + 1: j = j - 1\n P = P + 1: a(i, j) = P\n Wend\n 'move one position down or to the right in the bottom row, if possible\n If i < n Then\n i = i + 1\n ElseIf j < n Then\n j = j + 1\n Else\n Exit Do\n End If\n P = P + 1: a(i, j) = P\n 'move back up to the right\n While (i > 1) And (j < n)\n i = i - 1: j = j + 1\n P = P + 1: a(i, j) = P\n Wend\nLoop\n\n'print result\nDebug.Print \"Result for n=\"; n; \":\"\nFor i = 1 To n\n For j = 1 To n\n Debug.Print a(i, j),\n Next\n Debug.Print\nNext\nEnd Sub\n", "language": "VBA" }, { "code": "ZigZag(Cint(WScript.Arguments(0)))\n\nFunction ZigZag(n)\n\tDim arrZ()\n\tReDim arrZ(n-1,n-1)\n\ti = 1\n\tj = 1\n\tFor e = 0 To (n^2) - 1\n\t\tarrZ(i-1,j-1) = e\n\t\tIf ((i + j ) And 1) = 0 Then\n\t\t\tIf j < n Then\n\t\t\t\tj = j + 1\n\t\t\tElse\n\t\t\t\ti = i + 2\n\t\t\tEnd If\n\t\t\tIf i > 1 Then\n\t\t\t\ti = i - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tIf i < n Then\n\t\t\t\ti = i + 1\n\t\t\tElse\n\t\t\t\tj = j + 2\n\t\t\tEnd If\n\t\t\tIf j > 1 Then\n\t\t\t\tj = j - 1\n\t\t\tEnd If\n\t\tEnd If\n\tNext\n\tFor k = 0 To n-1\n\t\tFor l = 0 To n-1\n\t\t\tWScript.StdOut.Write Right(\" \" & arrZ(k,l),3)\n\t\tNext\n\t\tWScript.StdOut.WriteLine\n\tNext\nEnd Function\n", "language": "VBScript" }, { "code": "import \"./fmt\" for Conv, Fmt\n\nvar zigzag = Fn.new { |n|\n var r = List.filled(n*n, 0)\n var i = 0\n var n2 = n * 2\n for (d in 1..n2) {\n var x = d - n\n if (x < 0) x = 0\n var y = d - 1\n if (y > n - 1) y = n - 1\n var j = n2 - d\n if (j > d) j = d\n for (k in 0...j) {\n if (d&1 == 0) {\n r[(x+k)*n+y-k] = i\n } else {\n r[(y-k)*n+x+k] = i\n }\n i = i + 1\n }\n }\n return r\n}\n\nvar n = 5\nvar w = Conv.itoa(n*n - 1).count\nvar i = 0\nfor (e in zigzag.call(n)) {\n Fmt.write(\"$*d \", w, e)\n if (i%n == n - 1) System.print()\n i = i + 1\n}\n", "language": "Wren" }, { "code": "include c:\\cxpl\\codes;\ndef N=6;\nint A(N,N), X, Y, I, D;\n[I:=0; X:=0; Y:=0; D:=1;\nrepeat A(X,Y):=I;\n case of\n X+D>=N: [D:=-D; Y:=Y+1];\n Y-D>=N: [D:=-D; X:=X+1];\n X+D<0: [D:=-D; Y:=Y+1];\n Y-D<0: [D:=-D; X:=X+1]\n other [X:=X+D; Y:=Y-D];\n I:=I+1;\nuntil I>=N*N;\nfor Y:=0 to N-1 do\n [for X:=0 to N-1 do\n [I:=A(X,Y);\n ChOut(0,^ );\n if I<10 then ChOut(0,^ );\n IntOut(0, I);\n ];\n CrLf(0);\n ];\n]\n", "language": "XPL0" }, { "code": "Size = 5\nDIM array(Size-1, Size-1)\n\ni = 1\nj = 1\nFOR e = 0 TO Size^2-1\n array(i-1, j-1) = e\n IF and((i + j), 1) = 0 THEN\n IF j < Size then j = j + 1 ELSE i = i + 2 end if\n IF i > 1 i = i - 1\n ELSE\n IF i < Size then i = i + 1 ELSE j = j + 2 end if\n IF j > 1 j = j - 1\n ENDIF\nNEXT e\n\nFOR row = 0 TO Size-1\n FOR col = 0 TO Size-1\n PRINT array(row,col) USING \"##\";\n NEXT col\n PRINT\nNEXT row\n", "language": "Yabasic" }, { "code": "fcn zz(n){\n grid := (0).pump(n,List, (0).pump(n,List).copy).copy();\n ri := Ref(0);\n foreach d in ([1..n*2]){\n x:=(0).max(d - n); y:=(n - 1).min(d - 1);\n (0).pump(d.min(n*2 - d),Void,'wrap(it){\n grid[if(d%2)y-it else x+it][if(d%2)x+it else y-it] = ri.inc();\n });\n }\n grid.pump(String,'wrap(r){(\"%3s\"*n+\"\\n\").fmt(r.xplode())});\n}\n", "language": "Zkl" }, { "code": "fcn ceg(m){\n s := (0).pump(m*m,List).copy(); // copy to make writable\n rn := Ref(0);\n [[(i,j); [0..m*2-1]; '{[(0).max(i-m+1) .. i.min(m-1)]};\n '{ s[ if(i.isOdd) j*(m-1)+i else (i-j)*m+j ] = rn.inc(); }]];\n s.pump(String,T(Void.Read,m-1), (\"%3s\"*m+\"\\n\").fmt);\n}\n", "language": "Zkl" }, { "code": "fcn ceg2(m){\n rn := Ref(0);\n [[(i,j); [0..m*2-1]; '{[(0).max(i-m+1) .. i.min(m-1)]};\n '{ T( if(i.isOdd) j*(m-1)+i else (i-j)*m+j;, rn.inc() ) }]]\n .sort(fcn([(a,_)], [(b,_)]){ a<b }).apply(\"get\",1)\n .pump(String,T(Void.Read,m-1), (\"%3s\"*m+\"\\n\").fmt);\n}\n", "language": "Zkl" } ]
Zig-zag-matrix
[ { "code": "---\nfrom: http://rosettacode.org/wiki/Zumkeller_numbers\nnote: Prime Numbers\n", "language": "00-META" }, { "code": "Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on ''how'' the divisors are partitioned, only that the two partition sums are equal.\n\n\n;E.G.\n\n: '''6''' is a Zumkeller number; The divisors '''{1 2 3 6}''' can be partitioned into two groups '''{1 2 3}''' and '''{6}''' that both sum to 6.\n\n: '''10''' is not a Zumkeller number; The divisors '''{1 2 5 10}''' can not be partitioned into two groups in any way that will both sum to the same value.\n\n: '''12''' is a Zumkeller number; The divisors '''{1 2 3 4 6 12}''' can be partitioned into two groups '''{1 3 4 6}''' and '''{2 12}''' that both sum to 14.\n\n\nEven Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is ''at least'' one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task [[Abundant odd numbers]]; they are nearly the same except for the further restriction that the abundance ('''A(n) = sigma(n) - 2n'''), must be even: '''A(n) mod 2 == 0'''\n\n\n;Task:\n:* Write a routine (function, procedure, whatever) to find Zumkeller numbers.\n:* Use the routine to find and display here, on this page, the first '''220 Zumkeller numbers'''.\n:* Use the routine to find and display here, on this page, the first '''40 odd Zumkeller numbers'''.\n:* Optional, stretch goal: Use the routine to find and display here, on this page, the first '''40 odd Zumkeller numbers that don't end with 5'''.\n\n\n;See Also:\n\n:* '''[[oeis:A083207|OEIS:A083207 - Zumkeller numbers]]''' to get an impression of different partitions '''[[oeis:A083206/a083206.txt|OEIS:A083206 Zumkeller partitions]]'''\n:* '''[[oeis:A174865|OEIS:A174865 - Odd Zumkeller numbers]]'''\n\n\n;Related Tasks:\n\n:* '''[[Abundant odd numbers]]'''\n:* '''[[Abundant, deficient and perfect number classifications]]'''\n:* '''[[Proper divisors]]''' , '''[[Factors of an integer]]'''\n\n", "language": "00-TASK" }, { "code": "F getDivisors(n)\n V divs = [1, n]\n V i = 2\n L i * i <= n\n I n % i == 0\n divs [+]= i\n\n V j = n I/ i\n I i != j\n divs [+]= j\n i++\n R divs\n\nF isPartSum(divs, sum)\n I sum == 0\n R 1B\n\n V le = divs.len\n I le == 0\n R 0B\n\n V last = divs.last\n [Int] newDivs\n L(i) 0 .< le - 1\n newDivs [+]= divs[i]\n\n I last > sum\n R isPartSum(newDivs, sum)\n E\n R isPartSum(newDivs, sum) | isPartSum(newDivs, sum - last)\n\nF isZumkeller(n)\n V divs = getDivisors(n)\n V s = sum(divs)\n\n I s % 2 == 1\n R 0B\n\n I n % 2 == 1\n V abundance = s - 2 * n\n R abundance > 0 & abundance % 2 == 0\n\n R isPartSum(divs, s I/ 2)\n\nprint(‘The first 220 Zumkeller numbers are:’)\nV i = 2\nV count = 0\nL count < 220\n I isZumkeller(i)\n print(‘#3 ’.format(i), end' ‘’)\n count++\n I count % 20 == 0\n print()\n i++\n\nprint(\"\\nThe first 40 odd Zumkeller numbers are:\")\ni = 3\ncount = 0\nL count < 40\n I isZumkeller(i)\n print(‘#5 ’.format(i), end' ‘’)\n count++\n I count % 10 == 0\n print()\n i += 2\n\nprint(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\ni = 3\ncount = 0\nL count < 40\n I i % 10 != 5 & isZumkeller(i)\n print(‘#7 ’.format(i), end' ‘’)\n count++\n I count % 8 == 0\n print()\n i += 2\n", "language": "11l" }, { "code": "/* ARM assembly AARCH64 Raspberry PI 3B */\n/* program zumkellex641.s */\n\n/* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n\n/* REMARK 2 : this program is not optimized.\n Not search First 40 odd Zumkeller numbers not divisible by 5 */\n\n/*******************************************/\n/* Constantes file */\n/*******************************************/\n/* for this file see task include a file in language AArch64 assembly*/\n.include \"../includeConstantesARM64.inc\"\n\n.equ NBDIVISORS, 100\n\n\n/*******************************************/\n/* Structures */\n/********************************************/\n/* structurea area divisors */\n .struct 0\ndiv_ident: // ident\n .struct div_ident + 8\ndiv_flag: // value 0, 1 or 2\n .struct div_flag + 8\ndiv_fin:\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessStartPgm: .asciz \"Program start \\n\"\nszMessEndPgm: .asciz \"Program normal end.\\n\"\nszMessErrorArea: .asciz \"\\033[31mError : area divisors too small.\\n\"\nszMessError: .asciz \"\\033[31mError !!!\\n\"\n\nszCarriageReturn: .asciz \"\\n\"\n\n/* datas message display */\nszMessEntete: .asciz \"The first 220 Zumkeller numbers are:\\n\"\nsNumber: .space 4*20,' '\n .space 12,' ' // for end of conversion\nszMessListDivi: .asciz \"Divisors list : \\n\"\nszMessListDiviHeap: .asciz \"Heap 1 Divisors list : \\n\"\nszMessResult: .ascii \" \"\nsValue: .space 12,' '\n .asciz \"\"\n\nszMessEntete1: .asciz \"The first 40 odd Zumkeller numbers are:\\n\"\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n.align 4\ntbDivisors: .skip div_fin * NBDIVISORS // area divisors\nsZoneConv: .skip 30\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: // program start\n ldr x0,qAdrszMessStartPgm // display start message\n bl affichageMess\n\n ldr x0,qAdrszMessEntete // display message\n bl affichageMess\n mov x2,#1 // counter number\n mov x3,#0 // counter zumkeller number\n mov x4,#0 // counter for line display\n1:\n mov x0,x2 // number\n mov x1,#0 // display flag\n bl testZumkeller\n cmp x0,#1 // zumkeller ?\n bne 3f // no\n mov x0,x2\n ldr x1,qAdrsZoneConv // and convert ascii string\n bl conversion10\n ldr x0,qAdrsZoneConv // copy result in display line\n ldr x1,qAdrsNumber\n lsl x5,x4,#2\n add x1,x1,x5\n11:\n ldrb w5,[x0],1\n cbz w5,12f\n strb w5,[x1],1\n b 11b\n12:\n add x4,x4,#1\n cmp x4,#20\n blt 2f\n //add x1,x1,#3 // carriage return at end of display line\n mov x0,#'\\n'\n strb w0,[x1]\n mov x0,#0\n strb w0,[x1,#1] // end of display line\n ldr x0,qAdrsNumber // display result message\n bl affichageMess\n mov x4,#0\n2:\n add x3,x3,#1 // increment counter\n3:\n add x2,x2,#1 // increment number\n cmp x3,#220 // end ?\n blt 1b\n\n /* raz display line */\n ldr x0,qAdrsNumber\n mov x1,' '\n mov x2,0\n31:\n strb w1,[x0,x2]\n add x2,x2,1\n cmp x2,4*20\n blt 31b\n\n /* odd zumkeller numbers */\n ldr x0,qAdrszMessEntete1\n bl affichageMess\n mov x2,#1\n mov x3,#0\n mov x4,#0\n4:\n mov x0,x2 // number\n mov x1,#0 // display flag\n bl testZumkeller\n cmp x0,#1\n bne 6f\n mov x0,x2\n ldr x1,qAdrsZoneConv // and convert ascii string\n bl conversion10\n ldr x0,qAdrsZoneConv // copy result in display line\n ldr x1,qAdrsNumber\n lsl x5,x4,#3\n add x1,x1,x5\n41:\n ldrb w5,[x0],1\n cbz w5,42f\n strb w5,[x1],1\n b 41b\n42:\n add x4,x4,#1\n cmp x4,#8\n blt 5f\n mov x0,#'\\n'\n strb w0,[x1]\n strb wzr,[x1,#1]\n ldr x0,qAdrsNumber // display result message\n bl affichageMess\n mov x4,#0\n5:\n add x3,x3,#1\n6:\n add x2,x2,#2\n cmp x3,#40\n blt 4b\n\n\n ldr x0,qAdrszMessEndPgm // display end message\n bl affichageMess\n b 100f\n99: // display error message\n ldr x0,qAdrszMessError\n bl affichageMess\n100: // standard end of the program\n mov x0, #0 // return code\n mov x8, #EXIT // request to exit program\n svc 0 // perform system call\nqAdrszMessStartPgm: .quad szMessStartPgm\nqAdrszMessEndPgm: .quad szMessEndPgm\nqAdrszMessError: .quad szMessError\nqAdrszCarriageReturn: .quad szCarriageReturn\nqAdrszMessResult: .quad szMessResult\nqAdrsValue: .quad sValue\nqAdrszMessEntete: .quad szMessEntete\nqAdrszMessEntete1: .quad szMessEntete1\nqAdrsNumber: .quad sNumber\nqAdrsZoneConv: .quad sZoneConv\n/******************************************************************/\n/* test if number is Zumkeller number */\n/******************************************************************/\n/* x0 contains the number */\n/* x1 contains display flag (<>0: display, 0: no display ) */\n/* x0 return 1 if Zumkeller number else return 0 */\ntestZumkeller:\n stp x1,lr,[sp,-16]! // save registers\n stp x2,x3,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x7,[sp,-16]! // save registers\n mov x7,x1 // save flag\n ldr x1,qAdrtbDivisors\n bl divisors // create area of divisors\n cmp x0,#0 // 0 divisors or error ?\n ble 98f\n mov x5,x0 // number of dividers\n mov x6,x1 // number of odd dividers\n cmp x7,#1 // display divisors ?\n bne 1f\n ldr x0,qAdrszMessListDivi // yes\n bl affichageMess\n mov x0,x5\n mov x1,#0\n ldr x2,qAdrtbDivisors\n bl printHeap\n1:\n tst x6,#1 // number of odd divisors is odd ?\n bne 99f\n mov x0,x5\n mov x1,#0\n ldr x2,qAdrtbDivisors\n bl sumDivisors // compute divisors sum\n tst x0,#1 // sum is odd ?\n bne 99f // yes -> end\n lsr x6,x0,#1 // compute sum /2\n mov x0,x6 // x0 contains sum / 2\n mov x1,#1 // first heap\n mov x3,x5 // number divisors\n mov x4,#0 // N° element to start\n bl searchHeap\n cmp x0,#-2\n beq 100f // end\n cmp x0,#-1\n beq 100f // end\n\n cmp x7,#1 // print flag ?\n bne 2f\n ldr x0,qAdrszMessListDiviHeap\n bl affichageMess\n mov x0,x5 // yes print divisors of first heap\n ldr x2,qAdrtbDivisors\n mov x1,#1\n bl printHeap\n2:\n mov x0,#1 // ok\n b 100f\n98:\n mov x0,-1\n b 100f\n99:\n mov x0,#0\n b 100f\n100:\n ldp x6,x7,[sp],16 // restaur 2 registers\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x2,x3,[sp],16 // restaur 2 registers\n ldp x1,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\nqAdrtbDivisors: .quad tbDivisors\nqAdrszMessListDiviHeap: .quad szMessListDiviHeap\n/******************************************************************/\n/* search sum divisors = sum / 2 */\n/******************************************************************/\n/* x0 contains sum to search */\n/* x1 contains flag (1 or 2) */\n/* x2 contains address of divisors area */\n/* x3 contains elements number */\n/* x4 contains N° element to start */\n/* x0 return -2 end search */\n/* x0 return -1 no heap */\n/* x0 return 0 Ok */\n/* recursive routine */\nsearchHeap:\n stp x3,lr,[sp,-16]! // save registers\n stp x4,x5,[sp,-16]! // save registers\n stp x6,x8,[sp,-16]! // save registers\n1:\n cmp x4,x3 // indice = elements number\n beq 99f\n lsl x6,x4,#4 // compute element address\n add x6,x6,x2\n ldr x7,[x6,#div_flag] // flag equal ?\n cmp x7,#0\n bne 6f\n ldr x5,[x6,#div_ident]\n cmp x5,x0 // element value = remaining amount\n beq 7f // yes\n bgt 6f // too large\n // too less\n mov x8,x0 // save sum\n sub x0,x0,x5 // new sum to find\n add x4,x4,#1 // next divisors\n bl searchHeap // other search\n cmp x0,#0 // find -> ok\n beq 5f\n mov x0,x8 // sum begin\n sub x4,x4,#1 // prev divisors\n bl razFlags // zero in all flags > current element\n4:\n add x4,x4,#1 // last divisors\n b 1b\n5:\n str x1,[x6,#div_flag] // flag -> area element flag\n b 100f\n6:\n add x4,x4,#1 // last divisors\n b 1b\n7:\n str x1,[x6,#div_flag] // flag -> area element flag\n mov x0,#0 // search ok\n b 100f\n8:\n mov x0,#-1 // end search\n b 100f\n99:\n mov x0,#-2\n b 100f\n100:\n ldp x6,x8,[sp],16 // restaur 2 registers\n ldp x4,x5,[sp],16 // restaur 2 registers\n ldp x3,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/******************************************************************/\n/* raz flags */\n/******************************************************************/\n/* x0 contains sum to search */\n/* x1 contains flag (1 or 2) */\n/* x2 contains address of divisors area */\n/* x3 contains elements number */\n/* x4 contains N° element to start */\n/* x5 contains current sum */\n/* REMARK : NO SAVE REGISTERS x14 x15 x16 AND LR */\nrazFlags:\n mov x14,x4\n1:\n cmp x14,x3 // indice > nb elements ?\n bge 100f // yes -> end\n lsl x15,x14,#4\n add x15,x15,x2 // compute address element\n ldr x16,[x15,#div_flag] // load flag\n cmp x1,x16 // equal ?\n bne 2f\n str xzr,[x15,#div_flag] // yes -> store 0\n2:\n add x14,x14,#1 // increment indice\n b 1b // and loop\n100:\n ret // return to address lr x30\n/******************************************************************/\n/* compute sum of divisors */\n/******************************************************************/\n/* x0 contains elements number */\n/* x1 contains flag (0 1 or 2)\n/* x2 contains address of divisors area\n/* x0 return divisors sum */\n/* REMARK : NO SAVE REGISTERS x13 x14 x15 x16 AND LR */\nsumDivisors:\n mov x13,#0 // indice\n mov x16,#0 // sum\n1:\n lsl x14,x13,#4 // N° element * 16\n add x14,x14,x2\n ldr x15,[x14,#div_flag] // compare flag\n cmp x15,x1\n bne 2f\n ldr x15,[x14,#div_ident] // load value\n add x16,x16,x15 // and add\n2:\n add x13,x13,#1\n cmp x13,x0\n blt 1b\n mov x0,x16 // return sum\n100:\n ret // return to address lr x30\n/******************************************************************/\n/* print heap */\n/******************************************************************/\n/* x0 contains elements number */\n/* x1 contains flag (0 1 or 2) */\n/* x2 contains address of divisors area */\nprintHeap:\n stp x2,lr,[sp,-16]! // save registers\n stp x3,x4,[sp,-16]! // save registers\n stp x5,x6,[sp,-16]! // save registers\n stp x1,x7,[sp,-16]! // save registers\n mov x6,x0\n mov x5,x1\n mov x3,#0 // indice\n1:\n lsl x1,x3,#4 // N° element * 16\n add x1,x1,x2\n ldr x4,[x1,#div_flag]\n cmp x4,x5\n bne 2f\n ldr x0,[x1,#div_ident]\n ldr x1,qAdrsValue // and convert ascii string\n bl conversion10\n ldr x0,qAdrszMessResult // display result message\n bl affichageMess\n2:\n add x3,x3,#1\n cmp x3,x6\n blt 1b\n ldr x0,qAdrszCarriageReturn\n bl affichageMess\n100:\n ldp x1,x8,[sp],16 // restaur 2 registers\n ldp x5,x6,[sp],16 // restaur 2 registers\n ldp x3,x4,[sp],16 // restaur 2 registers\n ldp x2,lr,[sp],16 // restaur 2 registers\n ret // return to address lr x30\n/******************************************************************/\n/* divisors function */\n/******************************************************************/\n/* x0 contains the number */\n/* x1 contains address of divisors area\n/* x0 return divisors number */\n/* x1 return counter odd divisors */\n/* REMARK : NO SAVE REGISTERS x10 x11 x12 x13 x14 x15 x16 x17 x18 */\ndivisors:\n str lr,[sp,-16]! // save register LR\n cmp x0,#1 // = 1 ?\n ble 98f\n mov x17,x0\n mov x18,x1\n mov x11,#1 // counter odd divisors\n mov x0,#1 // first divisor = 1\n str x0,[x18,#div_ident]\n mov x0,#0\n str x0,[x18,#div_flag]\n tst x17,#1 // number is odd ?\n cinc x11,x11,ne // count odd divisors\n mov x0,x17 // last divisor = N\n add x10,x18,#16 // store at next element\n str x0,[x10,#div_ident]\n mov x0,#0\n str x0,[x10,#div_flag]\n\n mov x16,#2 // first divisor\n mov x15,#2 // Counter divisors\n2: // begin loop\n udiv x12,x17,x16\n msub x13,x12,x16,x17\n cmp x13,#0 // remainder = 0 ?\n bne 3f\n cmp x12,x16\n blt 4f // quot<divisor end\n lsl x10,x15,#4 // N° element * 16\n add x10,x10,x18 // and add at area begin address\n str x12,[x10,#div_ident]\n str xzr,[x10,#div_flag]\n add x15,x15,#1 // increment counter\n cmp x15,#NBDIVISORS // area maxi ?\n bge 99f\n tst x12,#1\n cinc x11,x11,ne // count odd divisors\n cmp x12,x16 // quotient = divisor ?\n ble 4f\n lsl x10,x15,#4 // N° element * 16\n add x10,x10,x18 // and add at area begin address\n str x16,[x10,#div_ident]\n str xzr,[x10,#div_flag]\n add x15,x15,#1 // increment counter\n cmp x15,#NBDIVISORS // area maxi ?\n bge 99f\n tst x16,#1\n cinc x11,x11,ne // count odd divisors\n3:\n cmp x12,x16\n ble 4f\n add x16,x16,#1 // increment divisor\n b 2b // and loop\n\n4:\n mov x0,x15 // return divisors number\n mov x1,x11 // return count odd divisors\n b 100f\n98:\n mov x0,0\n b 100f\n99: // error\n ldr x0,qAdrszMessErrorArea\n bl affichageMess\n mov x0,-1\n100:\n ldr lr,[sp],16 // restaur 1 registers\n ret // return to address lr x30\nqAdrszMessListDivi: .quad szMessListDivi\nqAdrszMessErrorArea: .quad szMessErrorArea\n/********************************************************/\n/* File Include fonctions */\n/********************************************************/\n/* for this file see task include a file in language AArch64 assembly */\n.include \"../includeARM64.inc\"\n", "language": "AArch64-Assembly" }, { "code": "-- Sum n's proper divisors.\non aliquotSum(n)\n if (n < 2) then return 0\n set sum to 1\n set sqrt to n ^ 0.5\n set limit to sqrt div 1\n if (limit = sqrt) then\n set sum to sum + limit\n set limit to limit - 1\n end if\n repeat with i from 2 to limit\n if (n mod i is 0) then set sum to sum + i + n div i\n end repeat\n\n return sum\nend aliquotSum\n\n-- Return n's proper divisors.\non properDivisors(n)\n set output to {}\n\n if (n > 1) then\n set sqrt to n ^ 0.5\n set limit to sqrt div 1\n if (limit = sqrt) then\n set end of output to limit\n set limit to limit - 1\n end if\n repeat with i from limit to 2 by -1\n if (n mod i is 0) then\n set beginning of output to i\n set end of output to n div i\n end if\n end repeat\n set beginning of output to 1\n end if\n\n return output\nend properDivisors\n\n-- Does a subset of the given list of numbers add up to the target value?\non subsetOf:numberList sumsTo:target\n script o\n property lst : numberList\n property someNegatives : false\n\n on ssp(target, i)\n repeat while (i > 1)\n set n to item i of my lst\n set i to i - 1\n if ((n = target) or (((n < target) or (someNegatives)) and (ssp(target - n, i)))) then return true\n end repeat\n return (target = beginning of my lst)\n end ssp\n end script\n -- The search can be more efficient if it's known the list contains no negatives.\n repeat with n in o's lst\n if (n < 0) then\n set o's someNegatives to true\n exit repeat\n end if\n end repeat\n\n return o's ssp(target, count o's lst)\nend subsetOf:sumsTo:\n\n-- Is n a Zumkeller number?\non isZumkeller(n)\n -- Yes if its aliquot sum is greater than or equal to it, the difference between them is even, and\n -- either n is odd or a subset of its proper divisors sums to half the sum of the divisors and it.\n -- Using aliquotSum() to get the divisor sum and then calling properDivisors() too if a list's actually\n -- needed is generally faster than using properDivisors() in the first place and summing the result.\n set sum to aliquotSum(n)\n return ((sum ≥ n) and ((sum - n) mod 2 = 0) and ¬\n ((n mod 2 = 1) or (my subsetOf:(properDivisors(n)) sumsTo:((sum + n) div 2))))\nend isZumkeller\n\n-- Task code:\n-- Find and return q Zumkeller numbers, starting the search at n and continuing at the\n-- given interval, applying the Zumkeller test only to numbers passing the given filter.\non zumkellerNumbers(q, n, interval, filter)\n script o\n property zumkellers : {}\n end script\n\n set counter to 0\n repeat until (counter = q)\n if ((filter's OK(n)) and (isZumkeller(n))) then\n set end of o's zumkellers to n\n set counter to counter + 1\n end if\n set n to n + interval\n end repeat\n\n return o's zumkellers\nend zumkellerNumbers\n\non joinText(textList, delimiter)\n set astid to AppleScript's text item delimiters\n set AppleScript's text item delimiters to delimiter\n set txt to textList as text\n set AppleScript's text item delimiters to astid\n\n return txt\nend joinText\n\non formatForDisplay(resultList, heading, resultsPerLine, separator)\n script o\n property input : resultList\n property output : {heading}\n end script\n\n set len to (count o's input)\n repeat with i from 1 to len by resultsPerLine\n set j to i + resultsPerLine - 1\n if (j > len) then set j to len\n set end of o's output to joinText(items i thru j of o's input, separator)\n end repeat\n\n return joinText(o's output, linefeed)\nend formatForDisplay\n\non doTask(cheating)\n set output to {}\n script noFilter\n on OK(n)\n return true\n end OK\n end script\n set header to \"1st 220 Zumkeller numbers:\"\n set end of output to formatForDisplay(zumkellerNumbers(220, 1, 1, noFilter), header, 20, \" \")\n set header to \"1st 40 odd Zumkeller numbers:\"\n set end of output to formatForDisplay(zumkellerNumbers(40, 1, 2, noFilter), header, 10, \" \")\n\n -- Stretch goal:\n set header to \"1st 40 odd Zumkeller numbers not ending with 5:\"\n script no5Multiples\n on OK(n)\n return (n mod 5 > 0)\n end OK\n end script\n if (cheating) then\n -- Knowing that the HCF of the first 203 odd Zumkellers not ending with 5\n -- is 63, just check 63 and each 126th number thereafter.\n -- For the 204th - 907th such numbers, the HCF reduces to 21, so adjust accordingly.\n -- (See Horsth's comments on the Talk page.)\n set zumkellers to zumkellerNumbers(40, 63, 126, no5Multiples)\n else\n -- Otherwise check alternate numbers from 1.\n set zumkellers to zumkellerNumbers(40, 1, 2, no5Multiples)\n end if\n set end of output to formatForDisplay(zumkellers, header, 10, \" \")\n\n return joinText(output, linefeed & linefeed)\nend doTask\n\nlocal cheating\nset cheating to false\ndoTask(cheating)\n", "language": "AppleScript" }, { "code": "\"1st 220 Zumkeller numbers:\n6 12 20 24 28 30 40 42 48 54 56 60 66 70 78 80 84 88 90 96\n102 104 108 112 114 120 126 132 138 140 150 156 160 168 174 176 180 186 192 198\n204 208 210 216 220 222 224 228 234 240 246 252 258 260 264 270 272 276 280 282\n294 300 304 306 308 312 318 320 330 336 340 342 348 350 352 354 360 364 366 368\n372 378 380 384 390 396 402 408 414 416 420 426 432 438 440 444 448 456 460 462\n464 468 474 476 480 486 490 492 496 498 500 504 510 516 520 522 528 532 534 540\n544 546 550 552 558 560 564 570 572 580 582 588 594 600 606 608 612 616 618 620\n624 630 636 640 642 644 650 654 660 666 672 678 680 684 690 696 700 702 704 708\n714 720 726 728 732 736 740 744 750 756 760 762 768 770 780 786 792 798 804 810\n812 816 820 822 828 832 834 836 840 852 858 860 864 868 870 876 880 888 894 896\n906 910 912 918 920 924 928 930 936 940 942 945 948 952 960 966 972 978 980 984\n\n1st 40 odd Zumkeller numbers:\n945 1575 2205 2835 3465 4095 4725 5355 5775 5985\n6435 6615 6825 7245 7425 7875 8085 8415 8505 8925\n9135 9555 9765 10395 11655 12285 12705 12915 13545 14175\n14805 15015 15435 16065 16695 17325 17955 18585 19215 19305\n\n1st 40 odd Zumkeller numbers not ending with 5:\n81081 153153 171171 189189 207207 223839 243243 261261 279279 297297\n351351 459459 513513 567567 621621 671517 729729 742203 783783 793611\n812889 837837 891891 908523 960687 999999 1024947 1054053 1072071 1073709\n1095633 1108107 1145529 1162161 1198197 1224531 1270269 1307691 1324323 1378377\"\n", "language": "AppleScript" }, { "code": "/* ARM assembly Raspberry PI */\n/* program zumkeller4.s */\n/* new version 10/2020 */\n\n /* REMARK 1 : this program use routines in a include file\n see task Include a file language arm assembly\n for the routine affichageMess conversion10\n see at end of this program the instruction include */\n/* for constantes see task include a file in arm assembly */\n/************************************/\n/* Constantes */\n/************************************/\n.include \"../constantes.inc\"\n\n.equ NBDIVISORS, 1000\n\n/*******************************************/\n/* Initialized data */\n/*******************************************/\n.data\nszMessStartPgm: .asciz \"Program start \\n\"\nszMessEndPgm: .asciz \"Program normal end.\\n\"\nszMessErrorArea: .asciz \"\\033[31mError : area divisors too small.\\n\"\nszMessError: .asciz \"\\033[31mError !!!\\n\"\nszMessErrGen: .asciz \"Error end program.\\n\"\nszMessNbPrem: .asciz \"This number is prime !!!.\\n\"\nszMessResultFact: .asciz \"@ \"\n\nszCarriageReturn: .asciz \"\\n\"\n\n/* datas message display */\nszMessEntete: .asciz \"The first 220 Zumkeller numbers are:\\n\"\nsNumber: .space 4*20,' '\n .space 12,' ' @ for end of conversion\nszMessListDivi: .asciz \"Divisors list : \\n\"\nszMessListDiviHeap: .asciz \"Heap 1 Divisors list : \\n\"\nszMessResult: .ascii \" \"\nsValue: .space 12,' '\n .asciz \"\"\n\nszMessEntete1: .asciz \"The first 40 odd Zumkeller numbers are:\\n\"\nszMessEntete2: .asciz \"First 40 odd Zumkeller numbers not divisible by 5:\\n\"\n/*******************************************/\n/* UnInitialized data */\n/*******************************************/\n.bss\n.align 4\nsZoneConv: .skip 24\ntbZoneDecom: .skip 8 * NBDIVISORS // facteur 4 octets, nombre 4\n/*******************************************/\n/* code section */\n/*******************************************/\n.text\n.global main\nmain: @ program start\n ldr r0,iAdrszMessStartPgm @ display start message\n bl affichageMess\n\n ldr r0,iAdrszMessEntete @ display result message\n bl affichageMess\n mov r2,#1\n mov r3,#0\n mov r4,#0\n1:\n mov r0,r2 @ number\n bl testZumkeller\n cmp r0,#1\n bne 3f\n mov r0,r2\n ldr r1,iAdrsNumber @ and convert ascii string\n lsl r5,r4,#2\n add r1,r5\n bl conversion10\n add r4,r4,#1\n cmp r4,#20\n blt 2f\n add r1,r1,#3\n mov r0,#'\\n'\n strb r0,[r1]\n mov r0,#0\n strb r0,[r1,#1]\n ldr r0,iAdrsNumber @ display result message\n bl affichageMess\n mov r4,#0\n2:\n add r3,r3,#1\n3:\n add r2,r2,#1\n cmp r3,#220\n blt 1b\n\n /* odd zumkeller numbers */\n ldr r0,iAdrszMessEntete1\n bl affichageMess\n mov r2,#1\n mov r3,#0\n mov r4,#0\n4:\n mov r0,r2 @ number\n bl testZumkeller\n cmp r0,#1\n bne 6f\n mov r0,r2\n ldr r1,iAdrsNumber @ and convert ascii string\n lsl r5,r4,#3\n add r1,r5\n bl conversion10\n add r4,r4,#1\n cmp r4,#8\n blt 5f\n add r1,r1,#8\n mov r0,#'\\n'\n strb r0,[r1]\n mov r0,#0\n strb r0,[r1,#1]\n ldr r0,iAdrsNumber @ display result message\n bl affichageMess\n mov r4,#0\n5:\n add r3,r3,#1\n6:\n add r2,r2,#2\n cmp r3,#40\n blt 4b\n /* odd zumkeller numbers not multiple5 */\n61:\n ldr r0,iAdrszMessEntete2\n bl affichageMess\n mov r3,#0\n mov r4,#0\n7:\n lsr r8,r2,#3 @ divide counter by 5\n add r8,r8,r2,lsr #4\n add r8,r8,r8,lsr #4\n add r8,r8,r8,lsr #8\n add r8,r8,r8,lsr #16\n add r9,r8,r8,lsl #2 @ multiply result by 5\n sub r9,r2,r9\n mov r6,#13\n mul r9,r6,r9\n lsr r9,#6\n add r9,r8 @ it is a quotient\n add r9,r9,r9,lsl #2 @ multiply by 5\n sub r9,r2,r9 @ compute remainder\n cmp r9,#0 @ remainder = zero ?\n beq 9f\n mov r0,r2 @ number\n bl testZumkeller\n cmp r0,#1\n bne 9f\n mov r0,r2\n ldr r1,iAdrsNumber @ and convert ascii string\n lsl r5,r4,#3\n add r1,r5\n bl conversion10\n add r4,r4,#1\n cmp r4,#8\n blt 8f\n add r1,r1,#8\n mov r0,#'\\n'\n strb r0,[r1]\n mov r0,#0\n strb r0,[r1,#1]\n ldr r0,iAdrsNumber @ display result message\n bl affichageMess\n mov r4,#0\n8:\n add r3,r3,#1\n9:\n add r2,r2,#2\n cmp r3,#40\n blt 7b\n\n ldr r0,iAdrszMessEndPgm @ display end message\n bl affichageMess\n b 100f\n99: @ display error message\n ldr r0,iAdrszMessError\n bl affichageMess\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessStartPgm: .int szMessStartPgm\niAdrszMessEndPgm: .int szMessEndPgm\niAdrszMessError: .int szMessError\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessResult: .int szMessResult\niAdrsValue: .int sValue\niAdrtbZoneDecom: .int tbZoneDecom\niAdrszMessEntete: .int szMessEntete\niAdrszMessEntete1: .int szMessEntete1\niAdrszMessEntete2: .int szMessEntete2\niAdrsNumber: .int sNumber\n\n/******************************************************************/\n/* test if number is Zumkeller number */\n/******************************************************************/\n/* r0 contains the number */\n/* r0 return 1 if Zumkeller number else return 0 */\ntestZumkeller:\n push {r1-r6,lr} @ save registers\n mov r6,r0 @ save number\n ldr r1,iAdrtbZoneDecom\n bl decompFact @ create area of divisors\n cmp r0,#1 @ no divisors\n movle r0,#0\n ble 100f\n tst r2,#1 @ odd sum ?\n movne r0,#0\n bne 100f @ yes -> end\n tst r1,#1 @ number of odd divisors is odd ?\n movne r0,#0\n bne 100f @ yes -> end\n lsl r5,r6,#1 @ abondant number\n cmp r5,r2\n movgt r0,#0\n bgt 100f @ no -> end\n mov r3,r0\n mov r4,r2 @ save sum\n ldr r0,iAdrtbZoneDecom\n mov r1,#0\n mov r2,r3\n bl shellSort @ sort table\n\n mov r1,r3 @ factors number\n ldr r0,iAdrtbZoneDecom\n lsr r2,r4,#1 @ sum / 2\n bl computePartIter @\n\n100:\n pop {r1-r6,lr} @ restaur registers\n bx lr @ return\n\n/******************************************************************/\n/* search factors to sum = entry value */\n/******************************************************************/\n/* r0 contains address of divisors area */\n/* r1 contains elements number */\n/* r2 contains divisors sum / 2 */\n/* r0 return 1 if ok 0 else */\ncomputePartIter:\n push {r1-r7,fp,lr} @ save registers\n lsl r7,r1,#3 @ compute size of temp table\n sub sp,r7 @ and reserve on stack\n mov fp,sp @ frame pointer = stack address = begin table\n mov r5,#0 @ stack indice\n sub r3,r1,#1\n1:\n ldr r4,[r0,r3,lsl #2] @ load factor\n cmp r4,r2 @ compare value\n bgt 2f\n beq 90f @ equal -> end ok\n cmp r3,#0 @ first item ?\n beq 3f\n sub r3,#1 @ push indice item in temp table\n add r6,fp,r5,lsl #3\n str r3,[r6]\n str r2,[r6,#4] @ push sum in temp table\n add r5,#1\n sub r2,r4 @ substract divisors from sum\n b 1b\n2:\n sub r3,#1 @ other divisors\n cmp r3,#0 @ first item ?\n bge 1b\n3: @ first item\n cmp r5,#0 @ stack empty ?\n moveq r0,#0 @ no sum factors equal to value\n beq 100f @ end\n sub r5,#1 @ else pop stack\n add r6,fp,r5,lsl #3 @ and restaur\n ldr r3,[r6] @ indice\n ldr r2,[r6,#4] @ and value\n b 1b @ and loop\n\n90:\n mov r0,#1 @ it is ok\n100:\n add sp,r7 @ stack alignement\n pop {r1-r7,fp,lr} @ restaur registers\n bx lr @ return\n\n/******************************************************************/\n/* factor decomposition */\n/******************************************************************/\n/* r0 contains number */\n/* r1 contains address of divisors area */\n/* r0 return divisors items in table */\n/* r1 return the number of odd divisors */\n/* r2 return the sum of divisors */\ndecompFact:\n push {r3-r8,lr} @ save registers\n mov r5,r1\n mov r8,r0 @ save number\n bl isPrime @ prime ?\n cmp r0,#1\n beq 98f @ yes is prime\n mov r1,#1\n str r1,[r5] @ first factor\n mov r12,#1 @ divisors sum\n mov r11,#1 @ number odd divisors\n mov r4,#1 @ indice divisors table\n mov r1,#2 @ first divisor\n mov r6,#0 @ previous divisor\n mov r7,#0 @ number of same divisors\n2:\n mov r0,r8 @ dividende\n bl division @ r1 divisor r2 quotient r3 remainder\n cmp r3,#0\n bne 5f @ if remainder <> zero -> no divisor\n mov r8,r2 @ else quotient -> new dividende\n cmp r1,r6 @ same divisor ?\n beq 4f @ yes\n mov r7,r4 @ number factors in table\n mov r9,#0 @ indice\n21:\n ldr r10,[r5,r9,lsl #2 ] @ load one factor\n mul r10,r1,r10 @ multiply\n str r10,[r5,r7,lsl #2] @ and store in the table\n tst r10,#1 @ divisor odd ?\n addne r11,#1\n add r12,r10\n add r7,r7,#1 @ and increment counter\n add r9,r9,#1\n cmp r9,r4\n blt 21b\n mov r4,r7\n mov r6,r1 @ new divisor\n b 7f\n4: @ same divisor\n sub r9,r4,#1\n mov r7,r4\n41:\n ldr r10,[r5,r9,lsl #2 ]\n cmp r10,r1\n subne r9,#1\n bne 41b\n sub r9,r4,r9\n42:\n ldr r10,[r5,r9,lsl #2 ]\n mul r10,r1,r10\n str r10,[r5,r7,lsl #2] @ and store in the table\n tst r10,#1 @ divsor odd ?\n addne r11,#1\n add r12,r10\n add r7,r7,#1 @ and increment counter\n add r9,r9,#1\n cmp r9,r4\n blt 42b\n mov r4,r7\n b 7f @ and loop\n\n /* not divisor -> increment next divisor */\n5:\n cmp r1,#2 @ if divisor = 2 -> add 1\n addeq r1,#1\n addne r1,#2 @ else add 2\n b 2b\n\n /* divisor -> test if new dividende is prime */\n7:\n mov r3,r1 @ save divisor\n cmp r8,#1 @ dividende = 1 ? -> end\n beq 10f\n mov r0,r8 @ new dividende is prime ?\n mov r1,#0\n bl isPrime @ the new dividende is prime ?\n cmp r0,#1\n bne 10f @ the new dividende is not prime\n\n cmp r8,r6 @ else dividende is same divisor ?\n beq 9f @ yes\n mov r7,r4 @ number factors in table\n mov r9,#0 @ indice\n71:\n ldr r10,[r5,r9,lsl #2 ] @ load one factor\n mul r10,r8,r10 @ multiply\n str r10,[r5,r7,lsl #2] @ and store in the table\n tst r10,#1 @ divsor odd ?\n addne r11,#1\n add r12,r10\n add r7,r7,#1 @ and increment counter\n add r9,r9,#1\n cmp r9,r4\n blt 71b\n mov r4,r7\n mov r7,#0\n b 11f\n9:\n sub r9,r4,#1\n mov r7,r4\n91:\n ldr r10,[r5,r9,lsl #2 ]\n cmp r10,r8\n subne r9,#1\n bne 91b\n sub r9,r4,r9\n92:\n ldr r10,[r5,r9,lsl #2 ]\n mul r10,r8,r10\n str r10,[r5,r7,lsl #2] @ and store in the table\n tst r10,#1 @ divisor odd ?\n addne r11,#1\n add r12,r10\n add r7,r7,#1 @ and increment counter\n add r9,r9,#1\n cmp r9,r4\n blt 92b\n mov r4,r7\n b 11f\n\n10:\n mov r1,r3 @ current divisor = new divisor\n cmp r1,r8 @ current divisor > new dividende ?\n ble 2b @ no -> loop\n\n /* end decomposition */\n11:\n mov r0,r4 @ return number of table items\n mov r2,r12 @ return sum\n mov r1,r11 @ return number of odd divisor\n mov r3,#0\n str r3,[r5,r4,lsl #2] @ store zéro in last table item\n b 100f\n\n\n98:\n //ldr r0,iAdrszMessNbPrem\n //bl affichageMess\n mov r0,#1 @ return code\n b 100f\n99:\n ldr r0,iAdrszMessError\n bl affichageMess\n mov r0,#-1 @ error code\n b 100f\n100:\n pop {r3-r8,lr} @ restaur registers\n bx lr\niAdrszMessNbPrem: .int szMessNbPrem\n/***************************************************/\n/* check if a number is prime */\n/***************************************************/\n/* r0 contains the number */\n/* r0 return 1 if prime 0 else */\n@2147483647\n@4294967297\n@131071\nisPrime:\n push {r1-r6,lr} @ save registers\n cmp r0,#0\n beq 90f\n cmp r0,#17\n bhi 1f\n cmp r0,#3\n bls 80f @ for 1,2,3 return prime\n cmp r0,#5\n beq 80f @ for 5 return prime\n cmp r0,#7\n beq 80f @ for 7 return prime\n cmp r0,#11\n beq 80f @ for 11 return prime\n cmp r0,#13\n beq 80f @ for 13 return prime\n cmp r0,#17\n beq 80f @ for 17 return prime\n1:\n tst r0,#1 @ even ?\n beq 90f @ yes -> not prime\n mov r2,r0 @ save number\n sub r1,r0,#1 @ exposant n - 1\n mov r0,#3 @ base\n bl moduloPuR32 @ compute base power n - 1 modulo n\n cmp r0,#1\n bne 90f @ if <> 1 -> not prime\n\n mov r0,#5\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#7\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#11\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#13\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n\n mov r0,#17\n bl moduloPuR32\n cmp r0,#1\n bne 90f\n80:\n mov r0,#1 @ is prime\n b 100f\n90:\n mov r0,#0 @ no prime\n100: @ fin standard de la fonction\n pop {r1-r6,lr} @ restaur des registres\n bx lr @ retour de la fonction en utilisant lr\n/********************************************************/\n/* Calcul modulo de b puissance e modulo m */\n/* Exemple 4 puissance 13 modulo 497 = 445 */\n/* */\n/********************************************************/\n/* r0 nombre */\n/* r1 exposant */\n/* r2 modulo */\n/* r0 return result */\nmoduloPuR32:\n push {r1-r7,lr} @ save registers\n cmp r0,#0 @ verif <> zero\n beq 100f\n cmp r2,#0 @ verif <> zero\n beq 100f @ TODO: vérifier les cas d erreur\n1:\n mov r4,r2 @ save modulo\n mov r5,r1 @ save exposant\n mov r6,r0 @ save base\n mov r3,#1 @ start result\n\n mov r1,#0 @ division de r0,r1 par r2\n bl division32R\n mov r6,r2 @ base <- remainder\n2:\n tst r5,#1 @ exposant even or odd\n beq 3f\n umull r0,r1,r6,r3\n mov r2,r4\n bl division32R\n mov r3,r2 @ result <- remainder\n3:\n umull r0,r1,r6,r6\n mov r2,r4\n bl division32R\n mov r6,r2 @ base <- remainder\n\n lsr r5,#1 @ left shift 1 bit\n cmp r5,#0 @ end ?\n bne 2b\n mov r0,r3\n100: @ fin standard de la fonction\n pop {r1-r7,lr} @ restaur des registres\n bx lr @ retour de la fonction en utilisant lr\n\n/***************************************************/\n/* division number 64 bits in 2 registers by number 32 bits */\n/***************************************************/\n/* r0 contains lower part dividende */\n/* r1 contains upper part dividende */\n/* r2 contains divisor */\n/* r0 return lower part quotient */\n/* r1 return upper part quotient */\n/* r2 return remainder */\ndivision32R:\n push {r3-r9,lr} @ save registers\n mov r6,#0 @ init upper upper part remainder !!\n mov r7,r1 @ init upper part remainder with upper part dividende\n mov r8,r0 @ init lower part remainder with lower part dividende\n mov r9,#0 @ upper part quotient\n mov r4,#0 @ lower part quotient\n mov r5,#32 @ bits number\n1: @ begin loop\n lsl r6,#1 @ shift upper upper part remainder\n lsls r7,#1 @ shift upper part remainder\n orrcs r6,#1\n lsls r8,#1 @ shift lower part remainder\n orrcs r7,#1\n lsls r4,#1 @ shift lower part quotient\n lsl r9,#1 @ shift upper part quotient\n orrcs r9,#1\n @ divisor sustract upper part remainder\n subs r7,r2\n sbcs r6,#0 @ and substract carry\n bmi 2f @ négative ?\n\n @ positive or equal\n orr r4,#1 @ 1 -> right bit quotient\n b 3f\n2: @ negative\n orr r4,#0 @ 0 -> right bit quotient\n adds r7,r2 @ and restaur remainder\n adc r6,#0\n3:\n subs r5,#1 @ decrement bit size\n bgt 1b @ end ?\n mov r0,r4 @ lower part quotient\n mov r1,r9 @ upper part quotient\n mov r2,r7 @ remainder\n100: @ function end\n pop {r3-r9,lr} @ restaur registers\n bx lr\n/***************************************************/\n/* shell Sort */\n/***************************************************/\n\n/* r0 contains the address of table */\n/* r1 contains the first element but not use !! */\n/* this routine use first element at index zero !!! */\n/* r2 contains the number of element */\nshellSort:\n push {r0-r7,lr} @save registers\n sub r2,#1 @ index last item\n mov r1,r2 @ init gap = last item\n1: @ start loop 1\n lsrs r1,#1 @ gap = gap / 2\n beq 100f @ if gap = 0 -> end\n mov r3,r1 @ init loop indice 1\n2: @ start loop 2\n ldr r4,[r0,r3,lsl #2] @ load first value\n mov r5,r3 @ init loop indice 2\n3: @ start loop 3\n cmp r5,r1 @ indice < gap\n blt 4f @ yes -> end loop 2\n sub r6,r5,r1 @ index = indice - gap\n ldr r7,[r0,r6,lsl #2] @ load second value\n cmp r4,r7 @ compare values\n strlt r7,[r0,r5,lsl #2] @ store if <\n sublt r5,r1 @ indice = indice - gap\n blt 3b @ and loop\n4: @ end loop 3\n str r4,[r0,r5,lsl #2] @ store value 1 at indice 2\n add r3,#1 @ increment indice 1\n cmp r3,r2 @ end ?\n ble 2b @ no -> loop 2\n b 1b @ yes loop for new gap\n\n100: @ end function\n pop {r0-r7,lr} @ restaur registers\n bx lr @ return\n/******************************************************************/\n/* display divisors function */\n/******************************************************************/\n/* r0 contains address of divisors area */\n/* r1 contains the number of area items */\ndisplayDivisors:\n push {r2-r8,lr} @ save registers\n cmp r1,#0\n beq 100f\n mov r2,r1\n mov r3,#0 @ indice\n mov r4,r0\n1:\n add r5,r4,r3,lsl #2\n ldr r0,[r5] @ load factor\n\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call décimal conversion\n ldr r0,iAdrszMessResultFact\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess @ display message\n add r3,#1 @ other ithem\n cmp r3,r2 @ items maxi ?\n blt 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n b 100f\n\n100:\n pop {r2-r8,lr} @ restaur registers\n bx lr @ return\niAdrszMessResultFact: .int szMessResultFact\niAdrsZoneConv: .int sZoneConv\n/***************************************************/\n/* ROUTINES INCLUDE */\n/***************************************************/\n.include \"../affichage.inc\"\n", "language": "ARM-Assembly" }, { "code": "#include <iostream\">\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <numeric>\n\nusing namespace std;\n\n// Returns n in binary right justified with length passed and padded with zeroes\nconst uint* binary(uint n, uint length);\n\n// Returns the sum of the binary ordered subset of rank r.\n// Adapted from Sympy implementation.\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r);\n\nvector<uint> factors(uint x);\n\nbool isPrime(uint number);\n\nbool isZum(uint n);\n\nostream& operator<<(ostream& os, const vector<uint>& zumz) {\n for (uint i = 0; i < zumz.size(); i++) {\n if (i % 10 == 0)\n os << endl;\n os << setw(10) << zumz[i] << ' ';\n }\n return os;\n}\n\nint main() {\n cout << \"First 220 Zumkeller numbers:\" << endl;\n vector<uint> zumz;\n for (uint n = 2; zumz.size() < 220; n++)\n if (isZum(n))\n zumz.push_back(n);\n cout << zumz << endl << endl;\n\n cout << \"First 40 odd Zumkeller numbers:\" << endl;\n vector<uint> zumz2;\n for (uint n = 2; zumz2.size() < 40; n++)\n if (n % 2 && isZum(n))\n zumz2.push_back(n);\n cout << zumz2 << endl << endl;\n\n cout << \"First 40 odd Zumkeller numbers not ending in 5:\" << endl;\n vector<uint> zumz3;\n for (uint n = 2; zumz3.size() < 40; n++)\n if (n % 2 && (n % 10) != 5 && isZum(n))\n zumz3.push_back(n);\n cout << zumz3 << endl << endl;\n\n return 0;\n}\n\n// Returns n in binary right justified with length passed and padded with zeroes\nconst uint* binary(uint n, uint length) {\n uint* bin = new uint[length];\t // array to hold result\n fill(bin, bin + length, 0); // fill with zeroes\n // convert n to binary and store right justified in bin\n for (uint i = 0; n > 0; i++) {\n uint rem = n % 2;\n n /= 2;\n if (rem)\n bin[length - 1 - i] = 1;\n }\n\n return bin;\n}\n\n// Returns the sum of the binary ordered subset of rank r.\n// Adapted from Sympy implementation.\nuint sum_subset_unrank_bin(const vector<uint>& d, uint r) {\n vector<uint> subset;\n // convert r to binary array of same size as d\n const uint* bits = binary(r, d.size() - 1);\n\n // get binary ordered subset\n for (uint i = 0; i < d.size() - 1; i++)\n if (bits[i])\n subset.push_back(d[i]);\n\n delete[] bits;\n\n return accumulate(subset.begin(), subset.end(), 0u);\n}\n\nvector<uint> factors(uint x) {\n vector<uint> result;\n // this will loop from 1 to int(sqrt(x))\n for (uint i = 1; i * i <= x; i++) {\n // Check if i divides x without leaving a remainder\n if (x % i == 0) {\n result.push_back(i);\n\n if (x / i != i)\n result.push_back(x / i);\n }\n }\n\n // return the sorted factors of x\n sort(result.begin(), result.end());\n return result;\n}\n\nbool isPrime(uint number) {\n if (number < 2) return false;\n if (number == 2) return true;\n if (number % 2 == 0) return false;\n for (uint i = 3; i * i <= number; i += 2)\n if (number % i == 0) return false;\n\n return true;\n}\n\nbool isZum(uint n) {\n // if prime it ain't no zum\n if (isPrime(n))\n return false;\n\n // get sum of divisors\n const auto d = factors(n);\n uint s = accumulate(d.begin(), d.end(), 0u);\n\n // if sum is odd or sum < 2*n it ain't no zum\n if (s % 2 || s < 2 * n)\n return false;\n\n // if we get here and n is odd or n has at least 24 divisors it's a zum!\n // Valid for even n < 99504. To test n beyond this bound, comment out this condition.\n // And wait all day. Thanks to User:Horsth for taking the time to find this bound!\n if (n % 2 || d.size() >= 24)\n return true;\n\n if (!(s % 2) && d[d.size() - 1] <= s / 2)\n for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) // using log2 prevents overflow\n if (sum_subset_unrank_bin(d, x) == s / 2)\n return true; // congratulations it's a zum num!!\n\n // if we get here it ain't no zum\n return false;\n}\n", "language": "C++" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ZumkellerNumbers {\n class Program {\n static List<int> GetDivisors(int n) {\n List<int> divs = new List<int> {\n 1, n\n };\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int j = n / i;\n divs.Add(i);\n if (i != j) {\n divs.Add(j);\n }\n }\n }\n return divs;\n }\n\n static bool IsPartSum(List<int> divs, int sum) {\n if (sum == 0) {\n return true;\n }\n var le = divs.Count;\n if (le == 0) {\n return false;\n }\n var last = divs[le - 1];\n List<int> newDivs = new List<int>();\n for (int i = 0; i < le - 1; i++) {\n newDivs.Add(divs[i]);\n }\n if (last > sum) {\n return IsPartSum(newDivs, sum);\n }\n return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);\n }\n\n static bool IsZumkeller(int n) {\n var divs = GetDivisors(n);\n var sum = divs.Sum();\n // if sum is odd can't be split into two partitions with equal sums\n if (sum % 2 == 1) {\n return false;\n }\n // if n is odd use 'abundant odd number' optimization\n if (n % 2 == 1) {\n var abundance = sum - 2 * n;\n return abundance > 0 && abundance % 2 == 0;\n }\n // if n and sum are both even check if there's a partition which totals sum / 2\n return IsPartSum(divs, sum / 2);\n }\n\n static void Main() {\n Console.WriteLine(\"The first 220 Zumkeller numbers are:\");\n int i = 2;\n for (int count = 0; count < 220; i++) {\n if (IsZumkeller(i)) {\n Console.Write(\"{0,3} \", i);\n count++;\n if (count % 20 == 0) {\n Console.WriteLine();\n }\n }\n }\n\n Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers are:\");\n i = 3;\n for (int count = 0; count < 40; i += 2) {\n if (IsZumkeller(i)) {\n Console.Write(\"{0,5} \", i);\n count++;\n if (count % 10 == 0) {\n Console.WriteLine();\n }\n }\n }\n\n Console.WriteLine(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n i = 3;\n for (int count = 0; count < 40; i += 2) {\n if (i % 10 != 5 && IsZumkeller(i)) {\n Console.Write(\"{0,7} \", i);\n count++;\n if (count % 8 == 0) {\n Console.WriteLine();\n }\n }\n }\n }\n }\n}\n", "language": "C-sharp" }, { "code": "import std.algorithm;\nimport std.stdio;\n\nint[] getDivisors(int n) {\n auto divs = [1, n];\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n divs ~= i;\n\n int j = n / i;\n if (i != j) {\n divs ~= j;\n }\n }\n }\n return divs;\n}\n\nbool isPartSum(int[] divs, int sum) {\n if (sum == 0) {\n return true;\n }\n auto le = divs.length;\n if (le == 0) {\n return false;\n }\n auto last = divs[$ - 1];\n int[] newDivs;\n for (int i = 0; i < le - 1; i++) {\n newDivs ~= divs[i];\n }\n if (last > sum) {\n return isPartSum(newDivs, sum);\n } else {\n return isPartSum(newDivs, sum) || isPartSum(newDivs, sum - last);\n }\n}\n\nbool isZumkeller(int n) {\n auto divs = getDivisors(n);\n auto sum = divs.sum();\n // if sum is odd can't be split into two partitions with equal sums\n if (sum % 2 == 1) {\n return false;\n }\n // if n is odd use 'abundant odd number' optimization\n if (n % 2 == 1) {\n auto abundance = sum - 2 * n;\n return abundance > 0 && abundance % 2 == 0;\n }\n // if n and sum are both even check if there's a partition which totals sum / 2\n return isPartSum(divs, sum / 2);\n}\n\nvoid main() {\n writeln(\"The first 220 Zumkeller numbers are:\");\n int i = 2;\n for (int count = 0; count < 220; i++) {\n if (isZumkeller(i)) {\n writef(\"%3d \", i);\n count++;\n if (count % 20 == 0) {\n writeln;\n }\n }\n }\n\n writeln(\"\\nThe first 40 odd Zumkeller numbers are:\");\n i = 3;\n for (int count = 0; count < 40; i += 2) {\n if (isZumkeller(i)) {\n writef(\"%5d \", i);\n count++;\n if (count % 10 == 0) {\n writeln;\n }\n }\n }\n\n writeln(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\n i = 3;\n for (int count = 0; count < 40; i += 2) {\n if (i % 10 != 5 && isZumkeller(i)) {\n writef(\"%7d \", i);\n count++;\n if (count % 8 == 0) {\n writeln;\n }\n }\n }\n}\n", "language": "D" }, { "code": "proc divisors n . divs[] .\n divs[] = [ 1 n ]\n for i = 2 to sqrt n\n if n mod i = 0\n j = n / i\n divs[] &= i\n if i <> j\n divs[] &= j\n .\n .\n .\n.\nfunc ispartsum divs[] sum .\n if sum = 0\n return 1\n .\n if len divs[] = 0\n return 0\n .\n last = divs[len divs[]]\n len divs[] -1\n if last > sum\n return ispartsum divs[] sum\n .\n if ispartsum divs[] sum = 1\n return 1\n .\n return ispartsum divs[] (sum - last)\n.\nfunc iszumkeller n .\n divisors n divs[]\n for v in divs[]\n sum += v\n .\n if sum mod 2 = 1\n return 0\n .\n if n mod 2 = 1\n abund = sum - 2 * n\n return if abund > 0 and abund mod 2 = 0\n .\n return ispartsum divs[] (sum / 2)\n.\n#\nprint \"The first 220 Zumkeller numbers are:\"\ni = 2\nrepeat\n if iszumkeller i = 1\n write i & \" \"\n count += 1\n .\n until count = 220\n i += 1\n.\nprint \"\\n\\nThe first 40 odd Zumkeller numbers are:\"\ncount = 0\ni = 3\nrepeat\n if iszumkeller i = 1\n write i & \" \"\n count += 1\n .\n until count = 40\n i += 2\n.\n", "language": "EasyLang" }, { "code": "// Zumkeller numbers: Nigel Galloway. May 16th., 2021\nlet rec fG n g=match g with h::_ when h>=n->h=n |h::t->fG n t || fG(n-h) t |_->false\nlet fN g=function n when n&&&1=1->false\n |n->let e=n/2-g in match compare e 0 with 0->true\n |1->let l=[1..e]|>List.filter(fun n->g%n=0)\n match compare(l|>List.sum) e with 1->fG e l |0->true |_->false\n |_->false\nSeq.initInfinite((+)1)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 220|>Seq.iter(fun(n,_)->printf \"%d \" n); printfn \"\\n\"\nSeq.initInfinite((*)2>>(+)1)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 40|>Seq.iter(fun(n,_)->printf \"%d \" n); printfn \"\\n\"\nSeq.initInfinite((*)2>>(+)1)|>Seq.filter(fun n->n%10<>5)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 40|>Seq.iter(fun(n,_)->printf \"%d \" n); printfn \"\\n\"\n", "language": "F-Sharp" }, { "code": "USING: combinators grouping io kernel lists lists.lazy math\nmath.primes.factors memoize prettyprint sequences ;\n\nMEMO: psum? ( seq n -- ? )\n {\n { [ dup zero? ] [ 2drop t ] }\n { [ over length zero? ] [ 2drop f ] }\n { [ over last over > ] [ [ but-last ] dip psum? ] }\n [\n [ [ but-last ] dip psum? ]\n [ over last - [ but-last ] dip psum? ] 2bi or\n ]\n } cond ;\n\n: zumkeller? ( n -- ? )\n dup divisors dup sum\n {\n { [ dup odd? ] [ 3drop f ] }\n { [ pick odd? ] [ nip swap 2 * - [ 0 > ] [ even? ] bi and ] }\n [ nipd 2/ psum? ]\n } cond ;\n\n: zumkellers ( -- list )\n 1 lfrom [ zumkeller? ] lfilter ;\n\n: odd-zumkellers ( -- list )\n 1 [ 2 + ] lfrom-by [ zumkeller? ] lfilter ;\n\n: odd-zumkellers-no-5 ( -- list )\n odd-zumkellers [ 5 mod zero? not ] lfilter ;\n\n: show ( count list row-len -- )\n [ ltake list>array ] dip group simple-table. nl ;\n\n\"First 220 Zumkeller numbers:\" print\n220 zumkellers 20 show\n\n\"First 40 odd Zumkeller numbers:\" print\n40 odd-zumkellers 10 show\n\n\"First 40 odd Zumkeller numbers not ending with 5:\" print\n40 odd-zumkellers-no-5 8 show\n", "language": "Factor" }, { "code": "package main\n\nimport \"fmt\"\n\nfunc getDivisors(n int) []int {\n divs := []int{1, n}\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n divs = append(divs, i)\n if i != j {\n divs = append(divs, j)\n }\n }\n }\n return divs\n}\n\nfunc sum(divs []int) int {\n sum := 0\n for _, div := range divs {\n sum += div\n }\n return sum\n}\n\nfunc isPartSum(divs []int, sum int) bool {\n if sum == 0 {\n return true\n }\n le := len(divs)\n if le == 0 {\n return false\n }\n last := divs[le-1]\n divs = divs[0 : le-1]\n if last > sum {\n return isPartSum(divs, sum)\n }\n return isPartSum(divs, sum) || isPartSum(divs, sum-last)\n}\n\nfunc isZumkeller(n int) bool {\n divs := getDivisors(n)\n sum := sum(divs)\n // if sum is odd can't be split into two partitions with equal sums\n if sum%2 == 1 {\n return false\n }\n // if n is odd use 'abundant odd number' optimization\n if n%2 == 1 {\n abundance := sum - 2*n\n return abundance > 0 && abundance%2 == 0\n }\n // if n and sum are both even check if there's a partition which totals sum / 2\n return isPartSum(divs, sum/2)\n}\n\nfunc main() {\n fmt.Println(\"The first 220 Zumkeller numbers are:\")\n for i, count := 2, 0; count < 220; i++ {\n if isZumkeller(i) {\n fmt.Printf(\"%3d \", i)\n count++\n if count%20 == 0 {\n fmt.Println()\n }\n }\n }\n fmt.Println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n for i, count := 3, 0; count < 40; i += 2 {\n if isZumkeller(i) {\n fmt.Printf(\"%5d \", i)\n count++\n if count%10 == 0 {\n fmt.Println()\n }\n }\n }\n fmt.Println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n for i, count := 3, 0; count < 40; i += 2 {\n if (i % 10 != 5) && isZumkeller(i) {\n fmt.Printf(\"%7d \", i)\n count++\n if count%8 == 0 {\n fmt.Println()\n }\n }\n }\n fmt.Println()\n}\n", "language": "Go" }, { "code": "import Data.List (group, sort)\nimport Data.List.Split (chunksOf)\nimport Data.Numbers.Primes (primeFactors)\n\n-------------------- ZUMKELLER NUMBERS -------------------\n\nisZumkeller :: Int -> Bool\nisZumkeller n =\n let ds = divisors n\n m = sum ds\n in ( even m\n && let half = div m 2\n in elem half ds\n || ( all (half >=) ds\n && summable half ds\n )\n )\n\nsummable :: Int -> [Int] -> Bool\nsummable _ [] = False\nsummable x xs@(h : t) =\n elem x xs\n || summable (x - h) t\n || summable x t\n\ndivisors :: Int -> [Int]\ndivisors x =\n sort\n ( foldr\n ( flip ((<*>) . fmap (*))\n . scanl (*) 1\n )\n [1]\n (group (primeFactors x))\n )\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n mapM_\n ( \\(s, n, xs) ->\n putStrLn $\n s\n <> ( '\\n' :\n tabulated\n 10\n (take n (filter isZumkeller xs))\n )\n )\n [ (\"First 220 Zumkeller numbers:\", 220, [1 ..]),\n (\"First 40 odd Zumkeller numbers:\", 40, [1, 3 ..])\n ]\n\n------------------------- DISPLAY ------------------------\ntabulated ::\n Show a =>\n Int ->\n [a] ->\n String\ntabulated nCols = go\n where\n go xs =\n let ts = show <$> xs\n w = succ (maximum (length <$> ts))\n in unlines\n ( concat\n <$> chunksOf\n nCols\n (justifyRight w ' ' <$> ts)\n )\n\njustifyRight :: Int -> Char -> String -> String\njustifyRight n c = (drop . length) <*> (replicate n c <>)\n", "language": "Haskell" }, { "code": "divisors=: {{ \\:~ */@>,{ (^ i.@>:)&.\">/ __ q: y }}\nzum=: {{\n if. 2|s=. +/divs=. divisors y do. 0\n elseif. 2|y do. (0<k) * 0=2|k=. s-2*y\n else. s=. -:s for_d. divs do. if. d<:s do. s=. s-d end. end. s=0\n end.\n}}@>\n", "language": "J" }, { "code": " 10 22$1+I.zum 1+i.1000 NB. first 220 Zumkeller numbers\n 6 12 20 24 28 30 40 42 48 54 56 60 66 70 78 80 84 88 90 96 102 104\n108 112 114 120 126 132 138 140 150 156 160 168 174 176 180 186 192 198 204 208 210 216\n220 222 224 228 234 240 246 252 258 260 264 270 272 276 280 282 294 300 304 306 308 312\n318 320 330 336 340 342 348 350 352 354 360 364 366 368 372 378 380 384 390 396 402 408\n414 416 420 426 432 438 440 444 448 456 460 462 464 468 474 476 480 486 490 492 496 498\n500 504 510 516 520 522 528 532 534 540 544 546 550 552 558 560 564 570 572 580 582 588\n594 600 606 608 612 616 618 620 624 630 636 640 642 644 650 654 660 666 672 678 680 684\n690 696 700 702 704 708 714 720 726 728 732 736 740 744 750 756 760 762 768 770 780 786\n792 798 804 810 812 816 820 822 828 832 834 836 840 852 858 860 864 868 870 876 880 888\n894 896 906 910 912 918 920 924 928 930 936 940 942 945 948 952 960 966 972 978 980 984\n 4 10$1+2*I.zum 1+2*i.1e4 NB. first 40 odd Zumkeller numbers\n 945 1575 2205 2835 3465 4095 4725 5355 5775 5985\n 6435 6615 6825 7245 7425 7875 8085 8415 8505 8925\n 9135 9555 9765 10395 11655 12285 12705 12915 13545 14175\n14805 15015 15435 16065 16695 17325 17955 18585 19215 19305\n 4 10$(#~ 0~:5|])1+2*I.zum 1+2*i.1e6 NB. first 40 odd Zumkeller numbers not divisible by 5\n 81081 153153 171171 189189 207207 223839 243243 261261 279279 297297\n 351351 459459 513513 567567 621621 671517 729729 742203 783783 793611\n 812889 837837 891891 908523 960687 999999 1024947 1054053 1072071 1073709\n1095633 1108107 1145529 1162161 1198197 1224531 1270269 1307691 1324323 1378377\n", "language": "J" }, { "code": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ZumkellerNumbers {\n\n public static void main(String[] args) {\n int n = 1;\n System.out.printf(\"First 220 Zumkeller numbers:%n\");\n for ( int count = 1 ; count <= 220 ; n += 1 ) {\n if ( isZumkeller(n) ) {\n System.out.printf(\"%3d \", n);\n if ( count % 20 == 0 ) {\n System.out.printf(\"%n\");\n }\n count++;\n }\n }\n\n n = 1;\n System.out.printf(\"%nFirst 40 odd Zumkeller numbers:%n\");\n for ( int count = 1 ; count <= 40 ; n += 2 ) {\n if ( isZumkeller(n) ) {\n System.out.printf(\"%6d\", n);\n if ( count % 10 == 0 ) {\n System.out.printf(\"%n\");\n }\n count++;\n }\n }\n\n n = 1;\n System.out.printf(\"%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n\");\n for ( int count = 1 ; count <= 40 ; n += 2 ) {\n if ( n % 5 != 0 && isZumkeller(n) ) {\n System.out.printf(\"%8d\", n);\n if ( count % 10 == 0 ) {\n System.out.printf(\"%n\");\n }\n count++;\n }\n }\n\n }\n\n private static boolean isZumkeller(int n) {\n // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers\n if ( n % 18 == 6 || n % 18 == 12 ) {\n return true;\n }\n\n List<Integer> divisors = getDivisors(n);\n int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();\n\n // divisor sum cannot be odd\n if ( divisorSum % 2 == 1 ) {\n return false;\n }\n\n // numbers where n is odd and the abundance is even are Zumkeller numbers\n int abundance = divisorSum - 2 * n;\n if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {\n return true;\n }\n\n Collections.sort(divisors);\n int j = divisors.size() - 1;\n int sum = divisorSum/2;\n\n // Largest divisor larger than sum - then cannot partition and not Zumkeller number\n if ( divisors.get(j) > sum ) {\n return false;\n }\n\n return canPartition(j, divisors, sum, new int[2]);\n }\n\n private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {\n if ( j < 0 ) {\n return true;\n }\n for ( int i = 0 ; i < 2 ; i++ ) {\n if ( buckets[i] + divisors.get(j) <= sum ) {\n buckets[i] += divisors.get(j);\n if ( canPartition(j-1, divisors, sum, buckets) ) {\n return true;\n }\n buckets[i] -= divisors.get(j);\n }\n if( buckets[i] == 0 ) {\n break;\n }\n }\n return false;\n }\n\n private static final List<Integer> getDivisors(int number) {\n List<Integer> divisors = new ArrayList<Integer>();\n long sqrt = (long) Math.sqrt(number);\n for ( int i = 1 ; i <= sqrt ; i++ ) {\n if ( number % i == 0 ) {\n divisors.add(i);\n int div = number / i;\n if ( div != i ) {\n divisors.add(div);\n }\n }\n }\n return divisors;\n }\n\n}\n", "language": "Java" }, { "code": "# The factors, sorted\ndef factors:\n . as $num\n | reduce range(1; 1 + sqrt|floor) as $i\n ([];\n if ($num % $i) == 0 then\n ($num / $i) as $r\n | if $i == $r then . + [$i] else . + [$i, $r] end\n else .\n end\n | sort) ;\n\n# If the input is a sorted array of distinct non-negative integers,\n# then the output will be a stream of [$x,$y] arrays,\n# where $x and $y are non-empty arrays that partition the\n# input, and where ($x|add) == $sum.\n# If [$x,$y] is emitted, then [$y,$x] will not also be emitted.\n# The items in $x appear in the same order as in the input, and similarly\n# for $y.\n#\ndef distinct_partitions($sum):\n # input: [$array, $n, $lim] where $n>0\n # output: a stream of arrays, $a, each with $n distinct items from $array,\n # preserving the order in $array, and such that\n # add == $lim\n def p:\n . as [$in, $n, $lim]\n | if $n==1 # this condition is very common so it saves time to check early on\n then ($in | bsearch($lim)) as $ix\n | if $ix < 0 then empty\n else [$lim]\n end\n else ($in|length) as $length\n | if $length <= $n then empty\n elif $length==$n then $in | select(add == $lim)\n elif ($in[-$n:]|add) < $lim then empty\n else ($in[:$n]|add) as $rsum\n | if $rsum > $lim then empty\n elif $rsum == $lim then \"amazing\" | debug | $in[:$n]\n else range(0; 1 + $length - $n) as $i\n | [$in[$i]] + ([$in[$i+1:], $n-1, $lim - $in[$i]]|p)\n end\n end\n end;\n\n range(1; (1+length)/2) as $i\n | ([., $i, $sum]|p) as $pi\n | [ $pi, (. - $pi)]\n | select( if (.[0]|length) == (.[1]|length) then (.[0] < .[1]) else true end) #1\n ;\n\ndef zumkellerPartitions:\n factors\n | add as $sum\n | if $sum % 2 == 1 then empty\n else distinct_partitions($sum / 2)\n end;\n\ndef is_zumkeller:\n first(factors\n | add as $sum\n | if $sum % 2 == 1 then empty\n else distinct_partitions($sum / 2)\n\t | select( (.[0]|add) == (.[1]|add)) // (\"internal error: \\(.)\" | debug | empty) #2\n\t end\n\t| true)\n // false;\n", "language": "Jq" }, { "code": "## The tasks:\n\n\"First 220:\", limit(220; range(2; infinite) | select(is_zumkeller)),\n\"\"\n\"First 40 odd:\", limit(40; range(3; infinite; 2) | select(is_zumkeller))\n", "language": "Jq" }, { "code": "using Primes\n\nfunction factorize(n)\n f = [one(n)]\n for (p, x) in factor(n)\n f = reduce(vcat, [f*p^i for i in 1:x], init=f)\n end\n f\nend\n\nfunction cansum(goal, list)\n if goal == 0 || list[1] == goal\n return true\n elseif length(list) > 1\n if list[1] > goal\n return cansum(goal, list[2:end])\n else\n return cansum(goal - list[1], list[2:end]) || cansum(goal, list[2:end])\n end\n end\n return false\nend\n\nfunction iszumkeller(n)\n f = reverse(factorize(n))\n fsum = sum(f)\n return iseven(fsum) && cansum(div(fsum, 2) - f[1], f[2:end])\nend\n\nfunction printconditionalnum(condition, maxcount, numperline = 20)\n count, spacing = 1, div(80, numperline)\n for i in 1:typemax(Int)\n if condition(i)\n count += 1\n print(rpad(i, spacing), (count - 1) % numperline == 0 ? \"\\n\" : \"\")\n if count > maxcount\n return\n end\n end\n end\nend\n\nprintln(\"First 220 Zumkeller numbers:\")\nprintconditionalnum(iszumkeller, 220)\nprintln(\"\\n\\nFirst 40 odd Zumkeller numbers:\")\nprintconditionalnum((n) -> isodd(n) && iszumkeller(n), 40, 8)\nprintln(\"\\n\\nFirst 40 odd Zumkeller numbers not ending with 5:\")\nprintconditionalnum((n) -> isodd(n) && (string(n)[end] != '5') && iszumkeller(n), 40, 8)\n", "language": "Julia" }, { "code": "import java.util.ArrayList\nimport kotlin.math.sqrt\n\nobject ZumkellerNumbers {\n @JvmStatic\n fun main(args: Array<String>) {\n var n = 1\n println(\"First 220 Zumkeller numbers:\")\n run {\n var count = 1\n while (count <= 220) {\n if (isZumkeller(n)) {\n print(\"%3d \".format(n))\n if (count % 20 == 0) {\n println()\n }\n count++\n }\n n += 1\n }\n }\n\n n = 1\n println(\"\\nFirst 40 odd Zumkeller numbers:\")\n run {\n var count = 1\n while (count <= 40) {\n if (isZumkeller(n)) {\n print(\"%6d\".format(n))\n if (count % 10 == 0) {\n println()\n }\n count++\n }\n n += 2\n }\n }\n\n n = 1\n println(\"\\nFirst 40 odd Zumkeller numbers that do not end in a 5:\")\n var count = 1\n while (count <= 40) {\n if (n % 5 != 0 && isZumkeller(n)) {\n print(\"%8d\".format(n))\n if (count % 10 == 0) {\n println()\n }\n count++\n }\n n += 2\n }\n }\n\n private fun isZumkeller(n: Int): Boolean { // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers\n if (n % 18 == 6 || n % 18 == 12) {\n return true\n }\n val divisors = getDivisors(n)\n val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum()\n // divisor sum cannot be odd\n if (divisorSum % 2 == 1) {\n return false\n }\n // numbers where n is odd and the abundance is even are Zumkeller numbers\n val abundance = divisorSum - 2 * n\n if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) {\n return true\n }\n divisors.sort()\n val j = divisors.size - 1\n val sum = divisorSum / 2\n // Largest divisor larger than sum - then cannot partition and not Zumkeller number\n return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2))\n }\n\n private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean {\n if (j < 0) {\n return true\n }\n for (i in 0..1) {\n if (buckets[i] + divisors[j] <= sum) {\n buckets[i] += divisors[j]\n if (canPartition(j - 1, divisors, sum, buckets)) {\n return true\n }\n buckets[i] -= divisors[j]\n }\n if (buckets[i] == 0) {\n break\n }\n }\n return false\n }\n\n private fun getDivisors(number: Int): MutableList<Int> {\n val divisors: MutableList<Int> = ArrayList()\n val sqrt = sqrt(number.toDouble()).toLong()\n for (i in 1..sqrt) {\n if (number % i == 0L) {\n divisors.add(i.toInt())\n val div = (number / i).toInt()\n if (div.toLong() != i) {\n divisors.add(div)\n }\n }\n }\n return divisors\n }\n}\n", "language": "Kotlin" }, { "code": "import std\n\n// Derived from Julia and Python versions\n\ndef get_divisors(n: int) -> [int]:\n var i = 2\n let d = [1, n]\n let limit = sqrt(n)\n while i <= limit:\n if n % i == 0:\n let j = n / i\n push(d,i)\n if i != j:\n push(d,j)\n i += 1\n return d\n\ndef isPartSum(divs: [int], sum: int) -> bool:\n if sum == 0:\n return true\n let len = length(divs)\n if len == 0:\n return false\n let last = pop(divs)\n if last > sum:\n return isPartSum(divs, sum)\n return isPartSum(copy(divs), sum) or isPartSum(divs, sum-last)\n\ndef isZumkeller(n: int) -> bool:\n let divs = get_divisors(n)\n let sum = fold(divs, 0): _a+_b\n if sum % 2 == 1:\n // if sum is odd can't be split into two partitions with equal sums\n return false\n if n % 2 == 1:\n // if n is odd use 'abundant odd number' optimization\n let abundance = sum - 2 * n\n return abundance > 0 and abundance % 2 == 0\n return isPartSum(divs, sum/2)\n\ndef printZumkellers(q: int, oddonly: bool):\n var nprinted = 0\n var res = \"\"\n for(100000) n:\n if (!oddonly or n % 2 != 0):\n if isZumkeller(n):\n let s = string(n)\n let z = length(s)\n res = concat_string([res, repeat_string(\" \",8-z), s], \"\")\n nprinted += 1\n if nprinted % 10 == 0 or nprinted >= q:\n print res\n res = \"\"\n if nprinted >= q:\n return\n\nprint \"220 Zumkeller numbers:\"\nprintZumkellers(220, false)\nprint \"\\n\\n40 odd Zumkeller numbers:\"\nprintZumkellers(40, true)\n", "language": "Lobster" }, { "code": "ClearAll[ZumkellerQ]\nZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x},\n ds = Total[d];\n If[Mod[ds, 2] == 1,\n False\n ,\n t = CoefficientList[Product[1 + x^i, {i, d}], x];\n t[[1 + ds/2]] > 0\n ]\n ];\ni = 1;\nres = {};\nWhile[Length[res] < 220,\n r = ZumkellerQ[i];\n If[r, AppendTo[res, i]];\n i++;\n ];\nres\n\ni = 1;\nres = {};\nWhile[Length[res] < 40,\n r = ZumkellerQ[i];\n If[r, AppendTo[res, i]];\n i += 2;\n ];\nres\n", "language": "Mathematica" }, { "code": "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 result = @[1, n]\n for i in 2..sqrt(n.toFloat).int:\n if n mod i == 0:\n let j = n div i\n result.add i\n if i != j: result.add j\n\n\nfunc isPartSum(divs: seq[int]; sum: int): bool =\n if sum == 0: return true\n if divs.len == 0: return false\n let last = divs[^1]\n let divs = divs[0..^2]\n result = isPartSum(divs, sum)\n if not result and last <= sum:\n result = isPartSum(divs, sum - last)\n\n\nfunc isZumkeller(n: int): bool =\n let divs = n.getDivisors()\n let sum = sum(divs)\n # If \"sum\" is odd, it can't be split into two partitions with equal sums.\n if sum.isOdd: return false\n # If \"n\" is odd use \"abundant odd number\" optimization.\n if n.isOdd:\n let abundance = sum - 2 * n\n return abundance > 0 and abundance.isEven\n # If \"n\" and \"sum\" are both even, check if there's a partition which totals \"sum / 2\".\n result = isPartSum(divs, sum div 2)\n\n\nwhen isMainModule:\n\n echo \"The first 220 Zumkeller numbers are:\"\n var n = 2\n var count = 0\n while count < 220:\n if n.isZumkeller:\n stdout.write align($n, 3)\n inc count\n stdout.write if count mod 20 == 0: '\\n' else: ' '\n inc n\n echo()\n\n echo \"The first 40 odd Zumkeller numbers are:\"\n n = 3\n count = 0\n while count < 40:\n if n.isZumkeller:\n stdout.write align($n, 5)\n inc count\n stdout.write if count mod 10 == 0: '\\n' else: ' '\n inc n, 2\n echo()\n\n echo \"The first 40 odd Zumkeller numbers which don't end in 5 are:\"\n n = 3\n count = 0\n while count < 40:\n if n mod 10 != 5 and n.isZumkeller:\n stdout.write align($n, 7)\n inc count\n stdout.write if count mod 8 == 0: '\\n' else: ' '\n inc n, 2\n", "language": "Nim" }, { "code": "\\\\ Define a function to check if a number is Zumkeller\nisZumkeller(n) = {\n my(d = divisors(n));\n my(ds = sum(i=1, #d, d[i])); \\\\ Total of divisors\n if (ds % 2, return(0)); \\\\ If sum of divisors is odd, return false\n my(coeffs = vector(ds+1, i, 0)); \\\\ Create a vector to store coefficients\n coeffs[1] = 1;\n for(i=1, #d, coeffs = Pol(coeffs) * (1 + x^d[i]); coeffs = Vecrev(coeffs); if(#coeffs > ds + 1, coeffs = coeffs[^1])); \\\\ Generate coefficients\n coeffs[ds \\ 2 + 1] > 0; \\\\ Check if the middle coefficient is positive\n}\n\n\\\\ Generate a list of Zumkeller numbers\nZumkellerList(limit) = {\n my(res = List(), i = 1);\n while(#res < limit,\n if(isZumkeller(i), listput(res, i));\n i++;\n );\n Vec(res); \\\\ Convert list to vector\n}\n\n\\\\ Generate a list of odd Zumkeller numbers\nOddZumkellerList(limit) = {\n my(res = List(), i = 1);\n while(#res < limit,\n if(isZumkeller(i), listput(res, i));\n i += 2; \\\\ Only check odd numbers\n );\n Vec(res); \\\\ Convert list to vector\n}\n\n\\\\ Call the functions to get the lists\nzumkeller220 = ZumkellerList(220);\noddZumkeller40 = OddZumkellerList(40);\n\n\\\\ Print the results\nprint(zumkeller220);\nprint(oddZumkeller40);\n", "language": "PARI-GP" }, { "code": "program zumkeller;\n//https://oeis.org/A083206/a083206.txt\n{$IFDEF FPC}\n {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON}\n// {$O+,I+}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\nuses\n sysutils\n{$IFDEF WINDOWS},Windows{$ENDIF}\n ;\n//######################################################################\n//prime decomposition\nconst\n//HCN(86) > 1.2E11 = 128,501,493,120 count of divs = 4096 7 3 1 1 1 1 1 1 1\n HCN_DivCnt = 4096;\n//stop never ending recursion\n RECCOUNTMAX = 100*1000*1000;\n DELTAMAX = 1000*1000;\ntype\n tItem = Uint64;\n tDivisors = array [0..HCN_DivCnt-1] of tItem;\n tpDivisor = pUint64;\nconst\n SizePrDeFe = 12697;//*72 <= 1 or 2 Mb ~ level 2 cache -32kB for DIVS\ntype\n tdigits = packed record\n dgtDgts : array [0..31] of Uint32;\n end;\n\n //the first number with 11 different divisors =\n // 2*3*5*7*11*13*17*19*23*29*31 = 2E11\n tprimeFac = packed record\n pfSumOfDivs,\n pfRemain : Uint64; //n div (p[0]^[pPot[0] *...) can handle primes <=821641^2 = 6.7e11\n pfpotPrim : array[0..9] of UInt32;//+10*4 = 56 Byte\n pfpotMax : array[0..9] of byte; //10 = 66\n pfMaxIdx : Uint16; //68\n pfDivCnt : Uint32; //72\n end;\n\n tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac;\n tPrimes = array[0..65535] of Uint32;\n\nvar\n SmallPrimes: tPrimes;\n//######################################################################\n//prime decomposition\nprocedure InitSmallPrimes;\n//only odd numbers\nconst\n MAXLIMIT = (821641-1) shr 1;\nvar\n pr : array[0..MAXLIMIT] of byte;\n p,j,d,flipflop :NativeUInt;\nBegin\n SmallPrimes[0] := 2;\n fillchar(pr[0],SizeOf(pr),#0);\n p := 0;\n repeat\n repeat\n p +=1\n until pr[p]= 0;\n j := (p+1)*p*2;\n if j>MAXLIMIT then\n BREAK;\n d := 2*p+1;\n repeat\n pr[j] := 1;\n j += d;\n until j>MAXLIMIT;\n until false;\n\n SmallPrimes[1] := 3;\n SmallPrimes[2] := 5;\n j := 3;\n d := 7;\n flipflop := 3-1;\n p := 3;\n repeat\n if pr[p] = 0 then\n begin\n SmallPrimes[j] := d;\n inc(j);\n end;\n d += 2*flipflop;\n p+=flipflop;\n flipflop := 3-flipflop;\n until (p > MAXLIMIT) OR (j>High(SmallPrimes));\nend;\n\nfunction OutPots(const pD:tprimeFac;n:NativeInt):Ansistring;\nvar\n s: String[31];\nBegin\n str(n,s);\n result := s+' :';\n with pd do\n begin\n str(pfDivCnt:3,s);\n result += s+' : ';\n For n := 0 to pfMaxIdx-1 do\n Begin\n if n>0 then\n result += '*';\n str(pFpotPrim[n],s);\n result += s;\n if pfpotMax[n] >1 then\n Begin\n str(pfpotMax[n],s);\n result += '^'+s;\n end;\n end;\n If pfRemain >1 then\n Begin\n str(pfRemain,s);\n result += '*'+s;\n end;\n str(pfSumOfDivs,s);\n result += '_SoD_'+s+'<';\n end;\nend;\n\nfunction CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt;\n//n must be multiple of base\nvar\n q,r: Uint64;\n i : NativeInt;\nBegin\n with dgt do\n Begin\n fillchar(dgtDgts,SizeOf(dgtDgts),#0);\n i := 0;\n// dgtNum:= n;\n n := n div base;\n result := 0;\n repeat\n r := n;\n q := n div base;\n r -= q*base;\n n := q;\n dgtDgts[i] := r;\n inc(i);\n until (q = 0);\n\n result := 0;\n while (result<i) AND (dgtDgts[result] = 0) do\n inc(result);\n inc(result);\n end;\nend;\n\nfunction IncByBaseInBase(var dgt:tDigits;base:NativeInt):NativeInt;\nvar\n q :NativeInt;\nBegin\n with dgt do\n Begin\n result := 0;\n q := dgtDgts[result]+1;\n// inc(dgtNum,base);\n if q = base then\n begin\n repeat\n dgtDgts[result] := 0;\n inc(result);\n q := dgtDgts[result]+1;\n until q <> base;\n end;\n dgtDgts[result] := q;\n result +=1;\n end;\nend;\n\nprocedure SieveOneSieve(var pdf:tPrimeDecompField;n:nativeUInt);\nvar\n dgt:tDigits;\n i, j, k,pr,fac : NativeUInt;\nbegin\n //init\n for i := 0 to High(pdf) do\n with pdf[i] do\n Begin\n pfDivCnt := 1;\n pfSumOfDivs := 1;\n pfRemain := n+i;\n pfMaxIdx := 0;\n end;\n\n //first 2 make n+i even\n i := n AND 1;\n repeat\n with pdf[i] do\n if n+i > 0 then\n begin\n j := BsfQWord(n+i);\n pfMaxIdx := 1;\n pfpotPrim[0] := 2;\n pfpotMax[0] := j;\n pfRemain := (n+i) shr j;\n pfSumOfDivs := (1 shl (j+1))-1;\n pfDivCnt := j+1;\n end;\n i += 2;\n until i >High(pdf);\n\n // i now index in SmallPrimes\n i := 0;\n repeat\n //search next prime that is in bounds of sieve\n repeat\n inc(i);\n if i >= High(SmallPrimes) then\n BREAK;\n pr := SmallPrimes[i];\n k := pr-n MOD pr;\n if (k = pr) AND (n>0) then\n k:= 0;\n if k < SizePrDeFe then\n break;\n until false;\n if i >= High(SmallPrimes) then\n BREAK;\n //no need to use higher primes\n if pr*pr > n+SizePrDeFe then\n BREAK;\n\n // j is power of prime\n j := CnvtoBASE(dgt,n+k,pr);\n repeat\n with pdf[k] do\n Begin\n pfpotPrim[pfMaxIdx] := pr;\n pfpotMax[pfMaxIdx] := j;\n pfDivCnt *= j+1;\n fac := pr;\n repeat\n pfRemain := pfRemain DIV pr;\n dec(j);\n fac *= pr;\n until j<= 0;\n pfSumOfDivs *= (fac-1)DIV(pr-1);\n inc(pfMaxIdx);\n end;\n k += pr;\n j := IncByBaseInBase(dgt,pr);\n until k >= SizePrDeFe;\n until false;\n\n //correct sum of & count of divisors\n for i := 0 to High(pdf) do\n Begin\n with pdf[i] do\n begin\n j := pfRemain;\n if j <> 1 then\n begin\n pfSumOFDivs *= (j+1);\n pfDivCnt *=2;\n end;\n end;\n end;\nend;\n//prime decomposition\n//######################################################################\nprocedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);forward;\n\nvar\n{$ALIGN 32}\n PrimeDecompField:tPrimeDecompField;\n{$ALIGN 32}\n Divs :tDivisors;\n SumOfDivs : tDivisors;\n DivUsedIdx : tDivisors;\n\n pDiv :tpDivisor;\n T0: Int64;\n count,rec_Cnt: NativeInt;\n depth : Int32;\n finished :Boolean;\n\nprocedure Check_rek_depth(SoD : Int64;i: NativeInt);\nvar\n sum : Int64;\nbegin\n if finished then\n EXIT;\n inc(rec_Cnt);\n\n WHILE (i>0) AND (pDiv[i]>SoD) do\n dec(i);\n\n while i >= 0 do\n Begin\n DivUsedIdx[depth] := pDiv[i];\n sum := SoD-pDiv[i];\n if sum = 0 then\n begin\n finished := true;\n EXIT;\n end;\n dec(i);\n inc(depth);\n if (i>= 0) AND (sum <= SumOfDivs[i]) then\n Check_rek_depth(sum,i);\n if finished then\n EXIT;\n// DivUsedIdx[depth] := 0;\n dec(depth);\n end;\nend;\n\nprocedure Out_One_Sol(const pd:tprimefac;n:NativeUInt;isZK : Boolean);\nvar\n sum : NativeInt;\nBegin\n if n< 7 then\n exit;\n with pd do\n begin\n writeln(OutPots(pD,n));\n if isZK then\n Begin\n Init_Check_rec(pD,Divs,SumOfDivs);\n Check_rek_depth(pfSumOfDivs shr 1-n,pFDivCnt-1);\n write(pfSumOfDivs shr 1:10,' = ');\n sum := n;\n while depth >= 0 do\n Begin\n sum += DivUsedIdx[depth];\n write(DivUsedIdx[depth],'+');\n dec(depth);\n end;\n write(n,' = ',sum);\n end\n else\n write(' no zumkeller ');\n end;\nend;\n\nprocedure InsertSort(pDiv:tpDivisor; Left, Right : NativeInt );\nvar\n I, J: NativeInt;\n Pivot : tItem;\nbegin\n for i:= 1 + Left to Right do\n begin\n Pivot:= pDiv[i];\n j:= i - 1;\n while (j >= Left) and (pDiv[j] > Pivot) do\n begin\n pDiv[j+1]:=pDiv[j];\n Dec(j);\n end;\n pDiv[j+1]:= pivot;\n end;\nend;\n\nprocedure GetDivs(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);\nvar\n pDivs : tpDivisor;\n pPot : UInt64;\n i,len,j,l,p,k: Int32;\nBegin\n i := pD.pfDivCnt;\n pDivs := @Divs[0];\n pDivs[0] := 1;\n len := 1;\n l := 1;\n with pD do\n Begin\n For i := 0 to pfMaxIdx-1 do\n begin\n //Multiply every divisor before with the new primefactors\n //and append them to the list\n k := pfpotMax[i];\n p := pfpotPrim[i];\n pPot :=1;\n repeat\n pPot *= p;\n For j := 0 to len-1 do\n Begin\n pDivs[l]:= pPot*pDivs[j];\n inc(l);\n end;\n dec(k);\n until k<=0;\n len := l;\n end;\n p := pfRemain;\n If p >1 then\n begin\n For j := 0 to len-1 do\n Begin\n pDivs[l]:= p*pDivs[j];\n inc(l);\n end;\n len := l;\n end;\n end;\n //Sort. Insertsort much faster than QuickSort in this special case\n InsertSort(pDivs,0,len-1);\n\n pPot := 0;\n For i := 0 to len-1 do\n begin\n pPot += pDivs[i];\n SumOfDivs[i] := pPot;\n end;\nend;\n\nprocedure Init_Check_rec(const pD:tprimeFac;var Divs,SumOfDivs:tDivisors);\nbegin\n GetDivs(pD,Divs,SUmOfDivs);\n finished := false;\n depth := 0;\n pDiv := @Divs[0];\nend;\n\nprocedure Check_rek(SoD : Int64;i: NativeInt);\nvar\n sum : Int64;\nbegin\n if finished then\n EXIT;\n if rec_Cnt >RECCOUNTMAX then\n begin\n rec_Cnt := -1;\n finished := true;\n exit;\n end;\n inc(rec_Cnt);\n\n WHILE (i>0) AND (pDiv[i]>SoD) do\n dec(i);\n\n while i >= 0 do\n Begin\n sum := SoD-pDiv[i];\n if sum = 0 then\n begin\n finished := true;\n EXIT;\n end;\n dec(i);\n if (i>= 0) AND (sum <= SumOfDivs[i]) then\n Check_rek(sum,i);\n if finished then\n EXIT;\n end;\nend;\n\nfunction GetZumKeller(n: NativeUint;var pD:tPrimefac): boolean;\nvar\n SoD,sum : Int64;\n Div_cnt,i,pracLmt: NativeInt;\nbegin\n rec_Cnt := 0;\n SoD:= pd.pfSumOfDivs;\n //sum must be even and n not deficient\n if Odd(SoD) or (SoD<2*n) THEN\n EXIT(false);\n//if Odd(n) then Exit(Not(odd(sum)));// to be tested\n\n SoD := SoD shr 1-n;\n If SoD < 2 then //0,1 is always true\n Exit(true);\n\n Div_cnt := pD.pfDivCnt;\n\n if Not(odd(n)) then\n if ((n mod 18) in [6,12]) then\n EXIT(true);\n\n //Now one needs to get the divisors\n Init_check_rec(pD,Divs,SumOfDivs);\n\n pracLmt:= 0;\n if Not(odd(n)) then\n begin\n For i := 1 to Div_Cnt do\n Begin\n sum := SumOfDivs[i];\n If (sum+1<Divs[i+1]) AND (sum<SoD) then\n Begin\n pracLmt := i;\n BREAK;\n end;\n IF (sum>=SoD) then break;\n end;\n if pracLmt = 0 then\n Exit(true);\n end;\n //number is practical followed by one big prime\n if pracLmt = (Div_Cnt-1) shr 1 then\n begin\n i := SoD mod Divs[pracLmt+1];\n with pD do\n begin\n if pfRemain > 1 then\n EXIT((pfRemain<=i) OR (i<=sum))\n else\n EXIT((pfpotPrim[pfMaxIdx-1]<=i)OR (i<=sum));\n end;\n end;\n\n Begin\n IF Div_cnt <= HCN_DivCnt then\n Begin\n Check_rek(SoD,Div_cnt-1);\n IF rec_Cnt = -1 then\n exit(true);\n exit(finished);\n end;\n end;\n result := false;\nend;\n\nvar\n Ofs,i,n : NativeUInt;\n Max: NativeUInt;\n\nprocedure Init_Sieve(n:NativeUint);\n//Init Sieve i,oFs are Global\nbegin\n i := n MOD SizePrDeFe;\n Ofs := (n DIV SizePrDeFe)*SizePrDeFe;\n SieveOneSieve(PrimeDecompField,Ofs);\nend;\n\nprocedure GetSmall(MaxIdx:Int32);\nvar\n ZK: Array of Uint32;\n idx: UInt32;\nBegin\n If MaxIdx<1 then\n EXIT;\n writeln('The first ',MaxIdx,' zumkeller numbers');\n Init_Sieve(0);\n setlength(ZK,MaxIdx);\n idx := Low(ZK);\n repeat\n if GetZumKeller(n,PrimeDecompField[i]) then\n Begin\n ZK[idx] := n;\n inc(idx);\n end;\n inc(i);\n inc(n);\n If i > High(PrimeDecompField) then\n begin\n dec(i,SizePrDeFe);\n inc(ofs,SizePrDeFe);\n SieveOneSieve(PrimeDecompField,Ofs);\n end;\n until idx >= MaxIdx;\n For idx := 0 to MaxIdx-1 do\n begin\n if idx MOD 20 = 0 then\n writeln;\n write(ZK[idx]:4);\n end;\n setlength(ZK,0);\n writeln;\n writeln;\nend;\n\nprocedure GetOdd(MaxIdx:Int32);\nvar\n ZK: Array of Uint32;\n idx: UInt32;\nBegin\n If MaxIdx<1 then\n EXIT;\n writeln('The first odd 40 zumkeller numbers');\n n := 1;\n Init_Sieve(n);\n setlength(ZK,MaxIdx);\n idx := Low(ZK);\n repeat\n if GetZumKeller(n,PrimeDecompField[i]) then\n Begin\n ZK[idx] := n;\n inc(idx);\n end;\n inc(i,2);\n inc(n,2);\n If i > High(PrimeDecompField) then\n begin\n dec(i,SizePrDeFe);\n inc(ofs,SizePrDeFe);\n SieveOneSieve(PrimeDecompField,Ofs);\n end;\n until idx >= MaxIdx;\n For idx := 0 to MaxIdx-1 do\n begin\n if idx MOD (80 DIV 8) = 0 then\n writeln;\n write(ZK[idx]:8);\n end;\n setlength(ZK,0);\n writeln;\n writeln;\nend;\n\nprocedure GetOddNot5(MaxIdx:Int32);\nvar\n ZK: Array of Uint32;\n idx: UInt32;\nBegin\n If MaxIdx<1 then\n EXIT;\n writeln('The first odd 40 zumkeller numbers not ending in 5');\n n := 1;\n Init_Sieve(n);\n setlength(ZK,MaxIdx);\n idx := Low(ZK);\n repeat\n if GetZumKeller(n,PrimeDecompField[i]) then\n Begin\n ZK[idx] := n;\n inc(idx);\n end;\n inc(i,2);\n inc(n,2);\n If n mod 5 = 0 then\n begin\n inc(i,2);\n inc(n,2);\n end;\n If i > High(PrimeDecompField) then\n begin\n dec(i,SizePrDeFe);\n inc(ofs,SizePrDeFe);\n SieveOneSieve(PrimeDecompField,Ofs);\n end;\n until idx >= MaxIdx;\n For idx := 0 to MaxIdx-1 do\n begin\n if idx MOD (80 DIV 8) = 0 then\n writeln;\n write(ZK[idx]:8);\n end;\n setlength(ZK,0);\n writeln;\n writeln;\nend;\nBEGIN\n InitSmallPrimes;\n\n T0 := GetTickCount64;\n GetSmall(220);\n GetOdd(40);\n GetOddNot5(40);\n\n writeln;\n n := 1;//8996229720;//1;\n Init_Sieve(n);\n writeln('Start ',n,' at ',i);\n T0 := GetTickCount64;\n MAX := (n DIV DELTAMAX+1)*DELTAMAX;\n count := 0;\n repeat\n writeln('Count of zumkeller numbers up to ',MAX:12);\n repeat\n if GetZumKeller(n,PrimeDecompField[i]) then\n inc(count);\n inc(i);\n inc(n);\n If i > High(PrimeDecompField) then\n begin\n dec(i,SizePrDeFe);\n inc(ofs,SizePrDeFe);\n SieveOneSieve(PrimeDecompField,Ofs);\n end;\n until n > MAX;\n writeln(n-1:10,' tested found ',count:10,' ratio ',count/n:10:7);\n MAX += DELTAMAX;\n until MAX>10*DELTAMAX;\n writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s');\n writeln;\n writeln('Count of recursion 59,641,327 for 8,996,229,720');\n n := 8996229720;\n Init_Sieve(n);\n T0 := GetTickCount64;\n Out_One_Sol(PrimeDecompField[i],n,true);\n writeln;\n writeln('runtime ',(GetTickCount64-T0)/1000:8:3,' s');\nEND.\n", "language": "Pascal" }, { "code": "use strict;\nuse warnings;\nuse feature 'say';\nuse ntheory <is_prime divisor_sum divisors vecsum forcomb lastfor>;\n\nsub in_columns {\n my($columns, $values) = @_;\n my @v = split ' ', $values;\n my $width = int(80/$columns);\n printf \"%${width}d\"x$columns.\"\\n\", @v[$_*$columns .. -1+(1+$_)*$columns] for 0..-1+@v/$columns;\n print \"\\n\";\n}\n\nsub is_Zumkeller {\n my($n) = @_;\n return 0 if is_prime($n);\n my @divisors = divisors($n);\n return 0 unless @divisors > 2 && 0 == @divisors % 2;\n my $sigma = divisor_sum($n);\n return 0 unless 0 == $sigma%2 && ($sigma/2) >= $n;\n if (1 == $n%2) {\n return 1\n } else {\n my $Z = 0;\n forcomb { $Z++, lastfor if vecsum(@divisors[@_]) == $sigma/2 } @divisors;\n return $Z;\n }\n}\n\nuse constant Inf => 1e10;\n\nsay 'First 220 Zumkeller numbers:';\nmy $n = 0; my $z;\n$z .= do { $n < 220 ? (is_Zumkeller($_) and ++$n and \"$_ \") : last } for 1 .. Inf;\nin_columns(20, $z);\n\nsay 'First 40 odd Zumkeller numbers:';\n$n = 0; $z = '';\n$z .= do { $n < 40 ? (!!($_%2) and is_Zumkeller($_) and ++$n and \"$_ \") : last } for 1 .. Inf;\nin_columns(10, $z);\n\nsay 'First 40 odd Zumkeller numbers not divisible by 5:';\n$n = 0; $z = '';\n$z .= do { $n < 40 ? (!!($_%2 and $_%5) and is_Zumkeller($_) and ++$n and \"$_ \") : last } for 1 .. Inf;\nin_columns(10, $z);\n", "language": "Perl" }, { "code": "with javascript_semantics\nfunction isPartSum(sequence f, integer l, t)\n if t=0 then return true end if\n if l=0 then return false end if\n integer last = f[l]\n return (t>=last and isPartSum(f, l-1, t-last))\n or isPartSum(f, l-1, t)\nend function\n\nfunction isZumkeller(integer n)\n sequence f = factors(n,1)\n integer t = sum(f)\n -- an odd sum cannot be split into two equal sums\n if odd(t) then return false end if\n -- if n is odd use 'abundant odd number' optimization\n if odd(n) then\n integer abundance := t - 2*n\n return abundance>0 and even(abundance)\n end if\n -- if n and t both even check for any partition of t/2\n return isPartSum(f, length(f), t/2)\nend function\n\nsequence tests = {{220,1,0,20,\"%3d %n\"},\n {40,2,0,10,\"%5d %n\"},\n {40,2,5,8,\"%7d %n\"}}\ninteger lim, step, rem, cr; string fmt\nfor t=1 to length(tests) do\n {lim, step, rem, cr, fmt} = tests[t]\n string o = iff(step=1?\"\":\"odd \"),\n w = iff(rem=0?\"\":\"which don't end in 5 \")\n printf(1,\"The first %d %sZumkeller numbers %sare:\\n\",{lim,o,w})\n integer i = step+1, count = 0\n while count<lim do\n if (rem=0 or remainder(i,10)!=rem)\n and isZumkeller(i) then\n count += 1\n printf(1,fmt,{i,remainder(count,cr)=0})\n end if\n i += step\n end while\n printf(1,\"\\n\")\nend for\n", "language": "Phix" }, { "code": "(de propdiv (N)\n (make\n (for I N\n (and (=0 (% N I)) (link I)) ) ) )\n(de sum? (G L)\n (cond\n ((=0 G) T)\n ((= (car L) G) T)\n ((cdr L)\n (if (> (car L) G)\n (sum? G (cdr L))\n (or\n (sum? (- G (car L)) (cdr L))\n (sum? G (cdr L)) ) ) ) ) )\n(de zum? (N)\n (let (L (propdiv N) S (sum prog L))\n (and\n (not (bit? 1 S))\n (if (bit? 1 N)\n (let A (- S (* 2 N))\n (and (gt0 A) (not (bit? 1 A)))\n )\n (sum?\n (- (/ S 2) (car L))\n (cdr L) ) ) ) ) )\n(zero C)\n(for (I 2 (> 220 C) (inc I))\n (when (zum? I)\n (prin (align 3 I) \" \")\n (inc 'C)\n (and\n (=0 (% C 20))\n (prinl) ) ) )\n(prinl)\n(zero C)\n(for (I 1 (> 40 C) (inc 'I 2))\n (when (zum? I)\n (prin (align 9 I) \" \")\n (inc 'C)\n (and\n (=0 (% C 8))\n (prinl) ) ) )\n(prinl)\n(zero C)\n# cheater\n(for (I 81079 (> 40 C) (inc 'I 2))\n (when (and (<> 5 (% I 10)) (zum? I))\n (prin (align 9 I) \" \")\n (inc 'C)\n (and\n (=0 (% C 8))\n (prinl) ) ) )\n", "language": "PicoLisp" }, { "code": "from sympy import divisors\n\nfrom sympy.combinatorics.subsets import Subset\n\ndef isZumkeller(n):\n d = divisors(n)\n s = sum(d)\n if not s % 2 and max(d) <= s/2:\n for x in range(1, 2**len(d)):\n if sum(Subset.unrank_binary(x, d).subset) == s/2:\n return True\n\n return False\n\n\n\ndef printZumkellers(N, oddonly=False):\n nprinted = 0\n for n in range(1, 10**5):\n if (oddonly == False or n % 2) and isZumkeller(n):\n print(f'{n:>8}', end='')\n nprinted += 1\n if nprinted % 10 == 0:\n print()\n if nprinted >= N:\n return\n\n\nprint(\"220 Zumkeller numbers:\")\nprintZumkellers(220)\nprint(\"\\n\\n40 odd Zumkeller numbers:\")\nprintZumkellers(40, True)\n", "language": "Python" }, { "code": "'''Zumkeller numbers'''\n\nfrom itertools import (\n accumulate, chain, count, groupby, islice, product\n)\nfrom functools import reduce\nfrom math import floor, sqrt\nimport operator\n\n\n# ---------------------- ZUMKELLER -----------------------\n\n# isZumkeller :: Int -> Bool\ndef isZumkeller(n):\n '''True if there exists a disjoint partition\n of the divisors of m, such that the two sets have\n the same sum.\n (In other words, if n is in OEIS A083207)\n '''\n ds = divisors(n)\n m = sum(ds)\n if even(m):\n half = m // 2\n return half in ds or (\n all(map(ge(half), ds)) and (\n summable(half, ds)\n )\n )\n else:\n return False\n\n\n# summable :: Int -> [Int] -> Bool\ndef summable(x, xs):\n '''True if any subset of the sorted\n list xs sums to x.\n '''\n if xs:\n if x in xs:\n return True\n else:\n t = xs[1:]\n return summable(x - xs[0], t) or summable(x, t)\n else:\n return False\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''First 220 Zumkeller numbers,\n and first 40 odd Zumkellers.\n '''\n\n tenColumns = tabulated(10)\n\n print('First 220 Zumkeller numbers:\\n')\n print(tenColumns(\n take(220)(\n filter(isZumkeller, count(1))\n )\n ))\n print('\\nFirst 40 odd Zumkeller numbers:\\n')\n print(tenColumns(\n take(40)(\n filter(isZumkeller, enumFromThen(1)(3))\n )\n ))\n\n\n# ---------------------- TABULATION ----------------------\n\n# tabulated :: Int -> [a] -> String\ndef tabulated(nCols):\n '''String representation of a list\n of values as rows of n columns.\n '''\n def go(xs):\n ts = [str(x) for x in xs]\n w = 1 + max(len(x) for x in ts)\n return '\\n'.join([\n ''.join(row) for row\n in chunksOf(nCols)([\n t.rjust(w, ' ') for t in ts\n ])\n ])\n return go\n\n\n# ----------------------- GENERIC ------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than n.\n '''\n def go(xs):\n return (\n xs[i:n + i] for i in range(0, len(xs), n)\n ) if 0 < n else None\n return go\n\n\n# divisors :: Int -> [Int]\ndef divisors(n):\n '''The ordered divisors of n.\n '''\n def go(a, x):\n return [a * b for a, b in product(\n a,\n accumulate(chain([1], x), operator.mul)\n )]\n return sorted(\n reduce(go, [\n list(g) for _, g in groupby(primeFactors(n))\n ], [1])\n ) if 1 < n else [1]\n\n\n# enumFromThen :: Int -> Int -> [Int]\ndef enumFromThen(m):\n '''A non-finite stream of integers\n starting at m, and continuing\n at the interval between m and n.\n '''\n return lambda n: count(m, n - m)\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.\n '''\n return 0 == x % 2\n\n\n# ge :: Eq a => a -> a -> Bool\ndef ge(a):\n def go(b):\n return operator.ge(a, b)\n return go\n\n\n# primeFactors :: Int -> [Int]\ndef primeFactors(n):\n '''A list of the prime factors of n.\n '''\n def f(qr):\n r = qr[1]\n return step(r), 1 + r\n\n def step(x):\n return 1 + (x << 2) - ((x >> 1) << 1)\n\n def go(x):\n root = floor(sqrt(x))\n\n def p(qr):\n q = qr[0]\n return root < q or 0 == (x % q)\n\n q = until(p)(f)(\n (2 if 0 == x % 2 else 3, 1)\n )[0]\n return [x] if q > root else [q] + go(x // q)\n\n return go(n)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\n '''\n def go(f):\n def g(x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()\n", "language": "Python" }, { "code": "#lang racket\n\n(require math/number-theory)\n\n(define (zum? n)\n (let* ((set (divisors n))\n (sum (apply + set)))\n (cond\n [(odd? sum) #f]\n [(odd? n) ; if n is odd use 'abundant odd number' optimization\n (let ((abundance (- sum (* n 2)))) (and (positive? abundance) (even? abundance)))]\n [else\n (let ((sum/2 (quotient sum 2)))\n (let loop ((acc (car set)) (set (cdr set)))\n (cond [(= acc sum/2) #t]\n [(> acc sum/2) #f]\n [(null? set) #f]\n [else (or (loop (+ (car set) acc) (cdr set))\n (loop acc (cdr set)))])))])))\n\n(define (first-n-matching-naturals count pred)\n (for/list ((i count) (j (stream-filter pred (in-naturals 1)))) j))\n\n(define (tabulate title ns (row-width 132))\n (displayln title)\n (let* ((cell-width (+ 2 (order-of-magnitude (apply max ns))))\n (cells/row (quotient row-width cell-width)))\n (let loop ((ns ns) (col cells/row))\n (cond [(null? ns) (unless (= col cells/row) (newline))]\n [(zero? col) (newline) (loop ns cells/row)]\n [else (display (~a #:width cell-width #:align 'right (car ns)))\n (loop (cdr ns) (sub1 col))]))))\n\n\n(tabulate \"First 220 Zumkeller numbers:\" (first-n-matching-naturals 220 zum?))\n(newline)\n(tabulate \"First 40 odd Zumkeller numbers:\"\n (first-n-matching-naturals 40 (λ (n) (and (odd? n) (zum? n)))))\n(newline)\n(tabulate \"First 40 odd Zumkeller numbers not ending in 5:\"\n (first-n-matching-naturals 40 (λ (n) (and (odd? n) (not (= 5 (modulo n 10))) (zum? n)))))\n", "language": "Racket" }, { "code": "use ntheory:from<Perl5> <factor is_prime>;\n\nsub zumkeller ($range) {\n $range.grep: -> $maybe {\n next if $maybe < 3 or $maybe.&is_prime;\n my @divisors = $maybe.&factor.combinations».reduce( &[×] ).unique.reverse;\n next unless [and] @divisors > 2, @divisors %% 2, (my $sum = @divisors.sum) %% 2, ($sum /= 2) ≥ $maybe;\n my $zumkeller = False;\n if $maybe % 2 {\n $zumkeller = True\n } else {\n TEST: for 1 ..^ @divisors/2 -> $c {\n @divisors.combinations($c).map: -> $d {\n next if $d.sum != $sum;\n $zumkeller = True and last TEST\n }\n }\n }\n $zumkeller\n }\n}\n\nsay \"First 220 Zumkeller numbers:\\n\" ~\n zumkeller(^Inf)[^220].rotor(20)».fmt('%3d').join: \"\\n\";\n\nput \"\\nFirst 40 odd Zumkeller numbers:\\n\" ~\n zumkeller((^Inf).map: * × 2 + 1)[^40].rotor(10)».fmt('%7d').join: \"\\n\";\n\n# Stretch. Slow to calculate. (minutes)\nput \"\\nFirst 40 odd Zumkeller numbers not divisible by 5:\\n\" ~\n zumkeller(flat (^Inf).map: {my \\p = 10 * $_; p+1, p+3, p+7, p+9} )[^40].rotor(10)».fmt('%7d').join: \"\\n\";\n", "language": "Raku" }, { "code": "/*REXX pgm finds & shows Zumkeller numbers: 1st N; 1st odd M; 1st odd V not ending in 5.*/\nparse arg n m v . /*obtain optional arguments from the CL*/\nif n=='' | n==\",\" then n= 220 /*Not specified? Then use the default.*/\nif m=='' | m==\",\" then m= 40 /* \" \" \" \" \" \" */\nif v=='' | v==\",\" then v= 40 /* \" \" \" \" \" \" */\n@zum= ' Zumkeller numbers are: ' /*literal used for displaying messages.*/\nsw= linesize() - 1 /*obtain the usable screen width. */\nsay\nif n>0 then say center(' The first ' n @zum, sw, \"═\")\n#= 0 /*the count of Zumkeller numbers so far*/\n$= /*initialize the $ list (to a null).*/\n do j=1 until #==n /*traipse through integers 'til done. */\n if \\Zum(j) then iterate /*if not a Zumkeller number, then skip.*/\n #= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/\n end /*j*/\n\nif $\\=='' then say $ /*Are there any residuals? Then display*/\nsay\nif m>0 then say center(' The first odd ' m @zum, sw, \"═\")\n#= 0 /*the count of Zumkeller numbers so far*/\n$= /*initialize the $ list (to a null).*/\n do j=1 by 2 until #==m /*traipse through integers 'til done. */\n if \\Zum(j) then iterate /*if not a Zumkeller number, then skip.*/\n #= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/\n end /*j*/\n\nif $\\=='' then say $ /*Are there any residuals? Then display*/\nsay\nif v>0 then say center(' The first odd ' v \" (not ending in 5) \" @zum, sw, '═')\n#= 0 /*the count of Zumkeller numbers so far*/\n$= /*initialize the $ list (to a null).*/\n do j=1 by 2 until #==v /*traipse through integers 'til done. */\n if right(j,1)==5 then iterate /*skip if odd number ends in digit \"5\".*/\n if \\Zum(j) then iterate /*if not a Zumkeller number, then skip.*/\n #= # + 1; call add$ /*bump Zumkeller count; add to $ list.*/\n end /*j*/\n\nif $\\=='' then say $ /*Are there any residuals? Then display*/\nexit /*stick a fork in it, we're all done. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nadd$: _= strip($ j, 'L'); if length(_)<sw then do; $= _; return; end /*add to $*/\n say strip($, 'L'); $= j; return /*say, add*/\n/*──────────────────────────────────────────────────────────────────────────────────────*/\niSqrt: procedure; parse arg x; r= 0; q= 1; do while q<=x; q=q*4; end\n do while q>1; q= q%4; _= x-r-q; r= r%2; if _>=0 then do; x= _; r= r+q; end; end\n return r /*R is the integer square root of X. */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nPDaS: procedure; parse arg x 1 b; odd= x//2 /*obtain X and B (the 1st argument).*/\n if x==1 then return 1 1 /*handle special case for unity. */\n r= iSqrt(x) /*calculate integer square root of X. */\n a= 1 /* [↓] use all, or only odd numbers. */\n sig= a + b /*initialize the sigma (so far) ___ */\n do j=2+odd by 1+odd to r - (r*r==x) /*divide by some integers up to √ X */\n if x//j==0 then do; a=a j; b= x%j b /*if ÷, add both divisors to α & ß. */\n sig= sig +j +x%j /*bump the sigma (the sum of divisors).*/\n end\n end /*j*/ /* [↑] % is the REXX integer division*/\n /* [↓] adjust for a square. ___*/\n if j*j==x then return sig+j a j b /*Was X a square? If so, add √ X */\n return sig a b /*return the divisors (both lists). */\n/*──────────────────────────────────────────────────────────────────────────────────────*/\nZum: procedure; parse arg x . /*obtain a # to be tested for Zumkeller*/\n if x<6 then return 0 /*test if X is too low \" \" */\n if x<945 then if x//2==1 then return 0 /* \" \" \" \" \" \" for odd \" */\n parse value PDaS(x) with sigma pdivs /*obtain sigma and the proper divisors.*/\n if sigma//2 then return 0 /*Is the sigma odd? Not Zumkeller.*/\n #= words(pdivs) /*count the number of divisors for X. */\n if #<3 then return 0 /*Not enough divisors? \" \" */\n if x//2 then do; _= sigma - x - x /*use abundant optimization for odd #'s*/\n return _>0 & _//2==0 /*Abundant is > 0 and even? It's a Zum*/\n end\n if #>23 then return 1 /*# divisors is 24 or more? It's a Zum*/\n\n do i=1 for #; @.i= word(pdivs, i) /*assign proper divisors to the @ array*/\n end /*i*/\n c=0; u= 2**#; !.= .\n do p=1 for u-2; b= x2b(d2x(p)) /*convert P──►binary with leading zeros*/\n b= right(strip(b, 'L', 0), #, 0) /*ensure enough leading zeros for B. */\n r= reverse(b); if !.r\\==. then iterate /*is this binary# a palindrome of prev?*/\n c= c + 1; yy.c= b; !.b= /*store this particular combination. */\n end /*p*/\n\n do part=1 for c; p1= 0; p2= 0 /*test of two partitions add to same #.*/\n _= yy.part /*obtain one method of partitioning. */\n do cp=1 for # /*obtain the sums of the two partitions*/\n if substr(_, cp, 1) then p1= p1 + @.cp /*if a one, then add it to P1.*/\n else p2= p2 + @.cp /* \" \" zero, \" \" \" \" P2.*/\n end /*cp*/\n if p1==p2 then return 1 /*Partition sums equal? Then X is Zum.*/\n end /*part*/\n return 0 /*no partition sum passed. X isn't Zum*/\n", "language": "REXX" }, { "code": "load \"stdlib.ring\"\n\nsee \"working...\" + nl\nsee \"The first 220 Zumkeller numbers are:\" + nl\n\npermut = []\nzumind = []\nzumodd = []\nlimit = 19305\nnum1 = 0\nnum2 = 0\n\nfor n = 2 to limit\n zumkeller = []\n zumList = []\n permut = []\n calmo = []\n zumind = []\n num = 0\n nold = 0\n for m = 1 to n\n if n % m = 0\n num = num + 1\n add(zumind,m)\n ok\n next\n for p = 1 to num\n add(zumList,1)\n add(zumList,2)\n next\n permut(zumList)\n lenZum = len(zumList)\n\n for n2 = 1 to len(permut)/lenZum\n str = \"\"\n for m = (n2-1)*lenZum+1 to n2*lenZum\n str = str + string(permut[m])\n next\n if str != \"\"\n strNum = number(str)\n add(calmo,strNum)\n ok\n next\n\n calmo = sort(calmo)\n\n for x = len(calmo) to 2 step -1\n if calmo[x] = calmo[x-1]\n del(calmo,x)\n ok\n next\n\n zumkeller = []\n calmoLen = len(string(calmo[1]))\n calmoLen2 = calmoLen/2\n for y = 1 to len(calmo)\n tmpStr = string(calmo[y])\n tmp1 = left(tmpStr,calmoLen2)\n tmp2 = number(tmp1)\n add(zumkeller,tmp2)\n next\n\n zumkeller = sort(zumkeller)\n\n for x = len(zumkeller) to 2 step -1\n if zumkeller[x] = zumkeller[x-1]\n del(zumkeller,x)\n ok\n next\n\n for z = 1 to len(zumkeller)\n zumsum1 = 0\n zumsum2 = 0\n zum1 = []\n zum2 = []\n\n for m = 1 to len(string(zumkeller[z]))\n zumstr = string(zumkeller[z])\n tmp = number(zumstr[m])\n if tmp = 1\n add(zum1,zumind[m])\n else\n add(zum2,zumind[m])\n ok\n next\n\n for z1 = 1 to len(zum1)\n zumsum1 = zumsum1 + zum1[z1]\n next\n\n for z2 = 1 to len(zum2)\n zumsum2 = zumsum2 + zum2[z2]\n next\n\n if zumsum1 = zumsum2\n num1 = num1 + 1\n if n != nold\n if num1 < 221\n if (n-1)%22 = 0\n see nl + \" \" + n\n else\n see \" \" + n\n ok\n ok\n if zumsum1%2 = 1\n num2 = num2 + 1\n if num2 < 41\n add(zumodd,n)\n ok\n ok\n ok\n nold = n\n ok\n next\nnext\n\nsee \"The first 40 odd Zumkeller numbers are:\" + nl\nfor n = 1 to len(zumodd)\n if (n-1)%8 = 0\n see nl + \" \" + zumodd[n]\n else\n see \" \" + zumodd[n]\n ok\nnext\n\nsee nl + \"done...\" + nl\n\nfunc permut(list)\n for perm = 1 to factorial(len(list))\n for i = 1 to len(list)\n add(permut,list[i])\n next\n perm(list)\n next\n\nfunc perm(a)\n elementcount = len(a)\n if elementcount < 1\n return\n ok\n pos = elementcount-1\n while a[pos] >= a[pos+1]\n pos -= 1\n if pos <= 0 permutationReverse(a, 1, elementcount)\n return\n ok\n end\n last = elementcount\n while a[last] <= a[pos]\n last -= 1\n end\n temp = a[pos]\n a[pos] = a[last]\n a[last] = temp\n permReverse(a, pos+1, elementcount)\n\n func permReverse(a,first,last)\n while first < last\n temp = a[first]\n a[first] = a[last]\n a[last] = temp\n first += 1\n last -= 1\n end\n", "language": "Ring" }, { "code": "class Integer\n\n def divisors\n res = [1, self]\n (2..Integer.sqrt(self)).each do |n|\n div, mod = divmod(n)\n res << n << div if mod.zero?\n end\n res.uniq.sort\n end\n\n def zumkeller?\n divs = divisors\n sum = divs.sum\n return false unless sum.even? && sum >= self*2\n half = sum / 2\n max_combi_size = divs.size / 2\n 1.upto(max_combi_size).any? do |combi_size|\n divs.combination(combi_size).any?{|combi| combi.sum == half}\n end\n end\n\nend\n\ndef p_enum(enum, cols = 10, col_width = 8)\n enum.each_slice(cols) {|slice| puts \"%#{col_width}d\"*slice.size % slice}\nend\n\nputs \"#{n=220} Zumkeller numbers:\"\np_enum 1.step.lazy.select(&:zumkeller?).take(n), 14, 6\n\nputs \"\\n#{n=40} odd Zumkeller numbers:\"\np_enum 1.step(by: 2).lazy.select(&:zumkeller?).take(n)\n\nputs \"\\n#{n=40} odd Zumkeller numbers not ending with 5:\"\np_enum 1.step(by: 2).lazy.select{|x| x % 5 > 0 && x.zumkeller?}.take(n)\n", "language": "Ruby" }, { "code": "use std::convert::TryInto;\n\n/// Gets all divisors of a number, including itself\nfn get_divisors(n: u32) -> Vec<u32> {\n let mut results = Vec::new();\n\n for i in 1..(n / 2 + 1) {\n if n % i == 0 {\n results.push(i);\n }\n }\n results.push(n);\n results\n}\n\n/// Calculates whether the divisors can be partitioned into two disjoint\n/// sets that sum to the same value\nfn is_summable(x: i32, divisors: &[u32]) -> bool {\n if !divisors.is_empty() {\n if divisors.contains(&(x as u32)) {\n return true;\n } else if let Some((first, t)) = divisors.split_first() {\n return is_summable(x - *first as i32, &t) || is_summable(x, &t);\n }\n }\n false\n}\n\n/// Calculates whether the number is a Zumkeller number\n/// Zumkeller numbers are the set of numbers whose divisors can be partitioned\n/// into two disjoint sets that sum to the same value. Each sum must contain\n/// divisor values that are not in the other sum, and all of the divisors must\n/// be in one or the other.\nfn is_zumkeller_number(number: u32) -> bool {\n if number % 18 == 6 || number % 18 == 12 {\n return true;\n }\n\n let div = get_divisors(number);\n let divisor_sum: u32 = div.iter().sum();\n if divisor_sum == 0 {\n return false;\n }\n if divisor_sum % 2 == 1 {\n return false;\n }\n\n // numbers where n is odd and the abundance is even are Zumkeller numbers\n let abundance = divisor_sum as i32 - 2 * number as i32;\n if number % 2 == 1 && abundance > 0 && abundance % 2 == 0 {\n return true;\n }\n\n let half = divisor_sum / 2;\n return div.contains(&half)\n || (div.iter().filter(|&&d| d < half).count() > 0\n && is_summable(half.try_into().unwrap(), &div));\n}\n\nfn main() {\n println!(\"\\nFirst 220 Zumkeller numbers:\");\n let mut counter: u32 = 0;\n let mut i: u32 = 0;\n while counter < 220 {\n if is_zumkeller_number(i) {\n print!(\"{:>3}\", i);\n counter += 1;\n print!(\"{}\", if counter % 20 == 0 { \"\\n\" } else { \",\" });\n }\n i += 1;\n }\n\n println!(\"\\nFirst 40 odd Zumkeller numbers:\");\n let mut counter: u32 = 0;\n let mut i: u32 = 3;\n while counter < 40 {\n if is_zumkeller_number(i) {\n print!(\"{:>5}\", i);\n counter += 1;\n print!(\"{}\", if counter % 20 == 0 { \"\\n\" } else { \",\" });\n }\n i += 2;\n }\n}\n", "language": "Rust" }, { "code": "func is_Zumkeller(n) {\n\n return false if n.is_prime\n return false if n.is_square\n\n var sigma = n.sigma\n\n # n must have an even abundance\n return false if (sigma.is_odd || (sigma < 2*n))\n\n # true if n is odd and has an even abundance\n return true if n.is_odd # conjecture\n\n var divisors = n.divisors\n\n for k in (2 .. divisors.end) {\n divisors.combinations(k, {|*a|\n if (2*a.sum == sigma) {\n return true\n }\n })\n }\n\n return false\n}\n\nsay \"First 220 Zumkeller numbers:\"\nsay (1..Inf -> lazy.grep(is_Zumkeller).first(220).join(' '))\n\nsay \"\\nFirst 40 odd Zumkeller numbers: \"\nsay (1..Inf `by` 2 -> lazy.grep(is_Zumkeller).first(40).join(' '))\n\nsay \"\\nFirst 40 odd Zumkeller numbers not divisible by 5: \"\nsay (1..Inf `by` 2 -> lazy.grep { _ % 5 != 0 }.grep(is_Zumkeller).first(40).join(' '))\n", "language": "Sidef" }, { "code": "exception Found of string ;\n\nval divisors = fn n =>\nlet\n val rec divr = fn ( c, divlist ,i) =>\n if c <2*i then c::divlist\n else divr (if c mod i = 0 then (c,i::divlist,i+1) else (c,divlist,i+1) )\nin\n divr (n,[],1)\nend;\n\n\nval subsetSums = fn M => fn input =>\nlet\n val getnrs = fn (v,x) => (* out: list of numbers index where v is true + x *)\n let\n val rec runthr = fn (v,i,x,lst)=> if i>=M then (v,i,x,lst) else runthr (v,i+1,x,if Vector.sub(v,i) then (i+x)::lst else lst) ;\n in\n #4 (runthr (v,0,x,[]))\n end;\n\n val nwVec = fn (v,nrs) =>\n let\n val rec upd = fn (v,i,[]) => (v,i,[])\n | (v,i,h::t) => upd ( case Int.compare (h,M) of\n\t\t LESS => ( Vector.update (v,h,true),i+1,t)\n\t\t | GREATER => (v,i+1,t)\n\t\t | EQUAL => raise Found (\"done \"^(Int.toString h)) )\n in\n #1 (upd (v,0,nrs))\n end;\n\n val rec setSums = fn ([],v) => ([],v)\n | (x::t,v) => setSums(t, nwVec(v, getnrs (v,x)))\nin\n\n #2 (setSums (input,Vector.tabulate (M+1,fn 0=> true|_=>false) ))\n\nend;\n\n\nval rec Zumkeller = fn n =>\n let\n val d = divisors n;\n val s = List.foldr op+ 0 d ;\n val hs = s div 2 -n ;\n in\n\n if s mod 2 = 1 orelse 0 > hs then false else\n Vector.sub ( subsetSums hs (tl d) ,hs) handle Found nr => true\n\nend;\n", "language": "Standard-ML" }, { "code": "- val Zumkellerlist = fn step => fn no5 =>\nlet\n val rec loop = fn incr => fn (i,n,v) =>\n if i= (case incr of 1 => 221 | 2 => 41 | _ => 5 )\n\t then (0,n,v)\n else if n mod 5 = 0 andalso no5 then loop incr (i,n+incr,v) else\n\t\t if Zumkeller n then loop incr (i+1,n+incr,(i,n)::v) else loop incr (i,n+incr,v)\nin\n rev (#3 ( loop step (1,3,[])))\nend;\n- List.app (fn x=> print (Int.toString (#2 x) ^ \", \")) (Zumkellerlist 1 false) ;\n6, 12, 20, 24, 28, 30, 40, 42, 48, 54, 56, 60, 66, 70, 78, 80, 84, 88, 90, 96, 102, 104, 108, 112, 114, 120, 126, 132,\n138, 140, 150, 156, 160, 168, 174, 176, 180, 186, 192, 198, 204, 208, 210, 216, 220, 222, 224, 228, 234, 240, 246, 252,\n258, 260, 264, 270, 272, 276, 280, 282, 294, 300, 304, 306, 308, 312, 318, 320, 330, 336, 340, 342, 348, 350, 352, 354,\n360, 364, 366, 368, 372, 378, 380, 384, 390, 396, 402, 408, 414, 416, 420, 426, 432, 438, 440, 444, 448, 456, 460, 462,\n464, 468, 474, 476, 480, 486, 490, 492, 496, 498, 500, 504, 510, 516, 520, 522, 528, 532, 534, 540, 544, 546, 550, 552,\n558, 560, 564, 570, 572, 580, 582, 588, 594, 600, 606, 608, 612, 616, 618, 620, 624, 630, 636, 640, 642, 644, 650, 654,\n660, 666, 672, 678, 680, 684, 690, 696, 700, 702, 704, 708, 714, 720, 726, 728, 732, 736, 740, 744, 750, 756, 760, 762,\n768, 770, 780, 786, 792, 798, 804, 810, 812, 816, 820, 822, 828, 832, 834, 836, 840, 852, 858, 860, 864, 868, 870, 876,\n880, 888, 894, 896, 906, 910, 912, 918, 920, 924, 928, 930, 936, 940, 942, 945, 948, 952, 960, 966, 972, 978, 980, 984\n\n- List.app (fn x=> print (Int.toString (#2 x) ^ \", \")) (Zumkellerlist 2 false) ;\n\n945, 1575, 2205, 2835, 3465, 4095, 4725, 5355, 5775, 5985, 6435, 6615, 6825, 7245, 7425, 7875, 8085, 8415, 8505, 8925,\n9135, 9555, 9765, 10395, 11655, 12285, 12705, 12915, 13545, 14175, 14805, 15015, 15435, 16065, 16695, 17325, 17955,\n8585, 19215, 19305\n\n\n- List.app (fn x=> print (Int.toString (#2 x) ^ \", \")) (Zumkellerlist 2 true) ;\n81081, 153153, 171171, 189189, 207207, 223839, 243243, 261261, 279279, 297297, 351351, 459459, 513513, 567567, 621621, 671517, 729729,\n742203, 783783, 793611, 812889, 837837, 891891, 908523, 960687, 999999, 1024947, 1054053, 1072071, 1073709, 1095633, 1108107, 1145529,\n1162161, 1198197, 1224531, 1270269, 1307691, 1324323, 1378377\n", "language": "Standard-ML" }, { "code": "import Foundation\n\nextension BinaryInteger {\n @inlinable\n public var isZumkeller: Bool {\n let divs = factors(sorted: false)\n let sum = divs.reduce(0, +)\n\n guard sum & 1 != 1 else {\n return false\n }\n\n guard self & 1 != 1 else {\n let abundance = sum - 2*self\n\n return abundance > 0 && abundance & 1 == 0\n }\n\n return isPartSum(divs: divs[...], sum: sum / 2)\n }\n\n @inlinable\n public func factors(sorted: Bool = true) -> [Self] {\n let maxN = Self(Double(self).squareRoot())\n var res = Set<Self>()\n\n for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {\n res.insert(factor)\n res.insert(self / factor)\n }\n\n return sorted ? res.sorted() : Array(res)\n }\n}\n\n@usableFromInline\nfunc isPartSum<T: BinaryInteger>(divs: ArraySlice<T>, sum: T) -> Bool {\n guard sum != 0 else {\n return true\n }\n\n guard !divs.isEmpty else {\n return false\n }\n\n let last = divs.last!\n\n if last > sum {\n return isPartSum(divs: divs.dropLast(), sum: sum)\n }\n\n return isPartSum(divs: divs.dropLast(), sum: sum) || isPartSum(divs: divs.dropLast(), sum: sum - last)\n}\n\nlet zums = (2...).lazy.filter({ $0.isZumkeller })\nlet oddZums = zums.filter({ $0 & 1 == 1 })\nlet oddZumsWithout5 = oddZums.filter({ String($0).last! != \"5\" })\n\nprint(\"First 220 zumkeller numbers are \\(Array(zums.prefix(220)))\")\nprint(\"First 40 odd zumkeller numbers are \\(Array(oddZums.prefix(40)))\")\nprint(\"First 40 odd zumkeller numbers that don't end in a 5 are: \\(Array(oddZumsWithout5.prefix(40)))\")\n", "language": "Swift" }, { "code": "/**\n * return an array of divisors of a number(n)\n * @params {number} n The number to find divisors from\n * @return {number[]} divisors of n\n*/\nfunction getDivisors(n: number): number[] {\n //initialize divisors array\n let divisors: number[] = [1, n]\n //loop through all numbers from 2 to sqrt(n)\n for (let i = 2; i*i <= n; i++) {\n // if i is a divisor of n\n if (n % i == 0) {\n // add i to divisors array\n divisors.push(i);\n // quotient of n/i is also a divisor of n\n let j = n/i;\n // if quotient is not equal to i\n if (i != j) {\n // add quotient to divisors array\n divisors.push(j);\n }\n }\n }\n\n return divisors\n }\n\n /**\n * return sum of an array of number\n * @param {number[]} arr The array we need to sum\n * @return {number} sum of arr\n */\n function getSum(arr: number[]): number {\n return arr.reduce((prev, curr) => prev + curr, 0)\n }\n\n /**\n * check if there is a subset of divisors which sums to a specific number\n * @param {number[]} divs The array of divisors\n * @param {number} sum The number to check if there's a subset of divisors which sums to it\n * @return {boolean} true if sum is 0, false if divisors length is 0\n */\n function isPartSum(divs: number[], sum: number): boolean {\n // if sum is 0, the partition is sum up to the number(sum)\n if (sum == 0) return true;\n //get length of divisors array\n let len = divs.length;\n // if divisors array is empty the partion doesnt not sum up to the number(sum)\n if (len == 0) return false;\n //get last element of divisors array\n let last = divs[len - 1];\n //create a copy of divisors array without the last element\n const newDivs = [...divs];\n newDivs.pop();\n // if last element is greater than sum\n if (last > sum) {\n // recursively check if there's a subset of divisors which sums to sum using the new divisors array\n return isPartSum(newDivs, sum);\n }\n // recursively check if there's a subset of divisors which sums to sum using the new divisors array\n // or if there's a subset of divisors which sums to sum - last using the new divisors array\n return isPartSum(newDivs, sum) || isPartSum(newDivs, sum - last);\n }\n\n /**\n * check if a number is a Zumkeller number\n * @param {number} n The number to check if it's a Zumkeller number\n * @returns {boolean} true if n is a Zumkeller number, false otherwise\n */\n function isZumkeller(n: number): boolean {\n // get divisors of n\n let divs = getDivisors(n);\n // get sum of divisors of n\n let sum = getSum(divs);\n // if sum is odd can't be split into two partitions with equal sums\n if (sum % 2 == 1) return false;\n // if n is odd use 'abundant odd number' optimization\n if (n % 2 == 1) {\n let abundance = sum - 2 * n\n return abundance > 0 && abundance%2 == 0;\n }\n\n // if n and sum are both even check if there's a partition which totals sum / 2\n return isPartSum(divs, sum/2);\n }\n\n /**\n * find x zumkeller numbers\n * @param {number} x The number of zumkeller numbers to find\n * @returns {number[]} array of x zumkeller numbers\n */\n function getXZumkelers(x: number): number[] {\n let zumkellers: number[] = [];\n let i = 2;\n let count= 0;\n while (count < x) {\n if (isZumkeller(i)) {\n zumkellers.push(i);\n count++;\n }\n i++;\n }\n\n return zumkellers;\n }\n\n /**\n * find x Odd Zumkeller numbers\n * @param {number} x The number of odd zumkeller numbers to find\n * @returns {number[]} array of x odd zumkeller numbers\n */\n function getXOddZumkelers(x: number): number[] {\n let oddZumkellers: number[] = [];\n let i = 3;\n let count = 0;\n while (count < x) {\n if (isZumkeller(i)) {\n oddZumkellers.push(i);\n count++;\n }\n i += 2;\n }\n\n return oddZumkellers;\n }\n\n /**\n * find x odd zumkeller number which are not end with 5\n * @param {number} x The number of odd zumkeller numbers to find\n * @returns {number[]} array of x odd zumkeller numbers\n */\n function getXOddZumkellersNotEndWith5(x: number): number[] {\n let oddZumkellers: number[] = [];\n let i = 3;\n let count = 0;\n while (count < x) {\n if (isZumkeller(i) && i % 10 != 5) {\n oddZumkellers.push(i);\n count++;\n }\n i += 2;\n }\n\n return oddZumkellers;\n }\n\n//get the first 220 zumkeller numbers\nconsole.log(\"First 220 Zumkeller numbers: \", getXZumkelers(220));\n\n//get the first 40 odd zumkeller numbers\nconsole.log(\"First 40 odd Zumkeller numbers: \", getXOddZumkelers(40));\n\n//get the first 40 odd zumkeller numbers which are not end with 5\nconsole.log(\"First 40 odd Zumkeller numbers which are not end with 5: \", getXOddZumkellersNotEndWith5(40));\n", "language": "TypeScript" }, { "code": "fn get_divisors(n int) []int {\n mut divs := [1, n]\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n j := n / i\n divs << i\n if i != j {\n divs << j\n }\n }\n }\n return divs\n}\n\nfn sum(divs []int) int {\n mut sum := 0\n for div in divs {\n sum += div\n }\n return sum\n}\n\nfn is_part_sum(d []int, sum int) bool {\n mut divs := d.clone()\n if sum == 0 {\n return true\n }\n le := divs.len\n if le == 0 {\n return false\n }\n last := divs[le-1]\n divs = divs[0 .. le-1]\n if last > sum {\n return is_part_sum(divs, sum)\n }\n return is_part_sum(divs, sum) || is_part_sum(divs, sum-last)\n}\n\nfn is_zumkeller(n int) bool {\n divs := get_divisors(n)\n s := sum(divs)\n // if sum is odd can't be split into two partitions with equal sums\n if s%2 == 1 {\n return false\n }\n // if n is odd use 'abundant odd number' optimization\n if n%2 == 1 {\n abundance := s - 2*n\n return abundance > 0 && abundance%2 == 0\n }\n // if n and sum are both even check if there's a partition which totals sum / 2\n return is_part_sum(divs, s/2)\n}\n\nfn main() {\n println(\"The first 220 Zumkeller numbers are:\")\n for i, count := 2, 0; count < 220; i++ {\n if is_zumkeller(i) {\n print(\"${i:3} \")\n count++\n if count%20 == 0 {\n println('')\n }\n }\n }\n println(\"\\nThe first 40 odd Zumkeller numbers are:\")\n for i, count := 3, 0; count < 40; i += 2 {\n if is_zumkeller(i) {\n print(\"${i:5} \")\n count++\n if count%10 == 0 {\n println('')\n }\n }\n }\n println(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\n for i, count := 3, 0; count < 40; i += 2 {\n if (i % 10 != 5) && is_zumkeller(i) {\n print(\"${i:7} \")\n count++\n if count%8 == 0 {\n println('')\n }\n }\n }\n println('')\n}\n", "language": "V-(Vlang)" }, { "code": "Module Module1\n Function GetDivisors(n As Integer) As List(Of Integer)\n Dim divs As New List(Of Integer) From {\n 1, n\n }\n Dim i = 2\n While i * i <= n\n If n Mod i = 0 Then\n Dim j = n \\ i\n divs.Add(i)\n If i <> j Then\n divs.Add(j)\n End If\n End If\n i += 1\n End While\n Return divs\n End Function\n\n Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean\n If sum = 0 Then\n Return True\n End If\n Dim le = divs.Count\n If le = 0 Then\n Return False\n End If\n Dim last = divs(le - 1)\n Dim newDivs As New List(Of Integer)\n For i = 1 To le - 1\n newDivs.Add(divs(i - 1))\n Next\n If last > sum Then\n Return IsPartSum(newDivs, sum)\n End If\n Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)\n End Function\n\n Function IsZumkeller(n As Integer) As Boolean\n Dim divs = GetDivisors(n)\n Dim sum = divs.Sum()\n REM if sum is odd can't be split into two partitions with equal sums\n If sum Mod 2 = 1 Then\n Return False\n End If\n REM if n is odd use 'abundant odd number' optimization\n If n Mod 2 = 1 Then\n Dim abundance = sum - 2 * n\n Return abundance > 0 AndAlso abundance Mod 2 = 0\n End If\n REM if n and sum are both even check if there's a partition which totals sum / 2\n Return IsPartSum(divs, sum \\ 2)\n End Function\n\n Sub Main()\n Console.WriteLine(\"The first 220 Zumkeller numbers are:\")\n Dim i = 2\n Dim count = 0\n While count < 220\n If IsZumkeller(i) Then\n Console.Write(\"{0,3} \", i)\n count += 1\n If count Mod 20 = 0 Then\n Console.WriteLine()\n End If\n End If\n i += 1\n End While\n Console.WriteLine()\n\n Console.WriteLine(\"The first 40 odd Zumkeller numbers are:\")\n i = 3\n count = 0\n While count < 40\n If IsZumkeller(i) Then\n Console.Write(\"{0,5} \", i)\n count += 1\n If count Mod 10 = 0 Then\n Console.WriteLine()\n End If\n End If\n i += 2\n End While\n Console.WriteLine()\n\n Console.WriteLine(\"The first 40 odd Zumkeller numbers which don't end in 5 are:\")\n i = 3\n count = 0\n While count < 40\n If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then\n Console.Write(\"{0,7} \", i)\n count += 1\n If count Mod 8 = 0 Then\n Console.WriteLine()\n End If\n End If\n i += 2\n End While\n End Sub\nEnd Module\n", "language": "Visual-Basic-.NET" }, { "code": "import \"./math\" for Int, Nums\nimport \"./fmt\" for Fmt\nimport \"io\" for Stdout\n\nvar isPartSum // recursive\nisPartSum = Fn.new { |divs, sum|\n if (sum == 0) return true\n if (divs.count == 0) return false\n var last = divs[-1]\n divs = divs[0...-1]\n if (last > sum) return isPartSum.call(divs, sum)\n return isPartSum.call(divs, sum-last) || isPartSum.call(divs, sum)\n}\n\nvar isZumkeller = Fn.new { |n|\n var divs = Int.divisors(n)\n var sum = Nums.sum(divs)\n // if sum is odd can't be split into two partitions with equal sums\n if (sum % 2 == 1) return false\n // if n is odd use 'abundant odd number' optimization\n if (n % 2 == 1) {\n var abundance = sum - 2 * n\n return abundance > 0 && abundance % 2 == 0\n }\n // if n and sum are both even check if there's a partition which totals sum / 2\n return isPartSum.call(divs, sum / 2)\n}\n\nSystem.print(\"The first 220 Zumkeller numbers are:\")\nvar count = 0\nvar i = 2\nwhile (count < 220) {\n if (isZumkeller.call(i)) {\n Fmt.write(\"$3d \", i)\n Stdout.flush()\n count = count + 1\n if (count % 20 == 0) System.print()\n }\n i = i + 1\n}\n\nSystem.print(\"\\nThe first 40 odd Zumkeller numbers are:\")\ncount = 0\ni = 3\nwhile (count < 40) {\n if (isZumkeller.call(i)) {\n Fmt.write(\"$5d \", i)\n Stdout.flush()\n count = count + 1\n if (count % 10 == 0) System.print()\n }\n i = i + 2\n}\n\nSystem.print(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\")\ncount = 0\ni = 3\nwhile (count < 40) {\n if ((i % 10 != 5) && isZumkeller.call(i)) {\n Fmt.write(\"$7d \", i)\n Stdout.flush()\n count = count + 1\n if (count % 8 == 0) System.print()\n }\n i = i + 2\n}\nSystem.print()\n", "language": "Wren" }, { "code": "fcn properDivs(n){ // does not include n\n// if(n==1) return(T);\t// we con't care about this case\n ( pd:=[1..(n).toFloat().sqrt()].filter('wrap(x){ n%x==0 }) )\n .pump(pd,'wrap(pd){ if(pd!=1 and (y:=n/pd)!=pd ) y else Void.Skip })\n}\nfcn canSum(goal,divs){\n if(goal==0 or divs[0]==goal) return(True);\n if(divs.len()>1){\n if(divs[0]>goal) return(canSum(goal,divs[1,*])); // tail recursion\n else return(canSum(goal - divs[0], divs[1,*]) or canSum(goal, divs[1,*]));\n }\n False\n}\nfcn isZumkellerW(n){\t// a filter for a iterator\n ds,sum := properDivs(n), ds.sum(0) + n;\n // if sum is odd, it can't be split into two partitions with equal sums\n if(sum.isOdd) return(Void.Skip);\n // if n is odd use 'abundant odd number' optimization\n if(n.isOdd){\n abundance:=sum - 2*n;\n return( if(abundance>0 and abundance.isEven) n else Void.Skip);\n }\n canSum(sum/2,ds) and n or Void.Skip\t// sum is even\n}\n", "language": "Zkl" }, { "code": "println(\"First 220 Zumkeller numbers:\");\nzw:=[2..].tweak(isZumkellerW);\ndo(11){ zw.walk(20).pump(String,\"%4d \".fmt).println() }\n\nprintln(\"\\nFirst 40 odd Zumkeller numbers:\");\nzw:=[3..*, 2].tweak(isZumkellerW);\ndo(4){ zw.walk(10).pump(String,\"%5d \".fmt).println() }\n\nprintln(\"\\nThe first 40 odd Zumkeller numbers which don't end in 5 are:\");\nzw:=[3..*, 2].tweak(fcn(n){ if(n%5) isZumkellerW(n) else Void.Skip });\ndo(5){ zw.walk(8).pump(String,\"%7d \".fmt).println() }\n", "language": "Zkl" } ]
Zumkeller-numbers