{"title": "100 doors", "language": "Go", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n doors := [100]bool{}\n\n // the 100 passes called for in the task description\n for pass := 1; pass <= 100; pass++ {\n for door := pass-1; door < 100; door += pass {\n doors[door] = !doors[door]\n }\n }\n\n // one more pass to answer the question\n for i, v := range doors {\n if v {\n fmt.Print(\"1\")\n } else {\n fmt.Print(\"0\")\n }\n\n if i%10 == 9 {\n fmt.Print(\"\\n\")\n } else {\n fmt.Print(\" \")\n }\n\n }\n}"} {"title": "100 prisoners", "language": "Go", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// Uses 0-based numbering rather than 1-based numbering throughout.\nfunc doTrials(trials, np int, strategy string) {\n pardoned := 0\ntrial:\n for t := 0; t < trials; t++ {\n var drawers [100]int\n for i := 0; i < 100; i++ {\n drawers[i] = i\n }\n rand.Shuffle(100, func(i, j int) {\n drawers[i], drawers[j] = drawers[j], drawers[i]\n })\n prisoner:\n for p := 0; p < np; p++ {\n if strategy == \"optimal\" {\n prev := p\n for d := 0; d < 50; d++ {\n this := drawers[prev]\n if this == p {\n continue prisoner\n }\n prev = this\n }\n } else {\n // Assumes a prisoner remembers previous drawers (s)he opened\n // and chooses at random from the others.\n var opened [100]bool\n for d := 0; d < 50; d++ {\n var n int\n for {\n n = rand.Intn(100)\n if !opened[n] {\n opened[n] = true\n break\n }\n }\n if drawers[n] == p {\n continue prisoner\n }\n }\n }\n continue trial\n }\n pardoned++\n }\n rf := float64(pardoned) / float64(trials) * 100\n fmt.Printf(\" strategy = %-7s pardoned = %-6d relative frequency = %5.2f%%\\n\\n\", strategy, pardoned, rf)\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n const trials = 100000\n for _, np := range []int{10, 100} {\n fmt.Printf(\"Results from %d trials with %d prisoners:\\n\\n\", trials, np)\n for _, strategy := range [2]string{\"random\", \"optimal\"} {\n doTrials(trials, np, strategy)\n }\n }\n}"} {"title": "15 puzzle game", "language": "Go", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tp := newPuzzle()\n\tp.play()\n}\n\ntype board [16]cell\ntype cell uint8\ntype move uint8\n\nconst (\n\tup move = iota\n\tdown\n\tright\n\tleft\n)\n\nfunc randMove() move { return move(rand.Intn(4)) }\n\nvar solvedBoard = board{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}\n\nfunc (b *board) String() string {\n\tvar buf strings.Builder\n\tfor i, c := range b {\n\t\tif c == 0 {\n\t\t\tbuf.WriteString(\" .\")\n\t\t} else {\n\t\t\t_, _ = fmt.Fprintf(&buf, \"%3d\", c)\n\t\t}\n\t\tif i%4 == 3 {\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn buf.String()\n}\n\ntype puzzle struct {\n\tboard board\n\tempty int // board[empty] == 0\n\tmoves int\n\tquit bool\n}\n\nfunc newPuzzle() *puzzle {\n\tp := &puzzle{\n\t\tboard: solvedBoard,\n\t\tempty: 15,\n\t}\n\t// Could make this configurable, 10==easy, 50==normal, 100==hard\n\tp.shuffle(50)\n\treturn p\n}\n\nfunc (p *puzzle) shuffle(moves int) {\n\t// As with other Rosetta solutions, we use some number\n\t// of random moves to \"shuffle\" the board.\n\tfor i := 0; i < moves || p.board == solvedBoard; {\n\t\tif p.doMove(randMove()) {\n\t\t\ti++\n\t\t}\n\t}\n}\n\nfunc (p *puzzle) isValidMove(m move) (newIndex int, ok bool) {\n\tswitch m {\n\tcase up:\n\t\treturn p.empty - 4, p.empty/4 > 0\n\tcase down:\n\t\treturn p.empty + 4, p.empty/4 < 3\n\tcase right:\n\t\treturn p.empty + 1, p.empty%4 < 3\n\tcase left:\n\t\treturn p.empty - 1, p.empty%4 > 0\n\tdefault:\n\t\tpanic(\"not reached\")\n\t}\n}\n\nfunc (p *puzzle) doMove(m move) bool {\n\ti := p.empty\n\tj, ok := p.isValidMove(m)\n\tif ok {\n\t\tp.board[i], p.board[j] = p.board[j], p.board[i]\n\t\tp.empty = j\n\t\tp.moves++\n\t}\n\treturn ok\n}\n\nfunc (p *puzzle) play() {\n\tfmt.Printf(\"Starting board:\")\n\tfor p.board != solvedBoard && !p.quit {\n\t\tfmt.Printf(\"\\n%v\\n\", &p.board)\n\t\tp.playOneMove()\n\t}\n\tif p.board == solvedBoard {\n\t\tfmt.Printf(\"You solved the puzzle in %d moves.\\n\", p.moves)\n\t}\n}\n\nfunc (p *puzzle) playOneMove() {\n\tfor {\n\t\tfmt.Printf(\"Enter move #%d (U, D, L, R, or Q): \", p.moves+1)\n\t\tvar s string\n\t\tif n, err := fmt.Scanln(&s); err != nil || n != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\ts = strings.TrimSpace(s)\n\t\tif s == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar m move\n\t\tswitch s[0] {\n\t\tcase 'U', 'u':\n\t\t\tm = up\n\t\tcase 'D', 'd':\n\t\t\tm = down\n\t\tcase 'L', 'l':\n\t\t\tm = left\n\t\tcase 'R', 'r':\n\t\t\tm = right\n\t\tcase 'Q', 'q':\n\t\t\tfmt.Printf(\"Quiting after %d moves.\\n\", p.moves)\n\t\t\tp.quit = true\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Println(`\nPlease enter \"U\", \"D\", \"L\", or \"R\" to move the empty cell\nup, down, left, or right. You can also enter \"Q\" to quit.\nUpper or lowercase is accepted and only the first non-blank\ncharacter is important (i.e. you may enter \"up\" if you like).\n`)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !p.doMove(m) {\n\t\t\tfmt.Println(\"That is not a valid move at the moment.\")\n\t\t\tcontinue\n\t\t}\n\n\t\treturn\n\t}\n}"} {"title": "21 game", "language": "Go", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"math/rand\"\n \"os\"\n \"strconv\"\n \"time\"\n)\n\nvar scanner = bufio.NewScanner(os.Stdin)\n\nvar (\n total = 0\n quit = false\n)\n\nfunc itob(i int) bool {\n if i == 0 {\n return false\n }\n return true\n}\n\nfunc getChoice() {\n for {\n fmt.Print(\"Your choice 1 to 3 : \")\n scanner.Scan()\n if scerr := scanner.Err(); scerr != nil {\n log.Fatalln(scerr, \"when choosing number\")\n }\n text := scanner.Text()\n if text == \"q\" || text == \"Q\" {\n quit = true\n return\n }\n input, err := strconv.Atoi(text)\n if err != nil {\n fmt.Println(\"Invalid number, try again\")\n continue\n }\n newTotal := total + input\n switch {\n case input < 1 || input > 3:\n fmt.Println(\"Out of range, try again\")\n case newTotal > 21:\n fmt.Println(\"Too big, try again\")\n default:\n total = newTotal\n fmt.Println(\"Running total is now\", total)\n return\n }\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n computer := itob(rand.Intn(2))\n fmt.Println(\"Enter q to quit at any time\\n\")\n if computer {\n fmt.Println(\"The computer will choose first\")\n } else {\n fmt.Println(\"You will choose first\")\n }\n fmt.Println(\"\\nRunning total is now 0\\n\")\n var choice int\n for round := 1; ; round++ {\n fmt.Printf(\"ROUND %d:\\n\\n\", round)\n for i := 0; i < 2; i++ {\n if computer {\n if total < 18 {\n choice = 1 + rand.Intn(3)\n } else {\n choice = 21 - total\n }\n total += choice\n fmt.Println(\"The computer chooses\", choice)\n fmt.Println(\"Running total is now\", total)\n if total == 21 {\n fmt.Println(\"\\nSo, commiserations, the computer has won!\")\n return\n }\n } else {\n getChoice()\n if quit {\n fmt.Println(\"OK, quitting the game\")\n return\n }\n if total == 21 {\n fmt.Println(\"\\nSo, congratulations, you've won!\")\n return\n }\n }\n fmt.Println()\n computer = !computer\n }\n }\n}"} {"title": "24 game", "language": "Go", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"time\"\n)\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n n := make([]rune, 4)\n for i := range n {\n n[i] = rune(rand.Intn(9) + '1')\n }\n fmt.Printf(\"Your numbers: %c\\n\", n)\n fmt.Print(\"Enter RPN: \")\n var expr string\n fmt.Scan(&expr)\n if len(expr) != 7 {\n fmt.Println(\"invalid. expression length must be 7.\" +\n \" (4 numbers, 3 operators, no spaces)\")\n return\n }\n stack := make([]float64, 0, 4)\n for _, r := range expr {\n if r >= '0' && r <= '9' {\n if len(n) == 0 {\n fmt.Println(\"too many numbers.\")\n return\n }\n i := 0\n for n[i] != r {\n i++\n if i == len(n) {\n fmt.Println(\"wrong numbers.\")\n return\n }\n }\n n = append(n[:i], n[i+1:]...)\n stack = append(stack, float64(r-'0'))\n continue\n }\n if len(stack) < 2 {\n fmt.Println(\"invalid expression syntax.\")\n return\n }\n switch r {\n case '+':\n stack[len(stack)-2] += stack[len(stack)-1]\n case '-':\n stack[len(stack)-2] -= stack[len(stack)-1]\n case '*':\n stack[len(stack)-2] *= stack[len(stack)-1]\n case '/':\n stack[len(stack)-2] /= stack[len(stack)-1]\n default:\n fmt.Printf(\"%c invalid.\\n\", r)\n return\n }\n stack = stack[:len(stack)-1]\n }\n if math.Abs(stack[0]-24) > 1e-6 {\n fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n } else {\n fmt.Println(\"correct.\")\n }\n}"} {"title": "24 game/Solve", "language": "Go", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n// Expression: can either be a single number, or a result of binary\n// operation from left and right node\ntype Expr struct {\n\top int\n\tleft, right *Expr\n\tvalue frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" / \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t// only one expression left, meaning all numbers are arranged into\n\t// a binary tree, so evaluate and see if we get 24\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t// try to combine a pair of expressions into one, thus reduce\n\t// the list length by 1, and recurse down\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t// try all 4 operators\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// also - and / are not commutative, so swap arguments\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\": \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}"} {"title": "4-rings or 4-squares puzzle", "language": "Go", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main(){\n\tn, c := getCombs(1,7,true)\n\tfmt.Printf(\"%d unique solutions in 1 to 7\\n\",n)\n\tfmt.Println(c)\n\tn, c = getCombs(3,9,true)\n\tfmt.Printf(\"%d unique solutions in 3 to 9\\n\",n)\n\tfmt.Println(c)\n\tn, _ = getCombs(0,9,false)\n\tfmt.Printf(\"%d non-unique solutions in 0 to 9\\n\",n)\n}\n\nfunc getCombs(low,high int,unique bool) (num int,validCombs [][]int){\n\tfor a := low; a <= high; a++ {\n\t\tfor b := low; b <= high; b++ {\n\t\t\tfor c := low; c <= high; c++ {\n\t\t\t\tfor d := low; d <= high; d++ {\n\t\t\t\t\tfor e := low; e <= high; e++ {\n\t\t\t\t\t\tfor f := low; f <= high; f++ {\n\t\t\t\t\t\t\tfor g := low; g <= high; g++ {\n\t\t\t\t\t\t\t\tif validComb(a,b,c,d,e,f,g) {\n\t\t\t\t\t\t\t\t\tif !unique || isUnique(a,b,c,d,e,f,g) {\n\t\t\t\t\t\t\t\t\t\tnum++\n\t\t\t\t\t\t\t\t\t\tvalidCombs = append(validCombs,[]int{a,b,c,d,e,f,g})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\nfunc isUnique(a,b,c,d,e,f,g int) (res bool) {\n\tdata := make(map[int]int)\n\tdata[a]++\n\tdata[b]++\n\tdata[c]++\n\tdata[d]++\n\tdata[e]++\n\tdata[f]++\n\tdata[g]++\n\treturn len(data) == 7\n}\nfunc validComb(a,b,c,d,e,f,g int) bool{\n\tsquare1 := a + b\n\tsquare2 := b + c + d\n\tsquare3 := d + e + f\n\tsquare4 := f + g\n\treturn square1 == square2 && square2 == square3 && square3 == square4\n}\n"} {"title": "99 bottles of beer", "language": "Go", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"strings\"\n \"time\"\n)\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n for i := 99; i > 0; i-- {\n fmt.Printf(\"%s %s %s\\n\",\n slur(numberName(i), i),\n pluralizeFirst(slur(\"bottle of\", i), i),\n slur(\"beer on the wall\", i))\n fmt.Printf(\"%s %s %s\\n\",\n slur(numberName(i), i),\n pluralizeFirst(slur(\"bottle of\", i), i),\n slur(\"beer\", i))\n fmt.Printf(\"%s %s %s\\n\",\n slur(\"take one\", i),\n slur(\"down\", i),\n slur(\"pass it around\", i))\n fmt.Printf(\"%s %s %s\\n\",\n slur(numberName(i-1), i),\n pluralizeFirst(slur(\"bottle of\", i), i-1),\n slur(\"beer on the wall\", i))\n }\n}\n\n// adapted from Number names task\nfunc numberName(n int) string {\n switch {\n case n < 0:\n case n < 20:\n return small[n]\n case n < 100:\n t := tens[n/10]\n s := n % 10\n if s > 0 {\n t += \" \" + small[s]\n }\n return t\n }\n return \"\"\n}\n\nvar small = []string{\"no\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = []string{\"ones\", \"ten\", \"twenty\", \"thirty\", \"forty\",\n \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\n\n// pluralize first word of s by adding an s, but only if n is not 1.\nfunc pluralizeFirst(s string, n int) string {\n if n == 1 {\n return s\n }\n w := strings.Fields(s)\n w[0] += \"s\"\n return strings.Join(w, \" \")\n}\n\n// p is string to slur, d is drunkenness, from 0 to 99\nfunc slur(p string, d int) string {\n // shuffle only interior letters\n a := []byte(p[1 : len(p)-1])\n // adapted from Knuth shuffle task.\n // shuffle letters with probability d/100.\n for i := len(a) - 1; i >= 1; i-- {\n if rand.Intn(100) >= d {\n j := rand.Intn(i + 1)\n a[i], a[j] = a[j], a[i]\n }\n }\n // condense spaces\n w := strings.Fields(p[:1] + string(a) + p[len(p)-1:])\n return strings.Join(w, \" \")\n}"} {"title": "99 bottles of beer", "language": "Go!", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "-- \n-- 99 Bottles of Beer in Go!\n-- John Knottenbelt\n-- \n-- Go! is a multi-paradigm programming language that is oriented\n-- to the needs of programming secure, production quality, agent\n-- based applications.\n-- \n-- http://www.doc.ic.ac.uk/~klc/dalt03.html \n-- \n\nmain .. {\n include \"sys:go/io.gof\".\n include \"sys:go/stdlib.gof\".\n\n main() ->\n drink(99);\n stdout.outLine(\"Time to buy some more beer...\").\n\n drink(0) -> {}.\n drink(i) -> stdout.outLine(\n bottles(i) <> \" on the wall,\\n\" <>\n bottles(i) <> \".\\n\" <>\n \"take one down, pass it around,\\n\" <>\n bottles(i-1) <> \" on the wall.\\n\");\n drink(i-1).\n\n bottles(0) => \"no bottles of beer\".\n bottles(1) => \"1 bottle of beer\".\n bottles(i) => i^0 <> \" bottles of beer\".\n}"} {"title": "9 billion names of God the integer", "language": "Go", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\n\tintMin := func(a, b int) int {\n\t\tif a < b {\n\t\t\treturn a\n\t\t} else {\n\t\t\treturn b\n\t\t}\n\t}\n\n\tvar cache = [][]*big.Int{{big.NewInt(1)}}\n\n\tcumu := func(n int) []*big.Int {\n\t\tfor y := len(cache); y <= n; y++ {\n\t\t\trow := []*big.Int{big.NewInt(0)}\n\t\t\tfor x := 1; x <= y; x++ {\n\t\t\t\tcacheValue := cache[y-x][intMin(x, y-x)]\n\t\t\t\trow = append(row, big.NewInt(0).Add(row[len(row)-1], cacheValue))\n\t\t\t}\n\t\t\tcache = append(cache, row)\n\t\t}\n\t\treturn cache[n]\n\t}\n\n\trow := func(n int) {\n\t\te := cumu(n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tfmt.Printf(\" %v \", (big.NewInt(0).Sub(e[i+1], e[i])).Text(10))\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println(\"rows:\")\n\tfor x := 1; x < 11; x++ {\n\t\trow(x)\n\t}\n\tfmt.Println()\n\t\n\tfmt.Println(\"sums:\")\n\tfor _, num := range [...]int{23, 123, 1234, 12345} {\n\t\tr := cumu(num)\n\t\tfmt.Printf(\"%d %v\\n\", num, r[len(r)-1].Text(10))\n\t}\n}"} {"title": "A+B", "language": "Go", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a, b int\n fmt.Scan(&a, &b)\n fmt.Println(a + b)\n}"} {"title": "ABC problem", "language": "Go", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc newSpeller(blocks string) func(string) bool {\n\tbl := strings.Fields(blocks)\n\treturn func(word string) bool {\n\t\treturn r(word, bl)\n\t}\n}\n\nfunc r(word string, bl []string) bool {\n\tif word == \"\" {\n\t\treturn true\n\t}\n\tc := word[0] | 32\n\tfor i, b := range bl {\n\t\tif c == b[0]|32 || c == b[1]|32 {\n\t\t\tbl[i], bl[0] = bl[0], b\n\t\t\tif r(word[1:], bl[1:]) == true {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tbl[i], bl[0] = bl[0], bl[i]\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main() {\n\tsp := newSpeller(\n\t\t\"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\")\n\tfor _, word := range []string{\n\t\t\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\"} {\n\t\tfmt.Println(word, sp(word))\n\t}\n}"} {"title": "ASCII art diagram converter", "language": "Go", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n \"strings\"\n)\n\ntype result struct {\n name string\n size int\n start int\n end int\n}\n\nfunc (r result) String() string {\n return fmt.Sprintf(\"%-7s %2d %3d %3d\", r.name, r.size, r.start, r.end)\n}\n\nfunc validate(diagram string) []string {\n var lines []string\n for _, line := range strings.Split(diagram, \"\\n\") {\n line = strings.Trim(line, \" \\t\")\n if line != \"\" {\n lines = append(lines, line)\n }\n }\n if len(lines) == 0 {\n log.Fatal(\"diagram has no non-empty lines!\")\n }\n width := len(lines[0])\n cols := (width - 1) / 3\n if cols != 8 && cols != 16 && cols != 32 && cols != 64 {\n log.Fatal(\"number of columns should be 8, 16, 32 or 64\")\n }\n if len(lines)%2 == 0 {\n log.Fatal(\"number of non-empty lines should be odd\")\n }\n if lines[0] != strings.Repeat(\"+--\", cols)+\"+\" {\n log.Fatal(\"incorrect header line\")\n }\n for i, line := range lines {\n if i == 0 {\n continue\n } else if i%2 == 0 {\n if line != lines[0] {\n log.Fatal(\"incorrect separator line\")\n }\n } else if len(line) != width {\n log.Fatal(\"inconsistent line widths\")\n } else if line[0] != '|' || line[width-1] != '|' {\n log.Fatal(\"non-separator lines must begin and end with '|'\")\n }\n }\n return lines\n}\n\nfunc decode(lines []string) []result {\n fmt.Println(\"Name Bits Start End\")\n fmt.Println(\"======= ==== ===== ===\")\n start := 0\n width := len(lines[0])\n var results []result\n for i, line := range lines {\n if i%2 == 0 {\n continue\n }\n line := line[1 : width-1]\n for _, name := range strings.Split(line, \"|\") {\n size := (len(name) + 1) / 3\n name = strings.TrimSpace(name)\n res := result{name, size, start, start + size - 1}\n results = append(results, res)\n fmt.Println(res)\n start += size\n }\n }\n return results\n}\n\nfunc unpack(results []result, hex string) {\n fmt.Println(\"\\nTest string in hex:\")\n fmt.Println(hex)\n fmt.Println(\"\\nTest string in binary:\")\n bin := hex2bin(hex)\n fmt.Println(bin)\n fmt.Println(\"\\nUnpacked:\\n\")\n fmt.Println(\"Name Size Bit pattern\")\n fmt.Println(\"======= ==== ================\")\n for _, res := range results {\n fmt.Printf(\"%-7s %2d %s\\n\", res.name, res.size, bin[res.start:res.end+1])\n }\n}\n\nfunc hex2bin(hex string) string {\n z := new(big.Int)\n z.SetString(hex, 16)\n return fmt.Sprintf(\"%0*b\", 4*len(hex), z)\n}\n\nfunc main() {\n const diagram = `\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n `\n lines := validate(diagram)\n fmt.Println(\"Diagram after trimming whitespace and removal of blank lines:\\n\")\n for _, line := range lines {\n fmt.Println(line)\n }\n fmt.Println(\"\\nDecoded:\\n\")\n results := decode(lines)\n hex := \"78477bbf5496e12e1bf169a4\" // test string\n unpack(results, hex)\n}"} {"title": "AVL tree", "language": "Go", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "package avl\n\n// AVL tree adapted from Julienne Walker's presentation at\n// http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx.\n// This port uses similar indentifier names.\n\n// The Key interface must be supported by data stored in the AVL tree.\ntype Key interface {\n Less(Key) bool\n Eq(Key) bool\n}\n\n// Node is a node in an AVL tree.\ntype Node struct {\n Data Key // anything comparable with Less and Eq.\n Balance int // balance factor\n Link [2]*Node // children, indexed by \"direction\", 0 or 1.\n}\n\n// A little readability function for returning the opposite of a direction,\n// where a direction is 0 or 1. Go inlines this.\n// Where JW writes !dir, this code has opp(dir).\nfunc opp(dir int) int {\n return 1 - dir\n}\n\n// single rotation\nfunc single(root *Node, dir int) *Node {\n save := root.Link[opp(dir)]\n root.Link[opp(dir)] = save.Link[dir]\n save.Link[dir] = root\n return save\n}\n\n// double rotation\nfunc double(root *Node, dir int) *Node {\n save := root.Link[opp(dir)].Link[dir]\n\n root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n save.Link[opp(dir)] = root.Link[opp(dir)]\n root.Link[opp(dir)] = save\n\n save = root.Link[opp(dir)]\n root.Link[opp(dir)] = save.Link[dir]\n save.Link[dir] = root\n return save\n}\n\n// adjust valance factors after double rotation\nfunc adjustBalance(root *Node, dir, bal int) {\n n := root.Link[dir]\n nn := n.Link[opp(dir)]\n switch nn.Balance {\n case 0:\n root.Balance = 0\n n.Balance = 0\n case bal:\n root.Balance = -bal\n n.Balance = 0\n default:\n root.Balance = 0\n n.Balance = bal\n }\n nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n n := root.Link[dir]\n bal := 2*dir - 1\n if n.Balance == bal {\n root.Balance = 0\n n.Balance = 0\n return single(root, opp(dir))\n }\n adjustBalance(root, dir, bal)\n return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n if root == nil {\n return &Node{Data: data}, false\n }\n dir := 0\n if root.Data.Less(data) {\n dir = 1\n }\n var done bool\n root.Link[dir], done = insertR(root.Link[dir], data)\n if done {\n return root, true\n }\n root.Balance += 2*dir - 1\n switch root.Balance {\n case 0:\n return root, true\n case 1, -1:\n return root, false\n }\n return insertBalance(root, dir), true\n}\n\n// Insert a node into the AVL tree.\n// Data is inserted even if other data with the same key already exists.\nfunc Insert(tree **Node, data Key) {\n *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n n := root.Link[opp(dir)]\n bal := 2*dir - 1\n switch n.Balance {\n case -bal:\n root.Balance = 0\n n.Balance = 0\n return single(root, dir), false\n case bal:\n adjustBalance(root, opp(dir), -bal)\n return double(root, dir), false\n }\n root.Balance = -bal\n n.Balance = bal\n return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n if root == nil {\n return nil, false\n }\n if root.Data.Eq(data) {\n switch {\n case root.Link[0] == nil:\n return root.Link[1], false\n case root.Link[1] == nil:\n return root.Link[0], false\n }\n heir := root.Link[0]\n for heir.Link[1] != nil {\n heir = heir.Link[1]\n }\n root.Data = heir.Data\n data = heir.Data\n }\n dir := 0\n if root.Data.Less(data) {\n dir = 1\n }\n var done bool\n root.Link[dir], done = removeR(root.Link[dir], data)\n if done {\n return root, true\n }\n root.Balance += 1 - 2*dir\n switch root.Balance {\n case 1, -1:\n return root, true\n case 0:\n return root, false\n }\n return removeBalance(root, dir)\n}\n\n// Remove a single item from an AVL tree.\n// If key does not exist, function has no effect.\nfunc Remove(tree **Node, data Key) {\n *tree, _ = removeR(*tree, data)\n}"} {"title": "Abbreviations, automatic", "language": "Go from Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "package main\n\nimport(\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strings\"\n)\n\nfunc distinctStrings(strs []string) []string {\n len := len(strs)\n set := make(map[string]bool, len)\n distinct := make([]string, 0, len)\n for _, str := range strs {\n if !set[str] {\n distinct = append(distinct, str)\n set[str] = true\n }\n }\n return distinct\n}\n\nfunc takeRunes(s string, n int) string {\n i := 0\n for j := range s {\n if i == n {\n return s[:j]\n }\n i++\n }\n return s\n}\n\nfunc main() {\n file, err := os.Open(\"days_of_week.txt\")\n if err != nil {\n fmt.Println(\"Unable to open file.\")\n return\n }\n defer file.Close()\n reader := bufio.NewReader(file)\n lineCount := 0\n for {\n line, err := reader.ReadString('\\n')\n if err != nil { // end of file reached\n return\n }\n line = strings.TrimSpace(line)\n lineCount++\n if line == \"\" {\n fmt.Println()\n continue\n }\n days := strings.Fields(line)\n daysLen := len(days)\n if (len(days) != 7) {\n fmt.Println(\"There aren't 7 days in line\", lineCount)\n return\n }\n if len(distinctStrings(days)) != 7 { // implies some days have the same name\n fmt.Println(\" \u221e \", line)\n continue\n }\n for abbrevLen := 1; ; abbrevLen++ {\n abbrevs := make([]string, daysLen)\n for i := 0; i < daysLen; i++ {\n abbrevs[i] = takeRunes(days[i], abbrevLen)\n }\n if len(distinctStrings(abbrevs)) == 7 {\n fmt.Printf(\"%2d %s\\n\", abbrevLen, line)\n break\n }\n }\n }\n}"} {"title": "Abbreviations, easy", "language": "Go from Kotlin", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \" +\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \" +\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \" +\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \" +\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up \"\n\nfunc validate(commands, words []string, minLens []int) []string {\n results := make([]string, 0)\n if len(words) == 0 {\n return results\n }\n for _, word := range words {\n matchFound := false\n wlen := len(word)\n for i, command := range commands {\n if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n continue\n }\n c := strings.ToUpper(command)\n w := strings.ToUpper(word)\n if strings.HasPrefix(c, w) {\n results = append(results, c)\n matchFound = true\n break\n }\n }\n if !matchFound {\n results = append(results, \"*error*\")\n }\n }\n return results\n}\n\nfunc main() {\n table = strings.TrimSpace(table)\n commands := strings.Fields(table)\n clen := len(commands)\n minLens := make([]int, clen)\n for i := 0; i < clen; i++ {\n count := 0\n for _, c := range commands[i] {\n if c >= 'A' && c <= 'Z' {\n count++\n }\n }\n minLens[i] = count\n }\n sentence := \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n words := strings.Fields(sentence)\n results := validate(commands, words, minLens)\n fmt.Print(\"user words: \")\n for j := 0; j < len(words); j++ {\n fmt.Printf(\"%-*s \", len(results[j]), words[j])\n }\n fmt.Print(\"\\nfull words: \")\n fmt.Println(strings.Join(results, \" \"))\n}"} {"title": "Abbreviations, simple", "language": "Go from Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\nfunc readTable(table string) ([]string, []int) {\n\tfields := strings.Fields(table)\n\tvar commands []string\n\tvar minLens []int\n\n\tfor i, max := 0, len(fields); i < max; {\n\t\tcmd := fields[i]\n\t\tcmdLen := len(cmd)\n\t\ti++\n\n\t\tif i < max {\n\t\t\tnum, err := strconv.Atoi(fields[i])\n\t\t\tif err == nil && 1 <= num && num < cmdLen {\n\t\t\t\tcmdLen = num\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tcommands = append(commands, cmd)\n\t\tminLens = append(minLens, cmdLen)\n\t}\n\n\treturn commands, minLens\n}\n\nfunc validateCommands(commands []string, minLens []int, words []string) []string {\n\tvar results []string\n\tfor _, word := range words {\n\t\tmatchFound := false\n\t\twlen := len(word)\n\t\tfor i, command := range commands {\n\t\t\tif minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := strings.ToUpper(command)\n\t\t\tw := strings.ToUpper(word)\n\t\t\tif strings.HasPrefix(c, w) {\n\t\t\t\tresults = append(results, c)\n\t\t\t\tmatchFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matchFound {\n\t\t\tresults = append(results, \"*error*\")\n\t\t}\n\t}\n\treturn results\n}\n\nfunc printResults(words []string, results []string) {\n\twr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)\n\tio.WriteString(wr, \"user words:\")\n\tfor _, word := range words {\n\t\tio.WriteString(wr, \"\\t\"+word)\n\t}\n\tio.WriteString(wr, \"\\n\")\n\tio.WriteString(wr, \"full words:\\t\"+strings.Join(results, \"\\t\")+\"\\n\")\n\twr.Flush()\n}\n\nfunc main() {\n\tconst table = \"\" +\n\t\t\"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \" +\n\t\t\"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \" +\n\t\t\"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n\t\t\"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \" +\n\t\t\"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \" +\n\t\t\"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \" +\n\t\t\"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n\t\t\"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 \"\n\n\tconst sentence = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\n\tcommands, minLens := readTable(table)\n\twords := strings.Fields(sentence)\n\n\tresults := validateCommands(commands, minLens, words)\n\n\tprintResults(words, results)\n}\n"} {"title": "Abelian sandpile model", "language": "Go from Rust", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"strings\"\n)\n\nconst dim = 16 // image size\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n// Outputs the result to the terminal using UTF-8 block characters.\nfunc drawPile(pile [][]uint) {\n chars:= []rune(\" \u2591\u2593\u2588\")\n for _, row := range pile {\n line := make([]rune, len(row))\n for i, elem := range row {\n if elem > 3 { // only possible when algorithm not yet completed.\n elem = 3\n }\n line[i] = chars[elem]\n }\n fmt.Println(string(line))\n }\n}\n\n// Creates a .ppm file in the current directory, which contains\n// a colored image of the pile.\nfunc writePile(pile [][]uint) {\n file, err := os.Create(\"output.ppm\")\n check(err)\n defer file.Close()\n // Write the signature, image dimensions and maximum color value to the file.\n fmt.Fprintf(file, \"P3\\n%d %d\\n255\\n\", dim, dim)\n bcolors := []string{\"125 0 25 \", \"125 80 0 \", \"186 118 0 \", \"224 142 0 \"}\n var line strings.Builder\n for _, row := range pile { \n for _, elem := range row {\n line.WriteString(bcolors[elem])\n }\n file.WriteString(line.String() + \"\\n\")\n line.Reset() \n }\n}\n\n// Main part of the algorithm, a simple, recursive implementation of the model.\nfunc handlePile(x, y uint, pile [][]uint) {\n if pile[y][x] >= 4 {\n pile[y][x] -= 4\n // Check each neighbor, whether they have enough \"sand\" to collapse and if they do,\n // recursively call handlePile on them.\n if y > 0 {\n pile[y-1][x]++\n if pile[y-1][x] >= 4 {\n handlePile(x, y-1, pile)\n }\n }\n if x > 0 {\n pile[y][x-1]++\n if pile[y][x-1] >= 4 {\n handlePile(x-1, y, pile)\n }\n }\n if y < dim-1 {\n pile[y+1][x]++\n if pile[y+1][x] >= 4 {\n handlePile(x, y+1, pile)\n }\n }\n if x < dim-1 {\n pile[y][x+1]++\n if pile[y][x+1] >= 4 {\n handlePile(x+1, y, pile)\n }\n }\n\n // Uncomment this line to show every iteration of the program.\n // Not recommended with large input values.\n // drawPile(pile)\n\n // Finally call the function on the current cell again,\n // in case it had more than 4 particles.\n handlePile(x, y, pile)\n }\n}\n\nfunc main() {\n // Create 2D grid and set size using the 'dim' constant.\n pile := make([][]uint, dim)\n for i := 0; i < dim; i++ {\n pile[i] = make([]uint, dim)\n }\n\n // Place some sand particles in the center of the grid and start the algorithm.\n hdim := uint(dim/2 - 1)\n pile[hdim][hdim] = 16\n handlePile(hdim, hdim, pile)\n drawPile(pile)\n\n // Uncomment this to save the final image to a file\n // after the recursive algorithm has ended.\n // writePile(pile)\n}"} {"title": "Abelian sandpile model/Identity", "language": "Go from Wren", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\ntype sandpile struct{ a [9]int }\n\nvar neighbors = [][]int{\n {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},\n}\n\n// 'a' is in row order\nfunc newSandpile(a [9]int) *sandpile { return &sandpile{a} }\n\nfunc (s *sandpile) plus(other *sandpile) *sandpile {\n b := [9]int{}\n for i := 0; i < 9; i++ {\n b[i] = s.a[i] + other.a[i]\n }\n return &sandpile{b}\n}\n\nfunc (s *sandpile) isStable() bool {\n for _, e := range s.a {\n if e > 3 {\n return false\n }\n }\n return true\n}\n\n// just topples once so we can observe intermediate results\nfunc (s *sandpile) topple() {\n for i := 0; i < 9; i++ {\n if s.a[i] > 3 {\n s.a[i] -= 4\n for _, j := range neighbors[i] {\n s.a[j]++\n }\n return\n }\n }\n}\n\nfunc (s *sandpile) String() string {\n var sb strings.Builder\n for i := 0; i < 3; i++ {\n for j := 0; j < 3; j++ {\n sb.WriteString(strconv.Itoa(s.a[3*i+j]) + \" \")\n }\n sb.WriteString(\"\\n\")\n }\n return sb.String()\n}\n\nfunc main() {\n fmt.Println(\"Avalanche of topplings:\\n\")\n s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})\n fmt.Println(s4)\n for !s4.isStable() {\n s4.topple()\n fmt.Println(s4)\n }\n\n fmt.Println(\"Commutative additions:\\n\")\n s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})\n s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})\n s3_a := s1.plus(s2)\n for !s3_a.isStable() {\n s3_a.topple()\n }\n s3_b := s2.plus(s1)\n for !s3_b.isStable() {\n s3_b.topple()\n }\n fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s1, s2, s3_a)\n fmt.Printf(\"and\\n\\n%s\\nplus\\n\\n%s\\nalso equals\\n\\n%s\\n\", s2, s1, s3_b)\n\n fmt.Println(\"Addition of identity sandpile:\\n\")\n s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})\n s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})\n s4 = s3.plus(s3_id)\n for !s4.isStable() {\n s4.topple()\n }\n fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\\n\", s3, s3_id, s4)\n\n fmt.Println(\"Addition of identities:\\n\")\n s5 := s3_id.plus(s3_id)\n for !s5.isStable() {\n s5.topple()\n }\n fmt.Printf(\"%s\\nplus\\n\\n%s\\nequals\\n\\n%s\", s3_id, s3_id, s5)\n}"} {"title": "Abundant odd numbers", "language": "Go", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\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(divs2) - 1; i >= 0; i-- {\n divs = append(divs, divs2[i])\n }\n return divs\n}\n\nfunc sum(divs []int) int {\n tot := 0\n for _, div := range divs {\n tot += div\n }\n return tot\n}\n\nfunc sumStr(divs []int) string {\n s := \"\"\n for _, div := range divs {\n s += strconv.Itoa(div) + \" + \"\n }\n return s[0 : len(s)-3]\n}\n\nfunc abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {\n count := countFrom\n n := searchFrom\n for ; count < countTo; n += 2 {\n divs := divisors(n)\n if tot := sum(divs); tot > n {\n count++\n if printOne && count < countTo {\n continue\n } \n s := sumStr(divs)\n if !printOne {\n fmt.Printf(\"%2d. %5d < %s = %d\\n\", count, n, s, tot)\n } else {\n fmt.Printf(\"%d < %s = %d\\n\", n, s, tot)\n }\n }\n }\n return n\n}\n\nfunc main() {\n const max = 25\n fmt.Println(\"The first\", max, \"abundant odd numbers are:\")\n n := abundantOdd(1, 0, 25, false)\n\n fmt.Println(\"\\nThe one thousandth abundant odd number is:\")\n abundantOdd(n, 25, 1000, true)\n\n fmt.Println(\"\\nThe first abundant odd number above one billion is:\")\n abundantOdd(1e9+1, 0, 1, true)\n}"} {"title": "Accumulator factory", "language": "Go", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc accumulator(sum interface{}) func(interface{}) interface{} {\n return func(nv interface{}) interface{} {\n switch s := sum.(type) {\n case int:\n switch n := nv.(type) {\n case int:\n sum = s + n\n case float64:\n sum = float64(s) + n\n }\n case float64:\n switch n := nv.(type) {\n case int:\n sum = s + float64(n)\n case float64:\n sum = s + n\n }\n default:\n sum = nv\n }\n return sum\n }\n}\n\nfunc main() {\n x := accumulator(1)\n x(5)\n accumulator(3)\n fmt.Println(x(2.3))\n}"} {"title": "Achilles numbers", "language": "Go from Wren", "task": "{{Wikipedia|Achilles number}}\n\n\nAn '''Achilles number''' is a number that is powerful but imperfect. ''Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.''\n\n\nA positive integer '''n''' is a powerful number if, for every prime factor '''p''' of '''n''', '''p2''' is also a divisor.\n\nIn other words, every prime factor appears at least squared in the factorization.\n\nAll '''Achilles numbers''' are powerful. However, not all powerful numbers are '''Achilles numbers''': only those that cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1'''.\n\n\nA '''''strong'' Achilles number''' is an '''Achilles number''' whose '''Euler totient ()''' is also an '''Achilles number'''.\n\n\n\n;E.G.\n\n'''108''' is a powerful number. Its prime factorization is '''22 x 33''', and thus its prime factors are '''2''' and '''3'''. Both '''22 = 4''' and '''32 = 9''' are divisors of '''108'''. However, '''108''' cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1''', so '''108''' is an '''Achilles number'''.\n\n'''360''' is ''not'' an '''Achilles number''' because it is not powerful. One of its prime factors is '''5''' but '''360''' is not divisible by '''52 = 25'''.\n\nFinally, '''784''' is ''not'' an '''Achilles number'''. It is a powerful number, because not only are '''2''' and '''7''' its only prime factors, but also '''22 = 4''' and '''72 = 49''' are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is ''not'' an '''Achilles number'''.\n\n\n'''500 = 22 x 53''' is a '''''strong'' Achilles number''' as its Euler totient, '''(500)''', is '''200 = 23 x 52''' which is ''also'' an '''Achilles number'''.\n\n\n\n;Task\n\n* Find and show the first 50 '''Achilles numbers'''.\n* Find and show at least the first 20 '''''strong'' Achilles numbers'''.\n* For at least 2 through 5, show the count of '''Achilles numbers''' with that many digits.\n\n\n;See also\n\n;* Wikipedia: Achilles number\n;* OEIS:A052486 - Achilles numbers - powerful but imperfect numbers\n;* OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number\n;* Related task: Powerful numbers\n;* Related task: Totient function\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"sort\"\n)\n\nfunc totient(n int) int {\n tot := n\n i := 2\n for i*i <= n {\n if n%i == 0 {\n for n%i == 0 {\n n /= i\n }\n tot -= tot / i\n }\n if i == 2 {\n i = 1\n }\n i += 2\n }\n if n > 1 {\n tot -= tot / n\n }\n return tot\n}\n\nvar pps = make(map[int]bool)\n\nfunc getPerfectPowers(maxExp int) {\n upper := math.Pow(10, float64(maxExp))\n for i := 2; i <= int(math.Sqrt(upper)); i++ {\n fi := float64(i)\n p := fi\n for {\n p *= fi\n if p >= upper {\n break\n }\n pps[int(p)] = true\n }\n }\n}\n\nfunc getAchilles(minExp, maxExp int) map[int]bool {\n lower := math.Pow(10, float64(minExp))\n upper := math.Pow(10, float64(maxExp))\n achilles := make(map[int]bool)\n for b := 1; b <= int(math.Cbrt(upper)); b++ {\n b3 := b * b * b\n for a := 1; a <= int(math.Sqrt(upper)); a++ {\n p := b3 * a * a\n if p >= int(upper) {\n break\n }\n if p >= int(lower) {\n if _, ok := pps[p]; !ok {\n achilles[p] = true\n }\n }\n }\n }\n return achilles\n}\n\nfunc main() {\n maxDigits := 15\n getPerfectPowers(maxDigits)\n achillesSet := getAchilles(1, 5) // enough for first 2 parts\n achilles := make([]int, len(achillesSet))\n i := 0\n for k := range achillesSet {\n achilles[i] = k\n i++\n }\n sort.Ints(achilles)\n\n fmt.Println(\"First 50 Achilles numbers:\")\n for i = 0; i < 50; i++ {\n fmt.Printf(\"%4d \", achilles[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n\n fmt.Println(\"\\nFirst 30 strong Achilles numbers:\")\n var strongAchilles []int\n count := 0\n for n := 0; count < 30; n++ {\n tot := totient(achilles[n])\n if _, ok := achillesSet[tot]; ok {\n strongAchilles = append(strongAchilles, achilles[n])\n count++\n }\n }\n for i = 0; i < 30; i++ {\n fmt.Printf(\"%5d \", strongAchilles[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n\n fmt.Println(\"\\nNumber of Achilles numbers with:\")\n for d := 2; d <= maxDigits; d++ {\n ac := len(getAchilles(d-1, d))\n fmt.Printf(\"%2d digits: %d\\n\", d, ac)\n }\n}"} {"title": "Aliquot sequence classifications", "language": "Go from Kotlin", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"strings\"\n)\n\nconst threshold = uint64(1) << 47\n\nfunc indexOf(s []uint64, search uint64) int {\n for i, e := range s {\n if e == search {\n return i\n }\n }\n return -1\n}\n\nfunc contains(s []uint64, search uint64) bool {\n return indexOf(s, search) > -1\n}\n\nfunc maxOf(i1, i2 int) int {\n if i1 > i2 {\n return i1\n }\n return i2\n}\n\nfunc sumProperDivisors(n uint64) uint64 {\n if n < 2 {\n return 0\n }\n sqrt := uint64(math.Sqrt(float64(n)))\n sum := uint64(1)\n for i := uint64(2); i <= sqrt; i++ {\n if n % i != 0 {\n continue\n }\n sum += i + n / i\n }\n if sqrt * sqrt == n {\n sum -= sqrt\n }\n return sum\n}\n\nfunc classifySequence(k uint64) ([]uint64, string) {\n if k == 0 {\n panic(\"Argument must be positive.\")\n }\n last := k\n var seq []uint64\n seq = append(seq, k)\n for {\n last = sumProperDivisors(last)\n seq = append(seq, last)\n n := len(seq)\n aliquot := \"\"\n switch {\n case last == 0:\n aliquot = \"Terminating\"\n case n == 2 && last == k:\n aliquot = \"Perfect\"\n case n == 3 && last == k:\n aliquot = \"Amicable\"\n case n >= 4 && last == k:\n aliquot = fmt.Sprintf(\"Sociable[%d]\", n - 1)\n case last == seq[n - 2]:\n aliquot = \"Aspiring\"\n case contains(seq[1 : maxOf(1, n - 2)], last):\n aliquot = fmt.Sprintf(\"Cyclic[%d]\", n - 1 - indexOf(seq[:], last))\n case n == 16 || last > threshold:\n aliquot = \"Non-Terminating\"\n }\n if aliquot != \"\" {\n return seq, aliquot\n }\n }\n}\n\nfunc joinWithCommas(seq []uint64) string {\n res := fmt.Sprint(seq)\n res = strings.Replace(res, \" \", \", \", -1)\n return res\n}\n\nfunc main() {\n fmt.Println(\"Aliquot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n for k := uint64(1); k <= 10; k++ {\n seq, aliquot := classifySequence(k)\n fmt.Printf(\"%2d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n }\n fmt.Println()\n\n s := []uint64{\n 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,\n }\n for _, k := range s {\n seq, aliquot := classifySequence(k)\n fmt.Printf(\"%7d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n }\n fmt.Println()\n\n k := uint64(15355717786080)\n seq, aliquot := classifySequence(k)\n fmt.Printf(\"%d: %-15s %s\\n\", k, aliquot, joinWithCommas(seq))\n}"} {"title": "Almkvist-Giullera formula for pi", "language": "Go from Wren", "task": "The Almkvist-Giullera formula for calculating 1/p2 is based on the Calabi-Yau\ndifferential equations of order 4 and 5, which were originally used to describe certain manifolds\nin string theory. \n\n\nThe formula is:\n::::: 1/p2 = (25/3) 0 ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1\n\n\nThis formula can be used to calculate the constant p-2, and thus to calculate p.\n\nNote that, because the product of all terms but the power of 1000 can be calculated as an integer,\nthe terms in the series can be separated into a large integer term:\n\n::::: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)\n\nmultiplied by a negative integer power of 10:\n\n::::: 10-(6n + 3) \n\n\n;Task:\n:* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.\n:* Use the complete formula to calculate and print p to 70 decimal digits of precision.\n\n\n;Reference:\n:* Gert Almkvist and Jesus Guillera, Ramanujan-like series for 1/p2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"strings\"\n)\n\nfunc factorial(n int64) *big.Int {\n var z big.Int\n return z.MulRange(1, n)\n}\n\nvar one = big.NewInt(1)\nvar three = big.NewInt(3)\nvar six = big.NewInt(6)\nvar ten = big.NewInt(10)\nvar seventy = big.NewInt(70)\n\nfunc almkvistGiullera(n int64, print bool) *big.Rat {\n t1 := big.NewInt(32)\n t1.Mul(factorial(6*n), t1)\n t2 := big.NewInt(532*n*n + 126*n + 9)\n t3 := new(big.Int)\n t3.Exp(factorial(n), six, nil)\n t3.Mul(t3, three)\n ip := new(big.Int)\n ip.Mul(t1, t2)\n ip.Quo(ip, t3)\n pw := 6*n + 3\n t1.SetInt64(pw)\n tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))\n if print {\n fmt.Printf(\"%d %44d %3d %-35s\\n\", n, ip, -pw, tm.FloatString(33))\n }\n return tm\n}\n\nfunc main() {\n fmt.Println(\"N Integer Portion Pow Nth Term (33 dp)\")\n fmt.Println(strings.Repeat(\"-\", 89))\n for n := int64(0); n < 10; n++ {\n almkvistGiullera(n, true)\n }\n\n sum := new(big.Rat)\n prev := new(big.Rat)\n pow70 := new(big.Int).Exp(ten, seventy, nil)\n prec := new(big.Rat).SetFrac(one, pow70)\n n := int64(0)\n for {\n term := almkvistGiullera(n, false)\n sum.Add(sum, term)\n z := new(big.Rat).Sub(sum, prev)\n z.Abs(z)\n if z.Cmp(prec) < 0 {\n break\n }\n prev.Set(sum)\n n++\n }\n sum.Inv(sum)\n pi := new(big.Float).SetPrec(256).SetRat(sum)\n pi.Sqrt(pi)\n fmt.Println(\"\\nPi to 70 decimal places is:\")\n fmt.Println(pi.Text('f', 70))\n}"} {"title": "Amb", "language": "Go", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n)\n\nfunc ambStrings(ss []string) chan []string {\n c := make(chan []string)\n go func() {\n for _, s := range ss {\n c <- []string{s}\n }\n close(c)\n }()\n return c\n}\n\nfunc ambChain(ss []string, cIn chan []string) chan []string {\n cOut := make(chan []string)\n go func() {\n var w sync.WaitGroup\n for chain := range cIn {\n w.Add(1)\n go func(chain []string) {\n for s1 := range ambStrings(ss) {\n if s1[0][len(s1[0])-1] == chain[0][0] {\n cOut <- append(s1, chain...)\n }\n }\n w.Done()\n }(chain)\n }\n w.Wait()\n close(cOut)\n }()\n return cOut\n}\n\nfunc main() {\n s1 := []string{\"the\", \"that\", \"a\"}\n s2 := []string{\"frog\", \"elephant\", \"thing\"}\n s3 := []string{\"walked\", \"treaded\", \"grows\"}\n s4 := []string{\"slowly\", \"quickly\"}\n c := ambChain(s1, ambChain(s2, ambChain(s3, ambStrings(s4))))\n for s := range c {\n fmt.Println(s)\n }\n}"} {"title": "Anagrams/Deranged anagrams", "language": "Go", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "package main\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strings\"\n\t\"sort\"\n)\n\nfunc deranged(a, b string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range(a) {\n\t\tif a[i] == b[i] { return false }\n\t}\n\treturn true\n}\n\nfunc main() {\n\t/* read the whole thing in. how big can it be? */\n\tbuf, _ := ioutil.ReadFile(\"unixdict.txt\")\n\twords := strings.Split(string(buf), \"\\n\")\n\n\tm := make(map[string] []string)\n\tbest_len, w1, w2 := 0, \"\", \"\"\n\n\tfor _, w := range(words) {\n\t\t// don't bother: too short to beat current record\n\t\tif len(w) <= best_len { continue }\n\n\t\t// save strings in map, with sorted string as key\n\t\tletters := strings.Split(w, \"\")\n\t\tsort.Strings(letters)\n\t\tk := strings.Join(letters, \"\")\n\n\t\tif _, ok := m[k]; !ok {\n\t\t\tm[k] = []string { w }\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, c := range(m[k]) {\n\t\t\tif deranged(w, c) {\n\t\t\t\tbest_len, w1, w2 = len(w), c, w\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tm[k] = append(m[k], w)\n\t}\n\n\tfmt.Println(w1, w2, \": Length\", best_len)\n}"} {"title": "Angle difference between two bearings", "language": "Go", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype bearing float64\n\nvar testCases = []struct{ b1, b2 bearing }{\n {20, 45},\n {-45, 45},\n {-85, 90},\n {-95, 90},\n {-45, 125},\n {-45, 145},\n {29.4803, -88.6381},\n {-78.3251, -159.036},\n}\n\nfunc main() {\n for _, tc := range testCases {\n fmt.Println(tc.b2.Sub(tc.b1))\n }\n}\n\nfunc (b2 bearing) Sub(b1 bearing) bearing {\n switch d := b2 - b1; {\n case d < -180:\n return d + 360\n case d > 180:\n return d - 360\n default:\n return d\n }\n}"} {"title": "Anti-primes", "language": "Go", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n if n < 2 {\n return 1\n }\n count := 2 // 1 and n\n for i := 2; i <= n/2; i++ {\n if n%i == 0 {\n count++\n }\n }\n return count\n}\n\nfunc main() {\n fmt.Println(\"The first 20 anti-primes are:\")\n maxDiv := 0\n count := 0\n for n := 1; count < 20; n++ {\n d := countDivisors(n)\n if d > maxDiv {\n fmt.Printf(\"%d \", n)\n maxDiv = d\n count++\n }\n }\n fmt.Println()\n}"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Go", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype filter struct {\n b, a []float64\n}\n\nfunc (f filter) filter(in []float64) []float64 {\n out := make([]float64, len(in))\n s := 1. / f.a[0]\n for i := range in {\n tmp := 0.\n b := f.b\n if i+1 < len(b) {\n b = b[:i+1]\n }\n for j, bj := range b {\n tmp += bj * in[i-j]\n }\n a := f.a[1:]\n if i < len(a) {\n a = a[:i]\n }\n for j, aj := range a {\n tmp -= aj * out[i-j-1]\n }\n out[i] = tmp * s\n }\n return out\n}\n\n//Constants for a Butterworth filter (order 3, low pass)\nvar bwf = filter{\n a: []float64{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17},\n b: []float64{0.16666667, 0.5, 0.5, 0.16666667},\n}\n\nvar sig = []float64{\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589,\n}\n\nfunc main() {\n for _, v := range bwf.filter(sig) {\n fmt.Printf(\"%9.6f\\n\", v)\n }\n}"} {"title": "Approximate equality", "language": "Go", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\nfunc max(a, b *big.Float) *big.Float {\n if a.Cmp(b) > 0 {\n return a\n }\n return b\n}\n\nfunc isClose(a, b *big.Float) bool {\n relTol := big.NewFloat(1e-9) // same as default for Python's math.isclose() function\n t := new(big.Float)\n t.Sub(a, b)\n t.Abs(t)\n u, v, w := new(big.Float), new(big.Float), new(big.Float)\n u.Mul(relTol, max(v.Abs(a), w.Abs(b)))\n return t.Cmp(u) <= 0\n}\n\nfunc nbf(s string) *big.Float {\n n, ok := new(big.Float).SetString(s)\n if !ok {\n log.Fatal(\"invalid floating point number\")\n }\n return n\n}\n\nfunc main() {\n root2 := big.NewFloat(2.0)\n root2.Sqrt(root2)\n pairs := [][2]*big.Float{\n {nbf(\"100000000000000.01\"), nbf(\"100000000000000.011\")},\n {nbf(\"100.01\"), nbf(\"100.011\")},\n {nbf(\"0\").Quo(nbf(\"10000000000000.001\"), nbf(\"10000.0\")), nbf(\"1000000000.0000001000\")},\n {nbf(\"0.001\"), nbf(\"0.0010000001\")},\n {nbf(\"0.000000000000000000000101\"), nbf(\"0.0\")},\n {nbf(\"0\").Mul(root2, root2), nbf(\"2.0\")},\n {nbf(\"0\").Mul(nbf(\"0\").Neg(root2), root2), nbf(\"-2.0\")},\n {nbf(\"100000000000000003.0\"), nbf(\"100000000000000004.0\")},\n {nbf(\"3.14159265358979323846\"), nbf(\"3.14159265358979324\")},\n }\n for _, pair := range pairs {\n s := \"\u2249\"\n if isClose(pair[0], pair[1]) {\n s = \"\u2248\"\n }\n fmt.Printf(\"% 21.19g %s %- 21.19g\\n\", pair[0], s, pair[1])\n }\n}"} {"title": "Arena storage pool", "language": "Go", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"runtime\"\n \"sync\"\n)\n\n// New to Go 1.3 are sync.Pools, basically goroutine-safe free lists.\n// There is overhead in the goroutine-safety and if you do not need this\n// you might do better by implementing your own free list.\n\nfunc main() {\n // Task 1: Define a pool (of ints). Just as the task says, a sync.Pool\n // allocates individually and can free as a group.\n p := sync.Pool{New: func() interface{} {\n fmt.Println(\"pool empty\")\n return new(int)\n }}\n // Task 2: Allocate some ints.\n i := new(int)\n j := new(int)\n // Show that they're usable.\n *i = 1\n *j = 2\n fmt.Println(*i + *j) // prints 3\n // Task 2 continued: Put allocated ints in pool p.\n // Task explanation: Variable p has a pool as its value. Another pool\n // could be be created and assigned to a different variable. You choose\n // a pool simply by using the appropriate variable, p here.\n p.Put(i)\n p.Put(j)\n // Drop references to i and j. This allows them to be garbage collected;\n // that is, freed as a group.\n i = nil\n j = nil\n // Get ints for i and j again, this time from the pool. P.Get may reuse\n // an object allocated above as long as objects haven't been garbage\n // collected yet; otherwise p.Get will allocate a new object.\n i = p.Get().(*int)\n j = p.Get().(*int)\n *i = 4\n *j = 5\n fmt.Println(*i + *j) // prints 9\n // One more test, this time forcing a garbage collection.\n p.Put(i)\n p.Put(j)\n i = nil\n j = nil\n runtime.GC()\n i = p.Get().(*int)\n j = p.Get().(*int)\n *i = 7\n *j = 8\n fmt.Println(*i + *j) // prints 15\n}"} {"title": "Arithmetic-geometric mean", "language": "Go", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst \u03b5 = 1e-14\n\nfunc agm(a, g float64) float64 {\n for math.Abs(a-g) > math.Abs(a)*\u03b5 {\n a, g = (a+g)*.5, math.Sqrt(a*g)\n }\n return a\n}\n\nfunc main() {\n fmt.Println(agm(1, 1/math.Sqrt2))\n}"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Go", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n one := big.NewFloat(1)\n two := big.NewFloat(2)\n four := big.NewFloat(4)\n prec := uint(768) // say\n\n a := big.NewFloat(1).SetPrec(prec)\n g := new(big.Float).SetPrec(prec)\n\n // temporary variables\n t := new(big.Float).SetPrec(prec)\n u := new(big.Float).SetPrec(prec)\n\n g.Quo(a, t.Sqrt(two))\n sum := new(big.Float)\n pow := big.NewFloat(2)\n\n for a.Cmp(g) != 0 {\n t.Add(a, g)\n t.Quo(t, two)\n g.Sqrt(u.Mul(a, g))\n a.Set(t)\n pow.Mul(pow, two)\n t.Sub(t.Mul(a, a), u.Mul(g, g))\n sum.Add(sum, t.Mul(t, pow))\n }\n\n t.Mul(a, a)\n t.Mul(t, four)\n pi := t.Quo(t, u.Sub(one, sum))\n fmt.Println(pi)\n}"} {"title": "Arithmetic numbers", "language": "Go from Wren", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"rcu\"\n \"sort\"\n)\n\nfunc main() {\n arithmetic := []int{1}\n primes := []int{}\n limit := int(1e6)\n for n := 3; len(arithmetic) < limit; n++ {\n divs := rcu.Divisors(n)\n if len(divs) == 2 {\n primes = append(primes, n)\n arithmetic = append(arithmetic, n)\n } else {\n mean := float64(rcu.SumInts(divs)) / float64(len(divs))\n if mean == math.Trunc(mean) {\n arithmetic = append(arithmetic, n)\n }\n }\n }\n fmt.Println(\"The first 100 arithmetic numbers are:\")\n rcu.PrintTable(arithmetic[0:100], 10, 3, false)\n\n for _, x := range []int{1e3, 1e4, 1e5, 1e6} {\n last := arithmetic[x-1]\n lastc := rcu.Commatize(last)\n fmt.Printf(\"\\nThe %sth arithmetic number is: %s\\n\", rcu.Commatize(x), lastc)\n pcount := sort.SearchInts(primes, last) + 1\n if !rcu.IsPrime(last) {\n pcount--\n }\n comp := x - pcount - 1 // 1 is not composite\n compc := rcu.Commatize(comp)\n fmt.Printf(\"The count of such numbers <= %s which are composite is %s.\\n\", lastc, compc)\n }\n}"} {"title": "Array length", "language": "Go", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tarr := [...]string{\"apple\", \"orange\", \"pear\"}\n\n\tfmt.Printf(\"Length of %v is %v.\\n\", arr, len(arr))\n}"} {"title": "Associative array/Merging", "language": "Go", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype assoc map[string]interface{}\n\nfunc merge(base, update assoc) assoc {\n result := make(assoc)\n for k, v := range base {\n result[k] = v\n }\n for k, v := range update {\n result[k] = v\n }\n return result\n}\n\nfunc main() {\n base := assoc{\"name\": \"Rocket Skates\", \"price\": 12.75, \"color\": \"yellow\"}\n update := assoc{\"price\": 15.25, \"color\": \"red\", \"year\": 1974}\n result := merge(base, update)\n fmt.Println(result)\n}"} {"title": "Attractive numbers", "language": "Go", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc isPrime(n int) bool {\n switch {\n case n < 2:\n return false\n case n%2 == 0:\n return n == 2\n case n%3 == 0:\n return n == 3\n default:\n d := 5\n for d*d <= n {\n if n%d == 0 {\n return false\n }\n d += 2\n if n%d == 0 {\n return false\n }\n d += 4\n }\n return true\n }\n}\n\nfunc countPrimeFactors(n int) int {\n switch {\n case n == 1:\n return 0\n case isPrime(n):\n return 1\n default:\n count, f := 0, 2\n for {\n if n%f == 0 {\n count++\n n /= f\n if n == 1 {\n return count\n }\n if isPrime(n) {\n f = n\n }\n } else if f >= 3 {\n f += 2\n } else {\n f = 3\n }\n }\n return count\n }\n}\n\nfunc main() {\n const max = 120\n fmt.Println(\"The attractive numbers up to and including\", max, \"are:\")\n count := 0\n for i := 1; i <= max; i++ {\n n := countPrimeFactors(i)\n if isPrime(n) {\n fmt.Printf(\"%4d\", i)\n count++\n if count % 20 == 0 {\n fmt.Println()\n }\n } \n }\n fmt.Println()\n}"} {"title": "Average loop length", "language": "Go", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n)\n\nconst nmax = 20\n\nfunc main() {\n fmt.Println(\" N average analytical (error)\")\n fmt.Println(\"=== ========= ============ =========\")\n for n := 1; n <= nmax; n++ {\n a := avg(n)\n b := ana(n)\n fmt.Printf(\"%3d %9.4f %12.4f (%6.2f%%)\\n\",\n n, a, b, math.Abs(a-b)/b*100)\n }\n}\n\nfunc avg(n int) float64 {\n const tests = 1e4\n sum := 0\n for t := 0; t < tests; t++ {\n var v [nmax]bool\n for x := 0; !v[x]; x = rand.Intn(n) {\n v[x] = true\n sum++\n }\n }\n return float64(sum) / tests\n}\n\nfunc ana(n int) float64 {\n nn := float64(n)\n term := 1.\n sum := 1.\n for i := nn - 1; i >= 1; i-- {\n term *= i / nn\n sum += term\n }\n return sum\n}"} {"title": "Averages/Mean angle", "language": "Go", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/cmplx\"\n)\n\nfunc deg2rad(d float64) float64 { return d * math.Pi / 180 }\nfunc rad2deg(r float64) float64 { return r * 180 / math.Pi }\n\nfunc mean_angle(deg []float64) float64 {\n\tsum := 0i\n\tfor _, x := range deg {\n\t\tsum += cmplx.Rect(1, deg2rad(x))\n\t}\n\treturn rad2deg(cmplx.Phase(sum))\n}\n\nfunc main() {\n\tfor _, angles := range [][]float64{\n\t\t{350, 10},\n\t\t{90, 180, 270, 360},\n\t\t{10, 20, 30},\n\t} {\n\t\tfmt.Printf(\"The mean angle of %v is: %f degrees\\n\", angles, mean_angle(angles))\n\t}\n}"} {"title": "Averages/Pythagorean means", "language": "Go", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n sum, sumr, prod := 0., 0., 1.\n for n := 1.; n <= 10; n++ {\n sum += n\n sumr += 1 / n\n prod *= n\n }\n a, g, h := sum/10, math.Pow(prod, .1), 10/sumr\n fmt.Println(\"A:\", a, \"G:\", g, \"H:\", h)\n fmt.Println(\"A >= G >= H:\", a >= g && g >= h)\n}"} {"title": "Averages/Root mean square", "language": "Go", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n const n = 10\n sum := 0.\n for x := 1.; x <= n; x++ {\n sum += x * x\n }\n fmt.Println(math.Sqrt(sum / n))\n}"} {"title": "Babbage problem", "language": "Go", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tconst (\n\t\ttarget = 269696\n\t\tmodulus = 1000000\n\t)\n\tfor n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...\n\t\tsquare := n * n\n\t\tending := square % modulus\n\t\tif ending == target {\n\t\t\tfmt.Println(\"The smallest number whose square ends with\",\n\t\t\t\ttarget, \"is\", n,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t}\n}"} {"title": "Balanced brackets", "language": "Go", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nfunc init() {\n rand.Seed(time.Now().UnixNano())\n}\n\nfunc generate(n uint) string {\n a := bytes.Repeat([]byte(\"[]\"), int(n))\n for i := len(a) - 1; i >= 1; i-- {\n j := rand.Intn(i + 1)\n a[i], a[j] = a[j], a[i]\n }\n return string(a)\n}\n\nfunc testBalanced(s string) {\n fmt.Print(s + \": \")\n open := 0\n for _,c := range s {\n switch c {\n case '[':\n open++\n case ']':\n if open == 0 {\n fmt.Println(\"not ok\")\n return\n }\n open--\n default:\n fmt.Println(\"not ok\")\n return\n }\n }\n if open == 0 {\n fmt.Println(\"ok\")\n } else {\n fmt.Println(\"not ok\")\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n for i := uint(0); i < 10; i++ {\n testBalanced(generate(i))\n }\n testBalanced(\"()\")\n}"} {"title": "Balanced ternary", "language": "Go", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\n// R1: representation is a slice of int8 digits of -1, 0, or 1.\n// digit at index 0 is least significant. zero value of type is\n// representation of the number 0.\ntype bt []int8\n\n// R2: string conversion:\n\n// btString is a constructor. valid input is a string of any length\n// consisting of only '+', '-', and '0' characters.\n// leading zeros are allowed but are trimmed and not represented.\n// false return means input was invalid.\nfunc btString(s string) (*bt, bool) {\n s = strings.TrimLeft(s, \"0\")\n b := make(bt, len(s))\n for i, last := 0, len(s)-1; i < len(s); i++ {\n switch s[i] {\n case '-':\n b[last-i] = -1\n case '0':\n b[last-i] = 0\n case '+':\n b[last-i] = 1\n default:\n return nil, false\n }\n }\n return &b, true\n}\n\n// String method converts the other direction, returning a string of\n// '+', '-', and '0' characters representing the number.\nfunc (b bt) String() string {\n if len(b) == 0 {\n return \"0\"\n }\n last := len(b) - 1\n r := make([]byte, len(b))\n for i, d := range b {\n r[last-i] = \"-0+\"[d+1]\n }\n return string(r)\n}\n\n// R3: integer conversion\n// int chosen as \"native integer\"\n\n// btInt is a constructor like btString.\nfunc btInt(i int) *bt {\n if i == 0 {\n return new(bt)\n }\n var b bt\n var btDigit func(int)\n btDigit = func(digit int) {\n m := int8(i % 3)\n i /= 3\n switch m {\n case 2:\n m = -1\n i++\n case -2:\n m = 1\n i--\n }\n if i == 0 {\n b = make(bt, digit+1)\n } else {\n btDigit(digit + 1)\n }\n b[digit] = m\n }\n btDigit(0)\n return &b\n}\n\n// Int method converts the other way, returning the value as an int type.\n// !ok means overflow occurred during conversion, not necessarily that the\n// value is not representable as an int. (Of course there are other ways\n// of doing it but this was chosen as \"reasonable.\")\nfunc (b bt) Int() (r int, ok bool) {\n pt := 1\n for _, d := range b {\n dp := int(d) * pt\n neg := r < 0\n r += dp\n if neg {\n if r > dp {\n return 0, false\n }\n } else {\n if r < dp {\n return 0, false\n }\n }\n pt *= 3\n }\n return r, true\n}\n\n// R4: negation, addition, and multiplication\n \nfunc (z *bt) Neg(b *bt) *bt {\n if z != b {\n if cap(*z) < len(*b) {\n *z = make(bt, len(*b))\n } else {\n *z = (*z)[:len(*b)]\n } \n }\n for i, d := range *b {\n (*z)[i] = -d\n }\n return z \n}\n\nfunc (z *bt) Add(a, b *bt) *bt {\n if len(*a) < len(*b) {\n a, b = b, a\n }\n r := *z\n r = r[:cap(r)]\n var carry int8 \n for i, da := range *a {\n if i == len(r) {\n n := make(bt, len(*a)+4)\n copy(n, r)\n r = n\n }\n sum := da + carry\n if i < len(*b) {\n sum += (*b)[i]\n }\n carry = sum / 3\n sum %= 3\n switch {\n case sum > 1:\n sum -= 3\n carry++\n case sum < -1:\n sum += 3\n carry--\n } \n r[i] = sum \n }\n last := len(*a)\n if carry != 0 {\n if len(r) == last {\n n := make(bt, last+4)\n copy(n, r)\n r = n\n }\n r[last] = carry\n *z = r[:last+1]\n return z\n }\n for {\n if last == 0 {\n *z = nil\n break\n }\n last--\n if r[last] != 0 {\n *z = r[:last+1]\n break\n }\n }\n return z\n}\n\nfunc (z *bt) Mul(a, b *bt) *bt {\n if len(*a) < len(*b) {\n a, b = b, a\n }\n var na bt\n for _, d := range *b {\n if d == -1 {\n na.Neg(a)\n break\n }\n }\n r := make(bt, len(*a)+len(*b))\n for i := len(*b) - 1; i >= 0; i-- {\n switch (*b)[i] {\n case 1:\n p := r[i:]\n p.Add(&p, a)\n case -1:\n p := r[i:]\n p.Add(&p, &na)\n }\n }\n i := len(r)\n for i > 0 && r[i-1] == 0 {\n i--\n }\n *z = r[:i]\n return z\n}\n\nfunc main() {\n a, _ := btString(\"+-0++0+\")\n b := btInt(-436)\n c, _ := btString(\"+-++-\")\n show(\"a:\", a) \n show(\"b:\", b)\n show(\"c:\", c)\n show(\"a(b-c):\", a.Mul(a, b.Add(b, c.Neg(c))))\n} \n\nfunc show(label string, b *bt) {\n fmt.Printf(\"%7s %12v \", label, b)\n if i, ok := b.Int(); ok {\n fmt.Printf(\"%7d\\n\", i)\n } else {\n fmt.Println(\"int overflow\")\n }\n}"} {"title": "Barnsley fern", "language": "Go", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "package main\n\nimport (\n \"image\"\n \"image/color\"\n \"image/draw\"\n \"image/png\"\n \"log\"\n \"math/rand\"\n \"os\"\n)\n\n// values from WP\nconst (\n xMin = -2.1820\n xMax = 2.6558\n yMin = 0.\n yMax = 9.9983\n)\n\n// parameters\nvar (\n width = 200\n n = int(1e6)\n c = color.RGBA{34, 139, 34, 255} // forest green\n)\n\nfunc main() {\n dx := xMax - xMin\n dy := yMax - yMin\n fw := float64(width)\n fh := fw * dy / dx\n height := int(fh)\n r := image.Rect(0, 0, width, height)\n img := image.NewRGBA(r)\n draw.Draw(img, r, &image.Uniform{color.White}, image.ZP, draw.Src)\n var x, y float64\n plot := func() {\n // transform computed float x, y to integer image coordinates\n ix := int(fw * (x - xMin) / dx)\n iy := int(fh * (yMax - y) / dy)\n img.SetRGBA(ix, iy, c)\n }\n plot()\n for i := 0; i < n; i++ {\n switch s := rand.Intn(100); {\n case s < 85:\n x, y =\n .85*x+.04*y,\n -.04*x+.85*y+1.6\n case s < 85+7:\n x, y =\n .2*x-.26*y,\n .23*x+.22*y+1.6\n case s < 85+7+7:\n x, y =\n -.15*x+.28*y,\n .26*x+.24*y+.44\n default:\n x, y = 0, .16*y\n }\n plot()\n }\n // write img to png file\n f, err := os.Create(\"bf.png\")\n if err != nil {\n log.Fatal(err)\n }\n if err := png.Encode(f, img); err != nil {\n log.Fatal(err)\n }\n}"} {"title": "Base64 decode data", "language": "Go", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "package main\n\nimport (\n \"encoding/base64\"\n \"fmt\"\n)\n\nfunc main() {\n msg := \"Rosetta Code Base64 decode data task\"\n fmt.Println(\"Original :\", msg)\n encoded := base64.StdEncoding.EncodeToString([]byte(msg))\n fmt.Println(\"\\nEncoded :\", encoded)\n decoded, err := base64.StdEncoding.DecodeString(encoded)\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"\\nDecoded :\", string(decoded))\n}"} {"title": "Bell numbers", "language": "Go", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc bellTriangle(n int) [][]*big.Int {\n tri := make([][]*big.Int, n)\n for i := 0; i < n; i++ {\n tri[i] = make([]*big.Int, i)\n for j := 0; j < i; j++ {\n tri[i][j] = new(big.Int)\n }\n }\n tri[1][0].SetUint64(1)\n for i := 2; i < n; i++ {\n tri[i][0].Set(tri[i-1][i-2])\n for j := 1; j < i; j++ {\n tri[i][j].Add(tri[i][j-1], tri[i-1][j-1])\n }\n }\n return tri\n}\n\nfunc main() {\n bt := bellTriangle(51)\n fmt.Println(\"First fifteen and fiftieth Bell numbers:\")\n for i := 1; i <= 15; i++ {\n fmt.Printf(\"%2d: %d\\n\", i, bt[i][0])\n }\n fmt.Println(\"50:\", bt[50][0])\n fmt.Println(\"\\nThe first ten rows of Bell's triangle:\")\n for i := 1; i <= 10; i++ {\n fmt.Println(bt[i])\n } \n}"} {"title": "Benford's law", "language": "Go", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc Fib1000() []float64 {\n a, b, r := 0., 1., [1000]float64{}\n for i := range r {\n r[i], a, b = b, b, b+a\n }\n return r[:]\n}\n\nfunc main() {\n show(Fib1000(), \"First 1000 Fibonacci numbers\")\n}\n\nfunc show(c []float64, title string) {\n var f [9]int\n for _, v := range c {\n f[fmt.Sprintf(\"%g\", v)[0]-'1']++\n }\n fmt.Println(title)\n fmt.Println(\"Digit Observed Predicted\")\n for i, n := range f {\n fmt.Printf(\" %d %9.3f %8.3f\\n\", i+1, float64(n)/float64(len(c)),\n math.Log10(1+1/float64(i+1)))\n }\n}"} {"title": "Best shuffle", "language": "Go from Icon and Unicon", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nvar ts = []string{\"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\", \"up\", \"a\"}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n for _, s := range ts {\n // create shuffled byte array of original string\n t := make([]byte, len(s))\n for i, r := range rand.Perm(len(s)) {\n t[i] = s[r]\n }\n // algorithm of Icon solution\n for i := range t {\n for j := range t {\n if i != j && t[i] != s[j] && t[j] != s[i] {\n t[i], t[j] = t[j], t[i]\n break\n }\n }\n }\n // count unchanged and output\n var count int\n for i, ic := range t {\n if ic == s[i] {\n count++\n }\n }\n fmt.Printf(\"%s -> %s (%d)\\n\", s, string(t), count)\n }\n}"} {"title": "Bin given limits", "language": "Go", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc getBins(limits, data []int) []int {\n n := len(limits)\n bins := make([]int, n+1)\n for _, d := range data {\n index := sort.SearchInts(limits, d) // uses binary search\n if index < len(limits) && d == limits[index] {\n index++\n }\n bins[index]++\n }\n return bins\n}\n\nfunc printBins(limits, bins []int) {\n n := len(limits)\n fmt.Printf(\" < %3d = %2d\\n\", limits[0], bins[0])\n for i := 1; i < n; i++ {\n fmt.Printf(\">= %3d and < %3d = %2d\\n\", limits[i-1], limits[i], bins[i])\n }\n fmt.Printf(\">= %3d = %2d\\n\", limits[n-1], bins[n])\n fmt.Println()\n}\n\nfunc main() {\n limitsList := [][]int{\n {23, 37, 43, 53, 67, 83},\n {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},\n }\n\n dataList := [][]int{\n {\n 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,\n 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,\n },\n {\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,\n 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,\n 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,\n 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,\n 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,\n 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,\n 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,\n 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,\n 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,\n },\n }\n\n for i := 0; i < len(limitsList); i++ {\n fmt.Println(\"Example\", i+1, \"\\b\\n\")\n bins := getBins(limitsList[i], dataList[i])\n printBins(limitsList[i], bins)\n }\n}"} {"title": "Bioinformatics/Global alignment", "language": "Go from Julia", "task": "Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the\nsequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle.\n\nCurrent DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, \"AAGATGGA\", GGAGCGCATC\", and \"ATCGCAATAAGGA\" can be assembled into the sequence \"AAGATGGAGCGCATCGCAATAAGGA\" by noting that \"GGA\" is at the tail of the first string and head of the second string and \"ATC\" likewise is at the tail\nof the second and head of the third string.\n\nWhen looking for the best global alignment in the output strings produced by DNA sequences, there are\ntypically a large number of such overlaps among a large number of sequences. In such a case, the ordering\nthat results in the shortest common superstring is generrally preferred.\n\nFinding such a supersequence is an NP-hard problem, and many algorithms have been proposed to\nshorten calculations, especially when many very long sequences are matched.\n\nThe shortest common superstring as used in bioinfomatics here differs from the string task\n[[Shortest_common_supersequence]]. In that task, a supersequence\nmay have other characters interposed as long as the characters of each subsequence appear in order,\nso that (abcbdab, abdcaba) -> abdcabdab. In this task, (abcbdab, abdcaba) -> abcbdabdcaba.\n\n\n;Task:\n:* Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences.\n\n:* Handle cases where two sequences are identical or one sequence is entirely contained in another.\n\n:* Print the resulting sequence along with its size (its base count) and a count of each base in the sequence.\n\n:* Find the shortest common superstring for the following four examples:\n: \n (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\")\n\n (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\")\n\n (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\")\n\n (\"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\")\n\n;Related tasks:\n:* Bioinformatics base count.\n:* Bioinformatics sequence mutation.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\n/* Gets n! for small n. */\nfunc factorial(n int) int {\n fact := 1\n for i := 2; i <= n; i++ {\n fact *= i\n }\n return fact\n}\n\n/* Gets all permutations of a list of strings. */\nfunc getPerms(input []string) [][]string {\n perms := [][]string{input}\n le := len(input)\n a := make([]string, le)\n copy(a, input)\n n := le - 1\n fact := factorial(n + 1)\n\n for c := 1; c < fact; c++ {\n i := n - 1\n j := n\n for i >= 0 && a[i] > a[i+1] {\n i--\n }\n if i == -1 {\n i = n\n }\n for a[j] < a[i] {\n j--\n }\n a[i], a[j] = a[j], a[i]\n j = n\n i++\n if i == n+1 {\n i = 0\n }\n for i < j {\n a[i], a[j] = a[j], a[i]\n i++\n j--\n }\n b := make([]string, le)\n copy(b, a)\n perms = append(perms, b)\n }\n return perms\n}\n\n/* Returns all distinct elements from a list of strings. */\nfunc distinct(slist []string) []string {\n distinctSet := make(map[string]int, len(slist))\n i := 0\n for _, s := range slist {\n if _, ok := distinctSet[s]; !ok {\n distinctSet[s] = i\n i++\n }\n }\n result := make([]string, len(distinctSet))\n for s, i := range distinctSet {\n result[i] = s\n }\n return result\n}\n\n/* Given a DNA sequence, report the sequence, length and base counts. */\nfunc printCounts(seq string) {\n bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}}\n for _, c := range seq {\n for _, base := range bases {\n if c == base[0] {\n base[1]++\n }\n }\n }\n sum := 0\n fmt.Println(\"\\nNucleotide counts for\", seq, \"\\b:\\n\")\n for _, base := range bases {\n fmt.Printf(\"%10c%12d\\n\", base[0], base[1])\n sum += int(base[1])\n }\n le := len(seq)\n fmt.Printf(\"%10s%12d\\n\", \"Other\", le-sum)\n fmt.Printf(\" ____________________\\n%14s%8d\\n\", \"Total length\", le)\n}\n\n/* Return the position in s1 of the start of overlap of tail of string s1 with head of string s2. */\nfunc headTailOverlap(s1, s2 string) int {\n for start := 0; ; start++ {\n ix := strings.IndexByte(s1[start:], s2[0])\n if ix == -1 {\n return 0\n } else {\n start += ix\n }\n if strings.HasPrefix(s2, s1[start:]) {\n return len(s1) - start\n }\n }\n}\n\n/* Remove duplicates and strings contained within a larger string from a list of strings. */\nfunc deduplicate(slist []string) []string {\n var filtered []string\n arr := distinct(slist)\n for i, s1 := range arr {\n withinLarger := false\n for j, s2 := range arr {\n if j != i && strings.Contains(s2, s1) {\n withinLarger = true\n break\n }\n }\n if !withinLarger {\n filtered = append(filtered, s1)\n }\n }\n return filtered\n}\n\n/* Returns shortest common superstring of a list of strings. */\nfunc shortestCommonSuperstring(slist []string) string {\n ss := deduplicate(slist)\n shortestSuper := strings.Join(ss, \"\")\n for _, perm := range getPerms(ss) {\n sup := perm[0]\n for i := 0; i < len(ss)-1; i++ {\n overlapPos := headTailOverlap(perm[i], perm[i+1])\n sup += perm[i+1][overlapPos:]\n }\n if len(sup) < len(shortestSuper) {\n shortestSuper = sup\n }\n }\n return shortestSuper\n}\n\nfunc main() {\n testSequences := [][]string{\n {\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"},\n {\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"},\n {\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"},\n {\n \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n },\n }\n\n for _, test := range testSequences {\n scs := shortestCommonSuperstring(test)\n printCounts(scs)\n }\n}"} {"title": "Bioinformatics/Sequence mutation", "language": "Go", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"sort\"\n \"time\"\n)\n\nconst bases = \"ACGT\"\n\n// 'w' contains the weights out of 300 for each\n// of swap, delete or insert in that order.\nfunc mutate(dna string, w [3]int) string {\n le := len(dna)\n // get a random position in the dna to mutate\n p := rand.Intn(le)\n // get a random number between 0 and 299 inclusive\n r := rand.Intn(300)\n bytes := []byte(dna)\n switch {\n case r < w[0]: // swap\n base := bases[rand.Intn(4)]\n fmt.Printf(\" Change @%3d %q to %q\\n\", p, bytes[p], base)\n bytes[p] = base\n case r < w[0]+w[1]: // delete\n fmt.Printf(\" Delete @%3d %q\\n\", p, bytes[p])\n copy(bytes[p:], bytes[p+1:])\n bytes = bytes[0 : le-1]\n default: // insert\n base := bases[rand.Intn(4)]\n bytes = append(bytes, 0)\n copy(bytes[p+1:], bytes[p:])\n fmt.Printf(\" Insert @%3d %q\\n\", p, base)\n bytes[p] = base\n }\n return string(bytes)\n}\n\n// Generate a random dna sequence of given length.\nfunc generate(le int) string {\n bytes := make([]byte, le)\n for i := 0; i < le; i++ {\n bytes[i] = bases[rand.Intn(4)]\n }\n return string(bytes)\n}\n\n// Pretty print dna and stats.\nfunc prettyPrint(dna string, rowLen int) {\n fmt.Println(\"SEQUENCE:\")\n le := len(dna)\n for i := 0; i < le; i += rowLen {\n k := i + rowLen\n if k > le {\n k = le\n }\n fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n }\n baseMap := make(map[byte]int) // allows for 'any' base\n for i := 0; i < le; i++ {\n baseMap[dna[i]]++\n }\n var bases []byte\n for k := range baseMap {\n bases = append(bases, k)\n }\n sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order\n return bases[i] < bases[j]\n })\n\n fmt.Println(\"\\nBASE COUNT:\")\n for _, base := range bases {\n fmt.Printf(\" %c: %3d\\n\", base, baseMap[base])\n }\n fmt.Println(\" ------\")\n fmt.Println(\" \u03a3:\", le)\n fmt.Println(\" ======\\n\")\n}\n\n// Express weights as a string.\nfunc wstring(w [3]int) string {\n return fmt.Sprintf(\" Change: %d\\n Delete: %d\\n Insert: %d\\n\", w[0], w[1], w[2])\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n dna := generate(250)\n prettyPrint(dna, 50)\n muts := 10\n w := [3]int{100, 100, 100} // use e.g. {0, 300, 0} to choose only deletions\n fmt.Printf(\"WEIGHTS (ex 300):\\n%s\\n\", wstring(w))\n fmt.Printf(\"MUTATIONS (%d):\\n\", muts)\n for i := 0; i < muts; i++ {\n dna = mutate(dna, w)\n }\n fmt.Println()\n prettyPrint(dna, 50)\n}"} {"title": "Bioinformatics/base count", "language": "Go", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc main() {\n dna := \"\" +\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\" +\n \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\" +\n \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\" +\n \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\" +\n \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\" +\n \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\" +\n \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\" +\n \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\" +\n \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\" +\n \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\n fmt.Println(\"SEQUENCE:\")\n le := len(dna)\n for i := 0; i < le; i += 50 {\n k := i + 50\n if k > le {\n k = le\n }\n fmt.Printf(\"%5d: %s\\n\", i, dna[i:k])\n }\n baseMap := make(map[byte]int) // allows for 'any' base\n for i := 0; i < le; i++ {\n baseMap[dna[i]]++\n }\n var bases []byte\n for k := range baseMap {\n bases = append(bases, k)\n }\n sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order\n return bases[i] < bases[j]\n })\n\n fmt.Println(\"\\nBASE COUNT:\")\n for _, base := range bases {\n fmt.Printf(\" %c: %3d\\n\", base, baseMap[base])\n }\n fmt.Println(\" ------\")\n fmt.Println(\" \u03a3:\", le)\n fmt.Println(\" ======\")\n}"} {"title": "Biorhythms", "language": "Go from Wren", "task": "For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in \"Things to Do with your Pocket Calculator\" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.\n\nIt's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!\n\nTo compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. \n\nThe three cycles and their lengths are as follows:\n:::{| class=\"wikitable\"\n! Cycle \n! Length\n|- \n|Physical \n| 23 days\n|- \n|Emotional \n| 28 days\n|- \n|Mental \n| 33 days\n|}\n\nThe first half of each cycle is in \"plus\" territory, with a peak at the quarter-way point; the second half in \"minus\" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called \"critical\" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.\n\nThe task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. \"up and rising\", \"peak\", \"up but falling\", \"critical\", \"down and falling\", \"valley\", \"down but rising\"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.\n\nExample run of my Raku implementation:\nraku br.raku 1943-03-09 1972-07-11\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n \"time\"\n)\n\nconst layout = \"2006-01-02\" // template for time.Parse\n\nvar cycles = [3]string{\"Physical day \", \"Emotional day\", \"Mental day \"}\nvar lengths = [3]int{23, 28, 33}\nvar quadrants = [4][2]string{\n {\"up and rising\", \"peak\"},\n {\"up but falling\", \"transition\"},\n {\"down and falling\", \"valley\"},\n {\"down but rising\", \"transition\"},\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n// Parameters assumed to be in YYYY-MM-DD format.\nfunc biorhythms(birthDate, targetDate string) {\n bd, err := time.Parse(layout, birthDate)\n check(err)\n td, err := time.Parse(layout, targetDate)\n check(err)\n days := int(td.Sub(bd).Hours() / 24)\n fmt.Printf(\"Born %s, Target %s\\n\", birthDate, targetDate)\n fmt.Println(\"Day\", days)\n for i := 0; i < 3; i++ {\n length := lengths[i]\n cycle := cycles[i]\n position := days % length\n quadrant := position * 4 / length\n percent := math.Sin(2 * math.Pi * float64(position) / float64(length))\n percent = math.Floor(percent*1000) / 10\n descript := \"\"\n if percent > 95 {\n descript = \" peak\"\n } else if percent < -95 {\n descript = \" valley\"\n } else if math.Abs(percent) < 5 {\n descript = \" critical transition\"\n } else {\n daysToAdd := (quadrant+1)*length/4 - position\n transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))\n trend := quadrants[quadrant][0]\n next := quadrants[quadrant][1]\n transStr := transition.Format(layout)\n descript = fmt.Sprintf(\"%5.1f%% (%s, next %s %s)\", percent, trend, next, transStr)\n }\n fmt.Printf(\"%s %2d : %s\\n\", cycle, position, descript)\n }\n fmt.Println()\n}\n\nfunc main() {\n datePairs := [][2]string{\n {\"1943-03-09\", \"1972-07-11\"},\n {\"1809-01-12\", \"1863-11-19\"},\n {\"1809-02-12\", \"1863-11-19\"}, // correct DOB for Abraham Lincoln\n }\n for _, datePair := range datePairs {\n biorhythms(datePair[0], datePair[1])\n }\n}"} {"title": "Bitcoin/address validation", "language": "Go from C", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"crypto/sha256\"\n \"errors\"\n \"os\"\n)\n\n// With at least one other bitcoin RC task, this source is styled more like\n// a package to show how functions of the two tasks might be combined into\n// a single package. It turns out there's not really that much shared code,\n// just the A25 type and doubleSHA256 method, but it's enough to suggest how\n// the code might be organized. Types, methods, and functions are capitalized\n// where they might be exported from a package.\n\n// A25 is a type for a 25 byte (not base58 encoded) bitcoin address.\ntype A25 [25]byte\n \nfunc (a *A25) Version() byte {\n return a[0]\n}\n \nfunc (a *A25) EmbeddedChecksum() (c [4]byte) {\n copy(c[:], a[21:])\n return\n}\n\n// DoubleSHA256 computes a double sha256 hash of the first 21 bytes of the\n// address. This is the one function shared with the other bitcoin RC task.\n// Returned is the full 32 byte sha256 hash. (The bitcoin checksum will be\n// the first four bytes of the slice.)\nfunc (a *A25) doubleSHA256() []byte {\n h := sha256.New()\n h.Write(a[:21])\n d := h.Sum([]byte{})\n h = sha256.New()\n h.Write(d)\n return h.Sum(d[:0])\n}\n\n// ComputeChecksum returns a four byte checksum computed from the first 21\n// bytes of the address. The embedded checksum is not updated.\nfunc (a *A25) ComputeChecksum() (c [4]byte) {\n copy(c[:], a.doubleSHA256())\n return\n"} {"title": "Bitwise IO", "language": "Go", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "// Package bit provides bit-wise IO to an io.Writer and from an io.Reader.\npackage bit\n\nimport (\n \"bufio\"\n \"errors\"\n \"io\"\n)\n\n// Order specifies the bit ordering within a byte stream.\ntype Order int\n\nconst (\n // LSB is for Least Significant Bits first\n LSB Order = iota\n // MSB is for Most Significant Bits first\n MSB\n)\n\n// ==== Writing / Encoding ====\n\ntype writer interface {\n io.ByteWriter\n Flush() error\n}\n\n// Writer implements bit-wise writing to an io.Writer.\ntype Writer struct {\n w writer\n order Order\n write func(uint32, uint) error // writeLSB or writeMSB\n bits uint32\n nBits uint\n err error\n}\n\n// writeLSB writes `width` bits of `c` in LSB order.\nfunc (w *Writer) writeLSB(c uint32, width uint) error {\n w.bits |= c << w.nBits\n w.nBits += width\n for w.nBits >= 8 {\n if err := w.w.WriteByte(uint8(w.bits)); err != nil {\n return err\n }\n w.bits >>= 8\n w.nBits -= 8\n }\n return nil\n}\n\n// writeMSB writes `width` bits of `c` in MSB order.\nfunc (w *Writer) writeMSB(c uint32, width uint) error {\n w.bits |= c << (32 - width - w.nBits)\n w.nBits += width\n for w.nBits >= 8 {\n if err := w.w.WriteByte(uint8(w.bits >> 24)); err != nil {\n return err\n }\n w.bits <<= 8\n w.nBits -= 8\n }\n return nil\n}\n\n// WriteBits writes up to 16 bits of `c` to the underlying writer.\n// Even for MSB ordering the bits are taken from the lower bits of `c`.\n// (e.g. WriteBits(0x0f,4) writes four 1 bits).\nfunc (w *Writer) WriteBits(c uint16, width uint) error {\n if w.err == nil {\n w.err = w.write(uint32(c), width)\n }\n return w.err\n}\n\nvar errClosed = errors.New(\"bit reader/writer is closed\")\n\n// Close closes the writer, flushing any pending output.\n// It does not close the underlying writer.\nfunc (w *Writer) Close() error {\n if w.err != nil {\n if w.err == errClosed {\n return nil\n }\n return w.err\n }\n // Write the final bits (zero padded).\n if w.nBits > 0 {\n if w.order == MSB {\n w.bits >>= 24\n }\n if w.err = w.w.WriteByte(uint8(w.bits)); w.err != nil {\n return w.err\n }\n }\n w.err = w.w.Flush()\n if w.err != nil {\n return w.err\n }\n\n // Make any future calls to Write return errClosed.\n w.err = errClosed\n return nil\n}\n\n// NewWriter returns a new bit Writer that writes completed bytes to `w`.\nfunc NewWriter(w io.Writer, order Order) *Writer {\n bw := &Writer{order: order}\n switch order {\n case LSB:\n bw.write = bw.writeLSB\n case MSB:\n bw.write = bw.writeMSB\n default:\n bw.err = errors.New(\"bit writer: unknown order\")\n return bw\n }\n if byteWriter, ok := w.(writer); ok {\n bw.w = byteWriter\n } else {\n bw.w = bufio.NewWriter(w)\n }\n return bw\n}\n\n// ==== Reading / Decoding ====\n\n// Reader implements bit-wise reading from an io.Reader.\ntype Reader struct {\n r io.ByteReader\n bits uint32\n nBits uint\n read func(width uint) (uint16, error) // readLSB or readMSB\n err error\n}\n\nfunc (r *Reader) readLSB(width uint) (uint16, error) {\n for r.nBits < width {\n x, err := r.r.ReadByte()\n if err != nil {\n return 0, err\n }\n r.bits |= uint32(x) << r.nBits\n r.nBits += 8\n }\n bits := uint16(r.bits & (1<>= width\n r.nBits -= width\n return bits, nil\n}\n\nfunc (r *Reader) readMSB(width uint) (uint16, error) {\n for r.nBits < width {\n x, err := r.r.ReadByte()\n if err != nil {\n return 0, err\n }\n r.bits |= uint32(x) << (24 - r.nBits)\n r.nBits += 8\n }\n bits := uint16(r.bits >> (32 - width))\n r.bits <<= width\n r.nBits -= width\n return bits, nil\n}\n\n// ReadBits reads up to 16 bits from the underlying reader.\nfunc (r *Reader) ReadBits(width uint) (uint16, error) {\n var bits uint16\n if r.err == nil {\n bits, r.err = r.read(width)\n }\n return bits, r.err\n}\n\n// Close closes the reader.\n// It does not close the underlying reader.\nfunc (r *Reader) Close() error {\n if r.err != nil && r.err != errClosed {\n return r.err\n }\n r.err = errClosed\n return nil\n}\n\n// NewReader returns a new bit Reader that reads bytes from `r`.\nfunc NewReader(r io.Reader, order Order) *Reader {\n br := new(Reader)\n switch order {\n case LSB:\n br.read = br.readLSB\n case MSB:\n br.read = br.readMSB\n default:\n br.err = errors.New(\"bit writer: unknown order\")\n return br\n }\n if byteReader, ok := r.(io.ByteReader); ok {\n br.r = byteReader\n } else {\n br.r = bufio.NewReader(r)\n }\n return br\n}"} {"title": "Box the compass", "language": "Go", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// function required by task\nfunc degrees2compasspoint(h float32) string {\n return compassPoint[cpx(h)]\n}\n\n// cpx returns integer index from 0 to 31 corresponding to compass point.\n// input heading h is in degrees. Note this index is a zero-based index\n// suitable for indexing into the table of printable compass points,\n// and is not the same as the index specified to be printed in the output.\nfunc cpx(h float32) int {\n x := int(h/11.25+.5) % 32\n if x < 0 {\n x += 32\n }\n return x\n}\n\n// printable compass points\nvar compassPoint = []string{\n \"North\",\n \"North by east\",\n \"North-northeast\",\n \"Northeast by north\",\n \"Northeast\",\n \"Northeast by east\",\n \"East-northeast\",\n \"East by north\",\n \"East\",\n \"East by south\",\n \"East-southeast\",\n \"Southeast by east\",\n \"Southeast\",\n \"Southeast by south\",\n \"South-southeast\",\n \"South by east\",\n \"South\",\n \"South by west\",\n \"South-southwest\",\n \"Southwest by south\",\n \"Southwest\",\n \"Southwest by west\",\n \"West-southwest\",\n \"West by south\",\n \"West\",\n \"West by north\",\n \"West-northwest\",\n \"Northwest by west\",\n \"Northwest\",\n \"Northwest by north\",\n \"North-northwest\",\n \"North by west\",\n}\n\nfunc main() {\n fmt.Println(\"Index Compass point Degree\")\n for i, h := range []float32{0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,\n 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,\n 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0,\n 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38} {\n index := i%32 + 1 // printable index computed per pseudocode\n fmt.Printf(\"%4d %-19s %7.2f\u00b0\\n\", index, degrees2compasspoint(h), h)\n }\n}"} {"title": "Brazilian numbers", "language": "Go", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc sameDigits(n, b int) bool {\n f := n % b\n n /= b\n for n > 0 {\n if n%b != f {\n return false\n }\n n /= b\n }\n return true\n}\n\nfunc isBrazilian(n int) bool {\n if n < 7 {\n return false\n }\n if n%2 == 0 && n >= 8 {\n return true\n }\n for b := 2; b < n-1; b++ {\n if sameDigits(n, b) {\n return true\n }\n }\n return false\n}\n\nfunc isPrime(n int) bool {\n switch {\n case n < 2:\n return false\n case n%2 == 0:\n return n == 2\n case n%3 == 0:\n return n == 3\n default:\n d := 5\n for d*d <= n {\n if n%d == 0 {\n return false\n }\n d += 2\n if n%d == 0 {\n return false\n }\n d += 4\n }\n return true\n }\n}\n\nfunc main() {\n kinds := []string{\" \", \" odd \", \" prime \"}\n for _, kind := range kinds {\n fmt.Printf(\"First 20%sBrazilian numbers:\\n\", kind)\n c := 0\n n := 7\n for {\n if isBrazilian(n) {\n fmt.Printf(\"%d \", n)\n c++\n if c == 20 {\n fmt.Println(\"\\n\")\n break\n }\n }\n switch kind {\n case \" \":\n n++\n case \" odd \":\n n += 2\n case \" prime \":\n for {\n n += 2\n if isPrime(n) {\n break\n }\n }\n }\n }\n }\n\n n := 7\n for c := 0; c < 100000; n++ {\n if isBrazilian(n) {\n c++\n }\n }\n fmt.Println(\"The 100,000th Brazilian number:\", n-1)\n}"} {"title": "Brazilian numbers", "language": "Go from C# (speedier version)", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"time\"\n)\n\n// flags\nconst (\n prMk int8 = 0 // prime\n sqMk = 1 // prime square\n upMk = 2 // non-prime\n brMk = -2 // Brazilian prime\n excp = 121 // the only Brazilian square prime\n)\n\nvar (\n pow = 9\n max = 0\n ps []int8\n)\n\n// typical sieve of Eratosthenes\nfunc primeSieve(top int) {\n ps = make([]int8, top)\n i, j := 2, 4\n ps[j] = sqMk\n for j < top-2 {\n j += 2\n ps[j] = upMk\n }\n i, j = 3, 9\n ps[j] = sqMk\n for j < top-6 {\n j += 6\n ps[j] = upMk\n }\n i = 5\n for i*i < top {\n if ps[i] == prMk {\n j = (top - i) / i\n if (j & 1) == 0 {\n j--\n }\n for {\n if ps[j] == prMk {\n ps[i*j] = upMk\n }\n j -= 2\n if j <= i {\n break\n }\n }\n ps[i*i] = sqMk\n }\n for {\n i += 2\n if ps[i] == prMk {\n break\n }\n }\n }\n}\n\n// returns whether a number is Brazilian\nfunc isBr(number int) bool {\n temp := ps[number]\n if temp < 0 {\n temp = -temp\n }\n return temp > sqMk\n}\n\n// shows the first few Brazilian numbers of several kinds\nfunc firstFew(kind string, amt int) {\n fmt.Printf(\"\\nThe first %d %sBrazilian numbers are:\\n\", amt, kind)\n i := 7\n for amt > 0 {\n if isBr(i) {\n amt--\n fmt.Printf(\"%d \", i)\n }\n switch kind {\n case \"odd \":\n i += 2\n case \"prime \":\n for {\n i += 2\n if ps[i] == brMk && i != excp {\n break\n }\n }\n default:\n i++\n }\n }\n fmt.Println()\n}\n\n// expands a 111_X number into an integer\nfunc expand(numberOfOnes, base int) int {\n res := 1\n for numberOfOnes > 1 {\n numberOfOnes--\n res = res*base + 1\n }\n if res > max || res < 0 {\n res = 0\n }\n return res\n}\n\nfunc toMs(d time.Duration) float64 {\n return float64(d) / 1e6\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n start := time.Now()\n st0 := start\n p2 := pow << 1\n p10 := int(math.Pow10(pow))\n p, cnt := 10, 0\n max = p10 * p2 / (p2 - 1)\n primeSieve(max)\n fmt.Printf(\"Sieving took %.4f ms\\n\", toMs(time.Since(start)))\n start = time.Now()\n primes := make([]int, 7)\n n := 3\n for i := 0; i < len(primes); i++ {\n primes[i] = n\n for {\n n += 2\n if ps[n] == 0 {\n break\n }\n }\n }\n fmt.Println(\"\\nChecking first few prime numbers of sequential ones:\")\n fmt.Println(\"ones checked found\")\n for _, i := range primes {\n fmt.Printf(\"%4d\", i)\n cnt, n = 0, 2\n for {\n if (n-1)%i != 0 {\n br := expand(i, n)\n if br > 0 {\n if ps[br] < upMk {\n ps[br] = brMk\n cnt++\n }\n } else {\n fmt.Printf(\"%8d%6d\\n\", n, cnt)\n break\n }\n }\n n++\n }\n }\n ms := toMs(time.Since(start))\n fmt.Printf(\"Adding Brazilian primes to the sieve took %.4f ms\\n\", ms)\n start = time.Now()\n for _, s := range []string{\"\", \"odd \", \"prime \"} {\n firstFew(s, 20)\n }\n fmt.Printf(\"\\nRequired output took %.4f ms\\n\", toMs(time.Since(start)))\n fmt.Println(\"\\nDecade count of Brazilian numbers:\")\n n, cnt = 6, 0\n for {\n for cnt < p {\n n++\n if isBr(n) {\n cnt++\n }\n }\n ms = toMs(time.Since(start))\n fmt.Printf(\"%15sth is %-15s time: %8.4f ms\\n\", commatize(cnt), commatize(n), ms)\n p *= 10\n if p > p10 {\n break\n }\n }\n fmt.Printf(\"\\nTotal elapsed was %.4f ms\\n\", toMs(time.Since(st0)))\n}"} {"title": "Break OO privacy", "language": "Go", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\ntype foobar struct {\n\tExported int // In Go identifiers that are capitalized are exported,\n\tunexported int // while lowercase identifiers are not.\n}\n\nfunc main() {\n\tobj := foobar{12, 42}\n\tfmt.Println(\"obj:\", obj)\n\n\texamineAndModify(&obj)\n\tfmt.Println(\"obj:\", obj)\n\n\tanotherExample()\n}\n\n// For simplicity this skips several checks. It assumes the thing in the\n// interface is a pointer without checking (v.Kind()==reflect.Ptr),\n// it then assumes it is a structure type with two int fields\n// (v.Kind()==reflect.Struct, f.Type()==reflect.TypeOf(int(0))).\nfunc examineAndModify(any interface{}) {\n\tv := reflect.ValueOf(any) // get a reflect.Value\n\tv = v.Elem() // dereference the pointer\n\tfmt.Println(\" v:\", v, \"=\", v.Interface())\n\tt := v.Type()\n\t// Loop through the struct fields\n\tfmt.Printf(\" %3s %-10s %-4s %s\\n\", \"Idx\", \"Name\", \"Type\", \"CanSet\")\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i) // reflect.Value of the field\n\t\tfmt.Printf(\" %2d: %-10s %-4s %t\\n\", i,\n\t\t\tt.Field(i).Name, f.Type(), f.CanSet())\n\t}\n\n\t// \"Exported\", field 0, has CanSet==true so we can do:\n\tv.Field(0).SetInt(16)\n\t// \"unexported\", field 1, has CanSet==false so the following\n\t// would fail at run-time with:\n\t// panic: reflect: reflect.Value.SetInt using value obtained using unexported field\n\t//v.Field(1).SetInt(43)\n\n\t// However, we can bypass this restriction with the unsafe\n\t// package once we know what type it is (so we can use the\n\t// correct pointer type, here *int):\n\tvp := v.Field(1).Addr() // Take the fields's address\n\tup := unsafe.Pointer(vp.Pointer()) // \u2026 get an int value of the address and convert it \"unsafely\"\n\tp := (*int)(up) // \u2026 and end up with what we want/need\n\tfmt.Printf(\" vp has type %-14T = %v\\n\", vp, vp)\n\tfmt.Printf(\" up has type %-14T = %#0x\\n\", up, up)\n\tfmt.Printf(\" p has type %-14T = %v pointing at %v\\n\", p, p, *p)\n\t*p = 43 // effectively obj.unexported = 43\n\t// or an incr all on one ulgy line:\n\t*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++\n\n\t// Note that as-per the package \"unsafe\" documentation,\n\t// the return value from vp.Pointer *must* be converted to\n\t// unsafe.Pointer in the same expression; the result is fragile.\n\t//\n\t// I.e. it is invalid to do:\n\t//\tthisIsFragile := vp.Pointer()\n\t//\tup := unsafe.Pointer(thisIsFragile)\n}\n\n// This time we'll use an external package to demonstrate that it's not\n// restricted to things defined locally. We'll mess with bufio.Reader's\n// interal workings by happening to know they have a non-exported\n// \"err\u00a0error\" field. Of course future versions of Go may not have this\n// field or use it in the same way :).\nfunc anotherExample() {\n\tr := bufio.NewReader(os.Stdin)\n\n\t// Do the dirty stuff in one ugly and unsafe statement:\n\terrp := (*error)(unsafe.Pointer(\n\t\treflect.ValueOf(r).Elem().FieldByName(\"err\").Addr().Pointer()))\n\t*errp = errors.New(\"unsafely injected error value into bufio inner workings\")\n\n\t_, err := r.ReadByte()\n\tfmt.Println(\"bufio.ReadByte returned error:\", err)\n}"} {"title": "Burrows\u2013Wheeler transform", "language": "Go from Python", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strings\"\n)\n\nconst stx = \"\\002\"\nconst etx = \"\\003\"\n\nfunc bwt(s string) (string, error) {\n if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 {\n return \"\", fmt.Errorf(\"String can't contain STX or ETX\")\n }\n s = stx + s + etx\n le := len(s)\n table := make([]string, le)\n table[0] = s\n for i := 1; i < le; i++ {\n table[i] = s[i:] + s[:i]\n }\n sort.Strings(table)\n lastBytes := make([]byte, le)\n for i := 0; i < le; i++ {\n lastBytes[i] = table[i][le-1]\n }\n return string(lastBytes), nil\n}\n\nfunc ibwt(r string) string {\n le := len(r)\n table := make([]string, le)\n for range table {\n for i := 0; i < le; i++ {\n table[i] = r[i:i+1] + table[i]\n }\n sort.Strings(table)\n }\n for _, row := range table {\n if strings.HasSuffix(row, etx) {\n return row[1 : le-1]\n }\n }\n return \"\"\n}\n\nfunc makePrintable(s string) string {\n // substitute ^ for STX and | for ETX to print results\n t := strings.Replace(s, stx, \"^\", 1)\n return strings.Replace(t, etx, \"|\", 1)\n}\n\nfunc main() {\n tests := []string{\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\002ABC\\003\",\n }\n for _, test := range tests {\n fmt.Println(makePrintable(test))\n fmt.Print(\" --> \")\n t, err := bwt(test)\n if err != nil {\n fmt.Println(\"ERROR:\", err)\n } else {\n fmt.Println(makePrintable(t))\n }\n r := ibwt(t)\n fmt.Println(\" -->\", r, \"\\n\")\n }\n}"} {"title": "CSV data manipulation", "language": "Go", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "package main\n\nimport (\n\t\"encoding/csv\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n)\n\nfunc main() {\n\trows := readSample()\n\tappendSum(rows)\n\twriteChanges(rows)\n}\n\nfunc readSample() [][]string {\n\tf, err := os.Open(\"sample.csv\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trows, err := csv.NewReader(f).ReadAll()\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn rows\n}\n\nfunc appendSum(rows [][]string) {\n\trows[0] = append(rows[0], \"SUM\")\n\tfor i := 1; i < len(rows); i++ {\n\t\trows[i] = append(rows[i], sum(rows[i]))\n\t}\n}\n\nfunc sum(row []string) string {\n\tsum := 0\n\tfor _, s := range row {\n\t\tx, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn \"NA\"\n\t\t}\n\t\tsum += x\n\t}\n\treturn strconv.Itoa(sum)\n}\n\nfunc writeChanges(rows [][]string) {\n\tf, err := os.Create(\"output.csv\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = csv.NewWriter(f).WriteAll(rows)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"title": "CSV to HTML translation", "language": "Go", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"encoding/csv\"\n \"flag\"\n \"fmt\"\n \"html/template\"\n \"strings\"\n)\n\nvar csvStr = `Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!`\n\nfunc main() {\n headings := flag.Bool(\"h\", false, \"format first row as column headings\")\n flag.Parse()\n if html, err := csvToHtml(csvStr, *headings); err != nil {\n fmt.Println(err)\n } else {\n fmt.Print(html)\n }\n}\n\nfunc csvToHtml(csvStr string, headings bool) (string, error) {\n data, err := csv.NewReader(bytes.NewBufferString(csvStr)).ReadAll()\n if err != nil {\n return \"\", err\n }\n tStr := tPlain\n if headings {\n tStr = tHeadings\n }\n var b strings.Builder\n err = template.Must(template.New(\"\").Parse(tStr)).Execute(&b, data)\n return b.String(), err\n}\n\nconst (\n tPlain = `\n{{range .}} {{range .}}{{end}}\n{{end}}
{{.}}
\n`\n tHeadings = `{{if .}}\n{{range $x, $e := .}}{{if $x}}\n {{range .}}{{end}}{{else}} \n {{range .}}{{end}}\n \n {{end}}{{end}}\n {{end}}\n
{{.}}
{{.}}
\n`\n)"} {"title": "Calculating the value of e", "language": "Go from Kotlin", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst epsilon = 1.0e-15\n\nfunc main() {\n fact := uint64(1)\n e := 2.0\n n := uint64(2)\n for {\n e0 := e\n fact *= n\n n++\n e += 1.0 / float64(fact)\n if math.Abs(e - e0) < epsilon {\n break\n }\n }\n fmt.Printf(\"e = %.15f\\n\", e)\n}"} {"title": "Calkin-Wilf sequence", "language": "Go from Wren", "task": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n {{math|a1}} = {{math|1}} \n {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 \n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} \n\n\n;Example:\nThe fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', \nwhich means '''9/4''' appears as the '''35th''' term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.\n\n\n;See also:\n* Wikipedia entry: Calkin-Wilf tree\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"strconv\"\n \"strings\"\n)\n\nfunc calkinWilf(n int) []*big.Rat {\n cw := make([]*big.Rat, n+1)\n cw[0] = big.NewRat(1, 1)\n one := big.NewRat(1, 1)\n two := big.NewRat(2, 1)\n for i := 1; i < n; i++ {\n t := new(big.Rat).Set(cw[i-1])\n f, _ := t.Float64()\n f = math.Floor(f)\n t.SetFloat64(f)\n t.Mul(t, two)\n t.Sub(t, cw[i-1])\n t.Add(t, one)\n t.Inv(t)\n cw[i] = new(big.Rat).Set(t)\n }\n return cw\n}\n\nfunc toContinued(r *big.Rat) []int {\n a := r.Num().Int64()\n b := r.Denom().Int64()\n var res []int\n for {\n res = append(res, int(a/b))\n t := a % b\n a, b = b, t\n if a == 1 {\n break\n }\n }\n le := len(res)\n if le%2 == 0 { // ensure always odd\n res[le-1]--\n res = append(res, 1)\n }\n return res\n}\n\nfunc getTermNumber(cf []int) int {\n b := \"\"\n d := \"1\"\n for _, n := range cf {\n b = strings.Repeat(d, n) + b\n if d == \"1\" {\n d = \"0\"\n } else {\n d = \"1\"\n }\n }\n i, _ := strconv.ParseInt(b, 2, 64)\n return int(i)\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n if n < 0 {\n s = s[1:]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfunc main() {\n cw := calkinWilf(20)\n fmt.Println(\"The first 20 terms of the Calkin-Wilf sequnence are:\")\n for i := 1; i <= 20; i++ {\n fmt.Printf(\"%2d: %s\\n\", i, cw[i-1].RatString())\n }\n fmt.Println()\n r := big.NewRat(83116, 51639)\n cf := toContinued(r)\n tn := getTermNumber(cf)\n fmt.Printf(\"%s is the %sth term of the sequence.\\n\", r.RatString(), commatize(tn))\n}"} {"title": "Call a function", "language": "Go", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// int parameter, so arguments will be passed to it by value.\nfunc zeroval(ival int) {\n\tival = 0\n}\n// has an *int parameter, meaning that it takes an int pointer.\nfunc zeroptr(iptr *int) {\n\t*iptr = 0\n}\nfunc main() {\n\ti := 1\n\tfmt.Println(\"initial:\", i) // prt initial: 1\n\tzeroval(i)\n\tfmt.Println(\"zeroval:\", i) // prt zeroval: 1\n\tzeroptr(&i)\n\tfmt.Println(\"zeroptr:\", i) // prt zeroptr: 0\n\tfmt.Println(\"pointer:\", &i) // prt pointer: 0xc0000140b8\n}"} {"title": "Canonicalize CIDR", "language": "Go from Ruby", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n \"strings\"\n)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\n// canonicalize a CIDR block: make sure none of the host bits are set\nfunc canonicalize(cidr string) string {\n // dotted-decimal / bits in network part\n split := strings.Split(cidr, \"/\")\n dotted := split[0]\n size, err := strconv.Atoi(split[1])\n check(err)\n\n // get IP as binary string\n var bin []string\n for _, n := range strings.Split(dotted, \".\") {\n i, err := strconv.Atoi(n)\n check(err)\n bin = append(bin, fmt.Sprintf(\"%08b\", i))\n }\n binary := strings.Join(bin, \"\")\n\n // replace the host part with all zeros\n binary = binary[0:size] + strings.Repeat(\"0\", 32-size)\n\n // convert back to dotted-decimal\n var canon []string\n for i := 0; i < len(binary); i += 8 {\n num, err := strconv.ParseInt(binary[i:i+8], 2, 64)\n check(err)\n canon = append(canon, fmt.Sprintf(\"%d\", num))\n }\n\n // and return\n return strings.Join(canon, \".\") + \"/\" + split[1]\n}\n\nfunc main() {\n tests := []string{\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\",\n }\n\n for _, test := range tests {\n fmt.Printf(\"%-18s -> %s\\n\", test, canonicalize(test))\n }\n}"} {"title": "Cantor set", "language": "Go from Kotlin", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "package main\n\nimport \"fmt\"\n\nconst (\n width = 81\n height = 5\n)\n\nvar lines [height][width]byte\n\nfunc init() {\n for i := 0; i < height; i++ {\n for j := 0; j < width; j++ {\n lines[i][j] = '*'\n }\n }\n}\n\nfunc cantor(start, len, index int) {\n seg := len / 3\n if seg == 0 {\n return\n }\n for i := index; i < height; i++ {\n for j := start + seg; j < start + 2 * seg; j++ {\n lines[i][j] = ' '\n }\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n}\n\nfunc main() {\n cantor(0, width, 1)\n for _, line := range lines {\n fmt.Println(string(line[:]))\n }\n}"} {"title": "Cartesian product of two or more lists", "language": "Go", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype pair [2]int\n\nfunc cart2(a, b []int) []pair {\n p := make([]pair, len(a)*len(b))\n i := 0\n for _, a := range a {\n for _, b := range b {\n p[i] = pair{a, b}\n i++\n }\n }\n return p\n}\n\nfunc main() {\n fmt.Println(cart2([]int{1, 2}, []int{3, 4}))\n fmt.Println(cart2([]int{3, 4}, []int{1, 2}))\n fmt.Println(cart2([]int{1, 2}, nil))\n fmt.Println(cart2(nil, []int{1, 2}))\n}"} {"title": "Casting out nines", "language": "Go", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strconv\"\n)\n\n// A casting out nines algorithm.\n\n// Quoting from: http://mathforum.org/library/drmath/view/55926.html\n/*\nFirst, for any number we can get a single digit, which I will call the \n\"check digit,\" by repeatedly adding the digits. That is, we add the \ndigits of the number, then if there is more than one digit in the \nresult we add its digits, and so on until there is only one digit \nleft.\n\n...\n\nYou may notice that when you add the digits of 6395, if you just \nignore the 9, and the 6+3 = 9, you still end up with 5 as your check \ndigit. This is because any 9's make no difference in the result. \nThat's why the process is called \"casting out\" nines. Also, at any \nstep in the process, you can add digits, not just at the end: to do \n8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is \n11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never \nhave to work with numbers bigger than 18.\n*/\n// The twist is that co9Peterson returns a function to do casting out nines\n// in any specified base from 2 to 36.\nfunc co9Peterson(base int) (cob func(string) (byte, error), err error) {\n if base < 2 || base > 36 {\n return nil, fmt.Errorf(\"co9Peterson: %d invalid base\", base)\n }\n // addDigits adds two digits in the specified base.\n // People perfoming casting out nines by hand would usually have their\n // addition facts memorized. In a program, a lookup table might be\n // analogous, but we expediently use features of the programming language\n // to add digits in the specified base.\n addDigits := func(a, b byte) (string, error) {\n ai, err := strconv.ParseInt(string(a), base, 64)\n if err != nil {\n return \"\", err\n }\n bi, err := strconv.ParseInt(string(b), base, 64)\n if err != nil {\n return \"\", err\n }\n return strconv.FormatInt(ai+bi, base), nil\n }\n // a '9' in the specified base. that is, the greatest digit.\n s9 := strconv.FormatInt(int64(base-1), base)\n b9 := s9[0]\n // define result function. The result function may return an error\n // if n is not a valid number in the specified base.\n cob = func(n string) (r byte, err error) {\n r = '0'\n for i := 0; i < len(n); i++ { // for each digit of the number\n d := n[i]\n switch {\n case d == b9: // if the digit is '9' of the base, cast it out\n continue\n // if the result so far is 0, the digit becomes the result\n case r == '0':\n r = d\n continue\n }\n // otherwise, add the new digit to the result digit\n s, err := addDigits(r, d)\n if err != nil {\n return 0, err\n }\n switch {\n case s == s9: // if the sum is \"9\" of the base, cast it out\n r = '0'\n continue\n // if the sum is a single digit, it becomes the result\n case len(s) == 1:\n r = s[0]\n continue\n }\n // otherwise, reduce this two digit intermediate result before\n // continuing.\n r, err = cob(s)\n if err != nil {\n return 0, err\n }\n }\n return\n }\n return\n}\n\n// Subset code required by task. Given a base and a range specified with\n// beginning and ending number in that base, return candidate Kaprekar numbers\n// based on the observation that k%(base-1) must equal (k*k)%(base-1).\n// For the % operation, rather than the language built-in operator, use\n// the method of casting out nines, which in fact implements %(base-1).\nfunc subset(base int, begin, end string) (s []string, err error) {\n // convert begin, end to native integer types for easier iteration\n begin64, err := strconv.ParseInt(begin, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset begin: %v\", err)\n }\n end64, err := strconv.ParseInt(end, base, 64)\n if err != nil {\n return nil, fmt.Errorf(\"subset end: %v\", err)\n }\n // generate casting out nines function for specified base\n cob, err := co9Peterson(base)\n if err != nil {\n return\n }\n for k := begin64; k <= end64; k++ {\n ks := strconv.FormatInt(k, base)\n rk, err := cob(ks)\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n rk2, err := cob(strconv.FormatInt(k*k, base))\n if err != nil { // assertion\n panic(err) // this would indicate a bug in subset\n }\n // test for candidate Kaprekar number\n if rk == rk2 {\n s = append(s, ks)\n }\n }\n return\n}\n\nvar testCases = []struct {\n base int\n begin, end string\n kaprekar []string\n}{\n {10, \"1\", \"100\", []string{\"1\", \"9\", \"45\", \"55\", \"99\"}},\n {17, \"10\", \"gg\", []string{\"3d\", \"d4\", \"gg\"}},\n}\n \nfunc main() {\n for _, tc := range testCases {\n fmt.Printf(\"\\nTest case base = %d, begin = %s, end = %s:\\n\",\n tc.base, tc.begin, tc.end)\n s, err := subset(tc.base, tc.begin, tc.end)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(\"Subset: \", s)\n fmt.Println(\"Kaprekar:\", tc.kaprekar)\n sx := 0\n for _, k := range tc.kaprekar {\n for {\n if sx == len(s) {\n fmt.Printf(\"Fail:\", k, \"not in subset\")\n return\n }\n if s[sx] == k {\n sx++\n break\n }\n sx++\n }\n }\n fmt.Println(\"Valid subset.\")\n }\n}"} {"title": "Catalan numbers/Pascal's triangle", "language": "Go from C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n const n = 15\n t := [n + 2]uint64{0, 1}\n for i := 1; i <= n; i++ {\n for j := i; j > 1; j-- {\n t[j] += t[j-1]\n }\n t[i+1] = t[i]\n for j := i + 1; j > 1; j-- {\n t[j] += t[j-1]\n }\n fmt.Printf(\"%2d : %d\\n\", i, t[i+1]-t[i])\n }\n}"} {"title": "Catamorphism", "language": "Go", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tn := []int{1, 2, 3, 4, 5}\n\n\tfmt.Println(reduce(add, n))\n\tfmt.Println(reduce(sub, n))\n\tfmt.Println(reduce(mul, n))\n}\n\nfunc add(a int, b int) int { return a + b }\nfunc sub(a int, b int) int { return a - b }\nfunc mul(a int, b int) int { return a * b }\n\nfunc reduce(rf func(int, int) int, m []int) int {\n\tr := m[0]\n\tfor _, v := range m[1:] {\n\t\tr = rf(r, v)\n\t}\n\treturn r\n}"} {"title": "Chaocipher", "language": "Go from Kotlin", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "package main\n\nimport(\n \"fmt\"\n \"strings\"\n \"unicode/utf8\"\n)\n\ntype Mode int\n\nconst(\n Encrypt Mode = iota\n Decrypt\n)\n\nconst(\n lAlphabet = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n rAlphabet = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n)\n\nfunc Chao(text string, mode Mode, showSteps bool) string {\n len := len(text)\n if utf8.RuneCountInString(text) != len {\n fmt.Println(\"Text contains non-ASCII characters\")\n return \"\"\n }\n left := lAlphabet\n right := rAlphabet\n eText := make([]byte, len)\n temp := make([]byte, 26)\n\n for i := 0; i < len; i++ {\n if showSteps {\n fmt.Println(left, \" \", right)\n }\n var index int\n if mode == Encrypt {\n index = strings.IndexByte(right, text[i])\n eText[i] = left[index]\n } else {\n index = strings.IndexByte(left, text[i])\n eText[i] = right[index]\n }\n if i == len - 1 {\n break\n }\n\n // permute left\n for j := index; j < 26; j++ {\n temp[j - index] = left[j]\n }\n for j := 0; j < index; j++ {\n temp[26 - index + j] = left[j]\n }\n store := temp[1]\n for j := 2; j < 14; j++ {\n temp[j - 1] = temp[j]\n }\n temp[13] = store\n left = string(temp[:])\n\n // permute right\n\n for j := index; j < 26; j++ {\n temp[j - index] = right[j]\n }\n for j := 0; j < index; j++ {\n temp[26 - index + j] = right[j]\n }\n store = temp[0]\n for j := 1; j < 26; j++ {\n temp[j - 1] = temp[j]\n }\n temp[25] = store\n store = temp[2]\n for j := 3; j < 14; j++ {\n temp[j - 1] = temp[j]\n }\n temp[13] = store\n right = string(temp[:])\n }\n\n return string(eText[:])\n}\n\nfunc main() {\n plainText := \"WELLDONEISBETTERTHANWELLSAID\"\n fmt.Println(\"The original plaintext is :\", plainText)\n fmt.Print(\"\\nThe left and right alphabets after each permutation \")\n fmt.Println(\"during encryption are :\\n\")\n cipherText := Chao(plainText, Encrypt, true)\n fmt.Println(\"\\nThe ciphertext is :\", cipherText)\n plainText2 := Chao(cipherText, Decrypt, false)\n fmt.Println(\"\\nThe recovered plaintext is :\", plainText2)\n}"} {"title": "Chaos game", "language": "Go", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/gif\"\n\t\"log\"\n\t\"math\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\nvar bwPalette = color.Palette{\n\tcolor.Transparent,\n\tcolor.White,\n\tcolor.RGBA{R: 0xff, A: 0xff},\n\tcolor.RGBA{G: 0xff, A: 0xff},\n\tcolor.RGBA{B: 0xff, A: 0xff},\n}\n\nfunc main() {\n\tconst (\n\t\twidth = 160\n\t\tframes = 100\n\t\tpointsPerFrame = 50\n\t\tdelay = 100 * time.Millisecond\n\t\tfilename = \"chaos_anim.gif\"\n\t)\n\n\tvar tan60 = math.Sin(math.Pi / 3)\n\theight := int(math.Round(float64(width) * tan60))\n\tb := image.Rect(0, 0, width, height)\n\tvertices := [...]image.Point{\n\t\t{0, height}, {width, height}, {width / 2, 0},\n\t}\n\n\t// Make a filled triangle.\n\tm := image.NewPaletted(b, bwPalette)\n\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\tbg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60))\n\t\tfor x := b.Min.X + bg; x < b.Max.X-bg; x++ {\n\t\t\tm.SetColorIndex(x, y, 1)\n\t\t}\n\t}\n\n\t// Pick starting point\n\tvar p image.Point\n\trand.Seed(time.Now().UnixNano())\n\tp.Y = rand.Intn(height) + b.Min.Y\n\tp.X = rand.Intn(width) + b.Min.X // TODO: make within triangle\n\n\tanim := newAnim(frames, delay)\n\taddFrame(anim, m)\n\tfor i := 1; i < frames; i++ {\n\t\tfor j := 0; j < pointsPerFrame; j++ {\n\t\t\t// Pick a random vertex\n\t\t\tvi := rand.Intn(len(vertices))\n\t\t\tv := vertices[vi]\n\t\t\t// Move p halfway there\n\t\t\tp.X = (p.X + v.X) / 2\n\t\t\tp.Y = (p.Y + v.Y) / 2\n\t\t\tm.SetColorIndex(p.X, p.Y, uint8(2+vi))\n\t\t}\n\t\taddFrame(anim, m)\n\t}\n\tif err := writeAnim(anim, filename); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"wrote to %q\\n\", filename)\n}\n\n// Stuff for making a simple GIF animation.\n\nfunc newAnim(frames int, delay time.Duration) *gif.GIF {\n\tconst gifDelayScale = 10 * time.Millisecond\n\tg := &gif.GIF{\n\t\tImage: make([]*image.Paletted, 0, frames),\n\t\tDelay: make([]int, 1, frames),\n\t}\n\tg.Delay[0] = int(delay / gifDelayScale)\n\treturn g\n}\nfunc addFrame(anim *gif.GIF, m *image.Paletted) {\n\tb := m.Bounds()\n\tdst := image.NewPaletted(b, m.Palette)\n\tdraw.Draw(dst, b, m, image.ZP, draw.Src)\n\tanim.Image = append(anim.Image, dst)\n\tif len(anim.Delay) < len(anim.Image) {\n\t\tanim.Delay = append(anim.Delay, anim.Delay[0])\n\t}\n}\nfunc writeAnim(anim *gif.GIF, filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = gif.EncodeAll(f, anim)\n\tif cerr := f.Close(); err == nil {\n\t\terr = cerr\n\t}\n\treturn err\n}"} {"title": "Check Machin-like formulas", "language": "Go from Python", "task": "Machin-like formulas are useful for efficiently computing numerical approximations for \\pi\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3} \n: {\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}\n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}\n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}\n: {\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8} \n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99} \n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}\n: {\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}\n: {\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}\n: {\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}\n: {\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}\n: {\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}\n: {\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}\n: {\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}\n\nand confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':\n\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}\n\nThese identities are useful in calculating the values:\n: \\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}\n\n: \\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}\n\n: \\tan(-a) = -\\tan(a)\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that ''{-3 pi \\over 4} < right hand side < {5 pi \\over 4}'' due to ''\\tan()'' periodicity.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\ntype mTerm struct {\n a, n, d int64\n}\n\nvar testCases = [][]mTerm{\n {{1, 1, 2}, {1, 1, 3}},\n {{2, 1, 3}, {1, 1, 7}},\n {{4, 1, 5}, {-1, 1, 239}},\n {{5, 1, 7}, {2, 3, 79}},\n {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},\n {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},\n {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},\n {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},\n {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},\n {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},\n {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},\n {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},\n {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},\n {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},\n {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},\n {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},\n}\n\nfunc main() {\n for _, m := range testCases {\n fmt.Printf(\"tan %v = %v\\n\", m, tans(m))\n }\n}\n\nvar one = big.NewRat(1, 1)\n\nfunc tans(m []mTerm) *big.Rat {\n if len(m) == 1 {\n return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))\n }\n half := len(m) / 2\n a := tans(m[:half])\n b := tans(m[half:])\n r := new(big.Rat)\n return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}\n\nfunc tanEval(coef int64, f *big.Rat) *big.Rat {\n if coef == 1 {\n return f\n }\n if coef < 0 {\n r := tanEval(-coef, f)\n return r.Neg(r)\n }\n ca := coef / 2\n cb := coef - ca\n a := tanEval(ca, f)\n b := tanEval(cb, f)\n r := new(big.Rat)\n return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))\n}"} {"title": "Check output device is a terminal", "language": "Go", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "package main\n\nimport (\n \"os\"\n \"fmt\"\n)\n\nfunc main() {\n if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {\n fmt.Println(\"Hello terminal\")\n } else {\n fmt.Println(\"Who are you? You're not a terminal\")\n }\n}"} {"title": "Cheryl's birthday", "language": "Go", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\ntype birthday struct{ month, day int }\n\nfunc (b birthday) String() string {\n return fmt.Sprintf(\"%s %d\", time.Month(b.month), b.day)\n}\n\nfunc (b birthday) monthUniqueIn(bds []birthday) bool {\n count := 0\n for _, bd := range bds {\n if bd.month == b.month {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfunc (b birthday) dayUniqueIn(bds []birthday) bool {\n count := 0\n for _, bd := range bds {\n if bd.day == b.day {\n count++\n }\n }\n if count == 1 {\n return true\n }\n return false\n}\n\nfunc (b birthday) monthWithUniqueDayIn(bds []birthday) bool {\n for _, bd := range bds {\n if bd.month == b.month && bd.dayUniqueIn(bds) {\n return true\n }\n }\n return false\n}\n\nfunc main() {\n choices := []birthday{\n {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},\n {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},\n }\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n var filtered []birthday\n for _, bd := range choices {\n if !bd.monthUniqueIn(choices) {\n filtered = append(filtered, bd)\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n var filtered2 []birthday\n for _, bd := range filtered {\n if !bd.monthWithUniqueDayIn(filtered) {\n filtered2 = append(filtered2, bd)\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n var filtered3 []birthday\n for _, bd := range filtered2 {\n if bd.dayUniqueIn(filtered2) {\n filtered3 = append(filtered3, bd)\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n var filtered4 []birthday\n for _, bd := range filtered3 {\n if bd.monthUniqueIn(filtered3) {\n filtered4 = append(filtered4, bd)\n }\n }\n\n if len(filtered4) == 1 {\n fmt.Println(\"Cheryl's birthday is\", filtered4[0])\n } else {\n fmt.Println(\"Something went wrong!\")\n }\n}"} {"title": "Chinese remainder theorem", "language": "Go", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nvar one = big.NewInt(1)\n\nfunc crt(a, n []*big.Int) (*big.Int, error) {\n p := new(big.Int).Set(n[0])\n for _, n1 := range n[1:] {\n p.Mul(p, n1)\n }\n var x, q, s, z big.Int\n for i, n1 := range n {\n q.Div(p, n1)\n z.GCD(nil, &s, n1, &q)\n if z.Cmp(one) != 0 {\n return nil, fmt.Errorf(\"%d not coprime\", n1)\n }\n x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))\n }\n return x.Mod(&x, p), nil\n}\n\nfunc main() {\n n := []*big.Int{\n big.NewInt(3),\n big.NewInt(5),\n big.NewInt(7),\n }\n a := []*big.Int{\n big.NewInt(2),\n big.NewInt(3),\n big.NewInt(2),\n }\n fmt.Println(crt(a, n))\n}"} {"title": "Chinese zodiac", "language": "Go", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "package main\n\nimport \"fmt\"\n\nvar (\n animalString = []string{\"Rat\", \"Ox\", \"Tiger\", \"Rabbit\", \"Dragon\", \"Snake\",\n \"Horse\", \"Goat\", \"Monkey\", \"Rooster\", \"Dog\", \"Pig\"}\n stemYYString = []string{\"Yang\", \"Yin\"}\n elementString = []string{\"Wood\", \"Fire\", \"Earth\", \"Metal\", \"Water\"}\n stemCh = []rune(\"\u7532\u4e59\u4e19\u4e01\u620a\u5df1\u5e9a\u8f9b\u58ec\u7678\")\n branchCh = []rune(\"\u5b50\u4e11\u5bc5\u536f\u8fb0\u5df3\u5348\u672a\u7533\u9149\u620c\u4ea5\")\n)\n\nfunc cz(yr int) (animal, yinYang, element, stemBranch string, cycleYear int) {\n yr -= 4\n stem := yr % 10\n branch := yr % 12\n return animalString[branch],\n stemYYString[stem%2],\n elementString[stem/2],\n string([]rune{stemCh[stem], branchCh[branch]}),\n yr%60 + 1\n}\n\nfunc main() {\n for _, yr := range []int{1935, 1938, 1968, 1972, 1976} {\n a, yy, e, sb, cy := cz(yr)\n fmt.Printf(\"%d: %s %s, %s, Cycle year %d %s\\n\",\n yr, e, a, yy, cy, sb)\n }\n}"} {"title": "Church numerals", "language": "Go", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\ntype fn func(any) any\n\ntype church func(fn) fn\n\nfunc zero(f fn) fn {\n return func(x any) any {\n return x\n }\n}\n\nfunc (c church) succ() church {\n return func(f fn) fn {\n return func(x any) any {\n return f(c(f)(x))\n }\n }\n}\n\nfunc (c church) add(d church) church {\n return func(f fn) fn {\n return func(x any) any {\n return c(f)(d(f)(x))\n }\n }\n}\n\nfunc (c church) mul(d church) church {\n return func(f fn) fn {\n return func(x any) any {\n return c(d(f))(x)\n }\n }\n}\n\nfunc (c church) pow(d church) church {\n di := d.toInt()\n prod := c\n for i := 1; i < di; i++ {\n prod = prod.mul(c)\n }\n return prod\n}\n\nfunc (c church) toInt() int {\n return c(incr)(0).(int)\n}\n\nfunc intToChurch(i int) church {\n if i == 0 {\n return zero\n } else {\n return intToChurch(i - 1).succ()\n }\n}\n\nfunc incr(i any) any {\n return i.(int) + 1\n}\n\nfunc main() {\n z := church(zero)\n three := z.succ().succ().succ()\n four := three.succ()\n\n fmt.Println(\"three ->\", three.toInt())\n fmt.Println(\"four ->\", four.toInt())\n fmt.Println(\"three + four ->\", three.add(four).toInt())\n fmt.Println(\"three * four ->\", three.mul(four).toInt())\n fmt.Println(\"three ^ four ->\", three.pow(four).toInt())\n fmt.Println(\"four ^ three ->\", four.pow(three).toInt())\n fmt.Println(\"5 -> five ->\", intToChurch(5).toInt())\n}"} {"title": "Circles of given radius through two points", "language": "Go", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nvar (\n Two = \"Two circles.\"\n R0 = \"R==0.0 does not describe circles.\"\n Co = \"Coincident points describe an infinite number of circles.\"\n CoR0 = \"Coincident points with r==0.0 describe a degenerate circle.\"\n Diam = \"Points form a diameter and describe only a single circle.\"\n Far = \"Points too far apart to form circles.\"\n)\n\ntype point struct{ x, y float64 }\n\nfunc circles(p1, p2 point, r float64) (c1, c2 point, Case string) {\n if p1 == p2 {\n if r == 0 {\n return p1, p1, CoR0\n }\n Case = Co\n return\n }\n if r == 0 {\n return p1, p2, R0\n }\n dx := p2.x - p1.x\n dy := p2.y - p1.y\n q := math.Hypot(dx, dy)\n if q > 2*r {\n Case = Far\n return\n }\n m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}\n if q == 2*r {\n return m, m, Diam\n }\n d := math.Sqrt(r*r - q*q/4)\n ox := d * dx / q\n oy := d * dy / q\n return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two\n}\n\nvar td = []struct {\n p1, p2 point\n r float64\n}{\n {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0},\n {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0},\n {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0},\n {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5},\n {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0},\n}\n\nfunc main() {\n for _, tc := range td {\n fmt.Println(\"p1: \", tc.p1)\n fmt.Println(\"p2: \", tc.p2)\n fmt.Println(\"r: \", tc.r)\n c1, c2, Case := circles(tc.p1, tc.p2, tc.r)\n fmt.Println(\" \", Case)\n switch Case {\n case CoR0, Diam:\n fmt.Println(\" Center: \", c1)\n case Two:\n fmt.Println(\" Center 1: \", c1)\n fmt.Println(\" Center 2: \", c2)\n }\n fmt.Println()\n }\n}"} {"title": "Cistercian numerals", "language": "Go from Wren", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "package main\n\nimport \"fmt\"\n\nvar n = make([][]string, 15)\n\nfunc initN() {\n for i := 0; i < 15; i++ {\n n[i] = make([]string, 11)\n for j := 0; j < 11; j++ {\n n[i][j] = \" \"\n }\n n[i][5] = \"x\"\n }\n}\n\nfunc horiz(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r][c] = \"x\"\n }\n}\n\nfunc verti(r1, r2, c int) {\n for r := r1; r <= r2; r++ {\n n[r][c] = \"x\"\n }\n}\n\nfunc diagd(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r+c-c1][c] = \"x\"\n }\n}\n\nfunc diagu(c1, c2, r int) {\n for c := c1; c <= c2; c++ {\n n[r-c+c1][c] = \"x\"\n }\n}\n\nvar draw map[int]func() // map contains recursive closures\n\nfunc initDraw() {\n draw = map[int]func(){\n 1: func() { horiz(6, 10, 0) },\n 2: func() { horiz(6, 10, 4) },\n 3: func() { diagd(6, 10, 0) },\n 4: func() { diagu(6, 10, 4) },\n 5: func() { draw[1](); draw[4]() },\n 6: func() { verti(0, 4, 10) },\n 7: func() { draw[1](); draw[6]() },\n 8: func() { draw[2](); draw[6]() },\n 9: func() { draw[1](); draw[8]() },\n\n 10: func() { horiz(0, 4, 0) },\n 20: func() { horiz(0, 4, 4) },\n 30: func() { diagu(0, 4, 4) },\n 40: func() { diagd(0, 4, 0) },\n 50: func() { draw[10](); draw[40]() },\n 60: func() { verti(0, 4, 0) },\n 70: func() { draw[10](); draw[60]() },\n 80: func() { draw[20](); draw[60]() },\n 90: func() { draw[10](); draw[80]() },\n\n 100: func() { horiz(6, 10, 14) },\n 200: func() { horiz(6, 10, 10) },\n 300: func() { diagu(6, 10, 14) },\n 400: func() { diagd(6, 10, 10) },\n 500: func() { draw[100](); draw[400]() },\n 600: func() { verti(10, 14, 10) },\n 700: func() { draw[100](); draw[600]() },\n 800: func() { draw[200](); draw[600]() },\n 900: func() { draw[100](); draw[800]() },\n\n 1000: func() { horiz(0, 4, 14) },\n 2000: func() { horiz(0, 4, 10) },\n 3000: func() { diagd(0, 4, 10) },\n 4000: func() { diagu(0, 4, 14) },\n 5000: func() { draw[1000](); draw[4000]() },\n 6000: func() { verti(10, 14, 0) },\n 7000: func() { draw[1000](); draw[6000]() },\n 8000: func() { draw[2000](); draw[6000]() },\n 9000: func() { draw[1000](); draw[8000]() },\n }\n}\n\nfunc printNumeral() {\n for i := 0; i < 15; i++ {\n for j := 0; j < 11; j++ {\n fmt.Printf(\"%s \", n[i][j])\n }\n fmt.Println()\n }\n fmt.Println()\n}\n\nfunc main() {\n initDraw()\n numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}\n for _, number := range numbers {\n initN()\n fmt.Printf(\"%d:\\n\", number)\n thousands := number / 1000\n number %= 1000\n hundreds := number / 100\n number %= 100\n tens := number / 10\n ones := number % 10\n if thousands > 0 {\n draw[thousands*1000]()\n }\n if hundreds > 0 {\n draw[hundreds*100]()\n }\n if tens > 0 {\n draw[tens*10]()\n }\n if ones > 0 {\n draw[ones]()\n }\n printNumeral()\n }\n}"} {"title": "Closures/Value capture", "language": "Go", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fs := make([]func() int, 10)\n for i := range fs {\n i := i\n fs[i] = func() int {\n return i * i\n }\n }\n fmt.Println(\"func #0:\", fs[0]())\n fmt.Println(\"func #3:\", fs[3]())\n}"} {"title": "Comma quibbling", "language": "Go", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc q(s []string) string {\n switch len(s) {\n case 0:\n return \"{}\"\n case 1:\n return \"{\" + s[0] + \"}\"\n case 2:\n return \"{\" + s[0] + \" and \" + s[1] + \"}\"\n default:\n return \"{\" +\n strings.Join(s[:len(s)-1], \", \") +\n \" and \" +\n s[len(s)-1] +\n \"}\"\n }\n}\n\nfunc main() {\n fmt.Println(q([]string{}))\n fmt.Println(q([]string{\"ABC\"}))\n fmt.Println(q([]string{\"ABC\", \"DEF\"}))\n fmt.Println(q([]string{\"ABC\", \"DEF\", \"G\", \"H\"}))\n}"} {"title": "Command-line arguments", "language": "Go", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n"} {"title": "Compare a list of strings", "language": "Go", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "package cmp\n\nfunc AllEqual(strings []string) bool {\n\tfor _, s := range strings {\n\t\tif s != strings[0] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc AllLessThan(strings []string) bool {\n\tfor i := 1; i < len(strings); i++ {\n\t\tif !(strings[i - 1] < s) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"title": "Compile-time calculation", "language": "Go", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(2*3*4*5*6*7*8*9*10)\n}"} {"title": "Compiler/AST interpreter", "language": "Go from C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype NodeType int\n\nconst (\n ndIdent NodeType = iota\n ndString\n ndInteger\n ndSequence\n ndIf\n ndPrtc\n ndPrts\n ndPrti\n ndWhile\n ndAssign\n ndNegate\n ndNot\n ndMul\n ndDiv\n ndMod\n ndAdd\n ndSub\n ndLss\n ndLeq\n ndGtr\n ndGeq\n ndEql\n ndNeq\n ndAnd\n ndOr\n)\n\ntype Tree struct {\n nodeType NodeType\n left *Tree\n right *Tree\n value int\n}\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\ntype atr struct {\n enumText string\n nodeType NodeType\n}\n\nvar atrs = []atr{\n {\"Identifier\", ndIdent},\n {\"String\", ndString},\n {\"Integer\", ndInteger},\n {\"Sequence\", ndSequence},\n {\"If\", ndIf},\n {\"Prtc\", ndPrtc},\n {\"Prts\", ndPrts},\n {\"Prti\", ndPrti},\n {\"While\", ndWhile},\n {\"Assign\", ndAssign},\n {\"Negate\", ndNegate},\n {\"Not\", ndNot},\n {\"Multiply\", ndMul},\n {\"Divide\", ndDiv},\n {\"Mod\", ndMod},\n {\"Add\", ndAdd},\n {\"Subtract\", ndSub},\n {\"Less\", ndLss},\n {\"LessEqual\", ndLeq},\n {\"Greater\", ndGtr},\n {\"GreaterEqual\", ndGeq},\n {\"Equal\", ndEql},\n {\"NotEqual\", ndNeq},\n {\"And\", ndAnd},\n {\"Or\", ndOr},\n}\n\nvar (\n stringPool []string\n globalNames []string\n globalValues = make(map[int]int)\n)\n\nvar (\n err error\n scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc btoi(b bool) int {\n if b {\n return 1\n }\n return 0\n}\n\nfunc itob(i int) bool {\n if i == 0 {\n return false\n }\n return true\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n return &Tree{nodeType, left, right, 0}\n}\n\nfunc makeLeaf(nodeType NodeType, value int) *Tree {\n return &Tree{nodeType, nil, nil, value}\n}\n\nfunc interp(x *Tree) int { // interpret the parse tree\n if x == nil {\n return 0\n }\n switch x.nodeType {\n case ndInteger:\n return x.value\n case ndIdent:\n return globalValues[x.value]\n case ndString:\n return x.value\n case ndAssign:\n n := interp(x.right)\n globalValues[x.left.value] = n\n return n\n case ndAdd:\n return interp(x.left) + interp(x.right)\n case ndSub:\n return interp(x.left) - interp(x.right)\n case ndMul:\n return interp(x.left) * interp(x.right)\n case ndDiv:\n return interp(x.left) / interp(x.right)\n case ndMod:\n return interp(x.left) % interp(x.right)\n case ndLss:\n return btoi(interp(x.left) < interp(x.right))\n case ndGtr:\n return btoi(interp(x.left) > interp(x.right))\n case ndLeq:\n return btoi(interp(x.left) <= interp(x.right))\n case ndEql:\n return btoi(interp(x.left) == interp(x.right))\n case ndNeq:\n return btoi(interp(x.left) != interp(x.right))\n case ndAnd:\n return btoi(itob(interp(x.left)) && itob(interp(x.right)))\n case ndOr:\n return btoi(itob(interp(x.left)) || itob(interp(x.right)))\n case ndNegate:\n return -interp(x.left)\n case ndNot:\n if interp(x.left) == 0 {\n return 1\n }\n return 0\n case ndIf:\n if interp(x.left) != 0 {\n interp(x.right.left)\n } else {\n interp(x.right.right)\n }\n return 0\n case ndWhile:\n for interp(x.left) != 0 {\n interp(x.right)\n }\n return 0\n case ndPrtc:\n fmt.Printf(\"%c\", interp(x.left))\n return 0\n case ndPrti:\n fmt.Printf(\"%d\", interp(x.left))\n return 0\n case ndPrts:\n fmt.Print(stringPool[interp(x.left)])\n return 0\n case ndSequence:\n interp(x.left)\n interp(x.right)\n return 0\n default:\n reportError(fmt.Sprintf(\"interp: unknown tree type %d\\n\", x.nodeType))\n }\n return 0\n}\n\nfunc getEnumValue(name string) NodeType {\n for _, atr := range atrs {\n if atr.enumText == name {\n return atr.nodeType\n }\n }\n reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n return -1\n}\n\nfunc fetchStringOffset(s string) int {\n var d strings.Builder\n s = s[1 : len(s)-1]\n for i := 0; i < len(s); i++ {\n if s[i] == '\\\\' && (i+1) < len(s) {\n if s[i+1] == 'n' {\n d.WriteByte('\\n')\n i++\n } else if s[i+1] == '\\\\' {\n d.WriteByte('\\\\')\n i++\n }\n } else {\n d.WriteByte(s[i])\n }\n }\n s = d.String()\n for i := 0; i < len(stringPool); i++ {\n if s == stringPool[i] {\n return i\n }\n }\n stringPool = append(stringPool, s)\n return len(stringPool) - 1\n}\n\nfunc fetchVarOffset(name string) int {\n for i := 0; i < len(globalNames); i++ {\n if globalNames[i] == name {\n return i\n }\n }\n globalNames = append(globalNames, name)\n return len(globalNames) - 1\n}\n\nfunc loadAst() *Tree {\n var nodeType NodeType\n var s string\n if scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n tokens := strings.Fields(line)\n first := tokens[0]\n if first[0] == ';' {\n return nil\n }\n nodeType = getEnumValue(first)\n le := len(tokens)\n if le == 2 {\n s = tokens[1]\n } else if le > 2 {\n idx := strings.Index(line, `\"`)\n s = line[idx:]\n }\n }\n check(scanner.Err())\n if s != \"\" {\n var n int\n switch nodeType {\n case ndIdent:\n n = fetchVarOffset(s)\n case ndInteger:\n n, err = strconv.Atoi(s)\n check(err)\n case ndString:\n n = fetchStringOffset(s)\n default:\n reportError(fmt.Sprintf(\"Unknown node type: %s\\n\", s))\n }\n return makeLeaf(nodeType, n)\n } \n left := loadAst()\n right := loadAst()\n return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n ast, err := os.Open(\"ast.txt\")\n check(err)\n defer ast.Close()\n scanner = bufio.NewScanner(ast)\n x := loadAst()\n interp(x)\n}"} {"title": "Compiler/code generator", "language": "Go from C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"encoding/binary\"\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype NodeType int\n\nconst (\n ndIdent NodeType = iota\n ndString\n ndInteger\n ndSequence\n ndIf\n ndPrtc\n ndPrts\n ndPrti\n ndWhile\n ndAssign\n ndNegate\n ndNot\n ndMul\n ndDiv\n ndMod\n ndAdd\n ndSub\n ndLss\n ndLeq\n ndGtr\n ndGeq\n ndEql\n ndNeq\n ndAnd\n ndOr\n)\n\ntype code = byte\n\nconst (\n fetch code = iota\n store\n push\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n neg\n not\n jmp\n jz\n prtc\n prts\n prti\n halt\n)\n\ntype Tree struct {\n nodeType NodeType\n left *Tree\n right *Tree\n value string\n}\n\n// dependency: Ordered by NodeType, must remain in same order as NodeType enum\ntype atr struct {\n enumText string\n nodeType NodeType\n opcode code\n}\n\nvar atrs = []atr{\n {\"Identifier\", ndIdent, 255},\n {\"String\", ndString, 255},\n {\"Integer\", ndInteger, 255},\n {\"Sequence\", ndSequence, 255},\n {\"If\", ndIf, 255},\n {\"Prtc\", ndPrtc, 255},\n {\"Prts\", ndPrts, 255},\n {\"Prti\", ndPrti, 255},\n {\"While\", ndWhile, 255},\n {\"Assign\", ndAssign, 255},\n {\"Negate\", ndNegate, neg},\n {\"Not\", ndNot, not},\n {\"Multiply\", ndMul, mul},\n {\"Divide\", ndDiv, div},\n {\"Mod\", ndMod, mod},\n {\"Add\", ndAdd, add},\n {\"Subtract\", ndSub, sub},\n {\"Less\", ndLss, lt},\n {\"LessEqual\", ndLeq, le},\n {\"Greater\", ndGtr, gt},\n {\"GreaterEqual\", ndGeq, ge},\n {\"Equal\", ndEql, eq},\n {\"NotEqual\", ndNeq, ne},\n {\"And\", ndAnd, and},\n {\"Or\", ndOr, or},\n}\n\nvar (\n stringPool []string\n globals []string\n object []code\n)\n\nvar (\n err error\n scanner *bufio.Scanner\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc nodeType2Op(nodeType NodeType) code {\n return atrs[nodeType].opcode\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n return &Tree{nodeType, nil, nil, value}\n}\n\n/*** Code generator ***/\n\nfunc emitByte(c code) {\n object = append(object, c)\n}\n\nfunc emitWord(n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for _, b := range bs {\n emitByte(code(b))\n }\n}\n\nfunc emitWordAt(at, n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for i := at; i < at+4; i++ {\n object[i] = code(bs[i-at])\n }\n}\n\nfunc hole() int {\n t := len(object)\n emitWord(0)\n return t\n}\n\nfunc fetchVarOffset(id string) int {\n for i := 0; i < len(globals); i++ {\n if globals[i] == id {\n return i\n }\n }\n globals = append(globals, id)\n return len(globals) - 1\n}\n\nfunc fetchStringOffset(st string) int {\n for i := 0; i < len(stringPool); i++ {\n if stringPool[i] == st {\n return i\n }\n }\n stringPool = append(stringPool, st)\n return len(stringPool) - 1\n}\n\nfunc codeGen(x *Tree) {\n if x == nil {\n return\n }\n var n, p1, p2 int\n switch x.nodeType {\n case ndIdent:\n emitByte(fetch)\n n = fetchVarOffset(x.value)\n emitWord(n)\n case ndInteger:\n emitByte(push)\n n, err = strconv.Atoi(x.value)\n check(err)\n emitWord(n)\n case ndString:\n emitByte(push)\n n = fetchStringOffset(x.value)\n emitWord(n)\n case ndAssign:\n n = fetchVarOffset(x.left.value)\n codeGen(x.right)\n emitByte(store)\n emitWord(n)\n case ndIf:\n codeGen(x.left) // if expr\n emitByte(jz) // if false, jump\n p1 = hole() // make room forjump dest\n codeGen(x.right.left) // if true statements\n if x.right.right != nil {\n emitByte(jmp)\n p2 = hole()\n }\n emitWordAt(p1, len(object)-p1)\n if x.right.right != nil {\n codeGen(x.right.right)\n emitWordAt(p2, len(object)-p2)\n }\n case ndWhile:\n p1 = len(object)\n codeGen(x.left) // while expr\n emitByte(jz) // if false, jump\n p2 = hole() // make room for jump dest\n codeGen(x.right) // statements\n emitByte(jmp) // back to the top\n emitWord(p1 - len(object)) // plug the top\n emitWordAt(p2, len(object)-p2) // plug the 'if false, jump'\n case ndSequence:\n codeGen(x.left)\n codeGen(x.right)\n case ndPrtc:\n codeGen(x.left)\n emitByte(prtc)\n case ndPrti:\n codeGen(x.left)\n emitByte(prti)\n case ndPrts:\n codeGen(x.left)\n emitByte(prts)\n case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,\n ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:\n codeGen(x.left)\n codeGen(x.right)\n emitByte(nodeType2Op(x.nodeType))\n case ndNegate, ndNot:\n codeGen(x.left)\n emitByte(nodeType2Op(x.nodeType))\n default:\n msg := fmt.Sprintf(\"error in code generator - found %d, expecting operator\\n\", x.nodeType)\n reportError(msg)\n }\n}\n\nfunc codeFinish() {\n emitByte(halt)\n}\n\nfunc listCode() {\n fmt.Printf(\"Datasize: %d Strings: %d\\n\", len(globals), len(stringPool))\n for _, s := range stringPool {\n fmt.Println(s)\n }\n pc := 0\n for pc < len(object) {\n fmt.Printf(\"%5d \", pc)\n op := object[pc]\n pc++\n switch op {\n case fetch:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"fetch [%d]\\n\", x)\n pc += 4\n case store:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"store [%d]\\n\", x)\n pc += 4\n case push:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"push %d\\n\", x)\n pc += 4\n case add:\n fmt.Println(\"add\")\n case sub:\n fmt.Println(\"sub\")\n case mul:\n fmt.Println(\"mul\")\n case div:\n fmt.Println(\"div\")\n case mod:\n fmt.Println(\"mod\")\n case lt:\n fmt.Println(\"lt\")\n case gt:\n fmt.Println(\"gt\")\n case le:\n fmt.Println(\"le\")\n case ge:\n fmt.Println(\"ge\")\n case eq:\n fmt.Println(\"eq\")\n case ne:\n fmt.Println(\"ne\")\n case and:\n fmt.Println(\"and\")\n case or:\n fmt.Println(\"or\")\n case neg:\n fmt.Println(\"neg\")\n case not:\n fmt.Println(\"not\")\n case jmp:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"jmp (%d) %d\\n\", x, int32(pc)+x)\n pc += 4\n case jz:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n fmt.Printf(\"jz (%d) %d\\n\", x, int32(pc)+x)\n pc += 4\n case prtc:\n fmt.Println(\"prtc\")\n case prti:\n fmt.Println(\"prti\")\n case prts:\n fmt.Println(\"prts\")\n case halt:\n fmt.Println(\"halt\")\n default:\n reportError(fmt.Sprintf(\"listCode: Unknown opcode %d\", op))\n }\n }\n}\n\nfunc getEnumValue(name string) NodeType {\n for _, atr := range atrs {\n if atr.enumText == name {\n return atr.nodeType\n }\n }\n reportError(fmt.Sprintf(\"Unknown token %s\\n\", name))\n return -1\n}\n\nfunc loadAst() *Tree {\n var nodeType NodeType\n var s string\n if scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n tokens := strings.Fields(line)\n first := tokens[0]\n if first[0] == ';' {\n return nil\n }\n nodeType = getEnumValue(first)\n le := len(tokens)\n if le == 2 {\n s = tokens[1]\n } else if le > 2 {\n idx := strings.Index(line, `\"`)\n s = line[idx:]\n }\n }\n check(scanner.Err())\n if s != \"\" {\n return makeLeaf(nodeType, s)\n }\n left := loadAst()\n right := loadAst()\n return makeNode(nodeType, left, right)\n}\n\nfunc main() {\n ast, err := os.Open(\"ast.txt\")\n check(err)\n defer ast.Close()\n scanner = bufio.NewScanner(ast)\n codeGen(loadAst())\n codeFinish()\n listCode()\n}"} {"title": "Compiler/lexical analyzer", "language": "Go from FreeBASIC", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n)\n\ntype TokenType int\n\nconst (\n tkEOI TokenType = iota\n tkMul\n tkDiv\n tkMod\n tkAdd\n tkSub\n tkNegate\n tkNot\n tkLss\n tkLeq\n tkGtr\n tkGeq\n tkEq\n tkNeq\n tkAssign\n tkAnd\n tkOr\n tkIf\n tkElse\n tkWhile\n tkPrint\n tkPutc\n tkLparen\n tkRparen\n tkLbrace\n tkRbrace\n tkSemi\n tkComma\n tkIdent\n tkInteger\n tkString\n)\n\ntype Symbol struct {\n name string\n tok TokenType\n}\n\n// symbol table\nvar symtab []Symbol\n\nvar scanner *bufio.Scanner\n\nvar (\n curLine = \"\"\n curCh byte\n lineNum = 0\n colNum = 0\n)\n\nconst etx byte = 4 // used to signify EOI\n\nfunc isDigit(ch byte) bool {\n return ch >= '0' && ch <= '9'\n}\n\nfunc isAlnum(ch byte) bool {\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || isDigit(ch)\n}\n\nfunc errorMsg(eline, ecol int, msg string) {\n log.Fatalf(\"(%d:%d) %s\", eline, ecol, msg)\n}\n\n// add an identifier to the symbol table\nfunc install(name string, tok TokenType) {\n sym := Symbol{name, tok}\n symtab = append(symtab, sym)\n}\n\n// search for an identifier in the symbol table\nfunc lookup(name string) int {\n for i := 0; i < len(symtab); i++ {\n if symtab[i].name == name {\n return i\n }\n }\n return -1\n}\n\n// read the next line of input from the source file\nfunc nextLine() {\n if scanner.Scan() {\n curLine = scanner.Text()\n lineNum++\n colNum = 0\n if curLine == \"\" { // skip blank lines\n nextLine()\n }\n } else {\n err := scanner.Err()\n if err == nil { // EOF\n curCh = etx\n curLine = \"\"\n lineNum++\n colNum = 1\n } else {\n log.Fatal(err)\n }\n }\n}\n\n// get the next char\nfunc nextChar() {\n if colNum >= len(curLine) {\n nextLine()\n }\n if colNum < len(curLine) {\n curCh = curLine[colNum]\n colNum++\n }\n}\n\nfunc follow(eline, ecol int, expect byte, ifyes, ifno TokenType) TokenType {\n if curCh == expect {\n nextChar()\n return ifyes\n }\n if ifno == tkEOI {\n errorMsg(eline, ecol, \"follow unrecognized character: \"+string(curCh))\n }\n return ifno\n}\n\nfunc gettok() (eline, ecol int, tok TokenType, v string) {\n // skip whitespace\n for curCh == ' ' || curCh == '\\t' || curCh == '\\n' {\n nextChar()\n }\n eline = lineNum\n ecol = colNum\n switch curCh {\n case etx:\n tok = tkEOI\n return\n case '{':\n tok = tkLbrace\n nextChar()\n return\n case '}':\n tok = tkRbrace\n nextChar()\n return\n case '(':\n tok = tkLparen\n nextChar()\n return\n case ')':\n tok = tkRparen\n nextChar()\n return\n case '+':\n tok = tkAdd\n nextChar()\n return\n case '-':\n tok = tkSub\n nextChar()\n return\n case '*':\n tok = tkMul\n nextChar()\n return\n case '%':\n tok = tkMod\n nextChar()\n return\n case ';':\n tok = tkSemi\n nextChar()\n return\n case ',':\n tok = tkComma\n nextChar()\n return\n case '/': // div or comment\n nextChar()\n if curCh != '*' {\n tok = tkDiv\n return\n }\n // skip comments\n nextChar()\n for {\n if curCh == '*' {\n nextChar()\n if curCh == '/' {\n nextChar()\n eline, ecol, tok, v = gettok()\n return\n }\n } else if curCh == etx {\n errorMsg(eline, ecol, \"EOF in comment\")\n } else {\n nextChar()\n }\n }\n case '\\'': // single char literals\n nextChar()\n v = fmt.Sprintf(\"%d\", curCh)\n if curCh == '\\'' {\n errorMsg(eline, ecol, \"Empty character constant\")\n }\n if curCh == '\\\\' {\n nextChar()\n if curCh == 'n' {\n v = \"10\"\n } else if curCh == '\\\\' {\n v = \"92\"\n } else {\n errorMsg(eline, ecol, \"unknown escape sequence: \"+string(curCh))\n }\n }\n nextChar()\n if curCh != '\\'' {\n errorMsg(eline, ecol, \"multi-character constant\")\n }\n nextChar()\n tok = tkInteger\n return\n case '<':\n nextChar()\n tok = follow(eline, ecol, '=', tkLeq, tkLss)\n return\n case '>':\n nextChar()\n tok = follow(eline, ecol, '=', tkGeq, tkGtr)\n return\n case '!':\n nextChar()\n tok = follow(eline, ecol, '=', tkNeq, tkNot)\n return\n case '=':\n nextChar()\n tok = follow(eline, ecol, '=', tkEq, tkAssign)\n return\n case '&':\n nextChar()\n tok = follow(eline, ecol, '&', tkAnd, tkEOI)\n return\n case '|':\n nextChar()\n tok = follow(eline, ecol, '|', tkOr, tkEOI)\n return\n case '\"': // string\n v = string(curCh)\n nextChar()\n for curCh != '\"' {\n if curCh == '\\n' {\n errorMsg(eline, ecol, \"EOL in string\")\n }\n if curCh == etx {\n errorMsg(eline, ecol, \"EOF in string\")\n }\n v += string(curCh)\n nextChar()\n }\n v += string(curCh)\n nextChar()\n tok = tkString\n return\n default: // integers or identifiers\n isNumber := isDigit(curCh)\n v = \"\"\n for isAlnum(curCh) || curCh == '_' {\n if !isDigit(curCh) {\n isNumber = false\n }\n v += string(curCh)\n nextChar()\n }\n if len(v) == 0 {\n errorMsg(eline, ecol, \"unknown character: \"+string(curCh))\n }\n if isDigit(v[0]) {\n if !isNumber {\n errorMsg(eline, ecol, \"invalid number: \"+string(curCh))\n }\n tok = tkInteger\n return\n }\n index := lookup(v)\n if index == -1 {\n tok = tkIdent\n } else {\n tok = symtab[index].tok\n }\n return\n }\n}\n\nfunc initLex() {\n install(\"else\", tkElse)\n install(\"if\", tkIf)\n install(\"print\", tkPrint)\n install(\"putc\", tkPutc)\n install(\"while\", tkWhile)\n nextChar()\n}\n\nfunc process() {\n tokMap := make(map[TokenType]string)\n tokMap[tkEOI] = \"End_of_input\"\n tokMap[tkMul] = \"Op_multiply\"\n tokMap[tkDiv] = \"Op_divide\"\n tokMap[tkMod] = \"Op_mod\"\n tokMap[tkAdd] = \"Op_add\"\n tokMap[tkSub] = \"Op_subtract\"\n tokMap[tkNegate] = \"Op_negate\"\n tokMap[tkNot] = \"Op_not\"\n tokMap[tkLss] = \"Op_less\"\n tokMap[tkLeq] = \"Op_lessequal\"\n tokMap[tkGtr] = \"Op_greater\"\n tokMap[tkGeq] = \"Op_greaterequal\"\n tokMap[tkEq] = \"Op_equal\"\n tokMap[tkNeq] = \"Op_notequal\"\n tokMap[tkAssign] = \"Op_assign\"\n tokMap[tkAnd] = \"Op_and\"\n tokMap[tkOr] = \"Op_or\"\n tokMap[tkIf] = \"Keyword_if\"\n tokMap[tkElse] = \"Keyword_else\"\n tokMap[tkWhile] = \"Keyword_while\"\n tokMap[tkPrint] = \"Keyword_print\"\n tokMap[tkPutc] = \"Keyword_putc\"\n tokMap[tkLparen] = \"LeftParen\"\n tokMap[tkRparen] = \"RightParen\"\n tokMap[tkLbrace] = \"LeftBrace\"\n tokMap[tkRbrace] = \"RightBrace\"\n tokMap[tkSemi] = \"Semicolon\"\n tokMap[tkComma] = \"Comma\"\n tokMap[tkIdent] = \"Identifier\"\n tokMap[tkInteger] = \"Integer\"\n tokMap[tkString] = \"String\"\n\n for {\n eline, ecol, tok, v := gettok()\n fmt.Printf(\"%5d %5d %-16s\", eline, ecol, tokMap[tok])\n if tok == tkInteger || tok == tkIdent || tok == tkString {\n fmt.Println(v)\n } else {\n fmt.Println()\n }\n if tok == tkEOI {\n return\n }\n }\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc main() {\n if len(os.Args) < 2 {\n fmt.Println(\"Filename required\")\n return\n }\n f, err := os.Open(os.Args[1])\n check(err)\n defer f.Close()\n scanner = bufio.NewScanner(f)\n initLex()\n process()\n}"} {"title": "Compiler/syntax analyzer", "language": "Go from C", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype TokenType int\n\nconst (\n tkEOI TokenType = iota\n tkMul\n tkDiv\n tkMod\n tkAdd\n tkSub\n tkNegate\n tkNot\n tkLss\n tkLeq\n tkGtr\n tkGeq\n tkEql\n tkNeq\n tkAssign\n tkAnd\n tkOr\n tkIf\n tkElse\n tkWhile\n tkPrint\n tkPutc\n tkLparen\n tkRparen\n tkLbrace\n tkRbrace\n tkSemi\n tkComma\n tkIdent\n tkInteger\n tkString\n)\n\ntype NodeType int\n\nconst (\n ndIdent NodeType = iota\n ndString\n ndInteger\n ndSequence\n ndIf\n ndPrtc\n ndPrts\n ndPrti\n ndWhile\n ndAssign\n ndNegate\n ndNot\n ndMul\n ndDiv\n ndMod\n ndAdd\n ndSub\n ndLss\n ndLeq\n ndGtr\n ndGeq\n ndEql\n ndNeq\n ndAnd\n ndOr\n)\n\ntype tokS struct {\n tok TokenType\n errLn int\n errCol int\n text string // ident or string literal or integer value\n}\n\ntype Tree struct {\n nodeType NodeType\n left *Tree\n right *Tree\n value string\n}\n\n// dependency: Ordered by tok, must remain in same order as TokenType consts\ntype atr struct {\n text string\n enumText string\n tok TokenType\n rightAssociative bool\n isBinary bool\n isUnary bool\n precedence int\n nodeType NodeType\n}\n\nvar atrs = []atr{\n {\"EOI\", \"End_of_input\", tkEOI, false, false, false, -1, -1},\n {\"*\", \"Op_multiply\", tkMul, false, true, false, 13, ndMul},\n {\"/\", \"Op_divide\", tkDiv, false, true, false, 13, ndDiv},\n {\"%\", \"Op_mod\", tkMod, false, true, false, 13, ndMod},\n {\"+\", \"Op_add\", tkAdd, false, true, false, 12, ndAdd},\n {\"-\", \"Op_subtract\", tkSub, false, true, false, 12, ndSub},\n {\"-\", \"Op_negate\", tkNegate, false, false, true, 14, ndNegate},\n {\"!\", \"Op_not\", tkNot, false, false, true, 14, ndNot},\n {\"<\", \"Op_less\", tkLss, false, true, false, 10, ndLss},\n {\"<=\", \"Op_lessequal\", tkLeq, false, true, false, 10, ndLeq},\n {\">\", \"Op_greater\", tkGtr, false, true, false, 10, ndGtr},\n {\">=\", \"Op_greaterequal\", tkGeq, false, true, false, 10, ndGeq},\n {\"==\", \"Op_equal\", tkEql, false, true, false, 9, ndEql},\n {\"!=\", \"Op_notequal\", tkNeq, false, true, false, 9, ndNeq},\n {\"=\", \"Op_assign\", tkAssign, false, false, false, -1, ndAssign},\n {\"&&\", \"Op_and\", tkAnd, false, true, false, 5, ndAnd},\n {\"||\", \"Op_or\", tkOr, false, true, false, 4, ndOr},\n {\"if\", \"Keyword_if\", tkIf, false, false, false, -1, ndIf},\n {\"else\", \"Keyword_else\", tkElse, false, false, false, -1, -1},\n {\"while\", \"Keyword_while\", tkWhile, false, false, false, -1, ndWhile},\n {\"print\", \"Keyword_print\", tkPrint, false, false, false, -1, -1},\n {\"putc\", \"Keyword_putc\", tkPutc, false, false, false, -1, -1},\n {\"(\", \"LeftParen\", tkLparen, false, false, false, -1, -1},\n {\")\", \"RightParen\", tkRparen, false, false, false, -1, -1},\n {\"{\", \"LeftBrace\", tkLbrace, false, false, false, -1, -1},\n {\"}\", \"RightBrace\", tkRbrace, false, false, false, -1, -1},\n {\";\", \"Semicolon\", tkSemi, false, false, false, -1, -1},\n {\",\", \"Comma\", tkComma, false, false, false, -1, -1},\n {\"Ident\", \"Identifier\", tkIdent, false, false, false, -1, ndIdent},\n {\"Integer literal\", \"Integer\", tkInteger, false, false, false, -1, ndInteger},\n {\"String literal\", \"String\", tkString, false, false, false, -1, ndString},\n}\n\nvar displayNodes = []string{\n \"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\", \"Prti\",\n \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\",\n \"NotEqual\", \"And\", \"Or\",\n}\n\nvar (\n err error\n token tokS\n scanner *bufio.Scanner\n)\n\nfunc reportError(errLine, errCol int, msg string) {\n log.Fatalf(\"(%d, %d) error : %s\\n\", errLine, errCol, msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc getEum(name string) TokenType { // return internal version of name#\n for _, atr := range atrs {\n if atr.enumText == name {\n return atr.tok\n }\n }\n reportError(0, 0, fmt.Sprintf(\"Unknown token %s\\n\", name))\n return tkEOI\n}\n\nfunc getTok() tokS {\n tok := tokS{}\n if scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n fields := strings.Fields(line)\n // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional\n tok.errLn, err = strconv.Atoi(fields[0])\n check(err)\n tok.errCol, err = strconv.Atoi(fields[1])\n check(err)\n tok.tok = getEum(fields[2])\n le := len(fields)\n if le == 4 {\n tok.text = fields[3]\n } else if le > 4 {\n idx := strings.Index(line, `\"`)\n tok.text = line[idx:]\n }\n }\n check(scanner.Err())\n return tok\n}\n\nfunc makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {\n return &Tree{nodeType, left, right, \"\"}\n}\n\nfunc makeLeaf(nodeType NodeType, value string) *Tree {\n return &Tree{nodeType, nil, nil, value}\n}\n\nfunc expect(msg string, s TokenType) {\n if token.tok == s {\n token = getTok()\n return\n }\n reportError(token.errLn, token.errCol,\n fmt.Sprintf(\"%s: Expecting '%s', found '%s'\\n\", msg, atrs[s].text, atrs[token.tok].text))\n}\n\nfunc expr(p int) *Tree {\n var x, node *Tree\n switch token.tok {\n case tkLparen:\n x = parenExpr()\n case tkSub, tkAdd:\n op := token.tok\n token = getTok()\n node = expr(atrs[tkNegate].precedence)\n if op == tkSub {\n x = makeNode(ndNegate, node, nil)\n } else {\n x = node\n }\n case tkNot:\n token = getTok()\n x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)\n case tkIdent:\n x = makeLeaf(ndIdent, token.text)\n token = getTok()\n case tkInteger:\n x = makeLeaf(ndInteger, token.text)\n token = getTok()\n default:\n reportError(token.errLn, token.errCol,\n fmt.Sprintf(\"Expecting a primary, found: %s\\n\", atrs[token.tok].text))\n }\n\n for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {\n op := token.tok\n token = getTok()\n q := atrs[op].precedence\n if !atrs[op].rightAssociative {\n q++\n }\n node = expr(q)\n x = makeNode(atrs[op].nodeType, x, node)\n }\n return x\n}\n\nfunc parenExpr() *Tree {\n expect(\"parenExpr\", tkLparen)\n t := expr(0)\n expect(\"parenExpr\", tkRparen)\n return t\n}\n\nfunc stmt() *Tree {\n var t, v, e, s, s2 *Tree\n switch token.tok {\n case tkIf:\n token = getTok()\n e = parenExpr()\n s = stmt()\n s2 = nil\n if token.tok == tkElse {\n token = getTok()\n s2 = stmt()\n }\n t = makeNode(ndIf, e, makeNode(ndIf, s, s2))\n case tkPutc:\n token = getTok()\n e = parenExpr()\n t = makeNode(ndPrtc, e, nil)\n expect(\"Putc\", tkSemi)\n case tkPrint: // print '(' expr {',' expr} ')'\n token = getTok()\n for expect(\"Print\", tkLparen); ; expect(\"Print\", tkComma) {\n if token.tok == tkString {\n e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)\n token = getTok()\n } else {\n e = makeNode(ndPrti, expr(0), nil)\n }\n t = makeNode(ndSequence, t, e)\n if token.tok != tkComma {\n break\n }\n }\n expect(\"Print\", tkRparen)\n expect(\"Print\", tkSemi)\n case tkSemi:\n token = getTok()\n case tkIdent:\n v = makeLeaf(ndIdent, token.text)\n token = getTok()\n expect(\"assign\", tkAssign)\n e = expr(0)\n t = makeNode(ndAssign, v, e)\n expect(\"assign\", tkSemi)\n case tkWhile:\n token = getTok()\n e = parenExpr()\n s = stmt()\n t = makeNode(ndWhile, e, s)\n case tkLbrace: // {stmt}\n for expect(\"Lbrace\", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {\n t = makeNode(ndSequence, t, stmt())\n }\n expect(\"Lbrace\", tkRbrace)\n case tkEOI:\n // do nothing\n default:\n reportError(token.errLn, token.errCol,\n fmt.Sprintf(\"expecting start of statement, found '%s'\\n\", atrs[token.tok].text))\n }\n return t\n}\n\nfunc parse() *Tree {\n var t *Tree\n token = getTok()\n for {\n t = makeNode(ndSequence, t, stmt())\n if t == nil || token.tok == tkEOI {\n break\n }\n }\n return t\n}\n\nfunc prtAst(t *Tree) {\n if t == nil {\n fmt.Print(\";\\n\")\n } else {\n fmt.Printf(\"%-14s \", displayNodes[t.nodeType])\n if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {\n fmt.Printf(\"%s\\n\", t.value)\n } else {\n fmt.Println()\n prtAst(t.left)\n prtAst(t.right)\n }\n }\n}\n\nfunc main() {\n source, err := os.Open(\"source.txt\")\n check(err)\n defer source.Close()\n scanner = bufio.NewScanner(source)\n prtAst(parse())\n}"} {"title": "Compiler/virtual machine interpreter", "language": "Go from Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"encoding/binary\"\n \"fmt\"\n \"log\"\n \"math\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\ntype code = byte\n\nconst (\n fetch code = iota\n store\n push\n add\n sub\n mul\n div\n mod\n lt\n gt\n le\n ge\n eq\n ne\n and\n or\n neg\n not\n jmp\n jz\n prtc\n prts\n prti\n halt\n)\n\nvar codeMap = map[string]code{\n \"fetch\": fetch,\n \"store\": store,\n \"push\": push,\n \"add\": add,\n \"sub\": sub,\n \"mul\": mul,\n \"div\": div,\n \"mod\": mod,\n \"lt\": lt,\n \"gt\": gt,\n \"le\": le,\n \"ge\": ge,\n \"eq\": eq,\n \"ne\": ne,\n \"and\": and,\n \"or\": or,\n \"neg\": neg,\n \"not\": not,\n \"jmp\": jmp,\n \"jz\": jz,\n \"prtc\": prtc,\n \"prts\": prts,\n \"prti\": prti,\n \"halt\": halt,\n}\n\nvar (\n err error\n scanner *bufio.Scanner\n object []code\n stringPool []string\n)\n\nfunc reportError(msg string) {\n log.Fatalf(\"error : %s\\n\", msg)\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc btoi(b bool) int32 {\n if b {\n return 1\n }\n return 0\n}\n\nfunc itob(i int32) bool {\n if i != 0 {\n return true\n }\n return false\n}\n\nfunc emitByte(c code) {\n object = append(object, c)\n}\n\nfunc emitWord(n int) {\n bs := make([]byte, 4)\n binary.LittleEndian.PutUint32(bs, uint32(n))\n for _, b := range bs {\n emitByte(code(b))\n }\n}\n\n/*** Virtual Machine interpreter ***/\nfunc runVM(dataSize int) {\n stack := make([]int32, dataSize+1)\n pc := int32(0)\n for {\n op := object[pc]\n pc++\n switch op {\n case fetch:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n stack = append(stack, stack[x])\n pc += 4\n case store:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n ln := len(stack)\n stack[x] = stack[ln-1]\n stack = stack[:ln-1]\n pc += 4\n case push:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n stack = append(stack, x)\n pc += 4\n case add:\n ln := len(stack)\n stack[ln-2] += stack[ln-1]\n stack = stack[:ln-1]\n case sub:\n ln := len(stack)\n stack[ln-2] -= stack[ln-1]\n stack = stack[:ln-1]\n case mul:\n ln := len(stack)\n stack[ln-2] *= stack[ln-1]\n stack = stack[:ln-1]\n case div:\n ln := len(stack)\n stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))\n stack = stack[:ln-1]\n case mod:\n ln := len(stack)\n stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))\n stack = stack[:ln-1]\n case lt:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])\n stack = stack[:ln-1]\n case gt:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])\n stack = stack[:ln-1]\n case le:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])\n stack = stack[:ln-1]\n case ge:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])\n stack = stack[:ln-1]\n case eq:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])\n stack = stack[:ln-1]\n case ne:\n ln := len(stack)\n stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])\n stack = stack[:ln-1]\n case and:\n ln := len(stack)\n stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))\n stack = stack[:ln-1]\n case or:\n ln := len(stack)\n stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))\n stack = stack[:ln-1]\n case neg:\n ln := len(stack)\n stack[ln-1] = -stack[ln-1]\n case not:\n ln := len(stack)\n stack[ln-1] = btoi(!itob(stack[ln-1]))\n case jmp:\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n pc += x\n case jz:\n ln := len(stack)\n v := stack[ln-1]\n stack = stack[:ln-1]\n if v != 0 {\n pc += 4\n } else {\n x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))\n pc += x\n }\n case prtc:\n ln := len(stack)\n fmt.Printf(\"%c\", stack[ln-1])\n stack = stack[:ln-1]\n case prts:\n ln := len(stack)\n fmt.Printf(\"%s\", stringPool[stack[ln-1]])\n stack = stack[:ln-1]\n case prti:\n ln := len(stack)\n fmt.Printf(\"%d\", stack[ln-1])\n stack = stack[:ln-1]\n case halt:\n return\n default:\n reportError(fmt.Sprintf(\"Unknown opcode %d\\n\", op))\n }\n }\n}\n\nfunc translate(s string) string {\n var d strings.Builder\n for i := 0; i < len(s); i++ {\n if s[i] == '\\\\' && (i+1) < len(s) {\n if s[i+1] == 'n' {\n d.WriteByte('\\n')\n i++\n } else if s[i+1] == '\\\\' {\n d.WriteByte('\\\\')\n i++\n }\n } else {\n d.WriteByte(s[i])\n }\n }\n return d.String()\n}\n\nfunc loadCode() int {\n var dataSize int\n firstLine := true\n for scanner.Scan() {\n line := strings.TrimRight(scanner.Text(), \" \\t\")\n if len(line) == 0 {\n if firstLine {\n reportError(\"empty line\")\n } else {\n break\n }\n }\n lineList := strings.Fields(line)\n if firstLine {\n dataSize, err = strconv.Atoi(lineList[1])\n check(err)\n nStrings, err := strconv.Atoi(lineList[3])\n check(err)\n for i := 0; i < nStrings; i++ {\n scanner.Scan()\n s := strings.Trim(scanner.Text(), \"\\\"\\n\")\n stringPool = append(stringPool, translate(s))\n }\n firstLine = false\n continue\n }\n offset, err := strconv.Atoi(lineList[0])\n check(err)\n instr := lineList[1]\n opCode, ok := codeMap[instr]\n if !ok {\n reportError(fmt.Sprintf(\"Unknown instruction %s at %d\", instr, opCode))\n }\n emitByte(opCode)\n switch opCode {\n case jmp, jz:\n p, err := strconv.Atoi(lineList[3])\n check(err)\n emitWord(p - offset - 1)\n case push:\n value, err := strconv.Atoi(lineList[2])\n check(err)\n emitWord(value)\n case fetch, store:\n value, err := strconv.Atoi(strings.Trim(lineList[2], \"[]\"))\n check(err)\n emitWord(value)\n }\n }\n check(scanner.Err())\n return dataSize\n}\n\nfunc main() {\n codeGen, err := os.Open(\"codegen.txt\")\n check(err)\n defer codeGen.Close()\n scanner = bufio.NewScanner(codeGen)\n runVM(loadCode())\n}"} {"title": "Conjugate transpose", "language": "Go", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n\n// a type to represent matrices\ntype matrix struct {\n ele []complex128\n cols int\n}\n\n// conjugate transpose, implemented here as a method on the matrix type.\nfunc (m *matrix) conjTranspose() *matrix {\n r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}\n rx := 0\n for _, e := range m.ele {\n r.ele[rx] = cmplx.Conj(e)\n rx += r.cols\n if rx >= len(r.ele) {\n rx -= len(r.ele) - 1\n }\n }\n return r\n}\n\n// program to demonstrate capabilites on example matricies\nfunc main() {\n show(\"h\", matrixFromRows([][]complex128{\n {3, 2 + 1i},\n {2 - 1i, 1}}))\n\n show(\"n\", matrixFromRows([][]complex128{\n {1, 1, 0},\n {0, 1, 1},\n {1, 0, 1}}))\n\n show(\"u\", matrixFromRows([][]complex128{\n {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},\n {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},\n {0, 0, 1i}}))\n}\n\nfunc show(name string, m *matrix) {\n m.print(name)\n ct := m.conjTranspose()\n ct.print(name + \"_ct\")\n\n fmt.Println(\"Hermitian:\", m.equal(ct, 1e-14))\n\n mct := m.mult(ct)\n ctm := ct.mult(m)\n fmt.Println(\"Normal:\", mct.equal(ctm, 1e-14))\n\n i := eye(m.cols)\n fmt.Println(\"Unitary:\", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))\n}\n\n// two constructors\nfunc matrixFromRows(rows [][]complex128) *matrix {\n m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}\n for rx, row := range rows {\n copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)\n }\n return m\n}\n\nfunc eye(n int) *matrix {\n r := &matrix{make([]complex128, n*n), n}\n n++\n for x := 0; x < len(r.ele); x += n {\n r.ele[x] = 1\n }\n return r\n}\n\n// print method outputs matrix to stdout\nfunc (m *matrix) print(heading string) {\n fmt.Print(\"\\n\", heading, \"\\n\")\n for e := 0; e < len(m.ele); e += m.cols {\n fmt.Printf(\"%6.3f \", m.ele[e:e+m.cols])\n fmt.Println()\n }\n}\n\n// equal method uses \u03b5 to allow for floating point error.\nfunc (a *matrix) equal(b *matrix, \u03b5 float64) bool {\n for x, aEle := range a.ele {\n if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*\u03b5 ||\n math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*\u03b5 {\n return false\n }\n }\n return true\n}\n\n// mult method taken from matrix multiply task\nfunc (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {\n m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}\n for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {\n for m2r0 := 0; m2r0 < m2.cols; m2r0++ {\n for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {\n m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]\n m1x++\n }\n m3x++\n }\n }\n return m3\n}"} {"title": "Continued fraction", "language": "Go", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype cfTerm struct {\n a, b int\n}\n\n// follows subscript convention of mathworld and WP where there is no b(0).\n// cf[0].b is unused in this representation.\ntype cf []cfTerm\n\nfunc cfSqrt2(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n f[n] = cfTerm{2, 1}\n }\n f[0].a = 1\n return f\n}\n\nfunc cfNap(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n f[n] = cfTerm{n, n - 1}\n }\n f[0].a = 2\n f[1].b = 1\n return f\n}\n\nfunc cfPi(nTerms int) cf {\n f := make(cf, nTerms)\n for n := range f {\n g := 2*n - 1\n f[n] = cfTerm{6, g * g}\n }\n f[0].a = 3\n return f\n}\n\nfunc (f cf) real() (r float64) {\n for n := len(f) - 1; n > 0; n-- {\n r = float64(f[n].b) / (float64(f[n].a) + r)\n }\n return r + float64(f[0].a)\n}\n\nfunc main() {\n fmt.Println(\"sqrt2:\", cfSqrt2(20).real())\n fmt.Println(\"nap: \", cfNap(20).real())\n fmt.Println(\"pi: \", cfPi(20).real())\n}"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Go", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "package cf\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// ContinuedFraction is a regular continued fraction.\ntype ContinuedFraction func() NextFn\n\n// NextFn is a function/closure that can return\n// a posibly infinite sequence of values.\ntype NextFn func() (term int64, ok bool)\n\n// String implements fmt.Stringer.\n// It formats a maximum of 20 values, ending the\n// sequence with \", ...\" if the sequence is longer.\nfunc (cf ContinuedFraction) String() string {\n\tvar buf strings.Builder\n\tbuf.WriteByte('[')\n\tsep := \"; \"\n\tconst maxTerms = 20\n\tnext := cf()\n\tfor n := 0; ; n++ {\n\t\tt, ok := next()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif n > 0 {\n\t\t\tbuf.WriteString(sep)\n\t\t\tsep = \", \"\n\t\t}\n\t\tif n >= maxTerms {\n\t\t\tbuf.WriteString(\"...\")\n\t\t\tbreak\n\t\t}\n\t\tfmt.Fprint(&buf, t)\n\t}\n\tbuf.WriteByte(']')\n\treturn buf.String()\n}\n\n// Sqrt2 is the continued fraction for \u221a2, [1; 2, 2, 2, ...].\nfunc Sqrt2() NextFn {\n\tfirst := true\n\treturn func() (int64, bool) {\n\t\tif first {\n\t\t\tfirst = false\n\t\t\treturn 1, true\n\t\t}\n\t\treturn 2, true\n\t}\n}\n\n// Phi is the continued fraction for \u03d5, [1; 1, 1, 1, ...].\nfunc Phi() NextFn {\n\treturn func() (int64, bool) { return 1, true }\n}\n\n// E is the continued fraction for e,\n// [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...].\nfunc E() NextFn {\n\tvar i int\n\treturn func() (int64, bool) {\n\t\ti++\n\t\tswitch {\n\t\tcase i == 1:\n\t\t\treturn 2, true\n\t\tcase i%3 == 0:\n\t\t\treturn int64(i/3) * 2, true\n\t\tdefault:\n\t\t\treturn 1, true\n\t\t}\n\t}\n}"} {"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Go", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "package cf\n\n// A 2\u00d72 matix:\n// [ a\u2081 a ]\n// [ b\u2081 b ]\n//\n// which when \"applied\" to a continued fraction representing x\n// gives a new continued fraction z such that:\n//\n// a\u2081 * x + a\n// z = ----------\n// b\u2081 * x + b\n//\n// Examples:\n// NG4{0, 1, 0, 4}.ApplyTo(x) gives 0*x + 1/4 -> 1/4 = [0; 4]\n// NG4{0, 1, 1, 0}.ApplyTo(x) gives 1/x\n// NG4{1, 1, 0, 2}.ApplyTo(x) gives (x+1)/2\n//\n// Note that several operations (e.g.\u00a0addition and division)\n// can be efficiently done with a single matrix application.\n// However, each matrix application may require\n// several calculations for each outputed term.\ntype NG4 struct {\n\tA1, A int64\n\tB1, B int64\n}\n\nfunc (ng NG4) needsIngest() bool {\n\tif ng.isDone() {\n\t\tpanic(\"b\u2081==b==0\")\n\t}\n\treturn ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B\n}\n\nfunc (ng NG4) isDone() bool {\n\treturn ng.B1 == 0 && ng.B == 0\n}\n\nfunc (ng *NG4) ingest(t int64) {\n\t// [ a\u2081 a ] becomes [ a + a\u2081\u00d7t a\u2081 ]\n\t// [ b\u2081 b ] [ b + b\u2081\u00d7t b\u2081 ]\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.A+ng.A1*t, ng.A1,\n\t\tng.B+ng.B1*t, ng.B1\n}\n\nfunc (ng *NG4) ingestInfinite() {\n\t// [ a\u2081 a ] becomes [ a\u2081 a\u2081 ]\n\t// [ b\u2081 b ] [ b\u2081 b\u2081 ]\n\tng.A, ng.B = ng.A1, ng.B1\n}\n\nfunc (ng *NG4) egest(t int64) {\n\t// [ a\u2081 a ] becomes [ b\u2081 b ]\n\t// [ b\u2081 b ] [ a\u2081 - b\u2081\u00d7t a - b\u00d7t ]\n\tng.A1, ng.A, ng.B1, ng.B =\n\t\tng.B1, ng.B,\n\t\tng.A1-ng.B1*t, ng.A-ng.B*t\n}\n\n// ApplyTo \"applies\" the matrix `ng` to the continued fraction `cf`,\n// returning the resulting continued fraction.\nfunc (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {\n\treturn func() NextFn {\n\t\tnext := cf()\n\t\tdone := false\n\t\treturn func() (int64, bool) {\n\t\t\tif done {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tfor ng.needsIngest() {\n\t\t\t\tif t, ok := next(); ok {\n\t\t\t\t\tng.ingest(t)\n\t\t\t\t} else {\n\t\t\t\t\tng.ingestInfinite()\n\t\t\t\t}\n\t\t\t}\n\t\t\tt := ng.A1 / ng.B1\n\t\t\tng.egest(t)\n\t\t\tdone = ng.isDone()\n\t\t\treturn t, true\n\t\t}\n\t}\n}"} {"title": "Convert decimal number to rational", "language": "Go", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n for _, d := range []string{\"0.9054054\", \"0.518518\", \"0.75\"} {\n if r, ok := new(big.Rat).SetString(d); ok {\n fmt.Println(d, \"=\", r)\n } else {\n fmt.Println(d, \"invalid decimal number\")\n }\n }\n}"} {"title": "Convert seconds to compound duration", "language": "Go", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main(){\n\tfmt.Println(TimeStr(7259))\n\tfmt.Println(TimeStr(86400))\n\tfmt.Println(TimeStr(6000000))\n}\n\nfunc TimeStr(sec int)(res string){\n\twks, sec := sec / 604800,sec % 604800\n\tds, sec := sec / 86400, sec % 86400\n\thrs, sec := sec / 3600, sec % 3600\n\tmins, sec := sec / 60, sec % 60\n\tCommaRequired := false\n\tif wks != 0 {\n\t\tres += fmt.Sprintf(\"%d wk\",wks)\n\t\tCommaRequired = true\n\t}\n\tif ds != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d d\",ds)\n\t\tCommaRequired = true\n\t}\n\tif hrs != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d hr\",hrs)\n\t\tCommaRequired = true\n\t}\n\tif mins != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d min\",mins)\n\t\tCommaRequired = true\n\t}\n\tif sec != 0 {\n\t\tif CommaRequired {\n\t\t\tres += \", \"\n\t\t}\n\t\tres += fmt.Sprintf(\"%d sec\",sec)\n\t}\n\treturn\n}\n"} {"title": "Copy stdin to stdout", "language": "Go", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"io\"\n \"os\"\n)\n\nfunc main() {\n r := bufio.NewReader(os.Stdin)\n w := bufio.NewWriter(os.Stdout)\n for {\n b, err := r.ReadByte() \n if err == io.EOF {\n return\n }\n w.WriteByte(b)\n w.Flush()\n } \n}"} {"title": "Count the coins", "language": "Go from lisp", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n amount := 100\n fmt.Println(\"amount, ways to make change:\", amount, countChange(amount))\n}\n\nfunc countChange(amount int) int64 {\n return cc(amount, 4)\n}\n\nfunc cc(amount, kindsOfCoins int) int64 {\n switch {\n case amount == 0:\n return 1\n case amount < 0 || kindsOfCoins == 0:\n return 0\n }\n return cc(amount, kindsOfCoins-1) +\n cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)\n}\n\nfunc firstDenomination(kindsOfCoins int) int {\n switch kindsOfCoins {\n case 1:\n return 1\n case 2:\n return 5\n case 3:\n return 10\n case 4:\n return 25\n }\n panic(kindsOfCoins)\n}"} {"title": "Create an HTML table", "language": "Go", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"html/template\"\n \"os\"\n)\n\ntype row struct {\n X, Y, Z int\n}\n\nvar tmpl = `\n \n{{range $ix, $row := .}} \n \n \n \n{{end}}
XYZ
{{$ix}}{{$row.X}}{{$row.Y}}{{$row.Z}}
\n`\n\nfunc main() {\n // create template\n ct := template.Must(template.New(\"\").Parse(tmpl))\n\n // make up data\n data := make([]row, 4)\n for r := range data {\n data[r] = row{r*3, r*3+1, r*3+2}\n }\n\n // apply template to data\n if err := ct.Execute(os.Stdout, data); err != nil {\n fmt.Println(err)\n }\n}"} {"title": "Currency", "language": "Go", "task": "Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n\nDollar signs and thousands separators are optional.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\n// DC for dollars and cents. Value is an integer number of cents.\ntype DC int64\n\nfunc (dc DC) String() string {\n d := dc / 100\n if dc < 0 {\n dc = -dc\n }\n return fmt.Sprintf(\"%d.%02d\", d, dc%100)\n}\n\n// Extend returns extended price of a unit price.\nfunc (dc DC) Extend(n int) DC {\n return dc * DC(n)\n}\n\nvar one = big.NewInt(1)\nvar hundred = big.NewRat(100, 1)\n\n// ParseDC parses dollars and cents as a string into a DC.\nfunc ParseDC(s string) (DC, bool) {\n r, ok := new(big.Rat).SetString(s)\n if !ok {\n return 0, false\n }\n r.Mul(r, hundred)\n if r.Denom().Cmp(one) != 0 {\n return 0, false\n }\n return DC(r.Num().Int64()), true\n}\n\n// TR for tax rate. Value is an an exact rational.\ntype TR struct {\n *big.Rat\n}\nfunc NewTR() TR {\n return TR{new(big.Rat)}\n}\n\n// SetString overrides Rat.SetString to return the TR type.\nfunc (tr TR) SetString(s string) (TR, bool) {\n if _, ok := tr.Rat.SetString(s); !ok {\n return TR{}, false\n }\n return tr, true\n}\n\nvar half = big.NewRat(1, 2)\n\n// Tax computes a tax amount, rounding to the nearest cent.\nfunc (tr TR) Tax(dc DC) DC {\n r := big.NewRat(int64(dc), 1)\n r.Add(r.Mul(r, tr.Rat), half)\n return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())\n}\n\nfunc main() {\n hamburgerPrice, ok := ParseDC(\"5.50\")\n if !ok {\n log.Fatal(\"Invalid hamburger price\")\n }\n milkshakePrice, ok := ParseDC(\"2.86\")\n if !ok {\n log.Fatal(\"Invalid milkshake price\")\n }\n taxRate, ok := NewTR().SetString(\"0.0765\")\n if !ok {\n log.Fatal(\"Invalid tax rate\")\n }\n\n totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +\n milkshakePrice.Extend(2)\n tax := taxRate.Tax(totalBeforeTax)\n total := totalBeforeTax + tax\n\n fmt.Printf(\"Total before tax: %22s\\n\", totalBeforeTax)\n fmt.Printf(\" Tax: %22s\\n\", tax)\n fmt.Printf(\" Total: %22s\\n\", total)\n}"} {"title": "Currying", "language": "Go", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc PowN(b float64) func(float64) float64 {\n return func(e float64) float64 { return math.Pow(b, e) }\n}\n\nfunc PowE(e float64) func(float64) float64 {\n return func(b float64) float64 { return math.Pow(b, e) }\n}\n\ntype Foo int\n\nfunc (f Foo) Method(b int) int {\n return int(f) + b\n}\n\nfunc main() {\n pow2 := PowN(2)\n cube := PowE(3)\n\n fmt.Println(\"2^8 =\", pow2(8))\n fmt.Println(\"4\u00b3 =\", cube(4))\n\n var a Foo = 2\n fn1 := a.Method // A \"method value\", like currying 'a'\n fn2 := Foo.Method // A \"method expression\", like uncurrying\n\n fmt.Println(\"2 + 2 =\", a.Method(2)) // regular method call\n fmt.Println(\"2 + 3 =\", fn1(3))\n fmt.Println(\"2 + 4 =\", fn2(a, 4))\n fmt.Println(\"3 + 5 =\", fn2(Foo(3), 5))\n}"} {"title": "Curzon numbers", "language": "Go from Wren", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* Numbers Aplenty - Curzon numbers\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n zero := big.NewInt(0)\n one := big.NewInt(1)\n for k := int64(2); k <= 10; k += 2 {\n bk := big.NewInt(k)\n fmt.Println(\"The first 50 Curzon numbers using a base of\", k, \":\")\n count := 0\n n := int64(1)\n pow := big.NewInt(k)\n z := new(big.Int)\n var curzon50 []int64\n for {\n z.Add(pow, one)\n d := k*n + 1\n bd := big.NewInt(d)\n if z.Rem(z, bd).Cmp(zero) == 0 {\n if count < 50 {\n curzon50 = append(curzon50, n)\n }\n count++\n if count == 50 {\n for i := 0; i < len(curzon50); i++ {\n fmt.Printf(\"%4d \", curzon50[i])\n if (i+1)%10 == 0 {\n fmt.Println()\n }\n }\n fmt.Print(\"\\nOne thousandth: \")\n }\n if count == 1000 {\n fmt.Println(n)\n break\n }\n }\n n++\n pow.Mul(pow, bk)\n }\n fmt.Println()\n }\n}"} {"title": "Cut a rectangle", "language": "Go from C", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar grid []byte\nvar w, h, last int\nvar cnt int\nvar next [4]int\nvar dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}\n\nfunc walk(y, x int) {\n if y == 0 || y == h || x == 0 || x == w {\n cnt += 2\n return\n }\n t := y*(w+1) + x\n grid[t]++\n grid[last-t]++\n for i, d := range dir {\n if grid[t+next[i]] == 0 {\n walk(y+d[0], x+d[1])\n }\n }\n grid[t]--\n grid[last-t]--\n}\n\nfunc solve(hh, ww, recur int) int {\n h = hh\n w = ww\n\n if h&1 != 0 {\n h, w = w, h\n }\n switch {\n case h&1 == 1:\n return 0\n case w == 1:\n return 1\n case w == 2:\n return h\n case h == 2:\n return w\n }\n cy := h / 2\n cx := w / 2\n\n grid = make([]byte, (h+1)*(w+1))\n last = len(grid) - 1\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n\n if recur != 0 {\n cnt = 0\n }\n for x := cx + 1; x < w; x++ {\n t := cy*(w+1) + x\n grid[t] = 1\n grid[last-t] = 1\n walk(cy-1, x)\n }\n cnt++\n\n if h == w {\n cnt *= 2\n } else if w&1 == 0 && recur != 0 {\n solve(w, h, 0)\n }\n return cnt\n}\n\nfunc main() {\n for y := 1; y <= 10; y++ {\n for x := 1; x <= y; x++ {\n if x&1 == 0 || y&1 == 0 {\n fmt.Printf(\"%d x %d: %d\\n\", y, x, solve(y, x, 1))\n }\n }\n }\n}"} {"title": "Cyclotomic polynomial", "language": "Go from Java", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n \"sort\"\n \"strings\"\n)\n\nconst (\n algo = 2\n maxAllFactors = 100000\n)\n\nfunc iabs(i int) int {\n if i < 0 {\n return -i\n }\n return i\n}\n\ntype term struct{ coef, exp int }\n\nfunc (t term) mul(t2 term) term {\n return term{t.coef * t2.coef, t.exp + t2.exp}\n}\n\nfunc (t term) add(t2 term) term {\n if t.exp != t2.exp {\n log.Fatal(\"exponents unequal in term.add method\")\n }\n return term{t.coef + t2.coef, t.exp}\n}\n\nfunc (t term) negate() term { return term{-t.coef, t.exp} }\n\nfunc (t term) String() string {\n switch {\n case t.coef == 0:\n return \"0\"\n case t.exp == 0:\n return fmt.Sprintf(\"%d\", t.coef)\n case t.coef == 1:\n if t.exp == 1 {\n return \"x\"\n } else {\n return fmt.Sprintf(\"x^%d\", t.exp)\n }\n case t.exp == 1:\n return fmt.Sprintf(\"%dx\", t.coef)\n }\n return fmt.Sprintf(\"%dx^%d\", t.coef, t.exp)\n}\n\ntype poly struct{ terms []term }\n\n// pass coef, exp in pairs as parameters\nfunc newPoly(values ...int) poly {\n le := len(values)\n if le == 0 {\n return poly{[]term{term{0, 0}}}\n }\n if le%2 != 0 {\n log.Fatalf(\"odd number of parameters (%d) passed to newPoly function\", le)\n }\n var terms []term\n for i := 0; i < le; i += 2 {\n terms = append(terms, term{values[i], values[i+1]})\n }\n p := poly{terms}.tidy()\n return p\n}\n\nfunc (p poly) hasCoefAbs(coef int) bool {\n for _, t := range p.terms {\n if iabs(t.coef) == coef {\n return true\n }\n }\n return false\n}\n\nfunc (p poly) add(p2 poly) poly {\n p3 := newPoly()\n le, le2 := len(p.terms), len(p2.terms)\n for le > 0 || le2 > 0 {\n if le == 0 {\n p3.terms = append(p3.terms, p2.terms[le2-1])\n le2--\n } else if le2 == 0 {\n p3.terms = append(p3.terms, p.terms[le-1])\n le--\n } else {\n t := p.terms[le-1]\n t2 := p2.terms[le2-1]\n if t.exp == t2.exp {\n t3 := t.add(t2)\n if t3.coef != 0 {\n p3.terms = append(p3.terms, t3)\n }\n le--\n le2--\n } else if t.exp < t2.exp {\n p3.terms = append(p3.terms, t)\n le--\n } else {\n p3.terms = append(p3.terms, t2)\n le2--\n }\n }\n }\n return p3.tidy()\n}\n\nfunc (p poly) addTerm(t term) poly {\n q := newPoly()\n added := false\n for i := 0; i < len(p.terms); i++ {\n ct := p.terms[i]\n if ct.exp == t.exp {\n added = true\n if ct.coef+t.coef != 0 {\n q.terms = append(q.terms, ct.add(t))\n }\n } else {\n q.terms = append(q.terms, ct)\n }\n }\n if !added {\n q.terms = append(q.terms, t)\n }\n return q.tidy()\n}\n\nfunc (p poly) mulTerm(t term) poly {\n q := newPoly()\n for i := 0; i < len(p.terms); i++ {\n ct := p.terms[i]\n q.terms = append(q.terms, ct.mul(t))\n }\n return q.tidy()\n}\n\nfunc (p poly) div(v poly) poly {\n q := newPoly()\n lcv := v.leadingCoef()\n dv := v.degree()\n for p.degree() >= v.degree() {\n lcp := p.leadingCoef()\n s := lcp / lcv\n t := term{s, p.degree() - dv}\n q = q.addTerm(t)\n p = p.add(v.mulTerm(t.negate()))\n }\n return q.tidy()\n}\n\nfunc (p poly) leadingCoef() int {\n return p.terms[0].coef\n}\n\nfunc (p poly) degree() int {\n return p.terms[0].exp\n}\n\nfunc (p poly) String() string {\n var sb strings.Builder\n first := true\n for _, t := range p.terms {\n if first {\n sb.WriteString(t.String())\n first = false\n } else {\n sb.WriteString(\" \")\n if t.coef > 0 {\n sb.WriteString(\"+ \")\n sb.WriteString(t.String())\n } else {\n sb.WriteString(\"- \")\n sb.WriteString(t.negate().String())\n }\n }\n }\n return sb.String()\n}\n\n// in place descending sort by term.exp\nfunc (p poly) sortTerms() {\n sort.Slice(p.terms, func(i, j int) bool {\n return p.terms[i].exp > p.terms[j].exp\n })\n}\n\n// sort terms and remove any unnecesary zero terms\nfunc (p poly) tidy() poly {\n p.sortTerms()\n if p.degree() == 0 {\n return p\n }\n for i := len(p.terms) - 1; i >= 0; i-- {\n if p.terms[i].coef == 0 {\n copy(p.terms[i:], p.terms[i+1:])\n p.terms[len(p.terms)-1] = term{0, 0}\n p.terms = p.terms[:len(p.terms)-1]\n }\n }\n if len(p.terms) == 0 {\n p.terms = append(p.terms, term{0, 0})\n }\n return p\n}\n\nfunc getDivisors(n int) []int {\n var divs []int\n sqrt := int(math.Sqrt(float64(n)))\n for i := 1; i <= sqrt; i++ {\n if n%i == 0 {\n divs = append(divs, i)\n d := n / i\n if d != i && d != n {\n divs = append(divs, d)\n }\n }\n }\n return divs\n}\n\nvar (\n computed = make(map[int]poly)\n allFactors = make(map[int]map[int]int)\n)\n\nfunc init() {\n f := map[int]int{2: 1}\n allFactors[2] = f\n}\n\nfunc getFactors(n int) map[int]int {\n if f, ok := allFactors[n]; ok {\n return f\n }\n factors := make(map[int]int)\n if n%2 == 0 {\n factorsDivTwo := getFactors(n / 2)\n for k, v := range factorsDivTwo {\n factors[k] = v\n }\n factors[2]++\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n return factors\n }\n prime := true\n sqrt := int(math.Sqrt(float64(n)))\n for i := 3; i <= sqrt; i += 2 {\n if n%i == 0 {\n prime = false\n for k, v := range getFactors(n / i) {\n factors[k] = v\n }\n factors[i]++\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n return factors\n }\n }\n if prime {\n factors[n] = 1\n if n < maxAllFactors {\n allFactors[n] = factors\n }\n }\n return factors\n}\n\nfunc cycloPoly(n int) poly {\n if p, ok := computed[n]; ok {\n return p\n }\n if n == 1 {\n // polynomial: x - 1\n p := newPoly(1, 1, -1, 0)\n computed[1] = p\n return p\n }\n factors := getFactors(n)\n cyclo := newPoly()\n if _, ok := factors[n]; ok {\n // n is prime\n for i := 0; i < n; i++ {\n cyclo.terms = append(cyclo.terms, term{1, i})\n }\n } else if len(factors) == 2 && factors[2] == 1 && factors[n/2] == 1 {\n // n == 2p\n prime := n / 2\n coef := -1\n for i := 0; i < prime; i++ {\n coef *= -1\n cyclo.terms = append(cyclo.terms, term{coef, i})\n }\n } else if len(factors) == 1 {\n if h, ok := factors[2]; ok {\n // n == 2^h\n cyclo.terms = append(cyclo.terms, term{1, 1 << (h - 1)}, term{1, 0})\n } else if _, ok := factors[n]; !ok {\n // n == p ^ k\n p := 0\n for prime := range factors {\n p = prime\n }\n k := factors[p]\n for i := 0; i < p; i++ {\n pk := int(math.Pow(float64(p), float64(k-1)))\n cyclo.terms = append(cyclo.terms, term{1, i * pk})\n }\n }\n } else if len(factors) == 2 && factors[2] != 0 {\n // n = 2^h * p^k\n p := 0\n for prime := range factors {\n if prime != 2 {\n p = prime\n }\n }\n coef := -1\n twoExp := 1 << (factors[2] - 1)\n k := factors[p]\n for i := 0; i < p; i++ {\n coef *= -1\n pk := int(math.Pow(float64(p), float64(k-1)))\n cyclo.terms = append(cyclo.terms, term{coef, i * twoExp * pk})\n }\n } else if factors[2] != 0 && ((n/2)%2 == 1) && (n/2) > 1 {\n // CP(2m)[x] == CP(-m)[x], n odd integer > 1\n cycloDiv2 := cycloPoly(n / 2)\n for _, t := range cycloDiv2.terms {\n t2 := t\n if t.exp%2 != 0 {\n t2 = t.negate()\n }\n cyclo.terms = append(cyclo.terms, t2)\n }\n } else if algo == 0 {\n // slow - uses basic definition\n divs := getDivisors(n)\n // polynomial: x^n - 1\n cyclo = newPoly(1, n, -1, 0)\n for _, i := range divs {\n p := cycloPoly(i)\n cyclo = cyclo.div(p)\n }\n } else if algo == 1 {\n // faster - remove max divisor (and all divisors of max divisor)\n // only one divide for all divisors of max divisor\n divs := getDivisors(n)\n maxDiv := math.MinInt32\n for _, d := range divs {\n if d > maxDiv {\n maxDiv = d\n }\n }\n var divsExceptMax []int\n for _, d := range divs {\n if maxDiv%d != 0 {\n divsExceptMax = append(divsExceptMax, d)\n }\n }\n // polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n cyclo = newPoly(1, n, -1, 0)\n cyclo = cyclo.div(newPoly(1, maxDiv, -1, 0))\n for _, i := range divsExceptMax {\n p := cycloPoly(i)\n cyclo = cyclo.div(p)\n }\n } else if algo == 2 {\n // fastest\n // let p, q be primes such that p does not divide n, and q divides n\n // then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n m := 1\n cyclo = cycloPoly(m)\n var primes []int\n for prime := range factors {\n primes = append(primes, prime)\n }\n sort.Ints(primes)\n for _, prime := range primes {\n // CP(m)[x]\n cycloM := cyclo\n // compute CP(m)[x^p]\n var terms []term\n for _, t := range cycloM.terms {\n terms = append(terms, term{t.coef, t.exp * prime})\n }\n cyclo = newPoly()\n cyclo.terms = append(cyclo.terms, terms...)\n cyclo = cyclo.tidy()\n cyclo = cyclo.div(cycloM)\n m *= prime\n }\n // now, m is the largest square free divisor of n\n s := n / m\n // Compute CP(n)[x] = CP(m)[x^s]\n var terms []term\n for _, t := range cyclo.terms {\n terms = append(terms, term{t.coef, t.exp * s})\n }\n cyclo = newPoly()\n cyclo.terms = append(cyclo.terms, terms...)\n } else {\n log.Fatal(\"invalid algorithm\")\n }\n cyclo = cyclo.tidy()\n computed[n] = cyclo\n return cyclo\n}\n\nfunc main() {\n fmt.Println(\"Task 1: cyclotomic polynomials for n <= 30:\")\n for i := 1; i <= 30; i++ {\n p := cycloPoly(i)\n fmt.Printf(\"CP[%2d] = %s\\n\", i, p)\n }\n\n fmt.Println(\"\\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\n n := 0\n for i := 1; i <= 10; i++ {\n for {\n n++\n cyclo := cycloPoly(n)\n if cyclo.hasCoefAbs(i) {\n fmt.Printf(\"CP[%d] has coefficient with magnitude = %d\\n\", n, i)\n n--\n break\n }\n }\n }\n}"} {"title": "Damm algorithm", "language": "Go", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar table = [10][10]byte{\n {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n}\n\nfunc damm(input string) bool {\n var interim byte\n for _, c := range []byte(input) {\n interim = table[interim][c-'0']\n }\n return interim == 0\n}\n\nfunc main() {\n for _, s := range []string{\"5724\", \"5727\", \"112946\", \"112949\"} {\n fmt.Printf(\"%6s %t\\n\", s, damm(s))\n }\n}"} {"title": "De Bruijn sequences", "language": "Go", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nconst digits = \"0123456789\"\n\nfunc deBruijn(k, n int) string {\n alphabet := digits[0:k]\n a := make([]byte, k*n)\n var seq []byte\n var db func(int, int) // recursive closure\n db = func(t, p int) {\n if t > n {\n if n%p == 0 {\n seq = append(seq, a[1:p+1]...)\n }\n } else {\n a[t] = a[t-p]\n db(t+1, p)\n for j := int(a[t-p] + 1); j < k; j++ {\n a[t] = byte(j)\n db(t+1, t)\n }\n }\n }\n db(1, 1)\n var buf bytes.Buffer\n for _, i := range seq {\n buf.WriteByte(alphabet[i])\n }\n b := buf.String()\n return b + b[0:n-1] // as cyclic append first (n-1) digits\n}\n\nfunc allDigits(s string) bool {\n for _, b := range s {\n if b < '0' || b > '9' {\n return false\n }\n }\n return true\n}\n\nfunc validate(db string) {\n le := len(db)\n found := make([]int, 10000)\n var errs []string\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for i := 0; i < le-3; i++ {\n s := db[i : i+4]\n if allDigits(s) {\n n, _ := strconv.Atoi(s)\n found[n]++\n }\n }\n for i := 0; i < 10000; i++ {\n if found[i] == 0 {\n errs = append(errs, fmt.Sprintf(\" PIN number %04d missing\", i))\n } else if found[i] > 1 {\n errs = append(errs, fmt.Sprintf(\" PIN number %04d occurs %d times\", i, found[i]))\n }\n }\n lerr := len(errs)\n if lerr == 0 {\n fmt.Println(\" No errors found\")\n } else {\n pl := \"s\"\n if lerr == 1 {\n pl = \"\"\n }\n fmt.Printf(\" %d error%s found:\\n\", lerr, pl)\n fmt.Println(strings.Join(errs, \"\\n\"))\n }\n}\n\nfunc reverse(s string) string {\n bytes := []byte(s)\n for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n bytes[i], bytes[j] = bytes[j], bytes[i]\n }\n return string(bytes)\n}\n\nfunc main() {\n db := deBruijn(10, 4)\n le := len(db)\n fmt.Println(\"The length of the de Bruijn sequence is\", le)\n fmt.Println(\"\\nThe first 130 digits of the de Bruijn sequence are:\")\n fmt.Println(db[0:130])\n fmt.Println(\"\\nThe last 130 digits of the de Bruijn sequence are:\")\n fmt.Println(db[le-130:])\n fmt.Println(\"\\nValidating the de Bruijn sequence:\")\n validate(db)\n\n fmt.Println(\"\\nValidating the reversed de Bruijn sequence:\")\n dbr := reverse(db)\n validate(dbr)\n\n bytes := []byte(db)\n bytes[4443] = '.'\n db = string(bytes)\n fmt.Println(\"\\nValidating the overlaid de Bruijn sequence:\")\n validate(db)\n}"} {"title": "Deepcopy", "language": "Go", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// a type that allows cyclic structures\ntype node []*node\n\n// recursively print the contents of a node\nfunc (n *node) list() {\n if n == nil {\n fmt.Println(n)\n return\n }\n listed := map[*node]bool{nil: true}\n var r func(*node)\n r = func(n *node) {\n listed[n] = true\n fmt.Printf(\"%p -> %v\\n\", n, *n)\n for _, m := range *n {\n if !listed[m] {\n r(m)\n }\n }\n }\n r(n)\n}\n\n// construct a deep copy of a node\nfunc (n *node) ccopy() *node {\n if n == nil {\n return n\n }\n cc := map[*node]*node{nil: nil}\n var r func(*node) *node\n r = func(n *node) *node {\n c := make(node, len(*n))\n cc[n] = &c\n for i, m := range *n {\n d, ok := cc[m]\n if !ok {\n d = r(m)\n }\n c[i] = d\n }\n return &c\n }\n return r(n)\n}\n\nfunc main() {\n a := node{nil}\n c := &node{&node{&a}}\n a[0] = c\n c.list()\n cc := c.ccopy()\n fmt.Println(\"copy:\")\n cc.list()\n fmt.Println(\"original:\")\n c.list()\n}"} {"title": "Deming's funnel", "language": "Go from Python", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype rule func(float64, float64) float64\n\nvar dxs = []float64{\n -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n 0.443, -0.521, -0.799, 0.087,\n}\n\nvar dys = []float64{\n 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n -0.947, -1.424, -0.542, -1.032,\n}\n\nfunc funnel(fa []float64, r rule) []float64 {\n x := 0.0\n result := make([]float64, len(fa))\n for i, f := range fa {\n result[i] = x + f\n x = r(x, f)\n }\n return result\n}\n\nfunc mean(fa []float64) float64 {\n sum := 0.0\n for _, f := range fa {\n sum += f\n }\n return sum / float64(len(fa))\n}\n\nfunc stdDev(fa []float64) float64 {\n m := mean(fa)\n sum := 0.0\n for _, f := range fa {\n sum += (f - m) * (f - m)\n }\n return math.Sqrt(sum / float64(len(fa)))\n}\n\nfunc experiment(label string, r rule) {\n rxs := funnel(dxs, r)\n rys := funnel(dys, r)\n fmt.Println(label, \" : x y\")\n fmt.Printf(\"Mean : %7.4f, %7.4f\\n\", mean(rxs), mean(rys))\n fmt.Printf(\"Std Dev : %7.4f, %7.4f\\n\", stdDev(rxs), stdDev(rys))\n fmt.Println()\n}\n\nfunc main() {\n experiment(\"Rule 1\", func(_, _ float64) float64 {\n return 0.0\n })\n experiment(\"Rule 2\", func(_, dz float64) float64 {\n return -dz\n })\n experiment(\"Rule 3\", func(z, dz float64) float64 {\n return -(z + dz)\n })\n experiment(\"Rule 4\", func(z, dz float64) float64 {\n return z + dz\n })\n}"} {"title": "Department numbers", "language": "Go from Kotlin", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(\"Police Sanitation Fire\")\n fmt.Println(\"------ ---------- ----\")\n count := 0\n for i := 2; i < 7; i += 2 {\n for j := 1; j < 8; j++ {\n if j == i { continue }\n for k := 1; k < 8; k++ {\n if k == i || k == j { continue }\n if i + j + k != 12 { continue }\n fmt.Printf(\" %d %d %d\\n\", i, j, k)\n count++\n }\n }\n }\n fmt.Printf(\"\\n%d valid combinations\\n\", count)\n}"} {"title": "Detect division by zero", "language": "Go", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc divCheck(x, y int) (q int, ok bool) {\n defer func() {\n recover()\n }()\n q = x / y\n return q, true\n}\n\nfunc main() {\n fmt.Println(divCheck(3, 2))\n fmt.Println(divCheck(3, 0))\n}"} {"title": "Determinant and permanent", "language": "Go", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"permute\"\n)\n\nfunc determinant(m [][]float64) (d float64) {\n p := make([]int, len(m))\n for i := range p {\n p[i] = i\n }\n it := permute.Iter(p)\n for s := it(); s != 0; s = it() {\n pr := 1.\n for i, \u03c3 := range p {\n pr *= m[i][\u03c3]\n }\n d += float64(s) * pr\n }\n return\n}\n\nfunc permanent(m [][]float64) (d float64) {\n p := make([]int, len(m))\n for i := range p {\n p[i] = i\n }\n it := permute.Iter(p)\n for s := it(); s != 0; s = it() {\n pr := 1.\n for i, \u03c3 := range p {\n pr *= m[i][\u03c3]\n }\n d += pr\n }\n return\n}\n\nvar m2 = [][]float64{\n {1, 2},\n {3, 4}}\n\nvar m3 = [][]float64{\n {2, 9, 4},\n {7, 5, 3},\n {6, 1, 8}}\n\nfunc main() {\n fmt.Println(determinant(m2), permanent(m2))\n fmt.Println(determinant(m3), permanent(m3))\n}"} {"title": "Determine if a string has all the same characters", "language": "Go", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc analyze(s string) {\n chars := []rune(s)\n le := len(chars)\n fmt.Printf(\"Analyzing %q which has a length of %d:\\n\", s, le)\n if le > 1 {\n for i := 1; i < le; i++ {\n if chars[i] != chars[i-1] {\n fmt.Println(\" Not all characters in the string are the same.\")\n fmt.Printf(\" %q (%#[1]x) is different at position %d.\\n\\n\", chars[i], i+1)\n return\n }\n }\n }\n fmt.Println(\" All characters in the string are the same.\\n\")\n}\n\nfunc main() {\n strings := []string{\n \"\",\n \" \",\n \"2\",\n \"333\",\n \".55\",\n \"tttTTT\",\n \"4444 444k\",\n \"p\u00e9p\u00e9\",\n \"\ud83d\udc36\ud83d\udc36\ud83d\udc3a\ud83d\udc36\",\n \"\ud83c\udf84\ud83c\udf84\ud83c\udf84\ud83c\udf84\",\n }\n for _, s := range strings {\n analyze(s)\n }\n}"} {"title": "Determine if a string has all unique characters", "language": "Go", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc analyze(s string) {\n chars := []rune(s)\n le := len(chars)\n fmt.Printf(\"Analyzing %q which has a length of %d:\\n\", s, le)\n if le > 1 {\n for i := 0; i < le-1; i++ {\n for j := i + 1; j < le; j++ {\n if chars[j] == chars[i] {\n fmt.Println(\" Not all characters in the string are unique.\")\n fmt.Printf(\" %q (%#[1]x) is duplicated at positions %d and %d.\\n\\n\", chars[i], i+1, j+1)\n return\n }\n }\n }\n }\n fmt.Println(\" All characters in the string are unique.\\n\")\n}\n\nfunc main() {\n strings := []string{\n \"\",\n \".\",\n \"abcABC\",\n \"XYZ ZYX\",\n \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\",\n \"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\",\n \"h\u00e9t\u00e9rog\u00e9n\u00e9it\u00e9\",\n \"\ud83c\udf86\ud83c\udf83\ud83c\udf87\ud83c\udf88\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude4c\",\n \"\ud83d\udc20\ud83d\udc1f\ud83d\udc21\ud83e\udd88\ud83d\udc2c\ud83d\udc33\ud83d\udc0b\ud83d\udc21\",\n }\n for _, s := range strings {\n analyze(s)\n }\n}"} {"title": "Determine if a string is collapsible", "language": "Go", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// Returns collapsed string, original and new lengths in\n// unicode code points (not normalized).\nfunc collapse(s string) (string, int, int) {\n r := []rune(s)\n le, del := len(r), 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == r[i+1] {\n copy(r[i:], r[i+1:])\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[:le-del]\n return string(r), le, len(r)\n}\n \nfunc main() {\n strings:= []string {\n \"\",\n `\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `,\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n }\n for _, s := range strings {\n cs, olen, clen := collapse(s)\n fmt.Printf(\"original : length = %2d, string = \u00ab\u00ab\u00ab%s\u00bb\u00bb\u00bb\\n\", olen, s)\n fmt.Printf(\"collapsed: length = %2d, string = \u00ab\u00ab\u00ab%s\u00bb\u00bb\u00bb\\n\\n\", clen, cs)\n }\n}"} {"title": "Determine if a string is squeezable", "language": "Go", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// Returns squeezed string, original and new lengths in\n// unicode code points (not normalized).\nfunc squeeze(s string, c rune) (string, int, int) {\n r := []rune(s)\n le, del := len(r), 0\n for i := le - 2; i >= 0; i-- {\n if r[i] == c && r[i] == r[i+1] {\n copy(r[i:], r[i+1:])\n del++\n }\n }\n if del == 0 {\n return s, le, le\n }\n r = r[:le-del]\n return string(r), le, len(r)\n}\n\nfunc main() {\n strings := []string{\n \"\",\n `\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln `,\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n }\n chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'\ud83d\ude0d'}}\n\n for i, s := range strings {\n for _, c := range chars[i] {\n ss, olen, slen := squeeze(s, c)\n fmt.Printf(\"specified character = %q\\n\", c)\n fmt.Printf(\"original : length = %2d, string = \u00ab\u00ab\u00ab%s\u00bb\u00bb\u00bb\\n\", olen, s)\n fmt.Printf(\"squeezed : length = %2d, string = \u00ab\u00ab\u00ab%s\u00bb\u00bb\u00bb\\n\\n\", slen, ss)\n }\n }\n}"} {"title": "Determine if two triangles overlap", "language": "Go from Kotlin", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype point struct {\n x, y float64\n}\n\nfunc (p point) String() string {\n return fmt.Sprintf(\"(%.1f, %.1f)\", p.x, p.y)\n}\n\ntype triangle struct {\n p1, p2, p3 point\n}\n\nfunc (t *triangle) String() string {\n return fmt.Sprintf(\"Triangle %s, %s, %s\", t.p1, t.p2, t.p3)\n}\n\nfunc (t *triangle) det2D() float64 {\n return t.p1.x * (t.p2.y - t.p3.y) +\n t.p2.x * (t.p3.y - t.p1.y) +\n t.p3.x * (t.p1.y - t.p2.y) \n}\n\nfunc (t *triangle) checkTriWinding(allowReversed bool) {\n detTri := t.det2D()\n if detTri < 0.0 {\n if allowReversed {\n a := t.p3\n t.p3 = t.p2\n t.p2 = a\n } else {\n panic(\"Triangle has wrong winding direction.\")\n }\n }\n}\n\nfunc boundaryCollideChk(t *triangle, eps float64) bool {\n return t.det2D() < eps\n}\n\nfunc boundaryDoesntCollideChk(t *triangle, eps float64) bool {\n return t.det2D() <= eps\n}\n\nfunc triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool {\n // Triangles must be expressed anti-clockwise.\n t1.checkTriWinding(allowReversed)\n t2.checkTriWinding(allowReversed)\n\n // 'onBoundary' determines whether points on boundary are considered as colliding or not.\n var chkEdge func (*triangle, float64) bool\n if onBoundary {\n chkEdge = boundaryCollideChk\n } else {\n chkEdge = boundaryDoesntCollideChk\n }\n lp1 := [3]point{t1.p1, t1.p2, t1.p3}\n lp2 := [3]point{t2.p1, t2.p2, t2.p3}\n\n // for each edge E of t1\n for i := 0; i < 3; i++ {\n j := (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n tri1 := &triangle{lp1[i], lp1[j], lp2[0]}\n tri2 := &triangle{lp1[i], lp1[j], lp2[1]}\n tri3 := &triangle{lp1[i], lp1[j], lp2[2]}\n if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {\n return false\n }\n }\n\n // for each edge E of t2\n for i := 0; i < 3; i++ {\n j := (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n tri1 := &triangle{lp2[i], lp2[j], lp1[0]}\n tri2 := &triangle{lp2[i], lp2[j], lp1[1]}\n tri3 := &triangle{lp2[i], lp2[j], lp1[2]}\n if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {\n return false\n }\n }\n\n // The triangles overlap.\n return true\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n if cond {\n return s1\n }\n return s2\n}\n\nfunc main() {\n t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}\n t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}}\n fmt.Printf(\"%s and\\n%s\\n\", t1, t2)\n overlapping := triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n // Need to allow reversed for this pair to avoid panic.\n t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}}\n t2 = t1\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, true, true)\n fmt.Println(iff(overlapping, \"overlap (reversed)\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}\n t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1.p3 = point{2.5, 5.0}\n t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}}\n t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}}\n t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}}\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n println(\"which have only a single corner in contact, if boundary points collide\")\n overlapping = triTri2D(t1, t2, 0.0, false, true)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n\n fmt.Printf(\"\\n%s and\\n%s\\n\", t1, t2)\n fmt.Println(\"which have only a single corner in contact, if boundary points do not collide\")\n overlapping = triTri2D(t1, t2, 0.0, false, false)\n fmt.Println(iff(overlapping, \"overlap\", \"do not overlap\"))\n}"} {"title": "Dice game probabilities", "language": "Go from C", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "package main\n\nimport(\n \"math\"\n \"fmt\"\n)\n\nfunc minOf(x, y uint) uint {\n if x < y {\n return x\n }\n return y\n}\n\nfunc throwDie(nSides, nDice, s uint, counts []uint) {\n if nDice == 0 {\n counts[s]++\n return\n }\n for i := uint(1); i <= nSides; i++ {\n throwDie(nSides, nDice - 1, s + i, counts)\n }\n}\n\nfunc beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {\n len1 := (nSides1 + 1) * nDice1\n c1 := make([]uint, len1) // all elements zero by default\n throwDie(nSides1, nDice1, 0, c1)\n\n len2 := (nSides2 + 1) * nDice2\n c2 := make([]uint, len2)\n throwDie(nSides2, nDice2, 0, c2)\n p12 := math.Pow(float64(nSides1), float64(nDice1)) *\n math.Pow(float64(nSides2), float64(nDice2))\n\n tot := 0.0\n for i := uint(0); i < len1; i++ {\n for j := uint(0); j < minOf(i, len2); j++ {\n tot += float64(c1[i] * c2[j]) / p12\n }\n }\n return tot\n}\n\nfunc main() {\n fmt.Println(beatingProbability(4, 9, 6, 6))\n fmt.Println(beatingProbability(10, 5, 7, 6))\n}"} {"title": "Digital root", "language": "Go", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n)\n\nfunc Sum(i uint64, base int) (sum int) {\n\tb64 := uint64(base)\n\tfor ; i > 0; i /= b64 {\n\t\tsum += int(i % b64)\n\t}\n\treturn\n}\n\nfunc DigitalRoot(n uint64, base int) (persistence, root int) {\n\troot = int(n)\n\tfor x := n; x >= uint64(base); x = uint64(root) {\n\t\troot = Sum(x, base)\n\t\tpersistence++\n\t}\n\treturn\n}\n\n// Normally the below would be moved to a *_test.go file and\n// use the testing package to be runnable as a regular test.\n\nvar testCases = []struct {\n\tn string\n\tbase int\n\tpersistence int\n\troot int\n}{\n\t{\"627615\", 10, 2, 9},\n\t{\"39390\", 10, 2, 6},\n\t{\"588225\", 10, 2, 3},\n\t{\"393900588225\", 10, 2, 9},\n\t{\"1\", 10, 0, 1},\n\t{\"11\", 10, 1, 2},\n\t{\"e\", 16, 0, 0xe},\n\t{\"87\", 16, 1, 0xf},\n\t// From Applesoft BASIC example:\n\t{\"DigitalRoot\", 30, 2, 26}, // 26 is Q base 30\n\t// From C++ example:\n\t{\"448944221089\", 10, 3, 1},\n\t{\"7e0\", 16, 2, 0x6},\n\t{\"14e344\", 16, 2, 0xf},\n\t{\"d60141\", 16, 2, 0xa},\n\t{\"12343210\", 16, 2, 0x1},\n\t// From the D example:\n\t{\"1101122201121110011000000\", 3, 3, 1},\n}\n\nfunc main() {\n\tfor _, tc := range testCases {\n\t\tn, err := strconv.ParseUint(tc.n, tc.base, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tp, r := DigitalRoot(n, tc.base)\n\t\tfmt.Printf(\"%12v (base %2d) has additive persistence %d and digital root %s\\n\",\n\t\t\ttc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))\n\t\tif p != tc.persistence || r != tc.root {\n\t\t\tlog.Fatalln(\"bad result:\", tc, p, r)\n\t\t}\n\t}\n}"} {"title": "Disarium numbers", "language": "Go from Wren", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nconst DMAX = 20 // maximum digits\nconst LIMIT = 20 // maximum number of disariums to find\n\nfunc main() {\n // Pre-calculated exponential and power serials\n EXP := make([][]uint64, 1+DMAX)\n POW := make([][]uint64, 1+DMAX)\n\n EXP[0] = make([]uint64, 11)\n EXP[1] = make([]uint64, 11)\n POW[0] = make([]uint64, 11)\n POW[1] = make([]uint64, 11)\n for i := uint64(1); i <= 10; i++ {\n EXP[1][i] = i\n }\n for i := uint64(1); i <= 9; i++ {\n POW[1][i] = i\n }\n POW[1][10] = 9\n\n for i := 2; i <= DMAX; i++ {\n EXP[i] = make([]uint64, 11)\n POW[i] = make([]uint64, 11)\n }\n for i := 1; i < DMAX; i++ {\n for j := 0; j <= 9; j++ {\n EXP[i+1][j] = EXP[i][j] * 10\n POW[i+1][j] = POW[i][j] * uint64(j)\n }\n EXP[i+1][10] = EXP[i][10] * 10\n POW[i+1][10] = POW[i][10] + POW[i+1][9]\n }\n\n // Digits of candidate and values of known low bits\n DIGITS := make([]int, 1+DMAX) // Digits form\n Exp := make([]uint64, 1+DMAX) // Number form\n Pow := make([]uint64, 1+DMAX) // Powers form\n\n var exp, pow, min, max uint64\n start := 1\n final := DMAX\n count := 0\n for digit := start; digit <= final; digit++ {\n fmt.Println(\"# of digits:\", digit)\n level := 1\n DIGITS[0] = 0\n for {\n // Check limits derived from already known low bit values\n // to find the most possible candidates\n for 0 < level && level < digit {\n // Reset path to try next if checking in level is done\n if DIGITS[level] > 9 {\n DIGITS[level] = 0\n level--\n DIGITS[level]++\n continue\n }\n\n // Update known low bit values\n Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n // Max possible value\n pow = Pow[level] + POW[digit-level][10]\n\n if pow < EXP[digit][1] { // Try next since upper limit is invalidly low\n DIGITS[level]++\n continue\n }\n\n max = pow % EXP[level][10]\n pow -= max\n if max < Exp[level] {\n pow -= EXP[level][10]\n }\n max = pow + Exp[level]\n\n if max < EXP[digit][1] { // Try next since upper limit is invalidly low\n DIGITS[level]++\n continue\n }\n\n // Min possible value\n exp = Exp[level] + EXP[digit][1]\n pow = Pow[level] + 1\n\n if exp > max || max < pow { // Try next since upper limit is invalidly low\n DIGITS[level]++\n continue\n }\n\n if pow > exp {\n min = pow % EXP[level][10]\n pow -= min\n if min > Exp[level] {\n pow += EXP[level][10]\n }\n min = pow + Exp[level]\n } else {\n min = exp\n }\n\n // Check limits existence\n if max < min {\n DIGITS[level]++ // Try next number since current limits invalid\n } else {\n level++ // Go for further level checking since limits available\n }\n }\n\n // All checking is done, escape from the main check loop\n if level < 1 {\n break\n }\n\n // Finally check last bit of the most possible candidates\n // Update known low bit values\n Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]\n Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]\n\n // Loop to check all last bits of candidates\n for DIGITS[level] < 10 {\n // Print out new Disarium number\n if Exp[level] == Pow[level] {\n s := \"\"\n for i := DMAX; i > 0; i-- {\n s += fmt.Sprintf(\"%d\", DIGITS[i])\n }\n n, _ := strconv.ParseUint(s, 10, 64)\n fmt.Println(n)\n count++\n if count == LIMIT {\n fmt.Println(\"\\nFound the first\", LIMIT, \"Disarium numbers.\")\n return\n }\n }\n\n // Go to followed last bit candidate\n DIGITS[level]++\n Exp[level] += EXP[level][1]\n Pow[level]++\n }\n\n // Reset to try next path\n DIGITS[level] = 0\n level--\n DIGITS[level]++\n }\n fmt.Println()\n }\n}"} {"title": "Display a linear combination", "language": "Go from Kotlin", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc linearCombo(c []int) string {\n var sb strings.Builder\n for i, n := range c {\n if n == 0 {\n continue\n }\n var op string\n switch {\n case n < 0 && sb.Len() == 0:\n op = \"-\"\n case n < 0:\n op = \" - \"\n case n > 0 && sb.Len() == 0:\n op = \"\"\n default:\n op = \" + \"\n }\n av := n\n if av < 0 {\n av = -av\n }\n coeff := fmt.Sprintf(\"%d*\", av)\n if av == 1 {\n coeff = \"\"\n }\n sb.WriteString(fmt.Sprintf(\"%s%se(%d)\", op, coeff, i+1))\n }\n if sb.Len() == 0 {\n return \"0\"\n } else {\n return sb.String()\n }\n}\n\nfunc main() {\n combos := [][]int{\n {1, 2, 3},\n {0, 1, 2, 3},\n {1, 0, 3, 4},\n {1, 2, 0},\n {0, 0, 0},\n {0},\n {1, 1, 1},\n {-1, -1, -1},\n {-1, -2, 0, -3},\n {-1},\n }\n for _, c := range combos {\n t := strings.Replace(fmt.Sprint(c), \" \", \", \", -1)\n fmt.Printf(\"%-15s -> %s\\n\", t, linearCombo(c))\n }\n}"} {"title": "Display an outline as a nested table", "language": "Go", "task": "{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\nThe graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.\n\n;Task:\nGiven a outline with at least 3 levels of indentation, for example:\n\nDisplay an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n\nwrite a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.\n\nThe WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:\n\n{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\n;Extra credit:\nUse background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.\n\n\n;Output:\nDisplay your nested table on this page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\ntype nNode struct {\n name string\n children []nNode\n}\n\ntype iNode struct {\n level int\n name string\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n if level == 0 {\n n.name = iNodes[0].name\n }\n for i := start + 1; i < len(iNodes); i++ {\n if iNodes[i].level == level+1 {\n c := nNode{iNodes[i].name, nil}\n toNest(iNodes, i, level+1, &c)\n n.children = append(n.children, c)\n } else if iNodes[i].level <= level {\n return\n }\n }\n}\n\nfunc makeIndent(outline string, tab int) []iNode {\n lines := strings.Split(outline, \"\\n\")\n iNodes := make([]iNode, len(lines))\n for i, line := range lines {\n line2 := strings.TrimLeft(line, \" \")\n le, le2 := len(line), len(line2)\n level := (le - le2) / tab\n iNodes[i] = iNode{level, line2}\n }\n return iNodes\n}\n\nfunc toMarkup(n nNode, cols []string, depth int) string {\n var span int\n\n var colSpan func(nn nNode)\n colSpan = func(nn nNode) {\n for i, c := range nn.children {\n if i > 0 {\n span++\n }\n colSpan(c)\n }\n }\n\n for _, c := range n.children {\n span = 1\n colSpan(c)\n }\n var lines []string\n lines = append(lines, `{| class=\"wikitable\" style=\"text-align: center;\"`)\n const l1, l2 = \"|-\", \"| |\"\n lines = append(lines, l1)\n span = 1\n colSpan(n)\n s := fmt.Sprintf(`| style=\"background: %s \" colSpan=%d | %s`, cols[0], span, n.name)\n lines = append(lines, s, l1)\n\n var nestedFor func(nn nNode, level, maxLevel, col int)\n nestedFor = func(nn nNode, level, maxLevel, col int) {\n if level == 1 && maxLevel > level {\n for i, c := range nn.children {\n nestedFor(c, 2, maxLevel, i)\n }\n } else if level < maxLevel {\n for _, c := range nn.children {\n nestedFor(c, level+1, maxLevel, col)\n }\n } else {\n if len(nn.children) > 0 {\n for i, c := range nn.children {\n span = 1\n colSpan(c)\n cn := col + 1\n if maxLevel == 1 {\n cn = i + 1\n }\n s := fmt.Sprintf(`| style=\"background: %s \" colspan=%d | %s`, cols[cn], span, c.name)\n lines = append(lines, s)\n }\n } else {\n lines = append(lines, l2)\n }\n }\n }\n for maxLevel := 1; maxLevel < depth; maxLevel++ {\n nestedFor(n, 1, maxLevel, 0)\n if maxLevel < depth-1 {\n lines = append(lines, l1)\n }\n }\n lines = append(lines, \"|}\")\n return strings.Join(lines, \"\\n\")\n}\n\nfunc main() {\n const outline = `Display an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children) \n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.`\n const (\n yellow = \"#ffffe6;\"\n orange = \"#ffebd2;\"\n green = \"#f0fff0;\"\n blue = \"#e6ffff;\"\n pink = \"#ffeeff;\"\n )\n cols := []string{yellow, orange, green, blue, pink}\n iNodes := makeIndent(outline, 4)\n var n nNode\n toNest(iNodes, 0, 0, &n)\n fmt.Println(toMarkup(n, cols, 4))\n\n fmt.Println(\"\\n\")\n const outline2 = `Display an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n Propagating the sums upward as necessary. \n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n Optionally add color to the nodes.`\n cols2 := []string{blue, yellow, orange, green, pink}\n var n2 nNode\n iNodes2 := makeIndent(outline2, 4)\n toNest(iNodes2, 0, 0, &n2)\n fmt.Println(toMarkup(n2, cols2, 4))\n}"} {"title": "Diversity prediction theorem", "language": "Go", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc averageSquareDiff(f float64, preds []float64) (av float64) {\n for _, pred := range preds {\n av += (pred - f) * (pred - f)\n }\n av /= float64(len(preds))\n return\n}\n\nfunc diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {\n av := 0.0\n for _, pred := range preds {\n av += pred\n }\n av /= float64(len(preds))\n avErr := averageSquareDiff(truth, preds)\n crowdErr := (truth - av) * (truth - av)\n div := averageSquareDiff(av, preds)\n return avErr, crowdErr, div\n}\n\nfunc main() {\n predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}\n truth := 49.0\n for _, preds := range predsArray {\n avErr, crowdErr, div := diversityTheorem(truth, preds)\n fmt.Printf(\"Average-error : %6.3f\\n\", avErr)\n fmt.Printf(\"Crowd-error : %6.3f\\n\", crowdErr)\n fmt.Printf(\"Diversity : %6.3f\\n\\n\", div)\n }\n}"} {"title": "Doomsday rule", "language": "Go from Wren", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nvar days = []string{\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}\n\nfunc anchorDay(y int) int {\n return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7\n}\n\nfunc isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }\n\nvar firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\nvar firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}\n\nfunc main() {\n dates := []string{\n \"1800-01-06\",\n \"1875-03-29\",\n \"1915-12-07\",\n \"1970-12-23\",\n \"2043-05-14\",\n \"2077-02-12\",\n \"2101-04-02\",\n }\n\n fmt.Println(\"Days of week given by Doomsday rule:\")\n for _, date := range dates {\n y, _ := strconv.Atoi(date[0:4])\n m, _ := strconv.Atoi(date[5:7])\n m--\n d, _ := strconv.Atoi(date[8:10])\n a := anchorDay(y)\n f := firstDaysCommon[m]\n if isLeapYear(y) {\n f = firstDaysLeap[m]\n }\n w := d - f\n if w < 0 {\n w = 7 + w\n }\n dow := (a + w) % 7\n fmt.Printf(\"%s -> %s\\n\", date, days[dow])\n }\n}"} {"title": "Dot product", "language": "Go", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"log\"\n)\n\nvar (\n v1 = []int{1, 3, -5}\n v2 = []int{4, -2, -1}\n)\n\nfunc dot(x, y []int) (r int, err error) {\n if len(x) != len(y) {\n return 0, errors.New(\"incompatible lengths\")\n }\n for i, xi := range x {\n r += xi * y[i]\n }\n return\n}\n\nfunc main() {\n d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(d)\n}"} {"title": "Draw a clock", "language": "Go", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "\n\nClock\n\n\n\n

Clock

\n\t\n \n Sorry, your browser does not support Canvas\n \n\t\n Sorry, your browser does not support Canvas\n \n\t\n Sorry, your browser does not support Canvas\n \n\t\n Sorry, your browser does not support Canvas\n \n\t\n\n"} {"title": "Draw a rotating cube", "language": "Go", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/gif\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 640, 640\n\toffset = height / 2\n\tfileName = \"rotatingCube.gif\"\n)\n\nvar nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100},\n\t{100, -100, -100}, {100, -100, 100}, {100, 100, -100}, {100, 100, 100}}\nvar edges = [][]int{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},\n\t{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}\n\nfunc main() {\n\tvar images []*image.Paletted\n\tfgCol := color.RGBA{0xff, 0x00, 0xff, 0xff}\n\tvar palette = []color.Color{color.RGBA{0x00, 0x00, 0x00, 0xff}, fgCol}\n\tvar delays []int\n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\n\trotateCube(math.Pi/4, math.Atan(math.Sqrt(2)))\n\tvar frame float64\n\tfor frame = 0; frame < 360; frame++ {\n\t\timg := image.NewPaletted(image.Rect(0, 0, width, height), palette)\n\t\timages = append(images, img)\n\t\tdelays = append(delays, 5)\n\t\tfor _, edge := range edges {\n\t\t\txy1 := nodes[edge[0]]\n\t\t\txy2 := nodes[edge[1]]\n\t\t\tdrawLine(int(xy1[0])+offset, int(xy1[1])+offset, int(xy2[0])+offset, int(xy2[1])+offset, img, fgCol)\n\t\t}\n\t\trotateCube(math.Pi/180, 0)\n\t}\n\tif err := gif.EncodeAll(imgFile, &gif.GIF{Image: images, Delay: delays}); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n\n}\n\nfunc rotateCube(angleX, angleY float64) {\n\tsinX := math.Sin(angleX)\n\tcosX := math.Cos(angleX)\n\tsinY := math.Sin(angleY)\n\tcosY := math.Cos(angleY)\n\tfor _, node := range nodes {\n\t\tx := node[0]\n\t\ty := node[1]\n\t\tz := node[2]\n\t\tnode[0] = x*cosX - z*sinX\n\t\tnode[2] = z*cosX + x*sinX\n\t\tz = node[2]\n\t\tnode[1] = y*cosY - z*sinY\n\t\tnode[2] = z*cosY + y*sinY\n\t}\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.Paletted, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\n\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}"} {"title": "Draw a sphere", "language": "Go from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"image\"\n \"image/color\"\n \"image/png\"\n \"math\"\n \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n invLen := 1 / math.Sqrt(dot(v, v))\n v[0] *= invLen\n v[1] *= invLen\n v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n w, h := r*4, r*3\n img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))\n vec := new(vector)\n for x := -r; x < r; x++ {\n for y := -r; y < r; y++ {\n if z := r*r - x*x - y*y; z >= 0 {\n vec[0] = float64(x)\n vec[1] = float64(y)\n vec[2] = math.Sqrt(float64(z))\n normalize(vec)\n s := dot(dir, vec)\n if s < 0 {\n s = 0\n }\n lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)\n if lum < 0 {\n lum = 0\n } else if lum > 255 {\n lum = 255\n }\n img.SetGray(x, y, color.Gray{uint8(lum)})\n }\n }\n }\n return img\n}\n\nfunc main() {\n dir := &vector{-30, -30, 50}\n normalize(dir)\n img := drawSphere(200, 1.5, .2, dir)\n f, err := os.Create(\"sphere.png\")\n if err != nil {\n fmt.Println(err)\n return\n }\n if err = png.Encode(f, img); err != nil {\n fmt.Println(err)\n }\n if err = f.Close(); err != nil {\n fmt.Println(err)\n }\n}"} {"title": "Dutch national flag problem", "language": "Go", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// constants define order of colors in Dutch national flag\nconst (\n red = iota\n white\n blue\n nColors\n)\n\n// zero object of type is valid red ball.\ntype ball struct {\n color int\n}\n\n// order of balls based on DNF\nfunc (b1 ball) lt(b2 ball) bool {\n return b1.color < b2.color\n}\n\n// type for arbitrary ordering of balls\ntype ordering []ball\n\n// predicate tells if balls are ordered by DNF\nfunc (o ordering) ordered() bool {\n var b0 ball\n for _, b := range o {\n if b.lt(b0) {\n return false\n }\n b0 = b\n }\n return true\n}\n\nfunc init() {\n rand.Seed(time.Now().Unix())\n}\n\n// constructor returns new ordering of balls which is randomized but\n// guaranteed to be not in DNF order. function panics for n < 2.\nfunc outOfOrder(n int) ordering {\n if n < 2 {\n panic(fmt.Sprintf(\"%d invalid\", n))\n }\n r := make(ordering, n)\n for {\n for i, _ := range r {\n r[i].color = rand.Intn(nColors)\n }\n if !r.ordered() {\n break\n }\n }\n return r\n}\n\n// O(n) algorithm\n// http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/\nfunc (a ordering) sort3() {\n lo, mid, hi := 0, 0, len(a)-1\n for mid <= hi {\n switch a[mid].color {\n case red:\n a[lo], a[mid] = a[mid], a[lo]\n lo++\n mid++\n case white:\n mid++\n default:\n a[mid], a[hi] = a[hi], a[mid]\n hi--\n }\n }\n}\n\nfunc main() {\n f := outOfOrder(12)\n fmt.Println(f)\n f.sort3()\n fmt.Println(f)\n}"} {"title": "EKG sequence convergence", "language": "Go", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* The EKG Sequence and the Tree of Numbers. (Video).\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc contains(a []int, b int) bool {\n for _, j := range a {\n if j == b {\n return true\n }\n }\n return false\n}\n\nfunc gcd(a, b int) int {\n for a != b {\n if a > b {\n a -= b\n } else {\n b -= a\n }\n }\n return a\n}\n\nfunc areSame(s, t []int) bool {\n le := len(s)\n if le != len(t) {\n return false\n }\n sort.Ints(s)\n sort.Ints(t)\n for i := 0; i < le; i++ {\n if s[i] != t[i] {\n return false\n }\n }\n return true\n}\n\nfunc main() {\n const limit = 100\n starts := [5]int{2, 5, 7, 9, 10}\n var ekg [5][limit]int\n\n for s, start := range starts {\n ekg[s][0] = 1\n ekg[s][1] = start\n for n := 2; n < limit; n++ {\n for i := 2; ; i++ {\n // a potential sequence member cannot already have been used\n // and must have a factor in common with previous member\n if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {\n ekg[s][n] = i\n break\n }\n }\n }\n fmt.Printf(\"EKG(%2d): %v\\n\", start, ekg[s][:30])\n } \n\n // now compare EKG5 and EKG7 for convergence\n for i := 2; i < limit; i++ {\n if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {\n fmt.Println(\"\\nEKG(5) and EKG(7) converge at term\", i+1)\n return\n }\n }\n fmt.Println(\"\\nEKG5(5) and EKG(7) do not converge within\", limit, \"terms\")\n}"} {"title": "Eban numbers", "language": "Go", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype Range struct {\n start, end uint64\n print bool\n}\n\nfunc main() {\n rgs := []Range{\n {2, 1000, true},\n {1000, 4000, true},\n {2, 1e4, false},\n {2, 1e5, false},\n {2, 1e6, false},\n {2, 1e7, false},\n {2, 1e8, false},\n {2, 1e9, false},\n }\n for _, rg := range rgs {\n if rg.start == 2 {\n fmt.Printf(\"eban numbers up to and including %d:\\n\", rg.end)\n } else {\n fmt.Printf(\"eban numbers between %d and %d (inclusive):\\n\", rg.start, rg.end)\n }\n count := 0\n for i := rg.start; i <= rg.end; i += 2 {\n b := i / 1000000000\n r := i % 1000000000\n m := r / 1000000\n r = i % 1000000\n t := r / 1000\n r %= 1000\n if m >= 30 && m <= 66 {\n m %= 10\n }\n if t >= 30 && t <= 66 {\n t %= 10\n }\n if r >= 30 && r <= 66 {\n r %= 10\n }\n if b == 0 || b == 2 || b == 4 || b == 6 { \n if m == 0 || m == 2 || m == 4 || m == 6 {\n if t == 0 || t == 2 || t == 4 || t == 6 {\n if r == 0 || r == 2 || r == 4 || r == 6 {\n if rg.print {\n fmt.Printf(\"%d \", i)\n }\n count++\n }\n }\n }\n }\n }\n if rg.print {\n fmt.Println()\n }\n fmt.Println(\"count =\", count, \"\\n\")\n }\n}"} {"title": "Eertree", "language": "Go", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n tree := eertree([]byte(\"eertree\"))\n fmt.Println(subPalindromes(tree))\n}\n\ntype edges map[byte]int\n\ntype node struct {\n length int\n edges\n suffix int\n}\n\nconst evenRoot = 0\nconst oddRoot = 1\n\nfunc eertree(s []byte) []node {\n tree := []node{\n evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},\n oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},\n }\n suffix := oddRoot\n var n, k int\n for i, c := range s {\n for n = suffix; ; n = tree[n].suffix {\n k = tree[n].length\n if b := i - k - 1; b >= 0 && s[b] == c {\n break\n }\n }\n if e, ok := tree[n].edges[c]; ok {\n suffix = e\n continue\n }\n suffix = len(tree)\n tree = append(tree, node{length: k + 2, edges: edges{}})\n tree[n].edges[c] = suffix\n if tree[suffix].length == 1 {\n tree[suffix].suffix = 0\n continue\n }\n for {\n n = tree[n].suffix\n if b := i - tree[n].length - 1; b >= 0 && s[b] == c {\n break\n }\n }\n tree[suffix].suffix = tree[n].edges[c]\n }\n return tree\n}\n\nfunc subPalindromes(tree []node) (s []string) {\n var children func(int, string)\n children = func(n int, p string) {\n for c, n := range tree[n].edges {\n c := string(c)\n p := c + p + c\n s = append(s, p)\n children(n, p)\n }\n }\n children(0, \"\")\n for c, n := range tree[1].edges {\n c := string(c)\n s = append(s, c)\n children(n, c)\n }\n return\n}"} {"title": "Egyptian division", "language": "Go from Kotlin", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc egyptianDivide(dividend, divisor int) (quotient, remainder int) {\n if dividend < 0 || divisor <= 0 {\n panic(\"Invalid argument(s)\")\n }\n if dividend < divisor {\n return 0, dividend\n }\n powersOfTwo := []int{1}\n doublings := []int{divisor}\n doubling := divisor\n for {\n doubling *= 2\n if doubling > dividend {\n break\n }\n l := len(powersOfTwo)\n powersOfTwo = append(powersOfTwo, powersOfTwo[l-1]*2)\n doublings = append(doublings, doubling)\n }\n answer := 0\n accumulator := 0\n for i := len(doublings) - 1; i >= 0; i-- {\n if accumulator+doublings[i] <= dividend {\n accumulator += doublings[i]\n answer += powersOfTwo[i]\n if accumulator == dividend {\n break\n }\n }\n }\n return answer, dividend - accumulator\n}\n\nfunc main() {\n dividend := 580\n divisor := 34\n quotient, remainder := egyptianDivide(dividend, divisor)\n fmt.Println(dividend, \"divided by\", divisor, \"is\", quotient, \"with remainder\", remainder)\n}"} {"title": "Elementary cellular automaton", "language": "Go", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"math/rand\"\n \"strings\"\n)\n\nfunc main() {\n const cells = 20\n const generations = 9\n fmt.Println(\"Single 1, rule 90:\")\n a := big.NewInt(1)\n a.Lsh(a, cells/2)\n elem(90, cells, generations, a)\n fmt.Println(\"Random intial state, rule 30:\")\n a = big.NewInt(1)\n a.Rand(rand.New(rand.NewSource(3)), a.Lsh(a, cells))\n elem(30, cells, generations, a)\n}\n\nfunc elem(rule uint, cells, generations int, a *big.Int) {\n output := func() {\n fmt.Println(strings.Replace(strings.Replace(\n fmt.Sprintf(\"%0*b\", cells, a), \"0\", \" \", -1), \"1\", \"#\", -1))\n }\n output()\n a1 := new(big.Int)\n set := func(cell int, k uint) {\n a1.SetBit(a1, cell, rule>>k&1)\n }\n last := cells - 1\n for r := 0; r < generations; r++ {\n k := a.Bit(last) | a.Bit(0)<<1 | a.Bit(1)<<2\n set(0, k)\n for c := 1; c < last; c++ {\n k = k>>1 | a.Bit(c+1)<<2\n set(c, k)\n }\n set(last, k>>1|a.Bit(0)<<2)\n a, a1 = a1, a\n output()\n }\n}"} {"title": "Elementary cellular automaton/Infinite length", "language": "Go from C++", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc btoi(b bool) int {\n if b {\n return 1\n }\n return 0\n}\n\nfunc evolve(l, rule int) {\n fmt.Printf(\" Rule #%d:\\n\", rule)\n cells := \"O\"\n for x := 0; x < l; x++ {\n cells = addNoCells(cells)\n width := 40 + (len(cells) >> 1)\n fmt.Printf(\"%*s\\n\", width, cells)\n cells = step(cells, rule)\n }\n}\n\nfunc step(cells string, rule int) string {\n newCells := new(strings.Builder)\n for i := 0; i < len(cells)-2; i++ {\n bin := 0\n b := uint(2)\n for n := i; n < i+3; n++ {\n bin += btoi(cells[n] == 'O') << b\n b >>= 1\n }\n a := '.'\n if rule&(1<= 0; q-- {\n st := state\n b |= (st & 1) << uint(q)\n state = 0\n for i := uint(0); i < n; i++ {\n var t1, t2, t3 uint64\n if i > 0 {\n t1 = st >> (i - 1)\n } else {\n t1 = st >> 63\n }\n if i == 0 {\n t2 = st << 1\n } else if i == 1 {\n t2 = st << 63\n\n } else {\n t2 = st << (n + 1 - i)\n }\n t3 = 7 & (t1 | t2)\n if (uint64(rule) & pow2(uint(t3))) != 0 {\n state |= pow2(i)\n }\n }\n }\n fmt.Printf(\"%d \", b)\n }\n fmt.Println()\n}\n\nfunc main() {\n evolve(1, 30)\n}"} {"title": "Elliptic curve arithmetic", "language": "Go from C", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst bCoeff = 7\n\ntype pt struct{ x, y float64 }\n\nfunc zero() pt {\n return pt{math.Inf(1), math.Inf(1)}\n}\n\nfunc is_zero(p pt) bool {\n return p.x > 1e20 || p.x < -1e20\n}\n\nfunc neg(p pt) pt {\n return pt{p.x, -p.y}\n}\n\nfunc dbl(p pt) pt {\n if is_zero(p) {\n return p\n }\n L := (3 * p.x * p.x) / (2 * p.y)\n x := L*L - 2*p.x\n return pt{\n x: x,\n y: L*(p.x-x) - p.y,\n }\n}\n\nfunc add(p, q pt) pt {\n if p.x == q.x && p.y == q.y {\n return dbl(p)\n }\n if is_zero(p) {\n return q\n }\n if is_zero(q) {\n return p\n }\n L := (q.y - p.y) / (q.x - p.x)\n x := L*L - p.x - q.x\n return pt{\n x: x,\n y: L*(p.x-x) - p.y,\n }\n}\n\nfunc mul(p pt, n int) pt {\n r := zero()\n for i := 1; i <= n; i <<= 1 {\n if i&n != 0 {\n r = add(r, p)\n }\n p = dbl(p)\n }\n return r\n}\n\nfunc show(s string, p pt) {\n fmt.Printf(\"%s\", s)\n if is_zero(p) {\n fmt.Println(\"Zero\")\n } else {\n fmt.Printf(\"(%.3f, %.3f)\\n\", p.x, p.y)\n }\n}\n\nfunc from_y(y float64) pt {\n return pt{\n x: math.Cbrt(y*y - bCoeff),\n y: y,\n }\n}\n \nfunc main() {\n a := from_y(1)\n b := from_y(2)\n show(\"a = \", a)\n show(\"b = \", b)\n c := add(a, b)\n show(\"c = a + b = \", c)\n d := neg(c)\n show(\"d = -c = \", d)\n show(\"c + d = \", add(c, d))\n show(\"a + b + d = \", add(a, add(b, d)))\n show(\"a * 12345 = \", mul(a, 12345))\n}"} {"title": "Empty directory", "language": "Go", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n)\n\nfunc main() {\n\tempty, err := IsEmptyDir(\"/tmp\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif empty {\n\t\tfmt.Printf(\"/tmp is empty\\n\")\n\t} else {\n\t\tfmt.Printf(\"/tmp is not empty\\n\")\n\t}\n}\n\nfunc IsEmptyDir(name string) (bool, error) {\n\tentries, err := ioutil.ReadDir(name)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn len(entries) == 0, nil\n}\n"} {"title": "Empty string", "language": "Go", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc test(s string) {\n\tif len(s) == 0 {\n\t\tfmt.Println(\"empty\")\n\t} else {\n\t\tfmt.Println(\"not empty\")\n\t}\n}\n\nfunc main() {\n\t// assign an empty string to a variable.\n\tstr1 := \"\"\n\tstr2 := \" \"\n\t// check if a string is empty.\n\ttest(str1) // prt empty\n\t// check that a string is not empty.\n\ttest(str2) // prt not empty\n}"} {"title": "Entropy/Narcissist", "language": "Go", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"math\"\n \"os\"\n \"runtime\"\n)\n\nfunc main() {\n _, src, _, _ := runtime.Caller(0)\n fmt.Println(\"Source file entropy:\", entropy(src))\n fmt.Println(\"Binary file entropy:\", entropy(os.Args[0]))\n}\n\nfunc entropy(file string) float64 {\n d, err := ioutil.ReadFile(file)\n if err != nil {\n log.Fatal(err)\n }\n var f [256]float64\n for _, b := range d {\n f[b]++\n }\n hm := 0.\n for _, c := range f {\n if c > 0 {\n hm += c * math.Log2(c)\n }\n }\n l := float64(len(d))\n return math.Log2(l) - hm/l\n}"} {"title": "Equilibrium index", "language": "Go", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nfunc main() {\n fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))\n\n // sequence of 1,000,000 random numbers, with values\n // chosen so that it will be likely to have a couple\n // of equalibrium indexes.\n rand.Seed(time.Now().UnixNano())\n verylong := make([]int32, 1e6)\n for i := range verylong {\n verylong[i] = rand.Int31n(1001) - 500\n }\n fmt.Println(ex(verylong))\n}\n\nfunc ex(s []int32) (eq []int) {\n var r, l int64\n for _, el := range s {\n r += int64(el)\n }\n for i, el := range s {\n r -= int64(el)\n if l == r {\n eq = append(eq, i)\n }\n l += int64(el)\n }\n return\n}"} {"title": "Erd\u0151s-Nicolas numbers", "language": "Go from C++", "task": "Definition\nAn perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.\n\n;Examples\n24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.\n\n6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.\n\n;Task\n\nFind and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.\n\n;Stretch\nDo the same for any further Erdos-Nicolas numbers which you have the patience for.\n\n;Note\nAs all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.\n\n;Reference\n* OEIS:A194472 - Erdos-Nicolas numbers\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tconst maxNumber = 100000000\n\tdsum := make([]int, maxNumber+1)\n\tdcount := make([]int, maxNumber+1)\n\tfor i := 0; i <= maxNumber; i++ {\n\t\tdsum[i] = 1\n\t\tdcount[i] = 1\n\t}\n\tfor i := 2; i <= maxNumber; i++ {\n\t\tfor j := i + i; j <= maxNumber; j += i {\n\t\t\tif dsum[j] == j {\n\t\t\t\tfmt.Printf(\"%8d equals the sum of its first %d divisors\\n\", j, dcount[j])\n\t\t\t}\n\t\t\tdsum[j] += i\n\t\t\tdcount[j]++\n\t\t}\n\t}\n}"} {"title": "Esthetic numbers", "language": "Go", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc uabs(a, b uint64) uint64 {\n if a > b {\n return a - b\n }\n return b - a\n}\n\nfunc isEsthetic(n, b uint64) bool {\n if n == 0 {\n return false\n }\n i := n % b\n n /= b\n for n > 0 {\n j := n % b\n if uabs(i, j) != 1 {\n return false\n }\n n /= b\n i = j\n }\n return true\n}\n\nvar esths []uint64\n\nfunc dfs(n, m, i uint64) {\n if i >= n && i <= m {\n esths = append(esths, i)\n }\n if i == 0 || i > m {\n return\n }\n d := i % 10\n i1 := i*10 + d - 1\n i2 := i1 + 2\n if d == 0 {\n dfs(n, m, i2)\n } else if d == 9 {\n dfs(n, m, i1)\n } else {\n dfs(n, m, i1)\n dfs(n, m, i2)\n }\n}\n\nfunc listEsths(n, n2, m, m2 uint64, perLine int, all bool) {\n esths = esths[:0]\n for i := uint64(0); i < 10; i++ {\n dfs(n2, m2, i)\n }\n le := len(esths)\n fmt.Printf(\"Base 10: %s esthetic numbers between %s and %s:\\n\",\n commatize(uint64(le)), commatize(n), commatize(m))\n if all {\n for c, esth := range esths {\n fmt.Printf(\"%d \", esth)\n if (c+1)%perLine == 0 {\n fmt.Println()\n }\n }\n } else {\n for i := 0; i < perLine; i++ {\n fmt.Printf(\"%d \", esths[i])\n }\n fmt.Println(\"\\n............\\n\")\n for i := le - perLine; i < le; i++ {\n fmt.Printf(\"%d \", esths[i])\n }\n }\n fmt.Println(\"\\n\")\n}\n\nfunc commatize(n uint64) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n for b := uint64(2); b <= 16; b++ {\n fmt.Printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4*b, 6*b)\n for n, c := uint64(1), uint64(0); c < 6*b; n++ {\n if isEsthetic(n, b) {\n c++\n if c >= 4*b {\n fmt.Printf(\"%s \", strconv.FormatUint(n, int(b)))\n }\n }\n }\n fmt.Println(\"\\n\")\n }\n\n // the following all use the obvious range limitations for the numbers in question\n listEsths(1000, 1010, 9999, 9898, 16, true)\n listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)\n listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)\n listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)\n listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)\n}"} {"title": "Euler's identity", "language": "Go", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "package main\n \nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n \nfunc main() {\n fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)\n}"} {"title": "Euler's sum of powers conjecture", "language": "Go from Python", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n)\n\nfunc main() {\n\tfmt.Println(eulerSum())\n}\n\nfunc eulerSum() (x0, x1, x2, x3, y int) {\n\tvar pow5 [250]int\n\tfor i := range pow5 {\n\t\tpow5[i] = i * i * i * i * i\n\t}\n\tfor x0 = 4; x0 < len(pow5); x0++ {\n\t\tfor x1 = 3; x1 < x0; x1++ {\n\t\t\tfor x2 = 2; x2 < x1; x2++ {\n\t\t\t\tfor x3 = 1; x3 < x2; x3++ {\n\t\t\t\t\tsum := pow5[x0] +\n\t\t\t\t\t\tpow5[x1] +\n\t\t\t\t\t\tpow5[x2] +\n\t\t\t\t\t\tpow5[x3]\n\t\t\t\t\tfor y = x0 + 1; y < len(pow5); y++ {\n\t\t\t\t\t\tif sum == pow5[y] {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Fatal(\"no solution\")\n\treturn\n}"} {"title": "Even or odd", "language": "Go", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n test(-2)\n test(-1)\n test(0)\n test(1)\n test(2)\n testBig(\"-222222222222222222222222222222222222\")\n testBig(\"-1\")\n testBig(\"0\")\n testBig(\"1\")\n testBig(\"222222222222222222222222222222222222\")\n}\n\nfunc test(n int) {\n fmt.Printf(\"Testing integer %3d: \", n)\n // & 1 is a good way to test\n if n&1 == 0 {\n fmt.Print(\"even \")\n } else {\n fmt.Print(\" odd \")\n }\n // Careful when using %: negative n % 2 returns -1. So, the code below\n // works, but can be broken by someone thinking they can reverse the\n // test by testing n % 2 == 1. The valid reverse test is n % 2 != 0.\n if n%2 == 0 {\n fmt.Println(\"even\")\n } else {\n fmt.Println(\" odd\")\n }\n}\n\nfunc testBig(s string) {\n b, _ := new(big.Int).SetString(s, 10)\n fmt.Printf(\"Testing big integer %v: \", b)\n // the Bit function is the only sensible test for big ints.\n if b.Bit(0) == 0 {\n fmt.Println(\"even\")\n } else {\n fmt.Println(\"odd\")\n }\n}"} {"title": "Evolutionary algorithm", "language": "Go", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nvar target = []byte(\"METHINKS IT IS LIKE A WEASEL\")\nvar set = []byte(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ \")\nvar parent []byte\n\nfunc init() {\n rand.Seed(time.Now().UnixNano())\n parent = make([]byte, len(target))\n for i := range parent {\n parent[i] = set[rand.Intn(len(set))]\n }\n}\n\n// fitness: 0 is perfect fit. greater numbers indicate worse fit.\nfunc fitness(a []byte) (h int) {\n // (hamming distance)\n for i, tc := range target {\n if a[i] != tc {\n h++\n }\n }\n return\n}\n\n// set m to mutation of p, with each character of p mutated with probability r\nfunc mutate(p, m []byte, r float64) {\n for i, ch := range p {\n if rand.Float64() < r {\n m[i] = set[rand.Intn(len(set))]\n } else {\n m[i] = ch\n }\n }\n}\n\nfunc main() {\n const c = 20 // number of times to copy and mutate parent\n\n copies := make([][]byte, c)\n for i := range copies {\n copies[i] = make([]byte, len(parent))\n }\n\n fmt.Println(string(parent))\n for best := fitness(parent); best > 0; {\n for _, cp := range copies {\n mutate(parent, cp, .05)\n }\n for _, cp := range copies {\n fm := fitness(cp)\n if fm < best {\n best = fm\n copy(parent, cp)\n fmt.Println(string(parent))\n }\n }\n }\n}"} {"title": "Executable library", "language": "Go", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "// modulino.go\npackage main\n\nimport \"fmt\"\n\n// Function borrowed from Hailstone sequence task.\n// 1st arg is the number to generate the sequence for.\n// 2nd arg is a slice to recycle, to reduce garbage.\nfunc hailstone(n int, recycle []int) []int {\n s := append(recycle[:0], n)\n for n > 1 {\n if n&1 == 0 {\n n = n / 2\n } else {\n n = 3*n + 1\n }\n s = append(s, n)\n }\n return s\n}\n\nfunc libMain() {\n seq := hailstone(27, nil)\n fmt.Println(\"\\nHailstone sequence for the number 27:\")\n fmt.Println(\" has\", len(seq), \"elements\")\n fmt.Println(\" starts with\", seq[0:4])\n fmt.Println(\" ends with\", seq[len(seq)-4:])\n\n var longest, length int\n for i := 1; i < 100000; i++ {\n if le := len(hailstone(i, nil)); le > length {\n longest = i\n length = le\n }\n }\n fmt.Printf(\"\\n%d has the longest Hailstone sequence, its length being %d.\\n\", longest, length)\n}"} {"title": "Execute Brain****", "language": "Go", "task": "Brainf***}}\nRCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. \n\nBelow are links to each of the versions of RCBF.\n\nAn implementation need only properly implement the following instructions:\n{| class=\"wikitable\"\n!Command\n!Description\n|-\n| style=\"text-align:center\"| > || Move the pointer to the right\n|-\n| style=\"text-align:center\"| < || Move the pointer to the left\n|-\n| style=\"text-align:center\"| + || Increment the memory cell under the pointer\n|-\n| style=\"text-align:center\"| - || Decrement the memory cell under the pointer\n|-\n| style=\"text-align:center\"| . || Output the character signified by the cell at the pointer\n|-\n| style=\"text-align:center\"| , || Input a character and store it in the cell at the pointer\n|-\n| style=\"text-align:center\"| [ || Jump past the matching ] if the cell under the pointer is 0\n|-\n| style=\"text-align:center\"| ] || Jump back to the matching [ if the cell under the pointer is nonzero\n|}\nAny cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n // example program is current Brain**** solution to\n // Hello world/Text task. only requires 10 bytes of data store!\n bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++\n++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>\n>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.\n<+++++++.--------.<<<<<+.<+++.---.`)\n}\n\nfunc bf(dLen int, is string) {\n ds := make([]byte, dLen) // data store\n var dp int // data pointer\n for ip := 0; ip < len(is); ip++ {\n switch is[ip] {\n case '>':\n dp++\n case '<':\n dp--\n case '+':\n ds[dp]++\n case '-':\n ds[dp]--\n case '.':\n fmt.Printf(\"%c\", ds[dp])\n case ',':\n fmt.Scanf(\"%c\", &ds[dp])\n case '[':\n if ds[dp] == 0 {\n for nc := 1; nc > 0; {\n ip++\n if is[ip] == '[' {\n nc++\n } else if is[ip] == ']' {\n nc--\n }\n }\n }\n case ']':\n if ds[dp] != 0 {\n for nc := 1; nc > 0; {\n ip--\n if is[ip] == ']' {\n nc++\n } else if is[ip] == '[' {\n nc--\n }\n }\n }\n }\n }\n}"} {"title": "Execute Computer/Zero", "language": "Go", "task": "Computer/zero Assembly}}\n\n;Task:\nCreate a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\n;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.\n\n\n\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tNOP = iota\n\tLDA\n\tSTA\n\tADD\n\tSUB\n\tBRZ\n\tJMP\n\tSTP\n)\n\nvar opcodes = map[string]int{\n\t\"NOP\": NOP,\n\t\"LDA\": LDA,\n\t\"STA\": STA,\n\t\"ADD\": ADD,\n\t\"SUB\": SUB,\n\t\"BRZ\": BRZ,\n\t\"JMP\": JMP,\n\t\"STP\": STP,\n}\n\nvar reIns = regexp.MustCompile(\n\t`\\s*(?:(\\w+):)?\\s*` + // label\n\t\t`(NOP|LDA|STA|ADD|SUB|BRZ|JMP|STP)?\\s*` + // opcode\n\t\t`(\\w+)?\\s*` + // argument\n\t\t`(?:;([\\w\\s]+))?`) // comment\n\ntype ByteCode [32]int\n\ntype instruction struct {\n\tLabel string\n\tOpcode string\n\tArg string\n}\n\ntype Program struct {\n\tInstructions []instruction\n\tLabels map[string]int\n}\n\nfunc newInstruction(line string) (*instruction, error) {\n\tmatch := reIns.FindStringSubmatch(line)\n\tif match == nil {\n\t\treturn nil, fmt.Errorf(\"syntax error: '%s'\", line)\n\t}\n\treturn &instruction{Label: match[1], Opcode: match[2], Arg: match[3]}, nil\n}\n\nfunc Parse(asm io.Reader) (*Program, error) {\n\tvar p Program\n\tp.Labels = make(map[string]int, 32)\n\tscanner := bufio.NewScanner(asm)\n\tlineNumber := 0\n\n\tfor scanner.Scan() {\n\t\tif instruction, err := newInstruction(scanner.Text()); err != nil {\n\t\t\treturn &p, err\n\t\t} else {\n\t\t\tif instruction.Label != \"\" {\n\t\t\t\tp.Labels[instruction.Label] = lineNumber\n\t\t\t}\n\t\t\tp.Instructions = append(p.Instructions, *instruction)\n\t\t\tlineNumber++\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}\n\nfunc (p *Program) Compile() (ByteCode, error) {\n\tvar bytecode ByteCode\n\tvar arg int\n\tfor i, ins := range p.Instructions {\n\t\tif ins.Arg == \"\" {\n\t\t\targ = 0\n\t\t} else if addr, err := strconv.Atoi(ins.Arg); err == nil {\n\t\t\targ = addr\n\t\t} else if addr, ok := p.Labels[ins.Arg]; ok {\n\t\t\targ = addr\n\t\t} else {\n\t\t\treturn bytecode, fmt.Errorf(\"unknown label %v\", ins.Arg)\n\t\t}\n\n\t\tif opcode, ok := opcodes[ins.Opcode]; ok {\n\t\t\tbytecode[i] = opcode<<5 | arg\n\t\t} else {\n\t\t\tbytecode[i] = arg\n\t\t}\n\t}\n\treturn bytecode, nil\n}\n\nfunc floorMod(a, b int) int {\n\treturn ((a % b) + b) % b\n}\n\nfunc Run(bytecode ByteCode) (int, error) {\n\tacc := 0\n\tpc := 0\n\tmem := bytecode\n\n\tvar op int\n\tvar arg int\n\nloop:\n\tfor pc < 32 {\n\t\top = mem[pc] >> 5\n\t\targ = mem[pc] & 31\n\t\tpc++\n\n\t\tswitch op {\n\t\tcase NOP:\n\t\t\tcontinue\n\t\tcase LDA:\n\t\t\tacc = mem[arg]\n\t\tcase STA:\n\t\t\tmem[arg] = acc\n\t\tcase ADD:\n\t\t\tacc = floorMod(acc+mem[arg], 256)\n\t\tcase SUB:\n\t\t\tacc = floorMod(acc-mem[arg], 256)\n\t\tcase BRZ:\n\t\t\tif acc == 0 {\n\t\t\t\tpc = arg\n\t\t\t}\n\t\tcase JMP:\n\t\t\tpc = arg\n\t\tcase STP:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t\treturn acc, fmt.Errorf(\"runtime error: %v %v\", op, arg)\n\t\t}\n\t}\n\n\treturn acc, nil\n}\n\nfunc Execute(asm string) (int, error) {\n\tprogram, err := Parse(strings.NewReader(asm))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"assembly error: %v\", err)\n\t}\n\n\tbytecode, err := program.Compile()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"compilation error: %v\", err)\n\t}\n\n\tresult, err := Run(bytecode)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result, nil\n}\n\nfunc main() {\n\texamples := []string{\n\t\t`LDA x\n\t\tADD y ; accumulator = x + y\n\t\tSTP\nx: 2\ny: 2`,\n\t\t`loop: LDA prodt\n\tADD x\n\tSTA prodt\n\tLDA y\n\tSUB one\n\tSTA y\n\tBRZ done\n\tJMP loop\ndone: LDA prodt ; to display it\n\tSTP\nx: 8\ny: 7\nprodt: 0\none: 1`,\n\t\t`loop: LDA n\n\tSTA temp\n\tADD m\n\tSTA n\n\tLDA temp\n\tSTA m\n\tLDA count\n\tSUB one\n\tBRZ done\n\tSTA count\n\tJMP loop\ndone: LDA n ; to display it\n\tSTP\nm: 1\nn: 1\ntemp: 0\ncount: 8 ; valid range: 1-11\none: 1`,\n\t\t`start: LDA load\nADD car ; head of list\nSTA ldcar\nADD one\nSTA ldcdr ; next CONS cell\nldcar: NOP\nSTA value\nldcdr: NOP\nBRZ done ; 0 stands for NIL\nSTA car\nJMP start\ndone: LDA value ; CAR of last CONS\nSTP\nload: LDA 0\nvalue: 0\ncar: 28\none: 1\n\t\t\t; order of CONS cells\n\t\t\t; in memory\n\t\t\t; does not matter\n\t6\n\t0 ; 0 stands for NIL\n\t2 ; (CADR ls)\n\t26 ; (CDDR ls) -- etc.\n\t5\n\t20\n\t3\n\t30\n\t1 ; value of (CAR ls)\n\t22 ; points to (CDR ls)\n\t4\n\t24`,\n\t\t`LDA 3\nSUB 4\nSTP 0\n\t 0\n\t 255`,\n\t\t`LDA 3\nSUB 4\nSTP 0\n\t\t0\n\t\t1`,\n\t\t`LDA 3\nADD 4\nSTP 0\n\t\t1\n\t\t255`,\n\t}\n\n\tfor _, asm := range examples {\n\t\tif result, err := Execute(asm); err == nil {\n\t\t\tfmt.Println(result)\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n"} {"title": "Exponentiation order", "language": "Go", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "package main\n\nimport \"fmt\"\nimport \"math\"\n\nfunc main() {\n var a, b, c float64\n a = math.Pow(5, math.Pow(3, 2))\n b = math.Pow(math.Pow(5, 3), 2)\n c = math.Pow(5, math.Pow(3, 2))\n fmt.Printf(\"5^3^2 = %.0f\\n\", a)\n fmt.Printf(\"(5^3)^2 = %.0f\\n\", b)\n fmt.Printf(\"5^(3^2) = %.0f\\n\", c)\n}"} {"title": "Exponentiation with infix operators in (or operating on) the base", "language": "Go", "task": "(Many programming languages, especially those with extended-precision integer arithmetic, usually\nsupport one of **, ^, | or some such for exponentiation.)\n\n\nSome languages treat/honor infix operators when performing exponentiation (raising\nnumbers to some power by the language's exponentiation operator, if the computer\nprogramming language has one).\n\n\nOther programming languages may make use of the '''POW''' or some other BIF\n ('''B'''uilt-'''I'''n '''F'''function), or some other library service.\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nThis task will deal with the case where there is some form of an ''infix operator'' operating\nin (or operating on) the base.\n\n\n;Example:\nA negative five raised to the 3rd power could be specified as:\n -5 ** 3 or as\n -(5) ** 3 or as\n (-5) ** 3 or as something else\n\n\n(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).\n\n\n;Task:\n:* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.\n:* Raise the following numbers (integer or real):\n:::* -5 and\n:::* +5\n:* to the following powers:\n:::* 2nd and\n:::* 3rd\n:* using the following expressions (if applicable in your language):\n:::* -x**p\n:::* -(x)**p\n:::* (-x)**p\n:::* -(x**p)\n:* Show here (on this page) the four (or more) types of symbolic expressions for each number and power.\n\n\nTry to present the results in the same format/manner as the other programming entries to make any differences apparent.\n\n\nThe variables may be of any type(s) that is/are applicable in your language.\n\n\n;Related tasks:\n* [[Exponentiation order]]\n* [[Exponentiation operator]]\n* [[Arbitrary-precision integers (included)]]\n* [[Parsing/RPN to infix conversion]]\n* [[Operator precedence]]\n\n;References:\n* Wikipedia: Order of operations in Programming languages\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype float float64\n\nfunc (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }\n\nfunc main() {\n ops := []string{\"-x.p(e)\", \"-(x).p(e)\", \"(-x).p(e)\", \"-(x.p(e))\"}\n for _, x := range []float{float(-5), float(5)} {\n for _, e := range []float{float(2), float(3)} {\n fmt.Printf(\"x = %2.0f e = %0.0f | \", x, e)\n fmt.Printf(\"%s = %4.0f | \", ops[0], -x.p(e))\n fmt.Printf(\"%s = %4.0f | \", ops[1], -(x).p(e))\n fmt.Printf(\"%s = %4.0f | \", ops[2], (-x).p(e))\n fmt.Printf(\"%s = %4.0f\\n\", ops[3], -(x.p(e)))\n }\n }\n}"} {"title": "Extend your language", "language": "Go from Kotlin", "task": "{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.\n", "solution": "package main\n\nimport \"fmt\"\n\ntype F func()\n\ntype If2 struct {cond1, cond2 bool}\n\nfunc (i If2) else1(f F) If2 {\n if i.cond1 && !i.cond2 {\n f()\n }\n return i\n}\n\nfunc (i If2) else2(f F) If2 {\n if i.cond2 && !i.cond1 {\n f()\n }\n return i\n}\n\nfunc (i If2) else0(f F) If2 {\n if !i.cond1 && !i.cond2 {\n f()\n }\n return i\n}\n\nfunc if2(cond1, cond2 bool, f F) If2 {\n if cond1 && cond2 {\n f()\n }\n return If2{cond1, cond2}\n}\n\nfunc main() {\n a, b := 0, 1\n if2 (a == 1, b == 3, func() {\n fmt.Println(\"a = 1 and b = 3\")\n }).else1 (func() {\n fmt.Println(\"a = 1 and b <> 3\")\n }).else2 (func() {\n fmt.Println(\"a <> 1 and b = 3\")\n }).else0 (func() {\n fmt.Println(\"a <> 1 and b <> 3\")\n })\n\n // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order\n a, b = 1, 0\n if2 (a == 1, b == 3, func() {\n fmt.Println(\"a = 1 and b = 3\")\n }).else0 (func() {\n fmt.Println(\"a <> 1 and b <> 3\")\n }).else1 (func() {\n fmt.Println(\"a = 1 and b <> 3\")\n })\n}"} {"title": "Extreme floating point values", "language": "Go", "task": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. \n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables. \n\nIf your language can directly enter these extreme floating point values then show it.\n\n\n;See also:\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\n\n;Related tasks:\n* [[Infinity]]\n* [[Detect division by zero]]\n* [[Literals/Floating point]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n // compute \"extreme values\" from non-extreme values\n var zero float64 // zero is handy.\n var negZero, posInf, negInf, nan float64 // values to compute.\n negZero = zero * -1\n posInf = 1 / zero\n negInf = -1 / zero\n nan = zero / zero\n\n // print extreme values stored in variables\n fmt.Println(negZero, posInf, negInf, nan)\n\n // directly obtain extreme values\n fmt.Println(math.Float64frombits(1<<63),\n math.Inf(1), math.Inf(-1), math.NaN())\n\n // validate some arithmetic on extreme values\n fmt.Println()\n validateNaN(negInf+posInf, \"-Inf + Inf\")\n validateNaN(0*posInf, \"0 * Inf\")\n validateNaN(posInf/posInf, \"Inf / Inf\")\n // mod is specifically named in \"What every computer scientist...\"\n // Go math package doc lists many special cases for other package functions.\n validateNaN(math.Mod(posInf, 1), \"Inf % 1\")\n validateNaN(1+nan, \"1 + NaN\")\n validateZero(1/posInf, \"1 / Inf\")\n validateGT(posInf, math.MaxFloat64, \"Inf > max value\")\n validateGT(-math.MaxFloat64, negInf, \"-Inf < max neg value\")\n validateNE(nan, nan, \"NaN != NaN\")\n validateEQ(negZero, 0, \"-0 == 0\")\n}\n\nfunc validateNaN(n float64, op string) {\n if math.IsNaN(n) {\n fmt.Println(op, \"-> NaN\")\n } else {\n fmt.Println(\"!!! Expected NaN from\", op, \" Found\", n)\n }\n}\n\nfunc validateZero(n float64, op string) {\n if n == 0 {\n fmt.Println(op, \"-> 0\")\n } else {\n fmt.Println(\"!!! Expected 0 from\", op, \" Found\", n)\n }\n}\n\nfunc validateGT(a, b float64, op string) {\n if a > b {\n fmt.Println(op)\n } else {\n fmt.Println(\"!!! Expected\", op, \" Found not true.\")\n }\n}\n\nfunc validateNE(a, b float64, op string) {\n if a == b {\n fmt.Println(\"!!! Expected\", op, \" Found not true.\")\n } else {\n fmt.Println(op)\n }\n}\n\nfunc validateEQ(a, b float64, op string) {\n if a == b {\n fmt.Println(op)\n } else {\n fmt.Println(\"!!! Expected\", op, \" Found not true.\")\n }\n}"} {"title": "FASTA format", "language": "Go", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n)\n\nfunc main() {\n f, err := os.Open(\"rc.fasta\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer f.Close()\n s := bufio.NewScanner(f)\n headerFound := false\n for s.Scan() {\n line := s.Text()\n switch {\n case line == \"\":\n continue\n case line[0] != '>':\n if !headerFound {\n fmt.Println(\"missing header\")\n return\n }\n fmt.Print(line)\n case headerFound:\n fmt.Println()\n fallthrough\n default:\n fmt.Printf(\"%s: \", line[1:])\n headerFound = true\n }\n }\n if headerFound {\n fmt.Println()\n }\n if err := s.Err(); err != nil {\n fmt.Println(err)\n }\n}"} {"title": "Faces from a mesh", "language": "Go", "task": "A mesh defining a surface has uniquely numbered vertices, and named, \nsimple-polygonal faces described usually by an ordered list of edge numbers \ngoing around the face, \n\n\nFor example:\nExternal image of two faces\nRough textual version without edges:\n\n\n 1 \n 17\n 7 A\n B\n\n 11 \n 23\n\n\n\n* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or\nany of all the rotations of those ordered vertices.\n 1 \n \n 7 A\n \n\n 11\n\n* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any \nof their rotations.\n1 \n 17\n\n B\n\n 11 \n 23\n\nLet's call the above the '''perimeter format''' as it traces around the perimeter.\n\n;A second format:\nA separate algorithm returns polygonal faces consisting of a face name and an unordered \nset of edge definitions for each face.\n* A single edge is described by the vertex numbers at its two ends, always in \nascending order.\n* All edges for the face are given, but in an undefined order.\n\nFor example face A could be described by the edges (1, 11), (7, 11), and (1, 7)\n(The order of each vertex number in an edge is ascending, but the order in \nwhich the edges are stated is arbitrary).\n\nSimilarly face B could be described by the edges (11, 23), (1, 17), (17, 23),\nand (1, 11) in arbitrary order of the edges. \n\nLet's call this second format the '''edge format'''.\n\n\n\n;Task:\n'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:\n Q: (8, 1, 3)\n R: (1, 3, 8)\n\n U: (18, 8, 14, 10, 12, 17, 19)\n V: (8, 14, 10, 12, 17, 19, 18)\n\n'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.\n E: {(1, 11), (7, 11), (1, 7)}\n F: {(11, 23), (1, 17), (17, 23), (1, 11)}\n G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}\n H: {(1, 3), (9, 11), (3, 11), (1, 11)}\n\n\nShow your output here.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\n// Check a slice contains a value.\nfunc contains(s []int, f int) bool {\n for _, e := range s {\n if e == f {\n return true\n }\n }\n return false\n}\n\n// Assumes s1, s2 are of same length.\nfunc sliceEqual(s1, s2 []int) bool {\n for i := 0; i < len(s1); i++ {\n if s1[i] != s2[i] {\n return false\n }\n }\n return true\n}\n\n// Reverses slice in place.\nfunc reverse(s []int) {\n for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n s[i], s[j] = s[j], s[i]\n }\n}\n\n// Check two perimeters are equal.\nfunc perimEqual(p1, p2 []int) bool {\n le := len(p1)\n if le != len(p2) {\n return false\n }\n for _, p := range p1 {\n if !contains(p2, p) {\n return false\n }\n }\n // use copy to avoid mutating 'p1'\n c := make([]int, le)\n copy(c, p1)\n for r := 0; r < 2; r++ {\n for i := 0; i < le; i++ {\n if sliceEqual(c, p2) {\n return true\n }\n // do circular shift to right\n t := c[le-1]\n copy(c[1:], c[0:le-1])\n c[0] = t\n }\n // now process in opposite direction\n reverse(c)\n }\n return false\n}\n\ntype edge [2]int\n\n// Translates a face to perimeter format.\nfunc faceToPerim(face []edge) []int {\n // use copy to avoid mutating 'face'\n le := len(face)\n if le == 0 {\n return nil\n }\n edges := make([]edge, le)\n for i := 0; i < le; i++ {\n // check edge pairs are in correct order\n if face[i][1] <= face[i][0] {\n return nil\n }\n edges[i] = face[i]\n }\n // sort edges in ascending order\n sort.Slice(edges, func(i, j int) bool {\n if edges[i][0] != edges[j][0] {\n return edges[i][0] < edges[j][0]\n }\n return edges[i][1] < edges[j][1]\n })\n var perim []int\n first, last := edges[0][0], edges[0][1]\n perim = append(perim, first, last)\n // remove first edge\n copy(edges, edges[1:])\n edges = edges[0 : le-1]\n le--\nouter:\n for le > 0 {\n for i, e := range edges {\n found := false\n if e[0] == last {\n perim = append(perim, e[1])\n last, found = e[1], true\n } else if e[1] == last {\n perim = append(perim, e[0])\n last, found = e[0], true\n }\n if found {\n // remove i'th edge\n copy(edges[i:], edges[i+1:])\n edges = edges[0 : le-1]\n le--\n if last == first {\n if le == 0 {\n break outer\n } else {\n return nil\n }\n }\n continue outer\n }\n }\n }\n return perim[0 : len(perim)-1]\n}\n\nfunc main() {\n fmt.Println(\"Perimeter format equality checks:\")\n areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8})\n fmt.Printf(\" Q == R is %t\\n\", areEqual)\n areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18})\n fmt.Printf(\" U == V is %t\\n\", areEqual)\n e := []edge{{7, 11}, {1, 11}, {1, 7}}\n f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}}\n g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}\n h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}}\n fmt.Println(\"\\nEdge to perimeter format translations:\")\n for i, face := range [][]edge{e, f, g, h} {\n perim := faceToPerim(face)\n if perim == nil {\n fmt.Printf(\" %c => Invalid edge format\\n\", i + 'E')\n } else {\n fmt.Printf(\" %c => %v\\n\", i + 'E', perim)\n }\n }\n}"} {"title": "Factorial base numbers indexing permutations of a collection", "language": "Go", "task": "You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.\nThe first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0\nObserve that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.\n\nI want to produce a 1 to 1 mapping between these numbers and permutations:-\n 0.0.0 -> 0123\n 0.0.1 -> 0132\n 0.1.0 -> 0213\n 0.1.1 -> 0231\n 0.2.0 -> 0312\n 0.2.1 -> 0321\n 1.0.0 -> 1023\n 1.0.1 -> 1032\n 1.1.0 -> 1203\n 1.1.1 -> 1230\n 1.2.0 -> 1302\n 1.2.1 -> 1320\n 2.0.0 -> 2013\n 2.0.1 -> 2031\n 2.1.0 -> 2103\n 2.1.1 -> 2130\n 2.2.0 -> 2301\n 2.2.1 -> 2310\n 3.0.0 -> 3012\n 3.0.1 -> 3021\n 3.1.0 -> 3102\n 3.1.1 -> 3120\n 3.2.0 -> 3201\n 3.2.1 -> 3210\n\nThe following psudo-code will do this:\nStarting with m=0 and O, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.\n\nIf g is greater than zero, rotate the elements from m to m+g in O (see example)\nIncrement m and repeat the first step using the next most significant digit until the factorial base number is exhausted.\nFor example: using the factorial base number 2.0.1 and O = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.\n\nStep 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3\nStep 2: m=1 g=0; No action.\nStep 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1\n\nLet me work 2.0.1 and 0123\n step 1 n=0 g=2 O=2013\n step 2 n=1 g=0 so no action\n step 3 n=2 g=1 O=2031\n\nThe task:\n\n First use your function to recreate the above table.\n Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with\n methods in rc's permutations task.\n Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:\n 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\n 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\n use your function to crate the corresponding permutation of the following shoe of cards:\n AKQJ1098765432AKQJ1098765432AKQJ1098765432AKQJ1098765432\n Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\nfunc factorial(n int) int {\n fact := 1\n for i := 2; i <= n; i++ {\n fact *= i\n }\n return fact\n}\n\nfunc genFactBaseNums(size int, countOnly bool) ([][]int, int) {\n var results [][]int\n count := 0\n for n := 0; ; n++ {\n radix := 2\n var res []int = nil\n if !countOnly { \n res = make([]int, size)\n }\n k := n\n for k > 0 {\n div := k / radix\n rem := k % radix\n if !countOnly {\n if radix <= size+1 {\n res[size-radix+1] = rem\n }\n }\n k = div\n radix++\n }\n if radix > size+2 {\n break\n }\n count++\n if !countOnly {\n results = append(results, res)\n }\n }\n return results, count\n}\n\nfunc mapToPerms(factNums [][]int) [][]int {\n var perms [][]int\n psize := len(factNums[0]) + 1\n start := make([]int, psize)\n for i := 0; i < psize; i++ {\n start[i] = i\n }\n for _, fn := range factNums {\n perm := make([]int, psize)\n copy(perm, start)\n for m := 0; m < len(fn); m++ {\n g := fn[m]\n if g == 0 {\n continue\n }\n first := m\n last := m + g\n for i := 1; i <= g; i++ {\n temp := perm[first]\n for j := first + 1; j <= last; j++ {\n perm[j-1] = perm[j]\n }\n perm[last] = temp\n }\n }\n perms = append(perms, perm)\n }\n return perms\n}\n\nfunc join(is []int, sep string) string {\n ss := make([]string, len(is))\n for i := 0; i < len(is); i++ {\n ss[i] = strconv.Itoa(is[i])\n }\n return strings.Join(ss, sep)\n}\n\nfunc undot(s string) []int {\n ss := strings.Split(s, \".\")\n is := make([]int, len(ss))\n for i := 0; i < len(ss); i++ {\n is[i], _ = strconv.Atoi(ss[i])\n }\n return is\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n\n // Recreate the table.\n factNums, _ := genFactBaseNums(3, false)\n perms := mapToPerms(factNums)\n for i, fn := range factNums {\n fmt.Printf(\"%v -> %v\\n\", join(fn, \".\"), join(perms[i], \"\"))\n }\n\n // Check that the number of perms generated is equal to 11! (this takes a while).\n _, count := genFactBaseNums(10, true)\n fmt.Println(\"\\nPermutations generated =\", count)\n fmt.Println(\"compared to 11! which =\", factorial(11))\n fmt.Println()\n\n // Generate shuffles for the 2 given 51 digit factorial base numbers.\n fbn51s := []string{\n \"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\",\n \"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\",\n }\n factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}\n perms = mapToPerms(factNums)\n shoe := []rune(\"A\u2660K\u2660Q\u2660J\u2660T\u26609\u26608\u26607\u26606\u26605\u26604\u26603\u26602\u2660A\u2665K\u2665Q\u2665J\u2665T\u26659\u26658\u26657\u26656\u26655\u26654\u26653\u26652\u2665A\u2666K\u2666Q\u2666J\u2666T\u26669\u26668\u26667\u26666\u26665\u26664\u26663\u26662\u2666A\u2663K\u2663Q\u2663J\u2663T\u26639\u26638\u26637\u26636\u26635\u26634\u26633\u26632\u2663\")\n cards := make([]string, 52)\n for i := 0; i < 52; i++ {\n cards[i] = string(shoe[2*i : 2*i+2])\n if cards[i][0] == 'T' {\n cards[i] = \"10\" + cards[i][1:]\n }\n }\n for i, fbn51 := range fbn51s {\n fmt.Println(fbn51)\n for _, d := range perms[i] {\n fmt.Print(cards[d])\n }\n fmt.Println(\"\\n\")\n }\n\n // Create a random 51 digit factorial base number and produce a shuffle from that.\n fbn51 := make([]int, 51)\n for i := 0; i < 51; i++ {\n fbn51[i] = rand.Intn(52 - i)\n }\n fmt.Println(join(fbn51, \".\"))\n perms = mapToPerms([][]int{fbn51})\n for _, d := range perms[0] {\n fmt.Print(cards[d])\n }\n fmt.Println()\n}"} {"title": "Factorions", "language": "Go", "task": "Definition:\nA factorion is a natural number that equals the sum of the factorials of its digits. \n\n\n;Example: \n'''145''' is a factorion in base '''10''' because:\n\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n\n\nIt can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.\n\n\n;Task:\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n:* There are '''3''' factorions in base '''9'''\n:* There are '''4''' factorions in base '''10'''\n:* There are '''5''' factorions in base '''11''' \n:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')\n\n\n;See also:\n:* '''Wikipedia article'''\n:* '''OEIS:A014080 - Factorions in base 10'''\n:* '''OEIS:A193163 - Factorions in base n'''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc main() {\n // cache factorials from 0 to 11\n var fact [12]uint64\n fact[0] = 1\n for n := uint64(1); n < 12; n++ {\n fact[n] = fact[n-1] * n\n }\n\n for b := 9; b <= 12; b++ {\n fmt.Printf(\"The factorions for base %d are:\\n\", b)\n for i := uint64(1); i < 1500000; i++ {\n digits := strconv.FormatUint(i, b)\n sum := uint64(0)\n for _, digit := range digits {\n if digit < 'a' {\n sum += fact[digit-'0']\n } else {\n sum += fact[digit+10-'a']\n }\n }\n if sum == i {\n fmt.Printf(\"%d \", i)\n }\n }\n fmt.Println(\"\\n\")\n }\n}"} {"title": "Fairshare between two and more", "language": "Go", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strconv\"\n \"strings\"\n)\n\nfunc fairshare(n, base int) []int {\n res := make([]int, n)\n for i := 0; i < n; i++ {\n j := i\n sum := 0\n for j > 0 {\n sum += j % base\n j /= base\n }\n res[i] = sum % base\n }\n return res\n}\n\nfunc turns(n int, fss []int) string {\n m := make(map[int]int)\n for _, fs := range fss {\n m[fs]++\n }\n m2 := make(map[int]int)\n for _, v := range m {\n m2[v]++\n }\n res := []int{}\n sum := 0\n for k, v := range m2 {\n sum += v\n res = append(res, k)\n }\n if sum != n {\n return fmt.Sprintf(\"only %d have a turn\", sum)\n }\n sort.Ints(res)\n res2 := make([]string, len(res))\n for i := range res {\n res2[i] = strconv.Itoa(res[i])\n }\n return strings.Join(res2, \" or \")\n}\n\nfunc main() {\n for _, base := range []int{2, 3, 5, 11} {\n fmt.Printf(\"%2d : %2d\\n\", base, fairshare(25, base))\n }\n fmt.Println(\"\\nHow many times does each get a turn in 50000 iterations?\")\n for _, base := range []int{191, 1377, 49999, 50000, 50001} {\n t := turns(base, fairshare(50000, base))\n fmt.Printf(\" With %d people: %s\\n\", base, t)\n }\n}"} {"title": "Farey sequence", "language": "Go", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype frac struct{ num, den int }\n\nfunc (f frac) String() string {\n return fmt.Sprintf(\"%d/%d\", f.num, f.den)\n}\n\nfunc f(l, r frac, n int) {\n m := frac{l.num + r.num, l.den + r.den}\n if m.den <= n {\n f(l, m, n)\n fmt.Print(m, \" \")\n f(m, r, n)\n }\n}\n\nfunc main() {\n // task 1. solution by recursive generation of mediants\n for n := 1; n <= 11; n++ {\n l := frac{0, 1}\n r := frac{1, 1}\n fmt.Printf(\"F(%d): %s \", n, l)\n f(l, r, n)\n fmt.Println(r)\n }\n // task 2. direct solution by summing totient function\n // 2.1 generate primes to 1000\n var composite [1001]bool\n for _, p := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} {\n for n := p * 2; n <= 1000; n += p {\n composite[n] = true\n }\n }\n // 2.2 generate totients to 1000\n var tot [1001]int\n for i := range tot {\n tot[i] = 1\n }\n for n := 2; n <= 1000; n++ {\n if !composite[n] {\n tot[n] = n - 1\n for a := n * 2; a <= 1000; a += n {\n f := n - 1\n for r := a / n; r%n == 0; r /= n {\n f *= n\n }\n tot[a] *= f\n }\n }\n }\n // 2.3 sum totients\n for n, sum := 1, 1; n <= 1000; n++ {\n sum += tot[n]\n if n%100 == 0 {\n fmt.Printf(\"|F(%d)|: %d\\n\", n, sum)\n }\n }\n}"} {"title": "Fast Fourier transform", "language": "Go", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/cmplx\"\n)\n\nfunc ditfft2(x []float64, y []complex128, n, s int) {\n if n == 1 {\n y[0] = complex(x[0], 0)\n return\n }\n ditfft2(x, y, n/2, 2*s)\n ditfft2(x[s:], y[n/2:], n/2, 2*s)\n for k := 0; k < n/2; k++ {\n tf := cmplx.Rect(1, -2*math.Pi*float64(k)/float64(n)) * y[k+n/2]\n y[k], y[k+n/2] = y[k]+tf, y[k]-tf\n }\n}\n\nfunc main() {\n x := []float64{1, 1, 1, 1, 0, 0, 0, 0}\n y := make([]complex128, len(x))\n ditfft2(x, y, len(x), 1)\n for _, c := range y {\n fmt.Printf(\"%8.4f\\n\", c)\n }\n}"} {"title": "Feigenbaum constant calculation", "language": "Go from Ring", "task": "Calculate the Feigenbaum constant. \n\n\n;See:\n:* Details in the Wikipedia article: Feigenbaum constant.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc feigenbaum() {\n maxIt, maxItJ := 13, 10\n a1, a2, d1 := 1.0, 0.0, 3.2\n fmt.Println(\" i d\")\n for i := 2; i <= maxIt; i++ {\n a := a1 + (a1-a2)/d1\n for j := 1; j <= maxItJ; j++ {\n x, y := 0.0, 0.0\n for k := 1; k <= 1<2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc g(i []int, c chan<- int) {\n\tvar sum int\n\tb := append([]int(nil), i...) // make a copy\n\tfor _, t := range b {\n\t\tc <- t\n\t\tsum += t\n\t}\n\tfor {\n\t\tfor j, t := range b {\n\t\t\tc <- sum\n\t\t\tb[j], sum = sum, sum+sum-t\n\t\t}\n\t}\n}\n\nfunc main() {\n\tfor _, s := range [...]struct {\n\t\tseq string\n\t\ti []int\n\t}{\n\t\t{\"Fibonacci\", []int{1, 1}},\n\t\t{\"Tribonacci\", []int{1, 1, 2}},\n\t\t{\"Tetranacci\", []int{1, 1, 2, 4}},\n\t\t{\"Lucas\", []int{2, 1}},\n\t} {\n\t\tfmt.Printf(\"%10s:\", s.seq)\n\t\tc := make(chan int)\n\t\t// Note/warning: these goroutines are leaked.\n\t\tgo g(s.i, c)\n\t\tfor j := 0; j < 10; j++ {\n\t\t\tfmt.Print(\" \", <-c)\n\t\t}\n\t\tfmt.Println()\n\t}\n}"} {"title": "Fibonacci word", "language": "Go", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// From http://rosettacode.org/wiki/Entropy#Go\nfunc entropy(s string) float64 {\n\tm := map[rune]float64{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\thm := 0.\n\tfor _, c := range m {\n\t\thm += c * math.Log2(c)\n\t}\n\tl := float64(len(s))\n\treturn math.Log2(l) - hm/l\n}\n\nconst F_Word1 = \"1\"\nconst F_Word2 = \"0\"\n\nfunc FibonacciWord(n int) string {\n\ta, b := F_Word1, F_Word2\n\tfor ; n > 1; n-- {\n\t\ta, b = b, b+a\n\t}\n\treturn a\n}\n\nfunc FibonacciWordGen() <-chan string {\n\tch := make(chan string)\n\tgo func() {\n\t\ta, b := F_Word1, F_Word2\n\t\tfor {\n\t\t\tch <- a\n\t\t\ta, b = b, b+a\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc main() {\n\tfibWords := FibonacciWordGen()\n\tfmt.Printf(\"%3s %9s %-18s %s\\n\", \"N\", \"Length\", \"Entropy\", \"Word\")\n\tn := 1\n\tfor ; n < 10; n++ {\n\t\ts := <-fibWords\n\t\t// Just to show the function and generator do the same thing:\n\t\tif s2 := FibonacciWord(n); s != s2 {\n\t\t\tfmt.Printf(\"For %d, generator produced %q, function produced %q\\n\", n, s, s2)\n\t\t}\n\t\tfmt.Printf(\"%3d %9d %.16f %s\\n\", n, len(s), entropy(s), s)\n\t}\n\tfor ; n <= 37; n++ {\n\t\ts := <-fibWords\n\t\tfmt.Printf(\"%3d %9d %.16f\\n\", n, len(s), entropy(s))\n\t}\n}"} {"title": "File extension is in extensions list", "language": "Go", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar extensions = []string{\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\n\nfunc fileExtInList(filename string) (bool, string) {\n filename2 := strings.ToLower(filename)\n for _, ext := range extensions {\n ext2 := \".\" + strings.ToLower(ext)\n if strings.HasSuffix(filename2, ext2) {\n return true, ext\n }\n }\n s := strings.Split(filename, \".\")\n if len(s) > 1 {\n t := s[len(s)-1]\n if t != \"\" {\n return false, t\n } else {\n return false, \"\"\n }\n } else {\n return false, \"\"\n }\n}\n\nfunc main() {\n fmt.Println(\"The listed extensions are:\")\n fmt.Println(extensions, \"\\n\")\n tests := []string{\n \"MyData.a##\", \"MyData.tar.Gz\", \"MyData.gzip\",\n \"MyData.7z.backup\", \"MyData...\", \"MyData\",\n \"MyData_v1.0.tar.bz2\", \"MyData_v1.0.bz2\",\n }\n for _, test := range tests {\n ok, ext := fileExtInList(test)\n fmt.Printf(\"%-20s => %-5t (extension = %s)\\n\", test, ok, ext)\n }\n}"} {"title": "File size distribution", "language": "Go from Kotlin", "task": "Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.\n\n\nMy suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.\n\nDon't forget that empty files may exist, to serve as a marker.\n\n\nIs your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n \"os\"\n \"path/filepath\"\n)\n\nfunc commatize(n int64) string {\n s := fmt.Sprintf(\"%d\", n)\n if n < 0 {\n s = s[1:]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfunc fileSizeDistribution(root string) {\n var sizes [12]int\n files := 0\n directories := 0\n totalSize := int64(0)\n walkFunc := func(path string, info os.FileInfo, err error) error {\n if err != nil {\n return err\n }\n files++\n if info.IsDir() {\n directories++\n }\n size := info.Size()\n if size == 0 {\n sizes[0]++\n return nil\n }\n totalSize += size\n logSize := math.Log10(float64(size))\n index := int(math.Floor(logSize))\n sizes[index+1]++\n return nil\n }\n err := filepath.Walk(root, walkFunc)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"File size distribution for '%s' :-\\n\\n\", root)\n for i := 0; i < len(sizes); i++ {\n if i == 0 {\n fmt.Print(\" \")\n } else {\n fmt.Print(\"+ \")\n }\n fmt.Printf(\"Files less than 10 ^ %-2d bytes : %5d\\n\", i, sizes[i])\n }\n fmt.Println(\" -----\")\n fmt.Printf(\"= Total number of files : %5d\\n\", files)\n fmt.Printf(\" including directories : %5d\\n\", directories)\n c := commatize(totalSize)\n fmt.Println(\"\\n Total size of files :\", c, \"bytes\")\n}\n\nfunc main() {\n fileSizeDistribution(\"./\")\n}"} {"title": "Find Chess960 starting position identifier", "language": "Go from Wren", "task": "Starting Position Identifier number (\"SP-ID\"), and generate the corresponding position. \n\n;Task:\nThis task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.\n\nYou may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.\n\n;Algorithm:\n\nThe derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).\n\n1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''\n\n2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.\n\n3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').\n\n4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518.\n\nNote that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.\n\n RQNBBKRN = 601\n RNQBBKRN = 617\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strings\"\n)\n\nvar glyphs = []rune(\"\u265c\u265e\u265d\u265b\u265a\u2656\u2658\u2657\u2655\u2654\")\nvar names = map[rune]string{'R': \"rook\", 'N': \"knight\", 'B': \"bishop\", 'Q': \"queen\", 'K': \"king\"}\nvar g2lMap = map[rune]string{\n '\u265c': \"R\", '\u265e': \"N\", '\u265d': \"B\", '\u265b': \"Q\", '\u265a': \"K\",\n '\u2656': \"R\", '\u2658': \"N\", '\u2657': \"B\", '\u2655': \"Q\", '\u2654': \"K\",\n}\n\nvar ntable = map[string]int{\"01\": 0, \"02\": 1, \"03\": 2, \"04\": 3, \"12\": 4, \"13\": 5, \"14\": 6, \"23\": 7, \"24\": 8, \"34\": 9}\n\nfunc g2l(pieces string) string {\n lets := \"\"\n for _, p := range pieces {\n lets += g2lMap[p]\n }\n return lets\n}\n\nfunc spid(pieces string) int {\n pieces = g2l(pieces) // convert glyphs to letters\n\n /* check for errors */\n if len(pieces) != 8 {\n log.Fatal(\"There must be exactly 8 pieces.\")\n }\n for _, one := range \"KQ\" {\n count := 0\n for _, p := range pieces {\n if p == one {\n count++\n }\n }\n if count != 1 {\n log.Fatalf(\"There must be one %s.\", names[one])\n }\n }\n for _, two := range \"RNB\" {\n count := 0\n for _, p := range pieces {\n if p == two {\n count++\n }\n }\n if count != 2 {\n log.Fatalf(\"There must be two %s.\", names[two])\n }\n }\n r1 := strings.Index(pieces, \"R\")\n r2 := strings.Index(pieces[r1+1:], \"R\") + r1 + 1\n k := strings.Index(pieces, \"K\")\n if k < r1 || k > r2 {\n log.Fatal(\"The king must be between the rooks.\")\n }\n b1 := strings.Index(pieces, \"B\")\n b2 := strings.Index(pieces[b1+1:], \"B\") + b1 + 1\n if (b2-b1)%2 == 0 {\n log.Fatal(\"The bishops must be on opposite color squares.\")\n }\n\n /* compute SP_ID */\n piecesN := strings.ReplaceAll(pieces, \"Q\", \"\")\n piecesN = strings.ReplaceAll(piecesN, \"B\", \"\")\n n1 := strings.Index(piecesN, \"N\")\n n2 := strings.Index(piecesN[n1+1:], \"N\") + n1 + 1\n np := fmt.Sprintf(\"%d%d\", n1, n2)\n N := ntable[np]\n\n piecesQ := strings.ReplaceAll(pieces, \"B\", \"\")\n Q := strings.Index(piecesQ, \"Q\")\n\n D := strings.Index(\"0246\", fmt.Sprintf(\"%d\", b1))\n L := strings.Index(\"1357\", fmt.Sprintf(\"%d\", b2))\n if D == -1 {\n D = strings.Index(\"0246\", fmt.Sprintf(\"%d\", b2))\n L = strings.Index(\"1357\", fmt.Sprintf(\"%d\", b1))\n }\n\n return 96*N + 16*Q + 4*D + L\n}\n\nfunc main() {\n for _, pieces := range []string{\"\u2655\u2658\u2656\u2657\u2657\u2658\u2654\u2656\", \"\u2656\u2658\u2657\u2655\u2654\u2657\u2658\u2656\", \"\u2656\u2655\u2658\u2657\u2657\u2654\u2656\u2658\", \"\u2656\u2658\u2655\u2657\u2657\u2654\u2656\u2658\"} {\n fmt.Printf(\"%s or %s has SP-ID of %d\\n\", pieces, g2l(pieces), spid(pieces))\n }\n}"} {"title": "Find duplicate files", "language": "Go", "task": "In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. \n\n\n;Task:\nCreate a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.\n\nThe program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. \n\nSpecify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. \n\nIdentify hard links (filenames referencing the same content) in the output if applicable for the filesystem. \n\nFor extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"crypto/md5\"\n \"io/ioutil\"\n \"log\"\n \"os\"\n \"path/filepath\"\n \"sort\"\n \"time\"\n)\n\ntype fileData struct {\n filePath string\n info os.FileInfo\n}\n\ntype hash [16]byte\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc checksum(filePath string) hash {\n bytes, err := ioutil.ReadFile(filePath)\n check(err)\n return hash(md5.Sum(bytes))\n}\n\nfunc findDuplicates(dirPath string, minSize int64) [][2]fileData {\n var dups [][2]fileData\n m := make(map[hash]fileData)\n werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {\n if err != nil {\n return err\n }\n if !info.IsDir() && info.Size() >= minSize {\n h := checksum(path)\n fd, ok := m[h]\n fd2 := fileData{path, info}\n if !ok {\n m[h] = fd2\n } else {\n dups = append(dups, [2]fileData{fd, fd2})\n }\n }\n return nil\n })\n check(werr)\n return dups\n}\n\nfunc main() {\n dups := findDuplicates(\".\", 1)\n fmt.Println(\"The following pairs of files have the same size and the same hash:\\n\")\n fmt.Println(\"File name Size Date last modified\")\n fmt.Println(\"==========================================================\")\n sort.Slice(dups, func(i, j int) bool {\n return dups[i][0].info.Size() > dups[j][0].info.Size() // in order of decreasing size\n })\n for _, dup := range dups {\n for i := 0; i < 2; i++ {\n d := dup[i]\n fmt.Printf(\"%-20s %8d %v\\n\", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))\n }\n fmt.Println()\n }\n}"} {"title": "Find if a point is within a triangle", "language": "Go from Wren", "task": "Find if a point is within a triangle.\n\n\n;Task:\n \n::* Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* You may use any algorithm. \n\n::* Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst EPS = 0.001\nconst EPS_SQUARE = EPS * EPS\n\nfunc side(x1, y1, x2, y2, x, y float64) float64 {\n return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)\n}\n\nfunc naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n checkSide1 := side(x1, y1, x2, y2, x, y) >= 0\n checkSide2 := side(x2, y2, x3, y3, x, y) >= 0\n checkSide3 := side(x3, y3, x1, y1, x, y) >= 0\n return checkSide1 && checkSide2 && checkSide3\n}\n\nfunc pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n xMin := math.Min(x1, math.Min(x2, x3)) - EPS\n xMax := math.Max(x1, math.Max(x2, x3)) + EPS\n yMin := math.Min(y1, math.Min(y2, y3)) - EPS\n yMax := math.Max(y1, math.Max(y2, y3)) + EPS\n return !(x < xMin || xMax < x || y < yMin || yMax < y)\n}\n\nfunc distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {\n p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)\n dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength\n if dotProduct < 0 {\n return (x-x1)*(x-x1) + (y-y1)*(y-y1)\n } else if dotProduct <= 1 {\n p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)\n return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength\n } else {\n return (x-x2)*(x-x2) + (y-y2)*(y-y2)\n }\n}\n\nfunc accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {\n if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {\n return false\n }\n if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {\n return true\n }\n if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {\n return true\n }\n if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {\n return true\n }\n if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {\n return true\n }\n return false\n}\n\nfunc main() {\n pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}\n tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}\n fmt.Println(\"Triangle is\", tri)\n x1, y1 := tri[0][0], tri[0][1]\n x2, y2 := tri[1][0], tri[1][1]\n x3, y3 := tri[2][0], tri[2][1]\n for _, pt := range pts {\n x, y := pt[0], pt[1]\n within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n fmt.Println(\"Point\", pt, \"is within triangle?\", within)\n }\n fmt.Println()\n tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}\n fmt.Println(\"Triangle is\", tri)\n x1, y1 = tri[0][0], tri[0][1]\n x2, y2 = tri[1][0], tri[1][1]\n x3, y3 = tri[2][0], tri[2][1]\n x := x1 + (3.0/7)*(x2-x1)\n y := y1 + (3.0/7)*(y2-y1)\n pt := [2]float64{x, y}\n within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n fmt.Println()\n tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}\n fmt.Println(\"Triangle is\", tri)\n x3 = tri[2][0]\n y3 = tri[2][1]\n within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n fmt.Println(\"Point\", pt, \"is within triangle ?\", within)\n}"} {"title": "Find limit of recursion", "language": "Go", "task": "{{selection|Short Circuit|Console Program Basics}}\n\n \n\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"runtime/debug\"\n)\n\nfunc main() {\n\tstack := flag.Int(\"stack\", 0, \"maximum per goroutine stack size or 0 for the default\")\n\tflag.Parse()\n\tif *stack > 0 {\n\t\tdebug.SetMaxStack(*stack)\n\t}\n\tr(1)\n}\n\nfunc r(l int) {\n\tif l%1000 == 0 {\n\t\tfmt.Println(l)\n\t}\n\tr(l + 1)\n}"} {"title": "Find palindromic numbers in both binary and ternary bases", "language": "Go from C", "task": "* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':\n:::* base 2\n:::* base 3\n* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\n\nIt's permissible to assume the first two numbers and simply list them.\n\n\n;See also\n* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"time\"\n)\n\nfunc isPalindrome2(n uint64) bool {\n x := uint64(0)\n if (n & 1) == 0 {\n return n == 0\n }\n for x < n {\n x = (x << 1) | (n & 1)\n n >>= 1\n }\n return n == x || n == (x>>1)\n}\n\nfunc reverse3(n uint64) uint64 {\n x := uint64(0)\n for n != 0 {\n x = x*3 + (n % 3)\n n /= 3\n }\n return x\n}\n\nfunc show(n uint64) {\n fmt.Println(\"Decimal :\", n)\n fmt.Println(\"Binary :\", strconv.FormatUint(n, 2))\n fmt.Println(\"Ternary :\", strconv.FormatUint(n, 3))\n fmt.Println(\"Time :\", time.Since(start))\n fmt.Println()\n}\n\nfunc min(a, b uint64) uint64 {\n if a < b {\n return a\n }\n return b\n}\n\nfunc max(a, b uint64) uint64 {\n if a > b {\n return a\n }\n return b\n}\n\nvar start time.Time\n\nfunc main() {\n start = time.Now()\n fmt.Println(\"The first 7 numbers which are palindromic in both binary and ternary are :\\n\")\n show(0)\n cnt := 1\n var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1\n for {\n i := lo\n for ; i < hi; i++ {\n n := (i*3+1)*pow3 + reverse3(i)\n if !isPalindrome2(n) {\n continue\n }\n show(n)\n cnt++\n if cnt >= 7 {\n return\n }\n }\n\n if i == pow3 {\n pow3 *= 3\n } else {\n pow2 *= 4\n }\n\n for {\n for pow2 <= pow3 {\n pow2 *= 4\n }\n\n lo2 := (pow2/pow3 - 1) / 3\n hi2 := (pow2*2/pow3-1)/3 + 1\n lo3 := pow3 / 3\n hi3 := pow3\n\n if lo2 >= hi3 {\n pow3 *= 3\n } else if lo3 >= hi2 {\n pow2 *= 4\n } else {\n lo = max(lo2, lo3)\n hi = min(hi2, hi3)\n break\n }\n }\n }\n}"} {"title": "Find the intersection of a line with a plane", "language": "Go from Kotlin", "task": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\n\n;Task:\nFind the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype Vector3D struct{ x, y, z float64 }\n\nfunc (v *Vector3D) Add(w *Vector3D) *Vector3D {\n return &Vector3D{v.x + w.x, v.y + w.y, v.z + w.z}\n}\n\nfunc (v *Vector3D) Sub(w *Vector3D) *Vector3D {\n return &Vector3D{v.x - w.x, v.y - w.y, v.z - w.z}\n}\n\nfunc (v *Vector3D) Mul(s float64) *Vector3D {\n return &Vector3D{s * v.x, s * v.y, s * v.z}\n}\n\nfunc (v *Vector3D) Dot(w *Vector3D) float64 {\n return v.x*w.x + v.y*w.y + v.z*w.z\n}\n\nfunc (v *Vector3D) String() string {\n return fmt.Sprintf(\"(%v, %v, %v)\", v.x, v.y, v.z)\n}\n\nfunc intersectPoint(rayVector, rayPoint, planeNormal, planePoint *Vector3D) *Vector3D {\n diff := rayPoint.Sub(planePoint)\n prod1 := diff.Dot(planeNormal)\n prod2 := rayVector.Dot(planeNormal)\n prod3 := prod1 / prod2\n return rayPoint.Sub(rayVector.Mul(prod3))\n}\n\nfunc main() {\n rv := &Vector3D{0.0, -1.0, -1.0}\n rp := &Vector3D{0.0, 0.0, 10.0}\n pn := &Vector3D{0.0, 0.0, 1.0}\n pp := &Vector3D{0.0, 0.0, 5.0}\n ip := intersectPoint(rv, rp, pn, pp)\n fmt.Println(\"The ray intersects the plane at\", ip)\n}"} {"title": "Find the intersection of two lines", "language": "Go", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"errors\"\n)\n\ntype Point struct {\n\tx float64\n\ty float64\n}\n\ntype Line struct {\n\tslope float64\n\tyint float64\n}\n\nfunc CreateLine (a, b Point) Line {\n\tslope := (b.y-a.y) / (b.x-a.x)\n\tyint := a.y - slope*a.x\n\treturn Line{slope, yint}\n} \n\nfunc EvalX (l Line, x float64) float64 {\n\treturn l.slope*x + l.yint\n}\n\nfunc Intersection (l1, l2 Line) (Point, error) {\n\tif l1.slope == l2.slope {\n\t\treturn Point{}, errors.New(\"The lines do not intersect\")\n\t}\n\tx := (l2.yint-l1.yint) / (l1.slope-l2.slope)\n\ty := EvalX(l1, x)\n\treturn Point{x, y}, nil\n}\n\nfunc main() {\n\tl1 := CreateLine(Point{4, 0}, Point{6, 10})\n\tl2 := CreateLine(Point{0, 3}, Point{10, 7})\n\tif result, err := Intersection(l1, l2); err == nil {\n\t\tfmt.Println(result)\n\t} else {\n\t\tfmt.Println(\"The lines do not intersect\")\n\t}\n}\n"} {"title": "Find the last Sunday of each month", "language": "Go", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\t\n\tvar year int\n\tvar t time.Time\n\tvar lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }\n\t\n\tfor {\n\t\tfmt.Print(\"Please select a year: \")\n\t\t_, err := fmt.Scanf(\"%d\", &year)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"Last Sundays of each month of\", year)\n\tfmt.Println(\"==================================\")\n\n\tfor i := 1;i < 13; i++ {\n\t\tj := lastDay[i-1]\n\t\tif i == 2 {\n\t\t\tif time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC).Month() == time.Date(int(year), time.Month(i), j-1, 0, 0, 0, 0, time.UTC).Month() {\n\t\t\t\tj = 29\n\t\t\t} else {\n\t\t\t\tj = 28\n\t\t\t}\n\t\t}\n\t\tfor {\n\t\t\tt = time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC)\n\t\t\tif t.Weekday() == 0 {\n\t\t\t\tfmt.Printf(\"%s: %d\\n\", time.Month(i), j)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tj = j - 1\n\t\t}\n\t}\n}\n"} {"title": "Find the missing permutation", "language": "Go", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar given = strings.Split(`ABCD\nCABD\nACDB\nDACB\nBCDA\nACBD\nADCB\nCDAB\nDABC\nBCAD\nCADB\nCDBA\nCBAD\nABDC\nADBC\nBDCA\nDCBA\nBACD\nBADC\nBDAC\nCBDA\nDBCA\nDCAB`, \"\\n\")\n\nfunc main() {\n b := make([]byte, len(given[0]))\n for i := range b {\n m := make(map[byte]int)\n for _, p := range given {\n m[p[i]]++\n }\n for char, count := range m {\n if count&1 == 1 {\n b[i] = char\n break\n }\n }\n }\n fmt.Println(string(b))\n}"} {"title": "First-class functions/Use numbers analogously", "language": "Go", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n x := 2.\n xi := .5\n y := 4.\n yi := .25\n z := func() float64 { return x + y }\n zi := func() float64 { return 1 / (x + y) }\n // point A\n\n numbers := []interface{}{&x, &y, z}\n inverses := []interface{}{&xi, &yi, zi}\n // point B\n\n mfs := make([]func(n interface{}) float64, len(numbers))\n for i := range mfs {\n mfs[i] = multiplier(numbers[i], inverses[i])\n }\n // pointC\n\n for _, mf := range mfs {\n fmt.Println(mf(1.))\n }\n}\n\nfunc multiplier(n1, n2 interface{}) func(interface{}) float64 {\n return func(m interface{}) float64 {\n // close on interface objects n1, n2, and m\n return eval(n1) * eval(n2) * eval(m)\n }\n}\n\n// utility function for evaluating multiplier interface objects\nfunc eval(n interface{}) float64 {\n switch n.(type) {\n case float64:\n return n.(float64)\n case *float64:\n return *n.(*float64)\n case func() float64:\n return n.(func() float64)()\n }\n panic(\"unsupported multiplier type\")\n return 0 // never reached\n}"} {"title": "First perfect square in base n with n unique digits", "language": "Go", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"strconv\"\n \"time\"\n)\n\nconst maxBase = 27\nconst minSq36 = \"1023456789abcdefghijklmnopqrstuvwxyz\"\nconst minSq36x = \"10123456789abcdefghijklmnopqrstuvwxyz\"\n\nvar bigZero = new(big.Int)\nvar bigOne = new(big.Int).SetUint64(1)\n\nfunc containsAll(sq string, base int) bool {\n var found [maxBase]byte\n le := len(sq)\n reps := 0\n for _, r := range sq {\n d := r - 48\n if d > 38 {\n d -= 39\n }\n found[d]++\n if found[d] > 1 {\n reps++\n if le-reps < base {\n return false\n }\n }\n }\n return true\n}\n\nfunc sumDigits(n, base *big.Int) *big.Int {\n q := new(big.Int).Set(n)\n r := new(big.Int)\n sum := new(big.Int).Set(bigZero)\n for q.Cmp(bigZero) == 1 {\n q.QuoRem(q, base, r)\n sum.Add(sum, r)\n }\n return sum\n}\n\nfunc digitalRoot(n *big.Int, base int) int {\n root := new(big.Int)\n b := big.NewInt(int64(base))\n for i := new(big.Int).Set(n); i.Cmp(b) >= 0; i.Set(root) {\n root.Set(sumDigits(i, b))\n }\n return int(root.Int64())\n}\n\nfunc minStart(base int) (string, uint64, int) {\n nn := new(big.Int)\n ms := minSq36[:base]\n nn.SetString(ms, base)\n bdr := digitalRoot(nn, base)\n var drs []int\n var ixs []uint64\n for n := uint64(1); n < uint64(2*base); n++ {\n nn.SetUint64(n * n)\n dr := digitalRoot(nn, base)\n if dr == 0 {\n dr = int(n * n)\n }\n if dr == bdr {\n ixs = append(ixs, n)\n }\n if n < uint64(base) && dr >= bdr {\n drs = append(drs, dr)\n }\n }\n inc := uint64(1)\n if len(ixs) >= 2 && base != 3 {\n inc = ixs[1] - ixs[0]\n }\n if len(drs) == 0 {\n return ms, inc, bdr\n }\n min := drs[0]\n for _, dr := range drs[1:] {\n if dr < min {\n min = dr\n }\n }\n rd := min - bdr\n if rd == 0 {\n return ms, inc, bdr\n }\n if rd == 1 {\n return minSq36x[:base+1], 1, bdr\n }\n ins := string(minSq36[rd])\n return (minSq36[:rd] + ins + minSq36[rd:])[:base+1], inc, bdr\n}\n\nfunc main() {\n start := time.Now()\n var nb, nn big.Int\n for n, k, base := uint64(2), uint64(1), 2; ; n += k {\n if base > 2 && n%uint64(base) == 0 {\n continue\n } \n nb.SetUint64(n)\n sq := nb.Mul(&nb, &nb).Text(base)\n if !containsAll(sq, base) {\n continue\n }\n ns := strconv.FormatUint(n, base)\n tt := time.Since(start).Seconds()\n fmt.Printf(\"Base %2d:%15s\u00b2 = %-27s in %8.3fs\\n\", base, ns, sq, tt)\n if base == maxBase {\n break\n }\n base++\n ms, inc, bdr := minStart(base)\n k = inc\n nn.SetString(ms, base)\n nb.Sqrt(&nn)\n if nb.Uint64() < n+1 {\n nb.SetUint64(n + 1)\n }\n if k != 1 {\n for {\n nn.Mul(&nb, &nb)\n dr := digitalRoot(&nn, base)\n if dr == bdr {\n n = nb.Uint64() - k\n break\n }\n nb.Add(&nb, bigOne)\n }\n } else {\n n = nb.Uint64() - k\n }\n }\n}"} {"title": "First power of 2 that has leading decimal digits of 12", "language": "Go from Pascal", "task": "(This task is taken from a ''Project Euler'' problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 = 128''' and '''7''' is\nthe first power of '''2''' whose leading decimal digits are '''12'''.\n\nThe next power of '''2''' whose leading decimal digits\nare '''12''' is '''80''',\n'''280 = 1208925819614629174706176'''.\n\n\nDefine ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest\nvalue of ''' ''j'' ''' such that the base ten representation\nof '''2''j''''' begins with the digits of ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) = 12710\n\n\n;Task:\n::* find: \n:::::* ''' ''p''(12, 1) ''' \n:::::* ''' ''p''(12, 2) ''' \n:::::* ''' ''p''(123, 45) ''' \n:::::* ''' ''p''(123, 12345) ''' \n:::::* ''' ''p''(123, 678910) ''' \n::* display the results here, on this page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"time\"\n)\n\nconst ld10 = math.Ln2 / math.Ln10\n\nfunc commatize(n uint64) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc p(L, n uint64) uint64 {\n i := L\n digits := uint64(1)\n for i >= 10 {\n digits *= 10\n i /= 10\n }\n count := uint64(0)\n for i = 0; count < n; i++ {\n e := math.Exp(math.Ln10 * math.Mod(float64(i)*ld10, 1))\n if uint64(math.Trunc(e*float64(digits))) == L {\n count++ \n }\n }\n return i - 1\n}\n\nfunc main() {\n start := time.Now()\n params := [][2]uint64{{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}}\n for _, param := range params {\n fmt.Printf(\"p(%d, %d) = %s\\n\", param[0], param[1], commatize(p(param[0], param[1])))\n }\n fmt.Printf(\"\\nTook %s\\n\", time.Since(start))\n}"} {"title": "Fivenum", "language": "Go from Perl", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"sort\"\n)\n\nfunc fivenum(a []float64) (n5 [5]float64) {\n sort.Float64s(a)\n n := float64(len(a))\n n4 := float64((len(a)+3)/2) / 2\n d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n}\n for e, de := range d {\n floor := int(de - 1)\n ceil := int(math.Ceil(de - 1))\n n5[e] = .5 * (a[floor] + a[ceil])\n }\n return\n}\n\nvar (\n x1 = []float64{36, 40, 7, 39, 41, 15}\n x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}\n x3 = []float64{\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578,\n }\n)\n\nfunc main() {\n fmt.Println(fivenum(x1))\n fmt.Println(fivenum(x2))\n fmt.Println(fivenum(x3))\n}"} {"title": "Fixed length records", "language": "Go", "task": "Fixed length read/write\n\nBefore terminals, computers commonly used punch card readers or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\n;Task:\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. \n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.\n\n;Sample data:\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.\n\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.\n\nprompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\n\n;Bonus round:\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc reverseBytes(bytes []byte) {\n for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {\n bytes[i], bytes[j] = bytes[j], bytes[i]\n }\n}\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc main() {\n in, err := os.Open(\"infile.dat\")\n check(err)\n defer in.Close()\n\n out, err := os.Create(\"outfile.dat\")\n check(err)\n\n record := make([]byte, 80)\n empty := make([]byte, 80)\n for {\n n, err := in.Read(record)\n if err != nil {\n if n == 0 {\n break // EOF reached\n } else {\n out.Close()\n log.Fatal(err)\n }\n }\n reverseBytes(record)\n out.Write(record)\n copy(record, empty)\n }\n out.Close()\n\n // Run dd from within program to write output.dat\n // to standard output as normal text with newlines.\n cmd := exec.Command(\"dd\", \"if=outfile.dat\", \"cbs=80\", \"conv=unblock\")\n bytes, err := cmd.Output()\n check(err)\n fmt.Println(string(bytes))\n}"} {"title": "Flatten a list", "language": "Go", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc list(s ...interface{}) []interface{} {\n return s\n}\n\nfunc main() {\n s := list(list(1),\n 2,\n list(list(3, 4), 5),\n list(list(list())),\n list(list(list(6))),\n 7,\n 8,\n list(),\n )\n fmt.Println(s)\n fmt.Println(flatten(s))\n}\n\nfunc flatten(s []interface{}) (r []int) {\n for _, e := range s {\n switch i := e.(type) {\n case int:\n r = append(r, i)\n case []interface{}:\n r = append(r, flatten(i)...)\n }\n }\n return\n}"} {"title": "Flipping bits game", "language": "Go", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\nfunc main() {\n\n\trand.Seed(time.Now().UnixNano())\n \n\tvar n int = 3 // Change to define board size\n\tvar moves int = 0\n\t\n\ta := make([][]int, n)\n\tfor i := range a {\n\t\ta[i] = make([]int, n)\n\t\tfor j := range a {\n\t\t\ta[i][j] = rand.Intn(2)\n\t\t}\n\t}\n\n b := make([][]int, len(a))\n\tfor i := range a {\n\t\tb[i] = make([]int, len(a[i]))\n\t\tcopy(b[i], a[i])\n\t}\n\t\n\tfor i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {\n\t\tb = flipCol(b, rand.Intn(n) + 1)\n\t\tb = flipRow(b, rand.Intn(n) + 1)\n\t}\n\t\n\tfmt.Println(\"Target:\")\n\tdrawBoard(a)\n\tfmt.Println(\"\\nBoard:\")\n\tdrawBoard(b)\n\t\n\tvar rc rune\n\tvar num int\n\t\n\tfor {\n\t\tfor{\n\t\t\tfmt.Printf(\"\\nFlip row (r) or column (c) 1 .. %d (c1, ...): \", n)\n\t\t\t_, err := fmt.Scanf(\"%c%d\", &rc, &num)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif num < 1 || num > n {\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\n\t\tswitch rc {\n\t\t\tcase 'c':\n\t\t\t\tfmt.Printf(\"Column %v will be flipped\\n\", num)\n\t\t\t\tflipCol(b, num)\n\t\t\tcase 'r':\n\t\t\t\tfmt.Printf(\"Row %v will be flipped\\n\", num)\n\t\t\t\tflipRow(b, num)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Wrong command!\")\n\t\t\t\tcontinue\n\t\t}\n\t\t\n\t\tmoves++\n\t\tfmt.Println(\"\\nMoves taken: \", moves)\n\t\t\n\t\tfmt.Println(\"Target:\")\n\t\tdrawBoard(a)\n\t\tfmt.Println(\"\\nBoard:\")\n\t\tdrawBoard(b)\n\t\n\t\tif compareSlices(a, b) {\n\t\t\tfmt.Printf(\"Finished. You win with %d moves!\\n\", moves)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc drawBoard (m [][]int) {\n\tfmt.Print(\" \")\n\tfor i := range m {\n\t\tfmt.Printf(\"%d \", i+1)\t\n\t}\n\tfor i := range m {\n\t\tfmt.Println()\n\t\tfmt.Printf(\"%d \", i+1)\n\t\tfor _, val := range m[i] {\n\t\t\tfmt.Printf(\" %d\", val)\n\t\t}\n\t}\n\tfmt.Print(\"\\n\")\n}\n\nfunc flipRow(m [][]int, row int) ([][]int) {\n\tfor j := range m {\n\t\tm[row-1][j] ^= 1\n\t}\n\treturn m\n}\n \nfunc flipCol(m [][]int, col int) ([][]int) {\n\tfor j := range m {\n\t\tm[j][col-1] ^= 1\n\t}\n\treturn m\n}\n\nfunc compareSlices(m [][]int, n[][]int) bool {\n\to := true\n\tfor i := range m {\n\t\tfor j := range m {\n\t\t\tif m[i][j] != n[i][j] { o = false }\n\t\t}\n\t}\n\treturn o \n}"} {"title": "Floyd's triangle", "language": "Go", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n floyd(5)\n floyd(14)\n}\n\nfunc floyd(n int) {\n fmt.Printf(\"Floyd %d:\\n\", n)\n lowerLeftCorner := n*(n-1)/2 + 1\n lastInColumn := lowerLeftCorner\n lastInRow := 1\n for i, row := 1, 1; row <= n; i++ {\n w := len(fmt.Sprint(lastInColumn))\n if i < lastInRow {\n fmt.Printf(\"%*d \", w, i)\n lastInColumn++\n } else {\n fmt.Printf(\"%*d\\n\", w, i)\n row++\n lastInRow += row\n lastInColumn = lowerLeftCorner\n }\n }\n}"} {"title": "Four bit adder", "language": "Go", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc xor(a, b byte) byte {\n return a&(^b) | b&(^a)\n}\n\nfunc ha(a, b byte) (s, c byte) {\n return xor(a, b), a & b\n}\n\nfunc fa(a, b, c0 byte) (s, c1 byte) {\n sa, ca := ha(a, c0)\n s, cb := ha(sa, b)\n c1 = ca | cb\n return\n}\n\nfunc add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {\n s0, c0 := fa(a0, b0, 0)\n s1, c1 := fa(a1, b1, c0)\n s2, c2 := fa(a2, b2, c1)\n s3, v = fa(a3, b3, c2)\n return\n}\n\nfunc main() {\n // add 10+9 result should be 1 0 0 1 1\n fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))\n}"} {"title": "Four is magic", "language": "Go", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range [...]int64{\n\t\t0, 4, 6, 11, 13, 75, 100, 337, -164,\n\t\tmath.MaxInt64,\n\t} {\n\t\tfmt.Println(fourIsMagic(n))\n\t}\n}\n\nfunc fourIsMagic(n int64) string {\n\ts := say(n)\n\ts = strings.ToUpper(s[:1]) + s[1:]\n\tt := s\n\tfor n != 4 {\n\t\tn = int64(len(s))\n\t\ts = say(n)\n\t\tt += \" is \" + s + \", \" + s\n\t}\n\tt += \" is magic.\"\n\treturn t\n}\n \n// Following is from https://rosettacode.org/wiki/Number_names#Go\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t// Note, for math.MinInt64 this leaves n negative.\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t// work right-to-left\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}"} {"title": "Four is the number of letters in the ...", "language": "Go", "task": "The '''Four is ...''' sequence is based on the counting of the number of\nletters in the words of the (never-ending) sentence:\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, *** \n\n\n;Definitions and directives:\n:* English is to be used in spelling numbers.\n:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').\n:* Commas are not counted, nor are hyphens (dashes or minus signs).\n:* '''twenty-three''' has eleven letters.\n:* '''twenty-three''' is considered one word (which is hyphenated).\n:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.\n:* The American version of numbers will be used here in this task (as opposed to the British version).\n '''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\n;Task:\n:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:\n '''4 2 3 6 2 7'''\n:* Only construct as much as is needed for the never-ending sentence.\n:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.\n:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.\n:* Show all output here.\n\n\n;Test cases:\n Display the first 201 numbers in the sequence (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n\n;Related tasks:\n:* [[Four is magic]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Self-referential sequence]]\n:* [[Spelling of ordinal numbers]]\n\n\n;Also see:\n:* See the OEIS sequence A72425 \"Four is the number of letters...\".\n:* See the OEIS sequence A72424 \"Five's the number of letters...\"\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tf := NewFourIsSeq()\n\tfmt.Print(\"The lengths of the first 201 words are:\")\n\tfor i := 1; i <= 201; i++ {\n\t\tif i%25 == 1 {\n\t\t\tfmt.Printf(\"\\n%3d: \", i)\n\t\t}\n\t\t_, n := f.WordLen(i)\n\t\tfmt.Printf(\" %2d\", n)\n\t}\n\tfmt.Println()\n\tfmt.Println(\"Length of sentence so far:\", f.TotalLength())\n\t/* For debugging:\n\tlog.Println(\"sentence:\", strings.Join(f.words, \" \"))\n\tfor i, w := range f.words {\n\t\tlog.Printf(\"%3d: %2d %q\\n\", i, countLetters(w), w)\n\t}\n\tlog.Println(f.WordLen(2202))\n\tlog.Println(\"len(f.words):\", len(f.words))\n\tlog.Println(\"sentence:\", strings.Join(f.words, \" \"))\n\t*/\n\tfor i := 1000; i <= 1e7; i *= 10 {\n\t\tw, n := f.WordLen(i)\n\t\tfmt.Printf(\"Word %8d is %q, with %d letters.\", i, w, n)\n\t\tfmt.Println(\" Length of sentence so far:\", f.TotalLength())\n\t}\n}\n\ntype FourIsSeq struct {\n\ti int // index of last word processed\n\twords []string // strings.Join(words,\" \") gives the sentence so far\n}\n\nfunc NewFourIsSeq() *FourIsSeq {\n\treturn &FourIsSeq{\n\t\t//words: strings.Fields(\"Four is the number of letters in the first word of this sentence,\"),\n\t\twords: []string{\n\t\t\t\"Four\", \"is\", \"the\", \"number\",\n\t\t\t\"of\", \"letters\", \"in\", \"the\",\n\t\t\t\"first\", \"word\", \"of\", \"this\", \"sentence,\",\n\t\t},\n\t}\n}\n\n// WordLen returns the w'th word and its length (only counting letters).\nfunc (f *FourIsSeq) WordLen(w int) (string, int) {\n\tfor len(f.words) < w {\n\t\tf.i++\n\t\tn := countLetters(f.words[f.i])\n\t\tns := say(int64(n))\n\t\tos := sayOrdinal(int64(f.i+1)) + \",\"\n\t\t// append something like: \"two in the second,\"\n\t\tf.words = append(f.words, strings.Fields(ns)...)\n\t\tf.words = append(f.words, \"in\", \"the\")\n\t\tf.words = append(f.words, strings.Fields(os)...)\n\t}\n\tword := f.words[w-1]\n\treturn word, countLetters(word)\n}\n\n// TotalLength returns the total number of characters (including blanks,\n// commas, and punctuation) of the sentence so far constructed.\nfunc (f FourIsSeq) TotalLength() int {\n\tcnt := 0\n\tfor _, w := range f.words {\n\t\tcnt += len(w) + 1\n\t}\n\treturn cnt - 1\n}\n\nfunc countLetters(s string) int {\n\tcnt := 0\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}\n\n// ...\n// the contents of\n// https://rosettacode.org/wiki/Spelling_of_ordinal_numbers#Go\n// omitted from this listing\n// ...\n"} {"title": "French Republican calendar", "language": "Go from BBC Basic", "task": "Write a program to convert dates between the French Republican calendar.\n\nThe year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fete de la vertu / Virtue Day, Fete du genie / Talent Day, Fete du travail / Labour Day, Fete de l'opinion / Opinion Day, and Fete des recompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fete de la Revolution / Revolution Day.\n\nAs a minimum, your program should give correct results for dates in the range from 1 Vendemiaire 1 = 22 September 1792 to 10 Nivose 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)\n\nTest your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:\n\n* 1 Vendemiaire 1 = 22 September 1792\n\n* 1 Prairial 3 = 20 May 1795\n\n* 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)\n\n* Fete de la Revolution 11 = 23 September 1803\n\n* 10 Nivose 14 = 31 December 1805\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\nvar (\n gregorianStr = []string{\"January\", \"February\", \"March\",\n \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"}\n gregorian = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}\n republicanStr = []string{\"Vendemiaire\", \"Brumaire\", \"Frimaire\",\n \"Nivose\", \"Pluviose\", \"Ventose\",\n \"Germinal\", \"Floreal\", \"Prairial\",\n \"Messidor\", \"Thermidor\", \"Fructidor\"}\n sansculottidesStr = []string{\"Fete de la vertu\", \"Fete du genie\",\n \"Fete du travail\", \"Fete de l'opinion\",\n \"Fete des recompenses\", \"Fete de la Revolution\"}\n)\n\nfunc main() {\n fmt.Println(\"*** French Republican ***\")\n fmt.Println(\"*** calendar converter ***\")\n fmt.Println(\"Enter a date to convert, in the format 'day month year'\")\n fmt.Println(\"e.g.: 1 Prairial 3,\")\n fmt.Println(\" 20 May 1795.\")\n fmt.Println(\"For Sansculottides, use 'day year'\")\n fmt.Println(\"e.g.: Fete de l'opinion 9.\")\n fmt.Println(\"Or just press 'RETURN' to exit the program.\")\n fmt.Println()\n for sc := bufio.NewScanner(os.Stdin); ; {\n fmt.Print(\"> \")\n sc.Scan()\n src := sc.Text()\n if src == \"\" {\n return\n }\n day, month, year := split(src)\n if year < 1792 {\n day, month, year = dayToGre(repToDay(day, month, year))\n fmt.Println(day, gregorianStr[month-1], year)\n } else {\n day, month, year := dayToRep(greToDay(day, month, year))\n if month == 13 {\n fmt.Println(sansculottidesStr[day-1], year)\n } else {\n fmt.Println(day, republicanStr[month-1], year)\n }\n }\n }\n}\n\nfunc split(s string) (d, m, y int) {\n if strings.HasPrefix(s, \"Fete\") {\n m = 13\n for i, sc := range sansculottidesStr {\n if strings.HasPrefix(s, sc) {\n d = i + 1\n y, _ = strconv.Atoi(s[len(sc)+1:])\n }\n }\n } else {\n d, _ = strconv.Atoi(s[:strings.Index(s, \" \")])\n my := s[strings.Index(s, \" \")+1:]\n mStr := my[:strings.Index(my, \" \")]\n y, _ = strconv.Atoi(my[strings.Index(my, \" \")+1:])\n months := gregorianStr\n if y < 1792 {\n months = republicanStr\n }\n for i, mn := range months {\n if mn == mStr {\n m = i + 1\n }\n }\n }\n return\n}\n\nfunc greToDay(d, m, y int) int {\n if m < 3 {\n y--\n m += 12\n }\n return y*36525/100 - y/100 + y/400 + 306*(m+1)/10 + d - 654842\n}\n\nfunc repToDay(d, m, y int) int {\n if m == 13 {\n m--\n d += 30\n }\n if repLeap(y) {\n d--\n }\n return 365*y + (y+1)/4 - (y+1)/100 + (y+1)/400 + 30*m + d - 395\n}\n\nfunc dayToGre(day int) (d, m, y int) {\n y = day * 100 / 36525\n d = day - y*36525/100 + 21\n y += 1792\n d += y/100 - y/400 - 13\n m = 8\n for d > gregorian[m] {\n d -= gregorian[m]\n m++\n if m == 12 {\n m = 0\n y++\n if greLeap(y) {\n gregorian[1] = 29\n } else {\n gregorian[1] = 28\n }\n }\n }\n m++\n return\n}\n\nfunc dayToRep(day int) (d, m, y int) {\n y = (day-1) * 100 / 36525\n if repLeap(y) {\n y--\n }\n d = day - (y+1)*36525/100 + 365 + (y+1)/100 - (y+1)/400\n y++\n m = 1\n sansculottides := 5\n if repLeap(y) {\n sansculottides = 6\n }\n for d > 30 {\n d -= 30\n m += 1\n if m == 13 {\n if d > sansculottides {\n d -= sansculottides\n m = 1\n y++\n sansculottides = 5\n if repLeap(y) {\n sansculottides = 6\n }\n }\n }\n }\n return\n}\n\nfunc repLeap(year int) bool {\n return (year+1)%4 == 0 && ((year+1)%100 != 0 || (year+1)%400 == 0)\n}\n\nfunc greLeap(year int) bool {\n return year%4 == 0 && (year%100 != 0 || year%400 == 0)\n}"} {"title": "Function prototype", "language": "Go", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "func a() // function with no arguments\nfunc b(x, y int) // function with two arguments\nfunc c(...int) // varargs are called \"variadic parameters\" in Go."} {"title": "Functional coverage tree", "language": "Go from Kotlin", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype FCNode struct {\n name string\n weight int\n coverage float64\n children []*FCNode\n parent *FCNode\n}\n\nfunc newFCN(name string, weight int, coverage float64) *FCNode {\n return &FCNode{name, weight, coverage, nil, nil}\n}\n\nfunc (n *FCNode) addChildren(nodes []*FCNode) {\n for _, node := range nodes {\n node.parent = n\n n.children = append(n.children, node)\n }\n n.updateCoverage()\n}\n\nfunc (n *FCNode) setCoverage(value float64) {\n if n.coverage != value {\n n.coverage = value\n // update any parent's coverage\n if n.parent != nil {\n n.parent.updateCoverage()\n }\n }\n}\n\nfunc (n *FCNode) updateCoverage() {\n v1 := 0.0\n v2 := 0\n for _, node := range n.children {\n v1 += float64(node.weight) * node.coverage\n v2 += node.weight\n }\n n.setCoverage(v1 / float64(v2))\n}\n\nfunc (n *FCNode) show(level int) {\n indent := level * 4\n nl := len(n.name) + indent\n fmt.Printf(\"%*s%*s %3d | %8.6f |\\n\", nl, n.name, 32-nl, \"|\", n.weight, n.coverage)\n if len(n.children) == 0 {\n return\n }\n for _, child := range n.children {\n child.show(level + 1)\n }\n}\n\nvar houses = []*FCNode{\n newFCN(\"house1\", 40, 0),\n newFCN(\"house2\", 60, 0),\n}\n\nvar house1 = []*FCNode{\n newFCN(\"bedrooms\", 1, 0.25),\n newFCN(\"bathrooms\", 1, 0),\n newFCN(\"attic\", 1, 0.75),\n newFCN(\"kitchen\", 1, 0.1),\n newFCN(\"living_rooms\", 1, 0),\n newFCN(\"basement\", 1, 0),\n newFCN(\"garage\", 1, 0),\n newFCN(\"garden\", 1, 0.8),\n}\n\nvar house2 = []*FCNode{\n newFCN(\"upstairs\", 1, 0),\n newFCN(\"groundfloor\", 1, 0),\n newFCN(\"basement\", 1, 0),\n}\n\nvar h1Bathrooms = []*FCNode{\n newFCN(\"bathroom1\", 1, 0.5),\n newFCN(\"bathroom2\", 1, 0),\n newFCN(\"outside_lavatory\", 1, 1),\n}\n\nvar h1LivingRooms = []*FCNode{\n newFCN(\"lounge\", 1, 0),\n newFCN(\"dining_room\", 1, 0),\n newFCN(\"conservatory\", 1, 0),\n newFCN(\"playroom\", 1, 1),\n}\n\nvar h2Upstairs = []*FCNode{\n newFCN(\"bedrooms\", 1, 0),\n newFCN(\"bathroom\", 1, 0),\n newFCN(\"toilet\", 1, 0),\n newFCN(\"attics\", 1, 0.6),\n}\n\nvar h2Groundfloor = []*FCNode{\n newFCN(\"kitchen\", 1, 0),\n newFCN(\"living_rooms\", 1, 0),\n newFCN(\"wet_room_&_toilet\", 1, 0),\n newFCN(\"garage\", 1, 0),\n newFCN(\"garden\", 1, 0.9),\n newFCN(\"hot_tub_suite\", 1, 1),\n}\n\nvar h2Basement = []*FCNode{\n newFCN(\"cellars\", 1, 1),\n newFCN(\"wine_cellar\", 1, 1),\n newFCN(\"cinema\", 1, 0.75),\n}\n\nvar h2UpstairsBedrooms = []*FCNode{\n newFCN(\"suite_1\", 1, 0),\n newFCN(\"suite_2\", 1, 0),\n newFCN(\"bedroom_3\", 1, 0),\n newFCN(\"bedroom_4\", 1, 0),\n}\n\nvar h2GroundfloorLivingRooms = []*FCNode{\n newFCN(\"lounge\", 1, 0),\n newFCN(\"dining_room\", 1, 0),\n newFCN(\"conservatory\", 1, 0),\n newFCN(\"playroom\", 1, 0),\n}\n\nfunc main() {\n cleaning := newFCN(\"cleaning\", 1, 0)\n\n house1[1].addChildren(h1Bathrooms)\n house1[4].addChildren(h1LivingRooms)\n houses[0].addChildren(house1)\n\n h2Upstairs[0].addChildren(h2UpstairsBedrooms)\n house2[0].addChildren(h2Upstairs)\n h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)\n house2[1].addChildren(h2Groundfloor)\n house2[2].addChildren(h2Basement)\n houses[1].addChildren(house2)\n\n cleaning.addChildren(houses)\n topCoverage := cleaning.coverage\n fmt.Printf(\"TOP COVERAGE = %8.6f\\n\\n\", topCoverage)\n fmt.Println(\"NAME HIERARCHY | WEIGHT | COVERAGE |\")\n cleaning.show(0)\n\n h2Basement[2].setCoverage(1) // change Cinema node coverage to 1\n diff := cleaning.coverage - topCoverage\n fmt.Println(\"\\nIf the coverage of the Cinema node were increased from 0.75 to 1\")\n fmt.Print(\"the top level coverage would increase by \")\n fmt.Printf(\"%8.6f to %8.6f\\n\", diff, topCoverage+diff)\n h2Basement[2].setCoverage(0.75) // restore to original value if required\n}"} {"title": "Fusc sequence", "language": "Go", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc fusc(n int) []int {\n if n <= 0 {\n return []int{}\n }\n if n == 1 {\n return []int{0}\n } \n res := make([]int, n)\n res[0] = 0\n res[1] = 1\n for i := 2; i < n; i++ {\n if i%2 == 0 {\n res[i] = res[i/2]\n } else {\n res[i] = res[(i-1)/2] + res[(i+1)/2]\n }\n }\n return res\n}\n\nfunc fuscMaxLen(n int) [][2]int {\n maxLen := -1\n maxFusc := -1\n f := fusc(n)\n var res [][2]int\n for i := 0; i < n; i++ {\n if f[i] <= maxFusc {\n continue // avoid expensive strconv operation where possible\n }\n maxFusc = f[i]\n le := len(strconv.Itoa(f[i]))\n if le > maxLen {\n res = append(res, [2]int{i, f[i]})\n maxLen = le\n }\n }\n return res\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n if n < 0 {\n s = s[1:]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfunc main() {\n fmt.Println(\"The first 61 fusc numbers are:\")\n fmt.Println(fusc(61))\n fmt.Println(\"\\nThe fusc numbers whose length > any previous fusc number length are:\")\n res := fuscMaxLen(20000000) // examine first twenty million numbers say\n for i := 0; i < len(res); i++ {\n fmt.Printf(\"%7s (index %10s)\\n\", commatize(res[i][1]), commatize(res[i][0]))\n }\n}"} {"title": "Gapful numbers", "language": "Go", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "program gapful;\n\n\n{$IFDEF FPC}\n {$MODE DELPHI}{$OPTIMIZATION ON,ALL}\n{$ELSE}\n {$APPTYPE CONSOLE}\n{$ENDIF}\n\nuses\n sysutils // IntToStr\n{$IFDEF FPC}\n ,strUtils // Numb2USA aka commatize\n{$ENDIF};\n\nconst\n cIdx = 5;\n starts: array[0..cIdx - 1] of Uint64 = (100, 1000 * 1000, 10 * 1000 * 1000,\n 1000 * 1000 * 1000, 7123);\n counts: array[0..cIdx - 1] of Uint64 = (30, 15, 15, 10, 25);\n //100| 74623687 => 1000*1000*1000\n //100| 746236131 => 10*1000*1000*1000\n //100|7462360431 =>100*1000*1000*1000\n Base = 10;\n\nvar\n ModsHL: array[0..99] of NativeUint;\n Pow10: Uint64; //global, seldom used\n countLmt: NativeUint; //Uint64; only for extreme counting\n\n{$IFNDEF FPC}\n\nfunction Numb2USA(const S: string): string;\nvar\n i, NA: Integer;\nbegin\n i := Length(S);\n Result := S;\n NA := 0;\n while (i > 0) do\n begin\n if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then\n begin\n insert(',', Result, i);\n inc(NA);\n end;\n Dec(i);\n end;\nend;\n{$ENDIF}\n\nprocedure OutHeader(i: NativeInt);\nbegin\n writeln('First ', counts[i], ', gapful numbers starting at ', Numb2USA(IntToStr\n (starts[i])));\nend;\n\nprocedure OutNum(n: Uint64);\nbegin\n write(' ', n);\nend;\n\nprocedure InitMods(n: Uint64; H_dgt: NativeUint);\n//calculate first mod of n, when it reaches n\nvar\n i, j: NativeInt;\nbegin\n j := H_dgt; //= H_dgt+i\n for i := 0 to Base - 1 do\n begin\n ModsHL[j] := n mod j;\n inc(n);\n inc(j);\n end;\nend;\n\nprocedure InitMods2(n: Uint64; H_dgt, L_Dgt: NativeUint);\n//calculate first mod of n, when it reaches n\n//beware, that the lower n are reached in the next base round\nvar\n i, j: NativeInt;\nbegin\n j := H_dgt;\n n := n - L_Dgt;\n for i := 0 to L_Dgt - 1 do\n begin\n ModsHL[j] := (n + base) mod j;\n inc(n);\n inc(j);\n end;\n for i := L_Dgt to Base - 1 do\n begin\n ModsHL[j] := n mod j;\n inc(n);\n inc(j);\n end;\nend;\n\nprocedure Main(TestNum: Uint64; Cnt: NativeUint);\nvar\n LmtNextNewHiDgt: Uint64;\n tmp, LowDgt, GapNum: NativeUint;\nbegin\n countLmt := Cnt;\n Pow10 := Base * Base;\n LmtNextNewHiDgt := Base * Pow10;\n while LmtNextNewHiDgt <= TestNum do\n begin\n Pow10 := LmtNextNewHiDgt;\n LmtNextNewHiDgt := LmtNextNewHiDgt * Base;\n end;\n LowDgt := TestNum mod Base;\n GapNum := TestNum div Pow10;\n LmtNextNewHiDgt := (GapNum + 1) * Pow10;\n GapNum := Base * GapNum;\n if LowDgt <> 0 then\n InitMods2(TestNum, GapNum, LowDgt)\n else\n InitMODS(TestNum, GapNum);\n\n GapNum := GapNum + LowDgt;\n repeat\n// if TestNum MOD (GapNum) = 0 then\n if ModsHL[GapNum] = 0 then\n begin\n tmp := countLmt - 1;\n if tmp < 32 then\n OutNum(TestNum);\n countLmt := tmp;\n // Test and BREAK only if something has changed\n if tmp = 0 then\n BREAK;\n end;\n tmp := Base + ModsHL[GapNum];\n //translate into \"if-less\" version 3.35s -> 1.85s\n //bad branch prediction :-(\n //if tmp >= GapNum then tmp -= GapNum;\n tmp := tmp - (-ORD(tmp >= GapNum) and GapNum);\n ModsHL[GapNum] := tmp;\n\n TestNum := TestNum + 1;\n tmp := LowDgt + 1;\n\n inc(GapNum);\n if tmp >= Base then\n begin\n tmp := 0;\n GapNum := GapNum - Base;\n end;\n LowDgt := tmp;\n //next Hi Digit\n if TestNum >= LmtNextNewHiDgt then\n begin\n LowDgt := 0;\n GapNum := GapNum + Base;\n LmtNextNewHiDgt := LmtNextNewHiDgt + Pow10;\n //next power of 10\n if GapNum >= Base * Base then\n begin\n Pow10 := Pow10 * Base;\n LmtNextNewHiDgt := 2 * Pow10;\n GapNum := Base;\n end;\n initMods(TestNum, GapNum);\n end;\n until false;\nend;\n\nvar\n i: integer;\n\nbegin\n for i := 0 to High(starts) do\n begin\n OutHeader(i);\n Main(starts[i], counts[i]);\n writeln(#13#10);\n end;\n {$IFNDEF LINUX} readln; {$ENDIF}\nend."} {"title": "Gauss-Jordan matrix inversion", "language": "Go from Kotlin", "task": "Invert matrix '''A''' using Gauss-Jordan method.\n\n'''A''' being an '''n''' x '''n''' matrix.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype vector = []float64\ntype matrix []vector\n\nfunc (m matrix) inverse() matrix {\n le := len(m)\n for _, v := range m {\n if len(v) != le {\n panic(\"Not a square matrix\")\n }\n }\n aug := make(matrix, le)\n for i := 0; i < le; i++ {\n aug[i] = make(vector, 2*le)\n copy(aug[i], m[i])\n // augment by identity matrix to right\n aug[i][i+le] = 1\n }\n aug.toReducedRowEchelonForm()\n inv := make(matrix, le)\n // remove identity matrix to left\n for i := 0; i < le; i++ {\n inv[i] = make(vector, le)\n copy(inv[i], aug[i][le:])\n }\n return inv\n}\n\n// note: this mutates the matrix in place\nfunc (m matrix) toReducedRowEchelonForm() {\n lead := 0\n rowCount, colCount := len(m), len(m[0])\n for r := 0; r < rowCount; r++ {\n if colCount <= lead {\n return\n }\n i := r\n\n for m[i][lead] == 0 {\n i++\n if rowCount == i {\n i = r\n lead++\n if colCount == lead {\n return\n }\n }\n }\n\n m[i], m[r] = m[r], m[i]\n if div := m[r][lead]; div != 0 {\n for j := 0; j < colCount; j++ {\n m[r][j] /= div\n }\n }\n\n for k := 0; k < rowCount; k++ {\n if k != r {\n mult := m[k][lead]\n for j := 0; j < colCount; j++ {\n m[k][j] -= m[r][j] * mult\n }\n }\n }\n lead++\n }\n}\n\nfunc (m matrix) print(title string) {\n fmt.Println(title)\n for _, v := range m {\n fmt.Printf(\"% f\\n\", v)\n }\n fmt.Println()\n}\n\nfunc main() {\n a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}\n a.inverse().print(\"Inverse of A is:\\n\")\n\n b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}\n b.inverse().print(\"Inverse of B is:\\n\")\n}"} {"title": "Gauss-Jordan matrix inversion", "language": "Go from PowerShell", "task": "Invert matrix '''A''' using Gauss-Jordan method.\n\n'''A''' being an '''n''' x '''n''' matrix.\n\n", "solution": "package main\n \nimport (\n \"fmt\"\n \"math\"\n)\n\ntype vector = []float64\ntype matrix []vector\n\nfunc (m matrix) print(title string) {\n fmt.Println(title)\n for _, v := range m {\n fmt.Printf(\"% f\\n\", v)\n }\n}\n\nfunc I(n int) matrix {\n b := make(matrix, n)\n for i := 0; i < n; i++ {\n b[i] = make(vector, n)\n b[i][i] = 1\n }\n return b\n}\n\nfunc (m matrix) inverse() matrix {\n n := len(m)\n for _, v := range m {\n if n != len(v) {\n panic(\"Not a square matrix\")\n }\n }\n b := I(n)\n a := make(matrix, n)\n for i, v := range m {\n a[i] = make(vector, n)\n copy(a[i], v)\n }\n for k := range a {\n iMax := 0\n max := -1.\n for i := k; i < n; i++ {\n row := a[i]\n // compute scale factor s = max abs in row\n s := -1.\n for j := k; j < n; j++ {\n x := math.Abs(row[j])\n if x > s {\n s = x\n }\n }\n if s == 0 {\n panic(\"Irregular matrix\")\n }\n // scale the abs used to pick the pivot.\n if abs := math.Abs(row[k]) / s; abs > max {\n iMax = i\n max = abs\n }\n }\n if k != iMax {\n a[k], a[iMax] = a[iMax], a[k]\n b[k], b[iMax] = b[iMax], b[k]\n }\n akk := a[k][k]\n for j := 0; j < n; j++ {\n a[k][j] /= akk\n b[k][j] /= akk\n }\n for i := 0; i < n; i++ {\n if (i != k) {\n aik := a[i][k]\n for j := 0; j < n; j++ {\n a[i][j] -= a[k][j] * aik\n b[i][j] -= b[k][j] * aik\n }\n }\n }\n }\n return b\n}\n \nfunc main() {\n a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}\n a.inverse().print(\"Inverse of A is:\\n\")\n\n b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}\n b.inverse().print(\"Inverse of B is:\\n\")\n}"} {"title": "Gaussian elimination", "language": "Go", "task": "Solve '''Ax=b''' using Gaussian elimination then backwards substitution. \n\n'''A''' being an '''n''' by '''n''' matrix. \n\nAlso, '''x''' and '''b''' are '''n''' by '''1''' vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* the Wikipedia entry: Gaussian elimination\n\n", "solution": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"log\"\n \"math\"\n)\n\ntype testCase struct {\n a [][]float64\n b []float64\n x []float64\n}\n\nvar tc = testCase{\n // common RC example. Result x computed with rational arithmetic then\n // converted to float64, and so should be about as close to correct as\n // float64 represention allows.\n a: [][]float64{\n {1.00, 0.00, 0.00, 0.00, 0.00, 0.00},\n {1.00, 0.63, 0.39, 0.25, 0.16, 0.10},\n {1.00, 1.26, 1.58, 1.98, 2.49, 3.13},\n {1.00, 1.88, 3.55, 6.70, 12.62, 23.80},\n {1.00, 2.51, 6.32, 15.88, 39.90, 100.28},\n {1.00, 3.14, 9.87, 31.01, 97.41, 306.02}},\n b: []float64{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02},\n x: []float64{-0.01, 1.602790394502114, -1.6132030599055613,\n 1.2454941213714368, -0.4909897195846576, 0.065760696175232},\n}\n\n// result from above test case turns out to be correct to this tolerance.\nconst \u03b5 = 1e-13\n\nfunc main() {\n x, err := GaussPartial(tc.a, tc.b)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(x)\n for i, xi := range x {\n if math.Abs(tc.x[i]-xi) > \u03b5 {\n log.Println(\"out of tolerance\")\n log.Fatal(\"expected\", tc.x)\n }\n }\n}\n\nfunc GaussPartial(a0 [][]float64, b0 []float64) ([]float64, error) {\n // make augmented matrix\n m := len(b0)\n a := make([][]float64, m)\n for i, ai := range a0 {\n row := make([]float64, m+1)\n copy(row, ai)\n row[m] = b0[i]\n a[i] = row\n }\n // WP algorithm from Gaussian elimination page\n // produces row-eschelon form\n for k := range a {\n // Find pivot for column k:\n iMax := k\n max := math.Abs(a[k][k])\n for i := k + 1; i < m; i++ {\n if abs := math.Abs(a[i][k]); abs > max {\n iMax = i\n max = abs\n }\n }\n if a[iMax][k] == 0 {\n return nil, errors.New(\"singular\")\n }\n // swap rows(k, i_max)\n a[k], a[iMax] = a[iMax], a[k]\n // Do for all rows below pivot:\n for i := k + 1; i < m; i++ {\n // Do for all remaining elements in current row:\n for j := k + 1; j <= m; j++ {\n a[i][j] -= a[k][j] * (a[i][k] / a[k][k])\n }\n // Fill lower triangular matrix with zeros:\n a[i][k] = 0\n }\n }\n // end of WP algorithm.\n // now back substitute to get result.\n x := make([]float64, m)\n for i := m - 1; i >= 0; i-- {\n x[i] = a[i][m]\n for j := i + 1; j < m; j++ {\n x[i] -= a[i][j] * x[j]\n }\n x[i] /= a[i][i]\n }\n return x, nil\n}"} {"title": "Generate Chess960 starting position", "language": "Go from Ruby", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n)\n\ntype symbols struct{ k, q, r, b, n rune }\n\nvar A = symbols{'K', 'Q', 'R', 'B', 'N'}\nvar W = symbols{'\u2654', '\u2655', '\u2656', '\u2657', '\u2658'}\nvar B = symbols{'\u265a', '\u265b', '\u265c', '\u265d', '\u265e'}\n\nvar krn = []string{\n \"nnrkr\", \"nrnkr\", \"nrknr\", \"nrkrn\",\n \"rnnkr\", \"rnknr\", \"rnkrn\",\n \"rknnr\", \"rknrn\",\n \"rkrnn\"}\n\nfunc (sym symbols) chess960(id int) string {\n var pos [8]rune\n q, r := id/4, id%4\n pos[r*2+1] = sym.b\n q, r = q/4, q%4\n pos[r*2] = sym.b\n q, r = q/6, q%6\n for i := 0; ; i++ {\n if pos[i] != 0 {\n continue\n }\n if r == 0 {\n pos[i] = sym.q\n break\n }\n r--\n }\n i := 0\n for _, f := range krn[q] {\n for pos[i] != 0 {\n i++\n }\n switch f {\n case 'k':\n pos[i] = sym.k\n case 'r':\n pos[i] = sym.r\n case 'n':\n pos[i] = sym.n\n }\n }\n return string(pos[:])\n}\n\nfunc main() {\n fmt.Println(\" ID Start position\")\n for _, id := range []int{0, 518, 959} {\n fmt.Printf(\"%3d %s\\n\", id, A.chess960(id))\n }\n fmt.Println(\"\\nRandom\")\n for i := 0; i < 5; i++ {\n fmt.Println(W.chess960(rand.Intn(960)))\n }\n}"} {"title": "Generate random chess position", "language": "Go from Java", "task": "Generate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced, but it must comply to the following rules:\n:* there is one and only one king of each color (one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\nvar grid [8][8]byte\n\nfunc abs(i int) int {\n if i >= 0 {\n return i\n } else {\n return -i\n }\n}\n\nfunc createFen() string {\n placeKings()\n placePieces(\"PPPPPPPP\", true)\n placePieces(\"pppppppp\", true)\n placePieces(\"RNBQBNR\", false)\n placePieces(\"rnbqbnr\", false)\n return toFen()\n}\n\nfunc placeKings() {\n for {\n r1 := rand.Intn(8)\n c1 := rand.Intn(8)\n r2 := rand.Intn(8)\n c2 := rand.Intn(8)\n if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {\n grid[r1][c1] = 'K'\n grid[r2][c2] = 'k'\n return\n }\n }\n}\n\nfunc placePieces(pieces string, isPawn bool) {\n numToPlace := rand.Intn(len(pieces))\n for n := 0; n < numToPlace; n++ {\n var r, c int\n for {\n r = rand.Intn(8)\n c = rand.Intn(8)\n if grid[r][c] == '\\000' && !(isPawn && (r == 7 || r == 0)) {\n break\n }\n }\n grid[r][c] = pieces[n]\n }\n}\n\nfunc toFen() string {\n var fen strings.Builder\n countEmpty := 0\n for r := 0; r < 8; r++ {\n for c := 0; c < 8; c++ {\n ch := grid[r][c]\n if ch == '\\000' {\n ch = '.'\n }\n fmt.Printf(\"%2c \", ch)\n if ch == '.' {\n countEmpty++\n } else {\n if countEmpty > 0 {\n fen.WriteString(strconv.Itoa(countEmpty))\n countEmpty = 0\n }\n fen.WriteByte(ch)\n }\n }\n if countEmpty > 0 {\n fen.WriteString(strconv.Itoa(countEmpty))\n countEmpty = 0\n }\n fen.WriteString(\"/\")\n fmt.Println()\n }\n fen.WriteString(\" w - - 0 1\")\n return fen.String()\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n fmt.Println(createFen())\n}"} {"title": "Generator/Exponential", "language": "Go", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\n// note: exponent not limited to ints\nfunc newPowGen(e float64) func() float64 {\n var i float64\n return func() (r float64) {\n r = math.Pow(i, e)\n i++\n return\n }\n}\n\n// given two functions af, bf, both monotonically increasing, return a\n// new function that returns values of af not returned by bf.\nfunc newMonoIncA_NotMonoIncB_Gen(af, bf func() float64) func() float64 {\n a, b := af(), bf()\n return func() (r float64) {\n for {\n if a < b {\n r = a\n a = af()\n break\n }\n if b == a {\n a = af()\n }\n b = bf()\n }\n return\n }\n}\n\nfunc main() {\n fGen := newMonoIncA_NotMonoIncB_Gen(newPowGen(2), newPowGen(3))\n for i := 0; i < 20; i++ {\n fGen()\n }\n for i := 0; i < 10; i++ {\n fmt.Print(fGen(), \" \")\n }\n fmt.Println()\n}"} {"title": "Get system command output", "language": "Go", "task": "Task\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). \n\n;Related task\n* Execute a system command\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os/exec\"\n)\n\nfunc main() {\n output, err := exec.Command(\"ls\", \"-l\").CombinedOutput()\n if err != nil {\n log.Fatal(err)\n }\n fmt.Print(string(output))\n}"} {"title": "Giuga numbers", "language": "Go from Wren", "task": "Definition\nA '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors\n'''f''' divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples. \n\n;Example\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\n;Task\nDetermine and show here the first four Giuga numbers.\n\n;Stretch\nDetermine the fifth Giuga number and any more you have the patience for.\n\n;References\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar factors []int\nvar inc = []int{4, 2, 4, 2, 4, 6, 2, 6}\n\n// Assumes n is even with exactly one factor of 2.\n// Empties 'factors' if any other prime factor is repeated.\nfunc primeFactors(n int) {\n factors = factors[:0]\n factors = append(factors, 2)\n last := 2\n n /= 2\n for n%3 == 0 {\n if last == 3 {\n factors = factors[:0]\n return\n }\n last = 3\n factors = append(factors, 3)\n n /= 3\n }\n for n%5 == 0 {\n if last == 5 {\n factors = factors[:0]\n return\n }\n last = 5\n factors = append(factors, 5)\n n /= 5\n }\n for k, i := 7, 0; k*k <= n; {\n if n%k == 0 {\n if last == k {\n factors = factors[:0]\n return\n }\n last = k\n factors = append(factors, k)\n n /= k\n } else {\n k += inc[i]\n i = (i + 1) % 8\n }\n }\n if n > 1 {\n factors = append(factors, n)\n }\n}\n\nfunc main() {\n const limit = 5\n var giuga []int\n // n can't be 2 or divisible by 4\n for n := 6; len(giuga) < limit; n += 4 {\n primeFactors(n)\n // can't be prime or semi-prime\n if len(factors) > 2 {\n isGiuga := true\n for _, f := range factors {\n if (n/f-1)%f != 0 {\n isGiuga = false\n break\n }\n }\n if isGiuga {\n giuga = append(giuga, n)\n }\n }\n }\n fmt.Println(\"The first\", limit, \"Giuga numbers are:\")\n fmt.Println(giuga)\n}"} {"title": "Globally replace text in several files", "language": "Go", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"io/ioutil\"\n \"log\"\n \"os\"\n)\n\nfunc main() {\n gRepNFiles(\"Goodbye London!\", \"Hello New York!\", []string{\n \"a.txt\",\n \"b.txt\",\n \"c.txt\",\n })\n}\n\nfunc gRepNFiles(olds, news string, files []string) {\n oldb := []byte(olds)\n newb := []byte(news)\n for _, fn := range files {\n if err := gRepFile(oldb, newb, fn); err != nil {\n log.Println(err)\n }\n }\n}\n\nfunc gRepFile(oldb, newb []byte, fn string) (err error) {\n var f *os.File\n if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {\n return\n }\n defer func() {\n if cErr := f.Close(); err == nil {\n err = cErr\n }\n }()\n var b []byte\n if b, err = ioutil.ReadAll(f); err != nil {\n return\n }\n if bytes.Index(b, oldb) < 0 {\n return\n }\n r := bytes.Replace(b, oldb, newb, -1)\n if err = f.Truncate(0); err != nil {\n return\n }\n _, err = f.WriteAt(r, 0)\n return\n}"} {"title": "Graph colouring", "language": "Go", "task": "A Graph is a collection of nodes\n(or vertices), connected by edges (or not).\nNodes directly connected by edges are called neighbours.\n\nIn our representation of graphs, nodes are numbered and edges are represented\nby the two node numbers connected by the edge separated by a dash.\nEdges define the nodes being connected. Only unconnected nodes ''need'' a separate\ndescription.\n\nFor example,\n0-1 1-2 2-0 3\nDescribes the following graph. Note that node 3 has no neighbours\n\n\n;Example graph:\n\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n\nA useful internal datastructure for a graph and for later graph algorithms is\nas a mapping between each node and the set/list of its neighbours.\n\nIn the above example:\n0 maps-to 1 and 2\n1 maps to 2 and 0\n2 maps-to 1 and 0\n3 maps-to \n\n;Graph colouring task:\nColour the vertices of a given graph so that no edge is between verticies of\nthe same colour.\n\n* Integers may be used to denote different colours.\n* Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is '''not''' a requirement).\n* Show for each edge, the colours assigned on each vertex.\n* Show the total number of nodes, edges, and colours used for each graph.\n\n;Use the following graphs:\n;Ex1:\n\n 0-1 1-2 2-0 3\n\n\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n;Ex2:\nThe wp articles left-side graph\n\n 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\n\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 3 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 6 | --- | 4 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 7 | --- | 2 | --- | 5 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n;Ex3:\nThe wp articles right-side graph which is the same graph as Ex2, but with\ndifferent node orderings and namings.\n\n 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\n\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 5 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 4 | --- | 7 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 6 | --- | 3 | --- | 2 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n;Ex4:\nThis is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.\nThis might alter the node order used in the greedy algorithm leading to differing numbers of colours.\n\n 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\n\n\n\n +-------------------------------------------------+\n | |\n | |\n +-------------------+---------+ |\n | | | |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n | | | | | |\n +---------+-----------------------------+---------+ | |\n | | | |\n | | | |\n +-----------------------------+-------------------+ |\n | |\n | |\n +-----------------------------+\n\n\n;References:\n* Greedy coloring Wikipedia.\n* Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\ntype graph struct {\n nn int // number of nodes\n st int // node numbering starts from\n nbr [][]int // neighbor list for each node\n}\n\ntype nodeval struct {\n n int // number of node\n v int // valence of node i.e. number of neighbors\n}\n\nfunc contains(s []int, n int) bool {\n for _, e := range s {\n if e == n {\n return true\n }\n }\n return false\n}\n\nfunc newGraph(nn, st int) graph {\n nbr := make([][]int, nn)\n return graph{nn, st, nbr}\n}\n\n// Note that this creates a single 'virtual' edge for an isolated node.\nfunc (g graph) addEdge(n1, n2 int) {\n n1, n2 = n1-g.st, n2-g.st // adjust to starting node number\n g.nbr[n1] = append(g.nbr[n1], n2)\n if n1 != n2 {\n g.nbr[n2] = append(g.nbr[n2], n1)\n }\n}\n\n// Uses 'greedy' algorithm.\nfunc (g graph) greedyColoring() []int {\n // create a slice with a color for each node, starting with color 0\n cols := make([]int, g.nn) // all zero by default including the first node\n for i := 1; i < g.nn; i++ {\n cols[i] = -1 // mark all nodes after the first as having no color assigned (-1)\n }\n // create a bool slice to keep track of which colors are available\n available := make([]bool, g.nn) // all false by default\n // assign colors to all nodes after the first\n for i := 1; i < g.nn; i++ {\n // iterate through neighbors and mark their colors as available\n for _, j := range g.nbr[i] {\n if cols[j] != -1 {\n available[cols[j]] = true\n }\n }\n // find the first available color\n c := 0\n for ; c < g.nn; c++ {\n if !available[c] {\n break\n }\n }\n cols[i] = c // assign it to the current node\n // reset the neighbors' colors to unavailable\n // before the next iteration\n for _, j := range g.nbr[i] {\n if cols[j] != -1 {\n available[cols[j]] = false\n }\n }\n }\n return cols\n}\n\n// Uses Welsh-Powell algorithm.\nfunc (g graph) wpColoring() []int {\n // create nodeval for each node\n nvs := make([]nodeval, g.nn)\n for i := 0; i < g.nn; i++ {\n v := len(g.nbr[i])\n if v == 1 && g.nbr[i][0] == i { // isolated node\n v = 0\n }\n nvs[i] = nodeval{i, v}\n }\n // sort the nodevals in descending order by valence\n sort.Slice(nvs, func(i, j int) bool {\n return nvs[i].v > nvs[j].v\n })\n // create colors slice with entries for each node\n cols := make([]int, g.nn)\n for i := range cols {\n cols[i] = -1 // set all nodes to no color (-1) initially\n }\n currCol := 0 // start with color 0\n for f := 0; f < g.nn-1; f++ {\n h := nvs[f].n\n if cols[h] != -1 { // already assigned a color\n continue\n }\n cols[h] = currCol\n // assign same color to all subsequent uncolored nodes which are\n // not connected to a previous colored one\n outer:\n for i := f + 1; i < g.nn; i++ {\n j := nvs[i].n\n if cols[j] != -1 { // already colored\n continue\n }\n for k := f; k < i; k++ {\n l := nvs[k].n\n if cols[l] == -1 { // not yet colored\n continue\n }\n if contains(g.nbr[j], l) {\n continue outer // node j is connected to an earlier colored node\n }\n }\n cols[j] = currCol\n }\n currCol++\n }\n return cols\n}\n\nfunc main() {\n fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring}\n titles := []string{\"'Greedy'\", \"Welsh-Powell\"}\n nns := []int{4, 8, 8, 8}\n starts := []int{0, 1, 1, 1}\n edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}}\n edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8},\n {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8},\n {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}}\n edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8},\n {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}}\n for j, fn := range fns {\n fmt.Println(\"Using the\", titles[j], \"algorithm:\\n\")\n for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} {\n fmt.Println(\" Example\", i+1)\n g := newGraph(nns[i], starts[i])\n for _, e := range edges {\n g.addEdge(e[0], e[1])\n }\n cols := fn(g)\n ecount := 0 // counts edges\n for _, e := range edges {\n if e[0] != e[1] {\n fmt.Printf(\" Edge %d-%d -> Color %d, %d\\n\", e[0], e[1],\n cols[e[0]-g.st], cols[e[1]-g.st])\n ecount++\n } else {\n fmt.Printf(\" Node %d -> Color %d\\n\", e[0], cols[e[0]-g.st])\n }\n }\n maxCol := 0 // maximum color number used\n for _, col := range cols {\n if col > maxCol {\n maxCol = col\n }\n }\n fmt.Println(\" Number of nodes :\", nns[i])\n fmt.Println(\" Number of edges :\", ecount)\n fmt.Println(\" Number of colors :\", maxCol+1)\n fmt.Println()\n }\n }\n}"} {"title": "Gray code", "language": "Go from Euphoria", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc enc(b int) int {\n return b ^ b>>1\n}\n\nfunc dec(g int) (b int) {\n for ; g != 0; g >>= 1 {\n b ^= g\n }\n return\n}\n\nfunc main() {\n fmt.Println(\"decimal binary gray decoded\")\n for b := 0; b < 32; b++ {\n g := enc(b)\n d := dec(g)\n fmt.Printf(\" %2d %05b %05b %05b %2d\\n\", b, b, g, d, d)\n }\n}"} {"title": "Greatest subsequential sum", "language": "Go", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc gss(s []int) ([]int, int) {\n var best, start, end, sum, sumStart int\n for i, x := range s {\n sum += x\n switch {\n case sum > best:\n best = sum\n start = sumStart\n end = i + 1\n case sum < 0:\n sum = 0\n sumStart = i + 1\n }\n }\n return s[start:end], best\n}\n\nvar testCases = [][]int{\n {-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1},\n {-1, 1, 2, -5, -6},\n {},\n {-1, -2, -1},\n}\n\nfunc main() {\n for _, c := range testCases {\n fmt.Println(\"Input: \", c)\n subSeq, sum := gss(c)\n fmt.Println(\"Sub seq:\", subSeq)\n fmt.Println(\"Sum: \", sum, \"\\n\")\n }\n}"} {"title": "Greedy algorithm for Egyptian fractions", "language": "Go from Kotlin", "task": "An Egyptian fraction is the sum of distinct unit fractions such as: \n\n:::: \\tfrac{1}{2} + \\tfrac{1}{3} + \\tfrac{1}{16} \\,(= \\tfrac{43}{48}) \n\nEach fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). \n\nFibonacci's Greedy algorithm for Egyptian fractions expands the fraction \\tfrac{x}{y} to be represented by repeatedly performing the replacement\n\n:::: \\frac{x}{y} = \\frac{1}{\\lceil y/x\\rceil} + \\frac{(-y)\\!\\!\\!\\!\\mod x}{y\\lceil y/x\\rceil} \n\n\n(simplifying the 2nd term in this replacement as necessary, and where \\lceil x \\rceil is the ''ceiling'' function).\n\n\n\nFor this task, Proper and improper fractions must be able to be expressed.\n\n\nProper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that a < b, and \n\nimproper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. \n\n\n(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)\n\nFor improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].\n\n\n;Task requirements:\n* show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* for all proper fractions, \\tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* the largest number of terms,\n::* the largest denominator.\n* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}\n\n\n;Also see:\n* Wolfram MathWorld(tm) entry: Egyptian fraction\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"strings\"\n)\n\nvar zero = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat {\n if br.Num().Cmp(zero) == 0 {\n return fracs\n }\n iquo := new(big.Int)\n irem := new(big.Int)\n iquo.QuoRem(br.Denom(), br.Num(), irem)\n if irem.Cmp(zero) > 0 {\n iquo.Add(iquo, one)\n }\n rquo := new(big.Rat).SetFrac(one, iquo)\n fracs = append(fracs, rquo)\n num2 := new(big.Int).Neg(br.Denom())\n num2.Rem(num2, br.Num())\n if num2.Cmp(zero) < 0 {\n num2.Add(num2, br.Num())\n }\n denom2 := new(big.Int)\n denom2.Mul(br.Denom(), iquo)\n f := new(big.Rat).SetFrac(num2, denom2)\n if f.Num().Cmp(one) == 0 {\n fracs = append(fracs, f)\n return fracs\n }\n fracs = toEgyptianRecursive(f, fracs)\n return fracs\n}\n\nfunc toEgyptian(rat *big.Rat) []*big.Rat {\n if rat.Num().Cmp(zero) == 0 {\n return []*big.Rat{rat}\n }\n var fracs []*big.Rat\n if rat.Num().CmpAbs(rat.Denom()) >= 0 {\n iquo := new(big.Int)\n iquo.Quo(rat.Num(), rat.Denom())\n rquo := new(big.Rat).SetFrac(iquo, one)\n rrem := new(big.Rat)\n rrem.Sub(rat, rquo)\n fracs = append(fracs, rquo)\n fracs = toEgyptianRecursive(rrem, fracs)\n } else {\n fracs = toEgyptianRecursive(rat, fracs)\n }\n return fracs\n}\n\nfunc main() {\n fracs := []*big.Rat{big.NewRat(43, 48), big.NewRat(5, 121), big.NewRat(2014, 59)}\n for _, frac := range fracs {\n list := toEgyptian(frac)\n if list[0].Denom().Cmp(one) == 0 {\n first := fmt.Sprintf(\"[%v]\", list[0].Num())\n temp := make([]string, len(list)-1)\n for i := 1; i < len(list); i++ {\n temp[i-1] = list[i].String()\n }\n rest := strings.Join(temp, \" + \")\n fmt.Printf(\"%v -> %v + %s\\n\", frac, first, rest)\n } else {\n temp := make([]string, len(list))\n for i := 0; i < len(list); i++ {\n temp[i] = list[i].String()\n }\n all := strings.Join(temp, \" + \")\n fmt.Printf(\"%v -> %s\\n\", frac, all)\n }\n }\n\n for _, r := range [2]int{98, 998} {\n if r == 98 {\n fmt.Println(\"\\nFor proper fractions with 1 or 2 digits:\")\n } else {\n fmt.Println(\"\\nFor proper fractions with 1, 2 or 3 digits:\")\n }\n maxSize := 0\n var maxSizeFracs []*big.Rat\n maxDen := zero\n var maxDenFracs []*big.Rat\n var sieve = make([][]bool, r+1) // to eliminate duplicates\n for i := 0; i <= r; i++ {\n sieve[i] = make([]bool, r+2)\n }\n for i := 1; i <= r; i++ {\n for j := i + 1; j <= r+1; j++ {\n if sieve[i][j] {\n continue\n }\n f := big.NewRat(int64(i), int64(j))\n list := toEgyptian(f)\n listSize := len(list)\n if listSize > maxSize {\n maxSize = listSize\n maxSizeFracs = maxSizeFracs[0:0]\n maxSizeFracs = append(maxSizeFracs, f)\n } else if listSize == maxSize {\n maxSizeFracs = append(maxSizeFracs, f)\n }\n listDen := list[len(list)-1].Denom()\n if listDen.Cmp(maxDen) > 0 {\n maxDen = listDen\n maxDenFracs = maxDenFracs[0:0]\n maxDenFracs = append(maxDenFracs, f)\n } else if listDen.Cmp(maxDen) == 0 {\n maxDenFracs = append(maxDenFracs, f)\n }\n if i < r/2 {\n k := 2\n for {\n if j*k > r+1 {\n break\n }\n sieve[i*k][j*k] = true\n k++\n }\n }\n }\n }\n fmt.Println(\" largest number of items =\", maxSize)\n fmt.Println(\" fraction(s) with this number :\", maxSizeFracs)\n md := maxDen.String()\n fmt.Print(\" largest denominator = \", len(md), \" digits, \")\n fmt.Print(md[0:20], \"...\", md[len(md)-20:], \"\\b\\n\")\n fmt.Println(\" fraction(s) with this denominator :\", maxDenFracs)\n }\n}"} {"title": "Greyscale bars/Display", "language": "Go from Java", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "package main\n\nimport (\n \"github.com/fogleman/gg\"\n \"math\"\n)\n\nfunc greyBars(dc *gg.Context) {\n run := 0\n colorComp := 0.0 // component of the color\n for colCount := 8; colCount < 128; colCount *= 2 {\n // by this gap we change the background color\n colorGap := 255.0 / float64(colCount-1)\n colWidth := float64(dc.Width() / colCount)\n colHeight := float64(dc.Height() / 4)\n // switches color directions with each iteration of for loop\n if run%2 == 0 {\n colorComp = 0.0\n } else {\n colorComp = 255.0\n colorGap = -colorGap\n }\n xstart, ystart := 0.0, colHeight*float64(run)\n for i := 0; i < colCount; i++ {\n icolor := int(math.Round(colorComp)) // round to nearer integer\n dc.SetRGB255(icolor, icolor, icolor)\n dc.DrawRectangle(xstart, ystart, colWidth, colHeight)\n dc.Fill()\n xstart += colWidth\n colorComp += colorGap\n }\n run++\n }\n}\n\nfunc main() {\n dc := gg.NewContext(640, 320)\n greyBars(dc)\n dc.SavePNG(\"greybars.png\")\n}"} {"title": "Hailstone sequence", "language": "Go", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// 1st arg is the number to generate the sequence for.\n// 2nd arg is a slice to recycle, to reduce garbage.\nfunc hs(n int, recycle []int) []int {\n s := append(recycle[:0], n)\n for n > 1 {\n if n&1 == 0 {\n n = n / 2\n } else {\n n = 3*n + 1\n }\n s = append(s, n)\n }\n return s\n}\n\nfunc main() {\n seq := hs(27, nil)\n fmt.Printf(\"hs(27): %d elements: [%d %d %d %d ... %d %d %d %d]\\n\",\n len(seq), seq[0], seq[1], seq[2], seq[3],\n seq[len(seq)-4], seq[len(seq)-3], seq[len(seq)-2], seq[len(seq)-1])\n\n var maxN, maxLen int\n for n := 1; n < 100000; n++ {\n seq = hs(n, seq)\n if len(seq) > maxLen {\n maxN = n\n maxLen = len(seq)\n }\n }\n fmt.Printf(\"hs(%d): %d elements\\n\", maxN, maxLen)\n}"} {"title": "Halt and catch fire", "language": "Go", "task": "Task\n\nCreate a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok?\n\nThe code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an internal corruption has been detected and it would be dangerous and irresponsible to continue.\n\n;References\n* Wikipedia: Halt and Catch Fire\n\n\n;Related Tasks\n* [[Program termination]]\n\n", "solution": "package main; import \"fmt\"; func main(){a, b := 0, 0; fmt.Println(a/b)}"} {"title": "Harmonic series", "language": "Go from Wren", "task": "{{Wikipedia|Harmonic number}}\n\n\nIn mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: \n\n\n'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''\n\nThe series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. \n\nHarmonic numbers are closely related to the Euler-Mascheroni constant.\n\nThe harmonic series is divergent, albeit quite slowly, and grows toward infinity.\n\n\n;Task\n* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.\n* Use that procedure to show the values of the first 20 harmonic numbers.\n* Find and show the position in the series of the first value greater than the integers 1 through 5\n\n\n;Stretch\n* Find and show the position in the series of the first value greater than the integers 6 through 10\n\n\n;Related\n* [[Egyptian fractions]]\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc harmonic(n int) *big.Rat {\n sum := new(big.Rat)\n for i := int64(1); i <= int64(n); i++ {\n r := big.NewRat(1, i)\n sum.Add(sum, r)\n }\n return sum\n}\n\nfunc main() {\n fmt.Println(\"The first 20 harmonic numbers and the 100th, expressed in rational form, are:\")\n numbers := make([]int, 21)\n for i := 1; i <= 20; i++ {\n numbers[i-1] = i\n }\n numbers[20] = 100\n for _, i := range numbers {\n fmt.Printf(\"%3d : %s\\n\", i, harmonic(i))\n }\n\n fmt.Println(\"\\nThe first harmonic number to exceed the following integers is:\")\n const limit = 10\n for i, n, h := 1, 1, 0.0; i <= limit; n++ {\n h += 1.0 / float64(n)\n if h > float64(i) {\n fmt.Printf(\"integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\\n\", i, n, h)\n i++\n }\n }\n}"} {"title": "Harshad or Niven series", "language": "Go", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype is func() int\n\nfunc newSum() is {\n var ms is\n ms = func() int {\n ms = newSum()\n return ms()\n }\n var msd, d int\n return func() int {\n if d < 9 {\n d++\n } else {\n d = 0\n msd = ms()\n }\n return msd + d\n }\n}\n\nfunc newHarshard() is {\n i := 0\n sum := newSum()\n return func() int {\n for i++; i%sum() != 0; i++ {\n }\n return i\n }\n}\n\nfunc main() {\n h := newHarshard()\n fmt.Print(h())\n for i := 1; i < 20; i++ {\n fmt.Print(\" \", h())\n }\n fmt.Println()\n h = newHarshard()\n n := h()\n for ; n <= 1000; n = h() {\n }\n fmt.Println(n)\n}"} {"title": "Hash join", "language": "Go", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n tableA := []struct {\n value int\n key string\n }{\n {27, \"Jonah\"}, {18, \"Alan\"}, {28, \"Glory\"}, {18, \"Popeye\"},\n {28, \"Alan\"},\n }\n tableB := []struct {\n key string\n value string\n }{\n {\"Jonah\", \"Whales\"}, {\"Jonah\", \"Spiders\"},\n {\"Alan\", \"Ghosts\"}, {\"Alan\", \"Zombies\"}, {\"Glory\", \"Buffy\"},\n }\n // hash phase\n h := map[string][]int{}\n for i, r := range tableA {\n h[r.key] = append(h[r.key], i)\n }\n // join phase\n for _, x := range tableB {\n for _, a := range h[x.key] {\n fmt.Println(tableA[a], x)\n }\n }\n}"} {"title": "Haversine formula", "language": "Go", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc haversine(\u03b8 float64) float64 {\n return .5 * (1 - math.Cos(\u03b8))\n}\n\ntype pos struct {\n \u03c6 float64 // latitude, radians\n \u03c8 float64 // longitude, radians\n}\n\nfunc degPos(lat, lon float64) pos {\n return pos{lat * math.Pi / 180, lon * math.Pi / 180}\n}\n\nconst rEarth = 6372.8 // km\n\nfunc hsDist(p1, p2 pos) float64 {\n return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.\u03c6-p1.\u03c6)+\n math.Cos(p1.\u03c6)*math.Cos(p2.\u03c6)*haversine(p2.\u03c8-p1.\u03c8)))\n}\n\nfunc main() {\n fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40)))\n}"} {"title": "Hello world/Line printer", "language": "Go", "task": "Cause a line printer attached to the computer to print a line containing the message: Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA line printer was an older-style printer which prints one line at a time to a continuous ream of paper. \n\nWith some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tlp0, err := os.Create(\"/dev/lp0\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer lp0.Close()\n\n\tfmt.Fprintln(lp0, \"Hello World!\")\n}"} {"title": "Hello world/Newbie", "language": "Go", "task": "Guide a new user of a language through the steps necessary \nto install the programming language and selection of a text editor if needed, \nto run the languages' example in the [[Hello world/Text]] task.\n* Assume the language-newbie is a programmer in another language.\n* Assume the language-newbie is competent in installing software for the platform.\n* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).\n* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).\n* Remember to state where to view the output.\n* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.\n\n\n;Note:\n* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.\n* You may use sub-headings if giving instructions for multiple platforms.\n\n", "solution": "Currently supported platforms are FreeBSD, Linux, Mac OS X, and Windows. \nFrom the landing page http://golang.org click the blue box \"Download Go\" \n(under the big gopher drawing.) \nThis takes you to [http://golang.org/doc/install Getting Started], \na fairly concise page that is very close to satisfying this task.\n\nThe first section, Download, has a link to a downloads page \nbut also mentions two other options, building from source and using GCC. \nI personally like building from source and have found it usually goes without a hitch. GCC isn't just C anymore and includes a number of language front ends. \nGo is one of them. \nThere are links there to separate pages of instructions for building \nfrom source and using GCC.\n\nContinuing with instructions for the precompiled binaries though, there is a section \"System Requirements\" and then a section \"Install the Go tools\", which means tools including the Go compiler. You need to follow some steps here. \nFollow the instructions for your operating system. (The steps are few, standard, \nand easy.) Pay attention to the paragraph \"Installing to a custom location\" \nif you are installing on a system where you do not have root or sudo access. \nSetting GOROOT as described is essential in this case. \nIf you are installing to the standard location, you should not set \nthis environment variable. \n(Setting it when it doesn't need to be set can lead to problems. Just don't.)\n\nYou're ready to test the installation with Hello World! \nThe RC Task mentions [[Editor|texteditor]]s. \nYou will want an editor that can edit Unicode UTF-8. \nGo source is specified to be UTF-8 and before long you will want an editor \nthat does this. \nThis task is all ASCII however, and any editor that can save plain ASCII text \nwill do for the moment. \nActually you probably don't even need an editor. \nFrom a Linux command line for example, you can type\n\n$ cat >hello.go\n\nCut and paste the code from [[Hello_world/Text#Go]], press ^D, \nand you should have the program. To run it type\n\n$ go run hello.go\n\nThis compiles to a temporary executable file and runs it, \ndisplaying output right there in the same window. \nIf you want a copy to give to your friends,\n\n$ go build hello.go\n\nwill create an executable called hello in the current directory.\n\nThis completes the RC task, but if at any point in the future \nyou will use Go for more than Hello World, you really really \nshould continue through the next section \"Set up your work environment.\" \nThis covers setting GOPATH, which is essential to standard workflow with Go.\n\n"} {"title": "Heronian triangles", "language": "Go", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"sort\"\n)\n\nconst (\n n = 200\n header = \"\\nSides P A\"\n)\n\nfunc gcd(a, b int) int {\n leftover := 1\n var dividend, divisor int\n if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a }\n\n for (leftover != 0) {\n leftover = dividend % divisor\n if (leftover > 0) {\n dividend, divisor = divisor, leftover\n }\n }\n return divisor\n}\n\nfunc is_heron(h float64) bool {\n return h > 0 && math.Mod(h, 1) == 0.0\n}\n\n// by_area_perimeter implements sort.Interface for [][]int based on the area first and perimeter value\ntype by_area_perimeter [][]int\n\nfunc (a by_area_perimeter) Len() int { return len(a) }\nfunc (a by_area_perimeter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a by_area_perimeter) Less(i, j int) bool {\n return a[i][4] < a[j][4] || a[i][4] == a[j][4] && a[i][3] < a[j][3]\n}\n\nfunc main() {\n var l [][]int\n for c := 1; c <= n; c++ {\n for b := 1; b <= c; b++ {\n for a := 1; a <= b; a++ {\n if (gcd(gcd(a, b), c) == 1) {\n p := a + b + c\n s := float64(p) / 2.0\n area := math.Sqrt(s * (s - float64(a)) * (s - float64(b)) * (s - float64(c)))\n if (is_heron(area)) {\n l = append(l, []int{a, b, c, p, int(area)})\n }\n }\n }\n }\n }\n\n fmt.Printf(\"Number of primitive Heronian triangles with sides up to %d: %d\", n, len(l))\n sort.Sort(by_area_perimeter(l))\n fmt.Printf(\"\\n\\nFirst ten when ordered by increasing area, then perimeter:\" + header)\n for i := 0; i < 10; i++ { fmt.Printf(\"\\n%3d\", l[i]) }\n\n a := 210\n fmt.Printf(\"\\n\\nArea = %d%s\", a, header)\n for _, it := range l {\n if (it[4] == a) {\n fmt.Printf(\"\\n%3d\", it)\n }\n }\n}"} {"title": "Hickerson series of almost integers", "language": "Go", "task": "The following function, due to D. Hickerson, is said to generate \"Almost integers\" by the \n\"Almost Integer\" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.)\n\n\nThe function is: h(n) = {\\operatorname{n}!\\over2(\\ln{2})^{n+1}}\n\n\nIt is said to produce \"almost integers\" for '''n''' between '''1''' and '''17'''. \nThe purpose of the task is to verify this assertion.\n\nAssume that an \"almost integer\" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation\n\n\n;Task:\nCalculate all values of the function checking and stating which are \"almost integers\".\n\nNote: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:\n h(18) = 3385534663256845326.39...\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n ln2, _ := new(big.Rat).SetString(\"0.6931471805599453094172\")\n h := big.NewRat(1, 2)\n h.Quo(h, ln2)\n var f big.Rat\n var w big.Int\n for i := int64(1); i <= 17; i++ {\n h.Quo(h.Mul(h, f.SetInt64(i)), ln2)\n w.Quo(h.Num(), h.Denom())\n f.Sub(h, f.SetInt(&w))\n y, _ := f.Float64()\n d := fmt.Sprintf(\"%.3f\", y)\n fmt.Printf(\"n: %2d h: %18d%s Nearly integer: %t\\n\",\n i, &w, d[1:], d[2] == '0' || d[2] == '9')\n }\n}"} {"title": "History variables", "language": "Go", "task": "''Storing the history of objects in a program is a common task. \nMaintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''\n\n''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.\n'' \n\n\"History Variables: \nThe Semantics, Formal Correctness, and Implementation of History Variables \nin an Imperative Programming Language\" by Mallon and Takaoka\n\nConcept also discussed on LtU and Patents.com.\n\n;Task: \nDemonstrate History variable support: \n* enable history variable support (if needed) \n* define a history variable\n* assign three values\n* non-destructively display the history\n* recall the three values. \n\nFor extra points, if the language of choice does not support history variables, \ndemonstrate how this might be implemented.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"sync\"\n \"time\"\n)\n\n// data type for history variable (its an int)\ntype history struct {\n timestamp tsFunc\n hs []hset\n}\n\n// data type for timestamp generator\ntype tsFunc func() time.Time\n\n// data type for a \"set\" event\ntype hset struct {\n int // new value\n t time.Time // timestamp\n}\n\n// newHistory creates a history variable\nfunc newHistory(ts tsFunc) history {\n return history{ts, []hset{{t: ts()}}}\n} \n \n// int returns the current value\nfunc (h history) int() int {\n return h.hs[len(h.hs)-1].int\n}\n \n// set does what you expect and returns the timestamp recorded for the event\nfunc (h *history) set(x int) time.Time {\n t := h.timestamp()\n h.hs = append(h.hs, hset{x, t})\n return t\n}\n\n// dump displays a complete history\nfunc (h history) dump() {\n for _, hs := range h.hs {\n fmt.Println(hs.t.Format(time.StampNano), hs.int)\n }\n} \n \n// recall recalls the value stored in the history variable at time t.\n// if the variable had not been created yet, ok is false.\nfunc (h history) recall(t time.Time) (int, /*ok*/ bool) {\n i := sort.Search(len(h.hs), func(i int) bool {\n return h.hs[i].t.After(t)\n })\n if i > 0 {\n return h.hs[i-1].int, true\n }\n return 0, false\n}\n\n// newTimestamper returns a function that generates unique timestamps.\n// Use a single timestamper for multiple history variables to preserve\n// an unambiguous sequence of assignments across the multiple history\n// variables within a single goroutine.\nfunc newTimestamper() tsFunc {\n var last time.Time\n return func() time.Time {\n if t := time.Now(); t.After(last) {\n last = t\n } else {\n last.Add(1)\n }\n return last\n }\n}\n\n// newProtectedTimestamper generates unique timestamps for concurrent\n// goroutines.\nfunc newProtectedTimestamper() tsFunc {\n var last time.Time\n var m sync.Mutex\n return func() (t time.Time) {\n t = time.Now()\n m.Lock() // m protects last\n if t.After(last) {\n last = t\n } else {\n last.Add(1)\n t = last\n }\n m.Unlock()\n return\n }\n}\n\nfunc main() {\n // enable history variable support appropriate for single goroutine.\n ts := newTimestamper()\n // define a history variable\n h := newHistory(ts)\n // assign three values. (timestamps kept for future reference.)\n ref := []time.Time{h.set(3), h.set(1), h.set(4)}\n // non-destructively display history\n fmt.Println(\"History of variable h:\")\n h.dump() \n // recall the three values. (this is non-destructive as well, but\n // different than the dump in that values are recalled by time.)\n fmt.Println(\"Recalling values:\")\n for _, t := range ref {\n rv, _ := h.recall(t)\n fmt.Println(rv)\n }\n}"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "Go", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n)\n\nfunc main() {\n a := []int{0, 1, 1} // ignore 0 element. work 1 based.\n x := 1 // last number in list\n n := 2 // index of last number in list = len(a)-1\n mallow := 0\n for p := 1; p < 20; p++ {\n max := 0.\n for nextPot := n*2; n < nextPot; {\n n = len(a) // advance n\n x = a[x]+a[n-x]\n a = append(a, x)\n f := float64(x)/float64(n)\n if f > max {\n max = f\n }\n if f >= .55 {\n mallow = n\n }\n }\n fmt.Printf(\"max between 2^%d and 2^%d was %f\\n\", p, p+1, max)\n }\n fmt.Println(\"winning number\", mallow)\n}"} {"title": "Hofstadter Figure-Figure sequences", "language": "Go", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar ffr, ffs func(int) int\n\n// The point of the init function is to encapsulate r and s. If you are\n// not concerned about that or do not want that, r and s can be variables at\n// package level and ffr and ffs can be ordinary functions at package level.\nfunc init() {\n // task 1, 2\n r := []int{0, 1}\n s := []int{0, 2}\n\n ffr = func(n int) int {\n for len(r) <= n {\n nrk := len(r) - 1 // last n for which r(n) is known\n rNxt := r[nrk] + s[nrk] // next value of r: r(nrk+1)\n r = append(r, rNxt) // extend sequence r by one element\n for sn := r[nrk] + 2; sn < rNxt; sn++ {\n s = append(s, sn) // extend sequence s up to rNext\n }\n s = append(s, rNxt+1) // extend sequence s one past rNext\n }\n return r[n]\n }\n\n ffs = func(n int) int {\n for len(s) <= n {\n ffr(len(r))\n }\n return s[n]\n }\n}\n\nfunc main() {\n // task 3\n for n := 1; n <= 10; n++ {\n fmt.Printf(\"r(%d): %d\\n\", n, ffr(n))\n }\n // task 4\n var found [1001]int\n for n := 1; n <= 40; n++ {\n found[ffr(n)]++\n }\n for n := 1; n <= 960; n++ {\n found[ffs(n)]++\n }\n for i := 1; i <= 1000; i++ {\n if found[i] != 1 {\n fmt.Println(\"task 4: FAIL\")\n return\n }\n }\n fmt.Println(\"task 4: PASS\")\n}"} {"title": "Hofstadter Q sequence", "language": "Go", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar m map[int]int\n\nfunc initMap() {\n m = make(map[int]int)\n m[1] = 1\n m[2] = 1\n}\n\nfunc q(n int) (r int) {\n if r = m[n]; r == 0 {\n r = q(n-q(n-1)) + q(n-q(n-2))\n m[n] = r\n }\n return\n}\n\nfunc main() {\n initMap()\n // task\n for n := 1; n <= 10; n++ {\n showQ(n)\n }\n // task\n showQ(1000)\n // extra credit\n count, p := 0, 1\n for n := 2; n <= 1e5; n++ {\n qn := q(n)\n if qn < p {\n count++\n }\n p = qn\n }\n fmt.Println(\"count:\", count)\n // extra credit\n initMap()\n showQ(1e6)\n}\n\nfunc showQ(n int) {\n fmt.Printf(\"Q(%d) = %d\\n\", n, q(n))\n}"} {"title": "Horner's rule for polynomial evaluation", "language": "Go", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.\n\nCf. [[Formal power series]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc horner(x int64, c []int64) (acc int64) {\n for i := len(c) - 1; i >= 0; i-- {\n acc = acc*x + c[i]\n }\n return\n}\n\nfunc main() {\n fmt.Println(horner(3, []int64{-19, 7, -4, 6}))\n}"} {"title": "I'm a software engineer, get me out of here", "language": "Go from Phix", "task": "Your latest contract has hit a snag. You came to update the army payroll system, but awoke this morning to the sound of mortars landing not far away and panicked generals banging on you door. The President has loaded his gold on trucks and needs to find the shortest route to safety. You are given the following map. The top left hand corner is (0,0). You and The President are located at HQ in the centre of the country (11,11). Cells marked 0 indicate safety. Numbers other than 0 indicate the number of cells that his party will travel in a day in any direction up, down, left, right, or diagonally. \n\n 00000 \n 00003130000 \n 000321322221000 \n 00231222432132200 \n 0041433223233211100 \n 0232231612142618530 \n 003152122326114121200 \n 031252235216111132210 \n 022211246332311115210 \n00113232262121317213200\n03152118212313211411110\n03231234121132221411410\n03513213411311414112320\n00427534125412213211400\n 013322444412122123210 \n 015132331312411123120 \n 003333612214233913300 \n 0219126511415312570 \n 0021321524341325100 \n 00211415413523200 \n 000122111322000 \n 00001120000 \n 00000 \n\nPart 1 Use Dijkstra's algorithm to find a list of the shortest routes from HQ to safety.\n\nPart 2\nSix days later and you are called to another briefing. The good news is The President and his gold are safe, so your invoice may be paid if you can get out of here. To do this a number of troop repositions will be required. It is concluded that you need to know the shortest route from each cell to every other cell. You decide to use Floyd's algorithm. Print the shortest route from (21,11) to (1,11) and from (1,11) to (21,11), and the longest shortest route between any two points.\n\nExtra Credit\n# Is there any cell in the country that can not be reached from HQ?\n# Which cells will it take longest to send reinforcements to from HQ?\n\nRelated tasks:\n# [[Dijkstra's algorithm]]\n# [[Floyd-Warshall algorithm]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar gmooh = strings.Split(\n `.........00000.........\n......00003130000......\n....000321322221000....\n...00231222432132200...\n..0041433223233211100..\n..0232231612142618530..\n.003152122326114121200.\n.031252235216111132210.\n.022211246332311115210.\n00113232262121317213200\n03152118212313211411110\n03231234121132221411410\n03513213411311414112320\n00427534125412213211400\n.013322444412122123210.\n.015132331312411123120.\n.003333612214233913300.\n..0219126511415312570..\n..0021321524341325100..\n...00211415413523200...\n....000122111322000....\n......00001120000......\n.........00000.........`, \"\\n\")\n\nvar width, height = len(gmooh[0]), len(gmooh)\n\ntype pyx [2]int // {y, x}\n\nvar d = []pyx{{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}\n\ntype route [3]int // {cost, fromy, fromx}\n\nvar zeroRoute = route{0, 0, 0}\nvar routes [][]route // route for each gmooh[][]\n\nfunc (p pyx) destruct() (int, int) {\n return p[0], p[1]\n}\n\nfunc (r route) destruct() (int, int, int) {\n return r[0], r[1], r[2]\n}\n\nfunc search(y, x int) {\n // Simple breadth-first search, populates routes.\n // This isn't strictly Dijkstra because graph edges are not weighted.\n cost := 0\n routes = make([][]route, height)\n for i := 0; i < width; i++ {\n routes[i] = make([]route, width)\n }\n routes[y][x] = route{0, y, x} // zero-cost, the starting point\n var next []route\n for {\n n := int(gmooh[y][x] - '0')\n for di := 0; di < len(d); di++ {\n dx, dy := d[di].destruct()\n rx, ry := x+n*dx, y+n*dy\n if rx >= 0 && rx < width && ry >= 0 && ry < height && gmooh[rx][ry] >= '0' {\n ryx := routes[ry][rx]\n if ryx == zeroRoute || ryx[0] > cost+1 {\n routes[ry][rx] = route{cost + 1, y, x}\n if gmooh[ry][rx] > '0' {\n next = append(next, route{cost + 1, ry, rx})\n // If the graph was weighted, at this point\n // that would get shuffled up into place.\n }\n }\n }\n }\n if len(next) == 0 {\n break\n }\n cost, y, x = next[0].destruct()\n next = next[1:]\n }\n}\n\nfunc getRoute(y, x int) []pyx {\n cost := 0\n res := []pyx{{y, x}}\n for {\n cost, y, x = routes[y][x].destruct()\n if cost == 0 {\n break\n }\n res = append(res, pyx{0, 0})\n copy(res[1:], res[0:])\n res[0] = pyx{y, x}\n }\n return res\n}\n\nfunc showShortest() {\n shortest := 9999\n var res []pyx\n for x := 0; x < width; x++ {\n for y := 0; y < height; y++ {\n if gmooh[y][x] == '0' {\n ryx := routes[y][x]\n if ryx != zeroRoute {\n cost := ryx[0]\n if cost <= shortest {\n if cost < shortest {\n res = res[:0]\n shortest = cost\n }\n res = append(res, pyx{y, x})\n }\n }\n }\n }\n }\n areis, s := \"is\", \"\"\n if len(res) > 1 {\n areis = \"are\"\n s = \"s\"\n }\n fmt.Printf(\"There %s %d shortest route%s of %d days to safety:\\n\", areis, len(res), s, shortest)\n for _, r := range res {\n fmt.Println(getRoute(r[0], r[1]))\n }\n}\n\nfunc showUnreachable() {\n var res []pyx\n for x := 0; x < width; x++ {\n for y := 0; y < height; y++ {\n if gmooh[y][x] >= '0' && routes[y][x] == zeroRoute {\n res = append(res, pyx{y, x})\n }\n }\n }\n fmt.Println(\"\\nThe following cells are unreachable:\")\n fmt.Println(res)\n}\n\nfunc showLongest() {\n longest := 0\n var res []pyx\n for x := 0; x < width; x++ {\n for y := 0; y < height; y++ {\n if gmooh[y][x] >= '0' {\n ryx := routes[y][x]\n if ryx != zeroRoute {\n rl := ryx[0]\n if rl >= longest {\n if rl > longest {\n res = res[:0]\n longest = rl\n }\n res = append(res, pyx{y, x})\n }\n }\n }\n }\n }\n fmt.Printf(\"\\nThere are %d cells that take %d days to send reinforcements to:\\n\", len(res), longest)\n for _, r := range res {\n fmt.Println(getRoute(r[0], r[1]))\n }\n}\n\nfunc main() {\n search(11, 11)\n showShortest()\n\n search(21, 11)\n fmt.Println(\"\\nThe shortest route from {21,11} to {1,11}:\")\n fmt.Println(getRoute(1, 11))\n\n search(1, 11)\n fmt.Println(\"\\nThe shortest route from {1,11} to {21,11}:\")\n fmt.Println(getRoute(21, 11))\n\n search(11, 11)\n showUnreachable()\n showLongest()\n}"} {"title": "ISBN13 check digit", "language": "Go", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n \"unicode/utf8\"\n)\n\nfunc checkIsbn13(isbn string) bool {\n // remove any hyphens or spaces\n isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, \"-\", \"\"), \" \", \"\")\n // check length == 13\n le := utf8.RuneCountInString(isbn)\n if le != 13 {\n return false\n }\n // check only contains digits and calculate weighted sum\n sum := int32(0)\n for i, c := range isbn {\n if c < '0' || c > '9' {\n return false\n }\n if i%2 == 0 {\n sum += c - '0'\n } else {\n sum += 3 * (c - '0')\n }\n }\n return sum%10 == 0\n}\n\nfunc main() {\n isbns := []string{\"978-1734314502\", \"978-1734314509\", \"978-1788399081\", \"978-1788399083\"}\n for _, isbn := range isbns {\n res := \"bad\"\n if checkIsbn13(isbn) {\n res = \"good\"\n }\n fmt.Printf(\"%s: %s\\n\", isbn, res)\n }\n}"} {"title": "I before E except after C", "language": "Go", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).\n \n\n;Stretch goal:\nAs a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc main() {\n\tf, err := os.Open(\"unixdict.txt\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer f.Close()\n\n\ts := bufio.NewScanner(f)\n\trie := regexp.MustCompile(\"^ie|[^c]ie\")\n\trei := regexp.MustCompile(\"^ei|[^c]ei\")\n\tvar cie, ie int\n\tvar cei, ei int\n\tfor s.Scan() {\n\t\tline := s.Text()\n\t\tif strings.Contains(line, \"cie\") {\n\t\t\tcie++\n\t\t}\n\t\tif strings.Contains(line, \"cei\") {\n\t\t\tcei++\n\t\t}\n\t\tif rie.MatchString(line) {\n\t\t\tie++\n\t\t}\n\t\tif rei.MatchString(line) {\n\t\t\tei++\n\t\t}\n\t}\n\terr = s.Err()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tif check(ie, ei, \"I before E when not preceded by C\") &&\n\t\tcheck(cei, cie, \"E before I when preceded by C\") {\n\t\tfmt.Println(\"Both plausable.\")\n\t\tfmt.Println(`\"I before E, except after C\" is plausable.`)\n\t} else {\n\t\tfmt.Println(\"One or both implausable.\")\n\t\tfmt.Println(`\"I before E, except after C\" is implausable.`)\n\t}\n}\n\n// check checks if a statement is plausible. Something is plausible if a is more\n// than two times b.\nfunc check(a, b int, s string) bool {\n\tswitch {\n\tcase a > b*2:\n\t\tfmt.Printf(\"%q is plausible (%d vs %d).\\n\", s, a, b)\n\t\treturn true\n\tcase a >= b:\n\t\tfmt.Printf(\"%q is implausible (%d vs %d).\\n\", s, a, b)\n\tdefault:\n\t\tfmt.Printf(\"%q is implausible and contra-indicated (%d vs %d).\\n\",\n\t\t\ts, a, b)\n\t}\n\treturn false\n}"} {"title": "Identity matrix", "language": "Go", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n\n \"gonum.org/v1/gonum/mat\"\n)\n\nfunc eye(n int) *mat.Dense {\n m := mat.NewDense(n, n, nil)\n for i := 0; i < n; i++ {\n m.Set(i, i, 1)\n }\n return m\n}\n\nfunc main() {\n fmt.Println(mat.Formatted(eye(3)))\n}"} {"title": "Idiomatically determine all the characters that can be used for symbols", "language": "Go", "task": "Idiomatically determine all the characters that can be used for ''symbols''.\nThe word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.\n\nThe method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n\n;Task requirements\n\nDisplay the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. \nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\nNote that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).\n\n;See also\n* Idiomatically determine all the lowercase and uppercase letters.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"go/ast\"\n\t\"go/parser\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc isValidIdentifier(identifier string) bool {\n\tnode, err := parser.ParseExpr(identifier)\n\tif err != nil {\n\t\treturn false\n\t}\n\tident, ok := node.(*ast.Ident)\n\treturn ok && ident.Name == identifier\n}\n\ntype runeRanges struct {\n\tranges []string\n\thasStart bool\n\tstart rune\n\tend rune\n}\n\nfunc (r *runeRanges) add(cp rune) {\n\tif !r.hasStart {\n\t\tr.hasStart = true\n\t\tr.start = cp\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tif cp == r.end+1 {\n\t\tr.end = cp\n\t\treturn\n\t}\n\n\tr.writeTo(&r.ranges)\n\n\tr.start = cp\n\tr.end = cp\n}\n\nfunc (r *runeRanges) writeTo(ranges *[]string) {\n\tif r.hasStart {\n\t\tif r.start == r.end {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U\", r.end))\n\t\t} else {\n\t\t\t*ranges = append(*ranges, fmt.Sprintf(\"%U-%U\", r.start, r.end))\n\t\t}\n\t}\n}\n\nfunc (r *runeRanges) String() string {\n\tranges := r.ranges\n\tr.writeTo(&ranges)\n\treturn strings.Join(ranges, \", \")\n}\n\nfunc main() {\n\tvar validFirst runeRanges\n\tvar validFollow runeRanges\n\tvar validOnlyFollow runeRanges\n\n\tfor r := rune(0); r <= unicode.MaxRune; r++ {\n\t\tfirst := isValidIdentifier(string([]rune{r}))\n\t\tfollow := isValidIdentifier(string([]rune{'_', r}))\n\t\tif first {\n\t\t\tvalidFirst.add(r)\n\t\t}\n\t\tif follow {\n\t\t\tvalidFollow.add(r)\n\t\t}\n\t\tif follow && !first {\n\t\t\tvalidOnlyFollow.add(r)\n\t\t}\n\t}\n\n\t_, _ = fmt.Println(\"Valid first:\", validFirst.String())\n\t_, _ = fmt.Println(\"Valid follow:\", validFollow.String())\n\t_, _ = fmt.Println(\"Only follow:\", validOnlyFollow.String())\n}"} {"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "Go", "task": "Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.\nThe method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n \n\n;Task requirements\n\nDisplay the set of all:\n::::::* lowercase letters \n::::::* uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. \n\n\nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\n\n;See also\n* Idiomatically determine all the characters that can be used for symbols.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"unicode\"\n)\n\nconst (\n\tlcASCII = \"abcdefghijklmnopqrstuvwxyz\"\n\tucASCII = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n)\n\nfunc main() {\n\tfmt.Println(\"ASCII lower case:\")\n\tfmt.Println(lcASCII)\n\tfor l := 'a'; l <= 'z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nASCII upper case:\")\n\tfmt.Println(ucASCII)\n\tfor l := 'A'; l <= 'Z'; l++ {\n\t\tfmt.Print(string(l))\n\t}\n\tfmt.Println()\n\n\tfmt.Println(\"\\nUnicode version \" + unicode.Version)\n\tshowRange16(\"Lower case 16-bit code points:\", unicode.Lower.R16)\n\tshowRange32(\"Lower case 32-bit code points:\", unicode.Lower.R32)\n\tshowRange16(\"Upper case 16-bit code points:\", unicode.Upper.R16)\n\tshowRange32(\"Upper case 32-bit code points:\", unicode.Upper.R32)\n}\n\nfunc showRange16(hdr string, rList []unicode.Range16) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n\nfunc showRange32(hdr string, rList []unicode.Range32) {\n\tfmt.Print(\"\\n\", hdr, \"\\n\")\n\tfmt.Printf(\"%d ranges:\\n\", len(rList))\n\tfor _, rng := range rList {\n\t\tfmt.Printf(\"%U: \", rng.Lo)\n\t\tfor r := rng.Lo; r <= rng.Hi; r += rng.Stride {\n\t\t\tfmt.Printf(\"%c\", r)\n\t\t}\n\t\tfmt.Println()\n\t}\n}"} {"title": "Imaginary base numbers", "language": "Go from Kotlin", "task": "Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. \n\n''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee Wikipedia: Quater-imaginary_base for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n 1\n\n\n2\n 2\n\n\n3\n 3\n\n\n4\n 10300\n\n\n5\n 10301\n\n\n6\n 10302\n\n\n7\n 10303\n\n\n8\n 10200\n\n\n9\n 10201\n\n\n10\n 10202\n\n\n11\n 10203\n\n\n12\n 10100\n\n\n13\n 10101\n\n\n14\n 10102\n\n\n15\n 10103\n\n\n16\n 10000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1\n 103\n\n\n-2\n 102\n\n\n-3\n 101\n\n\n-4\n 100\n\n\n-5\n 203\n\n\n-6\n 202\n\n\n-7\n 201\n\n\n-8\n 200\n\n\n-9\n 303\n\n\n-10\n 302\n\n\n-11\n 301\n\n\n-12\n 300\n\n\n-13\n 1030003\n\n\n-14\n 1030002\n\n\n-15\n 1030001\n\n\n-16\n 1030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1i\n0.2\n\n\n-2i\n1030.0\n\n\n-3i\n1030.2\n\n\n-4i\n1020.0\n\n\n-5i\n1020.2\n\n\n-6i\n1010.0\n\n\n-7i\n1010.2\n\n\n-8i\n1000.0\n\n\n-9i\n1000.2\n\n\n-10i\n2030.0\n\n\n-11i\n2030.2\n\n\n-12i\n2020.0\n\n\n-13i\n2020.2\n\n\n-14i\n2010.0\n\n\n-15i\n2010.2\n\n\n-16i\n2000.0\n\n\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"strconv\"\n \"strings\"\n)\n\nconst (\n twoI = 2.0i\n invTwoI = 1.0 / twoI\n)\n\ntype quaterImaginary struct {\n b2i string\n}\n\nfunc reverse(s string) string {\n r := []rune(s)\n for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {\n r[i], r[j] = r[j], r[i]\n }\n return string(r)\n}\n\nfunc newQuaterImaginary(b2i string) quaterImaginary {\n b2i = strings.TrimSpace(b2i)\n _, err := strconv.ParseFloat(b2i, 64)\n if err != nil {\n panic(\"invalid Base 2i number\")\n }\n return quaterImaginary{b2i}\n}\n\nfunc toComplex(q quaterImaginary) complex128 {\n pointPos := strings.Index(q.b2i, \".\")\n var posLen int\n if pointPos != -1 {\n posLen = pointPos\n } else {\n posLen = len(q.b2i)\n }\n sum := 0.0i\n prod := complex(1.0, 0.0)\n for j := 0; j < posLen; j++ {\n k := float64(q.b2i[posLen-1-j] - '0')\n if k > 0.0 {\n sum += prod * complex(k, 0.0)\n }\n prod *= twoI\n }\n if pointPos != -1 {\n prod = invTwoI\n for j := posLen + 1; j < len(q.b2i); j++ {\n k := float64(q.b2i[j] - '0')\n if k > 0.0 {\n sum += prod * complex(k, 0.0)\n }\n prod *= invTwoI\n }\n }\n return sum\n}\n\nfunc (q quaterImaginary) String() string {\n return q.b2i\n}\n\n// only works properly if 'real' and 'imag' are both integral\nfunc toQuaterImaginary(c complex128) quaterImaginary {\n if c == 0i {\n return quaterImaginary{\"0\"}\n }\n re := int(real(c))\n im := int(imag(c))\n fi := -1\n var sb strings.Builder\n for re != 0 {\n rem := re % -4\n re /= -4\n if rem < 0 {\n rem += 4\n re++\n }\n sb.WriteString(strconv.Itoa(rem))\n sb.WriteString(\"0\")\n }\n if im != 0 {\n f := real(complex(0.0, imag(c)) / 2.0i)\n im = int(math.Ceil(f))\n f = -4.0 * (f - float64(im))\n index := 1\n for im != 0 {\n rem := im % -4\n im /= -4\n if rem < 0 {\n rem += 4\n im++\n }\n if index < sb.Len() {\n bs := []byte(sb.String())\n bs[index] = byte(rem + 48)\n sb.Reset()\n sb.Write(bs)\n } else {\n sb.WriteString(\"0\")\n sb.WriteString(strconv.Itoa(rem))\n }\n index += 2\n }\n fi = int(f)\n }\n s := reverse(sb.String())\n if fi != -1 {\n s = fmt.Sprintf(\"%s.%d\", s, fi)\n }\n s = strings.TrimLeft(s, \"0\")\n if s[0] == '.' {\n s = \"0\" + s\n }\n return newQuaterImaginary(s)\n}\n\nfunc main() {\n for i := 1; i <= 16; i++ {\n c1 := complex(float64(i), 0.0)\n qi := toQuaterImaginary(c1)\n c2 := toComplex(qi)\n fmt.Printf(\"%4.0f -> %8s -> %4.0f \", real(c1), qi, real(c2))\n c1 = -c1\n qi = toQuaterImaginary(c1)\n c2 = toComplex(qi)\n fmt.Printf(\"%4.0f -> %8s -> %4.0f\\n\", real(c1), qi, real(c2))\n }\n fmt.Println()\n for i := 1; i <= 16; i++ {\n c1 := complex(0.0, float64(i))\n qi := toQuaterImaginary(c1)\n c2 := toComplex(qi)\n fmt.Printf(\"%3.0fi -> %8s -> %3.0fi \", imag(c1), qi, imag(c2))\n c1 = -c1\n qi = toQuaterImaginary(c1)\n c2 = toComplex(qi)\n fmt.Printf(\"%3.0fi -> %8s -> %3.0fi\\n\", imag(c1), qi, imag(c2))\n }\n}"} {"title": "Include a file", "language": "Go", "task": "Demonstrate the language's ability to include source code from other files.\n\n\n;See Also\n\n* [[Compiler/Simple file inclusion pre processor]]\n\n\n", "solution": "// main.go\npackage main\n\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello from main.go\")\n}\n\nfunc main() {\n hello()\n hello2()\n}"} {"title": "Increasing gaps between consecutive Niven numbers", "language": "Go", "task": "Note: '''Niven''' numbers are also called '''Harshad''' numbers.\n:::: They are also called '''multidigital''' numbers.\n\n\n'''Niven''' numbers are positive integers which are evenly divisible by the sum of its\ndigits (expressed in base ten).\n\n''Evenly divisible'' means ''divisible with no remainder''.\n\n\n;Task:\n:* find the gap (difference) of a Niven number from the previous Niven number\n:* if the gap is ''larger'' than the (highest) previous gap, then:\n:::* show the index (occurrence) of the gap (the 1st gap is '''1''')\n:::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''')\n:::* show the Niven number that starts the gap\n:::* show all numbers with comma separators where appropriate (optional)\n:::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864'''\n:* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number\n:* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer\n:* show all output here, on this page\n\n\n;Related task:\n:* Harshad or Niven series.\n\n\n;Also see:\n:* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers.\n:* (PDF) version of the (above) article by Doyon.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype is func() uint64\n\nfunc newSum() is {\n var ms is\n ms = func() uint64 {\n ms = newSum()\n return ms()\n }\n var msd, d uint64\n return func() uint64 {\n if d < 9 {\n d++\n } else {\n d = 0\n msd = ms()\n }\n return msd + d\n }\n}\n\nfunc newHarshard() is {\n i := uint64(0)\n sum := newSum()\n return func() uint64 {\n for i++; i%sum() != 0; i++ {\n }\n return i\n }\n}\n\nfunc commatize(n uint64) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n fmt.Println(\"Gap Index of gap Starting Niven\")\n fmt.Println(\"=== ============= ==============\")\n h := newHarshard()\n pg := uint64(0) // previous highest gap\n pn := h() // previous Niven number\n for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {\n g := n - pn\n if g > pg {\n fmt.Printf(\"%3d %13s %14s\\n\", g, commatize(i), commatize(pn))\n pg = g\n }\n pn = n\n }\n}"} {"title": "Index finite lists of positive integers", "language": "Go", "task": "It is known that the set of finite lists of positive integers is countable. \n\nThis means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. \n\n\n;Task:\nImplement such a mapping:\n:* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.\n:* write a function ''unrank'' which is the ''rank'' inverse function.\n\n\nDemonstrate your solution by:\n:* picking a random-length list of random positive integers\n:* turn it into an integer, and \n:* get the list back.\n\n\nThere are many ways to do this. Feel free to choose any one you like.\n\n\n;Extra credit:\nMake the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc rank(l []uint) (r big.Int) {\n for _, n := range l {\n r.Lsh(&r, n+1)\n r.SetBit(&r, int(n), 1)\n }\n return\n}\n\nfunc unrank(n big.Int) (l []uint) {\n m := new(big.Int).Set(&n)\n for a := m.BitLen(); a > 0; {\n m.SetBit(m, a-1, 0)\n b := m.BitLen()\n l = append(l, uint(a-b-1))\n a = b\n }\n return\n}\n\nfunc main() {\n var b big.Int\n for i := 0; i <= 10; i++ {\n b.SetInt64(int64(i))\n u := unrank(b)\n r := rank(u)\n fmt.Println(i, u, &r)\n }\n b.SetString(\"12345678901234567890\", 10)\n u := unrank(b)\n r := rank(u)\n fmt.Printf(\"\\n%v\\n%d\\n%d\\n\", &b, u, &r)\n}"} {"title": "Integer overflow", "language": "Go", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\t// Go's builtin integer types are:\n\t// int, int8, int16, int32, int64\n\t// uint, uint8, uint16, uint32, uint64\n\t// byte, rune, uintptr\n\t//\n\t// int is either 32 or 64 bit, depending on the system\n\t// uintptr is large enough to hold the bit pattern of any pointer\n\t// byte is 8 bits like int8\n\t// rune is 32 bits like int32\n\t//\n\t// Overflow and underflow is silent. The math package defines a number\n\t// of constants that can be helpfull, e.g.:\n\t// math.MaxInt64 = 1<<63 - 1\n\t// math.MinInt64 = -1 << 63\n\t// math.MaxUint64 = 1<<64 - 1\n\t//\n\t// The math/big package implements multi-precision\n\t// arithmetic (big numbers).\n\t//\n\t// In all cases assignment from one type to another requires\n\t// an explicit cast, even if the types are otherwise identical\n\t// (e.g. rune and int32 or int and either int32 or int64).\n\t// Casts silently truncate if required.\n\t//\n\t// Invalid:\n\t// var i int = int32(0)\n\t// var r rune = int32(0)\n\t// var b byte = int8(0)\n\t//\n\t// Valid:\n\tvar i64 int64 = 42\n\tvar i32 int32 = int32(i64)\n\tvar i16 int16 = int16(i64)\n\tvar i8 int8 = int8(i16)\n\tvar i int = int(i8)\n\tvar r rune = rune(i)\n\tvar b byte = byte(r)\n\tvar u64 uint64 = uint64(b)\n\tvar u32 uint32\n\n\t//const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit\n\tconst c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped\n\ti64 = c\n\t//i32 = c // Compiler error\n\t//i32 = -(-2147483647 - 1) // Compiler error\n\ti32 = -2147483647\n\ti32 = -(-i32 - 1)\n\tfmt.Println(\"32 bit signed integers\")\n\tfmt.Printf(\" -(-2147483647 - 1) = %d, got %d\\n\", i64, i32)\n\n\ti64 = 2000000000 + 2000000000\n\t//i32 = 2000000000 + 2000000000 // Compiler error\n\ti32 = 2000000000\n\ti32 = i32 + i32\n\tfmt.Printf(\" 2000000000 + 2000000000 = %d, got %d\\n\", i64, i32)\n\ti64 = -2147483647 - 2147483647\n\ti32 = 2147483647\n\ti32 = -i32 - i32\n\tfmt.Printf(\" -2147483647 - 2147483647 = %d, got %d\\n\", i64, i32)\n\ti64 = 46341 * 46341\n\ti32 = 46341\n\ti32 = i32 * i32\n\tfmt.Printf(\" 46341 * 46341 = %d, got %d\\n\", i64, i32)\n\ti64 = (-2147483647 - 1) / -1\n\ti32 = -2147483647\n\ti32 = (i32 - 1) / -1\n\tfmt.Printf(\" (-2147483647-1) / -1 = %d, got %d\\n\", i64, i32)\n\n\tfmt.Println(\"\\n64 bit signed integers\")\n\ti64 = -9223372036854775807\n\tfmt.Printf(\" -(%d - 1): %d\\n\", i64, -(i64 - 1))\n\ti64 = 5000000000000000000\n\tfmt.Printf(\" %d + %d: %d\\n\", i64, i64, i64+i64)\n\ti64 = 9223372036854775807\n\tfmt.Printf(\" -%d - %d: %d\\n\", i64, i64, -i64-i64)\n\ti64 = 3037000500\n\tfmt.Printf(\" %d * %d: %d\\n\", i64, i64, i64*i64)\n\ti64 = -9223372036854775807\n\tfmt.Printf(\" (%d - 1) / -1: %d\\n\", i64, (i64-1)/-1)\n\n\tfmt.Println(\"\\n32 bit unsigned integers:\")\n\t//u32 = -4294967295 // Compiler error\n\tu32 = 4294967295\n\tfmt.Printf(\" -%d: %d\\n\", u32, -u32)\n\tu32 = 3000000000\n\tfmt.Printf(\" %d + %d: %d\\n\", u32, u32, u32+u32)\n\ta := uint32(2147483647)\n\tu32 = 4294967295\n\tfmt.Printf(\" %d - %d: %d\\n\", a, u32, a-u32)\n\tu32 = 65537\n\tfmt.Printf(\" %d * %d: %d\\n\", u32, u32, u32*u32)\n\n\tfmt.Println(\"\\n64 bit unsigned integers:\")\n\tu64 = 18446744073709551615\n\tfmt.Printf(\" -%d: %d\\n\", u64, -u64)\n\tu64 = 10000000000000000000\n\tfmt.Printf(\" %d + %d: %d\\n\", u64, u64, u64+u64)\n\taa := uint64(9223372036854775807)\n\tu64 = 18446744073709551615\n\tfmt.Printf(\" %d - %d: %d\\n\", aa, u64, aa-u64)\n\tu64 = 4294967296\n\tfmt.Printf(\" %d * %d: %d\\n\", u64, u64, u64*u64)\n}"} {"title": "Integer sequence", "language": "Go", "task": "Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.\n\nIf appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.\n\n", "solution": "package main\n\nimport (\n \"big\"\n \"fmt\"\n)\n\nfunc main() {\n one := big.NewInt(1)\n for i := big.NewInt(1);; i.Add(i, one) {\n fmt.Println(i)\n }\n}"} {"title": "Intersecting number wheels", "language": "Go", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strconv\"\n)\n\ntype wheel struct {\n next int\n values []string\n}\n\ntype wheelMap = map[string]wheel\n\nfunc generate(wheels wheelMap, start string, maxCount int) {\n count := 0\n w := wheels[start]\n for {\n s := w.values[w.next]\n v, err := strconv.Atoi(s)\n w.next = (w.next + 1) % len(w.values)\n wheels[start] = w\n if err == nil {\n fmt.Printf(\"%d \", v)\n count++\n if count == maxCount {\n fmt.Println(\"...\\n\")\n return\n }\n } else {\n for {\n w2 := wheels[s]\n ss := s\n s = w2.values[w2.next]\n w2.next = (w2.next + 1) % len(w2.values)\n wheels[ss] = w2\n v, err = strconv.Atoi(s)\n if err == nil {\n fmt.Printf(\"%d \", v)\n count++\n if count == maxCount {\n fmt.Println(\"...\\n\")\n return\n }\n break\n }\n }\n }\n }\n}\n\nfunc printWheels(wheels wheelMap) {\n var names []string\n for name := range wheels {\n names = append(names, name)\n }\n sort.Strings(names)\n fmt.Println(\"Intersecting Number Wheel group:\")\n for _, name := range names {\n fmt.Printf(\" %s: %v\\n\", name, wheels[name].values)\n }\n fmt.Print(\" Generates:\\n \")\n}\n\nfunc main() {\n wheelMaps := []wheelMap{\n {\n \"A\": {0, []string{\"1\", \"2\", \"3\"}},\n },\n {\n \"A\": {0, []string{\"1\", \"B\", \"2\"}},\n \"B\": {0, []string{\"3\", \"4\"}},\n },\n {\n \"A\": {0, []string{\"1\", \"D\", \"D\"}},\n \"D\": {0, []string{\"6\", \"7\", \"8\"}},\n },\n {\n \"A\": {0, []string{\"1\", \"B\", \"C\"}},\n \"B\": {0, []string{\"3\", \"4\"}},\n \"C\": {0, []string{\"5\", \"B\"}},\n },\n }\n for _, wheels := range wheelMaps {\n printWheels(wheels)\n generate(wheels, \"A\", 20)\n }\n}"} {"title": "Inverted syntax", "language": "Go", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "package main\n\nimport \"fmt\"\n\ntype ibool bool\n\nconst itrue ibool = true\n\nfunc (ib ibool) iif(cond bool) bool {\n if cond {\n return bool(ib)\n }\n return bool(!ib)\n}\n\nfunc main() {\n var needUmbrella bool\n raining := true\n\n // normal syntax\n if raining {\n needUmbrella = true\n }\n fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n\n // inverted syntax\n raining = false\n needUmbrella = itrue.iif(raining)\n fmt.Printf(\"Is it raining? %t. Do I need an umbrella? %t\\n\", raining, needUmbrella)\n}"} {"title": "Isqrt (integer square root) of X", "language": "Go", "task": "Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a\nreal non-negative number.\n\nOften '''X''' is actually a non-negative integer.\n\nFor the purposes of this task, '''X''' can be an integer or a real number, but if it\nsimplifies things in your computer programming language, assume it's an integer.\n\n\nOne of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or\nprimes) up to the \n X of that\ninteger, either to find the factors of that integer, or to determine primality.\n\n\nAn alternative method for finding the '''Isqrt''' of a number is to\ncalculate: floor( sqrt(X) ) \n::* where '''sqrt''' is the square root function for non-negative real numbers, and\n::* where '''floor''' is the floor function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.\n\n\n;Pseudo-code using quadratic residue:\nFor this task, the integer square root of a non-negative number will be computed using a version\nof ''quadratic residue'', which has the advantage that no ''floating point'' calculations are\nused, only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):\n q <-- 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z <-- x /*set Z to the value of X.*/\n r <-- 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q <-- q / 4 /*integer divide by four. */\n t <-- z - r - q /*compute value of T. */\n r <-- r / 2 /*integer divide by two. */\n if t >= 0 then do \n z <-- t /*set Z to value of T. */\n r <-- r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) 1st '''perform''' is:\n perform until q > X /*perform until Q > X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here (on this page) for:\n::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.\n::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.\n::* use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, show what you can.\n\n\n;Related tasks:\n:* sequence of non-squares\n:* integer roots\n:* square root by hand\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\nvar zero = big.NewInt(0)\nvar one = big.NewInt(1)\n\nfunc isqrt(x *big.Int) *big.Int {\n if x.Cmp(zero) < 0 {\n log.Fatal(\"Argument cannot be negative.\")\n }\n q := big.NewInt(1)\n for q.Cmp(x) <= 0 {\n q.Lsh(q, 2)\n }\n z := new(big.Int).Set(x)\n r := big.NewInt(0)\n for q.Cmp(one) > 0 {\n q.Rsh(q, 2)\n t := new(big.Int)\n t.Add(t, z)\n t.Sub(t, r)\n t.Sub(t, q)\n r.Rsh(r, 1)\n if t.Cmp(zero) >= 0 {\n z.Set(t)\n r.Add(r, q)\n }\n }\n return r\n}\n\nfunc commatize(s string) string {\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n fmt.Println(\"The integer square roots of integers from 0 to 65 are:\")\n for i := int64(0); i <= 65; i++ {\n fmt.Printf(\"%d \", isqrt(big.NewInt(i)))\n }\n fmt.Println()\n fmt.Println(\"\\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\\n\")\n fmt.Println(\"power 7 ^ power integer square root\")\n fmt.Println(\"----- --------------------------------------------------------------------------------- -----------------------------------------\")\n pow7 := big.NewInt(7)\n bi49 := big.NewInt(49)\n for i := 1; i <= 73; i += 2 {\n fmt.Printf(\"%2d %84s %41s\\n\", i, commatize(pow7.String()), commatize(isqrt(pow7).String()))\n pow7.Mul(pow7, bi49)\n }\n}"} {"title": "Iterated digits squaring", "language": "Go", "task": "If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tvar d, n, o, u, u89 int64\n\n\tfor n = 1; n < 100000000; n++ {\n\t\to = n\n\t\tfor {\n\t\t\tu = 0\n\t\t\tfor {\n\t\t\t\td = o%10\n\t\t\t\to = (o - d) / 10\n\t\t\t\tu += d*d\n\t\t\t\tif o == 0 {\n\t\t\t\t\tbreak \n\t\t\t\t}\n\t\t\t}\n\t\t\tif u == 89 || u == 1 {\n\t\t\t\tif u == 89 { u89++ }\n\t\t\t\tbreak\n\t\t\t}\n\t\t\to = u\n\t\t}\n\t}\n\tfmt.Println(u89)\n}"} {"title": "JSON", "language": "Go", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "package main\n\nimport \"encoding/json\"\nimport \"fmt\"\n\nfunc main() {\n var data interface{}\n err := json.Unmarshal([]byte(`{\"foo\":1, \"bar\":[10, \"apples\"]}`), &data)\n if err == nil {\n fmt.Println(data)\n } else {\n fmt.Println(err)\n }\n\n sample := map[string]interface{}{\n \"blue\": []interface{}{1, 2},\n \"ocean\": \"water\",\n }\n json_string, err := json.Marshal(sample)\n if err == nil {\n fmt.Println(string(json_string))\n } else {\n fmt.Println(err)\n }\n}"} {"title": "Jacobi symbol", "language": "Go", "task": "The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)\n* (a | p) 1 if a is a square (mod p)\n* (a | p) -1 if a is not a square (mod p)\n* (a | p) 0 if a 0 \n\nIf n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).\n\n;Task:\nCalculate the Jacobi symbol (a | n).\n\n;Reference:\n* Wikipedia article on Jacobi symbol.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math/big\"\n)\n\nfunc jacobi(a, n uint64) int {\n if n%2 == 0 {\n log.Fatal(\"'n' must be a positive odd integer\")\n }\n a %= n\n result := 1\n for a != 0 {\n for a%2 == 0 {\n a /= 2\n nn := n % 8\n if nn == 3 || nn == 5 {\n result = -result\n }\n }\n a, n = n, a\n if a%4 == 3 && n%4 == 3 {\n result = -result\n }\n a %= n\n }\n if n == 1 {\n return result\n }\n return 0\n}\n\nfunc main() {\n fmt.Println(\"Using hand-coded version:\")\n fmt.Println(\"n/a 0 1 2 3 4 5 6 7 8 9\")\n fmt.Println(\"---------------------------------\")\n for n := uint64(1); n <= 17; n += 2 {\n fmt.Printf(\"%2d \", n)\n for a := uint64(0); a <= 9; a++ {\n fmt.Printf(\" % d\", jacobi(a, n))\n }\n fmt.Println()\n }\n\n ba, bn := new(big.Int), new(big.Int)\n fmt.Println(\"\\nUsing standard library function:\")\n fmt.Println(\"n/a 0 1 2 3 4 5 6 7 8 9\")\n fmt.Println(\"---------------------------------\")\n for n := uint64(1); n <= 17; n += 2 {\n fmt.Printf(\"%2d \", n)\n for a := uint64(0); a <= 9; a++ {\n ba.SetUint64(a)\n bn.SetUint64(n)\n fmt.Printf(\" % d\", big.Jacobi(ba, bn)) \n }\n fmt.Println()\n }\n}"} {"title": "Jacobsthal numbers", "language": "Go", "task": "'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.\n\n \n J0 = 0\n J1 = 1\n Jn = Jn-1 + 2 x Jn-2\n\n\nTerms may be calculated directly using one of several possible formulas:\n \n Jn = ( 2n - (-1)n ) / 3\n \n\n\n'''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''.\n\nTerms may be calculated directly using one of several possible formulas:\n \n JLn = 2n + (-1)n\n\n\n'''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''.\n\n\n'''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime.\n\n\n\n;Task\n* Find and display the first 30 '''Jacobsthal numbers'''\n* Find and display the first 30 '''Jacobsthal-Lucas numbers'''\n* Find and display the first 20 '''Jacobsthal oblong numbers'''\n* Find and display at least the first 10 '''Jacobsthal primes'''\n\n\n\n;See also\n;* Wikipedia: Jacobsthal number\n;* Numbers Aplenty - Jacobsthal number\n;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers)\n;* OEIS:A014551 - Jacobsthal-Lucas numbers.\n;* OEIS:A084175 - Jacobsthal oblong numbers\n;* OEIS:A049883 - Primes in the Jacobsthal sequence\n;* Related task: Fibonacci sequence\n;* Related task: Leonardo numbers\n\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc jacobsthal(n uint) *big.Int {\n t := big.NewInt(1)\n t.Lsh(t, n)\n s := big.NewInt(1)\n if n%2 != 0 {\n s.Neg(s)\n }\n t.Sub(t, s)\n return t.Div(t, big.NewInt(3))\n}\n\nfunc jacobsthalLucas(n uint) *big.Int {\n t := big.NewInt(1)\n t.Lsh(t, n)\n a := big.NewInt(1)\n if n%2 != 0 {\n a.Neg(a)\n }\n return t.Add(t, a)\n}\n\nfunc main() {\n jac := make([]*big.Int, 30)\n fmt.Println(\"First 30 Jacobsthal numbers:\")\n for i := uint(0); i < 30; i++ {\n jac[i] = jacobsthal(i)\n fmt.Printf(\"%9d \", jac[i])\n if (i+1)%5 == 0 {\n fmt.Println()\n }\n }\n\n fmt.Println(\"\\nFirst 30 Jacobsthal-Lucas numbers:\")\n for i := uint(0); i < 30; i++ {\n fmt.Printf(\"%9d \", jacobsthalLucas(i))\n if (i+1)%5 == 0 {\n fmt.Println()\n }\n }\n\n fmt.Println(\"\\nFirst 20 Jacobsthal oblong numbers:\")\n for i := uint(0); i < 20; i++ {\n t := big.NewInt(0)\n fmt.Printf(\"%11d \", t.Mul(jac[i], jac[i+1]))\n if (i+1)%5 == 0 {\n fmt.Println()\n }\n }\n\n fmt.Println(\"\\nFirst 20 Jacobsthal primes:\")\n for n, count := uint(0), 0; count < 20; n++ {\n j := jacobsthal(n)\n if j.ProbablyPrime(10) {\n fmt.Println(j)\n count++\n }\n }\n}"} {"title": "Jaro similarity", "language": "Go", "task": "The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity d_j of two given strings s_1 and s_2 is\n\n: d_j = \\left\\{\n\n\\begin{array}{l l}\n 0 & \\text{if }m = 0\\\\\n \\frac{1}{3}\\left(\\frac{m}{|s_1|} + \\frac{m}{|s_2|} + \\frac{m-t}{m}\\right) & \\text{otherwise} \\end{array} \\right.\n\nWhere:\n\n* m is the number of ''matching characters'';\n* t is half the number of ''transpositions''.\n\n\nTwo characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.\n\n\n;;Example\n\nGiven the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:\n\n* m = 4\n* |s_1| = 6\n* |s_2| = 5\n* t = 0\n\n\nWe find a Jaro score of:\n\n: d_j = \\frac{1}{3}\\left(\\frac{4}{6} + \\frac{4}{5} + \\frac{4-0}{4}\\right) = 0.822\n\n\n;Task\n\nImplement the Jaro algorithm and show the similarity scores for each of the following pairs:\n\n* (\"MARTHA\", \"MARHTA\")\n* (\"DIXON\", \"DICKSONX\")\n* (\"JELLYFISH\", \"SMELLYFISH\")\n\n\n; See also\n* Jaro-Winkler distance on Wikipedia.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc jaro(str1, str2 string) float64 {\n if len(str1) == 0 && len(str2) == 0 {\n return 1\n }\n if len(str1) == 0 || len(str2) == 0 {\n return 0\n }\n match_distance := len(str1)\n if len(str2) > match_distance {\n match_distance = len(str2)\n }\n match_distance = match_distance/2 - 1\n str1_matches := make([]bool, len(str1))\n str2_matches := make([]bool, len(str2))\n matches := 0.\n transpositions := 0.\n for i := range str1 {\n start := i - match_distance\n if start < 0 {\n start = 0\n }\n end := i + match_distance + 1\n if end > len(str2) {\n end = len(str2)\n }\n for k := start; k < end; k++ {\n if str2_matches[k] {\n continue\n }\n if str1[i] != str2[k] {\n continue\n }\n str1_matches[i] = true\n str2_matches[k] = true\n matches++\n break\n }\n }\n if matches == 0 {\n return 0\n }\n k := 0\n for i := range str1 {\n if !str1_matches[i] {\n continue\n }\n for !str2_matches[k] {\n k++\n }\n if str1[i] != str2[k] {\n transpositions++\n }\n k++\n }\n transpositions /= 2\n return (matches/float64(len(str1)) +\n matches/float64(len(str2)) +\n (matches-transpositions)/matches) / 3\n}\n\nfunc main() {\n fmt.Printf(\"%f\\n\", jaro(\"MARTHA\", \"MARHTA\"))\n fmt.Printf(\"%f\\n\", jaro(\"DIXON\", \"DICKSONX\"))\n fmt.Printf(\"%f\\n\", jaro(\"JELLYFISH\", \"SMELLYFISH\"))\n}"} {"title": "Jewels and stones", "language": "Go", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "package main\n \nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc js(stones, jewels string) (n int) {\n for _, b := range []byte(stones) {\n if strings.IndexByte(jewels, b) >= 0 {\n n++\n }\n }\n return\n}\n\nfunc main() {\n fmt.Println(js(\"aAAbbbb\", \"aA\"))\n}"} {"title": "Julia set", "language": "Go", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n)\n\nfunc main() {\n\tconst (\n\t\twidth, height = 800.0, 600.0\n\t\tmaxIter = 255\n\t\tcX, cY = -0.7, 0.27015\n\t\tfileName = \"julia.png\"\n\t)\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height))\n\n\tvar wg sync.WaitGroup\n\twg.Add(width)\n\tfor x := 0; x < width; x++ {\n\t\tthisx := float64(x)\n\t\tgo func() {\n\t\t\tvar tmp, zx, zy float64\n\t\t\tvar i uint8\n\t\t\tfor y := 0.0; y < height; y++ {\n\t\t\t\tzx = 1.5 * (thisx - width/2) / (0.5 * width)\n\t\t\t\tzy = (y - height/2) / (0.5 * height)\n\t\t\t\ti = maxIter\n\t\t\t\tfor zx*zx+zy*zy < 4.0 && i > 0 {\n\t\t\t\t\ttmp = zx*zx - zy*zy + cX\n\t\t\t\t\tzy = 2.0*zx*zy + cY\n\t\t\t\t\tzx = tmp\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t\timg.Set(int(thisx), int(y), color.RGBA{i, i, i << 3, 255})\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}"} {"title": "Jump anywhere", "language": "Go", "task": "Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis task provides a \"grab bag\" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n outer:\n for i := 0; i < 4; i++ {\n for j := 0; j < 4; j++ {\n if i + j == 4 { continue outer }\n if i + j == 5 { break outer }\n fmt.Println(i + j)\n }\n }\n\n k := 3\n if k == 3 { goto later }\n fmt.Println(k) // never executed\n later:\n k++\n fmt.Println(k)\n}"} {"title": "K-d tree", "language": "Go", "task": "{{wikipedia|K-d tree}}\n\nA k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). \nk-d trees are a special case of binary space partitioning trees.\n\nk-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. \nOtherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.\n\n'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:\n\n# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].\n# 1000 3-d points uniformly distributed in a 3-d cube.\n\nFor the Wikipedia example, find the nearest neighbor to point (9, 2)\nFor the random data, pick a random location and find the nearest neighbor.\n\nIn addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.\n\nOutput should show the point searched for, the point found, \nthe distance to the point, and the number of nodes visited.\n\nThere are variant algorithms for constructing the tree. \nYou can use a simple median strategy or implement something more efficient. \nVariants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. \nYou do not have to implement these. \nThe requirement for this task is specifically the nearest single neighbor. \nAlso there are algorithms for inserting, deleting, and balancing k-d trees. \nThese are also not required for the task.\n\n", "solution": "// Implmentation following pseudocode from \"An intoductory tutorial on kd-trees\"\n// by Andrew W. Moore, Carnegie Mellon University, PDF accessed from\n// http://www.autonlab.org/autonweb/14665\npackage main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"sort\"\n \"time\"\n)\n\n// point is a k-dimensional point.\ntype point []float64\n\n// sqd returns the square of the euclidean distance.\nfunc (p point) sqd(q point) float64 {\n var sum float64\n for dim, pCoord := range p {\n d := pCoord - q[dim]\n sum += d * d\n }\n return sum\n}\n\n// kdNode following field names in the paper.\n// rangeElt would be whatever data is associated with the point. we don't\n// bother with it for this example.\ntype kdNode struct {\n domElt point\n split int\n left, right *kdNode\n} \n\ntype kdTree struct {\n n *kdNode\n bounds hyperRect\n}\n \ntype hyperRect struct {\n min, max point\n}\n\n// Go slices are reference objects. The data must be copied if you want\n// to modify one without modifying the original.\nfunc (hr hyperRect) copy() hyperRect {\n return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}\n} \n \n// newKd constructs a kdTree from a list of points, also associating the\n// bounds of the tree. The bounds could be computed of course, but in this\n// example we know them already. The algorithm is table 6.3 in the paper.\nfunc newKd(pts []point, bounds hyperRect) kdTree {\n var nk2 func([]point, int) *kdNode\n nk2 = func(exset []point, split int) *kdNode {\n if len(exset) == 0 {\n return nil\n }\n // pivot choosing procedure. we find median, then find largest\n // index of points with median value. this satisfies the\n // inequalities of steps 6 and 7 in the algorithm.\n sort.Sort(part{exset, split})\n m := len(exset) / 2\n d := exset[m]\n for m+1 < len(exset) && exset[m+1][split] == d[split] {\n m++\n }\n // next split\n s2 := split + 1\n if s2 == len(d) {\n s2 = 0\n }\n return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}\n }\n return kdTree{nk2(pts, 0), bounds}\n}\n\n// a container type used for sorting. it holds the points to sort and\n// the dimension to use for the sort key.\ntype part struct {\n pts []point\n dPart int\n}\n\n// satisfy sort.Interface\nfunc (p part) Len() int { return len(p.pts) }\nfunc (p part) Less(i, j int) bool {\n return p.pts[i][p.dPart] < p.pts[j][p.dPart]\n}\nfunc (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }\n\n// nearest. find nearest neighbor. return values are:\n// nearest neighbor--the point within the tree that is nearest p.\n// square of the distance to that point.\n// a count of the nodes visited in the search.\nfunc (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {\n return nn(t.n, p, t.bounds, math.Inf(1))\n}\n\n// algorithm is table 6.4 from the paper, with the addition of counting\n// the number nodes visited.\nfunc nn(kd *kdNode, target point, hr hyperRect,\n maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {\n if kd == nil {\n return nil, math.Inf(1), 0\n }\n nodesVisited++\n s := kd.split\n pivot := kd.domElt\n leftHr := hr.copy()\n rightHr := hr.copy()\n leftHr.max[s] = pivot[s]\n rightHr.min[s] = pivot[s]\n targetInLeft := target[s] <= pivot[s]\n var nearerKd, furtherKd *kdNode\n var nearerHr, furtherHr hyperRect\n if targetInLeft {\n nearerKd, nearerHr = kd.left, leftHr\n furtherKd, furtherHr = kd.right, rightHr\n } else {\n nearerKd, nearerHr = kd.right, rightHr\n furtherKd, furtherHr = kd.left, leftHr\n }\n var nv int\n nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)\n nodesVisited += nv\n if distSqd < maxDistSqd {\n maxDistSqd = distSqd\n }\n d := pivot[s] - target[s]\n d *= d\n if d > maxDistSqd {\n return\n }\n if d = pivot.sqd(target); d < distSqd {\n nearest = pivot\n distSqd = d\n maxDistSqd = distSqd\n }\n tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)\n nodesVisited += nv\n if tempSqd < distSqd {\n nearest = tempNearest\n distSqd = tempSqd\n }\n return\n}\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},\n hyperRect{point{0, 0}, point{10, 10}})\n showNearest(\"WP example data\", kd, point{9, 2})\n kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})\n showNearest(\"1000 random 3d points\", kd, randomPt(3))\n} \n \nfunc randomPt(dim int) point {\n p := make(point, dim)\n for d := range p {\n p[d] = rand.Float64()\n }\n return p\n} \n \nfunc randomPts(dim, n int) []point {\n p := make([]point, n)\n for i := range p {\n p[i] = randomPt(dim) \n } \n return p\n}\n \nfunc showNearest(heading string, kd kdTree, p point) {\n fmt.Println()\n fmt.Println(heading)\n fmt.Println(\"point: \", p)\n nn, ssq, nv := kd.nearest(p)\n fmt.Println(\"nearest neighbor:\", nn)\n fmt.Println(\"distance: \", math.Sqrt(ssq))\n fmt.Println(\"nodes visited: \", nv)\n}"} {"title": "Kaprekar numbers", "language": "Go", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc kaprekar(n uint64, base uint64) (bool, int) {\n order := 0\n if n == 1 {\n return true, -1\n }\n\n nn, power := n*n, uint64(1)\n for power <= nn {\n power *= base\n order++\n }\n\n power /= base\n order--\n for ; power > 1; power /= base {\n q, r := nn/power, nn%power\n if q >= n {\n return false, -1\n }\n\n if q+r == n {\n return true, order\n }\n\n order--\n }\n\n return false, -1\n}\n\nfunc main() {\n max := uint64(10000)\n fmt.Printf(\"Kaprekar numbers < %d:\\n\", max)\n for m := uint64(0); m < max; m++ {\n if is, _ := kaprekar(m, 10); is {\n fmt.Println(\" \", m)\n }\n }\n\n // extra credit\n max = 1e6\n var count int\n for m := uint64(0); m < max; m++ {\n if is, _ := kaprekar(m, 10); is {\n count++\n }\n }\n fmt.Printf(\"\\nThere are %d Kaprekar numbers < %d.\\n\", count, max)\n\n // extra extra credit\n const base = 17\n maxB := \"1000000\"\n fmt.Printf(\"\\nKaprekar numbers between 1 and %s(base %d):\\n\", maxB, base)\n max, _ = strconv.ParseUint(maxB, base, 64)\n fmt.Printf(\"\\n Base 10 Base %d Square Split\\n\", base)\n for m := uint64(2); m < max; m++ {\n is, pos := kaprekar(m, base)\n if !is {\n continue\n }\n sq := strconv.FormatUint(m*m, base)\n str := strconv.FormatUint(m, base)\n split := len(sq)-pos\n fmt.Printf(\"%8d %7s %12s %6s + %s\\n\", m,\n str, sq, sq[:split], sq[split:]) // optional extra extra credit\n }\n}"} {"title": "Kernighans large earthquake problem", "language": "Go", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n f, err := os.Open(\"data.txt\")\n if err != nil {\n fmt.Println(\"Unable to open the file\")\n return\n }\n defer f.Close()\n fmt.Println(\"Those earthquakes with a magnitude > 6.0 are:\\n\")\n input := bufio.NewScanner(f)\n for input.Scan() {\n line := input.Text()\n fields := strings.Fields(line)\n mag, err := strconv.ParseFloat(fields[2], 64)\n if err != nil {\n fmt.Println(\"Unable to parse magnitude of an earthquake\")\n return\n }\n if mag > 6.0 {\n fmt.Println(line)\n }\n }\n}"} {"title": "Knight's tour", "language": "Go", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// input, 0-based start position\nconst startRow = 0\nconst startCol = 0\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n for !knightTour() {\n }\n}\n\nvar moves = []struct{ dr, dc int }{\n {2, 1},\n {2, -1},\n {1, 2},\n {1, -2},\n {-1, 2},\n {-1, -2},\n {-2, 1},\n {-2, -1},\n}\n\n// Attempt knight tour starting at startRow, startCol using Warnsdorff's rule\n// and random tie breaking. If a tour is found, print it and return true.\n// Otherwise no backtracking, just return false.\nfunc knightTour() bool {\n // 8x8 board. squares hold 1-based visit order. 0 means unvisited.\n board := make([][]int, 8)\n for i := range board {\n board[i] = make([]int, 8)\n }\n r := startRow\n c := startCol\n board[r][c] = 1 // first move\n for move := 2; move <= 64; move++ {\n minNext := 8\n var mr, mc, nm int\n candidateMoves:\n for _, cm := range moves {\n cr := r + cm.dr\n if cr < 0 || cr >= 8 { // off board\n continue\n }\n cc := c + cm.dc\n if cc < 0 || cc >= 8 { // off board\n continue\n }\n if board[cr][cc] > 0 { // already visited\n continue\n }\n // cr, cc candidate legal move.\n p := 0 // count possible next moves.\n for _, m2 := range moves {\n r2 := cr + m2.dr\n if r2 < 0 || r2 >= 8 {\n continue\n }\n c2 := cc + m2.dc\n if c2 < 0 || c2 >= 8 {\n continue\n }\n if board[r2][c2] > 0 {\n continue\n }\n p++\n if p > minNext { // bail out as soon as it's eliminated\n continue candidateMoves\n }\n }\n if p < minNext { // it's better. keep it.\n minNext = p // new min possible next moves\n nm = 1 // number of candidates with this p\n mr = cr // best candidate move\n mc = cc\n continue\n }\n // it ties for best so far.\n // keep it with probability 1/(number of tying moves)\n nm++ // number of tying moves\n if rand.Intn(nm) == 0 { // one chance to keep it\n mr = cr\n mc = cc\n }\n }\n if nm == 0 { // no legal move\n return false\n }\n // make selected move\n r = mr\n c = mc\n board[r][c] = move\n }\n // tour complete. print board.\n for _, r := range board {\n for _, m := range r {\n fmt.Printf(\"%3d\", m)\n }\n fmt.Println()\n }\n return true\n}"} {"title": "Knuth's algorithm S", "language": "Go", "task": "This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.\nThis means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).\n\n\n;The algorithm:\n:* Select the first n items as the sample as they become available;\n:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.\n:* Repeat 2nd step for any subsequent items.\n\n\n;The Task:\n:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.\n:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.\n:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:\n:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.\n:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.\n\n\nNote: A class taking n and generating a callable instance/function might also be used.\n\n\n;Reference:\n* The Art of Computer Programming, Vol 2, 3.4.2 p.142\n\n\n;Related tasks: \n* [[One of n lines in a file]] \n* [[Accumulator factory]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nfunc sOfNCreator(n int) func(byte) []byte {\n s := make([]byte, 0, n)\n m := n\n return func(item byte) []byte {\n if len(s) < n {\n s = append(s, item)\n } else {\n m++\n if rand.Intn(m) < n {\n s[rand.Intn(n)] = item\n }\n }\n return s\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n var freq [10]int\n for r := 0; r < 1e5; r++ {\n sOfN := sOfNCreator(3)\n for d := byte('0'); d < '9'; d++ {\n sOfN(d)\n }\n for _, d := range sOfN('9') {\n freq[d-'0']++\n }\n }\n fmt.Println(freq)\n}"} {"title": "Koch curve", "language": "Go from Ring", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "package main\n\nimport (\n \"github.com/fogleman/gg\"\n \"math\"\n)\n\nvar dc = gg.NewContext(512, 512)\n\nfunc koch(x1, y1, x2, y2 float64, iter int) {\n angle := math.Pi / 3 // 60 degrees\n x3 := (x1*2 + x2) / 3\n y3 := (y1*2 + y2) / 3\n x4 := (x1 + x2*2) / 3\n y4 := (y1 + y2*2) / 3\n x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)\n y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)\n if iter > 0 {\n iter--\n koch(x1, y1, x3, y3, iter)\n koch(x3, y3, x5, y5, iter)\n koch(x5, y5, x4, y4, iter)\n koch(x4, y4, x2, y2, iter)\n } else {\n dc.LineTo(x1, y1)\n dc.LineTo(x3, y3)\n dc.LineTo(x5, y5)\n dc.LineTo(x4, y4)\n dc.LineTo(x2, y2)\n }\n}\n\nfunc main() {\n dc.SetRGB(1, 1, 1) // White background\n dc.Clear()\n koch(100, 100, 400, 400, 4)\n dc.SetRGB(0, 0, 1) // Blue curve\n dc.SetLineWidth(2)\n dc.Stroke()\n dc.SavePNG(\"koch.png\")\n}"} {"title": "Kolakoski sequence", "language": "Go from Kotlin", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc nextInCycle(c []int, index int) int {\n return c[index % len(c)]\n}\n\nfunc kolakoski(c []int, slen int) []int {\n s := make([]int, slen)\n i, k := 0, 0\n for {\n s[i] = nextInCycle(c, k)\n if s[k] > 1 {\n for j := 1; j < s[k]; j++ {\n i++\n if i == slen {\n return s\n }\n s[i] = s[i - 1]\n }\n }\n i++\n if i == slen {\n return s\n }\n k++\n }\n}\n\nfunc possibleKolakoski(s []int) bool {\n slen := len(s)\n rle := make([]int, 0, slen)\n prev := s[0]\n count := 1\n for i := 1; i < slen; i++ {\n if s[i] == prev {\n count++\n } else {\n rle = append(rle, count)\n count = 1\n prev = s[i]\n }\n }\n // no point adding final 'count' to rle as we're not going to compare it anyway\n for i := 0; i < len(rle); i++ {\n if rle[i] != s[i] {\n return false\n }\n }\n return true\n}\n\nfunc printInts(ia []int, suffix string) {\n fmt.Print(\"[\")\n alen := len(ia)\n for i := 0; i < alen; i++ {\n fmt.Print(ia[i])\n if i < alen - 1 {\n fmt.Print(\", \")\n }\n }\n fmt.Printf(\"]%s\\n\", suffix)\n}\n\nfunc main() {\n ias := make([][]int, 4)\n ias[0] = []int{1, 2}\n ias[1] = []int{2, 1}\n ias[2] = []int{1, 3, 1, 2}\n ias[3] = []int{1, 3, 2, 1}\n slens := []int{20, 20, 30, 30}\n for i, ia := range ias {\n slen := slens[i]\n kol := kolakoski(ia, slen)\n fmt.Printf(\"First %d members of the sequence generated by \", slen)\n printInts(ia, \":\")\n printInts(kol, \"\")\n p := possibleKolakoski(kol)\n poss := \"Yes\"\n if !p {\n poss = \"No\"\n }\n fmt.Println(\"Possible Kolakoski sequence?\", poss, \"\\n\")\n }\n}"} {"title": "Kosaraju", "language": "Go", "task": "{{wikipedia|Graph}}\n\n\nKosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.\n\nFor this task consider the directed graph with these connections:\n 0 -> 1\n 1 -> 2\n 2 -> 0\n 3 -> 1, 3 -> 2, 3 -> 4\n 4 -> 3, 4 -> 5\n 5 -> 2, 5 -> 6\n 6 -> 5\n 7 -> 4, 7 -> 6, 7 -> 7\n\nAnd report the kosaraju strongly connected component for each node.\n\n;References:\n* The article on Wikipedia.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar g = [][]int{\n 0: {1},\n 1: {2},\n 2: {0},\n 3: {1, 2, 4},\n 4: {3, 5},\n 5: {2, 6},\n 6: {5},\n 7: {4, 6, 7},\n}\n\nfunc main() {\n fmt.Println(kosaraju(g))\n}\n\nfunc kosaraju(g [][]int) []int {\n // 1. For each vertex u of the graph, mark u as unvisited. Let L be empty.\n vis := make([]bool, len(g))\n L := make([]int, len(g))\n x := len(L) // index for filling L in reverse order\n t := make([][]int, len(g)) // transpose graph\n // 2. recursive subroutine:\n var Visit func(int)\n Visit = func(u int) {\n if !vis[u] {\n vis[u] = true\n for _, v := range g[u] {\n Visit(v)\n t[v] = append(t[v], u) // construct transpose\n }\n x--\n L[x] = u\n }\n }\n // 2. For each vertex u of the graph do Visit(u)\n for u := range g {\n Visit(u)\n }\n c := make([]int, len(g)) // result, the component assignment\n // 3: recursive subroutine:\n var Assign func(int, int)\n Assign = func(u, root int) {\n if vis[u] { // repurpose vis to mean \"unassigned\"\n vis[u] = false\n c[u] = root\n for _, v := range t[u] {\n Assign(v, root)\n }\n }\n }\n // 3: For each element u of L in order, do Assign(u,u)\n for _, u := range L {\n Assign(u, u)\n }\n return c\n}"} {"title": "Lah numbers", "language": "Go", "task": "Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.\n\nUnsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.\n\nLah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.\n\nLah numbers obey the identities and relations:\n L(n, 0), L(0, k) = 0 # for n, k > 0\n L(n, n) = 1\n L(n, 1) = n!\n L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers\n ''or''\n L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers\n\n;Task:\n:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Lah number'''\n:* '''OEIS:A105278 - Unsigned Lah numbers'''\n:* '''OEIS:A008297 - Signed Lah numbers'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Stirling numbers of the second kind'''\n:* '''Bell numbers'''\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n limit := 100\n last := 12\n unsigned := true\n l := make([][]*big.Int, limit+1)\n for n := 0; n <= limit; n++ {\n l[n] = make([]*big.Int, limit+1)\n for k := 0; k <= limit; k++ {\n l[n][k] = new(big.Int)\n }\n l[n][n].SetInt64(int64(1))\n if n != 1 {\n l[n][1].MulRange(int64(2), int64(n))\n }\n }\n var t big.Int\n for n := 1; n <= limit; n++ {\n for k := 1; k <= n; k++ {\n t.Mul(l[n][1], l[n-1][1])\n t.Quo(&t, l[k][1])\n t.Quo(&t, l[k-1][1])\n t.Quo(&t, l[n-k][1])\n l[n][k].Set(&t)\n if !unsigned && (n%2 == 1) {\n l[n][k].Neg(l[n][k])\n }\n }\n }\n fmt.Println(\"Unsigned Lah numbers: l(n, k):\")\n fmt.Printf(\"n/k\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"%10d \", i)\n }\n fmt.Printf(\"\\n--\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"-----------\")\n }\n fmt.Println()\n for n := 0; n <= last; n++ {\n fmt.Printf(\"%2d \", n)\n for k := 0; k <= n; k++ {\n fmt.Printf(\"%10d \", l[n][k])\n }\n fmt.Println()\n }\n fmt.Println(\"\\nMaximum value from the l(100, *) row:\")\n max := new(big.Int).Set(l[limit][0])\n for k := 1; k <= limit; k++ {\n if l[limit][k].Cmp(max) > 0 {\n max.Set(l[limit][k])\n }\n }\n fmt.Println(max)\n fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}"} {"title": "Largest int from concatenated ints", "language": "Go", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "// Variation of method 3. Repeat digits to at least the size of the longest,\n// then sort as strings.\npackage main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"sort\"\n \"strconv\"\n \"strings\"\n)\n\ntype c struct {\n i int\n s, rs string\n}\n\ntype cc []*c\n\nfunc (c cc) Len() int { return len(c) }\nfunc (c cc) Less(i, j int) bool { return c[j].rs < c[i].rs }\nfunc (c cc) Swap(i, j int) { c[i], c[j] = c[j], c[i] }\n\n// Function required by task. Takes a list of integers, returns big int.\nfunc li(is ...int) *big.Int {\n ps := make(cc, len(is))\n ss := make([]c, len(is))\n ml := 0\n for j, i := range is {\n p := &ss[j]\n ps[j] = p\n p.i = i\n p.s = strconv.Itoa(i)\n if len(p.s) > ml {\n ml = len(p.s)\n }\n }\n for _, p := range ps {\n p.rs = strings.Repeat(p.s, (ml+len(p.s)-1)/len(p.s))\n }\n sort.Sort(ps)\n s := make([]string, len(ps))\n for i, p := range ps {\n s[i] = p.s\n }\n b, _ := new(big.Int).SetString(strings.Join(s, \"\"), 10)\n return b\n}\n\nfunc main() {\n fmt.Println(li(1, 34, 3, 98, 9, 76, 45, 4))\n fmt.Println(li(54, 546, 548, 60))\n}"} {"title": "Largest number divisible by its digits", "language": "Go from Kotlin", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nfunc divByAll(num int, digits []byte) bool {\n for _, digit := range digits {\n if num%int(digit-'0') != 0 {\n return false\n }\n }\n return true\n}\n\nfunc main() {\n magic := 9 * 8 * 7\n high := 9876432 / magic * magic\n for i := high; i >= magic; i -= magic {\n if i%10 == 0 {\n continue // can't end in '0'\n }\n s := strconv.Itoa(i)\n if strings.ContainsAny(s, \"05\") {\n continue // can't contain '0'or '5'\n }\n var set = make(map[byte]bool)\n var sd []byte // distinct digits\n for _, b := range []byte(s) {\n if !set[b] {\n set[b] = true\n sd = append(sd, b)\n }\n }\n if len(sd) != len(s) {\n continue // digits must be unique\n }\n if divByAll(i, sd) {\n fmt.Println(\"Largest decimal number is\", i)\n return\n }\n }\n}"} {"title": "Largest proper divisor of n", "language": "Go", "task": "a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc largestProperDivisor(n int) int {\n for i := 2; i*i <= n; i++ {\n if n%i == 0 {\n return n / i\n }\n }\n return 1\n}\n\nfunc main() {\n fmt.Println(\"The largest proper divisors for numbers in the interval [1, 100] are:\")\n fmt.Print(\" 1 \")\n for n := 2; n <= 100; n++ {\n if n%2 == 0 {\n fmt.Printf(\"%2d \", n/2)\n } else {\n fmt.Printf(\"%2d \", largestProperDivisor(n))\n }\n if n%10 == 0 {\n fmt.Println()\n }\n }\n}"} {"title": "Last Friday of each month", "language": "Go", "task": "Write a program or a script that returns the date of the last Fridays of each month of a given year. \n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\nExample of an expected output:\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n;Related tasks\n* [[Five weekends]]\n* [[Day of the week]]\n* [[Find the last Sunday of each month]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\ty := time.Now().Year()\n\tif len(os.Args) == 2 {\n\t\tif i, err := strconv.Atoi(os.Args[1]); err == nil {\n\t\t\ty = i\n\t\t}\n\t}\n\tfor m := time.January; m <= time.December; m++ {\n\t\td := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour)\n\t\td = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour)\n\t\tfmt.Println(d.Format(\"2006-01-02\"))\n\t}\n}"} {"title": "Last letter-first letter", "language": "Go", "task": "A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar pokemon = `audino bagon baltoy...67 names omitted...`\n\nfunc main() {\n // split text into slice representing directed graph\n var d []string\n for _, l := range strings.Split(pokemon, \"\\n\") {\n d = append(d, strings.Fields(l)...)\n }\n fmt.Println(\"searching\", len(d), \"names...\")\n // try each name as possible start\n for i := range d {\n d[0], d[i] = d[i], d[0]\n search(d, 1, len(d[0]))\n d[0], d[i] = d[i], d[0]\n }\n fmt.Println(\"maximum path length:\", len(ex))\n fmt.Println(\"paths of that length:\", nMax)\n fmt.Print(\"example path of that length:\")\n for i, n := range ex {\n if i%6 == 0 {\n fmt.Print(\"\\n \")\n }\n fmt.Print(n, \" \")\n }\n fmt.Println()\n}\n\nvar ex []string\nvar nMax int\n\nfunc search(d []string, i, ncPath int) {\n // tally statistics\n if i == len(ex) {\n nMax++\n } else if i > len(ex) {\n nMax = 1\n ex = append(ex[:0], d[:i]...)\n }\n // recursive search\n lastName := d[i-1]\n lastChar := lastName[len(lastName)-1]\n for j := i; j < len(d); j++ {\n if d[j][0] == lastChar {\n d[i], d[j] = d[j], d[i]\n search(d, i+1, ncPath+1+len(d[i]))\n d[i], d[j] = d[j], d[i]\n }\n }\n}"} {"title": "Latin Squares in reduced form", "language": "Go", "task": "A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.\n\nFor a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.\n\nDemonstrate by:\n* displaying the four reduced Latin Squares of order 4.\n* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\ntype matrix [][]int\n\n// generate derangements of first n numbers, with 'start' in first place.\nfunc dList(n, start int) (r matrix) {\n start-- // use 0 basing\n a := make([]int, n)\n for i := range a {\n a[i] = i\n }\n a[0], a[start] = start, a[0]\n sort.Ints(a[1:])\n first := a[1]\n // recursive closure permutes a[1:]\n var recurse func(last int)\n recurse = func(last int) {\n if last == first {\n // bottom of recursion. you get here once for each permutation.\n // test if permutation is deranged.\n for j, v := range a[1:] { // j starts from 0, not 1\n if j+1 == v {\n return // no, ignore it\n }\n }\n // yes, save a copy\n b := make([]int, n)\n copy(b, a)\n for i := range b {\n b[i]++ // change back to 1 basing\n }\n r = append(r, b)\n return\n }\n for i := last; i >= 1; i-- {\n a[i], a[last] = a[last], a[i]\n recurse(last - 1)\n a[i], a[last] = a[last], a[i]\n }\n }\n recurse(n - 1)\n return\n}\n\nfunc reducedLatinSquare(n int, echo bool) uint64 {\n if n <= 0 {\n if echo {\n fmt.Println(\"[]\\n\")\n }\n return 0\n } else if n == 1 {\n if echo {\n fmt.Println(\"[1]\\n\")\n }\n return 1\n }\n rlatin := make(matrix, n)\n for i := 0; i < n; i++ {\n rlatin[i] = make([]int, n)\n }\n // first row\n for j := 0; j < n; j++ {\n rlatin[0][j] = j + 1\n }\n\n count := uint64(0)\n // recursive closure to compute reduced latin squares and count or print them\n var recurse func(i int)\n recurse = func(i int) {\n rows := dList(n, i) // get derangements of first n numbers, with 'i' first.\n outer:\n for r := 0; r < len(rows); r++ {\n copy(rlatin[i-1], rows[r])\n for k := 0; k < i-1; k++ {\n for j := 1; j < n; j++ {\n if rlatin[k][j] == rlatin[i-1][j] {\n if r < len(rows)-1 {\n continue outer\n } else if i > 2 {\n return\n }\n }\n }\n }\n if i < n {\n recurse(i + 1)\n } else {\n count++\n if echo {\n printSquare(rlatin, n)\n }\n }\n }\n return\n }\n\n // remaining rows\n recurse(2)\n return count\n}\n\nfunc printSquare(latin matrix, n int) {\n for i := 0; i < n; i++ {\n fmt.Println(latin[i])\n }\n fmt.Println()\n}\n\nfunc factorial(n uint64) uint64 {\n if n == 0 {\n return 1\n }\n prod := uint64(1)\n for i := uint64(2); i <= n; i++ {\n prod *= i\n }\n return prod\n}\n\nfunc main() {\n fmt.Println(\"The four reduced latin squares of order 4 are:\\n\")\n reducedLatinSquare(4, true)\n\n fmt.Println(\"The size of the set of reduced latin squares for the following orders\")\n fmt.Println(\"and hence the total number of latin squares of these orders are:\\n\")\n for n := uint64(1); n <= 6; n++ {\n size := reducedLatinSquare(int(n), false)\n f := factorial(n - 1)\n f *= f * n * size\n fmt.Printf(\"Order %d: Size %-4d x %d! x %d! => Total %d\\n\", n, size, n, n-1, f)\n }\n}"} {"title": "Law of cosines - triples", "language": "Go", "task": "The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype triple struct{ a, b, c int }\n\nvar squares13 = make(map[int]int, 13)\nvar squares10000 = make(map[int]int, 10000)\n\nfunc init() {\n for i := 1; i <= 13; i++ {\n squares13[i*i] = i\n }\n for i := 1; i <= 10000; i++ {\n squares10000[i*i] = i\n }\n}\n\nfunc solve(angle, maxLen int, allowSame bool) []triple {\n var solutions []triple\n for a := 1; a <= maxLen; a++ {\n for b := a; b <= maxLen; b++ {\n lhs := a*a + b*b\n if angle != 90 {\n switch angle {\n case 60:\n lhs -= a * b\n case 120:\n lhs += a * b\n default:\n panic(\"Angle must be 60, 90 or 120 degrees\")\n }\n }\n switch maxLen {\n case 13:\n if c, ok := squares13[lhs]; ok {\n if !allowSame && a == b && b == c {\n continue\n }\n solutions = append(solutions, triple{a, b, c})\n }\n case 10000:\n if c, ok := squares10000[lhs]; ok {\n if !allowSame && a == b && b == c {\n continue\n }\n solutions = append(solutions, triple{a, b, c})\n }\n default:\n panic(\"Maximum length must be either 13 or 10000\")\n }\n }\n }\n return solutions\n}\n\nfunc main() {\n fmt.Print(\"For sides in the range [1, 13] \")\n fmt.Println(\"where they can all be of the same length:-\\n\")\n angles := []int{90, 60, 120}\n var solutions []triple\n for _, angle := range angles {\n solutions = solve(angle, 13, true)\n fmt.Printf(\" For an angle of %d degrees\", angle)\n fmt.Println(\" there are\", len(solutions), \"solutions, namely:\")\n fmt.Printf(\" %v\\n\", solutions)\n fmt.Println()\n }\n fmt.Print(\"For sides in the range [1, 10000] \")\n fmt.Println(\"where they cannot ALL be of the same length:-\\n\")\n solutions = solve(60, 10000, false)\n fmt.Print(\" For an angle of 60 degrees\")\n fmt.Println(\" there are\", len(solutions), \"solutions.\")\n}"} {"title": "Least common multiple", "language": "Go", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n m.SetString(\"2562047788015215500854906332309589561\", 10)\n n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}"} {"title": "Left factorials", "language": "Go", "task": "'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: \n:::::::* !''n''` \n:::::::* !''n'' \n:::::::* ''n''! \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':\n\n::::: !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* zero through ten (inclusive)\n* 20 through 110 (inclusive) by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* 1,000 through 10,000 (inclusive), by thousands.\n\n\n;Also see:\n* The OEIS entry: A003422 left factorials\n* The MathWorld entry: left factorial\n* The MathWorld entry: factorial sums\n* The MathWorld entry: subfactorial\n\n\n;Related task:\n* permutations/derangements (subfactorials)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n fmt.Print(\"!0 through !10: 0\")\n one := big.NewInt(1)\n n := big.NewInt(1)\n f := big.NewInt(1)\n l := big.NewInt(1)\n next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }\n for ; ; next() {\n fmt.Print(\" \", l)\n if n.Int64() == 10 {\n break\n }\n }\n fmt.Println()\n for {\n for i := 0; i < 10; i++ {\n next()\n }\n fmt.Printf(\"!%d: %d\\n\", n, l)\n if n.Int64() == 110 {\n break\n }\n }\n fmt.Println(\"Lengths of !1000 through !10000 by thousands:\")\n for i := 110; i < 1000; i++ {\n next()\n }\n for {\n fmt.Print(\" \", len(l.String()))\n if n.Int64() == 10000 {\n break\n }\n for i := 0; i < 1000; i++ {\n next()\n }\n }\n fmt.Println()\n}"} {"title": "Levenshtein distance", "language": "Go", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n fmt.Println(ld(\"kitten\", \"sitting\"))\n}\n\nfunc ld(s, t string) int {\n d := make([][]int, len(s)+1)\n for i := range d {\n d[i] = make([]int, len(t)+1)\n }\n for i := range d {\n d[i][0] = i\n }\n for j := range d[0] {\n d[0][j] = j\n }\n for j := 1; j <= len(t); j++ {\n for i := 1; i <= len(s); i++ {\n if s[i-1] == t[j-1] {\n d[i][j] = d[i-1][j-1]\n } else {\n min := d[i-1][j]\n if d[i][j-1] < min {\n min = d[i][j-1]\n }\n if d[i-1][j-1] < min {\n min = d[i-1][j-1]\n }\n d[i][j] = min + 1\n }\n }\n\n }\n return d[len(s)][len(t)]\n}"} {"title": "Levenshtein distance", "language": "Go from C", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc levenshtein(s, t string) int {\n if s == \"\" { return len(t) }\n if t == \"\" { return len(s) }\n if s[0] == t[0] {\n return levenshtein(s[1:], t[1:])\n }\n a := levenshtein(s[1:], t[1:])\n b := levenshtein(s, t[1:])\n c := levenshtein(s[1:], t)\n if a > b { a = b }\n if a > c { a = c }\n return a + 1\n}\n\nfunc main() {\n s1 := \"rosettacode\"\n s2 := \"raisethysword\"\n fmt.Printf(\"distance between %s and %s: %d\\n\", s1, s2,\n levenshtein(s1, s2))\n}"} {"title": "List rooted trees", "language": "Go from C", "task": "You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.\n\nIf we use a matching pair of parentheses to represent a bag, the ways are:\n\nFor 1 bag, there's one way:\n ()\t<- a bag\n\nfor 2 bags, there's one way:\n (())\t<- one bag in another\n\nfor 3 bags, there are two:\n ((())) <- 3 bags nested Russian doll style\n (()()) <- 2 bags side by side, inside the third\n\nfor 4 bags, four:\n (()()())\n ((())())\n ((()()))\n (((())))\n\nNote that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.\n\nIt's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.\n\nThis task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.\n\nAs an example output, run 5 bags. There should be 9 ways.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n)\n\ntype tree uint64\n\nvar (\n list []tree\n offset = [32]uint{1: 1}\n)\n\nfunc add(t tree) {\n list = append(list, 1|t<<1)\n}\n\nfunc show(t tree, l uint) {\n for ; l > 0; t >>= 1 {\n l--\n var paren byte\n if (t & 1) != 0 {\n paren = '('\n } else {\n paren = ')'\n }\n fmt.Printf(\"%c\", paren)\n }\n}\n\nfunc listTrees(n uint) {\n for i := offset[n]; i < offset[n+1]; i++ {\n show(list[i], n*2)\n fmt.Println()\n }\n}\n\n/* assemble tree from subtrees\nn: length of tree we want to make\nt: assembled parts so far\nsl: length of subtree we are looking at\npos: offset of subtree we are looking at\nrem: remaining length to be put together\n*/\n\nfunc assemble(n uint, t tree, sl, pos, rem uint) {\n if rem == 0 {\n add(t)\n return\n }\n\n if sl > rem { // need smaller sub-trees\n sl = rem\n pos = offset[sl]\n } else if pos >= offset[sl+1] {\n // used up sl-trees, try smaller ones\n sl--\n if sl == 0 {\n return\n }\n pos = offset[sl]\n }\n\n assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)\n assemble(n, t, sl, pos+1, rem)\n}\n\nfunc mktrees(n uint) {\n if offset[n+1] > 0 {\n return\n }\n if n > 0 {\n mktrees(n - 1)\n }\n\n assemble(n, 0, n-1, offset[n-1], n-1)\n offset[n+1] = uint(len(list))\n}\n\nfunc main() {\n if len(os.Args) != 2 {\n log.Fatal(\"There must be exactly 1 command line argument\")\n }\n n, err := strconv.Atoi(os.Args[1])\n if err != nil {\n log.Fatal(\"Argument is not a valid number\")\n }\n if n <= 0 || n > 19 { // stack overflow for n == 20\n n = 5\n }\n // init 1-tree\n add(0)\n\n mktrees(uint(n))\n fmt.Fprintf(os.Stderr, \"Number of %d-trees: %d\\n\", n, offset[n+1]-offset[n])\n listTrees(uint(n))\n}"} {"title": "Long literals, with continuations", "language": "Go", "task": "This task is about writing a computer program that has long literals (character\nliterals that may require specifying the words/tokens on more than one (source)\nline, either with continuations or some other method, such as abutments or\nconcatenations (or some other mechanisms).\n\n\nThe literal is to be in the form of a \"list\", a literal that contains many\nwords (tokens) separated by a blank (space), in this case (so as to have a\ncommon list), the (English) names of the chemical elements of the periodic table.\n\n\nThe list is to be in (ascending) order of the (chemical) element's atomic number:\n\n ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''\n\n... up to the last known (named) chemical element (at this time).\n\n\nDo not include any of the \"unnamed\" chemical element names such as:\n\n ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''\n\n\nTo make computer programming languages comparable, the statement widths should be\nrestricted to less than '''81''' bytes (characters), or less\nif a computer programming language has more restrictive limitations or standards.\n\nAlso mention what column the programming statements can start in if ''not'' \nin column one.\n\n\nThe list ''may'' have leading/embedded/trailing blanks during the\ndeclaration (the actual program statements), this is allow the list to be\nmore readable. The \"final\" list shouldn't have any leading/trailing or superfluous\nblanks (when stored in the program's \"memory\").\n\nThis list should be written with the idea in mind that the\nprogram ''will'' be updated, most likely someone other than the\noriginal author, as there will be newer (discovered) elements of the periodic\ntable being added (possibly in the near future). These future updates\nshould be one of the primary concerns in writing these programs and it should be \"easy\"\nfor someone else to add chemical elements to the list (within the computer\nprogram).\n\nAttention should be paid so as to not exceed the ''clause length'' of\ncontinued or specified statements, if there is such a restriction. If the\nlimit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.\n\n\n;Task:\n:* Write a computer program (by whatever name) to contain a list of the known elements.\n:* The program should eventually contain a long literal of words (the elements).\n:* The literal should show how one could create a long list of blank-delineated words.\n:* The \"final\" (stored) list should only have a single blank between elements.\n:* Try to use the most idiomatic approach(es) in creating the final list.\n:* Use continuation if possible, and/or show alternatives (possibly using concatenation).\n:* Use a program comment to explain what the continuation character is if it isn't obvious.\n:* The program should contain a variable that has the date of the last update/revision.\n:* The program, when run, should display with verbiage:\n:::* The last update/revision date (and should be unambiguous).\n:::* The number of chemical elements in the list.\n:::* The name of the highest (last) element name.\n\n\nShow all output here, on this page.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"regexp\"\n \"strings\"\n)\n\n// Uses a 'raw string literal' which is a character sequence enclosed in back quotes.\n// Within the quotes any character (including new line) may appear except\n// back quotes themselves.\nvar elements = `\n hydrogen helium lithium beryllium\n boron carbon nitrogen oxygen\n fluorine neon sodium magnesium\n aluminum silicon phosphorous sulfur\n chlorine argon potassium calcium\n scandium titanium vanadium chromium\n manganese iron cobalt nickel\n copper zinc gallium germanium\n arsenic selenium bromine krypton\n rubidium strontium yttrium zirconium\n niobium molybdenum technetium ruthenium\n rhodium palladium silver cadmium\n indium tin antimony tellurium\n iodine xenon cesium barium\n lanthanum cerium praseodymium neodymium\n promethium samarium europium gadolinium\n terbium dysprosium holmium erbium\n thulium ytterbium lutetium hafnium\n tantalum tungsten rhenium osmium\n iridium platinum gold mercury\n thallium lead bismuth polonium\n astatine radon francium radium\n actinium thorium protactinium uranium\n neptunium plutonium americium curium\n berkelium californium einsteinium fermium\n mendelevium nobelium lawrencium rutherfordium\n dubnium seaborgium bohrium hassium\n meitnerium darmstadtium roentgenium copernicium\n nihonium flerovium moscovium livermorium\n tennessine oganesson\n`\n\nfunc main() {\n lastRevDate := \"March 24th, 2020\"\n re := regexp.MustCompile(`\\s+`) // split on one or more whitespace characters\n els := re.Split(strings.TrimSpace(elements), -1)\n numEls := len(els)\n // Recombine as a single string with elements separated by a single space.\n elements2 := strings.Join(els, \" \")\n // Required output.\n fmt.Println(\"Last revision Date: \", lastRevDate)\n fmt.Println(\"Number of elements: \", numEls)\n // The compiler complains that 'elements2' is unused if we don't use\n // something like this to get the last element rather than just els[numEls-1].\n lix := strings.LastIndex(elements2, \" \") // get index of last space\n fmt.Println(\"Last element : \", elements2[lix+1:])\n}"} {"title": "Long year", "language": "Go", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc main() {\n centuries := []string{\"20th\", \"21st\", \"22nd\"}\n starts := []int{1900, 2000, 2100} \n for i := 0; i < len(centuries); i++ {\n var longYears []int\n fmt.Printf(\"\\nLong years in the %s century:\\n\", centuries[i])\n for j := starts[i]; j < starts[i] + 100; j++ {\n t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)\n if _, week := t.ISOWeek(); week == 53 {\n longYears = append(longYears, j)\n }\n }\n fmt.Println(longYears)\n }\n}"} {"title": "Longest common subsequence", "language": "Go from Java", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "func lcs(a, b string) string {\n\tarunes := []rune(a)\n\tbrunes := []rune(b)\n\taLen := len(arunes)\n\tbLen := len(brunes)\n\tlengths := make([][]int, aLen+1)\n\tfor i := 0; i <= aLen; i++ {\n\t\tlengths[i] = make([]int, bLen+1)\n\t}\n\t// row 0 and column 0 are initialized to 0 already\n\n\tfor i := 0; i < aLen; i++ {\n\t\tfor j := 0; j < bLen; j++ {\n\t\t\tif arunes[i] == brunes[j] {\n\t\t\t\tlengths[i+1][j+1] = lengths[i][j] + 1\n\t\t\t} else if lengths[i+1][j] > lengths[i][j+1] {\n\t\t\t\tlengths[i+1][j+1] = lengths[i+1][j]\n\t\t\t} else {\n\t\t\t\tlengths[i+1][j+1] = lengths[i][j+1]\n\t\t\t}\n\t\t}\n\t}\n\n\t// read the substring out from the matrix\n\ts := make([]rune, 0, lengths[aLen][bLen])\n\tfor x, y := aLen, bLen; x != 0 && y != 0; {\n\t\tif lengths[x][y] == lengths[x-1][y] {\n\t\t\tx--\n\t\t} else if lengths[x][y] == lengths[x][y-1] {\n\t\t\ty--\n\t\t} else {\n\t\t\ts = append(s, arunes[x-1])\n\t\t\tx--\n\t\t\ty--\n\t\t}\n\t}\n\t// reverse string\n\tfor i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {\n\t\ts[i], s[j] = s[j], s[i]\n\t}\n\treturn string(s)\n}"} {"title": "Longest common substring", "language": "Go from C#", "task": "Write a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*Generalize Suffix Tree\n*[[Ukkonen's Suffix Tree Construction]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc lcs(a, b string) (output string) {\n lengths := make([]int, len(a)*len(b))\n greatestLength := 0\n for i, x := range a {\n for j, y := range b {\n if x == y {\n if i == 0 || j == 0 {\n lengths[i*len(b)+j] = 1\n } else {\n lengths[i*len(b)+j] = lengths[(i-1)*len(b)+j-1] + 1\n }\n if lengths[i*len(b)+j] > greatestLength {\n greatestLength = lengths[i*len(b)+j]\n output = a[i-greatestLength+1 : i+1]\n }\n }\n }\n }\n return\n}\n\nfunc main() {\n fmt.Println(lcs(\"thisisatest\", \"testing123testing\"))\n}"} {"title": "Longest increasing subsequence", "language": "Go", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\ntype Node struct {\n val int\n back *Node\n}\n\nfunc lis (n []int) (result []int) {\n var pileTops []*Node\n // sort into piles\n for _, x := range n {\n j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })\n node := &Node{ x, nil }\n if j != 0 { node.back = pileTops[j-1] }\n if j != len(pileTops) {\n pileTops[j] = node\n } else {\n pileTops = append(pileTops, node)\n }\n }\n\n if len(pileTops) == 0 { return []int{} }\n for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {\n result = append(result, node.val)\n }\n // reverse\n for i := 0; i < len(result)/2; i++ {\n result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]\n }\n return\n}\n\nfunc main() {\n for _, d := range [][]int{{3, 2, 6, 4, 5, 1},\n {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {\n fmt.Printf(\"an L.I.S. of %v is %v\\n\", d, lis(d))\n }\n}"} {"title": "Lucky and even lucky numbers", "language": "Go from Kotlin", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n +-------------------+----------------------------------------------------+\n | j | Jth lucky number |\n | j , lucky | Jth lucky number |\n | j , evenLucky | Jth even lucky number |\n | | |\n | j k | Jth through Kth (inclusive) lucky numbers |\n | j k lucky | Jth through Kth (inclusive) lucky numbers |\n | j k evenLucky | Jth through Kth (inclusive) even lucky numbers |\n | | |\n | j -k | all lucky numbers in the range j --> |k| |\n | j -k lucky | all lucky numbers in the range j --> |k| |\n | j -k evenLucky | all even lucky numbers in the range j --> |k| |\n +-------------------+----------------------------------------------------+\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki Lucky numbers.\n* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.\n* Entry lucky numbers on The Eric Weisstein's World of Mathematics.\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\nconst luckySize = 60000\n\nvar luckyOdd = make([]int, luckySize)\nvar luckyEven = make([]int, luckySize)\n\nfunc init() {\n for i := 0; i < luckySize; i++ {\n luckyOdd[i] = i*2 + 1\n luckyEven[i] = i*2 + 2\n }\n}\n\nfunc filterLuckyOdd() {\n for n := 2; n < len(luckyOdd); n++ {\n m := luckyOdd[n-1]\n end := (len(luckyOdd)/m)*m - 1\n for j := end; j >= m-1; j -= m {\n copy(luckyOdd[j:], luckyOdd[j+1:])\n luckyOdd = luckyOdd[:len(luckyOdd)-1]\n }\n }\n}\n\nfunc filterLuckyEven() {\n for n := 2; n < len(luckyEven); n++ {\n m := luckyEven[n-1]\n end := (len(luckyEven)/m)*m - 1\n for j := end; j >= m-1; j -= m {\n copy(luckyEven[j:], luckyEven[j+1:])\n luckyEven = luckyEven[:len(luckyEven)-1]\n }\n }\n}\n\nfunc printSingle(j int, odd bool) error {\n if odd {\n if j >= len(luckyOdd) {\n return fmt.Errorf(\"the argument, %d, is too big\", j)\n }\n fmt.Println(\"Lucky number\", j, \"=\", luckyOdd[j-1])\n } else {\n if j >= len(luckyEven) {\n return fmt.Errorf(\"the argument, %d, is too big\", j)\n }\n fmt.Println(\"Lucky even number\", j, \"=\", luckyEven[j-1])\n }\n return nil\n}\n\nfunc printRange(j, k int, odd bool) error {\n if odd {\n if k >= len(luckyOdd) {\n return fmt.Errorf(\"the argument, %d, is too big\", k)\n }\n fmt.Println(\"Lucky numbers\", j, \"to\", k, \"are:\")\n fmt.Println(luckyOdd[j-1 : k])\n } else {\n if k >= len(luckyEven) {\n return fmt.Errorf(\"the argument, %d, is too big\", k)\n }\n fmt.Println(\"Lucky even numbers\", j, \"to\", k, \"are:\")\n fmt.Println(luckyEven[j-1 : k])\n }\n return nil\n}\n\nfunc printBetween(j, k int, odd bool) error {\n var r []int\n if odd {\n max := luckyOdd[len(luckyOdd)-1]\n if j > max || k > max {\n return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n }\n for _, num := range luckyOdd {\n if num < j {\n continue\n }\n if num > k {\n break\n }\n r = append(r, num)\n }\n fmt.Println(\"Lucky numbers between\", j, \"and\", k, \"are:\")\n fmt.Println(r)\n } else {\n max := luckyEven[len(luckyEven)-1]\n if j > max || k > max {\n return fmt.Errorf(\"at least one argument, %d or %d, is too big\", j, k)\n }\n for _, num := range luckyEven {\n if num < j {\n continue\n }\n if num > k {\n break\n }\n r = append(r, num)\n }\n fmt.Println(\"Lucky even numbers between\", j, \"and\", k, \"are:\")\n fmt.Println(r)\n }\n return nil\n}\n\nfunc main() {\n nargs := len(os.Args)\n if nargs < 2 || nargs > 4 {\n log.Fatal(\"there must be between 1 and 3 command line arguments\")\n }\n filterLuckyOdd()\n filterLuckyEven()\n j, err := strconv.Atoi(os.Args[1])\n if err != nil || j < 1 {\n log.Fatalf(\"first argument, %s, must be a positive integer\", os.Args[1])\n }\n if nargs == 2 {\n if err := printSingle(j, true); err != nil {\n log.Fatal(err)\n }\n return\n }\n\n if nargs == 3 {\n k, err := strconv.Atoi(os.Args[2])\n if err != nil {\n log.Fatalf(\"second argument, %s, must be an integer\", os.Args[2])\n }\n if k >= 0 {\n if j > k {\n log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n }\n if err := printRange(j, k, true); err != nil {\n log.Fatal(err)\n }\n } else {\n l := -k\n if j > l {\n log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n }\n if err := printBetween(j, l, true); err != nil {\n log.Fatal(err)\n }\n }\n return\n }\n\n var odd bool\n switch lucky := strings.ToLower(os.Args[3]); lucky {\n case \"lucky\":\n odd = true\n case \"evenlucky\":\n odd = false\n default:\n log.Fatalf(\"third argument, %s, is invalid\", os.Args[3])\n }\n if os.Args[2] == \",\" {\n if err := printSingle(j, odd); err != nil {\n log.Fatal(err)\n }\n return\n }\n\n k, err := strconv.Atoi(os.Args[2])\n if err != nil {\n log.Fatal(\"second argument must be an integer or a comma\")\n }\n if k >= 0 {\n if j > k {\n log.Fatalf(\"second argument, %d, can't be less than first, %d\", k, j)\n }\n if err := printRange(j, k, odd); err != nil {\n log.Fatal(err)\n }\n } else {\n l := -k\n if j > l {\n log.Fatalf(\"second argument, %d, can't be less in absolute value than first, %d\", k, j)\n }\n if err := printBetween(j, l, odd); err != nil {\n log.Fatal(err)\n }\n }\n}"} {"title": "Lychrel numbers", "language": "Go", "task": "::# Take an integer n, greater than zero.\n::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n.\n::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.\n\n\nThe above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.\n\n\n;Example:\nIf n0 = 12 we get\n\n 12\n 12 + 21 = 33, a palindrome!\n\n\nAnd if n0 = 55 we get\n\n 55\n 55 + 55 = 110\n 110 + 011 = 121, a palindrome!\n\n\nNotice that the check for a palindrome happens ''after'' an addition.\n\n\nSome starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. \n\nThese numbers that do not end in a palindrome are called '''Lychrel numbers'''.\n\nFor the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.\n\n\n;Seed and related Lychrel numbers:\nAny integer produced in the sequence of a Lychrel number is also a Lychrel number.\n\nIn general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:\n\n 196\n 196 + 691 = 887\n 887 + 788 = 1675\n 1675 + 5761 = 7436\n 7436 + 6347 = 13783\n 13783 + 38731 = 52514\n 52514 + 41525 = 94039\n ...\n\n\n 689\n 689 + 986 = 1675\n 1675 + 5761 = 7436\n ...\n\nSo we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. \n\nBecause of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.\n\n\n;Task:\n* Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).\n* Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.\n* Print any seed Lychrel or related number that is itself a palindrome.\n\n\nShow all output here.\n\n\n;References:\n* What's special about 196? Numberphile video.\n* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).\n* Status of the 196 conjecture? Mathoverflow.\n\n", "solution": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"os\"\n)\n\nvar maxRev = big.NewInt(math.MaxUint64 / 10) // approximate\nvar ten = big.NewInt(10)\n\n// Reverse sets `result` to the value of the base ten digits of `v` in\n// reverse order and returns `result`.\n// Only handles positive integers.\nfunc reverseInt(v *big.Int, result *big.Int) *big.Int {\n\tif v.Cmp(maxRev) <= 0 {\n\t\t// optimize small values that fit within uint64\n\t\tresult.SetUint64(reverseUint64(v.Uint64()))\n\t} else {\n\t\tif true {\n\t\t\t// Reverse the string representation\n\t\t\ts := reverseString(v.String())\n\t\t\tresult.SetString(s, 10)\n\t\t} else {\n\t\t\t// This has fewer allocations but is slower:\n\t\t\t// Use a copy of `v` since we mutate it.\n\t\t\tv := new(big.Int).Set(v)\n\t\t\tdigit := new(big.Int)\n\t\t\tresult.SetUint64(0)\n\t\t\tfor v.BitLen() > 0 {\n\t\t\t\tv.QuoRem(v, ten, digit)\n\t\t\t\tresult.Mul(result, ten)\n\t\t\t\tresult.Add(result, digit)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc reverseUint64(v uint64) uint64 {\n\tvar r uint64\n\tfor v > 0 {\n\t\tr *= 10\n\t\tr += v % 10\n\t\tv /= 10\n\t}\n\treturn r\n}\n\nfunc reverseString(s string) string {\n\tb := make([]byte, len(s))\n\tfor i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {\n\t\tb[i] = s[j]\n\t}\n\treturn string(b)\n}\n\nvar known = make(map[string]bool)\n\nfunc Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {\n\tv, r := new(big.Int).SetUint64(n), new(big.Int)\n\treverseInt(v, r)\n\tseen := make(map[string]bool)\n\tisLychrel = true\n\tisSeed = true\n\tfor i := iter; i > 0; i-- {\n\t\tstr := v.String()\n\t\tif seen[str] {\n\t\t\t//log.Println(\"found a loop with\", n, \"at\", str)\n\t\t\tisLychrel = true\n\t\t\tbreak\n\t\t}\n\t\tif ans, ok := known[str]; ok {\n\t\t\t//log.Println(\"already know:\", str, ans)\n\t\t\tisLychrel = ans\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t\tseen[str] = true\n\n\t\tv = v.Add(v, r)\n\t\t//log.Printf(\"%v + %v = %v\\n\", str, r, v)\n\t\treverseInt(v, r)\n\t\tif v.Cmp(r) == 0 {\n\t\t\t//log.Println(v, \"is a palindrome,\", n, \"is not a Lychrel number\")\n\t\t\tisLychrel = false\n\t\t\tisSeed = false\n\t\t\tbreak\n\t\t}\n\t}\n\tfor k := range seen {\n\t\tknown[k] = isLychrel\n\t}\n\t//if isLychrel { log.Printf(\"%v may be a Lychrel number\\n\", n) }\n\treturn isLychrel, isSeed\n}\n\nfunc main() {\n\tmax := flag.Uint64(\"max\", 10000, \"search in the range 1..`N` inclusive\")\n\titer := flag.Uint(\"iter\", 500, \"limit palindrome search to `N` iterations\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Printf(\"Calculating using n = 1..%v and %v iterations:\\n\", *max, *iter)\n\tvar seeds []uint64\n\tvar related int\n\tvar pals []uint64\n\tfor i := uint64(1); i <= *max; i++ {\n\t\tif l, s := Lychrel(i, *iter); l {\n\t\t\tif s {\n\t\t\t\tseeds = append(seeds, i)\n\t\t\t} else {\n\t\t\t\trelated++\n\t\t\t}\n\t\t\tif i == reverseUint64(i) {\n\t\t\t\tpals = append(pals, i)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\" Number of Lychrel seeds:\", len(seeds))\n\tfmt.Println(\" Lychrel seeds:\", seeds)\n\tfmt.Println(\" Number of related:\", related)\n\tfmt.Println(\"Number of Lychrel palindromes:\", len(pals))\n\tfmt.Println(\" Lychrel palindromes:\", pals)\n}"} {"title": "MAC vendor lookup", "language": "Go", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA MAC address that does not return a valid result should return the String \"N/A\". An error related to the network connectivity or the API should return a null result.\n\nMany implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "package main\n\nimport (\n\t\"net/http\"\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\nfunc macLookUp(mac string) (res string){\n\tresp, _ := http.Get(\"http://api.macvendors.com/\" + mac)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tres = string(body)\n\treturn\n}\n\nfunc main() {\n\tfmt.Println(macLookUp(\"FC-A1-3E\"))\n\tfmt.Println(macLookUp(\"FC:FB:FB:01:FA:21\"))\n\tfmt.Println(macLookUp(\"BC:5F:F4\"))\n}\n"} {"title": "Machine code", "language": "Go from C", "task": "The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.\n\nFor example, the following assembly language program is given for x86 (32 bit) architectures:\n\nmov EAX, [ESP+4]\nadd EAX, [ESP+8]\nret\n\nThis would translate into the following opcode bytes:\n139 68 36 4 3 68 36 8 195\n\nOr in hexadecimal:\n8B 44 24 04 03 44 24 08 C3\n\n;Task:\nIf different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:\n\n* Poke the necessary opcodes into a memory location.\n* Provide a means to pass two values to the machine code.\n* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.\n* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\n/*\n#include \n#include \n#include \n#include \n\ntypedef unsigned char byte;\ntypedef byte (*mcfunc) (byte, byte);\n\nvoid runMachineCode(void *buf, byte a, byte b) {\n mcfunc fp = (mcfunc)buf;\n printf(\"%d\\n\", fp(a, b));\n}\n*/\nimport \"C\"\n\nfunc main() {\n code := []byte{\n 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,\n 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,\n 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,\n 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,\n }\n le := len(code)\n buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,\n C.MAP_PRIVATE|C.MAP_ANON, -1, 0)\n codePtr := C.CBytes(code)\n C.memcpy(buf, codePtr, C.size_t(le))\n var a, b byte = 7, 12\n fmt.Printf(\"%d + %d = \", a, b)\n C.runMachineCode(buf, C.byte(a), C.byte(b))\n C.munmap(buf, C.size_t(le))\n C.free(codePtr)\n}"} {"title": "Mad Libs", "language": "Go", "task": "{{wikipedia}}\n\n\nMad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"os\"\n \"regexp\"\n \"strings\"\n)\n\nfunc main() {\n pat := regexp.MustCompile(\"<.+?>\")\n if len(os.Args) != 2 {\n fmt.Println(\"usage: madlib \")\n return\n }\n b, err := ioutil.ReadFile(os.Args[1])\n if err != nil {\n log.Fatal(err)\n }\n tmpl := string(b)\n s := []string{} // patterns in order of appearance\n m := map[string]string{} // mapping from patterns to replacements\n for _, p := range pat.FindAllString(tmpl, -1) {\n if _, ok := m[p]; !ok {\n m[p] = \"\"\n s = append(s, p)\n }\n }\n fmt.Println(\"Enter replacements:\")\n br := bufio.NewReader(os.Stdin)\n for _, p := range s {\n for {\n fmt.Printf(\"%s: \", p[1:len(p)-1])\n r, isPre, err := br.ReadLine()\n if err != nil {\n log.Fatal(err)\n }\n if isPre {\n log.Fatal(\"you're not playing right. :P\")\n }\n s := strings.TrimSpace(string(r))\n if s == \"\" {\n fmt.Println(\" hmm?\")\n continue\n }\n m[p] = s\n break\n }\n }\n fmt.Println(\"\\nYour story:\\n\")\n fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string {\n return m[p]\n }))\n}"} {"title": "Magic 8-ball", "language": "Go from Kotlin", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"math/rand\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\tanswers := [...]string{\n\t\t\"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n\t\t\"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n\t\t\"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n\t\t\"Reply hazy, try again\", \"Ask again later\",\n\t\t\"Better not tell you now\", \"Cannot predict now\",\n\t\t\"Concentrate and ask again\", \"Don't bet on it\",\n\t\t\"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n\t\t\"Very doubtful\",\n\t}\n\tconst prompt = \"\\n? : \"\n\tfmt.Print(\"Please enter your question or a blank line to quit.\\n\" + prompt)\n\tsc := bufio.NewScanner(os.Stdin)\n\tfor sc.Scan() {\n\t\tquestion := sc.Bytes()\n\t\tquestion = bytes.TrimSpace(question)\n\t\tif len(question) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tanswer := answers[rand.Intn(len(answers))]\n\t\tfmt.Printf(\"\\n%s\\n\"+prompt, answer)\n\t}\n\tif err := sc.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}"} {"title": "Magic squares of doubly even order", "language": "Go", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst dimensions int = 8\n\nfunc setupMagicSquareData(d int) ([][]int, error) {\n\tvar output [][]int\n\tif d < 4 || d%4 != 0 {\n\t\treturn [][]int{}, fmt.Errorf(\"Square dimension must be a positive number which is divisible by 4\")\n\t}\n\tvar bits uint = 0x9669 // 0b1001011001101001\n\tsize := d * d\n\tmult := d / 4\n\tfor i, r := 0, 0; r < d; r++ {\n\t\toutput = append(output, []int{})\n\t\tfor c := 0; c < d; i, c = i+1, c+1 {\n\t\t\tbitPos := c/mult + (r/mult)*4\n\t\t\tif (bits & (1 << uint(bitPos))) != 0 {\n\t\t\t\toutput[r] = append(output[r], i+1)\n\t\t\t} else {\n\t\t\t\toutput[r] = append(output[r], size-i)\n\t\t\t}\n\t\t}\n\t}\n\treturn output, nil\n}\n\nfunc arrayItoa(input []int) []string {\n\tvar output []string\n\tfor _, i := range input {\n\t\toutput = append(output, fmt.Sprintf(\"%4d\", i))\n\t}\n\treturn output\n}\n\nfunc main() {\n\tdata, err := setupMagicSquareData(dimensions)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmagicConstant := (dimensions * (dimensions*dimensions + 1)) / 2\n\tfor _, row := range data {\n\t\tfmt.Println(strings.Join(arrayItoa(row), \" \"))\n\t}\n\tfmt.Printf(\"\\nMagic Constant: %d\\n\", magicConstant)\n}\n"} {"title": "Magic squares of odd order", "language": "Go from C", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n)\n\nfunc ms(n int) (int, []int) {\n M := func(x int) int { return (x + n - 1) % n }\n if n <= 0 || n&1 == 0 {\n n = 5\n log.Println(\"forcing size\", n)\n }\n m := make([]int, n*n)\n i, j := 0, n/2\n for k := 1; k <= n*n; k++ {\n m[i*n+j] = k\n if m[M(i)*n+M(j)] != 0 {\n i = (i + 1) % n\n } else {\n i, j = M(i), M(j)\n }\n }\n return n, m\n}\n\nfunc main() {\n n, m := ms(5)\n i := 2\n for j := 1; j <= n*n; j *= 10 {\n i++\n }\n f := fmt.Sprintf(\"%%%dd\", i)\n for i := 0; i < n; i++ {\n for j := 0; j < n; j++ {\n fmt.Printf(f, m[i*n+j])\n }\n fmt.Println()\n }\n}"} {"title": "Magic squares of singly even order", "language": "Go from Java", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n)\n\nfunc magicSquareOdd(n int) ([][]int, error) {\n if n < 3 || n%2 == 0 {\n return nil, fmt.Errorf(\"base must be odd and > 2\")\n }\n value := 1\n gridSize := n * n\n c, r := n/2, 0\n result := make([][]int, n)\n\n for i := 0; i < n; i++ {\n result[i] = make([]int, n)\n }\n\n for value <= gridSize {\n result[r][c] = value\n if r == 0 {\n if c == n-1 {\n r++\n } else {\n r = n - 1\n c++\n }\n } else if c == n-1 {\n r--\n c = 0\n } else if result[r-1][c+1] == 0 {\n r--\n c++\n } else {\n r++\n }\n value++\n }\n return result, nil\n}\n\nfunc magicSquareSinglyEven(n int) ([][]int, error) {\n if n < 6 || (n-2)%4 != 0 {\n return nil, fmt.Errorf(\"base must be a positive multiple of 4 plus 2\")\n }\n size := n * n\n halfN := n / 2\n subSquareSize := size / 4\n subSquare, err := magicSquareOdd(halfN)\n if err != nil {\n return nil, err\n }\n quadrantFactors := [4]int{0, 2, 3, 1}\n result := make([][]int, n)\n\n for i := 0; i < n; i++ {\n result[i] = make([]int, n)\n }\n\n for r := 0; r < n; r++ {\n for c := 0; c < n; c++ {\n quadrant := r/halfN*2 + c/halfN\n result[r][c] = subSquare[r%halfN][c%halfN]\n result[r][c] += quadrantFactors[quadrant] * subSquareSize\n }\n }\n\n nColsLeft := halfN / 2\n nColsRight := nColsLeft - 1\n\n for r := 0; r < halfN; r++ {\n for c := 0; c < n; c++ {\n if c < nColsLeft || c >= n-nColsRight ||\n (c == nColsLeft && r == nColsLeft) {\n if c == 0 && r == nColsLeft {\n continue\n }\n tmp := result[r][c]\n result[r][c] = result[r+halfN][c]\n result[r+halfN][c] = tmp\n }\n }\n }\n return result, nil\n}\n\nfunc main() {\n const n = 6\n msse, err := magicSquareSinglyEven(n)\n if err != nil {\n log.Fatal(err)\n }\n for _, row := range msse {\n for _, x := range row {\n fmt.Printf(\"%2d \", x)\n }\n fmt.Println()\n }\n fmt.Printf(\"\\nMagic constant: %d\\n\", (n*n+1)*n/2)\n}"} {"title": "Map range", "language": "Go", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype rangeBounds struct {\n b1, b2 float64\n}\n\nfunc mapRange(x, y rangeBounds, n float64) float64 {\n return y.b1 + (n - x.b1) * (y.b2 - y.b1) / (x.b2 - x.b1)\n}\n\nfunc main() {\n r1 := rangeBounds{0, 10}\n r2 := rangeBounds{-1, 0}\n for n := float64(0); n <= 10; n += 2 {\n fmt.Println(n, \"maps to\", mapRange(r1, r2, n))\n }\n}"} {"title": "Maximum triangle path sum", "language": "Go", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nconst t = ` 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`\n\nfunc main() {\n lines := strings.Split(t, \"\\n\")\n f := strings.Fields(lines[len(lines)-1])\n d := make([]int, len(f))\n var err error\n for i, s := range f {\n if d[i], err = strconv.Atoi(s); err != nil {\n panic(err)\n }\n }\n d1 := d[1:]\n var l, r, u int\n for row := len(lines) - 2; row >= 0; row-- {\n l = d[0]\n for i, s := range strings.Fields(lines[row]) {\n if u, err = strconv.Atoi(s); err != nil {\n panic(err)\n }\n if r = d1[i]; l > r {\n d[i] = u + l\n } else {\n d[i] = u + r\n }\n l = r\n }\n }\n fmt.Println(d[0])\n}"} {"title": "Mayan calendar", "language": "Go", "task": "The ancient Maya people had two somewhat distinct calendar systems.\n\nIn somewhat simplified terms, one is a cyclical calendar known as '''The Calendar Round''',\nthat meshes several sacred and civil cycles; the other is an offset calendar\nknown as '''The Long Count''', similar in many ways to the Gregorian calendar.\n\n'''The Calendar Round'''\n\n'''The Calendar Round''' has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.\n\n'''The Tzolk'in'''\n\nThe sacred cycle in the Mayan calendar round was called the '''Tzolk'in'''. The '''Tzolk'in''' has a cycle of 20 day names:\n\n Imix'\n Ik'\n Ak'bal\n K'an\n Chikchan\n Kimi\n Manik'\n Lamat\n Muluk\n Ok\n Chuwen\n Eb\n Ben\n Hix\n Men\n K'ib'\n Kaban\n Etz'nab'\n Kawak\n Ajaw\n\nIntermeshed with the named days, the '''Tzolk'in''' has a cycle of 13 numbered days; 1\nthrough 13. Every day has both a number and a name that repeat in a 260 day cycle.\n\nFor example:\n\n 1 Imix'\n 2 Ik'\n 3 Ak'bal\n ...\n 11 Chuwen\n 12 Eb\n 13 Ben\n 1 Hix\n 2 Men\n 3 K'ib'\n ... and so on.\n\n'''The Haab''''\n\nThe Mayan civil calendar is called the '''Haab''''. This calendar has 365 days per\nyear, and is sometimes called the 'vague year.' It is substantially the same as\nour year, but does not make leap year adjustments, so over long periods of time,\ngets out of synchronization with the seasons. It consists of 18 months with 20 days each, \nand the end of the year, a special month of only 5 days, giving a total of 365. \nThe 5 days of the month of '''Wayeb'''' (the last month), are usually considered to be \na time of bad luck.\n\nEach month in the '''Haab'''' has a name. The Mayan names for the civil months are:\n\n Pop\n Wo'\n Sip\n Sotz'\n Sek\n Xul\n Yaxk'in\n Mol\n Ch'en\n Yax\n Sak'\n Keh\n Mak\n K'ank'in\n Muwan\n Pax\n K'ayab\n Kumk'u\n Wayeb' (Short, \"unlucky\" month)\n\nThe months function very much like ours do. That is, for any given month we\ncount through all the days of that month, and then move on to the next month.\n\nNormally, the day '''1 Pop''' is considered the first day of the civil year, just as '''1 January''' \nis the first day of our year. In 2019, '''1 Pop''' falls on '''April 2nd'''. But,\nbecause of the leap year in 2020, '''1 Pop''' falls on '''April 1st''' in the years 2020-2023.\n\nThe only really unusual aspect of the '''Haab'''' calendar is that, although there are\n20 (or 5) days in each month, the last day of the month is not called\nthe 20th (5th). Instead, the last day of the month is referred to as the\n'seating,' or 'putting in place,' of the next month. (Much like how in our\nculture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In\nthe language of the ancient Maya, the word for seating was '''chum''', So you might\nhave:\n\n ...\n 18 Pop (18th day of the first month)\n 19 Pop (19th day of the first month)\n Chum Wo' (20th day of the first month)\n 1 Wo' (1st day of the second month)\n ... and so on.\n\nDates for any particular day are a combination of the '''Tzolk'in''' sacred date,\nand '''Haab'''' civil date. When put together we get the '''\"Calendar Round.\"'''\n\n'''Calendar Round''' dates always have two numbers and two names, and they are\nalways written in the same order:\n\n (1) the day number in the '''Tzolk'in'''\n (2) the day name in the '''Tzolk'in'''\n (3) the day of the month in the '''Haab''''\n (4) the month name in the '''Haab''''\n\nA calendar round is a repeating cycle with a period of just short of 52\nGregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)\n\n'''Lords of the Night'''\n\nA third cycle of nine days honored the nine '''Lords of the Night'''; nine deities\nthat were associated with each day in turn. The names of the nine deities are\nlost; they are now commonly referred to as '''G1''' through '''G9'''. The Lord of the Night\nmay or may not be included in a Mayan date, if it is, it is typically\njust the appropriate '''G(''x'')''' at the end.\n\n'''The Long Count'''\n\nMayans had a separate independent way of measuring time that did not run in\ncycles. (At least, not on normal human scales.) Instead, much like our yearly\ncalendar, each day just gets a little further from the starting point. For the\nancient Maya, the starting point was the 'creation date' of the current world.\nThis date corresponds to our date of August 11, 3114 B.C. Dates are calculated\nby measuring how many days have transpired since this starting date; This is\ncalled '''\"The Long Count.\"''' Rather than just an absolute count of days, the long\ncount is broken up into unit blocks, much like our calendar has months, years,\ndecades and centuries.\n\n The basic unit is a '''k'in''' - one day.\n A 20 day month is a '''winal'''.\n 18 '''winal''' (360 days) is a '''tun''' - sometimes referred to as a short year.\n 20 short years ('''tun''') is a '''k'atun'''\n 20 '''k'atun''' is a '''bak'tun'''\n\nThere are longer units too:\n\n '''Piktun''' == 20 '''Bak'tun''' (8,000 short years)\n '''Kalabtun''' == 20 '''Piktun''' (160,000 short years)\n '''Kinchiltun''' == 20 '''Kalabtun''' (3,200,000 short years)\n\nFor the most part, the Maya only used the blocks of time up to the '''bak'tun'''. One\n'''bak'tun''' is around 394 years, much more than a human life span, so that was all\nthey usually needed to describe dates in this era, or this world. It is worth\nnoting, the two calendars working together allow much more accurate and reliable\nnotation for dates than is available in many other calendar systems; mostly due\nto the pragmatic choice to make the calendar simply track days, rather than\ntrying to make it align with seasons and/or try to conflate it with the notion\nof time.\n\n'''Mayan Date correlations'''\n\nThere is some controversy over finding a correlation point between the Gregorian\nand Mayan calendars. The Gregorian calendar is full of jumps and skips to keep\nthe calendar aligned with the seasons so is much more difficult to work with.\nThe most commonly used correlation\nfactor is The '''GMT: 584283'''. Julian 584283 is a day count corresponding '''Mon, Aug 11, 3114 BCE''' \nin the Gregorian calendar, and the final day in the last Mayan long count\ncycle: 13.0.0.0.0 which is referred to as \"the day of creation\" in the Mayan\ncalendar. There is nothing in known Mayan writing or history that suggests that\na long count \"cycle\" resets ''every'' 13 '''bak'tun'''. Judging by their other practices,\nit would make much more sense for it to reset at 20, if at all.\n\nThe reason there was much interest at all, outside historical scholars, in\nthe Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,\nDec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy\ntheorists to predict a cataclysmic \"end-of-the-world\" scenario.\n\n'''Excerpts taken from, and recommended reading:'''\n\n*''From the website of the Foundation for the Advancement of Meso-America Studies, Inc.'' Pitts, Mark. The complete Writing in Maya Glyphs Book 2 - Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf\n\n*wikipedia: Maya calendar\n\n*wikipedia: Mesoamerican Long Count calendar\n\n\n'''The Task:'''\n\nWrite a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. ''If desired, support other correlations.''\n\nUsing the GMT correlation, the following Gregorian and Mayan dates are equivalent: \n\n '''Dec 21, 2012''' (Gregorian)\n '''4 Ajaw 3 K'ank'in G9''' (Calendar round)\n '''13.0.0.0.0''' (Long count)\n\nSupport looking up dates for at least 50 years before and after the Mayan Long Count '''13 bak'tun''' rollover: ''Dec 21, 2012''. ''(Will require taking into account Gregorian leap days.)''\n\nShow the output here, on this page, for ''at least'' the following dates:\n\n''(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)''\n\n 2004-06-19\n 2012-12-18\n 2012-12-21\n 2019-01-19\n 2019-03-27\n 2020-02-29\n 2020-03-01\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\nvar sacred = strings.Fields(\"Imix\u2019 Ik\u2019 Ak\u2019bal K\u2019an Chikchan Kimi Manik\u2019 Lamat Muluk Ok Chuwen Eb Ben Hix Men K\u2019ib\u2019 Kaban Etz\u2019nab\u2019 Kawak Ajaw\")\n\nvar civil = strings.Fields(\"Pop Wo\u2019 Sip Sotz\u2019 Sek Xul Yaxk\u2019in Mol Ch\u2019en Yax Sak\u2019 Keh Mak K\u2019ank\u2019in Muwan\u2019 Pax K\u2019ayab Kumk\u2019u Wayeb\u2019\")\n\nvar (\n date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC)\n date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC)\n)\n\nfunc tzolkin(date time.Time) (int, string) {\n diff := int(date.Sub(date1).Hours()) / 24\n rem := diff % 13\n if rem < 0 {\n rem = 13 + rem\n }\n var num int\n if rem <= 9 {\n num = rem + 4\n } else {\n num = rem - 9\n }\n rem = diff % 20\n if rem <= 0 {\n rem = 20 + rem\n }\n return num, sacred[rem-1]\n}\n\nfunc haab(date time.Time) (string, string) {\n diff := int(date.Sub(date2).Hours()) / 24\n rem := diff % 365\n if rem < 0 {\n rem = 365 + rem\n }\n month := civil[(rem+1)/20]\n last := 20\n if month == \"Wayeb\u2019\" {\n last = 5\n }\n d := rem%20 + 1\n if d < last {\n return strconv.Itoa(d), month\n }\n return \"Chum\", month\n}\n\nfunc longCount(date time.Time) string {\n diff := int(date.Sub(date1).Hours()) / 24\n diff += 13 * 400 * 360\n baktun := diff / (400 * 360)\n diff %= 400 * 360\n katun := diff / (20 * 360)\n diff %= 20 * 360\n tun := diff / 360\n diff %= 360\n winal := diff / 20\n kin := diff % 20\n return fmt.Sprintf(\"%d.%d.%d.%d.%d\", baktun, katun, tun, winal, kin) \n}\n\nfunc lord(date time.Time) string {\n diff := int(date.Sub(date1).Hours()) / 24\n rem := diff % 9\n if rem <= 0 {\n rem = 9 + rem\n }\n return fmt.Sprintf(\"G%d\", rem)\n}\n\nfunc main() {\n const shortForm = \"2006-01-02\"\n dates := []string{\n \"2004-06-19\",\n \"2012-12-18\",\n \"2012-12-21\",\n \"2019-01-19\",\n \"2019-03-27\",\n \"2020-02-29\",\n \"2020-03-01\",\n \"2071-05-16\",\n }\n fmt.Println(\" Gregorian Tzolk\u2019in Haab\u2019 Long Lord of\")\n fmt.Println(\" Date # Name Day Month Count the Night\")\n fmt.Println(\"---------- -------- ------------- -------------- ---------\")\n for _, dt := range dates {\n date, _ := time.Parse(shortForm, dt)\n n, s := tzolkin(date)\n d, m := haab(date)\n lc := longCount(date)\n l := lord(date)\n fmt.Printf(\"%s %2d %-8s %4s %-9s %-14s %s\\n\", dt, n, s, d, m, lc, l)\n }\n}"} {"title": "McNuggets problem", "language": "Go", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc mcnugget(limit int) {\n sv := make([]bool, limit+1) // all false by default\n for s := 0; s <= limit; s += 6 {\n for n := s; n <= limit; n += 9 {\n for t := n; t <= limit; t += 20 {\n sv[t] = true\n }\n }\n }\n for i := limit; i >= 0; i-- {\n if !sv[i] {\n fmt.Println(\"Maximum non-McNuggets number is\", i)\n return\n }\n }\n}\n\nfunc main() {\n mcnugget(100)\n}"} {"title": "Memory layout of a data structure", "language": "Go", "task": "It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.\n Pin Settings for Plug\n (Reverse order for socket.)\n __________________________________________\n 1 2 3 4 5 6 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20 21 22 23 24 25\n _________________\n 1 2 3 4 5\n 6 7 8 9\n 25 pin 9 pin\n 1 - PG Protective ground\n 2 - TD Transmitted data 3\n 3 - RD Received data 2\n 4 - RTS Request to send 7\n 5 - CTS Clear to send 8\n 6 - DSR Data set ready 6\n 7 - SG Signal ground 5\n 8 - CD Carrier detect 1\n 9 - + voltage (testing)\n 10 - - voltage (testing)\n 11 -\n 12 - SCD Secondary CD\n 13 - SCS Secondary CTS\n 14 - STD Secondary TD\n 15 - TC Transmit clock\n 16 - SRD Secondary RD\n 17 - RC Receiver clock\n 18 -\n 19 - SRS Secondary RTS \n 20 - DTR Data terminal ready 4\n 21 - SQD Signal quality detector\n 22 - RI Ring indicator 9\n 23 - DRS Data rate select\n 24 - XTC External clock\n 25 -\n", "solution": "package main\n\nimport \"fmt\"\n\ntype rs232p9 uint16\n\nconst (\n\tCD9 rs232p9 = 1 << iota // Carrier detect\n\tRD9 // Received data\n\tTD9 // Transmitted data\n\tDTR9 // Data terminal ready\n\tSG9 // signal ground\n\tDSR9 // Data set ready\n\tRTS9 // Request to send\n\tCTS9 // Clear to send\n\tRI9 // Ring indicator\n)\n\nfunc main() {\n\t// set some nonsense bits just for example\n\tp := RI9 | TD9 | CD9\n\tfmt.Printf(\"Type=%T value=%#04x\\n\", p, p)\n}"} {"title": "Metallic ratios", "language": "Go", "task": "Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series\nof related ratios that are referred to as the \"'''Metallic ratios'''\".\n\nThe '''Golden ratio''' was discovered and named by ancient civilizations as it was\nthought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was\nalso known to the early Greeks, though was not named so until later as a nod to\nthe '''Golden ratio''' to which it is closely related. The series has been extended to\nencompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').\n''Somewhat incongruously as the original Golden ratio referred to the adjective \"golden\" rather than the metal \"gold\".''\n\n'''Metallic ratios''' are the real roots of the general form equation:\n\n x2 - bx - 1 = 0 \n\nwhere the integer '''b''' determines which specific one it is.\n\nUsing the quadratic equation:\n\n ( -b +- (b2 - 4ac) ) / 2a = x \n\nSubstitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:\n\n ( b +- (b2 + 4) ) ) / 2 = x \n\nWe only want the real root:\n\n ( b + (b2 + 4) ) ) / 2 = x \n\nWhen we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.\n\n ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... \n\nWith '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.\n\n ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... \n\nWhen the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''\nare sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as\nstandard. After that there isn't really any attempt at standardized names. They\nare given names here on this page, but consider the names fanciful rather than\ncanonical.\n\nNote that technically, '''b''' can be '''0''' for a \"smaller\" ratio than the '''Golden ratio'''.\nWe will refer to it here as the '''Platinum ratio''', though it is kind-of a\ndegenerate case.\n\n'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:\n\n [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] \n\n\nSo, The first ten '''Metallic ratios''' are:\n\n:::::: {| class=\"wikitable\" style=\"text-align: center;\"\n|+ Metallic ratios\n!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link\n|-\n|Platinum||0||(0 + 4) / 2|| 1||-||-\n|-\n|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]\n|-\n|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]\n|-\n|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]\n|-\n|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]\n|-\n|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]\n|-\n|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]\n|-\n|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]\n|-\n|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]\n|-\n|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]\n|}\n\n\n\n\nThere are other ways to find the '''Metallic ratios'''; one, (the focus of this task)\nis through '''successive approximations of Lucas sequences'''.\n\nA traditional '''Lucas sequence''' is of the form:\n\n x''n'' = P * x''n-1'' - Q * x''n-2''\n\nand starts with the first 2 values '''0, 1'''. \n\nFor our purposes in this task, to find the metallic ratios we'll use the form:\n\n x''n'' = b * x''n-1'' + x''n-2''\n\n( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid \"divide by zero\" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' \n\nAt any rate, when '''b = 1''' we get:\n\n x''n'' = x''n-1'' + x''n-2''\n\n 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...\n\nmore commonly known as the Fibonacci sequence.\n\nWhen '''b = 2''':\n\n x''n'' = 2 * x''n-1'' + x''n-2''\n\n 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...\n\n\nAnd so on.\n\n\nTo find the ratio by successive approximations, divide the ('''n+1''')th term by the\n'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.\n\nFor '''b = 1''' (Fibonacci sequence):\n\n 1/1 = 1\n 2/1 = 2\n 3/2 = 1.5\n 5/3 = 1.666667\n 8/5 = 1.6\n 13/8 = 1.625\n 21/13 = 1.615385\n 34/21 = 1.619048\n 55/34 = 1.617647\n 89/55 = 1.618182\n etc.\n\nIt converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest\npossible convergence for any irrational number.\n\n\n;Task\n\nFor each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':\n\n* Generate the corresponding \"Lucas\" sequence.\n* Show here, on this page, at least the first '''15''' elements of the \"Lucas\" sequence.\n* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.\n* Show the '''value''' of the '''approximation''' at the required accuracy.\n* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).\n\nOptional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.\n\nYou may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.\n\n;See also\n* Wikipedia: Metallic mean\n* Wikipedia: Lucas sequence\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nvar names = [10]string{\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\",\n \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\"}\n\nfunc lucas(b int64) {\n fmt.Printf(\"Lucas sequence for %s ratio, where b = %d:\\n\", names[b], b)\n fmt.Print(\"First 15 elements: \")\n var x0, x1 int64 = 1, 1\n fmt.Printf(\"%d, %d\", x0, x1)\n for i := 1; i <= 13; i++ {\n x2 := b*x1 + x0\n fmt.Printf(\", %d\", x2)\n x0, x1 = x1, x2\n }\n fmt.Println()\n}\n\nfunc metallic(b int64, dp int) {\n x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)\n ratio := big.NewRat(1, 1)\n iters := 0\n prev := ratio.FloatString(dp)\n for {\n iters++\n x2.Mul(bb, x1)\n x2.Add(x2, x0)\n this := ratio.SetFrac(x2, x1).FloatString(dp)\n if prev == this {\n plural := \"s\"\n if iters == 1 {\n plural = \" \"\n }\n fmt.Printf(\"Value to %d dp after %2d iteration%s: %s\\n\\n\", dp, iters, plural, this)\n return\n }\n prev = this\n x0.Set(x1)\n x1.Set(x2)\n }\n}\n\nfunc main() {\n for b := int64(0); b < 10; b++ {\n lucas(b)\n metallic(b, 32)\n }\n fmt.Println(\"Golden ratio, where b = 1:\")\n metallic(1, 256)\n}"} {"title": "Metaprogramming", "language": "Go", "task": "{{omit from|BBC BASIC}}\nName and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \n\nFor the purposes of this task, \"support for metaprogramming\" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype person struct{\n name string\n age int\n}\n\nfunc copy(p person) person {\n return person{p.name, p.age}\n}\n\nfunc main() {\n p := person{\"Dave\", 40}\n fmt.Println(p)\n q := copy(p)\n fmt.Println(q)\n /*\n is := []int{1, 2, 3}\n it := make([]int, 3)\n copy(it, is)\n */ \n}"} {"title": "Metronome", "language": "Go", "task": "The task is to implement a metronome. \n\nThe metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.\n\nFor the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. \n\nHowever, the playing of the sounds should not interfere with the timing of the metronome.\n\nThe visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. \n\nIf the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar bpm = 72.0 // Beats Per Minute\n\tvar bpb = 4 // Beats Per Bar\n\n\td := time.Duration(float64(time.Minute) / bpm)\n\tfmt.Println(\"Delay:\", d)\n\tt := time.NewTicker(d)\n\ti := 1\n\tfor _ = range t.C {\n\t\ti--\n\t\tif i == 0 {\n\t\t\ti = bpb\n\t\t\tfmt.Printf(\"\\nTICK \")\n\t\t} else {\n\t\t\tfmt.Printf(\"tick \")\n\t\t}\n\t}\n}"} {"title": "Mian-Chowla sequence", "language": "Go", "task": "The Mian-Chowla sequence is an integer sequence defined recursively.\n\n\nMian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc contains(is []int, s int) bool {\n for _, i := range is {\n if s == i {\n return true\n }\n }\n return false\n}\n\nfunc mianChowla(n int) []int {\n mc := make([]int, n)\n mc[0] = 1\n is := []int{2}\n var sum int\n for i := 1; i < n; i++ {\n le := len(is)\n jloop:\n for j := mc[i-1] + 1; ; j++ {\n mc[i] = j\n for k := 0; k <= i; k++ {\n sum = mc[k] + j\n if contains(is, sum) {\n is = is[0:le]\n continue jloop\n }\n is = append(is, sum)\n }\n break\n }\n }\n return mc\n}\n\nfunc main() {\n mc := mianChowla(100)\n fmt.Println(\"The first 30 terms of the Mian-Chowla sequence are:\")\n fmt.Println(mc[0:30])\n fmt.Println(\"\\nTerms 91 to 100 of the Mian-Chowla sequence are:\")\n fmt.Println(mc[90:100])\n}"} {"title": "Middle three digits", "language": "Go", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "package m3_test\n\nimport (\n \"testing\"\n\n \"m3\"\n)\n\nfunc TestPassing(t *testing.T) {\n type s struct {\n i int\n m string\n }\n tcs := []s{\n {123, \"123\"},\n {12345, \"234\"},\n {1234567, \"345\"},\n {987654321, \"654\"},\n {10001, \"000\"},\n {-10001, \"000\"},\n }\n for _, tc := range tcs {\n m, err := m3.Digits(tc.i)\n if err != nil {\n t.Fatalf(\"d(%d) returned %q.\", tc.i, err)\n }\n if m != tc.m {\n t.Fatalf(\"d(%d) expected %q, got %q.\", tc.i, tc.m, m)\n }\n t.Logf(\"d(%d) = %q.\", tc.i, m)\n }\n}\n\nfunc TestFailing(t *testing.T) {\n type s struct {\n i int\n err error\n }\n tcs := []s{\n {1, m3.ErrorLT3},\n {2, m3.ErrorLT3},\n {-1, m3.ErrorLT3},\n {-10, m3.ErrorLT3},\n {2002, m3.ErrorEven},\n {-2002, m3.ErrorEven},\n {0, m3.ErrorLT3},\n }\n for _, tc := range tcs {\n m, err := m3.Digits(tc.i)\n if err == nil {\n t.Fatal(\"d(%d) expected error %q, got non-error %q.\",\n tc.i, tc.err, m)\n }\n if err != tc.err {\n t.Fatal(\"d(d) expected error %q, got %q\", tc.i, tc.err, err)\n }\n t.Logf(\"d(%d) returns %q\", tc.i, err)\n }\n}"} {"title": "Mind boggling card trick", "language": "Go", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (The above two steps complete the swap of '''X''' cards of the \"red\" and \"black\" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nfunc main() {\n // Create pack, half red, half black and shuffle it.\n var pack [52]byte\n for i := 0; i < 26; i++ {\n pack[i] = 'R'\n pack[26+i] = 'B'\n }\n rand.Seed(time.Now().UnixNano())\n rand.Shuffle(52, func(i, j int) {\n pack[i], pack[j] = pack[j], pack[i]\n })\n\n // Deal from pack into 3 stacks.\n var red, black, discard []byte\n for i := 0; i < 51; i += 2 {\n switch pack[i] {\n case 'B':\n black = append(black, pack[i+1])\n case 'R':\n red = append(red, pack[i+1])\n }\n discard = append(discard, pack[i])\n }\n lr, lb, ld := len(red), len(black), len(discard)\n fmt.Println(\"After dealing the cards the state of the stacks is:\")\n fmt.Printf(\" Red : %2d cards -> %c\\n\", lr, red)\n fmt.Printf(\" Black : %2d cards -> %c\\n\", lb, black)\n fmt.Printf(\" Discard: %2d cards -> %c\\n\", ld, discard)\n\n // Swap the same, random, number of cards between the red and black stacks.\n min := lr\n if lb < min {\n min = lb\n }\n n := 1 + rand.Intn(min)\n rp := rand.Perm(lr)[:n]\n bp := rand.Perm(lb)[:n]\n fmt.Printf(\"\\n%d card(s) are to be swapped.\\n\\n\", n)\n fmt.Println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n fmt.Printf(\" Red : %2d\\n\", rp)\n fmt.Printf(\" Black : %2d\\n\", bp)\n for i := 0; i < n; i++ {\n red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]\n }\n fmt.Println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n fmt.Printf(\" Red : %c\\n\", red)\n fmt.Printf(\" Black : %c\\n\", black)\n\n // Check that the number of black cards in the black stack equals\n // the number of red cards in the red stack.\n rcount, bcount := 0, 0\n for _, c := range red {\n if c == 'R' {\n rcount++\n }\n }\n for _, c := range black {\n if c == 'B' {\n bcount++\n }\n }\n\n fmt.Println(\"\\nThe number of red cards in the red stack =\", rcount)\n fmt.Println(\"The number of black cards in the black stack =\", bcount)\n if rcount == bcount {\n fmt.Println(\"So the asssertion is correct!\")\n } else {\n fmt.Println(\"So the asssertion is incorrect!\")\n }\n}"} {"title": "Minimal steps down to 1", "language": "Go", "task": "Given:\n* A starting, positive integer (greater than one), N.\n* A selection of possible integer perfect divisors, D.\n* And a selection of possible subtractors, S.\nThe goal is find the minimum number of steps necessary to reduce N down to one.\n\nAt any step, the number may be:\n* Divided by any member of D if it is perfectly divided by D, (remainder zero).\n* OR have one of S subtracted from it, if N is greater than the member of S.\n\n\nThere may be many ways to reduce the initial N down to 1. Your program needs to:\n* Find the ''minimum'' number of ''steps'' to reach 1.\n* Show '''one''' way of getting fron N to 1 in those minimum steps.\n\n;Examples:\nNo divisors, D. a single subtractor of 1.\n:Obviousely N will take N-1 subtractions of 1 to reach 1\n\nSingle divisor of 2; single subtractor of 1:\n:N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1\n:N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1\n\nDivisors 2 and 3; subtractor 1:\n:N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1\n\n;Task:\nUsing the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:\n\n:1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.\n:2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.\n\nUsing the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:\n\n:3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.\n:4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.\n\n\n;Optional stretch goal:\n:2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000\n\n\n;Reference:\n* Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nconst limit = 50000\n\nvar (\n divs, subs []int\n mins [][]string\n)\n\n// Assumes the numbers are presented in order up to 'limit'.\nfunc minsteps(n int) {\n if n == 1 {\n mins[1] = []string{}\n return\n }\n min := limit\n var p, q int\n var op byte\n for _, div := range divs {\n if n%div == 0 {\n d := n / div\n steps := len(mins[d]) + 1\n if steps < min {\n min = steps\n p, q, op = d, div, '/'\n }\n }\n }\n for _, sub := range subs {\n if d := n - sub; d >= 1 {\n steps := len(mins[d]) + 1\n if steps < min {\n min = steps\n p, q, op = d, sub, '-'\n }\n }\n }\n mins[n] = append(mins[n], fmt.Sprintf(\"%c%d -> %d\", op, q, p))\n mins[n] = append(mins[n], mins[p]...)\n}\n\nfunc main() {\n for r := 0; r < 2; r++ {\n divs = []int{2, 3}\n if r == 0 {\n subs = []int{1}\n } else {\n subs = []int{2}\n }\n mins = make([][]string, limit+1)\n fmt.Printf(\"With: Divisors: %v, Subtractors: %v =>\\n\", divs, subs)\n fmt.Println(\" Minimum number of steps to diminish the following numbers down to 1 is:\")\n for i := 1; i <= limit; i++ {\n minsteps(i)\n if i <= 10 {\n steps := len(mins[i])\n plural := \"s\"\n if steps == 1 {\n plural = \" \"\n }\n fmt.Printf(\" %2d: %d step%s: %s\\n\", i, steps, plural, strings.Join(mins[i], \", \"))\n }\n }\n for _, lim := range []int{2000, 20000, 50000} {\n max := 0\n for _, min := range mins[0 : lim+1] {\n m := len(min)\n if m > max {\n max = m\n }\n }\n var maxs []int\n for i, min := range mins[0 : lim+1] {\n if len(min) == max {\n maxs = append(maxs, i)\n }\n }\n nums := len(maxs)\n verb, verb2, plural := \"are\", \"have\", \"s\"\n if nums == 1 {\n verb, verb2, plural = \"is\", \"has\", \"\"\n }\n fmt.Printf(\" There %s %d number%s in the range 1-%d \", verb, nums, plural, lim)\n fmt.Printf(\"that %s maximum 'minimal steps' of %d:\\n\", verb2, max)\n fmt.Println(\" \", maxs)\n }\n fmt.Println()\n }\n}"} {"title": "Minkowski question-mark function", "language": "Go from FreeBASIC", "task": "The '''Minkowski question-mark function''' converts the continued fraction representation {{math|[a0; a1, a2, a3, ...]}} of a number into a binary decimal representation in which the integer part {{math|a0}} is unchanged and the {{math|a1, a2, ...}} become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place of the first zero. \n\nThus, {{math|?}}(31/7) = 71/16 because 31/7 has the continued fraction representation {{math|[4;2,3]}} giving the binary expansion {{math|4 + 0.01112}}.\n\nAmong its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.\n\nThe question-mark function is continuous and monotonically increasing, so it has an inverse.\n\n* Produce a function for {{math|?(x)}}. Be careful: rational numbers have two possible continued fraction representations:\n:::* {{math|[a0;a1,... an-1,an]}} and \n:::* {{math|[a0;a1,... an-1,an-1,1]}} \n* Choose one of the above that will give a binary expansion ending with a '''1'''.\n* Produce the inverse function {{math|?-1(x)}}\n* Verify that {{math|?(ph)}} = 5/3, where {{math|ph}} is the Greek golden ratio.\n* Verify that {{math|?-1(-5/9)}} = (13 - 7)/6\n* Verify that the two functions are inverses of each other by showing that {{math|?-1(?(x))}}={{math|x}} and {{math|?(?-1(y))}}={{math|y}} for {{math|x, y}} of your choice \n\n\nDon't worry about precision error in the last few digits. \n\n\n;See also:\n* Wikipedia entry: Minkowski's question-mark function\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst MAXITER = 151\n\nfunc minkowski(x float64) float64 {\n if x > 1 || x < 0 {\n return math.Floor(x) + minkowski(x-math.Floor(x))\n }\n p := uint64(x)\n q := uint64(1)\n r := p + 1\n s := uint64(1)\n d := 1.0\n y := float64(p)\n for {\n d = d / 2\n if y+d == y {\n break\n }\n m := p + r\n if m < 0 || p < 0 {\n break\n }\n n := q + s\n if n < 0 {\n break\n }\n if x < float64(m)/float64(n) {\n r = m\n s = n\n } else {\n y = y + d\n p = m\n q = n\n }\n }\n return y + d\n}\n\nfunc minkowskiInv(x float64) float64 {\n if x > 1 || x < 0 {\n return math.Floor(x) + minkowskiInv(x-math.Floor(x))\n }\n if x == 1 || x == 0 {\n return x\n }\n contFrac := []uint32{0}\n curr := uint32(0)\n count := uint32(1)\n i := 0\n for {\n x *= 2\n if curr == 0 {\n if x < 1 {\n count++\n } else {\n i++\n t := contFrac\n contFrac = make([]uint32, i+1)\n copy(contFrac, t)\n contFrac[i-1] = count\n count = 1\n curr = 1\n x--\n }\n } else {\n if x > 1 {\n count++\n x--\n } else {\n i++\n t := contFrac\n contFrac = make([]uint32, i+1)\n copy(contFrac, t)\n contFrac[i-1] = count\n count = 1\n curr = 0\n }\n }\n if x == math.Floor(x) {\n contFrac[i] = count\n break\n }\n if i == MAXITER {\n break\n }\n }\n ret := 1.0 / float64(contFrac[i])\n for j := i - 1; j >= 0; j-- {\n ret = float64(contFrac[j]) + 1.0/ret\n }\n return 1.0 / ret\n}\n\nfunc main() {\n fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)\n fmt.Printf(\"%19.16f %19.16f\\n\", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)\n fmt.Printf(\"%19.16f %19.16f\\n\", minkowski(minkowskiInv(0.718281828)),\n minkowskiInv(minkowski(0.1213141516171819)))\n}"} {"title": "Modified random distribution", "language": "Go from Wren", "task": "Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)\ntaking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier:\nwhile True:\n random1 = rgen()\n random2 = rgen()\n if random2 < modifier(random1):\n answer = random1\n break\n endif\nendwhile\n\n;Task:\n* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:\n modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5) \n* Create a generator of random numbers with probabilities modified by the above function.\n* Generate >= 10,000 random numbers subject to the probability modification.\n* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.\n\n\nShow your output here, on this page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"strings\"\n \"time\"\n)\n\nfunc rng(modifier func(x float64) float64) float64 {\n for {\n r1 := rand.Float64()\n r2 := rand.Float64()\n if r2 < modifier(r1) {\n return r1\n }\n }\n}\n\nfunc commatize(n int) string {\n s := fmt.Sprintf(\"%d\", n)\n if n < 0 {\n s = s[1:]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if n >= 0 {\n return s\n }\n return \"-\" + s\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n modifier := func(x float64) float64 {\n if x < 0.5 {\n return 2 * (0.5 - x)\n }\n return 2 * (x - 0.5)\n }\n const (\n N = 100000\n NUM_BINS = 20\n HIST_CHAR = \"\u25a0\"\n HIST_CHAR_SIZE = 125\n )\n bins := make([]int, NUM_BINS) // all zero by default\n binSize := 1.0 / NUM_BINS\n for i := 0; i < N; i++ {\n rn := rng(modifier)\n bn := int(math.Floor(rn / binSize))\n bins[bn]++\n }\n\n fmt.Println(\"Modified random distribution with\", commatize(N), \"samples in range [0, 1):\\n\")\n fmt.Println(\" Range Number of samples within that range\")\n for i := 0; i < NUM_BINS; i++ {\n hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))\n fi := float64(i)\n fmt.Printf(\"%4.2f ..< %4.2f %s %s\\n\", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))\n }\n}"} {"title": "Modular arithmetic", "language": "Go", "task": "equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// Define enough of a ring to meet the needs of the task. Addition and\n// multiplication are mentioned in the task; multiplicative identity is not\n// mentioned but is useful for the power function.\n\ntype ring interface {\n add(ringElement, ringElement) ringElement\n mul(ringElement, ringElement) ringElement\n mulIdent() ringElement\n}\n\ntype ringElement interface{}\n\n// Define a power function that works for any ring.\n\nfunc ringPow(r ring, a ringElement, p uint) (pow ringElement) {\n for pow = r.mulIdent(); p > 0; p-- {\n pow = r.mul(pow, a)\n }\n return\n}\n\n// The task function f has that constant 1 in it.\n// Define a special kind of ring that has this element.\n\ntype oneRing interface {\n ring\n one() ringElement // return ring element corresponding to '1'\n}\n\n// Now define the required function f.\n// It works for any ring (that has a \"one.\")\n\nfunc f(r oneRing, x ringElement) ringElement {\n return r.add(r.add(ringPow(r, x, 100), x), r.one())\n}\n\n// With rings and the function f defined in a general way, now define\n// the specific ring of integers modulo n.\n\ntype modRing uint // value is congruence modulus n\n\nfunc (m modRing) add(a, b ringElement) ringElement {\n return (a.(uint) + b.(uint)) % uint(m)\n}\n\nfunc (m modRing) mul(a, b ringElement) ringElement {\n return (a.(uint) * b.(uint)) % uint(m)\n}\n\nfunc (modRing) mulIdent() ringElement { return uint(1) }\n\nfunc (modRing) one() ringElement { return uint(1) }\n\n// Demonstrate the general function f on the specific ring with the\n// specific values.\n\nfunc main() {\n fmt.Println(f(modRing(13), uint(10)))\n}"} {"title": "Modular exponentiation", "language": "Go", "task": "Find the last '''40''' decimal digits of a^b, where\n\n::* a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: a^b \\mod m.\n\nThe algorithm must work for any integers a, b, m, where b \\ge 0 and m > 0.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n a, _ := new(big.Int).SetString(\n \"2988348162058574136915891421498819466320163312926952423791023078876139\", 10)\n b, _ := new(big.Int).SetString(\n \"2351399303373464486466122544523690094744975233415544072992656881240319\", 10)\n m := big.NewInt(10)\n r := big.NewInt(40)\n m.Exp(m, r, nil)\n\n r.Exp(a, b, m)\n fmt.Println(r)\n}"} {"title": "Modular inverse", "language": "Go", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\ta := big.NewInt(42)\n\tm := big.NewInt(2017)\n\tk := new(big.Int).ModInverse(a, m)\n\tfmt.Println(k)\n}"} {"title": "Monads/List monad", "language": "Go", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.\n\nThe bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.\n\n\nDemonstrate in your programming language the following:\n\n#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype mlist struct{ value []int }\n\nfunc (m mlist) bind(f func(lst []int) mlist) mlist {\n return f(m.value)\n}\n\nfunc unit(lst []int) mlist {\n return mlist{lst}\n}\n\nfunc increment(lst []int) mlist {\n lst2 := make([]int, len(lst))\n for i, v := range lst {\n lst2[i] = v + 1\n }\n return unit(lst2)\n}\n\nfunc double(lst []int) mlist {\n lst2 := make([]int, len(lst))\n for i, v := range lst {\n lst2[i] = 2 * v\n }\n return unit(lst2)\n}\n\nfunc main() {\n ml1 := unit([]int{3, 4, 5})\n ml2 := ml1.bind(increment).bind(double)\n fmt.Printf(\"%v -> %v\\n\", ml1.value, ml2.value)\n}"} {"title": "Monads/Maybe monad", "language": "Go", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\ntype maybe struct{ value *int }\n\nfunc (m maybe) bind(f func(p *int) maybe) maybe {\n return f(m.value)\n}\n\nfunc unit(p *int) maybe {\n return maybe{p}\n}\n\nfunc decrement(p *int) maybe {\n if p == nil {\n return unit(nil)\n } else {\n q := *p - 1\n return unit(&q)\n }\n}\n\nfunc triple(p *int) maybe {\n if p == nil {\n return unit(nil)\n } else {\n q := (*p) * 3\n return unit(&q)\n }\n}\n\nfunc main() {\n i, j, k := 3, 4, 5\n for _, p := range []*int{&i, &j, nil, &k} {\n m1 := unit(p)\n m2 := m1.bind(decrement).bind(triple)\n var s1, s2 string = \"none\", \"none\"\n if m1.value != nil {\n s1 = strconv.Itoa(*m1.value)\n }\n if m2.value != nil {\n s2 = strconv.Itoa(*m2.value)\n }\n fmt.Printf(\"%4s -> %s\\n\", s1, s2)\n }\n}"} {"title": "Monads/Writer monad", "language": "Go from Kotlin", "task": "The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype mwriter struct {\n value float64\n log string\n}\n\nfunc (m mwriter) bind(f func(v float64) mwriter) mwriter {\n n := f(m.value)\n n.log = m.log + n.log\n return n\n}\n\nfunc unit(v float64, s string) mwriter {\n return mwriter{v, fmt.Sprintf(\" %-17s: %g\\n\", s, v)}\n}\n\nfunc root(v float64) mwriter {\n return unit(math.Sqrt(v), \"Took square root\")\n}\n\nfunc addOne(v float64) mwriter {\n return unit(v+1, \"Added one\")\n}\n\nfunc half(v float64) mwriter {\n return unit(v/2, \"Divided by two\")\n}\n\nfunc main() {\n mw1 := unit(5, \"Initial value\")\n mw2 := mw1.bind(root).bind(addOne).bind(half)\n fmt.Println(\"The Golden Ratio is\", mw2.value)\n fmt.Println(\"\\nThis was derived as follows:-\")\n fmt.Println(mw2.log)\n}"} {"title": "Move-to-front algorithm", "language": "Go from Python", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype symbolTable string\n\nfunc (symbols symbolTable) encode(s string) []byte {\n\tseq := make([]byte, len(s))\n\tpad := []byte(symbols)\n\tfor i, c := range []byte(s) {\n\t\tx := bytes.IndexByte(pad, c)\n\t\tseq[i] = byte(x)\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn seq\n}\n\nfunc (symbols symbolTable) decode(seq []byte) string {\n\tchars := make([]byte, len(seq))\n\tpad := []byte(symbols)\n\tfor i, x := range seq {\n\t\tc := pad[x]\n\t\tchars[i] = c\n\t\tcopy(pad[1:], pad[:x])\n\t\tpad[0] = c\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\tm := symbolTable(\"abcdefghijklmnopqrstuvwxyz\")\n\tfor _, s := range []string{\"broood\", \"bananaaa\", \"hiphophiphop\"} {\n\t\tenc := m.encode(s)\n\t\tdec := m.decode(enc)\n\t\tfmt.Println(s, enc, dec)\n\t\tif dec != s {\n\t\t\tpanic(\"Whoops!\")\n\t\t}\n\t}\n}"} {"title": "Multi-dimensional array", "language": "Go", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype md struct {\n dim []int\n ele []float64\n}\n\nfunc newMD(dim ...int) *md {\n n := 1\n for _, d := range dim {\n n *= d\n }\n return &md{append([]int{}, dim...), make([]float64, n)}\n}\n\nfunc (m *md) index(i ...int) (x int) {\n for d, dx := range m.dim {\n x = x*dx + i[d]\n }\n return\n}\n\nfunc (m *md) at(i ...int) float64 {\n return m.ele[m.index(i...)]\n}\n\nfunc (m *md) set(x float64, i ...int) {\n m.ele[m.index(i...)] = x\n}\n\nfunc (m *md) show(i ...int) {\n fmt.Printf(\"m%d = %g\\n\", i, m.at(i...))\n}\n\nfunc main() {\n m := newMD(5, 4, 3, 2)\n m.show(4, 3, 2, 1)\n m.set(87, 4, 3, 2, 1)\n m.show(4, 3, 2, 1)\n\n for i := 0; i < m.dim[0]; i++ {\n for j := 0; j < m.dim[1]; j++ {\n for k := 0; k < m.dim[2]; k++ {\n for l := 0; l < m.dim[3]; l++ {\n x := m.index(i, j, k, l)\n m.set(float64(x)+.1, i, j, k, l)\n }\n }\n }\n }\n fmt.Println(m.ele[:10])\n fmt.Println(m.ele[len(m.ele)-10:])\n m.show(4, 3, 2, 1)\n}"} {"title": "Multifactorial", "language": "Go", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc multiFactorial(n, k int) int {\n r := 1\n for ; n > 1; n -= k {\n r *= n\n }\n return r\n}\n\nfunc main() {\n for k := 1; k <= 5; k++ {\n fmt.Print(\"degree \", k, \":\")\n for n := 1; n <= 10; n++ {\n fmt.Print(\" \", multiFactorial(n, k))\n }\n fmt.Println()\n }\n}"} {"title": "Multiple distinct objects", "language": "Go", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.\n\nBy ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to \"zero\" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of \"zero\" for that type.\n\nThis task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "func nxm(n, m int) [][]int {\n d1 := make([]int, m)\n d2 := make([][]int, n)\n for i := range d2 {\n d2[i] = d1\n }\n return d2\n}"} {"title": "Multisplit", "language": "Go", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc ms(txt string, sep []string) (ans []string) {\n for txt > \"\" {\n sepMatch := \"\"\n posMatch := len(txt)\n for _, s := range sep {\n if p := strings.Index(txt, s); p >= 0 && p < posMatch {\n sepMatch = s\n posMatch = p\n }\n }\n ans = append(ans, txt[:posMatch])\n txt = txt[posMatch+len(sepMatch):]\n }\n return\n}\n\nfunc main() {\n fmt.Printf(\"%q\\n\", ms(\"a!===b=!=c\", []string{\"==\", \"!=\", \"=\"}))\n}"} {"title": "Munchausen numbers", "language": "Go from Kotlin", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "package main\n\nimport(\n \"fmt\"\n \"math\"\n)\n\nvar powers [10]int\n\nfunc isMunchausen(n int) bool {\n if n < 0 { return false }\n n64 := int64(n)\n nn := n64\n var sum int64 = 0\n for nn > 0 {\n sum += int64(powers[nn % 10])\n if sum > n64 { return false }\n nn /= 10\n }\n return sum == n64\n}\n\nfunc main() {\n // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose\n for i := 1; i <= 9; i++ {\n d := float64(i) \n powers[i] = int(math.Pow(d, d))\n }\n \n // check numbers 0 to 500 million\n fmt.Println(\"The Munchausen numbers between 0 and 500 million are:\")\n for i := 0; i <= 500000000; i++ {\n if isMunchausen(i) { fmt.Printf(\"%d \", i) }\n }\n fmt.Println()\n}"} {"title": "Musical scale", "language": "Go from Sparkling", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "package main\n\nimport (\n \"encoding/binary\"\n \"log\"\n \"math\"\n \"os\"\n \"strings\"\n)\n\nfunc main() {\n const (\n sampleRate = 44100\n duration = 8\n dataLength = sampleRate * duration\n hdrSize = 44\n fileLen = dataLength + hdrSize - 8\n )\n\n // buffers\n buf1 := make([]byte, 1)\n buf2 := make([]byte, 2)\n buf4 := make([]byte, 4)\n\n // WAV header\n var sb strings.Builder\n sb.WriteString(\"RIFF\")\n binary.LittleEndian.PutUint32(buf4, fileLen)\n sb.Write(buf4) // file size - 8\n sb.WriteString(\"WAVE\")\n sb.WriteString(\"fmt \")\n binary.LittleEndian.PutUint32(buf4, 16)\n sb.Write(buf4) // length of format data (= 16)\n binary.LittleEndian.PutUint16(buf2, 1)\n sb.Write(buf2) // type of format (= 1 (PCM))\n sb.Write(buf2) // number of channels (= 1)\n binary.LittleEndian.PutUint32(buf4, sampleRate)\n sb.Write(buf4) // sample rate\n sb.Write(buf4) // sample rate * bps(8) * channels(1) / 8 (= sample rate)\n sb.Write(buf2) // bps(8) * channels(1) / 8 (= 1)\n binary.LittleEndian.PutUint16(buf2, 8)\n sb.Write(buf2) // bits per sample (bps) (= 8)\n sb.WriteString(\"data\")\n binary.LittleEndian.PutUint32(buf4, dataLength)\n sb.Write(buf4) // size of data section\n wavhdr := []byte(sb.String())\n\n // write WAV header\n f, err := os.Create(\"notes.wav\")\n if err != nil {\n log.Fatal(err)\n }\n defer f.Close()\n f.Write(wavhdr)\n\n // compute and write actual data\n freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}\n for j := 0; j < duration; j++ {\n freq := freqs[j]\n omega := 2 * math.Pi * freq\n for i := 0; i < dataLength/duration; i++ {\n y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))\n buf1[0] = byte(math.Round(y))\n f.Write(buf1)\n }\n }\n}"} {"title": "Mutex", "language": "Go from E", "task": "{{requires|Concurrency}}\n\n\nA '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. \nA mutex is said to be seized by a [[task]] decreasing ''k''. \nIt is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. \nA [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.\n\nA mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). \nEntering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. \n\n=Variants of mutexes=\n\n==Global and local mutexes==\nUsually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.\n\n==Reentrant mutex==\nA reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.\n\n==Read write mutex==\nA read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.\n\n=Deadlock prevention=\nThere exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem.\n\n=Sample implementations / APIs=\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sync\"\n \"time\"\n)\n\nvar value int\nvar m sync.Mutex\nvar wg sync.WaitGroup\n\nfunc slowInc() {\n m.Lock()\n v := value\n time.Sleep(1e8)\n value = v+1\n m.Unlock()\n wg.Done()\n}\n\nfunc main() {\n wg.Add(2)\n go slowInc()\n go slowInc()\n wg.Wait()\n fmt.Println(value)\n}"} {"title": "N-queens problem", "language": "Go", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// A fairly literal translation of the example program on the referenced\n// WP page. Well, it happened to be the example program the day I completed\n// the task. It seems from the WP history that there has been some churn\n// in the posted example program. The example program of the day was in\n// Pascal and was credited to Niklaus Wirth, from his \"Algorithms +\n// Data Structures = Programs.\"\npackage main\n \nimport \"fmt\"\n \nvar (\n i int\n q bool\n a [9]bool\n b [17]bool\n c [15]bool // offset by 7 relative to the Pascal version\n x [9]int\n)\n \nfunc try(i int) {\n for j := 1; ; j++ {\n q = false\n if a[j] && b[i+j] && c[i-j+7] {\n x[i] = j\n a[j] = false\n b[i+j] = false\n c[i-j+7] = false\n if i < 8 {\n try(i + 1)\n if !q {\n a[j] = true\n b[i+j] = true\n c[i-j+7] = true\n }\n } else {\n q = true\n }\n }\n if q || j == 8 {\n break\n }\n }\n}\n \nfunc main() {\n for i := 1; i <= 8; i++ {\n a[i] = true\n }\n for i := 2; i <= 16; i++ {\n b[i] = true\n }\n for i := 0; i <= 14; i++ {\n c[i] = true\n }\n try(1)\n if q {\n for i := 1; i <= 8; i++ {\n fmt.Println(i, x[i])\n }\n }\n}"} {"title": "Narcissist", "language": "Go", "task": "Quoting from the Esolangs wiki page:\n\n\nA '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].\n\nA quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a \"1\" or \"accept\" if that string matches its own source code, or a \"0\" or \"reject\" if it does not.\n\n\nFor concreteness, in this task we shall assume that symbol = character. \n\nThe narcissist should be able to cope with any finite input, whatever its length. \n\nAny form of output is allowed, as long as the program always halts, and \"accept\", \"reject\" and \"not yet finished\" are distinguishable.\n\n", "solution": "package main; import \"os\"; import \"fmt\"; import \"bytes\"; import \"io/ioutil\"; func main() {ios := \"os\"; ifmt := \"fmt\"; ibytes := \"bytes\"; iioutil := \"io/ioutil\"; zero := \"Reject\"; one := \"Accept\"; x := \"package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\\n\"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}"} {"title": "Narcissistic decimal number", "language": "Go", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc narc(n int) []int {\n\tpower := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\tlimit := 10\n\tresult := make([]int, 0, n)\n\tfor x := 0; len(result) < n; x++ {\n\t\tif x >= limit {\n\t\t\tfor i := range power {\n\t\t\t\tpower[i] *= i // i^m\n\t\t\t}\n\t\t\tlimit *= 10\n\t\t}\n\t\tsum := 0\n\t\tfor xx := x; xx > 0; xx /= 10 {\n\t\t\tsum += power[xx%10]\n\t\t}\n\t\tif sum == x {\n\t\t\tresult = append(result, x)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(narc(25))\n}"} {"title": "Nautical bell", "language": "Go", "task": "Task\n\nWrite a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.\n\nThe bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.\n\nIt is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice \"Two Bells Gone\"), if these are more usual for the system type. \n\n\n;Related task:\n* [[Sleep]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n \"time\"\n)\n\nfunc main() {\n watches := []string{\n \"First\", \"Middle\", \"Morning\", \"Forenoon\",\n \"Afternoon\", \"Dog\", \"First\",\n }\n for {\n t := time.Now()\n h := t.Hour()\n m := t.Minute()\n s := t.Second()\n if (m == 0 || m == 30) && s == 0 {\n bell := 0\n if m == 30 {\n bell = 1\n }\n bells := (h*2 + bell) % 8\n watch := h/4 + 1\n if bells == 0 {\n bells = 8\n watch--\n }\n sound := strings.Repeat(\"\\a\", bells)\n pl := \"s\"\n if bells == 1 {\n pl = \" \"\n }\n w := watches[watch] + \" watch\"\n if watch == 5 {\n if bells < 5 {\n w = \"First \" + w\n } else {\n w = \"Last \" + w\n }\n }\n fmt.Printf(\"%s%02d:%02d = %d bell%s : %s\\n\", sound, h, m, bells, pl, w)\n }\n time.Sleep(1 * time.Second)\n }\n}"} {"title": "Negative base numbers", "language": "Go from Kotlin", "task": "Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* supply an integer, that when encoded to base -62 (or something \"higher\"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"strings\"\n)\n\nconst digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\nfunc reverse(bs []byte) []byte {\n for i, j := 0, len(bs)-1; i < len(bs)/2; i, j = i+1, j-1 {\n bs[i], bs[j] = bs[j], bs[i]\n }\n return bs\n}\n\nfunc encodeNegBase(n, b int64) (string, error) {\n if b < -62 || b > -1 {\n return \"\", fmt.Errorf(\"base must be between -62 and -1 inclusive\")\n }\n if n == 0 {\n return \"0\", nil\n }\n var out []byte\n for n != 0 {\n rem := n % b\n n /= b\n if rem < 0 {\n n++\n rem -= b\n }\n out = append(out, digits[int(rem)])\n }\n reverse(out)\n return string(out), nil\n}\n\nfunc decodeNegBase(ns string, b int64) (int64, error) {\n if b < -62 || b > -1 {\n return 0, fmt.Errorf(\"base must be between -62 and -1 inclusive\")\n }\n if ns == \"0\" {\n return 0, nil\n }\n total := int64(0)\n bb := int64(1)\n bs := []byte(ns)\n reverse(bs)\n for _, c := range bs {\n total += int64(strings.IndexByte(digits, c)) * bb\n bb *= b\n }\n return total, nil\n}\n\nfunc main() {\n numbers := []int64{10, 146, 15, -942, 1488588316238}\n bases := []int64{-2, -3, -10, -62, -62}\n for i := 0; i < len(numbers); i++ {\n n := numbers[i]\n b := bases[i]\n ns, err := encodeNegBase(n, b)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"%13d encoded in base %-3d = %s\\n\", n, b, ns)\n n, err = decodeNegBase(ns, b)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"%13s decoded in base %-3d = %d\\n\\n\", ns, b, n)\n }\n}"} {"title": "Nested function", "language": "Go", "task": "In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator \". \" as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.\n\nThe inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.\n\n\n;References:\n:* Nested function\n\n", "solution": "package main\nimport \"fmt\"\n\nfunc makeList(separator string) string {\n counter := 1\n\n makeItem := func(item string) string {\n result := fmt.Sprintf(\"%d%s%s\\n\", counter, separator, item)\n counter += 1\n return result\n }\n\n return makeItem(\"first\") + makeItem(\"second\") + makeItem(\"third\")\n}\n\nfunc main() {\n fmt.Print(makeList(\". \"))\n}"} {"title": "Nested templated data", "language": "Go", "task": "A template for data is an arbitrarily nested tree of integer indices.\n \nData payloads are given as a separate mapping, array or other simpler, flat,\nassociation of indices to individual items of data, and are strings.\nThe idea is to create a data structure with the templates' nesting, and the \npayload corresponding to each index appearing at the position of each index.\n\nAnswers using simple string replacement or regexp are to be avoided. The idea is \nto use the native, or usual implementation of lists/tuples etc of the language\nand to hierarchically traverse the template to generate the output.\n\n;Task Detail:\nGiven the following input template t and list of payloads p:\n# Square brackets are used here to denote nesting but may be changed for other,\n# clear, visual representations of nested data appropriate to ones programming \n# language.\nt = [\n [[1, 2],\n [3, 4, 1], \n 5]]\n\np = 'Payload#0' ... 'Payload#6'\n\nThe correct output should have the following structure, (although spacing and \nlinefeeds may differ, the nesting and order should follow):\n[[['Payload#1', 'Payload#2'],\n ['Payload#3', 'Payload#4', 'Payload#1'],\n 'Payload#5']]\n\n1. Generate the output for the above template, t.\n\n;Optional Extended tasks:\n2. Show which payloads remain unused.\n3. Give some indication/handling of indices without a payload.\n\n''Show output on this page.''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"sort\"\n \"strings\"\n \"text/template\"\n)\n\nfunc main() {\n const t = `[[[{{index .P 1}}, {{index .P 2}}],\n [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], \n {{index .P 5}}]]\n`\n type S struct {\n P map[int]string\n }\n\n var s S\n s.P = map[int]string{\n 0: \"'Payload#0'\", 1: \"'Payload#1'\", 2: \"'Payload#2'\", 3: \"'Payload#3'\",\n 4: \"'Payload#4'\", 5: \"'Payload#5'\", 6: \"'Payload#6'\",\n }\n tmpl := template.Must(template.New(\"\").Parse(t))\n tmpl.Execute(os.Stdout, s)\n\n var unused []int\n for k, _ := range s.P {\n if !strings.Contains(t, fmt.Sprintf(\"{{index .P %d}}\", k)) {\n unused = append(unused, k)\n }\n }\n sort.Ints(unused)\n fmt.Println(\"\\nThe unused payloads have indices of :\", unused)\n}"} {"title": "Next highest int from digits", "language": "Go", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* Numbers will not be padded to the left with zeroes.\n* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).\n* If there is no next highest integer return zero.\n\n\n:*1 Alternatively phrased as: \"Find the smallest integer larger than the (positive or zero) integer '''N''' \n:: which can be obtained by reordering the (base ten) digits of '''N'''\".\n\n\n;Algorithm 1:\n# Generate all the permutations of the digits and sort into numeric order.\n# Find the number in the list.\n# Return the next highest number from the list.\n\n\nThe above could prove slow and memory hungry for numbers with large numbers of\ndigits, but should be easy to reason about its correctness.\n\n\n;Algorithm 2:\n# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.\n# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)\n\n\n'''E.g.:'''\n\n n = 12453\n\n 12_4_53\n\n 12_5_43\n\n 12_5_34\n\n return: 12534\n\n\nThis second algorithm is faster and more memory efficient, but implementations\nmay be harder to test. \n\nOne method of testing, (as used in developing the task), is to compare results from both\nalgorithms for random numbers generated from a range that the first algorithm can handle.\n\n\n;Task requirements:\nCalculate the next highest int from the digits of the following numbers:\n:* 0\n:* 9\n:* 12\n:* 21\n:* 12453\n:* 738440\n:* 45072010\n:* 95322020\n\n\n;Optional stretch goal:\n:* 9589776899767587796600\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc permute(s string) []string {\n var res []string\n if len(s) == 0 {\n return res\n }\n b := []byte(s)\n var rc func(int) // recursive closure\n rc = func(np int) {\n if np == 1 {\n res = append(res, string(b))\n return\n }\n np1 := np - 1\n pp := len(b) - np1\n rc(np1)\n for i := pp; i > 0; i-- {\n b[i], b[i-1] = b[i-1], b[i]\n rc(np1)\n }\n w := b[0]\n copy(b, b[1:pp+1])\n b[pp] = w\n }\n rc(len(b))\n return res\n}\n\nfunc algorithm1(nums []string) {\n fmt.Println(\"Algorithm 1\")\n fmt.Println(\"-----------\")\n for _, num := range nums {\n perms := permute(num)\n le := len(perms)\n if le == 0 { // ignore blanks\n continue\n }\n sort.Strings(perms)\n ix := sort.SearchStrings(perms, num)\n next := \"\"\n if ix < le-1 {\n for i := ix + 1; i < le; i++ {\n if perms[i] > num {\n next = perms[i]\n break\n }\n }\n }\n if len(next) > 0 {\n fmt.Printf(\"%29s -> %s\\n\", commatize(num), commatize(next))\n } else {\n fmt.Printf(\"%29s -> 0\\n\", commatize(num))\n }\n }\n fmt.Println()\n}\n\nfunc algorithm2(nums []string) {\n fmt.Println(\"Algorithm 2\")\n fmt.Println(\"-----------\")\nouter:\n for _, num := range nums {\n b := []byte(num)\n le := len(b)\n if le == 0 { // ignore blanks\n continue\n }\n max := num[le-1]\n mi := le - 1\n for i := le - 2; i >= 0; i-- {\n if b[i] < max {\n min := max - b[i]\n for j := mi + 1; j < le; j++ {\n min2 := b[j] - b[i]\n if min2 > 0 && min2 < min {\n min = min2\n mi = j\n }\n }\n b[i], b[mi] = b[mi], b[i]\n c := (b[i+1:])\n sort.Slice(c, func(i, j int) bool {\n return c[i] < c[j]\n })\n next := string(b[0:i+1]) + string(c)\n fmt.Printf(\"%29s -> %s\\n\", commatize(num), commatize(next))\n continue outer\n } else if b[i] > max {\n max = num[i]\n mi = i\n }\n }\n fmt.Printf(\"%29s -> 0\\n\", commatize(num))\n }\n}\n\nfunc commatize(s string) string {\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc main() {\n nums := []string{\"0\", \"9\", \"12\", \"21\", \"12453\", \"738440\", \"45072010\", \"95322020\", \"9589776899767587796600\"}\n algorithm1(nums[:len(nums)-1]) // exclude the last one\n algorithm2(nums) // include the last one\n}"} {"title": "Nim game", "language": "Go", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strconv\"\n)\n\nfunc showTokens(tokens int) {\n fmt.Println(\"Tokens remaining\", tokens, \"\\n\") \n}\n\nfunc main() {\n tokens := 12\n scanner := bufio.NewScanner(os.Stdin)\n for {\n showTokens(tokens)\n fmt.Print(\" How many tokens 1, 2 or 3? \")\n scanner.Scan()\n if scerr := scanner.Err(); scerr != nil {\n fmt.Println(\"Error reading standard input:\", scerr)\n return\n }\n t, err := strconv.Atoi(scanner.Text())\n if err != nil || t < 1 || t > 3 {\n fmt.Println(\"\\nMust be a number between 1 and 3, try again.\\n\")\n } else {\n ct := 4 - t\n s := \"s\"\n if ct == 1 {\n s = \"\"\n }\n fmt.Print(\" Computer takes \", ct, \" token\", s, \"\\n\\n\")\n tokens -= 4\n }\n if tokens == 0 {\n showTokens(0)\n fmt.Println(\" Computer wins!\")\n return\n }\n }\n}"} {"title": "Non-transitive dice", "language": "Go from Wren", "task": "Let our dice select numbers on their faces with equal probability, i.e. fair dice.\nDice may have more or less than six faces. (The possibility of there being a \n3D physical shape that has that many \"faces\" that allow them to be fair dice,\nis ignored for this task - a die with 3 or 33 defined sides is defined by the \nnumber of faces and the numbers on each face).\n\nThrowing dice will randomly select a face on each die with equal probability.\nTo show which die of dice thrown multiple times is more likely to win over the \nothers:\n# calculate all possible combinations of different faces from each die\n# Count how many times each die wins a combination\n# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.\n\n\n'''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.\n'''\n;Example 1:\nIf X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its\nfaces then the equal possibility outcomes from throwing both, and the winners \nis:\n \n X Y Winner\n = = ======\n 1 2 Y\n 1 3 Y\n 1 4 Y\n 3 2 X\n 3 3 -\n 3 4 Y\n 6 2 X\n 6 3 X\n 6 4 X\n \n TOTAL WINS: X=4, Y=4\n\nBoth die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y\n\n;Transitivity:\nIn mathematics transitivity are rules like: \n if a op b and b op c then a op c\nIf, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers\nwe get the familiar if a < b and b < c then a < c\n\n;Non-transitive dice\nThese are an ordered list of dice where the '>' operation between successive \ndice pairs applies but a comparison between the first and last of the list\nyields the opposite result, '<'.\n''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''\n\n\nThree dice S, T, U with appropriate face values could satisfy\n\n S < T, T < U and yet S > U\n\nTo be non-transitive.\n\n;Notes:\n\n* The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms).\n* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4\n* '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.\n\n\n;Task:\n;====\nFind all the ordered lists of ''three'' non-transitive dice S, T, U of the form \nS < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''\n, (unique w.r.t the notes), possible by having selections from the integers \n''one to four'' on any dies face.\n\nSolution can be found by generating all possble individual die then testing all\npossible permutations, (permutations are ordered), of three dice for \nnon-transitivity.\n\n;Optional stretch goal:\nFind lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.\n\n\nShow the results here, on this page.\n\n;References:\n* The Most Powerful Dice - Numberphile Video.\n* Nontransitive dice - Wikipedia.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nfunc fourFaceCombs() (res [][4]int) {\n found := make([]bool, 256)\n for i := 1; i <= 4; i++ {\n for j := 1; j <= 4; j++ {\n for k := 1; k <= 4; k++ {\n for l := 1; l <= 4; l++ {\n c := [4]int{i, j, k, l}\n sort.Ints(c[:])\n key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)\n if !found[key] {\n found[key] = true\n res = append(res, c)\n }\n }\n }\n }\n }\n return\n}\n\nfunc cmp(x, y [4]int) int {\n xw := 0\n yw := 0\n for i := 0; i < 4; i++ {\n for j := 0; j < 4; j++ {\n if x[i] > y[j] {\n xw++\n } else if y[j] > x[i] {\n yw++\n }\n }\n }\n if xw < yw {\n return -1\n } else if xw > yw {\n return 1\n }\n return 0\n}\n\nfunc findIntransitive3(cs [][4]int) (res [][3][4]int) {\n var c = len(cs)\n for i := 0; i < c; i++ {\n for j := 0; j < c; j++ {\n for k := 0; k < c; k++ {\n first := cmp(cs[i], cs[j])\n if first == -1 {\n second := cmp(cs[j], cs[k])\n if second == -1 {\n third := cmp(cs[i], cs[k])\n if third == 1 {\n res = append(res, [3][4]int{cs[i], cs[j], cs[k]})\n }\n }\n }\n }\n }\n }\n return\n}\n\nfunc findIntransitive4(cs [][4]int) (res [][4][4]int) {\n c := len(cs)\n for i := 0; i < c; i++ {\n for j := 0; j < c; j++ {\n for k := 0; k < c; k++ {\n for l := 0; l < c; l++ {\n first := cmp(cs[i], cs[j])\n if first == -1 {\n second := cmp(cs[j], cs[k])\n if second == -1 {\n third := cmp(cs[k], cs[l])\n if third == -1 {\n fourth := cmp(cs[i], cs[l])\n if fourth == 1 {\n res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})\n }\n }\n }\n }\n }\n }\n }\n }\n return\n}\n\nfunc main() {\n combs := fourFaceCombs()\n fmt.Println(\"Number of eligible 4-faced dice\", len(combs))\n it3 := findIntransitive3(combs)\n fmt.Printf(\"\\n%d ordered lists of 3 non-transitive dice found, namely:\\n\", len(it3))\n for _, a := range it3 {\n fmt.Println(a)\n }\n it4 := findIntransitive4(combs)\n fmt.Printf(\"\\n%d ordered lists of 4 non-transitive dice found, namely:\\n\", len(it4))\n for _, a := range it4 {\n fmt.Println(a)\n }\n}"} {"title": "Nonoblock", "language": "Go from Kotlin", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).\n* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.\n* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc printBlock(data string, le int) {\n a := []byte(data)\n sumBytes := 0\n for _, b := range a {\n sumBytes += int(b - 48)\n }\n fmt.Printf(\"\\nblocks %c, cells %d\\n\", a, le)\n if le-sumBytes <= 0 {\n fmt.Println(\"No solution\")\n return\n }\n prep := make([]string, len(a))\n for i, b := range a {\n prep[i] = strings.Repeat(\"1\", int(b-48))\n }\n for _, r := range genSequence(prep, le-sumBytes+1) {\n fmt.Println(r[1:])\n }\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n if len(ones) == 0 {\n return []string{strings.Repeat(\"0\", numZeros)}\n }\n var result []string\n for x := 1; x < numZeros-len(ones)+2; x++ {\n skipOne := ones[1:]\n for _, tail := range genSequence(skipOne, numZeros-x) {\n result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n }\n }\n return result\n}\n\nfunc main() {\n printBlock(\"21\", 5)\n printBlock(\"\", 5)\n printBlock(\"8\", 10)\n printBlock(\"2323\", 15)\n printBlock(\"23\", 5)\n}"} {"title": "Nonogram solver", "language": "Go from Java", "task": "nonogram is a puzzle that provides \nnumeric clues used to fill in a grid of cells, \nestablishing for each cell whether it is filled or not. \nThe puzzle solution is typically a picture of some kind.\n\nEach row and column of a rectangular grid is annotated with the lengths \nof its distinct runs of occupied cells. \nUsing only these lengths you should find one valid configuration \nof empty and occupied cells, or show a failure message.\n\n;Example\nProblem: Solution:\n\n. . . . . . . . 3 . # # # . . . . 3\n. . . . . . . . 2 1 # # . # . . . . 2 1\n. . . . . . . . 3 2 . # # # . . # # 3 2\n. . . . . . . . 2 2 . . # # . . # # 2 2\n. . . . . . . . 6 . . # # # # # # 6\n. . . . . . . . 1 5 # . # # # # # . 1 5\n. . . . . . . . 6 # # # # # # . . 6\n. . . . . . . . 1 . . . . # . . . 1\n. . . . . . . . 2 . . . # # . . . 2\n1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3\n2 1 5 1 2 1 5 1 \nThe problem above could be represented by two lists of lists:\nx = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]\ny = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]\nA more compact representation of the same problem uses strings, \nwhere the letters represent the numbers, A=1, B=2, etc:\nx = \"C BA CB BB F AE F A B\"\ny = \"AB CA AE GA E C D C\"\n\n;Task\nFor this task, try to solve the 4 problems below, read from a \"nonogram_problems.txt\" file that has this content \n(the blank lines are separators):\nC BA CB BB F AE F A B\nAB CA AE GA E C D C\n\nF CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\nD D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\n\nCA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\nBC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\n\nE BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\nE CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\n\n'''Extra credit''': generate nonograms with unique solutions, of desired height and width.\n\nThis task is the problem n.98 of the \"99 Prolog Problems\" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).\n\n; Related tasks\n* [[Nonoblock]].\n\n;See also\n* Arc Consistency Algorithm\n* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)\n* http://twanvl.nl/blog/haskell/Nonograms (Haskell)\n* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\ntype BitSet []bool\n\nfunc (bs BitSet) and(other BitSet) {\n for i := range bs {\n if bs[i] && other[i] {\n bs[i] = true\n } else {\n bs[i] = false\n }\n }\n}\n\nfunc (bs BitSet) or(other BitSet) {\n for i := range bs {\n if bs[i] || other[i] {\n bs[i] = true\n } else {\n bs[i] = false\n }\n }\n}\n\nfunc iff(cond bool, s1, s2 string) string {\n if cond {\n return s1\n }\n return s2\n}\n\nfunc newPuzzle(data [2]string) {\n rowData := strings.Fields(data[0])\n colData := strings.Fields(data[1])\n rows := getCandidates(rowData, len(colData))\n cols := getCandidates(colData, len(rowData))\n\n for {\n numChanged := reduceMutual(cols, rows)\n if numChanged == -1 {\n fmt.Println(\"No solution\")\n return\n }\n if numChanged == 0 {\n break\n }\n }\n\n for _, row := range rows {\n for i := 0; i < len(cols); i++ {\n fmt.Printf(iff(row[0][i], \"# \", \". \"))\n }\n fmt.Println()\n }\n fmt.Println()\n}\n\n// collect all possible solutions for the given clues\nfunc getCandidates(data []string, le int) [][]BitSet {\n var result [][]BitSet\n for _, s := range data {\n var lst []BitSet\n a := []byte(s)\n sumBytes := 0\n for _, b := range a {\n sumBytes += int(b - 'A' + 1)\n }\n prep := make([]string, len(a))\n for i, b := range a {\n prep[i] = strings.Repeat(\"1\", int(b-'A'+1))\n }\n for _, r := range genSequence(prep, le-sumBytes+1) {\n bits := []byte(r[1:])\n bitset := make(BitSet, len(bits))\n for i, b := range bits {\n bitset[i] = b == '1'\n }\n lst = append(lst, bitset)\n }\n result = append(result, lst)\n }\n return result\n}\n\nfunc genSequence(ones []string, numZeros int) []string {\n le := len(ones)\n if le == 0 {\n return []string{strings.Repeat(\"0\", numZeros)}\n }\n var result []string\n for x := 1; x < numZeros-le+2; x++ {\n skipOne := ones[1:]\n for _, tail := range genSequence(skipOne, numZeros-x) {\n result = append(result, strings.Repeat(\"0\", x)+ones[0]+tail)\n }\n }\n return result\n}\n\n/* If all the candidates for a row have a value in common for a certain cell,\n then it's the only possible outcome, and all the candidates from the\n corresponding column need to have that value for that cell too. The ones\n that don't, are removed. The same for all columns. It goes back and forth,\n until no more candidates can be removed or a list is empty (failure).\n*/\n\nfunc reduceMutual(cols, rows [][]BitSet) int {\n countRemoved1 := reduce(cols, rows)\n if countRemoved1 == -1 {\n return -1\n }\n countRemoved2 := reduce(rows, cols)\n if countRemoved2 == -1 {\n return -1\n }\n return countRemoved1 + countRemoved2\n}\n\nfunc reduce(a, b [][]BitSet) int {\n countRemoved := 0\n for i := 0; i < len(a); i++ {\n commonOn := make(BitSet, len(b))\n for j := 0; j < len(b); j++ {\n commonOn[j] = true\n }\n commonOff := make(BitSet, len(b))\n\n // determine which values all candidates of a[i] have in common\n for _, candidate := range a[i] {\n commonOn.and(candidate)\n commonOff.or(candidate)\n }\n\n // remove from b[j] all candidates that don't share the forced values\n for j := 0; j < len(b); j++ {\n fi, fj := i, j\n for k := len(b[j]) - 1; k >= 0; k-- {\n cnd := b[j][k]\n if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {\n lb := len(b[j])\n copy(b[j][k:], b[j][k+1:])\n b[j][lb-1] = nil\n b[j] = b[j][:lb-1]\n countRemoved++\n }\n }\n if len(b[j]) == 0 {\n return -1\n }\n }\n }\n return countRemoved\n}\n\nfunc main() {\n p1 := [2]string{\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\"}\n\n p2 := [2]string{\n \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\",\n }\n\n p3 := [2]string{\n \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n \"AAAAD BDG CEF CBDB BBB FC\",\n }\n\n p4 := [2]string{\n \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\",\n }\n\n for _, puzzleData := range [][2]string{p1, p2, p3, p4} {\n newPuzzle(puzzleData)\n }\n}"} {"title": "Numbers with equal rises and falls", "language": "Go from Wren", "task": "When a number is written in base 10, adjacent digits may \"rise\" or \"fall\" as the number is read (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series d:\n:* A ''rise'' is an index i such that d(i) < d(i+1)\n:* A ''fall'' is an index i such that d(i) > d(i+1)\n\n\n;Examples:\n:* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence.\n:* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence.\n\n\n;Task:\n:* Print the first '''200''' numbers in the sequence \n:* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002'''\n\n\n;See also:\n* OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* Esthetic numbers\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc risesEqualsFalls(n int) bool {\n if n < 10 {\n return true\n }\n rises := 0\n falls := 0\n prev := -1\n for n > 0 {\n d := n % 10\n if prev >= 0 {\n if d < prev {\n rises = rises + 1\n } else if d > prev {\n falls = falls + 1\n }\n }\n prev = d\n n /= 10 \n }\n return rises == falls\n}\n\nfunc main() {\n fmt.Println(\"The first 200 numbers in the sequence are:\")\n count := 0\n n := 1\n for {\n if risesEqualsFalls(n) {\n count++\n if count <= 200 {\n fmt.Printf(\"%3d \", n)\n if count%20 == 0 {\n fmt.Println()\n }\n }\n if count == 1e7 {\n fmt.Println(\"\\nThe 10 millionth number in the sequence is \", n)\n break\n }\n }\n n++\n }\n}"} {"title": "Numeric error propagation", "language": "Go", "task": "If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; \nthen if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, \nthen sf can be calculated as follows:\n\n:;Addition/Subtraction\n:* If f = a +- c, or f = c +- a then '''sf = sa'''\n:* If f = a +- b then '''sf2 = sa2 + sb2'''\n\n:;Multiplication/Division\n:* If f = ca or f = ac then '''sf = |csa|'''\n:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''\n\n:;Exponentiation\n:* If f = ac then '''sf = |fc(sa / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue.\n\n\n;Task details:\n# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.\n# Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 \n# Print and display both '''d''' and its error.\n\n \n\n;References:\n* A Guide to Error Propagation B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* [[Quaternion type]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\n// \"uncertain number type\"\n// a little optimization is to represent the error term with its square.\n// this saves some taking of square roots in various places.\ntype unc struct {\n n float64 // the number\n s float64 // *square* of one sigma error term\n}\n\n// constructor, nice to have so it can handle squaring of error term\nfunc newUnc(n, s float64) *unc {\n return &unc{n, s * s}\n}\n\n// error term accessor method, nice to have so it can handle recovering\n// (non-squared) error term from internal (squared) representation\nfunc (z *unc) errorTerm() float64 {\n return math.Sqrt(z.s)\n}\n\n// Arithmetic methods are modeled on the Go big number package.\n// The basic scheme is to pass all operands as method arguments, compute\n// the result into the method receiver, and then return the receiver as\n// the result of the method. This has an advantage of letting the programer\n// determine allocation and use of temporary objects, reducing garbage;\n// and has the convenience and efficiency of allowing operations to be chained.\n\n// addition/subtraction\nfunc (z *unc) addC(a *unc, c float64) *unc {\n *z = *a\n z.n += c\n return z\n}\n\nfunc (z *unc) subC(a *unc, c float64) *unc {\n *z = *a\n z.n -= c\n return z\n}\n\nfunc (z *unc) addU(a, b *unc) *unc {\n z.n = a.n + b.n\n z.s = a.s + b.s\n return z\n}\nfunc (z *unc) subU(a, b *unc) *unc {\n z.n = a.n - b.n\n z.s = a.s + b.s\n return z\n}\n\n// multiplication/division\nfunc (z *unc) mulC(a *unc, c float64) *unc {\n z.n = a.n * c\n z.s = a.s * c * c\n return z\n}\n\nfunc (z *unc) divC(a *unc, c float64) *unc {\n z.n = a.n / c\n z.s = a.s / (c * c)\n return z\n}\n\nfunc (z *unc) mulU(a, b *unc) *unc {\n prod := a.n * b.n\n z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n return z\n}\n\nfunc (z *unc) divU(a, b *unc) *unc {\n quot := a.n / b.n\n z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))\n return z\n}\n\n// exponentiation\nfunc (z *unc) expC(a *unc, c float64) *unc {\n f := math.Pow(a.n, c)\n g := f * c / a.n\n z.n = f\n z.s = a.s * g * g\n return z\n}\n\nfunc main() {\n x1 := newUnc(100, 1.1)\n x2 := newUnc(200, 2.2)\n y1 := newUnc(50, 1.2)\n y2 := newUnc(100, 2.3)\n var d, d2 unc\n d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)\n fmt.Println(\"d: \", d.n)\n fmt.Println(\"error:\", d.errorTerm())\n}"} {"title": "Numerical and alphabetical suffixes", "language": "Go", "task": "This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:\n::* an alphabetic (named) multiplier which could be abbreviated\n::* metric multiplier(s) which can be specified multiple times\n::* \"binary\" multiplier(s) which can be specified multiple times\n::* explanation marks ('''!''') which indicate a factorial or multifactorial\n\n\nThe (decimal) numbers can be expressed generally as:\n {+-} {digits} {'''.'''} {digits}\n ------ or ------\n {+-} {digits} {'''.'''} {digits} {'''E''' or '''e'''} {+-} {digits}\n\nwhere:\n::* numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)\n::* this task will only be dealing with decimal numbers, both in the ''mantissa'' and ''exponent''\n::* +- indicates an optional plus or minus sign ('''+''' or '''-''')\n::* digits are the decimal digits ('''0''' --> '''9''')\n::* the digits can have comma(s) interjected to separate the ''periods'' (thousands) such as: '''12,467,000'''\n::* '''.''' is the decimal point, sometimes also called a ''dot''\n::* '''e''' or '''E''' denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)\n\n\nThis isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.\n\nThe use of the word ''periods'' (thousands) is not meant to confuse, that word (as used above) is what the '''comma''' separates;\nthe groups of decimal digits are called ''periods'', and in almost all cases, are groups of three decimal digits.\n\nIf an '''e''' or '''E''' is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.\n\nAlso, there must be some digits expressed in all cases, not just a sign and/or decimal point.\n\nSuperfluous signs, decimal points, exponent numbers, and zeros need not be preserved.\n\nI.E.: \n'''+7''' '''007''' '''7.00''' '''7E-0''' '''7E000''' '''70e-1''' could all be expressed as '''7'''\n\nAll numbers to be \"expanded\" can be assumed to be valid and there won't be a requirement to verify their validity.\n\n\n;Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used):\n '''PAIRs''' multiply the number by '''2''' (as in pairs of shoes or pants)\n '''SCOres''' multiply the number by '''20''' (as '''3score''' would be '''60''')\n '''DOZens''' multiply the number by '''12'''\n '''GRoss''' multiply the number by '''144''' (twelve dozen)\n '''GREATGRoss''' multiply the number by '''1,728''' (a dozen gross)\n '''GOOGOLs''' multiply the number by '''10^100''' (ten raised to the 100>th power)\n\n\nNote that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)\n\n\n;Metric suffixes to be supported (whether or not they're officially sanctioned):\n '''K''' multiply the number by '''10^3''' kilo (1,000)\n '''M''' multiply the number by '''10^6''' mega (1,000,000)\n '''G''' multiply the number by '''10^9''' giga (1,000,000,000)\n '''T''' multiply the number by '''10^12''' tera (1,000,000,000,000)\n '''P''' multiply the number by '''10^15''' peta (1,000,000,000,000,000)\n '''E''' multiply the number by '''10^18''' exa (1,000,000,000,000,000,000)\n '''Z''' multiply the number by '''10^21''' zetta (1,000,000,000,000,000,000,000)\n '''Y''' multiply the number by '''10^24''' yotta (1,000,000,000,000,000,000,000,000)\n '''X''' multiply the number by '''10^27''' xenta (1,000,000,000,000,000,000,000,000,000)\n '''W''' multiply the number by '''10^30''' wekta (1,000,000,000,000,000,000,000,000,000,000)\n '''V''' multiply the number by '''10^33''' vendeka (1,000,000,000,000,000,000,000,000,000,000,000)\n '''U''' multiply the number by '''10^36''' udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)\n\n\n;Binary suffixes to be supported (whether or not they're officially sanctioned):\n '''Ki''' multiply the number by '''2^10''' kibi (1,024)\n '''Mi''' multiply the number by '''2^20''' mebi (1,048,576)\n '''Gi''' multiply the number by '''2^30''' gibi (1,073,741,824)\n '''Ti''' multiply the number by '''2^40''' tebi (1,099,571,627,776)\n '''Pi''' multiply the number by '''2^50''' pebi (1,125,899,906,884,629)\n '''Ei''' multiply the number by '''2^60''' exbi (1,152,921,504,606,846,976)\n '''Zi''' multiply the number by '''2^70''' zeb1 (1,180,591,620,717,411,303,424)\n '''Yi''' multiply the number by '''2^80''' yobi (1,208,925,819,614,629,174,706,176)\n '''Xi''' multiply the number by '''2^90''' xebi (1,237,940,039,285,380,274,899,124,224)\n '''Wi''' multiply the number by '''2^100''' webi (1,267,650,600,228,229,401,496,703,205,376)\n '''Vi''' multiply the number by '''2^110''' vebi (1,298,074,214,633,706,907,132,624,082,305,024)\n '''Ui''' multiply the number by '''2^120''' uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)\n\n\nAll of the metric and binary suffixes can be expressed in lowercase, uppercase, ''or'' mixed case.\n\nAll of the metric and binary suffixes can be ''stacked'' (expressed multiple times), and also be intermixed:\nI.E.: '''123k''' '''123K''' '''123GKi''' '''12.3GiGG''' '''12.3e-7T''' '''.78E100e'''\n \n\n;Factorial suffixes to be supported:\n '''!''' compute the (regular) factorial product: '''5!''' is '''5''' x '''4''' x '''3''' x '''2''' x '''1''' = '''120'''\n '''!!''' compute the double factorial product: '''8!''' is '''8''' x '''6''' x '''4''' x '''2''' = '''384'''\n '''!!!''' compute the triple factorial product: '''8!''' is '''8''' x '''5''' x '''2''' = '''80'''\n '''!!!!''' compute the quadruple factorial product: '''8!''' is '''8''' x '''4''' = '''32'''\n '''!!!!!''' compute the quintuple factorial product: '''8!''' is '''8''' x '''3''' = '''24'''\n *** the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ***\n\n\nFactorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.\n\n\nMultifactorials aren't to be confused with ''super-factorials'' where '''(4!)!''' would be '''(24)!'''.\n\n\n\n;Task:\n::* Using the test cases (below), show the \"expanded\" numbers here, on this page.\n::* For each list, show the input on one line, and also show the output on one line.\n::* When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.\n::* For each result (list) displayed on one line, separate each number with two blanks.\n::* Add commas to the output numbers were appropriate.\n\n\n;Test cases:\n 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n 1,567 +1.567k 0.1567e-2m\n 25.123kK 25.123m 2.5123e-00002G\n 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n -.25123e-34Vikki 2e-77gooGols\n 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!\n\nwhere the last number for the factorials has nine factorial symbols ('''!''') after the '''9'''\n\n\n\n;Related tasks:\n* [[Multifactorial]] (which has a clearer and more succinct definition of multifactorials.)\n* [[Factorial]]\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"strconv\"\n \"strings\"\n)\n\ntype minmult struct {\n min int\n mult float64\n}\n\nvar abbrevs = map[string]minmult{\n \"PAIRs\": {4, 2}, \"SCOres\": {3, 20}, \"DOZens\": {3, 12},\n \"GRoss\": {2, 144}, \"GREATGRoss\": {7, 1728}, \"GOOGOLs\": {6, 1e100},\n}\n\nvar metric = map[string]float64{\n \"K\": 1e3, \"M\": 1e6, \"G\": 1e9, \"T\": 1e12, \"P\": 1e15, \"E\": 1e18,\n \"Z\": 1e21, \"Y\": 1e24, \"X\": 1e27, \"W\": 1e30, \"V\": 1e33, \"U\": 1e36,\n}\n\nvar binary = map[string]float64{\n \"Ki\": b(10), \"Mi\": b(20), \"Gi\": b(30), \"Ti\": b(40), \"Pi\": b(50), \"Ei\": b(60),\n \"Zi\": b(70), \"Yi\": b(80), \"Xi\": b(90), \"Wi\": b(100), \"Vi\": b(110), \"Ui\": b(120),\n}\n\nfunc b(e float64) float64 {\n return math.Pow(2, e)\n}\n\nfunc googol() *big.Float {\n g1 := new(big.Float).SetPrec(500)\n g1.SetInt64(10000000000)\n g := new(big.Float)\n g.Set(g1)\n for i := 2; i <= 10; i++ {\n g.Mul(g, g1)\n }\n return g\n}\n\nfunc fact(num string, d int) int {\n prod := 1\n n, _ := strconv.Atoi(num)\n for i := n; i > 0; i -= d {\n prod *= i\n }\n return prod\n}\n\nfunc parse(number string) *big.Float {\n bf := new(big.Float).SetPrec(500)\n t1 := new(big.Float).SetPrec(500)\n t2 := new(big.Float).SetPrec(500)\n // find index of last digit\n var i int\n for i = len(number) - 1; i >= 0; i-- {\n if '0' <= number[i] && number[i] <= '9' {\n break\n }\n }\n num := number[:i+1]\n num = strings.Replace(num, \",\", \"\", -1) // get rid of any commas\n suf := strings.ToUpper(number[i+1:])\n if suf == \"\" {\n bf.SetString(num)\n return bf\n }\n if suf[0] == '!' {\n prod := fact(num, len(suf))\n bf.SetInt64(int64(prod))\n return bf\n }\n for k, v := range abbrevs {\n kk := strings.ToUpper(k)\n if strings.HasPrefix(kk, suf) && len(suf) >= v.min {\n t1.SetString(num)\n if k != \"GOOGOLs\" {\n t2.SetFloat64(v.mult)\n } else {\n t2 = googol() // for greater accuracy\n }\n bf.Mul(t1, t2)\n return bf\n }\n }\n bf.SetString(num)\n for k, v := range metric {\n for j := 0; j < len(suf); j++ {\n if k == suf[j:j+1] {\n if j < len(suf)-1 && suf[j+1] == 'I' {\n t1.SetFloat64(binary[k+\"i\"])\n bf.Mul(bf, t1)\n j++\n } else {\n t1.SetFloat64(v)\n bf.Mul(bf, t1)\n }\n }\n }\n }\n return bf\n}\n\nfunc commatize(s string) string {\n if len(s) == 0 {\n return \"\"\n }\n neg := s[0] == '-'\n if neg {\n s = s[1:]\n }\n frac := \"\"\n if ix := strings.Index(s, \".\"); ix >= 0 {\n frac = s[ix:]\n s = s[:ix]\n }\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n if !neg {\n return s + frac\n }\n return \"-\" + s + frac\n}\n\nfunc process(numbers []string) {\n fmt.Print(\"numbers = \")\n for _, number := range numbers {\n fmt.Printf(\"%s \", number)\n }\n fmt.Print(\"\\nresults = \")\n for _, number := range numbers {\n res := parse(number)\n t := res.Text('g', 50)\n fmt.Printf(\"%s \", commatize(t))\n }\n fmt.Println(\"\\n\")\n}\n\nfunc main() {\n numbers := []string{\"2greatGRo\", \"24Gros\", \"288Doz\", \"1,728pairs\", \"172.8SCOre\"}\n process(numbers)\n\n numbers = []string{\"1,567\", \"+1.567k\", \"0.1567e-2m\"}\n process(numbers)\n\n numbers = []string{\"25.123kK\", \"25.123m\", \"2.5123e-00002G\"}\n process(numbers)\n\n numbers = []string{\"25.123kiKI\", \"25.123Mi\", \"2.5123e-00002Gi\", \"+.25123E-7Ei\"}\n process(numbers)\n\n numbers = []string{\"-.25123e-34Vikki\", \"2e-77gooGols\"}\n process(numbers)\n\n numbers = []string{\"9!\", \"9!!\", \"9!!!\", \"9!!!!\", \"9!!!!!\", \"9!!!!!!\",\n \"9!!!!!!!\", \"9!!!!!!!!\", \"9!!!!!!!!!\"}\n process(numbers)\n}"} {"title": "Odd word problem", "language": "Go", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"io\"\n \"os\"\n \"unicode\"\n)\n\nfunc main() {\n owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n fmt.Println()\n owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n fmt.Println()\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n byte_in := func () byte {\n bs := make([]byte, 1)\n src.Read(bs)\n return bs[0]\n }\n byte_out := func (b byte) { dst.Write([]byte{b}) } \n odd := func() byte {\n for {\n b := byte_in()\n if unicode.IsPunct(int(b)) {\n return b\n }\n defer byte_out(b)\n }\n panic(\"impossible\")\n }\n for {\n for {\n b := byte_in()\n byte_out(b)\n if b == '.' {\n return\n }\n if unicode.IsPunct(rune(b)) {\n break\n }\n }\n b := odd()\n byte_out(b)\n if b == '.' {\n return\n }\n }\n}"} {"title": "Odd word problem", "language": "Go from Tcl", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"io\"\n \"os\"\n \"unicode\"\n)\n\nfunc main() {\n owp(os.Stdout, bytes.NewBufferString(\"what,is,the;meaning,of:life.\"))\n fmt.Println()\n owp(os.Stdout, bytes.NewBufferString(\"we,are;not,in,kansas;any,more.\"))\n fmt.Println()\n}\n\ntype Coroutine struct {\n out <-chan Coroutine\n in chan<- byte\n}\n\nfunc owp(dst io.Writer, src io.Reader) {\n byte_in := func () (byte, error) {\n bs := make([]byte, 1)\n _, err := src.Read(bs)\n return bs[0], err\n }\n byte_out := func (b byte) { dst.Write([]byte{b}) } \n\n var f, r Coroutine\n\n f = func () Coroutine {\n out := make(chan Coroutine)\n\tin := make(chan byte)\n var fwd func (byte) byte\n fwd = func (c byte) (z byte) {\n if unicode.IsLetter(rune(c)) {\n byte_out(c)\n out <- f\n z = fwd(<- in)\n } else {\n z = c\n }\n return\n }\n go func () {\n for {\n x, ok := <- in\n if !ok { break }\n byte_out(fwd(x))\n out <- r\n }\n } ()\n return Coroutine{ out, in }\n } ()\n r = func () Coroutine {\n out := make(chan Coroutine)\n\tin := make(chan byte)\n var rev func (byte) byte\n rev = func (c byte) (z byte) {\n if unicode.IsLetter(rune(c)) {\n out <- r\n z = rev(<- in)\n byte_out(c)\n } else {\n z = c\n }\n return\n }\n go func () {\n for {\n x, ok := <- in\n if !ok { break }\n byte_out(rev(x))\n out <- f\n }\n } ()\n return Coroutine{ out, in }\n } ()\n\n for coro := f; ; coro = <- coro.out {\n c, err := byte_in()\n if err != nil { break }\n coro.in <- c\n }\n close(f.in)\n close(r.in)\n}"} {"title": "Old Russian measure of length", "language": "Go from Kotlin", "task": "Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).\n\n\nIt is an example of a linear transformation of several variables. \n\n\nThe program should accept a single value in a selected unit of measurement, and convert and return it to the other units: \n''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.\n\n\n;Also see:\n:* Old Russian measure of length\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n units := []string{\n \"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n \"arshin\", \"sazhen\", \"versta\", \"milia\",\n \"centimeter\", \"meter\", \"kilometer\",\n }\n\n convs := []float32{\n 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,\n 71.12, 213.36, 10668, 74676,\n 1, 100, 10000,\n }\n\n scanner := bufio.NewScanner(os.Stdin)\n for {\n for i, u := range units {\n fmt.Printf(\"%2d %s\\n\", i+1, u)\n }\n fmt.Println()\n var unit int\n var err error\n for {\n fmt.Print(\"Please choose a unit 1 to 13 : \")\n scanner.Scan()\n unit, err = strconv.Atoi(scanner.Text())\n if err == nil && unit >= 1 && unit <= 13 {\n break\n }\n }\n unit--\n var value float64\n for {\n fmt.Print(\"Now enter a value in that unit : \")\n scanner.Scan()\n value, err = strconv.ParseFloat(scanner.Text(), 32)\n if err == nil && value >= 0 {\n break\n }\n }\n fmt.Println(\"\\nThe equivalent in the remaining units is:\\n\")\n for i, u := range units {\n if i == unit {\n continue\n }\n fmt.Printf(\" %10s : %g\\n\", u, float32(value)*convs[unit]/convs[i])\n }\n fmt.Println()\n yn := \"\"\n for yn != \"y\" && yn != \"n\" {\n fmt.Print(\"Do another one y/n : \")\n scanner.Scan()\n yn = strings.ToLower(scanner.Text())\n }\n if yn == \"n\" {\n return\n }\n }\n}"} {"title": "Old lady swallowed a fly", "language": "Go", "task": "Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar name, lyric, animals = 0, 1, [][]string{\n\t{\"fly\", \"I don't know why she swallowed a fly. Perhaps she'll die.\"},\n\t{\"spider\", \"That wiggled and jiggled and tickled inside her.\"},\n\t{\"bird\", \"How absurd, to swallow a bird.\"},\n\t{\"cat\", \"Imagine that, she swallowed a cat.\"},\n\t{\"dog\", \"What a hog, to swallow a dog.\"},\n\t{\"goat\", \"She just opened her throat and swallowed that goat.\"},\n\t{\"cow\", \"I don't know how she swallowed that cow.\"},\n\t{\"horse\", \"She's dead, of course.\"},\n}\n\nfunc main() {\n\tfor i, animal := range animals {\n\t\tfmt.Printf(\"There was an old lady who swallowed a %s,\\n\",\n\t\t\tanimal[name])\n\n\t\tif i > 0 {\n\t\t\tfmt.Println(animal[lyric])\n\t\t}\n\n\t\t// Swallowing the last animal signals her death, cutting the\n\t\t// lyrics short.\n\t\tif i+1 == len(animals) {\n\t\t\tbreak\n\t\t}\n\n\t\tfor ; i > 0; i-- {\n\t\t\tfmt.Printf(\"She swallowed the %s to catch the %s,\\n\",\n\t\t\t\tanimals[i][name], animals[i-1][name])\n\t\t}\n\n\t\tfmt.Println(animals[0][lyric] + \"\\n\")\n\t}\n}"} {"title": "One-time pad", "language": "Go from Kotlin", "task": "One-time pad, for encrypting and decrypting messages.\nTo keep it simple, we will be using letters only.\n\n;Sub-Tasks:\n* '''Generate''' the data for a One-time pad (user needs to specify a filename and length)\n: The important part is to get \"true random\" numbers, e.g. from /dev/random\n* '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] )\n: For this step, much of [[Vigenere cipher]] could be reused,with the key to be read from the file containing the One-time pad.\n* optional: '''management''' of One-time pads: list, mark as used, delete, etc.\n: Somehow, the users needs to keep track which pad to use for which partner.\n\nTo support the management of pad-files:\n* Such files have a file-extension \".1tp\"\n* Lines starting with \"#\" may contain arbitary meta-data (i.e. comments)\n* Lines starting with \"-\" count as \"used\"\n* Whitespace within the otp-data is ignored\n\n\n\nFor example, here is the data from Wikipedia:\n\n# Example data - Wikipedia - 2014-11-13\n-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ \n-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK \n YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK \n CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX \n QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR \n CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE \n EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE \n\n\n;See also\n* one time pad encryption in Python\n* snapfractalpop - One-Time-Pad Command-Line-Utility (C).\n* Crypt-OTP-2.00 on CPAN (Perl)\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"crypto/rand\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"math/big\"\n \"os\"\n \"strconv\"\n \"strings\"\n \"unicode\"\n)\n\nconst (\n charsPerLine = 48\n chunkSize = 6\n cols = 8\n demo = true // would normally be set to false\n)\n\ntype fileType int\n\nconst (\n otp fileType = iota\n enc\n dec\n)\n\nvar scnr = bufio.NewScanner(os.Stdin)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc toAlpha(s string) string {\n var filtered []rune\n for _, r := range s {\n if unicode.IsUpper(r) {\n filtered = append(filtered, r)\n }\n }\n return string(filtered)\n}\n\nfunc isOtpRelated(s string) bool {\n return strings.HasSuffix(s, \".1tp\") || strings.HasSuffix(s, \"1tp_cpy\") ||\n strings.HasSuffix(s, \".1tp_enc\") || strings.HasSuffix(s, \"1tp_dec\")\n}\n\nfunc makePad(nLines int) string {\n nChars := nLines * charsPerLine\n bytes := make([]byte, nChars)\n /* generate random upper case letters */\n max := big.NewInt(26)\n for i := 0; i < nChars; i++ {\n n, err := rand.Int(rand.Reader, max)\n check(err)\n bytes[i] = byte(65 + n.Uint64())\n }\n return inChunks(string(bytes), nLines, otp)\n}\n\nfunc vigenere(text, key string, encrypt bool) string {\n bytes := make([]byte, len(text))\n var ci byte\n for i, c := range text {\n if encrypt {\n ci = (byte(c) + key[i] - 130) % 26\n } else {\n ci = (byte(c) + 26 - key[i]) % 26\n }\n bytes[i] = ci + 65\n }\n temp := len(bytes) % charsPerLine\n if temp > 0 { // pad with random characters so each line is a full one\n max := big.NewInt(26)\n for i := temp; i < charsPerLine; i++ {\n n, err := rand.Int(rand.Reader, max)\n check(err)\n bytes = append(bytes, byte(65+n.Uint64()))\n }\n }\n ft := enc\n if !encrypt {\n ft = dec\n }\n return inChunks(string(bytes), len(bytes)/charsPerLine, ft)\n}\n\nfunc inChunks(s string, nLines int, ft fileType) string {\n nChunks := len(s) / chunkSize\n remainder := len(s) % chunkSize\n chunks := make([]string, nChunks)\n for i := 0; i < nChunks; i++ {\n chunks[i] = s[i*chunkSize : (i+1)*chunkSize]\n }\n if remainder > 0 {\n chunks = append(chunks, s[nChunks*chunkSize:])\n }\n var sb strings.Builder\n for i := 0; i < nLines; i++ {\n j := i * cols\n sb.WriteString(\" \" + strings.Join(chunks[j:j+cols], \" \") + \"\\n\")\n }\n ss := \" file\\n\" + sb.String()\n switch ft {\n case otp:\n return \"# OTP\" + ss\n case enc:\n return \"# Encrypted\" + ss\n default: // case dec:\n return \"# Decrypted\" + ss\n }\n}\n\nfunc menu() int {\n fmt.Println(`\n1. Create one time pad file.\n\n2. Delete one time pad file.\n\n3. List one time pad files.\n\n4. Encrypt plain text.\n\n5. Decrypt cipher text.\n\n6. Quit program.\n`)\n choice := 0\n for choice < 1 || choice > 6 {\n fmt.Print(\"Your choice (1 to 6) : \")\n scnr.Scan()\n choice, _ = strconv.Atoi(scnr.Text())\n check(scnr.Err())\n }\n return choice\n}\n\nfunc main() {\n for {\n choice := menu()\n fmt.Println()\n switch choice {\n case 1: // Create OTP\n fmt.Println(\"Note that encrypted lines always contain 48 characters.\\n\")\n fmt.Print(\"OTP file name to create (without extension) : \")\n scnr.Scan()\n fileName := scnr.Text() + \".1tp\"\n nLines := 0\n for nLines < 1 || nLines > 1000 {\n fmt.Print(\"Number of lines in OTP (max 1000) : \")\n scnr.Scan()\n nLines, _ = strconv.Atoi(scnr.Text())\n }\n check(scnr.Err())\n key := makePad(nLines)\n file, err := os.Create(fileName)\n check(err)\n _, err = file.WriteString(key)\n check(err)\n file.Close()\n fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", fileName)\n if demo {\n // a copy of the OTP file would normally be on a different machine\n fileName2 := fileName + \"_cpy\" // copy for decryption\n file, err := os.Create(fileName2)\n check(err)\n _, err = file.WriteString(key)\n check(err)\n file.Close()\n fmt.Printf(\"'%s' has been created in the current directory.\\n\", fileName2)\n fmt.Println(\"\\nThe contents of these files are :\\n\")\n fmt.Println(key)\n }\n case 2: // Delete OTP\n fmt.Println(\"Note that this will also delete ALL associated files.\\n\")\n fmt.Print(\"OTP file name to delete (without extension) : \")\n scnr.Scan()\n toDelete1 := scnr.Text() + \".1tp\"\n check(scnr.Err())\n toDelete2 := toDelete1 + \"_cpy\"\n toDelete3 := toDelete1 + \"_enc\"\n toDelete4 := toDelete1 + \"_dec\"\n allToDelete := []string{toDelete1, toDelete2, toDelete3, toDelete4}\n deleted := 0\n fmt.Println()\n for _, name := range allToDelete {\n if _, err := os.Stat(name); !os.IsNotExist(err) {\n err = os.Remove(name)\n check(err)\n deleted++\n fmt.Printf(\"'%s' has been deleted from the current directory.\\n\", name)\n }\n }\n if deleted == 0 {\n fmt.Println(\"There are no files to delete.\")\n }\n case 3: // List OTPs\n fmt.Println(\"The OTP (and related) files in the current directory are:\\n\")\n files, err := ioutil.ReadDir(\".\") // already sorted by file name\n check(err)\n for _, fi := range files {\n name := fi.Name()\n if !fi.IsDir() && isOtpRelated(name) {\n fmt.Println(name)\n }\n }\n case 4: // Encrypt\n fmt.Print(\"OTP file name to use (without extension) : \")\n scnr.Scan()\n keyFile := scnr.Text() + \".1tp\"\n if _, err := os.Stat(keyFile); !os.IsNotExist(err) {\n file, err := os.Open(keyFile)\n check(err)\n bytes, err := ioutil.ReadAll(file)\n check(err)\n file.Close()\n lines := strings.Split(string(bytes), \"\\n\")\n le := len(lines)\n first := le\n for i := 0; i < le; i++ {\n if strings.HasPrefix(lines[i], \" \") {\n first = i\n break\n }\n }\n if first == le {\n fmt.Println(\"\\nThat file has no unused lines.\")\n continue\n }\n lines2 := lines[first:] // get rid of comments and used lines\n\n fmt.Println(\"Text to encrypt :-\\n\")\n scnr.Scan()\n text := toAlpha(strings.ToUpper(scnr.Text()))\n check(scnr.Err())\n tl := len(text)\n nLines := tl / charsPerLine\n if tl%charsPerLine > 0 {\n nLines++\n }\n if len(lines2) >= nLines {\n key := toAlpha(strings.Join(lines2[0:nLines], \"\"))\n encrypted := vigenere(text, key, true)\n encFile := keyFile + \"_enc\"\n file2, err := os.Create(encFile)\n check(err)\n _, err = file2.WriteString(encrypted)\n check(err)\n file2.Close()\n fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", encFile)\n for i := first; i < first+nLines; i++ {\n lines[i] = \"-\" + lines[i][1:]\n }\n file3, err := os.Create(keyFile)\n check(err)\n _, err = file3.WriteString(strings.Join(lines, \"\\n\"))\n check(err)\n file3.Close()\n if demo {\n fmt.Println(\"\\nThe contents of the encrypted file are :\\n\")\n fmt.Println(encrypted)\n }\n } else {\n fmt.Println(\"Not enough lines left in that file to do encryption.\")\n }\n } else {\n fmt.Println(\"\\nThat file does not exist.\")\n }\n case 5: // Decrypt\n fmt.Print(\"OTP file name to use (without extension) : \")\n scnr.Scan()\n keyFile := scnr.Text() + \".1tp_cpy\"\n check(scnr.Err())\n if _, err := os.Stat(keyFile); !os.IsNotExist(err) {\n file, err := os.Open(keyFile)\n check(err)\n bytes, err := ioutil.ReadAll(file)\n check(err)\n file.Close()\n keyLines := strings.Split(string(bytes), \"\\n\")\n le := len(keyLines)\n first := le\n for i := 0; i < le; i++ {\n if strings.HasPrefix(keyLines[i], \" \") {\n first = i\n break\n }\n }\n if first == le {\n fmt.Println(\"\\nThat file has no unused lines.\")\n continue\n }\n keyLines2 := keyLines[first:] // get rid of comments and used lines\n\n encFile := keyFile[0:len(keyFile)-3] + \"enc\"\n if _, err := os.Stat(encFile); !os.IsNotExist(err) {\n file2, err := os.Open(encFile)\n check(err)\n bytes, err := ioutil.ReadAll(file2)\n check(err)\n file2.Close()\n encLines := strings.Split(string(bytes), \"\\n\")[1:] // exclude comment line\n nLines := len(encLines)\n if len(keyLines2) >= nLines {\n encrypted := toAlpha(strings.Join(encLines, \"\"))\n key := toAlpha(strings.Join(keyLines2[0:nLines], \"\"))\n decrypted := vigenere(encrypted, key, false)\n decFile := keyFile[0:len(keyFile)-3] + \"dec\"\n file3, err := os.Create(decFile)\n check(err)\n _, err = file3.WriteString(decrypted)\n check(err)\n file3.Close()\n fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", decFile)\n for i := first; i < first+nLines; i++ {\n keyLines[i] = \"-\" + keyLines[i][1:]\n }\n file4, err := os.Create(keyFile)\n check(err)\n _, err = file4.WriteString(strings.Join(keyLines, \"\\n\"))\n check(err)\n file4.Close()\n if demo {\n fmt.Println(\"\\nThe contents of the decrypted file are :\\n\")\n fmt.Println(decrypted)\n }\n }\n } else {\n fmt.Println(\"Not enough lines left in that file to do decryption.\")\n }\n } else {\n fmt.Println(\"\\nThat file does not exist.\")\n }\n case 6: // Quit program\n return\n }\n }\n}"} {"title": "One of n lines in a file", "language": "Go", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.\n::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.\n::* ...\n::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.\n# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io\"\n \"math/rand\"\n \"time\"\n)\n\n// choseLineRandomly implements the method described in the task.\n// input is a an io.Reader, which could be an os.File, for example.\n// Or, to implement a simulation, it could be anything else that implements\n// io.Reader. The method as described suggests saving and returning\n// lines, but the rest of the task requires line numbers. This function\n// thus returns both.\nfunc choseLineRandomly(r io.Reader) (s string, ln int, err error) {\n br := bufio.NewReader(r)\n s, err = br.ReadString('\\n')\n if err != nil {\n return\n }\n ln = 1\n lnLast := 1.\n var sLast string\n for {\n // note bufio.ReadString used here. This effectively defines a\n // line of the file as zero or more bytes followed by a newline.\n sLast, err = br.ReadString('\\n')\n if err == io.EOF {\n return s, ln, nil // normal return\n }\n if err != nil {\n break\n }\n lnLast++\n if rand.Float64() < 1/lnLast {\n s = sLast\n ln = int(lnLast)\n }\n }\n return // error return\n}\n\n// oneOfN function required for task item 1. Specified to take a number\n// n, the number of lines in a file, but the method (above) specified to\n// to be used does not need n, but rather the file itself. This function\n// thus takes both, ignoring n and passing the file to choseLineRandomly.\nfunc oneOfN(n int, file io.Reader) int {\n _, ln, err := choseLineRandomly(file)\n if err != nil {\n panic(err)\n }\n return ln\n}\n\n// simulated file reader for task item 2\ntype simReader int\n\nfunc (r *simReader) Read(b []byte) (int, error) {\n if *r <= 0 {\n return 0, io.EOF\n }\n b[0] = '\\n'\n *r--\n return 1, nil\n}\n\nfunc main() {\n // task item 2 simulation consists of accumulating frequency statistic\n // on 1,000,000 calls of oneOfN on simulated file.\n n := 10\n freq := make([]int, n)\n rand.Seed(time.Now().UnixNano())\n for times := 0; times < 1e6; times++ {\n sr := simReader(n)\n freq[oneOfN(n, &sr)-1]++\n }\n\n // task item 3. show frequencies.\n fmt.Println(freq)\n}"} {"title": "OpenWebNet password", "language": "Go from Python", "task": "Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist\n\n'''Note:''' Factory default password is '12345'. Changing it is highly recommended !\n\nconversation goes as follows\n\n- *#*1##\n- *99*0##\n- *#603356072##\n\nat which point a password should be sent back, calculated from the \"password open\" that is set in the gateway, and the nonce that was just sent\n\n- *#25280520##\n- *#*1##\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc ownCalcPass(password, nonce string) uint32 {\n start := true\n num1 := uint32(0)\n num2 := num1\n i, _ := strconv.Atoi(password)\n pwd := uint32(i)\n for _, c := range nonce {\n if c != '0' {\n if start {\n num2 = pwd\n }\n start = false\n }\n switch c {\n case '1':\n num1 = (num2 & 0xFFFFFF80) >> 7\n num2 = num2 << 25\n case '2':\n num1 = (num2 & 0xFFFFFFF0) >> 4\n num2 = num2 << 28\n case '3':\n num1 = (num2 & 0xFFFFFFF8) >> 3\n num2 = num2 << 29\n case '4':\n num1 = num2 << 1\n num2 = num2 >> 31\n case '5':\n num1 = num2 << 5\n num2 = num2 >> 27\n case '6':\n num1 = num2 << 12\n num2 = num2 >> 20\n case '7':\n num3 := num2 & 0x0000FF00\n num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)\n num1 = num3 | num4\n num2 = (num2 & 0xFF000000) >> 8\n case '8':\n num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)\n num2 = (num2 & 0x00FF0000) >> 8\n case '9':\n num1 = ^num2\n default:\n num1 = num2\n }\n\n num1 &= 0xFFFFFFFF\n num2 &= 0xFFFFFFFF\n if c != '0' && c != '9' {\n num1 |= num2\n }\n num2 = num1\n }\n return num1\n}\n\nfunc testPasswordCalc(password, nonce string, expected uint32) {\n res := ownCalcPass(password, nonce)\n m := fmt.Sprintf(\"%s %s %-10d %-10d\", password, nonce, res, expected)\n if res == expected {\n fmt.Println(\"PASS\", m)\n } else {\n fmt.Println(\"FAIL\", m)\n }\n}\n\nfunc main() {\n testPasswordCalc(\"12345\", \"603356072\", 25280520)\n testPasswordCalc(\"12345\", \"410501656\", 119537670)\n testPasswordCalc(\"12345\", \"630292165\", 4269684735)\n}"} {"title": "Operator precedence", "language": "Go", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "{| class=\"wikitable\"\n! Precedence\n! Operators\n|-\n| Highest\n| Unary operators: +, -, !, ^, *, &, <-\n|-\n| 5\n| *, /, %, <<, >>, &, &^\n|-\n| 4\n| +, -, |, ^\n|-\n| 3\n| ==, !=, <, <=, >, >=\n|-\n| 2\n| &&\n|-\n| 1\n| ||\n|}\nBinary operators of the same precedence associate from left to right.\nAssociativity has no meaning for unary operators.\n\nSyntactic elements not in the list are not considered operators in Go; if they present ambiguity in order of evaluation, the ambiguity is resolved by other rules specific to those elements.\n\n"} {"title": "Padovan n-step number sequences", "language": "Go from Wren", "task": "As the [[Fibonacci sequence]] expands to the [[Fibonacci n-step number sequences]]; We similarly expand the [[Padovan sequence]] to form these Padovan n-step number sequences.\n\nThe Fibonacci-like sequences can be defined like this:\n\n For n == 2:\n start: 1, 1\n Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2\n For n == N:\n start: First N terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))\n\nFor this task we similarly define terms of the first 2..n-step Padovan sequences as:\n\n For n == 2:\n start: 1, 1, 1\n Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2\n For n == N:\n start: First N + 1 terms of R(N-1, x)\n Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))\n\nThe initial values of the sequences are:\n:: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Padovan n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Values !! OEIS Entry\n|-\n| 2 || 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... || A134816: 'Padovan's spiral numbers'\n|-\n| 3 || 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... || A000930: 'Narayana's cows sequence'\n|-\n| 4 || 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... || A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'\n|-\n| 5 || 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... || A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'\n|-\n| 6 || 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... || \n|-\n| 7 || 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... || A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'\n|-\n| 8 || 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... || \n|-\n|}\n\n\n;Task:\n# Write a function to generate the first t terms, of the first 2..max_n Padovan n-step number sequences as defined above.\n# Use this to print and show here at least the first t=15 values of the first 2..8 n-step sequences. (The OEIS column in the table above should be omitted).\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc padovanN(n, t int) []int {\n if n < 2 || t < 3 {\n ones := make([]int, t)\n for i := 0; i < t; i++ {\n ones[i] = 1\n }\n return ones\n }\n p := padovanN(n-1, t)\n for i := n + 1; i < t; i++ {\n p[i] = 0\n for j := i - 2; j >= i-n-1; j-- {\n p[i] += p[j]\n }\n }\n return p\n}\n\nfunc main() {\n t := 15\n fmt.Println(\"First\", t, \"terms of the Padovan n-step number sequences:\")\n for n := 2; n <= 8; n++ {\n fmt.Printf(\"%d: %3d\\n\", n, padovanN(n, t))\n }\n}"} {"title": "Padovan sequence", "language": "Go from Wren", "task": "The Fibonacci sequence in several ways.\nSome are given in the table below, and the referenced video shows some of the geometric\nsimilarities.\n\n::{| class=\"wikitable\"\n! Comment !! Padovan !! Fibonacci\n|-\n| || || \n|-\n| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci\n|-\n| || || \n|-\n| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1\n|-\n| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)\n|-\n| || || \n|-\n| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34\n|-\n| || || \n|-\n| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g\n|-\n| || 1.324717957244746025960908854... || 1.6180339887498948482...\n|-\n| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2\n|-\n| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1\n|-\n| || || \n|-\n| Spirally tiling the plane using. || Equilateral triangles || Squares\n|-\n| || || \n|-\n| Constants for ... || s= 1.0453567932525329623 || a=5**0.5\n|-\n| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)\n|-\n| || || \n|-\n| L-System Variables. || A,B,C || A,B\n|-\n| L-System Start/Axiom. || A || A\n|-\n| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB\n|}\n\n;Task:\n* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.\n* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.\n* Show the first twenty terms of the sequence.\n* Confirm that the recurrence and floor based functions give the same results for 64 terms,\n* Write a function/method/... using the L-system to generate successive strings.\n* Show the first 10 strings produced from the L-system\n* Confirm that the length of the first 32 strings produced is the Padovan sequence.\n\nShow output here, on this page.\n\n;Ref:\n* The Plastic Ratio - Numberphile video.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n \"strings\"\n)\n\nfunc padovanRecur(n int) []int {\n p := make([]int, n)\n p[0], p[1], p[2] = 1, 1, 1\n for i := 3; i < n; i++ {\n p[i] = p[i-2] + p[i-3]\n }\n return p\n}\n\nfunc padovanFloor(n int) []int {\n var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)\n p, _ = p.SetString(\"1.324717957244746025960908854\")\n s, _ = s.SetString(\"1.0453567932525329623\")\n f := make([]int, n)\n pow := new(big.Rat).SetInt64(1)\n u = u.SetFrac64(1, 2)\n t.Quo(pow, p)\n t.Quo(t, s)\n t.Add(t, u)\n v, _ := t.Float64()\n f[0] = int(math.Floor(v))\n for i := 1; i < n; i++ {\n t.Quo(pow, s)\n t.Add(t, u)\n v, _ = t.Float64()\n f[i] = int(math.Floor(v))\n pow.Mul(pow, p)\n }\n return f\n}\n\ntype LSystem struct {\n rules map[string]string\n init, current string\n}\n\nfunc step(lsys *LSystem) string {\n var sb strings.Builder\n if lsys.current == \"\" {\n lsys.current = lsys.init\n } else {\n for _, c := range lsys.current {\n sb.WriteString(lsys.rules[string(c)])\n }\n lsys.current = sb.String()\n }\n return lsys.current\n}\n\nfunc padovanLSys(n int) []string {\n rules := map[string]string{\"A\": \"B\", \"B\": \"C\", \"C\": \"AB\"}\n lsys := &LSystem{rules, \"A\", \"\"}\n p := make([]string, n)\n for i := 0; i < n; i++ {\n p[i] = step(lsys)\n }\n return p\n}\n\n// assumes lists are same length\nfunc areSame(l1, l2 []int) bool {\n for i := 0; i < len(l1); i++ {\n if l1[i] != l2[i] {\n return false\n }\n }\n return true\n}\n\nfunc main() {\n fmt.Println(\"First 20 members of the Padovan sequence:\")\n fmt.Println(padovanRecur(20))\n recur := padovanRecur(64)\n floor := padovanFloor(64)\n same := areSame(recur, floor)\n s := \"give\"\n if !same {\n s = \"do not give\"\n }\n fmt.Println(\"\\nThe recurrence and floor based functions\", s, \"the same results for 64 terms.\")\n\n p := padovanLSys(32)\n lsyst := make([]int, 32)\n for i := 0; i < 32; i++ {\n lsyst[i] = len(p[i])\n }\n fmt.Println(\"\\nFirst 10 members of the Padovan L-System:\")\n fmt.Println(p[:10])\n fmt.Println(\"\\nand their lengths:\")\n fmt.Println(lsyst[:10])\n\n same = areSame(recur[:32], lsyst)\n s = \"give\"\n if !same {\n s = \"do not give\"\n }\n fmt.Println(\"\\nThe recurrence and L-system based functions\", s, \"the same results for 32 terms.\")\n"} {"title": "Palindrome dates", "language": "Go", "task": "Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format.\n\n\n;Task\nWrite a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc reverse(s string) string {\n chars := []rune(s)\n for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n chars[i], chars[j] = chars[j], chars[i]\n }\n return string(chars)\n}\n\nfunc main() {\n const (\n layout = \"20060102\"\n layout2 = \"2006-01-02\"\n )\n fmt.Println(\"The next 15 palindromic dates in yyyymmdd format after 20200202 are:\")\n date := time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC)\n count := 0\n for count < 15 {\n date = date.AddDate(0, 0, 1)\n s := date.Format(layout)\n r := reverse(s)\n if r == s {\n fmt.Println(date.Format(layout2))\n count++\n }\n }\n}"} {"title": "Palindromic gapful numbers", "language": "Go", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''1037'''. \n\n\nA palindromic number is (for this task, a positive integer expressed in base ten), when the number is \nreversed, is the same as the original number.\n\n\n;Task:\n:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:\n:::* the digit '''1'''\n:::* the digit '''2'''\n:::* the digit '''3'''\n:::* the digit '''4'''\n:::* the digit '''5'''\n:::* the digit '''6'''\n:::* the digit '''7'''\n:::* the digit '''8'''\n:::* the digit '''9'''\n:* Show (nine sets, like above) of palindromic gapful numbers:\n:::* the last '''15''' palindromic gapful numbers (out of '''100''')\n:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}\n\n\nFor other ways of expressing the (above) requirements, see the ''discussion'' page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* palindrome detection.\n:* gapful numbers.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc reverse(s uint64) uint64 {\n e := uint64(0)\n for s > 0 {\n e = e*10 + (s % 10)\n s /= 10\n }\n return e\n}\n\nfunc commatize(n uint) string {\n s := fmt.Sprintf(\"%d\", n)\n le := len(s)\n for i := le - 3; i >= 1; i -= 3 {\n s = s[0:i] + \",\" + s[i:]\n }\n return s\n}\n\nfunc ord(n uint) string {\n var suffix string\n if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {\n suffix = \"th\"\n } else {\n switch n % 10 {\n case 1:\n suffix = \"st\"\n case 2:\n suffix = \"nd\"\n case 3:\n suffix = \"rd\"\n default:\n suffix = \"th\"\n }\n }\n return fmt.Sprintf(\"%s%s\", commatize(n), suffix)\n}\n\nfunc main() {\n const max = 10_000_000\n data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},\n {1e6, 1e6, 16}, {1e7, 1e7, 18}}\n results := make(map[uint][]uint64)\n for _, d := range data {\n for i := d[0]; i <= d[1]; i++ {\n results[i] = make([]uint64, 9)\n }\n }\n var p uint64\nouter:\n for d := uint64(1); d < 10; d++ {\n count := uint(0)\n pow := uint64(1)\n fl := d * 11\n for nd := 3; nd < 20; nd++ {\n slim := (d + 1) * pow\n for s := d * pow; s < slim; s++ {\n e := reverse(s)\n mlim := uint64(1)\n if nd%2 == 1 {\n mlim = 10\n }\n for m := uint64(0); m < mlim; m++ {\n if nd%2 == 0 {\n p = s*pow*10 + e\n } else {\n p = s*pow*100 + m*pow*10 + e\n }\n if p%fl == 0 {\n count++\n if _, ok := results[count]; ok {\n results[count][d-1] = p\n }\n if count == max {\n continue outer\n }\n }\n }\n }\n if nd%2 == 1 {\n pow *= 10\n }\n }\n }\n\n for _, d := range data {\n if d[0] != d[1] {\n fmt.Printf(\"%s to %s palindromic gapful numbers (> 100) ending with:\\n\", ord(d[0]), ord(d[1]))\n } else {\n fmt.Printf(\"%s palindromic gapful number (> 100) ending with:\\n\", ord(d[0]))\n }\n for i := 1; i <= 9; i++ {\n fmt.Printf(\"%d: \", i)\n for j := d[0]; j <= d[1]; j++ {\n fmt.Printf(\"%*d \", d[2], results[j][i-1])\n }\n fmt.Println()\n }\n fmt.Println()\n }\n}"} {"title": "Pancake numbers", "language": "Go from Phix", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# Bill Gates and the pancake problem\n# A058986\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc pancake(n int) int {\n gap, sum, adj := 2, 2, -1\n for sum < n {\n adj++\n gap = gap*2 - 1\n sum += gap\n }\n return n + adj\n}\n\nfunc main() {\n for i := 0; i < 4; i++ {\n for j := 1; j < 6; j++ {\n n := i*5 + j\n fmt.Printf(\"p(%2d) = %2d \", n, pancake(n))\n }\n fmt.Println()\n }\n}"} {"title": "Pancake numbers", "language": "Go from Wren", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# Bill Gates and the pancake problem\n# A058986\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\ntype assoc map[string]int\n\n// Converts a string of the form \"[1 2]\" into a slice of ints: {1, 2}\nfunc asSlice(s string) []int {\n split := strings.Split(s[1:len(s)-1], \" \")\n le := len(split)\n res := make([]int, le)\n for i := 0; i < le; i++ {\n res[i], _ = strconv.Atoi(split[i])\n }\n return res\n}\n\n// Merges two assocs into one. If the same key is present in both assocs\n// its value will be the one in the second assoc.\nfunc merge(m1, m2 assoc) assoc {\n m3 := make(assoc)\n for k, v := range m1 {\n m3[k] = v\n }\n for k, v := range m2 {\n m3[k] = v\n }\n return m3\n}\n\n// Finds the maximum value in 'dict' and returns the first key\n// it finds (iteration order is undefined) with that value.\nfunc findMax(dict assoc) string {\n max := -1\n maxKey := \"\"\n for k, v := range dict {\n if v > max {\n max = v\n maxKey = k\n }\n }\n return maxKey\n}\n\n// Creates a new slice of ints by reversing an existing one.\nfunc reverse(s []int) []int {\n le := len(s)\n rev := make([]int, le)\n for i := 0; i < le; i++ {\n rev[i] = s[le-1-i]\n }\n return rev\n}\n\nfunc pancake(n int) (string, int) {\n numStacks := 1\n gs := make([]int, n)\n for i := 0; i < n; i++ {\n gs[i] = i + 1\n }\n goalStack := fmt.Sprintf(\"%v\", gs)\n stacks := assoc{goalStack: 0}\n newStacks := assoc{goalStack: 0}\n for i := 1; i <= 1000; i++ {\n nextStacks := assoc{}\n for key := range newStacks {\n arr := asSlice(key)\n for pos := 2; pos <= n; pos++ {\n t := append(reverse(arr[0:pos]), arr[pos:len(arr)]...)\n newStack := fmt.Sprintf(\"%v\", t)\n if _, ok := stacks[newStack]; !ok {\n nextStacks[newStack] = i\n }\n }\n }\n newStacks = nextStacks\n stacks = merge(stacks, newStacks)\n perms := len(stacks)\n if perms == numStacks {\n return findMax(stacks), i - 1\n }\n numStacks = perms\n }\n return \"\", 0\n}\n\nfunc main() {\n start := time.Now()\n fmt.Println(\"The maximum number of flips to sort a given number of elements is:\")\n for i := 1; i <= 10; i++ {\n example, steps := pancake(i)\n fmt.Printf(\"pancake(%2d) = %-2d example: %s\\n\", i, steps, example)\n }\n fmt.Printf(\"\\nTook %s\\n\", time.Since(start))\n}"} {"title": "Pangram checker", "language": "Go", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n for _, s := range []string{\n \"The quick brown fox jumps over the lazy dog.\",\n `Watch \"Jeopardy!\", Alex Trebek's fun TV quiz game.`,\n \"Not a pangram.\",\n } {\n if pangram(s) {\n fmt.Println(\"Yes:\", s)\n } else {\n fmt.Println(\"No: \", s)\n }\n }\n}\n\nfunc pangram(s string) bool {\n\tvar missing uint32 = (1 << 26) - 1\n\tfor _, c := range s {\n\t\tvar index uint32\n\t\tif 'a' <= c && c <= 'z' {\n\t\t\tindex = uint32(c - 'a')\n\t\t} else if 'A' <= c && c <= 'Z' {\n\t\t\tindex = uint32(c - 'A')\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\tmissing &^= 1 << index\n\t\tif missing == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"title": "Paraffins", "language": "Go from C", "task": "This organic chemistry task is essentially to implement a tree enumeration algorithm.\n\n\n;Task:\nEnumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). \n\n\nParaffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the \"backbone\" structure, with adding hydrogen atoms linking the remaining unused bonds.\n\nIn a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2\n\nBut for all '''n''' >= 4 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when '''n''' increases. \n\nIn counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D \"out of the paper\" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.\n\n\n;Example:\nWith '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations: \n:::* a straight chain: (CH3)(CH2)(CH2)(CH3) \n:::* a branched chain: (CH3)(CH(CH3))(CH3)\n\nDue to bond rotations, it doesn't matter which direction the branch points in. \n\nThe phenomenon of \"stereo-isomerism\" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.\n\nThe input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \n::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. \n\nThe sequence is (the index starts from zero, and represents the number of carbon atoms):\n\n 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,\n 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,\n 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,\n 10660307791, 27711253769, ...\n\n\n;Extra credit:\nShow the paraffins in some way. \n\nA flat 1D representation, with arrays or lists is enough, for instance:\n\n*Main> all_paraffins 1\n [CCP H H H H]\n*Main> all_paraffins 2\n [BCP (C H H H) (C H H H)]\n*Main> all_paraffins 3\n [CCP H H (C H H H) (C H H H)]\n*Main> all_paraffins 4\n [BCP (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 5\n [CCP H H (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 6\n [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),\n BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),\n BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),\n CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]\nShowing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):\n methane ethane propane isobutane\n \n H H H H H H H H H\n | | | | | | | | |\n H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H\n | | | | | | | | |\n H H H H H H H | H\n |\n H - C - H\n |\n H \n\n;Links:\n* A paper that explains the problem and its solution in a functional language:\nhttp://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf\n\n* A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* A Fortress implementation: (this site has been closed)\nhttp://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nconst branches = 4\nconst nMax = 500\n\nvar rooted, unrooted [nMax + 1]big.Int\nvar c [branches]big.Int\nvar tmp = new(big.Int)\nvar one = big.NewInt(1)\n\nfunc tree(br, n, l, sum int, cnt *big.Int) {\n for b := br + 1; b <= branches; b++ {\n sum += n\n if sum > nMax {\n return\n }\n if l*2 >= sum && b >= branches {\n return\n }\n if b == br+1 {\n c[br].Mul(&rooted[n], cnt)\n } else {\n tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))\n c[br].Mul(&c[br], tmp)\n c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))\n }\n if l*2 < sum {\n unrooted[sum].Add(&unrooted[sum], &c[br])\n }\n if b < branches {\n rooted[sum].Add(&rooted[sum], &c[br])\n }\n for m := n - 1; m > 0; m-- {\n tree(b, m, l, sum, &c[br])\n }\n }\n}\n\nfunc bicenter(s int) {\n if s&1 == 0 {\n tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)\n unrooted[s].Add(&unrooted[s], tmp)\n }\n}\n\nfunc main() {\n rooted[0].SetInt64(1)\n rooted[1].SetInt64(1)\n unrooted[0].SetInt64(1)\n unrooted[1].SetInt64(1)\n for n := 1; n <= nMax; n++ {\n tree(0, n, n, 1, big.NewInt(1))\n bicenter(n)\n fmt.Printf(\"%d: %d\\n\", n, &unrooted[n])\n }\n}"} {"title": "Parse an IP Address", "language": "Go", "task": "The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.\n \n\nTaking the following as inputs:\n::: {| border=\"5\" cellspacing=\"0\" cellpadding=2\n|-\n|127.0.0.1\n|The \"localhost\" IPv4 address\n|-\n|127.0.0.1:80\n|The \"localhost\" IPv4 address, with a specified port (80)\n|-\n|::1\n|The \"localhost\" IPv6 address\n|-\n|[::1]:80\n|The \"localhost\" IPv6 address, with a specified port (80)\n|-\n|2605:2700:0:3::4713:93e3\n|Rosetta Code's primary server's public IPv6 address\n|-\n|[2605:2700:0:3::4713:93e3]:80\n|Rosetta Code's primary server's public IPv6 address, with a specified port (80)\n|}\n\n\n;Task:\nEmit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. \n\nIn languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.\n\n\n;Example:\n'''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal) \nin the ipv4 address space. \n\n'''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the \naddress number '''FFFF7F000001''' (281472812449793 decimal). \n\n'''::1''' has address number '''1''' and serves the same purpose in the ipv6 address \nspace that '''127.0.0.1''' serves in the ipv4 address space.\n\n", "solution": "package main\n\nimport (\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n)\n\n// parseIPPort parses an IP with an optional port, returning an IP and a port (or nil\n// if no port was present in the given address).\nfunc parseIPPort(address string) (net.IP, *uint64, error) {\n\tip := net.ParseIP(address)\n\tif ip != nil {\n\t\treturn ip, nil, nil\n\t}\n\n\thost, portStr, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"splithostport failed: %w\", err)\n\t}\n\n\tport, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse port: %w\", err)\n\t}\n\n\tip = net.ParseIP(host)\n\tif ip == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse ip address\")\n\t}\n\n\treturn ip, &port, nil\n}\n\nfunc ipVersion(ip net.IP) int {\n\tif ip.To4() == nil {\n\t\treturn 6\n\t}\n\n\treturn 4\n}\n\nfunc main() {\n\ttestCases := []string{\n\t\t\"127.0.0.1\",\n\t\t\"127.0.0.1:80\",\n\t\t\"::1\",\n\t\t\"[::1]:443\",\n\t\t\"2605:2700:0:3::4713:93e3\",\n\t\t\"[2605:2700:0:3::4713:93e3]:80\",\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\n\twriteTSV := func(w io.Writer, args ...interface{}) {\n\t\tfmt.Fprintf(w, strings.Repeat(\"%s\\t\", len(args)), args...)\n\t\tfmt.Fprintf(w, \"\\n\")\n\t}\n\n\twriteTSV(w, \"Input\", \"Address\", \"Space\", \"Port\")\n\n\tfor _, addr := range testCases {\n\t\tip, port, err := parseIPPort(addr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tportStr := \"n/a\"\n\t\tif port != nil {\n\t\t\tportStr = fmt.Sprint(*port)\n\t\t}\n\n\t\tipVersion := fmt.Sprintf(\"IPv%d\", ipVersion(ip))\n\n\t\twriteTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)\n\t}\n\n\tw.Flush()\n}\n"} {"title": "Parsing/RPN calculator algorithm", "language": "Go", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"strconv\"\n \"strings\"\n)\n\nvar input = \"3 4 2 * 1 5 - 2 3 ^ ^ / +\"\n\nfunc main() {\n fmt.Printf(\"For postfix %q\\n\", input)\n fmt.Println(\"\\nToken Action Stack\")\n var stack []float64\n for _, tok := range strings.Fields(input) {\n action := \"Apply op to top of stack\"\n switch tok {\n case \"+\":\n stack[len(stack)-2] += stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n case \"-\":\n stack[len(stack)-2] -= stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n case \"*\":\n stack[len(stack)-2] *= stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n case \"/\":\n stack[len(stack)-2] /= stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n case \"^\":\n stack[len(stack)-2] =\n math.Pow(stack[len(stack)-2], stack[len(stack)-1])\n stack = stack[:len(stack)-1]\n default:\n action = \"Push num onto top of stack\"\n f, _ := strconv.ParseFloat(tok, 64)\n stack = append(stack, f)\n }\n fmt.Printf(\"%3s %-26s %v\\n\", tok, action, stack)\n }\n fmt.Println(\"\\nThe final value is\", stack[0])\n}"} {"title": "Parsing/RPN to infix conversion", "language": "Go", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar tests = []string{\n \"3 4 2 * 1 5 - 2 3 ^ ^ / +\",\n \"1 2 + 3 4 + ^ 5 6 + ^\",\n}\n\nvar opa = map[string]struct {\n prec int\n rAssoc bool\n}{\n \"^\": {4, true},\n \"*\": {3, false},\n \"/\": {3, false},\n \"+\": {2, false},\n \"-\": {2, false},\n}\n\nconst nPrec = 9\n\nfunc main() {\n for _, t := range tests {\n parseRPN(t)\n }\n}\n\nfunc parseRPN(e string) {\n fmt.Println(\"\\npostfix:\", e)\n type sf struct {\n prec int\n expr string\n }\n var stack []sf\n for _, tok := range strings.Fields(e) {\n fmt.Println(\"token:\", tok)\n if op, isOp := opa[tok]; isOp {\n rhs := &stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n lhs := &stack[len(stack)-1]\n if lhs.prec < op.prec || (lhs.prec == op.prec && op.rAssoc) {\n lhs.expr = \"(\" + lhs.expr + \")\"\n }\n lhs.expr += \" \" + tok + \" \"\n if rhs.prec < op.prec || (rhs.prec == op.prec && !op.rAssoc) {\n lhs.expr += \"(\" + rhs.expr + \")\"\n } else {\n lhs.expr += rhs.expr\n }\n lhs.prec = op.prec\n } else {\n stack = append(stack, sf{nPrec, tok})\n }\n for _, f := range stack {\n fmt.Printf(\" %d %q\\n\", f.prec, f.expr)\n }\n }\n fmt.Println(\"infix:\", stack[0].expr)\n}"} {"title": "Parsing/Shunting-yard algorithm", "language": "Go", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nvar input = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\"\n\nvar opa = map[string]struct {\n prec int\n rAssoc bool\n}{\n \"^\": {4, true},\n \"*\": {3, false},\n \"/\": {3, false},\n \"+\": {2, false},\n \"-\": {2, false},\n}\n\nfunc main() {\n fmt.Println(\"infix: \", input)\n fmt.Println(\"postfix:\", parseInfix(input))\n}\n\nfunc parseInfix(e string) (rpn string) {\n var stack []string // holds operators and left parenthesis\n for _, tok := range strings.Fields(e) {\n switch tok {\n case \"(\":\n stack = append(stack, tok) // push \"(\" to stack\n case \")\":\n var op string\n for {\n // pop item (\"(\" or operator) from stack\n op, stack = stack[len(stack)-1], stack[:len(stack)-1]\n if op == \"(\" {\n break // discard \"(\"\n }\n rpn += \" \" + op // add operator to result\n }\n default:\n if o1, isOp := opa[tok]; isOp {\n // token is an operator\n for len(stack) > 0 {\n // consider top item on stack\n op := stack[len(stack)-1]\n if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||\n o1.prec == o2.prec && o1.rAssoc {\n break\n }\n // top item is an operator that needs to come off\n stack = stack[:len(stack)-1] // pop it\n rpn += \" \" + op // add it to result\n }\n // push operator (the new one) to stack\n stack = append(stack, tok)\n } else { // token is an operand\n if rpn > \"\" {\n rpn += \" \"\n }\n rpn += tok // add operand to result\n }\n }\n }\n // drain stack to result\n for len(stack) > 0 {\n rpn += \" \" + stack[len(stack)-1]\n stack = stack[:len(stack)-1]\n }\n return\n}"} {"title": "Pascal's triangle/Puzzle", "language": "Go", "task": "This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.\n\n [ 151]\n [ ][ ]\n [40][ ][ ]\n [ ][ ][ ][ ]\n [ X][11][ Y][ 4][ Z]\n\nEach brick of the pyramid is the sum of the two bricks situated below it.\nOf the three missing numbers at the base of the pyramid, \nthe middle one is the sum of the other two (that is, Y = X + Z).\n\n\n;Task:\nWrite a program to find a solution to this puzzle.\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// representation of an expression in x, y, and z\ntype expr struct {\n x, y, z float64 // coefficients\n c float64 // constant term\n}\n\n// add two expressions \nfunc addExpr(a, b expr) expr {\n return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}\n} \n \n// subtract two expressions\nfunc subExpr(a, b expr) expr {\n return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}\n} \n\n// multiply expression by a constant\nfunc mulExpr(a expr, c float64) expr {\n return expr{a.x * c, a.y * c, a.z * c, a.c * c}\n}\n\n// given a row of expressions, produce the next row up, by the given\n// sum relation between blocks \nfunc addRow(l []expr) []expr {\n if len(l) == 0 {\n panic(\"wrong\")\n }\n r := make([]expr, len(l)-1)\n for i := range r {\n r[i] = addExpr(l[i], l[i+1])\n }\n return r\n} \n\n// given expression b in a variable, and expression a, \n// take b == 0 and substitute to remove that variable from a.\nfunc substX(a, b expr) expr {\n if b.x == 0 {\n panic(\"wrong\")\n }\n return subExpr(a, mulExpr(b, a.x/b.x))\n}\n\nfunc substY(a, b expr) expr {\n if b.y == 0 {\n panic(\"wrong\")\n }\n return subExpr(a, mulExpr(b, a.y/b.y))\n}\n\nfunc substZ(a, b expr) expr {\n if b.z == 0 {\n panic(\"wrong\")\n }\n return subExpr(a, mulExpr(b, a.z/b.z))\n}\n\n// given an expression in a single variable, return value of that variable\nfunc solveX(a expr) float64 {\n if a.x == 0 || a.y != 0 || a.z != 0 {\n panic(\"wrong\")\n }\n return -a.c / a.x\n}\n\nfunc solveY(a expr) float64 {\n if a.x != 0 || a.y == 0 || a.z != 0 {\n panic(\"wrong\")\n }\n return -a.c / a.y\n}\n\nfunc solveZ(a expr) float64 {\n if a.x != 0 || a.y != 0 || a.z == 0 {\n panic(\"wrong\")\n }\n return -a.c / a.z\n}\n\nfunc main() {\n // representation of given information for bottom row\n r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}\n fmt.Println(\"bottom row:\", r5)\n\n // given definition of brick sum relation\n r4 := addRow(r5)\n fmt.Println(\"next row up:\", r4)\n r3 := addRow(r4)\n fmt.Println(\"middle row:\", r3)\n\n // given relation y = x + z\n xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})\n fmt.Println(\"xyz relation:\", xyz)\n // remove z from third cell using xyz relation\n r3[2] = substZ(r3[2], xyz)\n fmt.Println(\"middle row after substituting for z:\", r3)\n\n // given cell = 40,\n b := expr{c: 40}\n // this gives an xy relation\n xy := subExpr(r3[0], b)\n fmt.Println(\"xy relation:\", xy)\n // substitute 40 for cell\n r3[0] = b\n\n // remove x from third cell using xy relation\n r3[2] = substX(r3[2], xy)\n fmt.Println(\"middle row after substituting for x:\", r3)\n \n // continue applying brick sum relation to get top cell\n r2 := addRow(r3)\n fmt.Println(\"next row up:\", r2)\n r1 := addRow(r2)\n fmt.Println(\"top row:\", r1)\n\n // given top cell = 151, we have an equation in y\n y := subExpr(r1[0], expr{c: 151})\n fmt.Println(\"y relation:\", y)\n // using xy relation, we get an equation in x\n x := substY(xy, y)\n fmt.Println(\"x relation:\", x)\n // using xyz relation, we get an equation in z\n z := substX(substY(xyz, y), x)\n fmt.Println(\"z relation:\", z)\n\n // show final answers\n fmt.Println(\"x =\", solveX(x))\n fmt.Println(\"y =\", solveY(y))\n fmt.Println(\"z =\", solveZ(z)) \n}"} {"title": "Pascal matrix generation", "language": "Go from Kotlin", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc binomial(n, k int) int {\n if n < k {\n return 0\n }\n if n == 0 || k == 0 {\n return 1\n }\n num := 1\n for i := k + 1; i <= n; i++ {\n num *= i\n }\n den := 1\n for i := 2; i <= n-k; i++ {\n den *= i\n }\n return num / den\n}\n\nfunc pascalUpperTriangular(n int) [][]int {\n m := make([][]int, n)\n for i := 0; i < n; i++ {\n m[i] = make([]int, n)\n for j := 0; j < n; j++ {\n m[i][j] = binomial(j, i)\n }\n }\n return m\n}\n\nfunc pascalLowerTriangular(n int) [][]int {\n m := make([][]int, n)\n for i := 0; i < n; i++ {\n m[i] = make([]int, n)\n for j := 0; j < n; j++ {\n m[i][j] = binomial(i, j)\n }\n }\n return m\n}\n\nfunc pascalSymmetric(n int) [][]int {\n m := make([][]int, n)\n for i := 0; i < n; i++ {\n m[i] = make([]int, n)\n for j := 0; j < n; j++ {\n m[i][j] = binomial(i+j, i)\n }\n }\n return m\n}\n\nfunc printMatrix(title string, m [][]int) {\n n := len(m)\n fmt.Println(title)\n fmt.Print(\"[\")\n for i := 0; i < n; i++ {\n if i > 0 {\n fmt.Print(\" \")\n }\n mi := strings.Replace(fmt.Sprint(m[i]), \" \", \", \", -1)\n fmt.Print(mi)\n if i < n-1 {\n fmt.Println(\",\")\n } else {\n fmt.Println(\"]\\n\")\n }\n }\n}\n\nfunc main() {\n printMatrix(\"Pascal upper-triangular matrix\", pascalUpperTriangular(5))\n printMatrix(\"Pascal lower-triangular matrix\", pascalLowerTriangular(5))\n printMatrix(\"Pascal symmetric matrix\", pascalSymmetric(5))\n}"} {"title": "Password generator", "language": "Go", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "package main\n\nimport (\n\t\"crypto/rand\"\n\t\"math/big\"\n\t\"strings\"\n\t\"flag\"\n\t\"math\"\n \"fmt\" \n)\n\nvar lowercase = \"abcdefghijklmnopqrstuvwxyz\"\nvar uppercase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nvar numbers = \"0123456789\"\nvar signs = \"!\\\"#$%&'()*+,-./:;<=>?@[]^_{|}~\"\nvar similar = \"Il1O05S2Z\"\n\nfunc check(e error){\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc randstr(length int, alphastr string) string{\n\talphabet := []byte(alphastr)\n\tpass := make([]byte,length)\n\tfor i := 0; i < length; i++ {\n\t\tbign, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))\n\t\tcheck(err)\n\t\tn := bign.Int64()\n\t\tpass[i] = alphabet[n]\n\t}\n\treturn string(pass)\n}\n\nfunc verify(pass string,checkUpper bool,checkLower bool, checkNumber bool, checkSign bool) bool{\n\tisValid := true\n\tif(checkUpper){\n\t\tisValid = isValid && strings.ContainsAny(pass,uppercase)\n\t}\n\tif(checkLower){\n\t\tisValid = isValid && strings.ContainsAny(pass,lowercase)\n\t}\n\tif(checkNumber){\n\t\tisValid = isValid && strings.ContainsAny(pass,numbers)\n\t}\n\tif(checkSign){\n\t\tisValid = isValid && strings.ContainsAny(pass,signs)\n\t}\n\treturn isValid\n}\n\n\nfunc main() {\n\tpassCount := flag.Int(\"pc\", 6, \"Number of passwords\")\n\tpassLength := flag.Int(\"pl\", 10, \"Passwordlength\")\n\tuseUpper := flag.Bool(\"upper\", true, \"Enables or disables uppercase letters\")\n\tuseLower := flag.Bool(\"lower\", true, \"Enables or disables lowercase letters\")\n\tuseSign := flag.Bool(\"sign\", true, \"Enables or disables signs\")\n\tuseNumbers := flag.Bool(\"number\", true, \"Enables or disables numbers\")\n\tuseSimilar := flag.Bool(\"similar\", true,\"Enables or disables visually similar characters\")\n\tflag.Parse()\n\n\tpassAlphabet := \"\"\n\tif *useUpper {\n\t\tpassAlphabet += uppercase\n\t}\n\tif *useLower {\n\t\tpassAlphabet += lowercase\n\t}\n\tif *useSign {\n\t\tpassAlphabet += signs\n\t}\n\tif *useNumbers {\n\t\tpassAlphabet += numbers\n\t}\n\tif !*useSimilar {\n\t\tfor _, r := range similar{\n\t\t\tpassAlphabet = strings.Replace(passAlphabet,string(r),\"\", 1)\n\t\t}\n\t}\n\tfmt.Printf(\"Generating passwords with an average entropy of %.1f bits \\n\", math.Log2(float64(len(passAlphabet))) * float64(*passLength))\n\tfor i := 0; i < *passCount;i++{\n\t\tpassFound := false\n\t\tpass := \"\"\n\t\tfor(!passFound){\n\t\t\tpass = randstr(*passLength,passAlphabet)\n\t\t\tpassFound = verify(pass,*useUpper,*useLower,*useNumbers,*useSign)\n\t\t}\n\t\tfmt.Println(pass)\n\t}\n}\n"} {"title": "Pathological floating point problems", "language": "Go", "task": "Most programmers are familiar with the inexactness of floating point calculations in a binary processor. \n\nThe classic example being:\n\n0.1 + 0.2 = 0.30000000000000004\n\n\nIn many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.\n\nThere are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.\n\nThis task's purpose is to show how your language deals with such classes of problems.\n\n\n'''A sequence that seems to converge to a wrong limit.''' \n\nConsider the sequence:\n:::::: v1 = 2 \n:::::: v2 = -4 \n:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) \n\n\nAs '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.\n\n n = 3 18.5\n n = 4 9.378378\n n = 5 7.801153\n n = 6 7.154414\n n = 7 6.806785\n n = 8 6.5926328\n n = 20 6.0435521101892689\n n = 30 6.006786093031205758530554\n n = 50 6.0001758466271871889456140207471954695237\n n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266\n\n\n\n;Task 2:\n'''The Chaotic Bank Society''' is offering a new investment account to their customers. \n\nYou first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.\n\nAfter each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. \n\nSo ...\n::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.\n::* after 2 years your balance will be doubled and $1 removed.\n::* after 3 years your balance will be tripled and $1 removed.\n::* ... \n::* after 10 years, multiplied by 10 and $1 removed, and so on. \n\n\nWhat will your balance be after 25 years?\n Starting balance: $e-1\n Balance = (Balance * year) - 1 for 25 years\n Balance after 25 years: $0.0399387296732302\n\n\n;Task 3, extra credit:\n'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.\n:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) \n:::::: compute f(a,b) where a=77617.0 and b=33096.0 \n:::::: f(77617.0, 33096.0) = -0.827396059946821 \n\n\nDemonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.\n\n\n;See also;\n* Floating-Point Arithmetic Section 1.3.2 Difficult problems.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n sequence()\n bank()\n rump()\n}\n\nfunc sequence() {\n // exact computations using big.Rat\n var v, v1 big.Rat\n v1.SetInt64(2)\n v.SetInt64(-4)\n n := 2\n c111 := big.NewRat(111, 1)\n c1130 := big.NewRat(1130, 1)\n c3000 := big.NewRat(3000, 1)\n var t2, t3 big.Rat\n r := func() (vn big.Rat) {\n vn.Add(vn.Sub(c111, t2.Quo(c1130, &v)), t3.Quo(c3000, t3.Mul(&v, &v1)))\n return\n }\n fmt.Println(\" n sequence value\")\n for _, x := range []int{3, 4, 5, 6, 7, 8, 20, 30, 50, 100} {\n for ; n < x; n++ {\n v1, v = v, r()\n }\n f, _ := v.Float64()\n fmt.Printf(\"%3d %19.16f\\n\", n, f)\n }\n}\n\nfunc bank() {\n // balance as integer multiples of e and whole dollars using big.Int\n var balance struct{ e, d big.Int }\n // initial balance\n balance.e.SetInt64(1)\n balance.d.SetInt64(-1)\n // compute balance over 25 years\n var m, one big.Int\n one.SetInt64(1)\n for y := 1; y <= 25; y++ {\n m.SetInt64(int64(y))\n balance.e.Mul(&m, &balance.e)\n balance.d.Mul(&m, &balance.d)\n balance.d.Sub(&balance.d, &one)\n }\n // sum account components using big.Float\n var e, ef, df, b big.Float\n e.SetPrec(100).SetString(\"2.71828182845904523536028747135\")\n ef.SetInt(&balance.e)\n df.SetInt(&balance.d)\n b.Add(b.Mul(&e, &ef), &df)\n fmt.Printf(\"Bank balance after 25 years: $%.2f\\n\", &b)\n}\n\nfunc rump() {\n a, b := 77617., 33096.\n fmt.Printf(\"Rump f(%g, %g): %g\\n\", a, b, f(a, b))\n}\n\nfunc f(a, b float64) float64 {\n // computations done with big.Float with enough precision to give\n // a correct answer.\n fp := func(x float64) *big.Float { return big.NewFloat(x).SetPrec(128) }\n a1 := fp(a)\n b1 := fp(b)\n a2 := new(big.Float).Mul(a1, a1)\n b2 := new(big.Float).Mul(b1, b1)\n b4 := new(big.Float).Mul(b2, b2)\n b6 := new(big.Float).Mul(b2, b4)\n b8 := new(big.Float).Mul(b4, b4)\n two := fp(2)\n t1 := fp(333.75)\n t1.Mul(t1, b6)\n t21 := fp(11)\n t21.Mul(t21.Mul(t21, a2), b2)\n t23 := fp(121)\n t23.Mul(t23, b4)\n t2 := new(big.Float).Sub(t21, b6)\n t2.Mul(a2, t2.Sub(t2.Sub(t2, t23), two))\n t3 := fp(5.5)\n t3.Mul(t3, b8)\n t4 := new(big.Float).Mul(two, b1)\n t4.Quo(a1, t4)\n s := new(big.Float).Add(t1, t2)\n f64, _ := s.Add(s.Add(s, t3), t4).Float64()\n return f64\n}"} {"title": "Peaceful chess queen armies", "language": "Go", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\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\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* A250000 OEIS\n\n", "solution": "package main\n\nimport \"fmt\"\n\nconst (\n empty = iota\n black\n white\n)\n\nconst (\n bqueen = 'B'\n wqueen = 'W'\n bbullet = '\u2022'\n wbullet = '\u25e6'\n)\n\ntype position struct{ i, j int }\n\nfunc iabs(i int) int {\n if i < 0 {\n return -i\n }\n return i\n}\n\nfunc place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {\n if m == 0 {\n return true\n }\n placingBlack := true\n for i := 0; i < n; i++ {\n inner:\n for j := 0; j < n; j++ {\n pos := position{i, j}\n for _, queen := range *pBlackQueens {\n if queen == pos || !placingBlack && isAttacking(queen, pos) {\n continue inner\n }\n }\n for _, queen := range *pWhiteQueens {\n if queen == pos || placingBlack && isAttacking(queen, pos) {\n continue inner\n }\n }\n if placingBlack {\n *pBlackQueens = append(*pBlackQueens, pos)\n placingBlack = false\n } else {\n *pWhiteQueens = append(*pWhiteQueens, pos)\n if place(m-1, n, pBlackQueens, pWhiteQueens) {\n return true\n }\n *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]\n placingBlack = true\n }\n }\n }\n if !placingBlack {\n *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]\n }\n return false\n}\n\nfunc isAttacking(queen, pos position) bool {\n if queen.i == pos.i {\n return true\n }\n if queen.j == pos.j {\n return true\n }\n if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {\n return true\n }\n return false\n}\n\nfunc printBoard(n int, blackQueens, whiteQueens []position) {\n board := make([]int, n*n)\n for _, queen := range blackQueens {\n board[queen.i*n+queen.j] = black\n }\n for _, queen := range whiteQueens {\n board[queen.i*n+queen.j] = white\n }\n\n for i, b := range board {\n if i != 0 && i%n == 0 {\n fmt.Println()\n }\n switch b {\n case black:\n fmt.Printf(\"%c \", bqueen)\n case white:\n fmt.Printf(\"%c \", wqueen)\n case empty:\n if i%2 == 0 {\n fmt.Printf(\"%c \", bbullet)\n } else {\n fmt.Printf(\"%c \", wbullet)\n }\n }\n }\n fmt.Println(\"\\n\")\n}\n\nfunc main() {\n nms := [][2]int{\n {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n }\n for _, nm := range nms {\n n, m := nm[0], nm[1]\n fmt.Printf(\"%d black and %d white queens on a %d x %d board:\\n\", m, m, n, n)\n var blackQueens, whiteQueens []position\n if place(m, n, &blackQueens, &whiteQueens) {\n printBoard(n, blackQueens, whiteQueens)\n } else {\n fmt.Println(\"No solution exists.\\n\")\n }\n }\n}"} {"title": "Pentomino tiling", "language": "Go from Java", "task": "A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, \nif you don't count rotations and reflections. Most pentominoes can form their own mirror image through \nrotation, but some of them have to be flipped over.\n\n I \n I L N Y \n FF I L NN PP TTT V W X YY ZZ\nFF I L N PP T U U V WW XXX Y Z \n F I LL N P T UUU VVV WW X Y ZZ \n\n\nA Pentomino tiling is an example of an exact cover problem and can take on many forms. \nA traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered \nby the 12 pentomino shapes, without overlaps, with every shape only used once.\n\nThe 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.\n\n\n;Task\nCreate an 8 by 8 tiling and print the result.\n\n\n;Example\n\nF I I I I I L N\nF F F L L L L N\nW F - X Z Z N N\nW W X X X Z N V\nT W W X - Z Z V\nT T T P P V V V\nT Y - P P U U U\nY Y Y Y P U - U\n\n\n;Related tasks\n* Free polyominoes enumeration\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nvar F = [][]int{\n {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},\n {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},\n {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},\n {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},\n}\n\nvar I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}\n\nvar L = [][]int{\n {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},\n {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},\n {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},\n}\n\nvar N = [][]int{\n {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},\n {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},\n {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},\n}\n\nvar P = [][]int{\n {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},\n {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},\n {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},\n}\n\nvar T = [][]int{\n {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},\n {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},\n}\n\nvar U = [][]int{\n {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},\n {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},\n}\n\nvar V = [][]int{\n {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},\n {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},\n}\n\nvar W = [][]int{\n {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},\n {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},\n}\n\nvar X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}\n\nvar Y = [][]int{\n {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},\n {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},\n {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},\n}\n\nvar Z = [][]int{\n {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},\n {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},\n}\n\nvar shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}\n\nvar symbols = []byte(\"FILNPTUVWXYZ-\")\n\nconst (\n nRows = 8\n nCols = 8\n blank = 12\n)\n\nvar grid [nRows][nCols]int\nvar placed [12]bool\n\nfunc tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {\n for i := 0; i < len(o); i += 2 {\n x := c + o[i+1]\n y := r + o[i]\n if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {\n return false\n }\n }\n grid[r][c] = shapeIndex\n for i := 0; i < len(o); i += 2 {\n grid[r+o[i]][c+o[i+1]] = shapeIndex\n }\n return true\n}\n\nfunc removeOrientation(o []int, r, c int) {\n grid[r][c] = -1\n for i := 0; i < len(o); i += 2 {\n grid[r+o[i]][c+o[i+1]] = -1\n }\n}\n\nfunc solve(pos, numPlaced int) bool {\n if numPlaced == len(shapes) {\n return true\n }\n row := pos / nCols\n col := pos % nCols\n if grid[row][col] != -1 {\n return solve(pos+1, numPlaced)\n }\n\n for i := range shapes {\n if !placed[i] {\n for _, orientation := range shapes[i] {\n if !tryPlaceOrientation(orientation, row, col, i) {\n continue\n }\n placed[i] = true\n if solve(pos+1, numPlaced+1) {\n return true\n }\n removeOrientation(orientation, row, col)\n placed[i] = false\n }\n }\n }\n return false\n}\n\nfunc shuffleShapes() {\n rand.Shuffle(len(shapes), func(i, j int) {\n shapes[i], shapes[j] = shapes[j], shapes[i]\n symbols[i], symbols[j] = symbols[j], symbols[i]\n })\n}\n\nfunc printResult() {\n for _, r := range grid {\n for _, i := range r {\n fmt.Printf(\"%c \", symbols[i])\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n shuffleShapes()\n for r := 0; r < nRows; r++ {\n for i := range grid[r] {\n grid[r][i] = -1\n }\n }\n for i := 0; i < 4; i++ {\n var randRow, randCol int\n for {\n randRow = rand.Intn(nRows)\n randCol = rand.Intn(nCols)\n if grid[randRow][randCol] != blank {\n break\n }\n }\n grid[randRow][randCol] = blank\n }\n if solve(0, 0) {\n printResult()\n } else {\n fmt.Println(\"No solution\")\n }\n}"} {"title": "Perfect shuffle", "language": "Go", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype Deck struct {\n\tCards []int\n\tlength int\n}\n\nfunc NewDeck(deckSize int) (res *Deck){\n\tif deckSize % 2 != 0{\n\t\tpanic(\"Deck size must be even\")\n\t}\n\tres = new(Deck)\n\tres.Cards = make([]int, deckSize)\n\tres.length = deckSize\n\tfor i,_ := range res.Cards{\n\t\tres.Cards[i] = i\n\t}\n\treturn\n}\nfunc (d *Deck)shuffleDeck(){\n\ttmp := make([]int,d.length)\n\tfor i := 0;i = k and k >= 1\")\n }\n\n s := 1\n for n&1 == 0 && k&1 == 0 {\n n >>= 1\n k >>= 1\n s <<= 1\n }\n\n t := n\n if n&1 != 0 {\n t = -k\n }\n for t != 0 {\n for t&1 == 0 {\n t >>= 1\n }\n if t > 0 {\n n = t\n } else {\n k = -t\n }\n t = n - k\n }\n return n * s\n}\n\nfunc totient(n int) int {\n tot := 0\n for k := 1; k <= n; k++ {\n if gcd(n, k) == 1 {\n tot++\n }\n }\n return tot\n}\n\nfunc main() {\n var perfect []int\n for n := 1; len(perfect) < 20; n += 2 {\n tot := n\n sum := 0\n for tot != 1 {\n tot = totient(tot)\n sum += tot\n }\n if sum == n {\n perfect = append(perfect, n)\n }\n }\n fmt.Println(\"The first 20 perfect totient numbers are:\")\n fmt.Println(perfect)\n}"} {"title": "Periodic table", "language": "Go from Wren", "task": "Display the row and column in the periodic table of the given atomic number.\n\n;The periodic table:\nLet us consider the following periodic table representation.\n\n\n __________________________________________________________________________ \n | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |\n | |\n |1 H He |\n | |\n |2 Li Be B C N O F Ne |\n | |\n |3 Na Mg Al Si P S Cl Ar |\n | |\n |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr |\n | |\n |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe |\n | |\n |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn |\n | |\n |7 Fr Ra deg Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og |\n |__________________________________________________________________________|\n | |\n | |\n |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu |\n | |\n |9 Aktinoidideg Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr |\n |__________________________________________________________________________|\n\n\n;Example test cases;\n\n* 1 -> 1 1\n* 2 -> 1 18\n* 29 -> 4 11\n* 42 -> 5 6\n* 57 -> 8 4\n* 58 -> 8 5\n* 72 -> 6 4\n* 89 -> 9 4\n\n;Details;\n\nThe representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3.\n\nYou may take a look at the atomic number repartitions here.\n\nThe atomic number is at least 1, at most 118.\n\n\n;See also: \n* the periodic table\n* This task was an idea from CompSciFact\n* The periodic table in ascii that was used as template\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n)\n\nvar limits = [][2]int{\n {3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118},\n}\n\nfunc periodicTable(n int) (int, int) {\n if n < 1 || n > 118 {\n log.Fatal(\"Atomic number is out of range.\")\n }\n if n == 1 {\n return 1, 1\n }\n if n == 2 {\n return 1, 18\n }\n if n >= 57 && n <= 71 {\n return 8, n - 53\n }\n if n >= 89 && n <= 103 {\n return 9, n - 85\n }\n var row, start, end int\n for i := 0; i < len(limits); i++ {\n limit := limits[i]\n if n >= limit[0] && n <= limit[1] {\n row, start, end = i+2, limit[0], limit[1]\n break\n }\n }\n if n < start+2 || row == 4 || row == 5 {\n return row, n - start + 1\n }\n return row, n - end + 18\n}\n\nfunc main() {\n for _, n := range []int{1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113} {\n row, col := periodicTable(n)\n fmt.Printf(\"Atomic number %3d -> %d, %-2d\\n\", n, row, col)\n }\n}"} {"title": "Perlin noise", "language": "Go", "task": "The '''computer graphics, most notably to procedurally generate textures or heightmaps. \n\nThe Perlin noise is basically a pseudo-random mapping of \\R^d into \\R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4.\n\nEither by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.\n\n\n''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n fmt.Println(noise(3.14, 42, 7))\n}\n\nfunc noise(x, y, z float64) float64 {\n X := int(math.Floor(x)) & 255\n Y := int(math.Floor(y)) & 255\n Z := int(math.Floor(z)) & 255\n x -= math.Floor(x)\n y -= math.Floor(y)\n z -= math.Floor(z)\n u := fade(x)\n v := fade(y)\n w := fade(z)\n A := p[X] + Y\n AA := p[A] + Z\n AB := p[A+1] + Z\n B := p[X+1] + Y\n BA := p[B] + Z\n BB := p[B+1] + Z\n return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),\n grad(p[BA], x-1, y, z)),\n lerp(u, grad(p[AB], x, y-1, z),\n grad(p[BB], x-1, y-1, z))),\n lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),\n grad(p[BA+1], x-1, y, z-1)),\n lerp(u, grad(p[AB+1], x, y-1, z-1),\n grad(p[BB+1], x-1, y-1, z-1))))\n}\nfunc fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) }\nfunc lerp(t, a, b float64) float64 { return a + t*(b-a) }\nfunc grad(hash int, x, y, z float64) float64 {\n // Go doesn't have a ternary. Ternaries can be translated directly\n // with if statements, but chains of if statements are often better\n // expressed with switch statements.\n switch hash & 15 {\n case 0, 12:\n return x + y\n case 1, 14:\n return y - x\n case 2:\n return x - y\n case 3:\n return -x - y\n case 4:\n return x + z\n case 5:\n return z - x\n case 6:\n return x - z\n case 7:\n return -x - z\n case 8:\n return y + z\n case 9, 13:\n return z - y\n case 10:\n return y - z\n }\n // case 11, 16:\n return -y - z\n}\n\nvar permutation = []int{\n 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n}\nvar p = append(permutation, permutation...)"} {"title": "Permutations/Derangements", "language": "Go", "task": "A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.\n\nFor example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).\n\nThe number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. \nThere are various ways to calculate !''n''.\n\n\n;Task:\n# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). \n# Generate ''and show'' all the derangements of 4 integers using the above routine.\n# Create a function that calculates the subfactorial of ''n'', !''n''.\n# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.\n\n\n;Optional stretch goal:\n* Calculate !''20'' \n\n\n;Related tasks:\n* [[Anagrams/Deranged anagrams]]\n* [[Best shuffle]]\n* [[Left_factorials]]\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\n// task 1: function returns list of derangements of n integers\nfunc dList(n int) (r [][]int) {\n a := make([]int, n)\n for i := range a {\n a[i] = i\n }\n // recursive closure permutes a\n var recurse func(last int)\n recurse = func(last int) {\n if last == 0 {\n // bottom of recursion. you get here once for each permutation.\n // test if permutation is deranged.\n for j, v := range a {\n if j == v {\n return // no, ignore it\n }\n }\n // yes, save a copy\n r = append(r, append([]int{}, a...))\n return\n }\n for i := last; i >= 0; i-- {\n a[i], a[last] = a[last], a[i]\n recurse(last - 1)\n a[i], a[last] = a[last], a[i]\n }\n }\n recurse(n - 1)\n return\n}\n\n// task 3: function computes subfactorial of n\nfunc subFact(n int) *big.Int {\n if n == 0 {\n return big.NewInt(1)\n } else if n == 1 {\n return big.NewInt(0)\n }\n d0 := big.NewInt(1)\n d1 := big.NewInt(0)\n f := new(big.Int)\n for i, n64 := int64(1), int64(n); i < n64; i++ {\n d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1))\n }\n return d1\n}\n\nfunc main() {\n // task 2:\n fmt.Println(\"Derangements of 4 integers\")\n for _, d := range dList(4) {\n fmt.Println(d)\n }\n\n // task 4:\n fmt.Println(\"\\nNumber of derangements\")\n fmt.Println(\"N Counted Calculated\")\n for n := 0; n <= 9; n++ {\n fmt.Printf(\"%d %8d %11s\\n\", n, len(dList(n)), subFact(n).String())\n }\n\n // stretch (sic)\n fmt.Println(\"\\n!20 =\", subFact(20))\n}"} {"title": "Permutations/Rank of a permutation", "language": "Go", "task": "A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. \nFor our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).\n\nFor example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:\n\n PERMUTATION RANK\n (0, 1, 2, 3) -> 0\n (0, 1, 3, 2) -> 1\n (0, 2, 1, 3) -> 2\n (0, 2, 3, 1) -> 3\n (0, 3, 1, 2) -> 4\n (0, 3, 2, 1) -> 5\n (1, 0, 2, 3) -> 6\n (1, 0, 3, 2) -> 7\n (1, 2, 0, 3) -> 8\n (1, 2, 3, 0) -> 9\n (1, 3, 0, 2) -> 10\n (1, 3, 2, 0) -> 11\n (2, 0, 1, 3) -> 12\n (2, 0, 3, 1) -> 13\n (2, 1, 0, 3) -> 14\n (2, 1, 3, 0) -> 15\n (2, 3, 0, 1) -> 16\n (2, 3, 1, 0) -> 17\n (3, 0, 1, 2) -> 18\n (3, 0, 2, 1) -> 19\n (3, 1, 0, 2) -> 20\n (3, 1, 2, 0) -> 21\n (3, 2, 0, 1) -> 22\n (3, 2, 1, 0) -> 23\n\nAlgorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).\n\nOne use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.\n\nA question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.\n\n\n;Task:\n# Create a function to generate a permutation from a rank.\n# Create the inverse function that given the permutation generates its rank.\n# Show that for n=3 the two functions are indeed inverses of each other.\n# Compute and show here 4 random, individual, samples of permutations of 12 objects.\n\n\n;Stretch goal:\n* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.\n\n\n;References:\n# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).\n# Ranks on the DevData site.\n# Another answer on Stack Overflow to a different question that explains its algorithm in detail.\n\n;Related tasks:\n#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n)\n\n// returns permutation q of n items, using Myrvold-Ruskey rank.\nfunc MRPerm(q, n int) []int {\n p := ident(n)\n var r int\n for n > 0 {\n q, r = q/n, q%n\n n--\n p[n], p[r] = p[r], p[n]\n }\n return p\n}\n\n// returns identity permutation of n items.\nfunc ident(n int) []int {\n p := make([]int, n)\n for i := range p {\n p[i] = i\n }\n return p\n}\n\n// returns Myrvold-Ruskey rank of permutation p\nfunc MRRank(p []int) (r int) {\n p = append([]int{}, p...)\n inv := inverse(p)\n for i := len(p) - 1; i > 0; i-- {\n s := p[i]\n p[inv[i]] = s\n inv[s] = inv[i]\n }\n for i := 1; i < len(p); i++ {\n r = r*(i+1) + p[i]\n }\n return\n}\n\n// returns inverse of a permutation.\nfunc inverse(p []int) []int {\n r := make([]int, len(p))\n for i, x := range p {\n r[x] = i\n }\n return r\n}\n\n// returns n!\nfunc fact(n int) (f int) {\n for f = n; n > 2; {\n n--\n f *= n\n }\n return\n}\n\nfunc main() {\n n := 3\n fmt.Println(\"permutations of\", n, \"items\")\n f := fact(n)\n for i := 0; i < f; i++ {\n p := MRPerm(i, n)\n fmt.Println(i, p, MRRank(p))\n }\n n = 12\n fmt.Println(\"permutations of\", n, \"items\")\n f = fact(n)\n m := map[int]bool{}\n for len(m) < 4 {\n r := rand.Intn(f)\n if m[r] {\n continue\n }\n m[r] = true\n fmt.Println(r, MRPerm(r, n))\n }\n}"} {"title": "Permutations by swapping", "language": "Go", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "package permute\n\n// Iter takes a slice p and returns an iterator function. The iterator\n// permutes p in place and returns the sign. After all permutations have\n// been generated, the iterator returns 0 and p is left in its initial order.\nfunc Iter(p []int) func() int {\n f := pf(len(p))\n return func() int {\n return f(p)\n }\n}\n\n// Recursive function used by perm, returns a chain of closures that\n// implement a loopless recursive SJT.\nfunc pf(n int) func([]int) int {\n sign := 1\n switch n {\n case 0, 1:\n return func([]int) (s int) {\n s = sign\n sign = 0\n return\n }\n default:\n p0 := pf(n - 1)\n i := n\n var d int\n return func(p []int) int {\n switch {\n case sign == 0:\n case i == n:\n i--\n sign = p0(p[:i])\n d = -1\n case i == 0:\n i++\n sign *= p0(p[1:])\n d = 1\n if sign == 0 {\n p[0], p[1] = p[1], p[0]\n }\n default:\n p[i], p[i-1] = p[i-1], p[i]\n sign = -sign\n i += d\n }\n return sign\n }\n }\n}"} {"title": "Phrase reversals", "language": "Go", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst phrase = \"rosetta code phrase reversal\"\n\nfunc revStr(s string) string {\n\trs := make([]rune, len(s))\n\ti := len(s)\n\tfor _, r := range s {\n\t\ti--\n\t\trs[i] = r\n\t}\n\treturn string(rs[i:])\n}\n\nfunc main() {\n\tfmt.Println(\"Reversed: \", revStr(phrase))\n\n\tws := strings.Fields(phrase)\n\tfor i, w := range ws {\n\t\tws[i] = revStr(w)\n\t}\n\tfmt.Println(\"Words reversed: \", strings.Join(ws, \" \"))\n\n\tws = strings.Fields(phrase)\n\tlast := len(ws) - 1\n\tfor i, w := range ws[:len(ws)/2] {\n\t\tws[i], ws[last-i] = ws[last-i], w\n\t}\n\tfmt.Println(\"Word order reversed:\", strings.Join(ws, \" \"))\n}"} {"title": "Pig the dice game", "language": "Go", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano()) //Set seed to current time\n\n\tplayerScores := [...]int{0, 0}\n\tturn := 0\n\tcurrentScore := 0\n\n\tfor {\n\t\tplayer := turn % len(playerScores)\n\n\t\tfmt.Printf(\"Player %v [%v, %v], (H)old, (R)oll or (Q)uit: \", player,\n\t\t\tplayerScores[player], currentScore)\n\n\t\tvar answer string\n\t\tfmt.Scanf(\"%v\", &answer)\n\t\tswitch strings.ToLower(answer) {\n\t\tcase \"h\": //Hold\n\t\t\tplayerScores[player] += currentScore\n\t\t\tfmt.Printf(\" Player %v now has a score of %v.\\n\\n\", player, playerScores[player])\n\n\t\t\tif playerScores[player] >= 100 {\n\t\t\t\tfmt.Printf(\" Player %v wins!!!\\n\", player)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcurrentScore = 0\n\t\t\tturn += 1\n\t\tcase \"r\": //Roll\n\t\t\troll := rand.Intn(6) + 1\n\n\t\t\tif roll == 1 {\n\t\t\t\tfmt.Printf(\" Rolled a 1. Bust!\\n\\n\")\n\t\t\t\tcurrentScore = 0\n\t\t\t\tturn += 1\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\" Rolled a %v.\\n\", roll)\n\t\t\t\tcurrentScore += roll\n\t\t\t}\n\t\tcase \"q\": //Quit\n\t\t\treturn\n\t\tdefault: //Incorrent input\n\t\t\tfmt.Print(\" Please enter one of the given inputs.\\n\")\n\t\t}\n\t}\n\tfmt.Printf(\"Player %v wins!!!\\n\", (turn-1)%len(playerScores))\n}"} {"title": "Pig the dice game/Player", "language": "Go", "task": "Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.\n* State here the play strategies involved.\n* Show play during a game here.\n\n\nAs a stretch goal:\n* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.\n\n\n;Game Rules:\nThe game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach 100 points or more.\nPlay is taken in turns. On each person's turn that person has the option of either\n\n# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n# '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.\n\n\n;References\n* Pig (dice)\n* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.\n\n", "solution": "package pig\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\ntype (\n\tPlayerID int\n\tMessageID int\n\tStrategyID int\n\n\tPigGameData struct {\n\t\tplayer PlayerID\n\t\tturnCount int\n\t\tturnRollCount int\n\t\tturnScore int\n\t\tlastRoll int\n\t\tscores [2]int\n\t\tverbose bool\n\t}\n)\n\nconst (\n\t// Status messages\n\tgameOver = iota\n\tpiggedOut\n\trolls\n\tpointSpending\n\tholds\n\tturn\n\tgameOverSummary\n\t// Players\n\tplayer1 = PlayerID(0)\n\tplayer2 = PlayerID(1)\n\tnoPlayer = PlayerID(-1)\n\t// Max score\n\tmaxScore = 100\n\t// Strategies\n\tscoreChaseStrat = iota\n\trollCountStrat\n)\n\n// Returns \"s\" if n != 1\nfunc pluralS(n int) string {\n\tif n != 1 {\n\t\treturn \"s\"\n\t}\n\treturn \"\"\n}\n\n// Creates an intializes a new PigGameData structure, returns a *PigGameData\nfunc New() *PigGameData {\n\treturn &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}\n}\n\n// Create a status message for a given message ID\nfunc (pg *PigGameData) statusMessage(id MessageID) string {\n\tvar msg string\n\tswitch id {\n\tcase gameOver:\n\t\tmsg = fmt.Sprintf(\"Game is over after %d turns\", pg.turnCount)\n\tcase piggedOut:\n\t\tmsg = fmt.Sprintf(\" Pigged out after %d roll%s\", pg.turnRollCount, pluralS(pg.turnRollCount))\n\tcase rolls:\n\t\tmsg = fmt.Sprintf(\" Rolls %d\", pg.lastRoll)\n\tcase pointSpending:\n\t\tmsg = fmt.Sprintf(\" %d point%s pending\", pg.turnScore, pluralS(pg.turnScore))\n\tcase holds:\n\t\tmsg = fmt.Sprintf(\" Holds after %d turns, adding %d points for a total of %d\", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))\n\tcase turn:\n\t\tmsg = fmt.Sprintf(\"Player %d's turn:\", pg.player+1)\n\tcase gameOverSummary:\n\t\tmsg = fmt.Sprintf(\"Game over after %d turns\\n player 1 %d\\n player 2 %d\\n\", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))\n\t}\n\treturn msg\n}\n\n// Print a status message, if pg.Verbose is true\nfunc (pg *PigGameData) PrintStatus(id MessageID) {\n\tif pg.verbose {\n\t\tfmt.Println(pg.statusMessage(id))\n\t}\n}\n\n// Play a given strategy\nfunc (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {\n\tif pg.GameOver() {\n\t\tpg.PrintStatus(gameOver)\n\t\treturn false\n\t}\n\n\tif pg.turnCount == 0 {\n\t\tpg.player = player2\n\t\tpg.NextPlayer()\n\t}\n\n\tpg.lastRoll = rand.Intn(6) + 1\n\tpg.PrintStatus(rolls)\n\tpg.turnRollCount++\n\tif pg.lastRoll == 1 {\n\t\tpg.PrintStatus(piggedOut)\n\t\tpg.NextPlayer()\n\t} else {\n\t\tpg.turnScore += pg.lastRoll\n\t\tpg.PrintStatus(pointSpending)\n\t\tsuccess := false\n\t\tswitch id {\n\t\tcase scoreChaseStrat:\n\t\t\tsuccess = pg.scoreChaseStrategy()\n\t\tcase rollCountStrat:\n\t\t\tsuccess = pg.rollCountStrategy()\n\t\t}\n\t\tif success {\n\t\t\tpg.Hold()\n\t\t\tpg.NextPlayer()\n\t\t}\n\t}\n\treturn true\n}\n\n// Get the score for a given player\nfunc (pg *PigGameData) PlayerScore(id PlayerID) int {\n\tif id == noPlayer {\n\t\treturn pg.scores[pg.player]\n\t}\n\treturn pg.scores[id]\n}\n\n// Check if the game is over\nfunc (pg *PigGameData) GameOver() bool {\n\treturn pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore\n}\n\n// Returns the Player ID if there is a winner, or -1\nfunc (pg *PigGameData) Winner() PlayerID {\n\tfor index, score := range pg.scores {\n\t\tif score >= maxScore {\n\t\t\treturn PlayerID(index)\n\t\t}\n\t}\n\treturn noPlayer\n}\n\n// Get the ID of the other player\nfunc (pg *PigGameData) otherPlayer() PlayerID {\n\t// 0 becomes 1, 1 becomes 0\n\treturn 1 - pg.player\n}\n\nfunc (pg *PigGameData) Hold() {\n\tpg.scores[pg.player] += pg.turnScore\n\tpg.PrintStatus(holds)\n\tpg.turnRollCount, pg.turnScore = 0, 0\n}\n\nfunc (pg *PigGameData) NextPlayer() {\n\tpg.turnCount++\n\tpg.turnRollCount, pg.turnScore = 0, 0\n\tpg.player = pg.otherPlayer()\n\tpg.PrintStatus(turn)\n}\n\nfunc (pg *PigGameData) rollCountStrategy() bool {\n\treturn pg.turnRollCount >= 3\n}\n\nfunc (pg *PigGameData) scoreChaseStrategy() bool {\n\tmyScore := pg.PlayerScore(pg.player)\n\totherScore := pg.PlayerScore(pg.otherPlayer())\n\tmyPendingScore := pg.turnScore + myScore\n\treturn myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5\n}\n\n// Run the simulation\nfunc main() {\n\t// Seed the random number generator\n\trand.Seed(time.Now().UnixNano())\n\n\t// Start a new game\n\tpg := New()\n\tpg.verbose = true\n\tstrategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}\n\n\t// Play until game over\n\tfor !pg.GameOver() {\n\t\tpg.Play(strategies[pg.player])\n\t}\n\tpg.PrintStatus(gameOverSummary)\n}"} {"title": "Plasma effect", "language": "Go", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "package main\n\nimport (\n \"image\"\n \"image/color\"\n \"image/gif\"\n \"log\"\n \"math\"\n \"os\"\n)\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n for x := 0; x < w; x++ {\n for y := 0; y < h; y++ {\n img.SetColorIndex(x, y, ci)\n }\n }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n u := int(bri*255 + 0.5)\n if sat == 0 {\n r, g, b = u, u, u\n } else {\n h := (hue - math.Floor(hue)) * 6\n f := h - math.Floor(h)\n p := int(bri*(1-sat)*255 + 0.5)\n q := int(bri*(1-sat*f)*255 + 0.5)\n t := int(bri*(1-sat*(1-f))*255 + 0.5)\n switch int(h) {\n case 0:\n r, g, b = u, t, p\n case 1:\n r, g, b = q, u, p\n case 2:\n r, g, b = p, u, t\n case 3:\n r, g, b = p, q, u\n case 4:\n r, g, b = t, p, u\n case 5:\n r, g, b = u, p, q\n }\n }\n return\n}\n\nfunc main() {\n const degToRad = math.Pi / 180\n const nframes = 100\n const delay = 4 // 40ms\n w, h := 640, 640\n anim := gif.GIF{LoopCount: nframes}\n rect := image.Rect(0, 0, w, h)\n palette := make([]color.Color, nframes+1)\n palette[0] = color.White\n for i := 1; i <= nframes; i++ {\n r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)\n palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n }\n for f := 1; f <= nframes; f++ {\n img := image.NewPaletted(rect, palette)\n setBackgroundColor(img, w, h, 0) // white background\n for y := 0; y < h; y++ {\n for x := 0; x < w; x++ {\n fx, fy := float64(x), float64(y)\n value := math.Sin(fx / 16)\n value += math.Sin(fy / 8)\n value += math.Sin((fx + fy) / 16)\n value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)\n value += 4 // shift range from [-4, 4] to [0, 8]\n value /= 8 // bring range down to [0, 1]\n _, rem := math.Modf(value + float64(f)/float64(nframes))\n ci := uint8(nframes*rem) + 1\n img.SetColorIndex(x, y, ci)\n }\n }\n anim.Delay = append(anim.Delay, delay)\n anim.Image = append(anim.Image, img)\n }\n file, err := os.Create(\"plasma.gif\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close() \n if err2 := gif.EncodeAll(file, &anim); err != nil {\n log.Fatal(err2)\n } \n}"} {"title": "Playfair cipher", "language": "Go from Kotlin", "task": "Implement a Playfair cipher for encryption and decryption.\n\n\nThe user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n;Output example:\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"os\"\n \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n noQ playfairOption = iota\n iEqualsJ\n)\n\ntype playfair struct {\n keyword string\n pfo playfairOption\n table [5][5]byte\n}\n\nfunc (p *playfair) init() {\n // Build table.\n var used [26]bool // all elements false\n if p.pfo == noQ {\n used[16] = true // Q used\n } else {\n used[9] = true // J used\n }\n alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n c := alphabet[k]\n if c < 'A' || c > 'Z' {\n continue\n }\n d := int(c - 65)\n if !used[d] {\n p.table[i][j] = c\n used[d] = true\n j++\n if j == 5 {\n i++\n if i == 5 {\n break // table has been filled\n }\n j = 0\n }\n }\n }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n // Ensure everything is upper case.\n plainText = strings.ToUpper(plainText)\n // Get rid of any non-letters and insert X between duplicate letters.\n var cleanText strings.Builder\n // Safe to assume null byte won't be present in plainText.\n prevByte := byte('\\000')\n for i := 0; i < len(plainText); i++ {\n nextByte := plainText[i]\n // It appears that Q should be omitted altogether if NO_Q option is specified;\n // we assume so anyway.\n if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n continue\n }\n // If iEqualsJ option specified, replace J with I.\n if nextByte == 'J' && p.pfo == iEqualsJ {\n nextByte = 'I'\n }\n if nextByte != prevByte {\n cleanText.WriteByte(nextByte)\n } else {\n cleanText.WriteByte('X')\n cleanText.WriteByte(nextByte)\n }\n prevByte = nextByte\n }\n l := cleanText.Len()\n if l%2 == 1 {\n // Dangling letter at end so add another letter to complete digram.\n if cleanText.String()[l-1] != 'X' {\n cleanText.WriteByte('X')\n } else {\n cleanText.WriteByte('Z')\n }\n }\n return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n for i := 0; i < 5; i++ {\n for j := 0; j < 5; j++ {\n if p.table[i][j] == c {\n return i, j\n }\n }\n }\n return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n cleanText := p.getCleanText(plainText)\n var cipherText strings.Builder\n l := len(cleanText)\n for i := 0; i < l; i += 2 {\n row1, col1 := p.findByte(cleanText[i])\n row2, col2 := p.findByte(cleanText[i+1])\n switch {\n case row1 == row2:\n cipherText.WriteByte(p.table[row1][(col1+1)%5])\n cipherText.WriteByte(p.table[row2][(col2+1)%5])\n case col1 == col2:\n cipherText.WriteByte(p.table[(row1+1)%5][col1])\n cipherText.WriteByte(p.table[(row2+1)%5][col2])\n default:\n cipherText.WriteByte(p.table[row1][col2])\n cipherText.WriteByte(p.table[row2][col1])\n }\n if i < l-1 {\n cipherText.WriteByte(' ')\n }\n }\n return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n var decodedText strings.Builder\n l := len(cipherText)\n // cipherText will include spaces so we need to skip them.\n for i := 0; i < l; i += 3 {\n row1, col1 := p.findByte(cipherText[i])\n row2, col2 := p.findByte(cipherText[i+1])\n switch {\n case row1 == row2:\n temp := 4\n if col1 > 0 {\n temp = col1 - 1\n }\n decodedText.WriteByte(p.table[row1][temp])\n temp = 4\n if col2 > 0 {\n temp = col2 - 1\n }\n decodedText.WriteByte(p.table[row2][temp])\n case col1 == col2:\n temp := 4\n if row1 > 0 {\n temp = row1 - 1\n }\n decodedText.WriteByte(p.table[temp][col1])\n temp = 4\n if row2 > 0 {\n temp = row2 - 1\n }\n decodedText.WriteByte(p.table[temp][col2])\n default:\n decodedText.WriteByte(p.table[row1][col2])\n decodedText.WriteByte(p.table[row2][col1])\n }\n if i < l-1 {\n decodedText.WriteByte(' ')\n }\n }\n return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n fmt.Println(\"The table to be used is :\\n\")\n for i := 0; i < 5; i++ {\n for j := 0; j < 5; j++ {\n fmt.Printf(\"%c \", p.table[i][j])\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n scanner := bufio.NewScanner(os.Stdin)\n fmt.Print(\"Enter Playfair keyword : \")\n scanner.Scan()\n keyword := scanner.Text()\n var ignoreQ string\n for ignoreQ != \"y\" && ignoreQ != \"n\" {\n fmt.Print(\"Ignore Q when building table y/n : \")\n scanner.Scan()\n ignoreQ = strings.ToLower(scanner.Text())\n }\n pfo := noQ\n if ignoreQ == \"n\" {\n pfo = iEqualsJ\n }\n var table [5][5]byte\n pf := &playfair{keyword, pfo, table}\n pf.init()\n pf.printTable()\n fmt.Print(\"\\nEnter plain text : \")\n scanner.Scan()\n plainText := scanner.Text()\n if err := scanner.Err(); err != nil {\n fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n return\n }\n encodedText := pf.encode(plainText)\n fmt.Println(\"\\nEncoded text is :\", encodedText)\n decodedText := pf.decode(encodedText)\n fmt.Println(\"Deccoded text is :\", decodedText)\n}"} {"title": "Plot coordinate pairs", "language": "Go", "task": "Plot a function represented as x, y numerical arrays.\n\nPost the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):\n x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os/exec\"\n)\n\nvar (\n x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}\n)\n\nfunc main() {\n g := exec.Command(\"gnuplot\", \"-persist\")\n w, err := g.StdinPipe()\n if err != nil {\n log.Fatal(err)\n }\n if err = g.Start(); err != nil {\n log.Fatal(err)\n }\n fmt.Fprintln(w, \"unset key; plot '-'\")\n for i, xi := range x {\n fmt.Fprintf(w, \"%d %f\\n\", xi, y[i])\n }\n fmt.Fprintln(w, \"e\")\n w.Close()\n g.Wait()\n}"} {"title": "Poker hand analyser", "language": "Go from Kotlin", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strings\"\n)\n\ntype card struct {\n face byte\n suit byte\n}\n\nconst faces = \"23456789tjqka\"\nconst suits = \"shdc\"\n\nfunc isStraight(cards []card) bool {\n sorted := make([]card, 5)\n copy(sorted, cards)\n sort.Slice(sorted, func(i, j int) bool {\n return sorted[i].face < sorted[j].face\n })\n if sorted[0].face+4 == sorted[4].face {\n return true\n }\n if sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5 {\n return true\n }\n return false\n}\n\nfunc isFlush(cards []card) bool {\n suit := cards[0].suit\n for i := 1; i < 5; i++ {\n if cards[i].suit != suit {\n return false\n }\n }\n return true\n}\n\nfunc analyzeHand(hand string) string {\n temp := strings.Fields(strings.ToLower(hand))\n splitSet := make(map[string]bool)\n var split []string\n for _, s := range temp {\n if !splitSet[s] {\n splitSet[s] = true\n split = append(split, s)\n }\n }\n if len(split) != 5 {\n return \"invalid\"\n }\n var cards []card\n\n for _, s := range split {\n if len(s) != 2 {\n return \"invalid\"\n }\n fIndex := strings.IndexByte(faces, s[0])\n if fIndex == -1 {\n return \"invalid\"\n }\n sIndex := strings.IndexByte(suits, s[1])\n if sIndex == -1 {\n return \"invalid\"\n }\n cards = append(cards, card{byte(fIndex + 2), s[1]})\n }\n\n groups := make(map[byte][]card)\n for _, c := range cards {\n groups[c.face] = append(groups[c.face], c)\n }\n\n switch len(groups) {\n case 2:\n for _, group := range groups {\n if len(group) == 4 {\n return \"four-of-a-kind\"\n }\n }\n return \"full-house\"\n case 3:\n for _, group := range groups {\n if len(group) == 3 {\n return \"three-of-a-kind\"\n }\n }\n return \"two-pair\"\n case 4:\n return \"one-pair\"\n default:\n flush := isFlush(cards)\n straight := isStraight(cards)\n switch {\n case flush && straight:\n return \"straight-flush\"\n case flush:\n return \"flush\"\n case straight:\n return \"straight\"\n default:\n return \"high-card\"\n }\n }\n}\n\nfunc main() {\n hands := [...]string{\n \"2h 2d 2c kc qd\",\n \"2h 5h 7d 8c 9s\",\n \"ah 2d 3c 4c 5d\",\n \"2h 3h 2d 3c 3d\",\n \"2h 7h 2d 3c 3d\",\n \"2h 7h 7d 7c 7s\",\n \"th jh qh kh ah\",\n \"4h 4s ks 5d ts\",\n \"qc tc 7c 6c 4c\",\n \"ah ah 7c 6c 4c\",\n }\n for _, hand := range hands {\n fmt.Printf(\"%s: %s\\n\", hand, analyzeHand(hand))\n }\n}"} {"title": "Polyspiral", "language": "Go", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "package main\n\nimport (\n \"image\"\n \"image/color\"\n \"image/gif\"\n \"log\" \n \"math\"\n \"os\"\n)\n\nfunc drawLine(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {\n var first, last int\n if x2 != x1 {\n m := float64(y2-y1) / float64(x2-x1)\n if x1 < x2 {\n first, last = x1, x2\n } else {\n first, last = x2, x1\n }\n for x := first; x <= last; x++ {\n y := int(m*float64(x-x1)+0.5) + y1\n img.SetColorIndex(x, y, ci)\n }\n } else {\n if y1 < y2 {\n first, last = y1, y2\n } else {\n first, last = y2, y1\n }\n for y := first; y <= last; y++ {\n img.SetColorIndex(x1, y, ci)\n }\n }\n}\n\nfunc setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {\n for x := 0; x < w; x++ {\n for y := 0; y < h; y++ {\n img.SetColorIndex(x, y, ci)\n }\n }\n}\n\nfunc hsb2rgb(hue, sat, bri float64) (r, g, b int) {\n u := int(bri*255 + 0.5)\n if sat == 0 {\n r, g, b = u, u, u\n } else {\n h := (hue - math.Floor(hue)) * 6\n f := h - math.Floor(h)\n p := int(bri*(1-sat)*255 + 0.5)\n q := int(bri*(1-sat*f)*255 + 0.5)\n t := int(bri*(1-sat*(1-f))*255 + 0.5)\n switch int(h) {\n case 0:\n r, g, b = u, t, p\n case 1:\n r, g, b = q, u, p\n case 2:\n r, g, b = p, u, t\n case 3:\n r, g, b = p, q, u\n case 4:\n r, g, b = t, p, u\n case 5:\n r, g, b = u, p, q\n }\n }\n return\n}\n\nfunc main() {\n const degToRad = math.Pi / 180\n const nframes = 360\n const delay = 20 // 200ms\n width, height := 640, 640\n anim := gif.GIF{LoopCount: nframes}\n rect := image.Rect(0, 0, width, height)\n palette := make([]color.Color, 151)\n palette[0] = color.White\n for i := 1; i <= 150; i++ {\n r, g, b := hsb2rgb(float64(i)/150, 1, 1)\n palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}\n }\n incr := 0\n for f := 1; f <= nframes; f++ {\n incr = (incr + 1) % 360\n x1, y1 := width/2, height/2\n length := 5.0\n img := image.NewPaletted(rect, palette)\n setBackgroundColor(img, width, height, 0) // white background\n angle := incr\n for ci := uint8(1); ci <= 150; ci++ {\n x2 := x1 + int(math.Cos(float64(angle)*degToRad)*length)\n y2 := y1 - int(math.Sin(float64(angle)*degToRad)*length)\n drawLine(img, x1, y1, x2, y2, ci)\n x1, y1 = x2, y2\n length += 3\n angle = (angle + incr) % 360\n }\n anim.Delay = append(anim.Delay, delay)\n anim.Image = append(anim.Image, img)\n }\n file, err := os.Create(\"polyspiral.gif\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close() \n if err2 := gif.EncodeAll(file, &anim); err != nil {\n log.Fatal(err2)\n }\n}"} {"title": "Population count", "language": "Go", "task": "The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.\n\n''Population count'' is also known as:\n::::* ''pop count''\n::::* ''popcount'' \n::::* ''sideways sum''\n::::* ''bit summation'' \n::::* ''Hamming weight'' \n\n\nFor example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.\n\n\n''Evil numbers'' are non-negative integers that have an ''even'' population count.\n\n''Odious numbers'' are positive integers that have an ''odd'' population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with '''0''' (zero indexed).\n:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').\n:* display the 1st thirty ''evil'' numbers.\n:* display the 1st thirty ''odious'' numbers.\n* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/bits\"\n)\n\nfunc main() {\n fmt.Println(\"Pop counts, powers of 3:\")\n n := uint64(1) // 3^0\n for i := 0; i < 30; i++ {\n fmt.Printf(\"%d \", bits.OnesCount64(n))\n n *= 3\n }\n fmt.Println()\n fmt.Println(\"Evil numbers:\")\n var od [30]uint64\n var ne, no int\n for n = 0; ne+no < 60; n++ {\n if bits.OnesCount64(n)&1 == 0 {\n if ne < 30 {\n fmt.Printf(\"%d \", n)\n ne++\n }\n } else {\n if no < 30 {\n od[no] = n\n no++\n }\n }\n }\n fmt.Println()\n fmt.Println(\"Odious numbers:\")\n for _, n := range od {\n fmt.Printf(\"%d \", n)\n }\n fmt.Println()\n}"} {"title": "Prime triangle", "language": "Go from Phix", "task": "You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.\n\n\n;See also\n:* OEIS:A036440\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar canFollow [][]bool\nvar arrang []int\nvar bFirst = true\n\nvar pmap = make(map[int]bool)\n\nfunc init() {\n for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {\n pmap[i] = true\n }\n}\n\nfunc ptrs(res, n, done int) int {\n ad := arrang[done-1]\n if n-done <= 1 {\n if canFollow[ad-1][n-1] {\n if bFirst {\n for _, e := range arrang {\n fmt.Printf(\"%2d \", e)\n }\n fmt.Println()\n bFirst = false\n }\n res++\n }\n } else {\n done++\n for i := done - 1; i <= n-2; i += 2 {\n ai := arrang[i]\n if canFollow[ad-1][ai-1] {\n arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n res = ptrs(res, n, done)\n arrang[i], arrang[done-1] = arrang[done-1], arrang[i]\n }\n }\n }\n return res\n}\n\nfunc primeTriangle(n int) int {\n canFollow = make([][]bool, n)\n for i := 0; i < n; i++ {\n canFollow[i] = make([]bool, n)\n for j := 0; j < n; j++ {\n _, ok := pmap[i+j+2]\n canFollow[i][j] = ok\n }\n }\n bFirst = true\n arrang = make([]int, n)\n for i := 0; i < n; i++ {\n arrang[i] = i + 1\n }\n return ptrs(0, n, 1)\n}\n\nfunc main() {\n counts := make([]int, 19)\n for i := 2; i <= 20; i++ {\n counts[i-2] = primeTriangle(i)\n }\n fmt.Println()\n for i := 0; i < 19; i++ {\n fmt.Printf(\"%d \", counts[i])\n }\n fmt.Println()\n}"} {"title": "Priority queue", "language": "Go", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"container/heap\"\n)\n\ntype Task struct {\n priority int\n name string\n}\n\ntype TaskPQ []Task\n\nfunc (self TaskPQ) Len() int { return len(self) }\nfunc (self TaskPQ) Less(i, j int) bool {\n return self[i].priority < self[j].priority\n}\nfunc (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }\nfunc (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }\nfunc (self *TaskPQ) Pop() (popped interface{}) {\n popped = (*self)[len(*self)-1]\n *self = (*self)[:len(*self)-1]\n return\n}\n\nfunc main() {\n pq := &TaskPQ{{3, \"Clear drains\"},\n {4, \"Feed cat\"},\n {5, \"Make tea\"},\n {1, \"Solve RC tasks\"}}\n\n // heapify\n heap.Init(pq)\n\n // enqueue\n heap.Push(pq, Task{2, \"Tax return\"})\n\n for pq.Len() != 0 { \n // dequeue\n fmt.Println(heap.Pop(pq))\n }\n}"} {"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "Go from Python", "task": "MRG32k3a Combined recursive generator (pseudo-code):\n\n /* Constants */\n /* First generator */\n a1 = [0, 1403580, -810728]\n m1 = 2**32 - 209\n /* Second Generator */\n a2 = [527612, 0, -1370589]\n m2 = 2**32 - 22853\n \n d = m1 + 1\n \n class MRG32k3a\n x1 = [0, 0, 0] /* list of three last values of gen #1 */\n x2 = [0, 0, 0] /* list of three last values of gen #2 */\n \n method seed(u64 seed_state)\n assert seed_state in range >0 and < d \n x1 = [seed_state, 0, 0]\n x2 = [seed_state, 0, 0]\n end method\n \n method next_int()\n x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1\n x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2\n x1 = [x1i, x1[0], x1[1]] /* Keep last three */\n x2 = [x2i, x2[0], x2[1]] /* Keep last three */\n z = (x1i - x2i) % m1\n answer = (z + 1)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / d\n end method\n \n end class\n \n:MRG32k3a Use:\n random_gen = instance MRG32k3a\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 1459213977 */\n print(random_gen.next_int()) /* 2827710106 */\n print(random_gen.next_int()) /* 4245671317 */\n print(random_gen.next_int()) /* 3877608661 */\n print(random_gen.next_int()) /* 2595287583 */\n \n \n;Task\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers generated with the seed `1234567`\nare as shown above \n\n* Show that for an initial seed of '987654321' the counts of 100_000\nrepetitions of\n\n floor(random_gen.next_float() * 5)\n\nIs as follows:\n \n 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931\n\n* Show your output here, on this page.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n)\n\nvar a1 = []int64{0, 1403580, -810728}\nvar a2 = []int64{527612, 0, -1370589}\n\nconst m1 = int64((1 << 32) - 209)\nconst m2 = int64((1 << 32) - 22853)\nconst d = m1 + 1\n\n// Python style modulus\nfunc mod(x, y int64) int64 {\n m := x % y\n if m < 0 {\n if y < 0 {\n return m - y\n } else {\n return m + y\n }\n }\n return m\n}\n\ntype MRG32k3a struct{ x1, x2 [3]int64 }\n\nfunc MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }\n\nfunc (mrg *MRG32k3a) seed(seedState int64) {\n if seedState <= 0 || seedState >= d {\n log.Fatalf(\"Argument must be in the range [0, %d].\\n\", d)\n }\n mrg.x1 = [3]int64{seedState, 0, 0}\n mrg.x2 = [3]int64{seedState, 0, 0}\n}\n\nfunc (mrg *MRG32k3a) nextInt() int64 {\n x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)\n x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)\n mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} /* keep last three */\n mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} /* keep last three */\n return mod(x1i-x2i, m1) + 1\n}\n\nfunc (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }\n\nfunc main() {\n randomGen := MRG32k3aNew()\n randomGen.seed(1234567)\n for i := 0; i < 5; i++ {\n fmt.Println(randomGen.nextInt())\n }\n\n var counts [5]int\n randomGen.seed(987654321)\n for i := 0; i < 1e5; i++ {\n j := int(math.Floor(randomGen.nextFloat() * 5))\n counts[j]++\n }\n fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n for i := 0; i < 5; i++ {\n fmt.Printf(\" %d : %d\\n\", i, counts[i])\n }\n}"} {"title": "Pseudo-random numbers/Middle-square method", "language": "Go", "task": "{{Wikipedia|Middle-square method|en}}\n; The Method:\nTo generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. \n; Pseudo code:\n\nvar seed = 675248\nfunction random()\n var s = str(seed * seed) 'str: turn a number into string\n do while not len(s) = 12\n s = \"0\" + s 'add zeroes before the string\n end do\n seed = val(mid(s, 4, 6)) 'mid: string variable, start, length\n 'val: turn a string into number\n return seed\nend function\n\n; Middle-square method use:\n\nfor i = 1 to 5\n print random()\nend for\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers (6 digits) as shown above.\n\n* Show the first five integers generated with the seed 675248 as shown above.\n\n* Show your output here, on this page.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc random(seed int) int {\n return seed * seed / 1e3 % 1e6\n}\n\nfunc main() {\n seed := 675248\n for i := 1; i <= 5; i++ {\n seed = random(seed)\n fmt.Println(seed)\n }\n}"} {"title": "Pseudo-random numbers/PCG32", "language": "Go from Python", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;PCG32 Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst CONST = 6364136223846793005\n\ntype Pcg32 struct{ state, inc uint64 }\n\nfunc Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }\n\nfunc (pcg *Pcg32) seed(seedState, seedSequence uint64) {\n pcg.state = 0\n pcg.inc = (seedSequence << 1) | 1\n pcg.nextInt()\n pcg.state = pcg.state + seedState\n pcg.nextInt()\n}\n\nfunc (pcg *Pcg32) nextInt() uint32 {\n old := pcg.state\n pcg.state = old*CONST + pcg.inc\n pcgshifted := uint32(((old >> 18) ^ old) >> 27)\n rot := uint32(old >> 59)\n return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))\n}\n\nfunc (pcg *Pcg32) nextFloat() float64 {\n return float64(pcg.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n randomGen := Pcg32New()\n randomGen.seed(42, 54)\n for i := 0; i < 5; i++ {\n fmt.Println(randomGen.nextInt())\n }\n\n var counts [5]int\n randomGen.seed(987654321, 1)\n for i := 0; i < 1e5; i++ {\n j := int(math.Floor(randomGen.nextFloat() * 5))\n counts[j]++\n }\n fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n for i := 0; i < 5; i++ {\n fmt.Printf(\" %d : %d\\n\", i, counts[i])\n }\n}"} {"title": "Pseudo-random numbers/Xorshift star", "language": "Go from Python", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nconst CONST = 0x2545F4914F6CDD1D\n\ntype XorshiftStar struct{ state uint64 }\n\nfunc XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }\n\nfunc (xor *XorshiftStar) seed(state uint64) { xor.state = state }\n\nfunc (xor *XorshiftStar) nextInt() uint32 {\n x := xor.state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n xor.state = x\n return uint32((x * CONST) >> 32)\n}\n\nfunc (xor *XorshiftStar) nextFloat() float64 {\n return float64(xor.nextInt()) / (1 << 32)\n}\n\nfunc main() {\n randomGen := XorshiftStarNew(1234567)\n for i := 0; i < 5; i++ {\n fmt.Println(randomGen.nextInt())\n }\n\n var counts [5]int\n randomGen.seed(987654321)\n for i := 0; i < 1e5; i++ {\n j := int(math.Floor(randomGen.nextFloat() * 5))\n counts[j]++\n }\n fmt.Println(\"\\nThe counts for 100,000 repetitions are:\")\n for i := 0; i < 5; i++ {\n fmt.Printf(\" %d : %d\\n\", i, counts[i])\n }\n}"} {"title": "Pythagoras tree", "language": "Go", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"image/draw\"\n\t\"image/png\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\twidth, height = 800, 600\n\tmaxDepth = 11 // how far to recurse, between 1 and 20 is reasonable\n\tcolFactor = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out\n\tfileName = \"pythagorasTree.png\"\n)\n\nfunc main() {\n\timg := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image\n\tbg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background\n\tdraw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background\n\n\tdrawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image\n\n\timgFile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer imgFile.Close()\n\tif err := png.Encode(imgFile, img); err != nil {\n\t\timgFile.Close()\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {\n\tif depth > maxDepth {\n\t\treturn\n\t}\n\tdx, dy := bx-ax, ay-by\n\tx3, y3 := bx-dy, by-dx\n\tx4, y4 := ax-dy, ay-dx\n\tx5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2\n\tcol := color.RGBA{0, uint8(depth) * colFactor, 0, 255}\n\tdrawLine(ax, ay, bx, by, img, col)\n\tdrawLine(bx, by, x3, y3, img, col)\n\tdrawLine(x3, y3, x4, y4, img, col)\n\tdrawLine(x4, y4, ax, ay, img, col)\n\tdrawSquares(x4, y4, x5, y5, img, depth+1)\n\tdrawSquares(x5, y5, x3, y3, img, depth+1)\n}\n\nfunc drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {\n\tdx := abs(x1 - x0)\n\tdy := abs(y1 - y0)\n\tvar sx, sy int = -1, -1\n\tif x0 < x1 {\n\t\tsx = 1\n\t}\n\tif y0 < y1 {\n\t\tsy = 1\n\t}\n\terr := dx - dy\n\tfor {\n\t\timg.Set(x0, y0, col)\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := 2 * err\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}"} {"title": "Pythagorean quadruples", "language": "Go from FreeBASIC", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nconst (\n N = 2200\n N2 = N * N * 2\n)\n\nfunc main() {\n s := 3 \n var s1, s2 int \n var r [N + 1]bool\n var ab [N2 + 1]bool\n\n for a := 1; a <= N; a++ {\n a2 := a * a\n for b := a; b <= N; b++ {\n ab[a2 + b * b] = true\n }\n }\n\n for c := 1; c <= N; c++ {\n s1 = s\n s += 2\n s2 = s\n for d := c + 1; d <= N; d++ {\n if ab[s1] {\n r[d] = true\n }\n s1 += s2\n s2 += 2\n }\n }\n\n for d := 1; d <= N; d++ {\n if !r[d] {\n fmt.Printf(\"%d \", d)\n } \n }\n fmt.Println()\n}"} {"title": "Pythagorean triples", "language": "Go", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n if p := s0 + s1 + s2; p <= maxPeri {\n prim++\n total += maxPeri / p\n newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n }\n}\n\nfunc main() {\n for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n prim = 0\n total = 0\n newTri(3, 4, 5)\n fmt.Printf(\"Up to %d: %d triples, %d primitives\\n\",\n maxPeri, total, prim)\n }\n}"} {"title": "Quaternion type", "language": "Go", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype qtn struct {\n r, i, j, k float64\n}\n\nvar (\n q = &qtn{1, 2, 3, 4}\n q1 = &qtn{2, 3, 4, 5}\n q2 = &qtn{3, 4, 5, 6}\n\n r float64 = 7\n)\n\nfunc main() {\n fmt.Println(\"Inputs\")\n fmt.Println(\"q:\", q)\n fmt.Println(\"q1:\", q1)\n fmt.Println(\"q2:\", q2)\n fmt.Println(\"r:\", r)\n\n var qr qtn\n fmt.Println(\"\\nFunctions\")\n fmt.Println(\"q.norm():\", q.norm())\n fmt.Println(\"neg(q):\", qr.neg(q))\n fmt.Println(\"conj(q):\", qr.conj(q))\n fmt.Println(\"addF(q, r):\", qr.addF(q, r))\n fmt.Println(\"addQ(q1, q2):\", qr.addQ(q1, q2))\n fmt.Println(\"mulF(q, r):\", qr.mulF(q, r))\n fmt.Println(\"mulQ(q1, q2):\", qr.mulQ(q1, q2))\n fmt.Println(\"mulQ(q2, q1):\", qr.mulQ(q2, q1))\n}\n\nfunc (q *qtn) String() string {\n return fmt.Sprintf(\"(%g, %g, %g, %g)\", q.r, q.i, q.j, q.k)\n}\n\nfunc (q *qtn) norm() float64 {\n return math.Sqrt(q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k)\n}\n\nfunc (z *qtn) neg(q *qtn) *qtn {\n z.r, z.i, z.j, z.k = -q.r, -q.i, -q.j, -q.k\n return z\n}\n\nfunc (z *qtn) conj(q *qtn) *qtn {\n z.r, z.i, z.j, z.k = q.r, -q.i, -q.j, -q.k\n return z\n}\n\nfunc (z *qtn) addF(q *qtn, r float64) *qtn {\n z.r, z.i, z.j, z.k = q.r+r, q.i, q.j, q.k\n return z\n}\n\nfunc (z *qtn) addQ(q1, q2 *qtn) *qtn {\n z.r, z.i, z.j, z.k = q1.r+q2.r, q1.i+q2.i, q1.j+q2.j, q1.k+q2.k\n return z\n}\n\nfunc (z *qtn) mulF(q *qtn, r float64) *qtn {\n z.r, z.i, z.j, z.k = q.r*r, q.i*r, q.j*r, q.k*r\n return z\n}\n\nfunc (z *qtn) mulQ(q1, q2 *qtn) *qtn {\n z.r, z.i, z.j, z.k =\n q1.r*q2.r-q1.i*q2.i-q1.j*q2.j-q1.k*q2.k,\n q1.r*q2.i+q1.i*q2.r+q1.j*q2.k-q1.k*q2.j,\n q1.r*q2.j-q1.i*q2.k+q1.j*q2.r+q1.k*q2.i,\n q1.r*q2.k+q1.i*q2.j-q1.j*q2.i+q1.k*q2.r\n return z\n}"} {"title": "Quine", "language": "Go", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA '''quine''' (named after Willard Van Orman Quine) is also known as:\n::* ''self-reproducing automata'' (1972)\n::* ''self-replicating program'' or ''self-replicating computer program''\n::* ''self-reproducing program'' or ''self-reproducing computer program''\n::* ''self-copying program'' or ''self-copying computer program''\n\n\n\nIt is named after the philosopher and logician \nwho studied self-reference and quoting in natural language, \nas for example in the paradox \"'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation.\"\n\n\"Source\" has one of two meanings. It can refer to the text-based program source. \nFor languages in which program source is represented as a data structure, \"source\" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.\n\nThe usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.\n\n\n;Task:\nWrite a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.\n\nThere are several difficulties that one runs into when writing a quine, mostly dealing with quoting:\n* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.\n** Some languages have a function for getting the \"source code representation\" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.\n** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.\n* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. \"\\n\"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.\n** If the language has a way of getting the \"source code representation\", it usually handles the escaping of characters, so this is not a problem.\n** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.\n** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.\n\n\n'''Next to the Quines presented here, many other versions can be found on the Quine page.'''\n\n\n;Related task:\n:* print itself.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := \"package main\\n\\nimport \\\"fmt\\\"\\n\\nfunc main() {\\n\\ta := %q\\n\\tfmt.Printf(a, a)\\n}\\n\"\n\tfmt.Printf(a, a)\n}"} {"title": "Quoting constructs", "language": "Go", "task": "Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.\n\nShow examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?\n\nThis is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, '''NOT''' just a link to [See the language docs].\n\nNote: This is primarily for quoting constructs for data to be \"embedded\" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"regexp\"\n \"strconv\"\n)\n\n/* Quoting constructs in Go. */\n\n// In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune'\n// but the more familiar term 'character' will be used instead here.\n\n// Character literal (single quotes).\n// Can contain any single character including an escaped character.\nvar (\n rl1 = 'a'\n rl2 = '\\'' // single quote can only be included in escaped form\n)\n\n// Interpreted string literal (double quotes).\n// A sequence of characters including escaped characters.\nvar (\n is1 = \"abc\"\n is2 = \"\\\"ab\\tc\\\"\" // double quote can only be included in escaped form\n)\n\n// Raw string literal(single back quotes).\n// Can contain any character including a 'physical' new line but excluding back quote.\n// Escaped characters are interpreted literally i.e. `\\n` is backslash followed by n.\n// Raw strings are typically used for hard-coding pieces of text perhaps\n// including single and/or double quotes without the need to escape them.\n// They are particularly useful for regular expressions.\nvar (\n rs1 = `\nfirst\"\nsecond'\nthird\"\n`\n rs2 = `This is one way of including a ` + \"`\" + ` in a raw string literal.`\n rs3 = `\\d+` // a sequence of one or more digits in a regular expression\n)\n\nfunc main() {\n fmt.Println(rl1, rl2) // prints the code point value not the character itself\n fmt.Println(is1, is2)\n fmt.Println(rs1)\n fmt.Println(rs2)\n re := regexp.MustCompile(rs3)\n fmt.Println(re.FindString(\"abcd1234efgh\"))\n\n /* None of the above quoting constructs can deal directly with interpolation.\n This is done instead using library functions.\n */\n\n // C-style using %d, %f, %s etc. within a 'printf' type function.\n n := 3\n fmt.Printf(\"\\nThere are %d quoting constructs in Go.\\n\", n)\n\n // Using a function such as fmt.Println which can take a variable\n // number of arguments, of any type, and print then out separated by spaces.\n s := \"constructs\"\n fmt.Println(\"There are\", n, \"quoting\", s, \"in Go.\")\n\n // Using the function os.Expand which requires a mapper function to fill placeholders\n // denoted by ${...} within a string.\n mapper := func(placeholder string) string {\n switch placeholder {\n case \"NUMBER\":\n return strconv.Itoa(n)\n case \"TYPES\":\n return s\n }\n return \"\"\n }\n fmt.Println(os.Expand(\"There are ${NUMBER} quoting ${TYPES} in Go.\", mapper))\n}"} {"title": "RPG attributes generator", "language": "Go", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"sort\"\n \"time\"\n)\n\nfunc main() {\n s := rand.NewSource(time.Now().UnixNano())\n r := rand.New(s)\n for {\n var values [6]int\n vsum := 0\n for i := range values {\n var numbers [4]int\n for j := range numbers {\n numbers[j] = 1 + r.Intn(6)\n }\n sort.Ints(numbers[:])\n nsum := 0\n for _, n := range numbers[1:] {\n nsum += n\n }\n values[i] = nsum\n vsum += values[i]\n }\n if vsum < 75 {\n continue\n }\n vcount := 0\n for _, v := range values {\n if v >= 15 {\n vcount++\n }\n }\n if vcount < 2 {\n continue\n }\n fmt.Println(\"The 6 random numbers generated are:\")\n fmt.Println(values)\n fmt.Println(\"\\nTheir sum is\", vsum, \"and\", vcount, \"of them are >= 15\")\n break\n }\n}"} {"title": "Ramer-Douglas-Peucker line simplification", "language": "Go", "task": "The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:\n (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) \n\nThe error threshold to be used is: '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype point struct{ x, y float64 }\n\nfunc RDP(l []point, \u03b5 float64) []point {\n x := 0\n dMax := -1.\n last := len(l) - 1\n p1 := l[0]\n p2 := l[last]\n x21 := p2.x - p1.x\n y21 := p2.y - p1.y\n for i, p := range l[1:last] {\n if d := math.Abs(y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax {\n x = i + 1\n dMax = d\n }\n }\n if dMax > \u03b5 {\n return append(RDP(l[:x+1], \u03b5), RDP(l[x:], \u03b5)[1:]...)\n }\n return []point{l[0], l[len(l)-1]}\n}\n\nfunc main() {\n fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1},\n {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1))\n}"} {"title": "Random Latin squares", "language": "Go", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\ntype matrix [][]int\n\nfunc shuffle(row []int, n int) {\n rand.Shuffle(n, func(i, j int) {\n row[i], row[j] = row[j], row[i]\n })\n}\n\nfunc latinSquare(n int) {\n if n <= 0 {\n fmt.Println(\"[]\\n\")\n return\n }\n latin := make(matrix, n)\n for i := 0; i < n; i++ {\n latin[i] = make([]int, n)\n if i == n-1 {\n break\n }\n for j := 0; j < n; j++ {\n latin[i][j] = j\n }\n }\n // first row\n shuffle(latin[0], n)\n\n // middle row(s)\n for i := 1; i < n-1; i++ {\n shuffled := false\n shuffling:\n for !shuffled {\n shuffle(latin[i], n)\n for k := 0; k < i; k++ {\n for j := 0; j < n; j++ {\n if latin[k][j] == latin[i][j] {\n continue shuffling\n }\n }\n }\n shuffled = true\n }\n }\n\n // last row\n for j := 0; j < n; j++ {\n used := make([]bool, n)\n for i := 0; i < n-1; i++ {\n used[latin[i][j]] = true\n }\n for k := 0; k < n; k++ {\n if !used[k] {\n latin[n-1][j] = k\n break\n }\n }\n }\n printSquare(latin, n)\n}\n\nfunc printSquare(latin matrix, n int) {\n for i := 0; i < n; i++ {\n fmt.Println(latin[i])\n }\n fmt.Println()\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n latinSquare(5)\n latinSquare(5)\n latinSquare(10) // for good measure\n}"} {"title": "Random number generator (device)", "language": "Go", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "package main\n\nimport (\n \"crypto/rand\"\n \"encoding/binary\"\n \"fmt\"\n \"io\"\n \"os\"\n)\n\nfunc main() {\n testRandom(\"crypto/rand\", rand.Reader)\n testRandom(\"dev/random\", newDevRandom())\n}\n\nfunc newDevRandom() (f *os.File) {\n var err error\n if f, err = os.Open(\"/dev/random\"); err != nil {\n panic(err)\n }\n return\n}\n\nfunc testRandom(label string, src io.Reader) {\n fmt.Printf(\"%s:\\n\", label)\n var r int32\n for i := 0; i < 10; i++ {\n if err := binary.Read(src, binary.LittleEndian, &r); err != nil {\n panic(err)\n }\n fmt.Print(r, \" \")\n }\n fmt.Println()\n}"} {"title": "Random number generator (included)", "language": "Go", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "Go has two random number packages in the standard library and another package in the \"subrepository.\"\n\n# [https://golang.org/pkg/math/rand/ math/rand] in the standard library provides general purpose random number support, implementing some sort of feedback shift register. (It uses a large array commented \"feeback register\" and has variables named \"tap\" and \"feed.\") Comments in the code attribute the algorithm to DP Mitchell and JA Reeds. A little more insight is in [https://github.com/golang/go/issues/21835 this issue] in the Go issue tracker.\n# [https://golang.org/pkg/crypto/rand/ crypto/rand], also in the standard library, says it \"implements a cryptographically secure pseudorandom number generator.\" I think though it should say that it ''accesses'' a cryptographically secure pseudorandom number generator. It uses /dev/urandom on Unix-like systems and the CryptGenRandom API on Windows.\n# [https://godoc.org/golang.org/x/exp/rand x/exp/rand] implements the Permuted Congruential Generator which is also described in the issue linked above.\n\n"} {"title": "Range consolidation", "language": "Go", "task": "Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* If one range covers all of the other then the result is that encompassing range.\n* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.\n* Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. \n\nIf '''N < 2''' then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then \n: there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then \n: there is : an overlap '''[2.5, 1.8]''' between the ranges and \n: the result is the single range '''[1, 4.7]'''. \n: Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then \n: they touch at '''7.2''' and \n: the result is the single range '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' \n: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' \n: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and \n: consolidate to produce the range '''[1, 5]'''. \n: This range, in turn, overlaps the other range '''[4, 8]''', and \n: so consolidates to the final output of the single range '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; and show the\nrange with the smaller lower bound to the left of other ranges when showing multiple ranges.\n\nOutput the ''normalized'' result of applying consolidation to these five sets of ranges: \n [1.1, 2.2]\n [6.1, 7.2], [7.2, 8.3]\n [4, 3], [2, 1]\n [4, 3], [2, 1], [-1, -2], [3.9, 10]\n [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] \nShow all output here.\n\n\n;See also:\n* [[Set consolidation]]\n* [[Set of real numbers]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"sort\"\n)\n\ntype Range struct{ Lower, Upper float64 }\n\nfunc (r Range) Norm() Range {\n if r.Lower > r.Upper {\n return Range{r.Upper, r.Lower}\n }\n return r\n}\n\nfunc (r Range) String() string {\n return fmt.Sprintf(\"[%g, %g]\", r.Lower, r.Upper)\n}\n\nfunc (r1 Range) Union(r2 Range) []Range {\n if r1.Upper < r2.Lower {\n return []Range{r1, r2}\n }\n r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)}\n return []Range{r}\n}\n\nfunc consolidate(rs []Range) []Range {\n for i := range rs {\n rs[i] = rs[i].Norm()\n }\n le := len(rs)\n if le < 2 {\n return rs\n }\n sort.Slice(rs, func(i, j int) bool {\n return rs[i].Lower < rs[j].Lower\n })\n if le == 2 {\n return rs[0].Union(rs[1])\n }\n for i := 0; i < le-1; i++ {\n for j := i + 1; j < le; j++ {\n ru := rs[i].Union(rs[j])\n if len(ru) == 1 {\n rs[i] = ru[0]\n copy(rs[j:], rs[j+1:])\n rs = rs[:le-1]\n le--\n i--\n break\n }\n }\n }\n return rs\n}\n\nfunc main() {\n rss := [][]Range{\n {{1.1, 2.2}},\n {{6.1, 7.2}, {7.2, 8.3}},\n {{4, 3}, {2, 1}},\n {{4, 3}, {2, 1}, {-1, -2}, {3.9, 10}},\n {{1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6}},\n }\n for _, rs := range rss {\n s := fmt.Sprintf(\"%v\", rs)\n fmt.Printf(\"%40s => \", s[1:len(s)-1])\n rs2 := consolidate(rs)\n s = fmt.Sprintf(\"%v\", rs2)\n fmt.Println(s[1 : len(s)-1])\n }\n}"} {"title": "Range expansion", "language": "Go", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nconst input = \"-6,-3--1,3-5,7-11,14,15,17-20\"\n\nfunc main() {\n fmt.Println(\"range:\", input)\n var r []int\n var last int\n for _, part := range strings.Split(input, \",\") {\n if i := strings.Index(part[1:], \"-\"); i == -1 {\n n, err := strconv.Atoi(part)\n if err != nil {\n fmt.Println(err)\n return\n }\n if len(r) > 0 {\n if last == n {\n fmt.Println(\"duplicate value:\", n)\n return\n } else if last > n {\n fmt.Println(\"values not ordered:\", last, \">\", n)\n return\n }\n }\n r = append(r, n)\n last = n\n } else {\n n1, err := strconv.Atoi(part[:i+1])\n if err != nil {\n fmt.Println(err)\n return\n }\n n2, err := strconv.Atoi(part[i+2:])\n if err != nil {\n fmt.Println(err)\n return\n }\n if n2 < n1+2 {\n fmt.Println(\"invalid range:\", part)\n return\n }\n if len(r) > 0 {\n if last == n1 {\n fmt.Println(\"duplicate value:\", n1)\n return\n } else if last > n1 {\n fmt.Println(\"values not ordered:\", last, \">\", n1)\n return\n }\n }\n for i = n1; i <= n2; i++ {\n r = append(r, i)\n }\n last = n2\n }\n }\n fmt.Println(\"expanded:\", r)\n}"} {"title": "Range extraction", "language": "Go", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n rf, err := rangeFormat([]int{\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39,\n })\n if err != nil {\n fmt.Println(err)\n return\n }\n fmt.Println(\"range format:\", rf)\n}\n\nfunc rangeFormat(a []int) (string, error) {\n if len(a) == 0 {\n return \"\", nil\n }\n var parts []string\n for n1 := 0; ; {\n n2 := n1 + 1\n for n2 < len(a) && a[n2] == a[n2-1]+1 {\n n2++\n }\n s := strconv.Itoa(a[n1])\n if n2 == n1+2 {\n s += \",\" + strconv.Itoa(a[n2-1])\n } else if n2 > n1+2 {\n s += \"-\" + strconv.Itoa(a[n2-1])\n }\n parts = append(parts, s)\n if n2 == len(a) {\n break\n }\n if a[n2] == a[n2-1] {\n return \"\", errors.New(fmt.Sprintf(\n \"sequence repeats value %d\", a[n2]))\n }\n if a[n2] < a[n2-1] {\n return \"\", errors.New(fmt.Sprintf(\n \"sequence not ordered: %d < %d\", a[n2], a[n2-1]))\n }\n n1 = n2\n }\n return strings.Join(parts, \",\"), nil\n}"} {"title": "Rate counter", "language": "Go from C", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\n// representation of time.Time is nanosecond, actual resolution system specific\ntype rateStateS struct {\n lastFlush time.Time\n period time.Duration\n tickCount int\n}\n\nfunc ticRate(pRate *rateStateS) {\n pRate.tickCount++\n now := time.Now()\n if now.Sub(pRate.lastFlush) >= pRate.period {\n // TPS Report\n tps := 0.\n if pRate.tickCount > 0 {\n tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()\n }\n fmt.Println(tps, \"tics per second.\")\n\n // Reset\n pRate.tickCount = 0\n pRate.lastFlush = now\n }\n}\n\nfunc somethingWeDo() {\n time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) // sleep about .1 second.\n}\n\nfunc main() {\n start := time.Now()\n\n rateWatch := rateStateS{\n lastFlush: start,\n period: 5 * time.Second,\n }\n\n // Loop for twenty seconds\n latest := start\n for latest.Sub(start) < 20*time.Second {\n somethingWeDo()\n ticRate(&rateWatch)\n latest = time.Now()\n }\n}"} {"title": "Read a specific line from a file", "language": "Go", "task": "Some languages have special semantics for obtaining a known line number from a file.\n\n\n;Task:\nDemonstrate how to obtain the contents of a specific line within a file. \n\nFor the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, it is permissible to read line by line. \n\nNote that empty lines are considered and should still be counted.\n\nAlso note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.\n\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc main() {\n\tif line, err := rsl(\"input.txt\", 7); err == nil {\n\t\tfmt.Println(\"7th line:\")\n\t\tfmt.Println(line)\n\t} else {\n\t\tfmt.Println(\"rsl:\", err)\n\t}\n}\n\nfunc rsl(fn string, n int) (string, error) {\n\tif n < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid request: line %d\", n)\n\t}\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tbf := bufio.NewReader(f)\n\tvar line string\n\tfor lnum := 0; lnum < n; lnum++ {\n\t\tline, err = bf.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tswitch lnum {\n\t\t\tcase 0:\n\t\t\t\treturn \"\", errors.New(\"no lines in file\")\n\t\t\tcase 1:\n\t\t\t\treturn \"\", errors.New(\"only 1 line\")\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"only %d lines\", lnum)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif line == \"\" {\n\t\treturn \"\", fmt.Errorf(\"line %d empty\", n)\n\t}\n\treturn line, nil\n}"} {"title": "Recaman's sequence", "language": "Go", "task": "The '''Recaman's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n a := []int{0}\n used := make(map[int]bool, 1001)\n used[0] = true\n used1000 := make(map[int]bool, 1001)\n used1000[0] = true\n for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {\n next := a[n-1] - n\n if next < 1 || used[next] {\n next += 2 * n\n }\n alreadyUsed := used[next]\n a = append(a, next)\n\n if !alreadyUsed {\n used[next] = true\n if next >= 0 && next <= 1000 {\n used1000[next] = true\n }\n }\n\n if n == 14 {\n fmt.Println(\"The first 15 terms of the Recaman's sequence are:\", a)\n }\n\n if !foundDup && alreadyUsed {\n fmt.Printf(\"The first duplicated term is a[%d] = %d\\n\", n, next)\n foundDup = true\n }\n\n if len(used1000) == 1001 {\n fmt.Printf(\"Terms up to a[%d] are needed to generate 0 to 1000\\n\", n)\n }\n }\n}"} {"title": "Remove lines from a file", "language": "Go", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"errors\"\n \"fmt\"\n \"io/ioutil\"\n \"os\"\n)\n\nfunc main() {\n if err := removeLines(\"foobar.txt\", 1, 2); err != nil {\n fmt.Println(err)\n }\n}\n\nfunc removeLines(fn string, start, n int) (err error) {\n if start < 1 {\n return errors.New(\"invalid request. line numbers start at 1.\")\n }\n if n < 0 {\n return errors.New(\"invalid request. negative number to remove.\")\n }\n var f *os.File\n if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {\n return\n }\n defer func() {\n if cErr := f.Close(); err == nil {\n err = cErr\n }\n }()\n var b []byte\n if b, err = ioutil.ReadAll(f); err != nil {\n return\n }\n cut, ok := skip(b, start-1)\n if !ok {\n return fmt.Errorf(\"less than %d lines\", start)\n }\n if n == 0 {\n return nil\n }\n tail, ok := skip(cut, n)\n if !ok {\n return fmt.Errorf(\"less than %d lines after line %d\", n, start)\n }\n t := int64(len(b) - len(cut))\n if err = f.Truncate(t); err != nil {\n return\n }\n if len(tail) > 0 {\n _, err = f.WriteAt(tail, t)\n }\n return\n}\n\nfunc skip(b []byte, n int) ([]byte, bool) {\n for ; n > 0; n-- {\n if len(b) == 0 {\n return nil, false\n }\n x := bytes.IndexByte(b, '\\n')\n if x < 0 {\n x = len(b)\n } else {\n x++\n }\n b = b[x:]\n }\n return b, true\n}"} {"title": "Rep-string", "language": "Go from Python", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc rep(s string) int {\n for x := len(s) / 2; x > 0; x-- {\n if strings.HasPrefix(s, s[x:]) {\n return x\n }\n }\n return 0\n}\n\nconst m = `\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1`\n\nfunc main() {\n for _, s := range strings.Fields(m) {\n if n := rep(s); n > 0 {\n fmt.Printf(\"%q %d rep-string %q\\n\", s, n, s[:n])\n } else {\n fmt.Printf(\"%q not a rep-string\\n\", s)\n }\n }\n}"} {"title": "Repeat", "language": "Go", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc repeat(n int, f func()) {\n for i := 0; i < n; i++ {\n f()\n }\n}\n\nfunc fn() {\n fmt.Println(\"Example\")\n}\n\nfunc main() {\n repeat(4, fn)\n}"} {"title": "Resistor mesh", "language": "Go from C", "task": "Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,\nfind the resistance between points '''A''' and '''B'''.\n\n\n;See also:\n* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)\n* An article on how to calculate this and an implementation in Mathematica\n\n", "solution": "package main\n\nimport \"fmt\"\n\nconst (\n\tS = 10\n)\n\ntype node struct {\n\tv float64\n\tfixed int\n}\n\nfunc alloc2(w, h int) [][]node {\n\ta := make([][]node, h)\n\n\tfor i := range a {\n\t\ta[i] = make([]node, w)\n\t}\n\treturn a\n}\n\nfunc set_boundary(m [][]node) {\n\tm[1][1].fixed = 1\n\tm[1][1].v = 1\n\tm[6][7].fixed = -1\n\tm[6][7].v = -1\n}\n\nfunc calc_diff(m [][]node, d [][]node, w, h int) float64 {\n\ttotal := 0.0\n\tfor i := 0; i < h; i++ {\n\t\tfor j := 0; j < w; j++ {\n\t\t\tv := 0.0\n\t\t\tn := 0\n\t\t\tif i != 0 {\n\t\t\t\tv += m[i-1][j].v\n\t\t\t\tn++\n\t\t\t}\n\t\t\tif j != 0 {\n\t\t\t\tv += m[i][j-1].v\n\t\t\t\tn++\n\t\t\t}\n\t\t\tif i+1 < h {\n\t\t\t\tv += m[i+1][j].v\n\t\t\t\tn++\n\t\t\t}\n\t\t\tif j+1 < w {\n\t\t\t\tv += m[i][j+1].v\n\t\t\t\tn++\n\t\t\t}\n\n\t\t\tv = m[i][j].v - v/float64(n)\n\t\t\td[i][j].v = v\n\t\t\tif m[i][j].fixed == 0 {\n\t\t\t\ttotal += v * v\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}\n\nfunc iter(m [][]node, w, h int) float64 {\n\td := alloc2(w, h)\n\tdiff := 1.0e10\n\tcur := []float64{0, 0, 0}\n\n\tfor diff > 1e-24 {\n\t\tset_boundary(m)\n\t\tdiff = calc_diff(m, d, w, h)\n\t\tfor i := 0; i < h; i++ {\n\t\t\tfor j := 0; j < w; j++ {\n\t\t\t\tm[i][j].v -= d[i][j].v\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < h; i++ {\n\t\tfor j := 0; j < w; j++ {\n\t\t\tt := 0\n\t\t\tif i != 0 {\n\t\t\t\tt += 1\n\t\t\t}\n\t\t\tif j != 0 {\n\t\t\t\tt += 1\n\t\t\t}\n\t\t\tif i < h-1 {\n\t\t\t\tt += 1\n\t\t\t}\n\t\t\tif j < w-1 {\n\t\t\t\tt += 1\n\t\t\t}\n\t\t\tcur[m[i][j].fixed+1] += d[i][j].v * float64(t)\n\t\t}\n\t}\n\treturn (cur[2] - cur[0]) / 2\n}\n\nfunc main() {\n\tmesh := alloc2(S, S)\n\tfmt.Printf(\"R = %g\\n\", 2/iter(mesh, S, S))\n}\n"} {"title": "Reverse words in a string", "language": "Go", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\n// a number of strings\nvar n = []string{\n \"---------- Ice and Fire ------------\",\n \" \",\n \"fire, in end will world the say Some\",\n \"ice. in say Some \",\n \"desire of tasted I've what From \",\n \"fire. favor who those with hold I \",\n \" \",\n \"... elided paragraph last ... \",\n \" \",\n \"Frost Robert -----------------------\",\n}\n\nfunc main() {\n for i, s := range n {\n t := strings.Fields(s) // tokenize\n // reverse\n last := len(t) - 1\n for j, k := range t[:len(t)/2] {\n t[j], t[last-j] = t[last-j], k\n }\n n[i] = strings.Join(t, \" \")\n }\n // display result\n for _, t := range n {\n fmt.Println(t)\n }\n}"} {"title": "Roman numerals/Decode", "language": "Go", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "package main\n\nimport (\n \"errors\"\n \"fmt\"\n)\n\nvar m = map[rune]int{\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000,\n}\n\nfunc parseRoman(s string) (r int, err error) {\n if s == \"\" {\n return 0, errors.New(\"Empty string\")\n }\n is := []rune(s) // easier to convert string up front\n var c0 rune // c0: roman character last read\n var cv0 int // cv0: value of cv\n\n // the key to the algorithm is to process digits from right to left\n for i := len(is) - 1; i >= 0; i-- {\n // read roman digit\n c := is[i]\n k := c == '\\u0305' // unicode overbar combining character\n if k {\n if i == 0 {\n return 0, errors.New(\n \"Overbar combining character invalid at position 0\")\n }\n i--\n c = is[i]\n }\n cv := m[c]\n if cv == 0 {\n if c == 0x0305 {\n return 0, fmt.Errorf(\n \"Overbar combining character invalid at position %d\", i)\n } else {\n return 0, fmt.Errorf(\n \"Character unrecognized as Roman digit: %c\", c)\n }\n }\n if k {\n c = -c // convention indicating overbar\n cv *= 1000\n }\n\n // handle cases of new, same, subtractive, changed, in that order.\n switch {\n default: // case 4: digit change\n fallthrough\n case c0 == 0: // case 1: no previous digit\n c0 = c\n cv0 = cv\n case c == c0: // case 2: same digit\n case cv*5 == cv0 || cv*10 == cv0: // case 3: subtractive\n // handle next digit as new.\n // a subtractive digit doesn't count as a previous digit.\n c0 = 0\n r -= cv // subtract...\n continue // ...instead of adding\n }\n r += cv // add, in all cases except subtractive\n }\n return r, nil\n}\n\nfunc main() {\n // parse three numbers mentioned in task description\n for _, r := range []string{\"MCMXC\", \"MMVIII\", \"MDCLXVI\"} {\n v, err := parseRoman(r)\n if err != nil {\n fmt.Println(err)\n } else {\n fmt.Println(r, \"==\", v)\n }\n }\n}"} {"title": "Roman numerals/Encode", "language": "Go", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar (\n m0 = []string{\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"}\n m1 = []string{\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"}\n m2 = []string{\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"}\n m3 = []string{\"\", \"M\", \"MM\", \"MMM\", \"I\u0305V\u0305\",\n \"V\u0305\", \"V\u0305I\u0305\", \"V\u0305I\u0305I\u0305\", \"V\u0305I\u0305I\u0305I\u0305\", \"I\u0305X\u0305\"}\n m4 = []string{\"\", \"X\u0305\", \"X\u0305X\u0305\", \"X\u0305X\u0305X\u0305\", \"X\u0305L\u0305\",\n \"L\u0305\", \"L\u0305X\u0305\", \"L\u0305X\u0305X\u0305\", \"L\u0305X\u0305X\u0305X\u0305\", \"X\u0305C\u0305\"}\n m5 = []string{\"\", \"C\u0305\", \"C\u0305C\u0305\", \"C\u0305C\u0305C\u0305\", \"C\u0305D\u0305\",\n \"D\u0305\", \"D\u0305C\u0305\", \"D\u0305C\u0305C\u0305\", \"D\u0305C\u0305C\u0305C\u0305\", \"C\u0305M\u0305\"}\n m6 = []string{\"\", \"M\u0305\", \"M\u0305M\u0305\", \"M\u0305M\u0305M\u0305\"}\n)\n\nfunc formatRoman(n int) (string, bool) {\n if n < 1 || n >= 4e6 {\n return \"\", false\n }\n // this is efficient in Go. the seven operands are evaluated,\n // then a single allocation is made of the exact size needed for the result.\n return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +\n m2[n%1e3/1e2] + m1[n%100/10] + m0[n%10],\n true\n}\n\nfunc main() {\n // show three numbers mentioned in task descriptions\n for _, n := range []int{1990, 2008, 1666} {\n r, ok := formatRoman(n)\n if ok {\n fmt.Println(n, \"==\", r)\n } else {\n fmt.Println(n, \"not representable\")\n }\n }\n}"} {"title": "Rosetta Code/Rank languages by number of users", "language": "Go", "task": "Sort most popular programming languages based on the number of users on Rosetta Code. \n\nShow the languages with at least 100 users.\n\n\n;A method to solve the task:\nUsers of a computer programming language '''X''' are those referenced in the page: \n https://rosettacode.org/wiki/Category:X_User, or preferably: \n https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. \n\nIn order to find the list of such categories, it's possible to first parse the entries of: \n http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. \n\nThen download and parse each computer language ''users'' category to find the number of users of that computer language.\n\n\nSample output on 18 February 2019:\nLanguage Users\n--------------------------\nC 391\nJava 276\nC++ 275\nPython 262\nJavaScript 238\nPerl 171\nPHP 167\nSQL 138\nUNIX Shell 131\nBASIC 120\nC sharp 118\nPascal 116\nHaskell 102\n\nA Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"net/http\"\n \"regexp\"\n \"sort\"\n \"strconv\"\n)\n\ntype Result struct {\n lang string\n users int\n}\n\nfunc main() {\n const minimum = 25\n ex := `\"Category:(.+?)( User)?\"(\\}|,\"categoryinfo\":\\{\"size\":(\\d+),)`\n re := regexp.MustCompile(ex)\n page := \"http://rosettacode.org/mw/api.php?\"\n action := \"action=query\"\n format := \"format=json\"\n fversion := \"formatversion=2\"\n generator := \"generator=categorymembers\"\n gcmTitle := \"gcmtitle=Category:Language%20users\"\n gcmLimit := \"gcmlimit=500\"\n prop := \"prop=categoryinfo\"\n rawContinue := \"rawcontinue=\"\n page += fmt.Sprintf(\"%s&%s&%s&%s&%s&%s&%s&%s\", action, format, fversion,\n generator, gcmTitle, gcmLimit, prop, rawContinue)\n resp, _ := http.Get(page)\n body, _ := ioutil.ReadAll(resp.Body)\n matches := re.FindAllStringSubmatch(string(body), -1)\n resp.Body.Close()\n var results []Result\n for _, match := range matches {\n if len(match) == 5 {\n users, _ := strconv.Atoi(match[4]) \n if users >= minimum {\n result := Result{match[1], users}\n results = append(results, result)\n }\n }\n }\n sort.Slice(results, func(i, j int) bool {\n return results[j].users < results[i].users\n })\n\n fmt.Println(\"Rank Users Language\")\n fmt.Println(\"---- ----- --------\")\n rank := 0\n lastUsers := 0\n lastRank := 0\n for i, result := range results {\n eq := \" \"\n rank = i + 1\n if lastUsers == result.users {\n eq = \"=\"\n rank = lastRank\n } else {\n lastUsers = result.users\n lastRank = rank\n }\n fmt.Printf(\" %-2d%s %3d %s\\n\", rank, eq, result.users, result.lang)\n }\n}"} {"title": "Runtime evaluation", "language": "Go", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "package main\nimport (\n\t\"fmt\"\n\t\"bitbucket.org/binet/go-eval/pkg/eval\"\n\t\"go/token\"\n)\n\nfunc main() {\n\tw := eval.NewWorld();\n\tfset := token.NewFileSet();\n\n\tcode, err := w.Compile(fset, \"1 + 2\")\n\tif err != nil {\n\t\tfmt.Println(\"Compile error\");\n\t\treturn\n\t}\n\n\tval, err := code.Run();\n\tif err != nil {\n\t\tfmt.Println(\"Run time error\");\n\t\treturn;\n\t}\n\tfmt.Println(\"Return value:\", val) //prints, well, 3\n\n}"} {"title": "Runtime evaluation/In an environment", "language": "Go", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "package main\n\nimport (\n \"bitbucket.org/binet/go-eval/pkg/eval\"\n \"fmt\"\n \"go/parser\"\n \"go/token\"\n)\n\nfunc main() {\n // an expression on x\n squareExpr := \"x*x\"\n\n // parse to abstract syntax tree\n fset := token.NewFileSet()\n squareAst, err := parser.ParseExpr(squareExpr)\n if err != nil {\n fmt.Println(err)\n return\n }\n // create an environment or \"world\"\n w := eval.NewWorld()\n\n // allocate a variable\n wVar := new(intV)\n\n // bind the variable to the name x\n err = w.DefineVar(\"x\", eval.IntType, wVar)\n if err != nil {\n fmt.Println(err)\n return\n }\n // bind the expression AST to the world\n squareCode, err := w.CompileExpr(fset, squareAst)\n if err != nil {\n fmt.Println(err)\n return\n }\n // directly manipulate value of variable within world\n *wVar = 5\n // evaluate\n r0, err := squareCode.Run()\n if err != nil {\n fmt.Println(err)\n return\n }\n // change value\n *wVar--\n // revaluate\n r1, err := squareCode.Run()\n if err != nil {\n fmt.Println(err)\n return\n }\n // print difference\n fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))\n}\n\n// int value implementation.\ntype intV int64\n\nfunc (v *intV) String() string { return fmt.Sprint(*v) }\nfunc (v *intV) Get(*eval.Thread) int64 { return int64(*v) }\nfunc (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }\nfunc (v *intV) Assign(t *eval.Thread, o eval.Value) {\n *v = intV(o.(eval.IntValue).Get(t))\n}"} {"title": "SHA-1", "language": "Go", "task": "'''SHA-1''' or '''SHA1''' is a one-way hash function; \nit computes a 160-bit message digest. \nSHA-1 often appears in security protocols; for example, \nmany HTTPS websites use RSA with SHA-1 to secure their connections. \nBitTorrent uses SHA-1 to verify downloads. \nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\n{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. \nThis is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. \nFor production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}\n", "solution": "package main\n\nimport (\n \"crypto/sha1\"\n \"fmt\"\n)\n\nfunc main() {\n h := sha1.New()\n h.Write([]byte(\"Rosetta Code\"))\n fmt.Printf(\"%x\\n\", h.Sum(nil))\n}"} {"title": "Sailors, coconuts and a monkey problem", "language": "Go from Kotlin", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n coconuts := 11\nouter:\n for ns := 2; ns < 10; ns++ {\n hidden := make([]int, ns)\n coconuts = (coconuts/ns)*ns + 1\n for {\n nc := coconuts\n for s := 1; s <= ns; s++ {\n if nc%ns == 1 {\n hidden[s-1] = nc / ns\n nc -= hidden[s-1] + 1\n if s == ns && nc%ns == 0 {\n fmt.Println(ns, \"sailors require a minimum of\", coconuts, \"coconuts\")\n for t := 1; t <= ns; t++ {\n fmt.Println(\"\\tSailor\", t, \"hides\", hidden[t-1])\n }\n fmt.Println(\"\\tThe monkey gets\", ns)\n fmt.Println(\"\\tFinally, each sailor takes\", nc/ns, \"\\b\\n\")\n continue outer\n }\n } else {\n break\n }\n }\n coconuts += ns\n }\n }\n}"} {"title": "Same fringe", "language": "Go", "task": "Write a routine that will compare the leaves (\"fringe\") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.\n\nAny solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.\n\nAny representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype node struct {\n int\n left, right *node\n}\n\n// function returns a channel that yields the leaves of the tree.\n// the channel is closed after all leaves are received.\nfunc leaves(t *node) chan int {\n ch := make(chan int)\n // recursive function to walk tree.\n var f func(*node)\n f = func(n *node) {\n if n == nil {\n return\n }\n // leaves are identified by having no children.\n if n.left == nil && n.right == nil {\n ch <- n.int\n } else {\n f(n.left)\n f(n.right)\n }\n }\n // goroutine runs concurrently with others.\n // it walks the tree then closes the channel.\n go func() {\n f(t)\n close(ch)\n }()\n return ch\n}\n\nfunc sameFringe(t1, t2 *node) bool {\n f1 := leaves(t1)\n f2 := leaves(t2)\n for l1 := range f1 {\n // both trees must yield a leaf, and the leaves must be equal.\n if l2, ok := <-f2; !ok || l1 != l2 {\n return false\n }\n }\n // there must be nothing left in f2 after consuming all of f1.\n _, ok := <-f2\n return !ok\n}\n\nfunc main() {\n // the different shapes of the trees is shown with indention.\n // the leaves are easy to spot by the int: key.\n t1 := &node{3,\n &node{1,\n &node{int: 1},\n &node{int: 2}},\n &node{8,\n &node{int: 5},\n &node{int: 13}}}\n // t2 with negative values for internal nodes that can't possibly match\n // positive values in t1, just to show that only leaves are being compared.\n t2 := &node{-8,\n &node{-3,\n &node{-1,\n &node{int: 1},\n &node{int: 2}},\n &node{int: 5}},\n &node{int: 13}}\n fmt.Println(sameFringe(t1, t2)) // prints true.\n}"} {"title": "Selectively replace multiple instances of a character within a string", "language": "Go from Wren", "task": "Task\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc main() {\n s := \"abracadabra\"\n ss := []byte(s)\n var ixs []int\n for ix, c := range s {\n if c == 'a' {\n ixs = append(ixs, ix)\n }\n }\n repl := \"ABaCD\"\n for i := 0; i < 5; i++ {\n ss[ixs[i]] = repl[i]\n }\n s = string(ss)\n s = strings.Replace(s, \"b\", \"E\", 1)\n s = strings.Replace(s, \"r\", \"F\", 2)\n s = strings.Replace(s, \"F\", \"r\", 1)\n fmt.Println(s)\n}"} {"title": "Self-describing numbers", "language": "Go", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n \"strings\"\n \"time\"\n)\n\nfunc selfDesc(n uint64) bool {\n if n >= 1e10 {\n return false\n }\n s := strconv.FormatUint(n, 10)\n for d, p := range s {\n if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {\n return false\n }\n }\n return true\n}\n\nfunc main() {\n start := time.Now()\n fmt.Println(\"The self-describing numbers are:\")\n i := uint64(10) // self-describing number must end in 0\n pw := uint64(10) // power of 10\n fd := uint64(1) // first digit\n sd := uint64(1) // second digit\n dg := uint64(2) // number of digits\n mx := uint64(11) // maximum for current batch\n lim := uint64(9_100_000_001) // sum of digits can't be more than 10\n for i < lim {\n if selfDesc(i) {\n secs := time.Since(start).Seconds()\n fmt.Printf(\"%d (in %.1f secs)\\n\", i, secs)\n }\n i += 10\n if i > mx {\n fd++\n sd--\n if sd >= 0 {\n i = fd * pw\n } else {\n pw *= 10\n dg++\n i = pw\n fd = 1\n sd = dg - 1\n }\n mx = i + sd*pw/10\n }\n }\n osecs := time.Since(start).Seconds()\n fmt.Printf(\"\\nTook %.1f secs overall\\n\", osecs)\n}"} {"title": "Self numbers", "language": "Go", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc sumDigits(n int) int {\n sum := 0\n for n > 0 {\n sum += n % 10\n n /= 10\n }\n return sum\n}\n\nfunc max(x, y int) int {\n if x > y {\n return x\n }\n return y\n}\n\nfunc main() {\n st := time.Now()\n count := 0\n var selfs []int\n i := 1\n pow := 10\n digits := 1\n offset := 9\n lastSelf := 0\n for count < 1e8 {\n isSelf := true\n start := max(i-offset, 0)\n sum := sumDigits(start)\n for j := start; j < i; j++ {\n if j+sum == i {\n isSelf = false\n break\n }\n if (j+1)%10 != 0 {\n sum++\n } else {\n sum = sumDigits(j + 1)\n }\n }\n if isSelf {\n count++\n lastSelf = i\n if count <= 50 {\n selfs = append(selfs, i)\n if count == 50 {\n fmt.Println(\"The first 50 self numbers are:\")\n fmt.Println(selfs)\n }\n }\n }\n i++\n if i%pow == 0 {\n pow *= 10\n digits++\n offset = digits * 9\n }\n }\n fmt.Println(\"\\nThe 100 millionth self number is\", lastSelf)\n fmt.Println(\"Took\", time.Since(st))\n}"} {"title": "Self numbers", "language": "Go from Pascal", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nconst MAX_COUNT = 103*1e4*1e4 + 11*9 + 1\n\nvar sv = make([]bool, MAX_COUNT+1)\nvar digitSum = make([]int, 1e4)\n\nfunc init() {\n i := 9999\n var s, t int\n for a := 9; a >= 0; a-- {\n for b := 9; b >= 0; b-- {\n s = a + b\n for c := 9; c >= 0; c-- {\n t = s + c\n for d := 9; d >= 0; d-- {\n digitSum[i] = t + d\n i--\n }\n }\n }\n }\n}\n\nfunc sieve() {\n n := 0\n for a := 0; a < 103; a++ {\n for b := 0; b < 1e4; b++ {\n s := digitSum[a] + digitSum[b] + n\n for c := 0; c < 1e4; c++ {\n sv[digitSum[c]+s] = true\n s++\n }\n n += 1e4\n }\n }\n}\n\nfunc main() {\n st := time.Now()\n sieve()\n fmt.Println(\"Sieving took\", time.Since(st))\n count := 0\n fmt.Println(\"\\nThe first 50 self numbers are:\")\n for i := 0; i < len(sv); i++ {\n if !sv[i] {\n count++\n if count <= 50 {\n fmt.Printf(\"%d \", i)\n } else {\n fmt.Println(\"\\n\\n Index Self number\")\n break\n }\n }\n }\n count = 0\n limit := 1\n for i := 0; i < len(sv); i++ {\n if !sv[i] {\n count++\n if count == limit {\n fmt.Printf(\"%10d %11d\\n\", count, i)\n limit *= 10\n if limit == 1e10 {\n break\n }\n }\n }\n }\n fmt.Println(\"\\nOverall took\", time.Since(st))\n}"} {"title": "Semordnilap", "language": "Go", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"strings\"\n)\n\nfunc main() {\n // read file into memory as one big block\n data, err := ioutil.ReadFile(\"unixdict.txt\")\n if err != nil {\n log.Fatal(err)\n }\n // copy the block, split it up into words\n words := strings.Split(string(data), \"\\n\")\n // optional, free the first block for garbage collection\n data = nil\n // put words in a map, also determine length of longest word\n m := make(map[string]bool)\n longest := 0\n for _, w := range words {\n m[string(w)] = true\n if len(w) > longest {\n longest = len(w)\n }\n }\n // allocate a buffer for reversing words\n r := make([]byte, longest)\n // iterate over word list\n sem := 0\n var five []string\n for _, w := range words {\n // first, delete from map. this prevents a palindrome from matching\n // itself, and also prevents it's reversal from matching later.\n delete(m, w)\n // use buffer to reverse word\n last := len(w) - 1\n for i := 0; i < len(w); i++ {\n r[i] = w[last-i]\n }\n rs := string(r[:len(w)])\n // see if reversed word is in map, accumulate results\n if m[rs] {\n sem++\n if len(five) < 5 {\n five = append(five, w+\"/\"+rs)\n }\n }\n }\n // print results\n fmt.Println(sem, \"pairs\")\n fmt.Println(\"examples:\")\n for _, e := range five {\n fmt.Println(\" \", e)\n }\n}"} {"title": "Sequence: nth number with exactly n divisors", "language": "Go", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/big\"\n)\n\nvar bi = new(big.Int)\n\nfunc isPrime(n int) bool {\n bi.SetUint64(uint64(n))\n return bi.ProbablyPrime(0)\n}\n\nfunc generateSmallPrimes(n int) []int {\n primes := make([]int, n)\n primes[0] = 2\n for i, count := 3, 1; count < n; i += 2 {\n if isPrime(i) {\n primes[count] = i\n count++\n }\n }\n return primes\n}\n\nfunc countDivisors(n int) int {\n count := 1\n for n%2 == 0 {\n n >>= 1\n count++\n }\n for d := 3; d*d <= n; d += 2 {\n q, r := n/d, n%d\n if r == 0 {\n dc := 0\n for r == 0 {\n dc += count\n n = q\n q, r = n/d, n%d\n }\n count += dc\n }\n }\n if n != 1 {\n count *= 2\n }\n return count\n}\n\nfunc main() {\n const max = 33\n primes := generateSmallPrimes(max)\n z := new(big.Int)\n p := new(big.Int)\n fmt.Println(\"The first\", max, \"terms in the sequence are:\")\n for i := 1; i <= max; i++ {\n if isPrime(i) {\n z.SetUint64(uint64(primes[i-1]))\n p.SetUint64(uint64(i - 1))\n z.Exp(z, p, nil)\n fmt.Printf(\"%2d : %d\\n\", i, z)\n } else {\n count := 0\n for j := 1; ; j++ {\n if i%2 == 1 {\n sq := int(math.Sqrt(float64(j)))\n if sq*sq != j {\n continue\n }\n }\n if countDivisors(j) == i {\n count++\n if count == i {\n fmt.Printf(\"%2d : %d\\n\", i, j)\n break\n }\n }\n }\n }\n }\n}"} {"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "Go", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n count := 0\n for i := 1; i*i <= n; i++ {\n if n%i == 0 {\n if i == n/i {\n count++\n } else {\n count += 2\n }\n }\n }\n return count\n}\n\nfunc main() {\n const max = 15\n fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n for i, next := 1, 1; next <= max; i++ {\n if next == countDivisors(i) {\n fmt.Printf(\"%d \", i)\n next++\n }\n }\n fmt.Println()\n}"} {"title": "Sequence: smallest number with exactly n divisors", "language": "Go", "task": "Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n count := 0\n for i := 1; i*i <= n; i++ {\n if n%i == 0 {\n if i == n/i {\n count++\n } else {\n count += 2\n }\n }\n }\n return count\n}\n\nfunc main() {\n const max = 15\n seq := make([]int, max)\n fmt.Println(\"The first\", max, \"terms of the sequence are:\")\n for i, n := 1, 0; n < max; i++ {\n if k := countDivisors(i); k <= max && seq[k-1] == 0 {\n seq[k-1] = i\n n++\n }\n }\n fmt.Println(seq)\n}"} {"title": "Set consolidation", "language": "Go from Python", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype set map[string]bool\n\nvar testCase = []set{\n set{\"H\": true, \"I\": true, \"K\": true},\n set{\"A\": true, \"B\": true},\n set{\"C\": true, \"D\": true},\n set{\"D\": true, \"B\": true},\n set{\"F\": true, \"G\": true, \"H\": true},\n}\n\nfunc main() {\n fmt.Println(consolidate(testCase))\n}\n\nfunc consolidate(sets []set) []set {\n setlist := []set{}\n for _, s := range sets {\n if s != nil && len(s) > 0 {\n setlist = append(setlist, s)\n }\n }\n for i, s1 := range setlist {\n if len(s1) > 0 {\n for _, s2 := range setlist[i+1:] {\n if s1.disjoint(s2) {\n continue\n }\n for e := range s1 {\n s2[e] = true\n delete(s1, e)\n }\n s1 = s2\n }\n }\n }\n r := []set{}\n for _, s := range setlist {\n if len(s) > 0 {\n r = append(r, s)\n }\n }\n return r\n}\n\nfunc (s1 set) disjoint(s2 set) bool {\n for e := range s2 {\n if s1[e] {\n return false\n }\n }\n return true\n}"} {"title": "Set of real numbers", "language": "Go", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype Set func(float64) bool\n\nfunc Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } }\nfunc Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } }\nfunc Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } }\nfunc open(a, b float64) Set { return func(x float64) bool { return a < x && x < b } }\nfunc closed(a, b float64) Set { return func(x float64) bool { return a <= x && x <= b } }\nfunc opCl(a, b float64) Set { return func(x float64) bool { return a < x && x <= b } }\nfunc clOp(a, b float64) Set { return func(x float64) bool { return a <= x && x < b } }\n\nfunc main() {\n\ts := make([]Set, 4)\n\ts[0] = Union(opCl(0, 1), clOp(0, 2)) // (0,1] \u222a [0,2)\n\ts[1] = Inter(clOp(0, 2), opCl(1, 2)) // [0,2) \u2229 (1,2]\n\ts[2] = Diff(clOp(0, 3), open(0, 1)) // [0,3) \u2212 (0,1)\n\ts[3] = Diff(clOp(0, 3), closed(0, 1)) // [0,3) \u2212 [0,1]\n\n\tfor i := range s {\n\t\tfor x := float64(0); x < 3; x++ {\n\t\t\tfmt.Printf(\"%v \u2208 s%d: %t\\n\", x, i, s[i](x))\n\t\t}\n\t\tfmt.Println()\n\t}\n}"} {"title": "Set right-adjacent bits", "language": "Go from Wren", "task": "Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000, \nand a zero or more integer n :\n* Output the result of setting the n bits to the right of any set bit in b \n(if those bits are present in b and therefore also preserving the width, e).\n \n'''Some examples:''' \n\n Set of examples showing how one bit in a nibble gets changed:\n \n n = 2; Width e = 4:\n \n Input b: 1000\n Result: 1110\n \n Input b: 0100\n Result: 0111\n \n Input b: 0010\n Result: 0011\n \n Input b: 0000\n Result: 0000\n \n Set of examples with the same input with set bits of varying distance apart:\n \n n = 0; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 010000000000100000000010000000010000000100000010000010000100010010\n \n n = 1; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011000000000110000000011000000011000000110000011000011000110011011\n \n n = 2; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011100000000111000000011100000011100000111000011100011100111011111\n \n n = 3; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011110000000111100000011110000011110000111100011110011110111111111\n\n'''Task:'''\n\n* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.\n* Use it to show, here, the results for the input examples above.\n* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\ntype test struct {\n bs string\n n int\n}\n\nfunc setRightBits(bits []byte, e, n int) []byte {\n if e == 0 || n <= 0 {\n return bits\n }\n bits2 := make([]byte, len(bits))\n copy(bits2, bits)\n for i := 0; i < e-1; i++ {\n c := bits[i]\n if c == 1 {\n j := i + 1\n for j <= i+n && j < e {\n bits2[j] = 1\n j++\n }\n }\n }\n return bits2\n}\n\nfunc main() {\n b := \"010000000000100000000010000000010000000100000010000010000100010010\"\n tests := []test{\n test{\"1000\", 2}, test{\"0100\", 2}, test{\"0010\", 2}, test{\"0000\", 2},\n test{b, 0}, test{b, 1}, test{b, 2}, test{b, 3},\n }\n for _, test := range tests {\n bs := test.bs\n e := len(bs)\n n := test.n\n fmt.Println(\"n =\", n, \"\\b; Width e =\", e, \"\\b:\")\n fmt.Println(\" Input b:\", bs)\n bits := []byte(bs)\n for i := 0; i < len(bits); i++ {\n bits[i] = bits[i] - '0'\n }\n bits = setRightBits(bits, e, n)\n var sb strings.Builder\n for i := 0; i < len(bits); i++ {\n sb.WriteByte(bits[i] + '0')\n }\n fmt.Println(\" Result :\", sb.String())\n }\n}"} {"title": "Shoelace formula for polygonal area", "language": "Go", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype point struct{ x, y float64 }\n\nfunc shoelace(pts []point) float64 {\n sum := 0.\n p0 := pts[len(pts)-1]\n for _, p1 := range pts {\n sum += p0.y*p1.x - p0.x*p1.y\n p0 = p1\n }\n return sum / 2\n}\n\nfunc main() {\n fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}}))\n}"} {"title": "Shortest common supersequence", "language": "Go from Kotlin", "task": "The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.\n\n\n;;Task:\nGiven two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.\n\nDemonstrate this by printing s where u = \"abcbdab\" and v = \"bdcaba\".\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc lcs(x, y string) string {\n xl, yl := len(x), len(y)\n if xl == 0 || yl == 0 {\n return \"\"\n }\n x1, y1 := x[:xl-1], y[:yl-1]\n if x[xl-1] == y[yl-1] {\n return fmt.Sprintf(\"%s%c\", lcs(x1, y1), x[xl-1])\n }\n x2, y2 := lcs(x, y1), lcs(x1, y)\n if len(x2) > len(y2) {\n return x2\n } else {\n return y2\n }\n}\n\nfunc scs(u, v string) string {\n ul, vl := len(u), len(v)\n lcs := lcs(u, v)\n ui, vi := 0, 0\n var sb strings.Builder\n for i := 0; i < len(lcs); i++ {\n for ui < ul && u[ui] != lcs[i] {\n sb.WriteByte(u[ui])\n ui++\n }\n for vi < vl && v[vi] != lcs[i] {\n sb.WriteByte(v[vi])\n vi++\n }\n sb.WriteByte(lcs[i])\n ui++\n vi++\n }\n if ui < ul {\n sb.WriteString(u[ui:])\n }\n if vi < vl {\n sb.WriteString(v[vi:])\n }\n return sb.String()\n}\n\nfunc main() {\n u := \"abcbdab\"\n v := \"bdcaba\"\n fmt.Println(scs(u, v))\n}"} {"title": "Show ASCII table", "language": "Go", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n for i := 0; i < 16; i++ {\n for j := 32 + i; j < 128; j += 16 {\n k := string(j)\n switch j {\n case 32:\n k = \"Spc\"\n case 127:\n k = \"Del\"\n }\n fmt.Printf(\"%3d : %-3s \", j, k)\n }\n fmt.Println()\n }\n}"} {"title": "Show the epoch", "language": "Go", "task": "Choose popular date libraries used by your language and show the epoch those libraries use. \n\nA demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. \n\nFor consistency's sake, show the date in UTC time where possible.\n\n\n;Related task:\n* [[Date format]]\n\n", "solution": "package main\nimport (\"fmt\"; \"time\")\n\nfunc main() {\n fmt.Println(time.Time{})\n}"} {"title": "Sierpinski triangle/Graphical", "language": "Go from Icon and Unicon", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"image\"\n \"image/color\"\n \"image/draw\"\n \"image/png\"\n \"os\"\n)\n\nfunc main() {\n const order = 8\n const width = 1 << order\n const margin = 10\n bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)\n im := image.NewGray(bounds)\n gBlack := color.Gray{0}\n gWhite := color.Gray{255}\n draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)\n\n for y := 0; y < width; y++ {\n for x := 0; x < width; x++ {\n if x&y == 0 {\n im.SetGray(x, y, gBlack)\n }\n }\n }\n f, err := os.Create(\"sierpinski.png\")\n if err != nil {\n fmt.Println(err)\n return\n }\n if err = png.Encode(f, im); err != nil {\n fmt.Println(err)\n }\n if err = f.Close(); err != nil {\n fmt.Println(err)\n }\n}"} {"title": "Smith numbers", "language": "Go from C", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc numPrimeFactors(x uint) int {\n\tvar p uint = 2\n\tvar pf int\n\tif x == 1 {\n\t\treturn 1\n\t}\n\tfor {\n\t\tif (x % p) == 0 {\n\t\t\tpf++\n\t\t\tx /= p\n\t\t\tif x == 1 {\n\t\t\t\treturn pf\n\t\t\t}\n\t\t} else {\n\t\t\tp++\n\t\t}\n\t}\n}\n\nfunc primeFactors(x uint, arr []uint) {\n\tvar p uint = 2\n\tvar pf int\n\tif x == 1 {\n\t\tarr[pf] = 1\n\t\treturn\n\t}\n\tfor {\n\t\tif (x % p) == 0 {\n\t\t\tarr[pf] = p\n\t\t\tpf++\n\t\t\tx /= p\n\t\t\tif x == 1 {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tp++\n\t\t}\n\t}\n}\n\nfunc sumDigits(x uint) uint {\n\tvar sum uint\n\tfor x != 0 {\n\t\tsum += x % 10\n\t\tx /= 10\n\t}\n\treturn sum\n}\n\nfunc sumFactors(arr []uint, size int) uint {\n\tvar sum uint\n\tfor a := 0; a < size; a++ {\n\t\tsum += sumDigits(arr[a])\n\t}\n\treturn sum\n}\n\nfunc listAllSmithNumbers(maxSmith uint) {\n\tvar arr []uint\n\tvar a uint\n\tfor a = 4; a < maxSmith; a++ {\n\t\tnumfactors := numPrimeFactors(a)\n\t\tarr = make([]uint, numfactors)\n\t\tif numfactors < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tprimeFactors(a, arr)\n\t\tif sumDigits(a) == sumFactors(arr, numfactors) {\n\t\t\tfmt.Printf(\"%4d \", a)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tconst maxSmith = 10000\n\tfmt.Printf(\"All the Smith Numbers less than %d are:\\n\", maxSmith)\n\tlistAllSmithNumbers(maxSmith)\n\tfmt.Println()\n}\n"} {"title": "Solve a Hidato puzzle", "language": "Go from Java", "task": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n** The grid is not necessarily rectangular.\n** The grid may have holes in it.\n** The grid is always connected.\n** The number \"1\" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from \"1\" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n** A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]];\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strconv\"\n \"strings\"\n)\n\nvar board [][]int\nvar start, given []int\n\nfunc setup(input []string) {\n /* This task is not about input validation, so\n we're going to trust the input to be valid */\n puzzle := make([][]string, len(input))\n for i := 0; i < len(input); i++ {\n puzzle[i] = strings.Fields(input[i])\n }\n nCols := len(puzzle[0])\n nRows := len(puzzle)\n list := make([]int, nRows*nCols)\n board = make([][]int, nRows+2)\n for i := 0; i < nRows+2; i++ {\n board[i] = make([]int, nCols+2)\n for j := 0; j < nCols+2; j++ {\n board[i][j] = -1\n }\n }\n for r := 0; r < nRows; r++ {\n row := puzzle[r]\n for c := 0; c < nCols; c++ {\n switch cell := row[c]; cell {\n case \"_\":\n board[r+1][c+1] = 0\n case \".\":\n break\n default:\n val, _ := strconv.Atoi(cell)\n board[r+1][c+1] = val\n list = append(list, val)\n if val == 1 {\n start = append(start, r+1, c+1)\n }\n }\n }\n }\n sort.Ints(list)\n given = make([]int, len(list))\n for i := 0; i < len(given); i++ {\n given[i] = list[i]\n }\n}\n\nfunc solve(r, c, n, next int) bool {\n if n > given[len(given)-1] {\n return true\n }\n\n back := board[r][c]\n if back != 0 && back != n {\n return false\n }\n\n if back == 0 && given[next] == n {\n return false\n }\n\n if back == n {\n next++\n }\n\n board[r][c] = n\n for i := -1; i < 2; i++ {\n for j := -1; j < 2; j++ {\n if solve(r+i, c+j, n+1, next) {\n return true\n }\n }\n }\n\n board[r][c] = back\n return false\n}\n\nfunc printBoard() {\n for _, row := range board {\n for _, c := range row {\n switch {\n case c == -1:\n fmt.Print(\" . \")\n case c > 0:\n fmt.Printf(\"%2d \", c)\n default:\n fmt.Print(\"__ \")\n }\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n input := []string{\n \"_ 33 35 _ _ . . .\",\n \"_ _ 24 22 _ . . .\",\n \"_ _ _ 21 _ _ . .\",\n \"_ 26 _ 13 40 11 . .\",\n \"27 _ _ _ 9 _ 1 .\",\n \". . _ _ 18 _ _ .\",\n \". . . . _ 7 _ _\",\n \". . . . . . 5 _\",\n }\n setup(input)\n printBoard()\n fmt.Println(\"\\nFound:\")\n solve(start[0], start[1], 1, 0)\n printBoard()\n}"} {"title": "Solve a Holy Knight's tour", "language": "Go from Python", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar moves = [][2]int{\n {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},\n}\n\nvar board1 = \" xxx \" +\n \" x xx \" +\n \" xxxxxxx\" +\n \"xxx x x\" +\n \"x x xxx\" +\n \"sxxxxxx \" +\n \" xx x \" +\n \" xxx \"\n\nvar board2 = \".....s.x.....\" +\n \".....x.x.....\" +\n \"....xxxxx....\" +\n \".....xxx.....\" +\n \"..x..x.x..x..\" +\n \"xxxxx...xxxxx\" +\n \"..xx.....xx..\" +\n \"xxxxx...xxxxx\" +\n \"..x..x.x..x..\" +\n \".....xxx.....\" +\n \"....xxxxx....\" +\n \".....x.x.....\" +\n \".....x.x.....\"\n\nfunc solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {\n if idx > cnt {\n return true\n }\n for i := 0; i < len(moves); i++ {\n x := sx + moves[i][0]\n y := sy + moves[i][1]\n if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {\n pz[x][y] = idx\n if solve(pz, sz, x, y, idx+1, cnt) {\n return true\n }\n pz[x][y] = 0\n }\n }\n return false\n}\n\nfunc findSolution(b string, sz int) {\n pz := make([][]int, sz)\n for i := 0; i < sz; i++ {\n pz[i] = make([]int, sz)\n for j := 0; j < sz; j++ {\n pz[i][j] = -1\n }\n }\n var x, y, idx, cnt int\n for j := 0; j < sz; j++ {\n for i := 0; i < sz; i++ {\n switch b[idx] {\n case 'x':\n pz[i][j] = 0\n cnt++\n case 's':\n pz[i][j] = 1\n cnt++\n x, y = i, j\n }\n idx++\n }\n }\n\n if solve(pz, sz, x, y, 2, cnt) {\n for j := 0; j < sz; j++ {\n for i := 0; i < sz; i++ {\n if pz[i][j] != -1 {\n fmt.Printf(\"%02d \", pz[i][j])\n } else {\n fmt.Print(\"-- \")\n }\n }\n fmt.Println()\n }\n } else {\n fmt.Println(\"Cannot solve this puzzle!\")\n }\n}\n\nfunc main() {\n findSolution(board1, 8)\n fmt.Println()\n findSolution(board2, 13)\n}"} {"title": "Solve a Hopido puzzle", "language": "Go from Java", "task": "Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:\n\n\"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!\"\n\nKnowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.\n\nExample:\n\n . 0 0 . 0 0 .\n 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0\n . 0 0 0 0 0 .\n . . 0 0 0 . .\n . . . 0 . . .\n\nExtra credits are available for other interesting designs.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\nvar board = []string{\n \".00.00.\",\n \"0000000\",\n \"0000000\",\n \".00000.\",\n \"..000..\",\n \"...0...\",\n}\n\nvar moves = [][2]int{\n {-3, 0}, {0, 3}, {3, 0}, {0, -3},\n {2, 2}, {2, -2}, {-2, 2}, {-2, -2},\n}\n\nvar grid [][]int\n\nvar totalToFill = 0\n\nfunc solve(r, c, count int) bool {\n if count > totalToFill {\n return true\n }\n nbrs := neighbors(r, c)\n if len(nbrs) == 0 && count != totalToFill {\n return false\n }\n sort.Slice(nbrs, func(i, j int) bool {\n return nbrs[i][2] < nbrs[j][2]\n })\n\n for _, nb := range nbrs {\n r = nb[0]\n c = nb[1]\n grid[r][c] = count\n if solve(r, c, count+1) {\n return true\n }\n grid[r][c] = 0\n }\n return false\n}\n\nfunc neighbors(r, c int) (nbrs [][3]int) {\n for _, m := range moves {\n x := m[0]\n y := m[1]\n if grid[r+y][c+x] == 0 {\n num := countNeighbors(r+y, c+x) - 1\n nbrs = append(nbrs, [3]int{r + y, c + x, num})\n }\n }\n return\n}\n\nfunc countNeighbors(r, c int) int {\n num := 0\n for _, m := range moves {\n if grid[r+m[1]][c+m[0]] == 0 {\n num++\n }\n }\n return num\n}\n\nfunc printResult() {\n for _, row := range grid {\n for _, i := range row {\n if i == -1 {\n fmt.Print(\" \")\n } else {\n fmt.Printf(\"%2d \", i)\n }\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n nRows := len(board) + 6\n nCols := len(board[0]) + 6\n grid = make([][]int, nRows)\n for r := 0; r < nRows; r++ {\n grid[r] = make([]int, nCols)\n for c := 0; c < nCols; c++ {\n grid[r][c] = -1\n }\n for c := 3; c < nCols-3; c++ {\n if r >= 3 && r < nRows-3 {\n if board[r-3][c-3] == '0' {\n grid[r][c] = 0\n totalToFill++\n }\n }\n }\n }\n pos, r, c := -1, 0, 0\n for {\n for {\n pos++\n r = pos / nCols\n c = pos % nCols\n if grid[r][c] != -1 {\n break\n }\n }\n grid[r][c] = 1\n if solve(r, c, 2) {\n break\n }\n grid[r][c] = 0\n if pos >= nRows*nCols {\n break\n }\n }\n printResult()\n}"} {"title": "Solve a Numbrix puzzle", "language": "Go from Kotlin", "task": "Numbrix puzzles are similar to Hidato. \nThe most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). \nPublished puzzles also tend not to have holes in the grid and may not always indicate the end node. \nTwo examples follow:\n\n;Example 1\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 0 46 45 0 55 74 0 0\n 0 38 0 0 43 0 0 78 0\n 0 35 0 0 0 0 0 71 0\n 0 0 33 0 0 0 59 0 0\n 0 17 0 0 0 0 0 67 0\n 0 18 0 0 11 0 0 64 0\n 0 0 24 21 0 1 2 0 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 49 50 51 52 53 54 75 76 81\n 48 47 46 45 44 55 74 77 80\n 37 38 39 40 43 56 73 78 79\n 36 35 34 41 42 57 72 71 70\n 31 32 33 14 13 58 59 68 69\n 30 17 16 15 12 61 60 67 66\n 29 18 19 20 11 62 63 64 65\n 28 25 24 21 10 1 2 3 4\n 27 26 23 22 9 8 7 6 5\n\n;Example 2\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n 34 33 4 3 24 23 58 57 68\n 35 32 31 2 25 54 55 56 69\n 36 37 30 1 26 53 74 73 70\n 39 38 29 28 27 52 75 72 71\n 40 43 44 47 48 51 76 77 78\n 41 42 45 46 49 50 81 80 79\n\n;Task\nWrite a program to solve puzzles of this ilk, \ndemonstrating your program by solving the above examples. \nExtra credit for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n \"strconv\"\n \"strings\"\n)\n\nvar example1 = []string{\n \"00,00,00,00,00,00,00,00,00\",\n \"00,00,46,45,00,55,74,00,00\",\n \"00,38,00,00,43,00,00,78,00\",\n \"00,35,00,00,00,00,00,71,00\",\n \"00,00,33,00,00,00,59,00,00\",\n \"00,17,00,00,00,00,00,67,00\",\n \"00,18,00,00,11,00,00,64,00\",\n \"00,00,24,21,00,01,02,00,00\",\n \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar example2 = []string{\n \"00,00,00,00,00,00,00,00,00\",\n \"00,11,12,15,18,21,62,61,00\",\n \"00,06,00,00,00,00,00,60,00\",\n \"00,33,00,00,00,00,00,57,00\",\n \"00,32,00,00,00,00,00,56,00\",\n \"00,37,00,01,00,00,00,73,00\",\n \"00,38,00,00,00,00,00,72,00\",\n \"00,43,44,47,48,51,76,77,00\",\n \"00,00,00,00,00,00,00,00,00\",\n}\n\nvar moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}\n\nvar (\n grid [][]int\n clues []int\n totalToFill = 0\n)\n\nfunc solve(r, c, count, nextClue int) bool {\n if count > totalToFill {\n return true\n }\n\n back := grid[r][c]\n\n if back != 0 && back != count {\n return false\n }\n\n if back == 0 && nextClue < len(clues) && clues[nextClue] == count {\n return false\n }\n\n if back == count {\n nextClue++\n }\n\n grid[r][c] = count\n for _, move := range moves {\n if solve(r+move[1], c+move[0], count+1, nextClue) {\n return true\n }\n }\n grid[r][c] = back\n return false\n}\n\nfunc printResult(n int) {\n fmt.Println(\"Solution for example\", n, \"\\b:\")\n for _, row := range grid {\n for _, i := range row {\n if i == -1 {\n continue\n }\n fmt.Printf(\"%2d \", i)\n }\n fmt.Println()\n }\n}\n\nfunc main() {\n for n, board := range [2][]string{example1, example2} {\n nRows := len(board) + 2\n nCols := len(strings.Split(board[0], \",\")) + 2\n startRow, startCol := 0, 0\n grid = make([][]int, nRows)\n totalToFill = (nRows - 2) * (nCols - 2)\n var lst []int\n\n for r := 0; r < nRows; r++ {\n grid[r] = make([]int, nCols)\n for c := 0; c < nCols; c++ {\n grid[r][c] = -1\n }\n if r >= 1 && r < nRows-1 {\n row := strings.Split(board[r-1], \",\")\n for c := 1; c < nCols-1; c++ {\n val, _ := strconv.Atoi(row[c-1])\n if val > 0 {\n lst = append(lst, val)\n }\n if val == 1 {\n startRow, startCol = r, c\n }\n grid[r][c] = val\n }\n }\n }\n\n sort.Ints(lst)\n clues = lst\n if solve(startRow, startCol, 1, 0) {\n printResult(n + 1)\n }\n }\n}"} {"title": "Sort an outline at every level", "language": "Go from Wren", "task": "Write and test a function over an indented plain text outline which either:\n# Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or\n# reports that the indentation characters or widths are not consistent enough to make the outline structure clear.\n\n\n\nYour code should detect and warn of at least two types of inconsistent indentation:\n* inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces)\n* inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces.\n\n\nYour code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units.\n\nYou should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts.\n\nYour sort should not alter the type or size of the indentation units used in the input outline.\n\n\n(For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text is available for inspection on Github).\n\n\n'''Tests'''\n\n* Sort every level of the (4 space indented) outline below lexically, once ascending and once descending.\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\n* Do the same with a tab-indented equivalent of the same outline.\n\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n\n\nThe output sequence of an ascending lexical sort of each level should be:\n\nalpha\n epsilon\n iota\n theta\nzeta\n beta\n delta\n gamma\n kappa\n lambda\n mu\n\nThe output sequence of a descending lexical sort of each level should be:\n\nzeta\n gamma\n mu\n lambda\n kappa\n delta\n beta\nalpha\n theta\n iota\n epsilon\n\n* Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code.\n\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\n\n\n;Related tasks:\n\n:* [[Functional_coverage_tree]\n:* [[Display_an_outline_as_a_nested_table]]\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"sort\"\n \"strings\"\n)\n\nfunc sortedOutline(originalOutline []string, ascending bool) {\n outline := make([]string, len(originalOutline))\n copy(outline, originalOutline) // make copy in case we mutate it\n indent := \"\"\n del := \"\\x7f\"\n sep := \"\\x00\"\n var messages []string\n if strings.TrimLeft(outline[0], \" \\t\") != outline[0] {\n fmt.Println(\" outline structure is unclear\")\n return\n }\n for i := 1; i < len(outline); i++ {\n line := outline[i]\n lc := len(line)\n if strings.HasPrefix(line, \" \") || strings.HasPrefix(line, \" \\t\") || line[0] == '\\t' {\n lc2 := len(strings.TrimLeft(line, \" \\t\"))\n currIndent := line[0 : lc-lc2]\n if indent == \"\" {\n indent = currIndent\n } else {\n correctionNeeded := false\n if (strings.ContainsRune(currIndent, '\\t') && !strings.ContainsRune(indent, '\\t')) ||\n (!strings.ContainsRune(currIndent, '\\t') && strings.ContainsRune(indent, '\\t')) {\n m := fmt.Sprintf(\"corrected inconsistent whitespace use at line %q\", line)\n messages = append(messages, indent+m)\n correctionNeeded = true\n } else if len(currIndent)%len(indent) != 0 {\n m := fmt.Sprintf(\"corrected inconsistent indent width at line %q\", line)\n messages = append(messages, indent+m)\n correctionNeeded = true\n }\n if correctionNeeded {\n mult := int(math.Round(float64(len(currIndent)) / float64(len(indent))))\n outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:]\n }\n }\n }\n }\n levels := make([]int, len(outline))\n levels[0] = 1\n margin := \"\"\n for level := 1; ; level++ {\n allPos := true\n for i := 1; i < len(levels); i++ {\n if levels[i] == 0 {\n allPos = false\n break\n }\n }\n if allPos {\n break\n }\n mc := len(margin)\n for i := 1; i < len(outline); i++ {\n if levels[i] == 0 {\n line := outline[i]\n if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\\t' {\n levels[i] = level\n }\n }\n }\n margin += indent\n }\n lines := make([]string, len(outline))\n lines[0] = outline[0]\n var nodes []string\n for i := 1; i < len(outline); i++ {\n if levels[i] > levels[i-1] {\n if len(nodes) == 0 {\n nodes = append(nodes, outline[i-1])\n } else {\n nodes = append(nodes, sep+outline[i-1])\n }\n } else if levels[i] < levels[i-1] {\n j := levels[i-1] - levels[i]\n nodes = nodes[0 : len(nodes)-j]\n }\n if len(nodes) > 0 {\n lines[i] = strings.Join(nodes, \"\") + sep + outline[i]\n } else {\n lines[i] = outline[i]\n }\n }\n if ascending {\n sort.Strings(lines)\n } else {\n maxLen := len(lines[0])\n for i := 1; i < len(lines); i++ {\n if len(lines[i]) > maxLen {\n maxLen = len(lines[i])\n }\n }\n for i := 0; i < len(lines); i++ {\n lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i]))\n }\n sort.Sort(sort.Reverse(sort.StringSlice(lines)))\n }\n for i := 0; i < len(lines); i++ {\n s := strings.Split(lines[i], sep)\n lines[i] = s[len(s)-1]\n if !ascending {\n lines[i] = strings.TrimRight(lines[i], del)\n }\n }\n if len(messages) > 0 {\n fmt.Println(strings.Join(messages, \"\\n\"))\n fmt.Println()\n }\n fmt.Println(strings.Join(lines, \"\\n\"))\n}\n\nfunc main() {\n outline := []string{\n \"zeta\",\n \" beta\",\n \" gamma\",\n \" lambda\",\n \" kappa\",\n \" mu\",\n \" delta\",\n \"alpha\",\n \" theta\",\n \" iota\",\n \" epsilon\",\n }\n\n outline2 := make([]string, len(outline))\n for i := 0; i < len(outline); i++ {\n outline2[i] = strings.ReplaceAll(outline[i], \" \", \"\\t\")\n }\n\n outline3 := []string{\n \"alpha\",\n \" epsilon\",\n \" iota\",\n \" theta\",\n \"zeta\",\n \" beta\",\n \" delta\",\n \" gamma\",\n \" \\t kappa\", // same length but \\t instead of space\n \" lambda\",\n \" mu\",\n }\n\n outline4 := []string{\n \"zeta\",\n \" beta\",\n \" gamma\",\n \" lambda\",\n \" kappa\",\n \" mu\",\n \" delta\",\n \"alpha\",\n \" theta\",\n \" iota\",\n \" epsilon\",\n }\n\n fmt.Println(\"Four space indented outline, ascending sort:\")\n sortedOutline(outline, true)\n\n fmt.Println(\"\\nFour space indented outline, descending sort:\")\n sortedOutline(outline, false)\n\n fmt.Println(\"\\nTab indented outline, ascending sort:\")\n sortedOutline(outline2, true)\n\n fmt.Println(\"\\nTab indented outline, descending sort:\")\n sortedOutline(outline2, false)\n\n fmt.Println(\"\\nFirst unspecified outline, ascending sort:\")\n sortedOutline(outline3, true)\n\n fmt.Println(\"\\nFirst unspecified outline, descending sort:\")\n sortedOutline(outline3, false)\n\n fmt.Println(\"\\nSecond unspecified outline, ascending sort:\")\n sortedOutline(outline4, true)\n\n fmt.Println(\"\\nSecond unspecified outline, descending sort:\")\n sortedOutline(outline4, false)\n}"} {"title": "Sparkline in unicode", "language": "Go", "task": "A sparkline is a graph of successive values laid out horizontally \nwhere the height of the line is proportional to the values in succession.\n\n\n;Task:\nUse the following series of Unicode characters to create a program \nthat takes a series of numbers separated by one or more whitespace or comma characters \nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: '########'\n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input, \nhere on this page:\n# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \n:(note the mix of separators in this second case)!\n\n;Notes: \n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n:: \"0, 1, 19, 20\" -> ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"errors\"\n \"fmt\"\n \"math\"\n \"os\"\n \"regexp\"\n \"strconv\"\n \"strings\"\n)\n\nfunc main() {\n fmt.Println(\"Numbers please separated by space/commas:\")\n sc := bufio.NewScanner(os.Stdin)\n sc.Scan()\n s, n, min, max, err := spark(sc.Text())\n if err != nil {\n fmt.Println(err)\n return\n }\n if n == 1 {\n fmt.Println(\"1 value =\", min)\n } else {\n fmt.Println(n, \"values. Min:\", min, \"Max:\", max)\n }\n fmt.Println(s)\n}\n\nvar sep = regexp.MustCompile(`[\\s,]+`)\n\nfunc spark(s0 string) (sp string, n int, min, max float64, err error) {\n ss := sep.Split(s0, -1)\n n = len(ss)\n vs := make([]float64, n)\n var v float64\n min = math.Inf(1)\n max = math.Inf(-1)\n for i, s := range ss {\n switch v, err = strconv.ParseFloat(s, 64); {\n case err != nil:\n case math.IsNaN(v):\n err = errors.New(\"NaN not supported.\")\n case math.IsInf(v, 0):\n err = errors.New(\"Inf not supported.\")\n default:\n if v < min {\n min = v\n }\n if v > max {\n max = v\n }\n vs[i] = v\n continue\n }\n return\n }\n if min == max {\n sp = strings.Repeat(\"\u2584\", n)\n } else {\n rs := make([]rune, n)\n f := 8 / (max - min)\n for j, v := range vs {\n i := rune(f * (v - min))\n if i > 7 {\n i = 7\n }\n rs[j] = '\u2581' + i\n }\n sp = string(rs)\n }\n return\n}"} {"title": "Spelling of ordinal numbers", "language": "Go", "task": "'''Ordinal numbers''' (as used in this Rosetta Code task), are numbers that describe the ''position'' of something in a list.\n\nIt is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.\n\n\nThe ordinal numbers are (at least, one form of them):\n 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** etc\n\nsometimes expressed as:\n 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th ***\n\n\nFor this task, the following (English-spelled form) will be used:\n first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth\n\n\nFurthermore, the American version of numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\n;Task:\nWrite a driver and a function (subroutine/routine ***) that returns the English-spelled ordinal version of a specified number (a positive integer).\n\nOptionally, try to support as many forms of an integer that can be expressed: '''123''' '''00123.0''' '''1.23e2''' all are forms of the same integer.\n\nShow all output here.\n\n\n;Test cases:\nUse (at least) the test cases of:\n 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003\n\n\n;Related tasks:\n* [[Number names]]\n* [[N'th]]\n\n", "solution": "import (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfor _, n := range []int64{\n\t\t1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\t} {\n\t\tfmt.Println(sayOrdinal(n))\n\t}\n}\n\nvar irregularOrdinals = map[string]string{\n\t\"one\": \"first\",\n\t\"two\": \"second\",\n\t\"three\": \"third\",\n\t\"five\": \"fifth\",\n\t\"eight\": \"eighth\",\n\t\"nine\": \"ninth\",\n\t\"twelve\": \"twelfth\",\n}\n\nfunc sayOrdinal(n int64) string {\n\ts := say(n)\n\ti := strings.LastIndexAny(s, \" -\")\n\ti++\n\t// Now s[:i] is everything upto and including the space or hyphen\n\t// and s[i:] is the last word; we modify s[i:] as required.\n\t// Since LastIndex returns -1 if there was no space/hyphen,\n\t// `i` will be zero and this will still be fine.\n\tif x, ok := irregularOrdinals[s[i:]]; ok {\n\t\ts = s[:i] + x\n\t} else if s[len(s)-1] == 'y' {\n\t\ts = s[:i] + s[i:len(s)-1] + \"ieth\"\n\t} else {\n\t\ts = s[:i] + s[i:] + \"th\"\n\t}\n\treturn s\n}\n\n// Below is a copy of https://rosettacode.org/wiki/Number_names#Go\n\nvar small = [...]string{\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n\t\"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n\t\"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"}\nvar tens = [...]string{\"\", \"\", \"twenty\", \"thirty\", \"forty\",\n\t\"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"}\nvar illions = [...]string{\"\", \" thousand\", \" million\", \" billion\",\n\t\" trillion\", \" quadrillion\", \" quintillion\"}\n\nfunc say(n int64) string {\n\tvar t string\n\tif n < 0 {\n\t\tt = \"negative \"\n\t\t// Note, for math.MinInt64 this leaves n negative.\n\t\tn = -n\n\t}\n\tswitch {\n\tcase n < 20:\n\t\tt += small[n]\n\tcase n < 100:\n\t\tt += tens[n/10]\n\t\ts := n % 10\n\t\tif s > 0 {\n\t\t\tt += \"-\" + small[s]\n\t\t}\n\tcase n < 1000:\n\t\tt += small[n/100] + \" hundred\"\n\t\ts := n % 100\n\t\tif s > 0 {\n\t\t\tt += \" \" + say(s)\n\t\t}\n\tdefault:\n\t\t// work right-to-left\n\t\tsx := \"\"\n\t\tfor i := 0; n > 0; i++ {\n\t\t\tp := n % 1000\n\t\t\tn /= 1000\n\t\t\tif p > 0 {\n\t\t\t\tix := say(p) + illions[i]\n\t\t\t\tif sx != \"\" {\n\t\t\t\t\tix += \" \" + sx\n\t\t\t\t}\n\t\t\t\tsx = ix\n\t\t\t}\n\t\t}\n\t\tt += sx\n\t}\n\treturn t\n}"} {"title": "Split a character string based on change of character", "language": "Go", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc main() {\n fmt.Println(scc(`gHHH5YY++///\\`))\n}\n\nfunc scc(s string) string {\n if len(s) < 2 {\n return s\n }\n var b strings.Builder\n p := s[0]\n b.WriteByte(p)\n for _, c := range []byte(s[1:]) {\n if c != p {\n b.WriteString(\", \")\n }\n b.WriteByte(c)\n p = c\n }\n return b.String()\n}"} {"title": "Square-free integers", "language": "Go", "task": "Write a function to test if a number is ''square-free''.\n\n\nA ''square-free'' is an integer which is divisible by no perfect square other\nthan '''1''' (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* '''1''' ---> '''145''' (inclusive)\n::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* '''1''' ---> one hundred (inclusive)\n::* '''1''' ---> one thousand (inclusive)\n::* '''1''' ---> ten thousand (inclusive)\n::* '''1''' ---> one hundred thousand (inclusive)\n::* '''1''' ---> one million (inclusive)\n\n\n;See also:\n:* the Wikipedia entry: square-free integer\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc sieve(limit uint64) []uint64 {\n primes := []uint64{2}\n c := make([]bool, limit+1) // composite = true\n // no need to process even numbers > 2\n p := uint64(3)\n for {\n p2 := p * p\n if p2 > limit {\n break\n }\n for i := p2; i <= limit; i += 2 * p {\n c[i] = true\n }\n for {\n p += 2\n if !c[p] {\n break\n }\n }\n }\n for i := uint64(3); i <= limit; i += 2 {\n if !c[i] {\n primes = append(primes, i)\n }\n }\n return primes\n}\n\nfunc squareFree(from, to uint64) (results []uint64) {\n limit := uint64(math.Sqrt(float64(to)))\n primes := sieve(limit)\nouter:\n for i := from; i <= to; i++ {\n for _, p := range primes {\n p2 := p * p\n if p2 > i {\n break\n }\n if i%p2 == 0 {\n continue outer\n }\n }\n results = append(results, i)\n }\n return\n}\n\nconst trillion uint64 = 1000000000000\n\nfunc main() {\n fmt.Println(\"Square-free integers from 1 to 145:\")\n sf := squareFree(1, 145)\n for i := 0; i < len(sf); i++ {\n if i > 0 && i%20 == 0 {\n fmt.Println()\n }\n fmt.Printf(\"%4d\", sf[i])\n }\n\n fmt.Printf(\"\\n\\nSquare-free integers from %d to %d:\\n\", trillion, trillion+145)\n sf = squareFree(trillion, trillion+145)\n for i := 0; i < len(sf); i++ {\n if i > 0 && i%5 == 0 {\n fmt.Println()\n }\n fmt.Printf(\"%14d\", sf[i])\n }\n\n fmt.Println(\"\\n\\nNumber of square-free integers:\\n\")\n a := [...]uint64{100, 1000, 10000, 100000, 1000000}\n for _, n := range a {\n fmt.Printf(\" from %d to %d = %d\\n\", 1, n, len(squareFree(1, n)))\n }\n}"} {"title": "Square but not cube", "language": "Go", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nfunc main() {\n for n, count := 1, 0; count < 30; n++ {\n sq := n * n\n cr := int(math.Cbrt(float64(sq)))\n if cr*cr*cr != sq {\n count++\n fmt.Println(sq)\n } else {\n fmt.Println(sq, \"is square and cube\")\n }\n }\n}"} {"title": "Start from a main routine", "language": "Go", "task": "Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.\n\n\n;Task:\nDemonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.\n\nLanguages that always run from main() can be omitted from this task.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nvar count = 0\n\nfunc foo() {\n fmt.Println(\"foo called\")\n}\n\nfunc init() {\n fmt.Println(\"first init called\")\n foo()\n}\n\nfunc init() {\n fmt.Println(\"second init called\")\n main()\n}\n\nfunc main() {\n count++\n fmt.Println(\"main called when count is\", count)\n}"} {"title": "Statistics/Normal distribution", "language": "Go", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n \"math/rand\"\n \"strings\"\n)\n\n// Box-Muller\nfunc norm2() (s, c float64) {\n r := math.Sqrt(-2 * math.Log(rand.Float64()))\n s, c = math.Sincos(2 * math.Pi * rand.Float64())\n return s * r, c * r\n}\n\nfunc main() {\n const (\n n = 10000\n bins = 12\n sig = 3\n scale = 100\n )\n var sum, sumSq float64\n h := make([]int, bins)\n for i, accum := 0, func(v float64) {\n sum += v\n sumSq += v * v\n b := int((v + sig) * bins / sig / 2)\n if b >= 0 && b < bins {\n h[b]++\n }\n }; i < n/2; i++ {\n v1, v2 := norm2()\n accum(v1)\n accum(v2)\n }\n m := sum / n\n fmt.Println(\"mean:\", m)\n fmt.Println(\"stddev:\", math.Sqrt(sumSq/float64(n)-m*m))\n for _, p := range h {\n fmt.Println(strings.Repeat(\"*\", p/scale))\n }\n}"} {"title": "Stern-Brocot sequence", "language": "Go", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "// SB implements the Stern-Brocot sequence.\n//\n// Generator() satisfies RC Task 1. For remaining tasks, Generator could be\n// used but FirstN(), and Find() are simpler methods for specific stopping\n// criteria. FirstN and Find might also be considered to satisfy Task 1,\n// in which case Generator would not really be needed. Anyway, there it is.\npackage sb\n\n// Seq represents an even number of terms of a Stern-Brocot sequence.\n//\n// Terms are stored in a slice. Terms start with 1.\n// (Specifically, the zeroth term, 0, given in OEIS A002487 is not represented.)\n// Term 1 (== 1) is stored at slice index 0.\n//\n// Methods on Seq rely on Seq always containing an even number of terms.\ntype Seq []int\n\n// New returns a Seq with the two base terms.\nfunc New() *Seq {\n return &Seq{1, 1} // Step 1 of the RC task.\n}\n\n// TwoMore appends two more terms to p.\n// It's the body of the loop in the RC algorithm.\n// Generate(), FirstN(), and Find() wrap this body in different ways.\nfunc (p *Seq) TwoMore() {\n s := *p\n n := len(s) / 2 // Steps 2 and 5 of the RC task.\n c := s[n]\n *p = append(s, c+s[n-1], c) // Steps 3 and 4 of the RC task.\n}\n\n// Generator returns a generator function that returns successive terms\n// (until overflow.)\nfunc Generator() func() int {\n n := 0\n p := New()\n return func() int {\n if len(*p) == n {\n p.TwoMore()\n }\n t := (*p)[n]\n n++\n return t\n }\n}\n\n// FirstN lazily extends p as needed so that it has at least n terms.\n// FirstN then returns a list of the first n terms.\nfunc (p *Seq) FirstN(n int) []int {\n for len(*p) < n {\n p.TwoMore()\n }\n return []int((*p)[:n])\n}\n\n// Find lazily extends p as needed until it contains the value x\n// Find then returns the slice index of x in p.\nfunc (p *Seq) Find(x int) int {\n for n, f := range *p {\n if f == x {\n return n\n }\n }\n for {\n p.TwoMore()\n switch x {\n case (*p)[len(*p)-2]:\n return len(*p) - 2\n case (*p)[len(*p)-1]:\n return len(*p) - 1\n }\n }\n}"} {"title": "Stirling numbers of the first kind", "language": "Go", "task": "Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number\nof cycles (counting fixed points as cycles of length one).\n\nThey may be defined directly to be the number of permutations of '''n'''\nelements with '''k''' disjoint cycles.\n\nStirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.\n\nDepending on the application, Stirling numbers of the first kind may be \"signed\"\nor \"unsigned\". Signed Stirling numbers of the first kind arise when the\npolynomial expansion is expressed in terms of falling factorials; unsigned when\nexpressed in terms of rising factorials. The only substantial difference is that,\nfor signed Stirling numbers of the first kind, values of S1(n, k) are negative\nwhen n + k is odd.\n\nStirling numbers of the first kind follow the simple identities:\n\n S1(0, 0) = 1\n S1(n, 0) = 0 if n > 0\n S1(n, k) = 0 if k > n\n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned\n ''or''\n S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the first kind'''\n:* '''OEIS:A008275 - Signed Stirling numbers of the first kind'''\n:* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the second kind'''\n:* '''Lah numbers'''\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n limit := 100\n last := 12\n unsigned := true\n s1 := make([][]*big.Int, limit+1)\n for n := 0; n <= limit; n++ {\n s1[n] = make([]*big.Int, limit+1)\n for k := 0; k <= limit; k++ {\n s1[n][k] = new(big.Int)\n }\n }\n s1[0][0].SetInt64(int64(1))\n var t big.Int\n for n := 1; n <= limit; n++ {\n for k := 1; k <= n; k++ {\n t.SetInt64(int64(n - 1))\n t.Mul(&t, s1[n-1][k]) \n if unsigned {\n s1[n][k].Add(s1[n-1][k-1], &t)\n } else {\n s1[n][k].Sub(s1[n-1][k-1], &t)\n } \n }\n }\n fmt.Println(\"Unsigned Stirling numbers of the first kind: S1(n, k):\")\n fmt.Printf(\"n/k\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"%9d \", i)\n }\n fmt.Printf(\"\\n--\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"----------\")\n }\n fmt.Println()\n for n := 0; n <= last; n++ {\n fmt.Printf(\"%2d \", n)\n for k := 0; k <= n; k++ {\n fmt.Printf(\"%9d \", s1[n][k])\n }\n fmt.Println()\n }\n fmt.Println(\"\\nMaximum value from the S1(100, *) row:\")\n max := new(big.Int).Set(s1[limit][0])\n for k := 1; k <= limit; k++ {\n if s1[limit][k].Cmp(max) > 0 {\n max.Set(s1[limit][k])\n }\n }\n fmt.Println(max)\n fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}"} {"title": "Stirling numbers of the second kind", "language": "Go", "task": "Stirling numbers of the second kind, or Stirling partition numbers, are the\nnumber of ways to partition a set of n objects into k non-empty subsets. They are\nclosely related to [[Bell numbers]], and may be derived from them.\n\n\nStirling numbers of the second kind obey the recurrence relation:\n\n S2(n, 0) and S2(0, k) = 0 # for n, k > 0\n S2(n, n) = 1\n S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)\n\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the second kind'''\n:* '''OEIS:A008277 - Stirling numbers of the second kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Bell numbers'''\n:* '''Lah numbers'''\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n limit := 100\n last := 12\n s2 := make([][]*big.Int, limit+1)\n for n := 0; n <= limit; n++ {\n s2[n] = make([]*big.Int, limit+1)\n for k := 0; k <= limit; k++ {\n s2[n][k] = new(big.Int)\n }\n s2[n][n].SetInt64(int64(1))\n }\n var t big.Int\n for n := 1; n <= limit; n++ {\n for k := 1; k <= n; k++ {\n t.SetInt64(int64(k))\n t.Mul(&t, s2[n-1][k])\n s2[n][k].Add(&t, s2[n-1][k-1])\n }\n }\n fmt.Println(\"Stirling numbers of the second kind: S2(n, k):\")\n fmt.Printf(\"n/k\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"%9d \", i)\n }\n fmt.Printf(\"\\n--\")\n for i := 0; i <= last; i++ {\n fmt.Printf(\"----------\")\n }\n fmt.Println()\n for n := 0; n <= last; n++ {\n fmt.Printf(\"%2d \", n)\n for k := 0; k <= n; k++ {\n fmt.Printf(\"%9d \", s2[n][k])\n }\n fmt.Println()\n }\n fmt.Println(\"\\nMaximum value from the S2(100, *) row:\")\n max := new(big.Int).Set(s2[limit][0])\n for k := 1; k <= limit; k++ {\n if s2[limit][k].Cmp(max) > 0 {\n max.Set(s2[limit][k])\n }\n }\n fmt.Println(max)\n fmt.Printf(\"which has %d digits.\\n\", len(max.String()))\n}"} {"title": "Strassen's algorithm", "language": "Go from Wren", "task": "Description\nIn linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication. \n\nIt is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.\n\n\n;Task\nWrite a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.\n\nWhile practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512x512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.\n\n\n;Related task\n:* [[Matrix multiplication]]\n\n\n;See also\n:* Wikipedia article\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n)\n\ntype Matrix [][]float64\n\nfunc (m Matrix) rows() int { return len(m) }\nfunc (m Matrix) cols() int { return len(m[0]) }\n\nfunc (m Matrix) add(m2 Matrix) Matrix {\n if m.rows() != m2.rows() || m.cols() != m2.cols() {\n log.Fatal(\"Matrices must have the same dimensions.\")\n }\n c := make(Matrix, m.rows())\n for i := 0; i < m.rows(); i++ {\n c[i] = make([]float64, m.cols())\n for j := 0; j < m.cols(); j++ {\n c[i][j] = m[i][j] + m2[i][j]\n }\n }\n return c\n}\n\nfunc (m Matrix) sub(m2 Matrix) Matrix {\n if m.rows() != m2.rows() || m.cols() != m2.cols() {\n log.Fatal(\"Matrices must have the same dimensions.\")\n }\n c := make(Matrix, m.rows())\n for i := 0; i < m.rows(); i++ {\n c[i] = make([]float64, m.cols())\n for j := 0; j < m.cols(); j++ {\n c[i][j] = m[i][j] - m2[i][j]\n }\n }\n return c\n}\n\nfunc (m Matrix) mul(m2 Matrix) Matrix {\n if m.cols() != m2.rows() {\n log.Fatal(\"Cannot multiply these matrices.\")\n }\n c := make(Matrix, m.rows())\n for i := 0; i < m.rows(); i++ {\n c[i] = make([]float64, m2.cols())\n for j := 0; j < m2.cols(); j++ {\n for k := 0; k < m2.rows(); k++ {\n c[i][j] += m[i][k] * m2[k][j]\n }\n }\n }\n return c\n}\n\nfunc (m Matrix) toString(p int) string {\n s := make([]string, m.rows())\n pow := math.Pow(10, float64(p))\n for i := 0; i < m.rows(); i++ {\n t := make([]string, m.cols())\n for j := 0; j < m.cols(); j++ {\n r := math.Round(m[i][j]*pow) / pow\n t[j] = fmt.Sprintf(\"%g\", r)\n if t[j] == \"-0\" {\n t[j] = \"0\"\n }\n }\n s[i] = fmt.Sprintf(\"%v\", t)\n }\n return fmt.Sprintf(\"%v\", s)\n}\n\nfunc params(r, c int) [4][6]int {\n return [4][6]int{\n {0, r, 0, c, 0, 0},\n {0, r, c, 2 * c, 0, c},\n {r, 2 * r, 0, c, r, 0},\n {r, 2 * r, c, 2 * c, r, c},\n }\n}\n\nfunc toQuarters(m Matrix) [4]Matrix {\n r := m.rows() / 2\n c := m.cols() / 2\n p := params(r, c)\n var quarters [4]Matrix\n for k := 0; k < 4; k++ {\n q := make(Matrix, r)\n for i := p[k][0]; i < p[k][1]; i++ {\n q[i-p[k][4]] = make([]float64, c)\n for j := p[k][2]; j < p[k][3]; j++ {\n q[i-p[k][4]][j-p[k][5]] = m[i][j]\n }\n }\n quarters[k] = q\n }\n return quarters\n}\n\nfunc fromQuarters(q [4]Matrix) Matrix {\n r := q[0].rows()\n c := q[0].cols()\n p := params(r, c)\n r *= 2\n c *= 2\n m := make(Matrix, r)\n for i := 0; i < c; i++ {\n m[i] = make([]float64, c)\n }\n for k := 0; k < 4; k++ {\n for i := p[k][0]; i < p[k][1]; i++ {\n for j := p[k][2]; j < p[k][3]; j++ {\n m[i][j] = q[k][i-p[k][4]][j-p[k][5]]\n }\n }\n }\n return m\n}\n\nfunc strassen(a, b Matrix) Matrix {\n if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() {\n log.Fatal(\"Matrices must be square and of equal size.\")\n }\n if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 {\n log.Fatal(\"Size of matrices must be a power of two.\")\n }\n if a.rows() == 1 {\n return a.mul(b)\n }\n qa := toQuarters(a)\n qb := toQuarters(b)\n p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3]))\n p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3]))\n p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1]))\n p4 := strassen(qa[0].add(qa[1]), qb[3])\n p5 := strassen(qa[0], qb[1].sub(qb[3]))\n p6 := strassen(qa[3], qb[2].sub(qb[0]))\n p7 := strassen(qa[2].add(qa[3]), qb[0])\n var q [4]Matrix\n q[0] = p1.add(p2).sub(p4).add(p6)\n q[1] = p4.add(p5)\n q[2] = p6.add(p7)\n q[3] = p2.sub(p3).add(p5).sub(p7)\n return fromQuarters(q)\n}\n\nfunc main() {\n a := Matrix{{1, 2}, {3, 4}}\n b := Matrix{{5, 6}, {7, 8}}\n c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}}\n d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24},\n {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}}\n e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}\n f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}\n fmt.Println(\"Using 'normal' matrix multiplication:\")\n fmt.Printf(\" a * b = %v\\n\", a.mul(b))\n fmt.Printf(\" c * d = %v\\n\", c.mul(d).toString(6))\n fmt.Printf(\" e * f = %v\\n\", e.mul(f))\n fmt.Println(\"\\nUsing 'Strassen' matrix multiplication:\")\n fmt.Printf(\" a * b = %v\\n\", strassen(a, b))\n fmt.Printf(\" c * d = %v\\n\", strassen(c, d).toString(6))\n fmt.Printf(\" e * f = %v\\n\", strassen(e, f))\n}"} {"title": "Stream merge", "language": "Go", "task": " 2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n; ''N''-stream merge\n: The same as above, but reading from ''N'' sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].\n\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams.\n\n", "solution": "package main\n\nimport (\n \"container/heap\"\n \"fmt\"\n \"io\"\n \"log\"\n \"os\"\n \"strings\"\n)\n\nvar s1 = \"3 14 15\"\nvar s2 = \"2 17 18\"\nvar s3 = \"\"\nvar s4 = \"2 3 5 7\"\n\nfunc main() {\n fmt.Print(\"merge2: \")\n merge2(\n os.Stdout,\n strings.NewReader(s1),\n strings.NewReader(s2))\n fmt.Println()\n\n fmt.Print(\"mergeN: \")\n mergeN(\n os.Stdout,\n strings.NewReader(s1),\n strings.NewReader(s2),\n strings.NewReader(s3),\n strings.NewReader(s4))\n fmt.Println()\n}\n\nfunc r1(r io.Reader) (v int, ok bool) {\n switch _, err := fmt.Fscan(r, &v); {\n case err == nil:\n return v, true\n case err != io.EOF:\n log.Fatal(err)\n }\n return\n}\n\nfunc merge2(m io.Writer, s1, s2 io.Reader) {\n v1, d1 := r1(s1)\n v2, d2 := r1(s2)\n var v int\n for d1 || d2 {\n if !d2 || d1 && v1 < v2 {\n v = v1\n v1, d1 = r1(s1)\n } else {\n v = v2\n v2, d2 = r1(s2)\n }\n fmt.Fprint(m, v, \" \")\n }\n}\n\ntype sv struct {\n s io.Reader\n v int\n}\n\ntype sh []sv\n\nfunc (s sh) Len() int { return len(s) }\nfunc (s sh) Less(i, j int) bool { return s[i].v < s[j].v }\nfunc (s sh) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (p *sh) Push(x interface{}) { *p = append(*p, x.(sv)) }\nfunc (p *sh) Pop() interface{} {\n s := *p\n last := len(s) - 1\n v := s[last]\n *p = s[:last]\n return v\n}\n\nfunc mergeN(m io.Writer, s ...io.Reader) {\n var h sh\n for _, s := range s {\n if v, d := r1(s); d {\n h = append(h, sv{s, v})\n }\n }\n heap.Init(&h)\n for len(h) > 0 {\n p := heap.Pop(&h).(sv)\n fmt.Fprint(m, p.v, \" \")\n if v, d := r1(p.s); d {\n heap.Push(&h, sv{p.s, v})\n }\n }\n}"} {"title": "Strip control codes and extended characters from a string", "language": "Go", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "package main\n\nimport (\n\t\"golang.org/x/text/transform\"\n\t\"golang.org/x/text/unicode/norm\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// two byte-oriented functions identical except for operator comparing c to 127.\nfunc stripCtlFromBytes(str string) string {\n\tb := make([]byte, len(str))\n\tvar bl int\n\tfor i := 0; i < len(str); i++ {\n\t\tc := str[i]\n\t\tif c >= 32 && c != 127 {\n\t\t\tb[bl] = c\n\t\t\tbl++\n\t\t}\n\t}\n\treturn string(b[:bl])\n}\n\nfunc stripCtlAndExtFromBytes(str string) string {\n\tb := make([]byte, len(str))\n\tvar bl int\n\tfor i := 0; i < len(str); i++ {\n\t\tc := str[i]\n\t\tif c >= 32 && c < 127 {\n\t\t\tb[bl] = c\n\t\t\tbl++\n\t\t}\n\t}\n\treturn string(b[:bl])\n}\n\n// two UTF-8 functions identical except for operator comparing c to 127\nfunc stripCtlFromUTF8(str string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r >= 32 && r != 127 {\n\t\t\treturn r\n\t\t}\n\t\treturn -1\n\t}, str)\n}\n\nfunc stripCtlAndExtFromUTF8(str string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif r >= 32 && r < 127 {\n\t\t\treturn r\n\t\t}\n\t\treturn -1\n\t}, str)\n}\n\n// Advanced Unicode normalization and filtering,\n// see http://blog.golang.org/normalization and\n// http://godoc.org/golang.org/x/text/unicode/norm for more\n// details.\nfunc stripCtlAndExtFromUnicode(str string) string {\n\tisOk := func(r rune) bool {\n\t\treturn r < 32 || r >= 127\n\t}\n\t// The isOk filter is such that there is no need to chain to norm.NFC\n\tt := transform.Chain(norm.NFKD, transform.RemoveFunc(isOk))\n\t// This Transformer could also trivially be applied as an io.Reader\n\t// or io.Writer filter to automatically do such filtering when reading\n\t// or writing data anywhere.\n\tstr, _, _ = transform.String(t, str)\n\treturn str\n}\n\nconst src = \"d\u00e9j\u00e0 vu\" + // precomposed unicode\n\t\"\\n\\000\\037 \\041\\176\\177\\200\\377\\n\" + // various boundary cases\n\t\"as\u20dddf\u0305\" // unicode combining characters\n\nfunc main() {\n\tfmt.Println(\"source text:\")\n\tfmt.Println(src)\n\tfmt.Println(\"\\nas bytes, stripped of control codes:\")\n\tfmt.Println(stripCtlFromBytes(src))\n\tfmt.Println(\"\\nas bytes, stripped of control codes and extended characters:\")\n\tfmt.Println(stripCtlAndExtFromBytes(src))\n\tfmt.Println(\"\\nas UTF-8, stripped of control codes:\")\n\tfmt.Println(stripCtlFromUTF8(src))\n\tfmt.Println(\"\\nas UTF-8, stripped of control codes and extended characters:\")\n\tfmt.Println(stripCtlAndExtFromUTF8(src))\n\tfmt.Println(\"\\nas decomposed and stripped Unicode:\")\n\tfmt.Println(stripCtlAndExtFromUnicode(src))\n}"} {"title": "Subleq", "language": "Go", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:\n::::* simple numeric values \n::::* memory addresses \n::::* characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.\n:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.\n:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \"Hello, world!\" program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "package main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\tvar mem = []int{\n\t\t15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1,\n\t\t//'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\\n',\n\t\t72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10,\n\t\t0,\n\t}\n\tfor ip := 0; ip >= 0; {\n\t\tswitch {\n\t\tcase mem[ip] == -1:\n\t\t\tmem[mem[ip+1]] = readbyte()\n\t\tcase mem[ip+1] == -1:\n\t\t\twritebyte(mem[mem[ip]])\n\t\tdefault:\n\t\t\tb := mem[ip+1]\n\t\t\tv := mem[b] - mem[mem[ip]]\n\t\t\tmem[b] = v\n\t\t\tif v <= 0 {\n\t\t\t\tip = mem[ip+2]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tip += 3\n\t}\n}\n\nfunc readbyte() int {\n\tvar b [1]byte\n\tif _, err := io.ReadFull(os.Stdin, b[:]); err != nil {\n\t\tlog.Fatalln(\"read:\", err)\n\t}\n\treturn int(b[0])\n}\n\nfunc writebyte(b int) {\n\tif _, err := os.Stdout.Write([]byte{byte(b)}); err != nil {\n\t\tlog.Fatalln(\"write:\", err)\n\t}\n}"} {"title": "Substring/Top and tail", "language": "Go", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"unicode/utf8\"\n)\n\nfunc main() {\n // ASCII contents: Interpreting \"characters\" as bytes.\n s := \"ASCII\"\n fmt.Println(\"String: \", s)\n fmt.Println(\"First byte removed: \", s[1:])\n fmt.Println(\"Last byte removed: \", s[:len(s)-1])\n fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n // UTF-8 contents: \"Characters\" as runes (unicode code points)\n u := \"\u0394\u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\u03ae\"\n fmt.Println(\"String: \", u)\n _, sizeFirst := utf8.DecodeRuneInString(u)\n fmt.Println(\"First rune removed: \", u[sizeFirst:])\n _, sizeLast := utf8.DecodeLastRuneInString(u)\n fmt.Println(\"Last rune removed: \", u[:len(u)-sizeLast])\n fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}"} {"title": "Suffixation of decimal numbers", "language": "Go", "task": "'''Suffixation''': a letter or a group of letters added to the end of a word to change its meaning.\n::::::: ----- or, as used herein -----\n'''Suffixation''': the addition of a metric or \"binary\" metric suffix to a number, with/without rounding.\n\n\n;Task:\nWrite a function(s) to append (if possible) a metric or a \"binary\" metric suffix to a\nnumber (displayed in decimal).\n\nThe number may be rounded (as per user specification) (via shortening of the number when the number of\ndigits past the decimal point are to be used).\n\n\n;Task requirements:\n::* write a function (or functions) to add (if possible) a suffix to a number\n::* the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified\n::* the sign should be preserved (if present)\n::* the number may have commas within the number (the commas need not be preserved)\n::* the number may have a decimal point and/or an exponent as in: -123.7e-01\n::* the suffix that might be appended should be in uppercase; however, the '''i''' should be in lowercase\n::* support:\n::::* the metric suffixes: '''K M G T P E Z Y X W V U'''\n::::* the binary metric suffixes: '''Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui'''\n::::* the (full name) suffix: '''googol''' (lowercase) (equal to '''1e100''') (optional)\n::::* a number of decimal digits past the decimal point (with rounding). The default is to display all significant digits\n::* validation of the (supplied/specified) arguments is optional but recommended\n::* display (with identifying text):\n::::* the original number (with identifying text)\n::::* the number of digits past the decimal point being used (or none, if not specified)\n::::* the type of suffix being used (metric or \"binary\" metric)\n::::* the (new) number with the appropriate (if any) suffix\n::::* all output here on this page\n\n\n;Metric suffixes to be supported (whether or not they're officially sanctioned):\n '''K''' multiply the number by '''10^3''' kilo (1,000)\n '''M''' multiply the number by '''10^6''' mega (1,000,000)\n '''G''' multiply the number by '''10^9''' giga (1,000,000,000)\n '''T''' multiply the number by '''10^12''' tera (1,000,000,000,000)\n '''P''' multiply the number by '''10^15''' peta (1,000,000,000,000,000)\n '''E''' multiply the number by '''10^18''' exa (1,000,000,000,000,000,000)\n '''Z''' multiply the number by '''10^21''' zetta (1,000,000,000,000,000,000,000)\n '''Y''' multiply the number by '''10^24''' yotta (1,000,000,000,000,000,000,000,000)\n '''X''' multiply the number by '''10^27''' xenta (1,000,000,000,000,000,000,000,000,000)\n '''W''' multiply the number by '''10^30''' wekta (1,000,000,000,000,000,000,000,000,000,000)\n '''V''' multiply the number by '''10^33''' vendeka (1,000,000,000,000,000,000,000,000,000,000,000)\n '''U''' multiply the number by '''10^36''' udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)\n\n\n;\"Binary\" suffixes to be supported (whether or not they're officially sanctioned):\n '''Ki''' multiply the number by '''2^10''' kibi (1,024)\n '''Mi''' multiply the number by '''2^20''' mebi (1,048,576)\n '''Gi''' multiply the number by '''2^30''' gibi (1,073,741,824)\n '''Ti''' multiply the number by '''2^40''' tebi (1,099,571,627,776)\n '''Pi''' multiply the number by '''2^50''' pebi (1,125,899,906,884,629)\n '''Ei''' multiply the number by '''2^60''' exbi (1,152,921,504,606,846,976)\n '''Zi''' multiply the number by '''2^70''' zebi (1,180,591,620,717,411,303,424)\n '''Yi''' multiply the number by '''2^80''' yobi (1,208,925,819,614,629,174,706,176)\n '''Xi''' multiply the number by '''2^90''' xebi (1,237,940,039,285,380,274,899,124,224)\n '''Wi''' multiply the number by '''2^100''' webi (1,267,650,600,228,229,401,496,703,205,376)\n '''Vi''' multiply the number by '''2^110''' vebi (1,298,074,214,633,706,907,132,624,082,305,024)\n '''Ui''' multiply the number by '''2^120''' uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)\n\n\n;For instance, with this pseudo-code:\n /* 1st arg: the number to be transformed.*/\n /* 2nd arg: # digits past the dec. point.*/\n /* 3rd arg: the type of suffix to use. */\n /* 2 indicates \"binary\" suffix.*/\n /* 10 indicates decimal suffix.*/\n a = '456,789,100,000,000' /* \"A\" has eight trailing zeros. */\n say ' aa=' suffize(a) /* Display a suffized number to terminal.*/\n /* The \"1\" below shows one decimal ****/\n /* digit past the decimal point. */\n n = suffize(a, 1) /* SUFFIZE is the function name. */\n n = suffize(a, 1, 10) /* (identical to the above statement.) */\n say ' n=' n /* Display value of N to terminal. */\n /* Note the rounding that occurs. */\n f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */\n say ' f=' f /* Display value of F to terminal. */\n /* Display value in \"binary\" metric. */\n bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */\n say 'bin=' bin /* Display value of BIN to terminal. */\n win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */\n say 'win=' win /* Display value of WIN to terminal. */\n xvi = ' +16777216 ' /* this used to be a big computer *** */\n big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */\n say 'big=' big /* Display value of BIG to terminal. */\nwould display:\n aa= 456.7891T\n n= 456.8T\n f= 415.4Ti\n bin= 415.44727Ti\n win= 415Ti\n big= 16Mi\n\n\n;Use these test cases:\n 87,654,321\n -998,877,665,544,332,211,000 3\n +112,233 0\n 16,777,216 1\n 456,789,100,000,000 2\n 456,789,100,000,000 2 10\n 456,789,100,000,000 5 2\n 456,789,100,000.000e+00 0 10\n +16777216 , 2\n 1.2e101\n (your primary disk free space) 1 <####### optional\n\n\nUse whatever parameterizing your computer language supports, and it's permitted to create as many\nseparate functions as are needed (if needed) if function arguments aren't allowed to\nbe omitted or varied.\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"strconv\"\n \"strings\"\n)\n\nvar suffixes = \" KMGTPEZYXWVU\"\nvar ggl = googol()\n\nfunc googol() *big.Float {\n g1 := new(big.Float).SetPrec(500)\n g1.SetInt64(10000000000)\n g := new(big.Float)\n g.Set(g1)\n for i := 2; i <= 10; i++ {\n g.Mul(g, g1)\n }\n return g\n}\n\nfunc suffize(arg string) {\n fields := strings.Fields(arg)\n a := fields[0]\n if a == \"\" {\n a = \"0\"\n }\n var places, base int\n var frac, radix string\n switch len(fields) {\n case 1:\n places = -1\n base = 10\n case 2:\n places, _ = strconv.Atoi(fields[1])\n base = 10\n frac = strconv.Itoa(places)\n case 3:\n if fields[1] == \",\" {\n places = 0\n frac = \",\"\n } else {\n places, _ = strconv.Atoi(fields[1])\n frac = strconv.Itoa(places)\n }\n base, _ = strconv.Atoi(fields[2])\n if base != 2 && base != 10 {\n base = 10\n }\n radix = strconv.Itoa(base)\n }\n a = strings.Replace(a, \",\", \"\", -1) // get rid of any commas\n sign := \"\"\n if a[0] == '+' || a[0] == '-' {\n sign = string(a[0])\n a = a[1:] // remove any sign after storing it\n }\n b := new(big.Float).SetPrec(500)\n d := new(big.Float).SetPrec(500)\n b.SetString(a)\n g := false\n if b.Cmp(ggl) >= 0 {\n g = true\n }\n if !g && base == 2 {\n d.SetUint64(1024)\n } else if !g && base == 10 {\n d.SetUint64(1000)\n } else {\n d.Set(ggl)\n }\n c := 0\n for b.Cmp(d) >= 0 && c < 12 { // allow b >= 1K if c would otherwise exceed 12\n b.Quo(b, d)\n c++\n }\n var suffix string\n if !g {\n suffix = string(suffixes[c])\n } else {\n suffix = \"googol\"\n }\n if base == 2 {\n suffix += \"i\"\n }\n fmt.Println(\" input number =\", fields[0])\n fmt.Println(\" fraction digs =\", frac)\n fmt.Println(\"specified radix =\", radix)\n fmt.Print(\" new number = \")\n if places >= 0 {\n fmt.Printf(\"%s%.*f%s\\n\", sign, places, b, suffix)\n } else {\n fmt.Printf(\"%s%s%s\\n\", sign, b.Text('g', 50), suffix)\n }\n fmt.Println()\n}\n\nfunc main() {\n tests := []string{\n \"87,654,321\",\n \"-998,877,665,544,332,211,000 3\",\n \"+112,233 0\",\n \"16,777,216 1\",\n \"456,789,100,000,000\",\n \"456,789,100,000,000 2 10\",\n \"456,789,100,000,000 5 2\",\n \"456,789,100,000.000e+00 0 10\",\n \"+16777216 , 2\",\n \"1.2e101\",\n \"446,835,273,728 1\",\n \"1e36\",\n \"1e39\", // there isn't a big enough suffix for this one but it's less than googol\n }\n for _, test := range tests {\n suffize(test)\n }\n}"} {"title": "Sum and product puzzle", "language": "Go", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype pair struct{ x, y int }\n\nfunc main() {\n\t//const max = 100\n\t// Use 1685 (the highest with a unique answer) instead\n\t// of 100 just to make it work a little harder :).\n\tconst max = 1685\n\tvar all []pair\n\tfor a := 2; a < max; a++ {\n\t\tfor b := a + 1; b < max-a; b++ {\n\t\t\tall = append(all, pair{a, b})\n\t\t}\n\t}\n\tfmt.Println(\"There are\", len(all), \"pairs where a+b <\", max, \"(and a= 1; k-- {\n\t\tnum += pow * k\n\t\tswitch op(c % 3) {\n\t\tcase Add:\n\t\t\tsum += num\n\t\t\tnum, pow = 0, 1\n\t\tcase Sub:\n\t\t\tsum -= num\n\t\t\tnum, pow = 0, 1\n\t\tcase Join:\n\t\t\tpow *= 10\n\t\t}\n\t\tc /= 3\n\t}\n\treturn sum\n}\n\nfunc (c code) String() string {\n\tbuf := make([]byte, 0, 18)\n\ta, b := code(pow3_9), code(pow3_8)\n\tfor k := 1; k <= 9; k++ {\n\t\tswitch op((c % a) / b) {\n\t\tcase Add:\n\t\t\tif k > 1 {\n\t\t\t\tbuf = append(buf, '+')\n\t\t\t}\n\t\tcase Sub:\n\t\t\tbuf = append(buf, '-')\n\t\t}\n\t\tbuf = append(buf, '0'+byte(k))\n\t\ta, b = b, b/3\n\t}\n\treturn string(buf)\n}\n\ntype sumCode struct {\n\tsum int\n\tcode code\n}\ntype sumCodes []sumCode\n\ntype sumCount struct {\n\tsum int\n\tcount int\n}\ntype sumCounts []sumCount\n\n// For sorting (could also use sort.Slice with just Less).\nfunc (p sumCodes) Len() int { return len(p) }\nfunc (p sumCodes) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p sumCodes) Less(i, j int) bool { return p[i].sum < p[j].sum }\nfunc (p sumCounts) Len() int { return len(p) }\nfunc (p sumCounts) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p sumCounts) Less(i, j int) bool { return p[i].count > p[j].count }\n\n// For printing.\nfunc (sc sumCode) String() string {\n\treturn fmt.Sprintf(\"% 10d = %v\", sc.sum, sc.code)\n}\nfunc (sc sumCount) String() string {\n\treturn fmt.Sprintf(\"% 10d has %d solutions\", sc.sum, sc.count)\n}\n\nfunc main() {\n\t// Evaluate all expressions.\n\texpressions := make(sumCodes, 0, maxExprs/2)\n\tcounts := make(sumCounts, 0, 1715)\n\tfor c := code(0); c < maxExprs; c++ {\n\t\t// All negative sums are exactly like their positive\n\t\t// counterpart with all +/- switched, we don't need to\n\t\t// keep track of them.\n\t\tsum := c.evaluate()\n\t\tif sum >= 0 {\n\t\t\texpressions = append(expressions, sumCode{sum, c})\n\t\t}\n\t}\n\tsort.Sort(expressions)\n\n\t// Count all unique sums\n\tsc := sumCount{expressions[0].sum, 1}\n\tfor _, e := range expressions[1:] {\n\t\tif e.sum == sc.sum {\n\t\t\tsc.count++\n\t\t} else {\n\t\t\tcounts = append(counts, sc)\n\t\t\tsc = sumCount{e.sum, 1}\n\t\t}\n\t}\n\tcounts = append(counts, sc)\n\tsort.Sort(counts)\n\n\t// Extract required results\n\n\tfmt.Println(\"All solutions that sum to 100:\")\n\ti := sort.Search(len(expressions), func(i int) bool {\n\t\treturn expressions[i].sum >= 100\n\t})\n\tfor _, e := range expressions[i:] {\n\t\tif e.sum != 100 {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(e)\n\t}\n\n\tfmt.Println(\"\\nThe positive sum with maximum number of solutions:\")\n\tfmt.Println(counts[0])\n\n\tfmt.Println(\"\\nThe lowest positive number that can't be expressed:\")\n\ts := 1\n\tfor _, e := range expressions {\n\t\tif e.sum == s {\n\t\t\ts++\n\t\t} else if e.sum > s {\n\t\t\tfmt.Printf(\"% 10d\\n\", s)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"\\nThe ten highest numbers that can be expressed:\")\n\tfor _, e := range expressions[len(expressions)-10:] {\n\t\tfmt.Println(e)\n\t}\n}"} {"title": "Summarize and say sequence", "language": "Go", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strconv\"\n)\n\nfunc main() {\n var maxLen int\n var seqMaxLen [][]string\n for n := 1; n < 1e6; n++ {\n switch s := seq(n); {\n case len(s) == maxLen:\n seqMaxLen = append(seqMaxLen, s)\n case len(s) > maxLen:\n maxLen = len(s)\n seqMaxLen = [][]string{s}\n }\n }\n fmt.Println(\"Max sequence length:\", maxLen)\n fmt.Println(\"Sequences:\", len(seqMaxLen))\n for _, seq := range seqMaxLen {\n fmt.Println(\"Sequence:\")\n for _, t := range seq {\n fmt.Println(t)\n }\n }\n}\n\nfunc seq(n int) []string {\n s := strconv.Itoa(n)\n ss := []string{s}\n\n for {\n dSeq := sortD(s)\n d := dSeq[0]\n nd := 1\n s = \"\"\n for i := 1; ; i++ {\n if i == len(dSeq) {\n s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n break\n }\n if dSeq[i] == d {\n nd++\n } else {\n s = fmt.Sprintf(\"%s%d%c\", s, nd, d)\n d = dSeq[i]\n nd = 1\n }\n }\n for _, s0 := range ss {\n if s == s0 {\n return ss\n }\n }\n ss = append(ss, s)\n }\n panic(\"unreachable\")\n}\n\nfunc sortD(s string) []rune {\n r := make([]rune, len(s))\n for i, d := range s {\n j := 0\n for ; j < i; j++ {\n if d > r[j] {\n copy(r[j+1:], r[j:i])\n break\n }\n }\n r[j] = d\n }\n return r\n}"} {"title": "Super-d numbers", "language": "Go", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"strings\"\n \"time\"\n)\n\nfunc main() {\n start := time.Now()\n rd := []string{\"22\", \"333\", \"4444\", \"55555\", \"666666\", \"7777777\", \"88888888\", \"999999999\"}\n one := big.NewInt(1)\n nine := big.NewInt(9)\n for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) {\n fmt.Printf(\"First 10 super-%d numbers:\\n\", i)\n ii := i.Uint64()\n k := new(big.Int)\n count := 0\n inner:\n for j := big.NewInt(3); ; j.Add(j, one) {\n k.Exp(j, i, nil)\n k.Mul(i, k)\n ix := strings.Index(k.String(), rd[ii-2])\n if ix >= 0 {\n count++\n fmt.Printf(\"%d \", j)\n if count == 10 {\n fmt.Printf(\"\\nfound in %d ms\\n\\n\", time.Since(start).Milliseconds())\n break inner\n }\n }\n }\n }\n}"} {"title": "Superpermutation minimisation", "language": "Go from C", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* The Minimal Superpermutation Problem. by Nathaniel Johnston.\n* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* Superpermutations - Numberphile. A video\n* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.\n* New Superpermutations Discovered! Standupmaths & Numberphile.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nconst max = 12\n\nvar (\n super []byte\n pos int\n cnt [max]int\n)\n\n// 1! + 2! + ... + n!\nfunc factSum(n int) int {\n s := 0\n for x, f := 0, 1; x < n; {\n x++\n f *= x\n s += f\n }\n return s\n}\n\nfunc r(n int) bool {\n if n == 0 {\n return false\n }\n c := super[pos-n]\n cnt[n]--\n if cnt[n] == 0 {\n cnt[n] = n\n if !r(n - 1) {\n return false\n }\n }\n super[pos] = c\n pos++\n return true\n}\n\nfunc superperm(n int) {\n pos = n\n le := factSum(n)\n super = make([]byte, le)\n for i := 0; i <= n; i++ {\n cnt[i] = i\n }\n for i := 1; i <= n; i++ {\n super[i-1] = byte(i) + '0'\n }\n\n for r(n) {\n }\n}\n\nfunc main() {\n for n := 0; n < max; n++ {\n fmt.Printf(\"superperm(%2d) \", n)\n superperm(n)\n fmt.Printf(\"len = %d\\n\", len(super))\n }\n}"} {"title": "Sylvester's sequence", "language": "Go from Wren", "task": "{{Wikipedia|Sylvester's sequence}}\n\n\nIn number theory, '''Sylvester's sequence''' is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.\n\nIts values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to '''1''' more rapidly than any other series of unit fractions with the same number of terms. \n\nFurther, the sum of the first '''k''' terms of the infinite series of reciprocals provides the closest possible underestimate of '''1''' by any k-term Egyptian fraction.\n\n\n;Task:\n* Write a routine (function, procedure, generator, whatever) to calculate '''Sylvester's sequence'''.\n* Use that routine to show the values of the first '''10''' elements in the sequence.\n* Show the sum of the reciprocals of the first '''10''' elements on the sequence, ideally as an exact fraction.\n\n\n;Related tasks:\n* [[Egyptian fractions]]\n* [[Harmonic series]]\n\n\n;See also: \n* OEIS A000058 - Sylvester's sequence\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\nfunc main() {\n one := big.NewInt(1)\n two := big.NewInt(2)\n next := new(big.Int)\n sylvester := []*big.Int{two}\n prod := new(big.Int).Set(two)\n count := 1\n for count < 10 {\n next.Add(prod, one)\n sylvester = append(sylvester, new(big.Int).Set(next))\n count++\n prod.Mul(prod, next)\n }\n fmt.Println(\"The first 10 terms in the Sylvester sequence are:\")\n for i := 0; i < 10; i++ {\n fmt.Println(sylvester[i])\n }\n\n sumRecip := new(big.Rat)\n for _, s := range sylvester {\n sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))\n }\n fmt.Println(\"\\nThe sum of their reciprocals as a rational number is:\")\n fmt.Println(sumRecip)\n fmt.Println(\"\\nThe sum of their reciprocals as a decimal number (to 211 places) is:\")\n fmt.Println(sumRecip.FloatString(211))\n}"} {"title": "Tarjan", "language": "Go", "task": "{{wikipedia|Graph}}\n\n\n\nTarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. \n\nIt runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. \n\nTarjan's Algorithm is named for its discoverer, Robert Tarjan.\n\n\n;References:\n* The article on Wikipedia.\n\nSee also: [[Kosaraju]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n)\n\n// (same data as zkl example)\nvar g = [][]int{\n 0: {1},\n 2: {0},\n 5: {2, 6},\n 6: {5},\n 1: {2},\n 3: {1, 2, 4},\n 4: {5, 3},\n 7: {4, 7, 6},\n}\n\nfunc main() {\n tarjan(g, func(c []int) { fmt.Println(c) })\n}\n\n// the function calls the emit argument for each component identified.\n// each component is a list of nodes.\nfunc tarjan(g [][]int, emit func([]int)) {\n var indexed, stacked big.Int\n index := make([]int, len(g))\n lowlink := make([]int, len(g))\n x := 0\n var S []int\n var sc func(int) bool\n sc = func(n int) bool {\n index[n] = x\n indexed.SetBit(&indexed, n, 1)\n lowlink[n] = x\n x++\n S = append(S, n)\n stacked.SetBit(&stacked, n, 1)\n for _, nb := range g[n] {\n if indexed.Bit(nb) == 0 {\n if !sc(nb) {\n return false\n }\n if lowlink[nb] < lowlink[n] {\n lowlink[n] = lowlink[nb]\n }\n } else if stacked.Bit(nb) == 1 {\n if index[nb] < lowlink[n] {\n lowlink[n] = index[nb]\n }\n }\n }\n if lowlink[n] == index[n] {\n var c []int\n for {\n last := len(S) - 1\n w := S[last]\n S = S[:last]\n stacked.SetBit(&stacked, w, 0)\n c = append(c, w)\n if w == n {\n emit(c)\n break\n }\n }\n }\n return true\n }\n for n := range g {\n if indexed.Bit(n) == 0 && !sc(n) {\n return\n }\n }\n}"} {"title": "Tau function", "language": "Go", "task": "Given a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first '''100''' positive integers.\n\n\n;Related task\n* [[Tau number]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc countDivisors(n int) int {\n count := 0\n i := 1\n k := 2\n if n%2 == 0 {\n k = 1\n }\n for i*i <= n {\n if n%i == 0 {\n count++\n j := n / i\n if j != i {\n count++\n }\n }\n i += k\n }\n return count\n}\n\nfunc main() {\n fmt.Println(\"The tau functions for the first 100 positive integers are:\")\n for i := 1; i <= 100; i++ {\n fmt.Printf(\"%2d \", countDivisors(i))\n if i%20 == 0 {\n fmt.Println()\n }\n }\n}"} {"title": "Teacup rim text", "language": "Go", "task": "On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). \n\nIt occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: unixdict.txt. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) \n\nHaving listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. \n\nThe words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n \"sort\"\n \"strings\"\n)\n\nfunc check(err error) {\n if err != nil {\n log.Fatal(err)\n }\n}\n\nfunc readWords(fileName string) []string {\n file, err := os.Open(fileName)\n check(err)\n defer file.Close()\n var words []string\n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n word := strings.ToLower(strings.TrimSpace(scanner.Text()))\n if len(word) >= 3 {\n words = append(words, word)\n }\n }\n check(scanner.Err())\n return words\n}\n\nfunc rotate(runes []rune) {\n first := runes[0]\n copy(runes, runes[1:])\n runes[len(runes)-1] = first\n}\n\nfunc main() {\n dicts := []string{\"mit_10000.txt\", \"unixdict.txt\"} // local copies\n for _, dict := range dicts {\n fmt.Printf(\"Using %s:\\n\\n\", dict)\n words := readWords(dict)\n n := len(words)\n used := make(map[string]bool)\n outer:\n for _, word := range words {\n runes := []rune(word)\n variants := []string{word}\n for i := 0; i < len(runes)-1; i++ {\n rotate(runes)\n word2 := string(runes)\n if word == word2 || used[word2] {\n continue outer\n }\n ix := sort.SearchStrings(words, word2)\n if ix == n || words[ix] != word2 {\n continue outer\n }\n variants = append(variants, word2)\n }\n for _, variant := range variants {\n used[variant] = true\n }\n fmt.Println(variants)\n }\n fmt.Println()\n }\n}"} {"title": "Temperature conversion", "language": "Go", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"os\"\n \"strconv\"\n)\n\nfunc main() {\n if len(os.Args) != 2 {\n fmt.Println(\"Usage: k \")\n return\n }\n k, err := strconv.ParseFloat(os.Args[1], 64)\n if err != nil {\n fmt.Println(err)\n return\n }\n if k < 0 {\n fmt.Println(\"Kelvin must be >= 0.\")\n return\n }\n fmt.Printf(\"K %.2f\\n\", k)\n fmt.Printf(\"C %.2f\\n\", k-273.15)\n fmt.Printf(\"F %.2f\\n\", k*9/5-459.67)\n fmt.Printf(\"R %.2f\\n\", k*9/5)\n}"} {"title": "Terminal control/Coloured text", "language": "Go", "task": "Display a word in various colours on the terminal. \n\nThe system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.\n\n\nOptionally demonstrate:\n* How the system should determine if the terminal supports colour\n* Setting of the background colour\n* How to cause blinking or flashing (if supported by the terminal)\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"os/exec\"\n)\n\nfunc main() {\n // set background color to blue, log error message if impossible.\n if err := tput(\"setb\", blue); err != nil {\n log.Fatal(\"no color capability\")\n }\n // clearing the screen will fill screen with background color\n // on most terminals.\n tput(\"clear\")\n\n tput(\"blink\") // set blink attribute\n tput(\"setb\", red) // new background color\n fmt.Println(\" Blinking Red \")\n tput(\"sgr0\") // clear blink (and all other attributes)\n}\n\nconst (\n blue = \"1\"\n green = \"2\"\n red = \"4\"\n)\n\nfunc tput(args ...string) error {\n cmd := exec.Command(\"tput\", args...)\n cmd.Stdout = os.Stdout\n return cmd.Run()\n}"} {"title": "Test integerness", "language": "Go", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math/big\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\n// Go provides an integerness test only for the big.Rat and big.Float types\n// in the standard library.\n\n// The fundamental piece of code needed for built-in floating point types\n// is a test on the float64 type:\n\nfunc Float64IsInt(f float64) bool {\n\t_, frac := math.Modf(f)\n\treturn frac == 0\n}\n\n// Other built-in or stanadard library numeric types are either always\n// integer or can be easily tested using Float64IsInt.\n\nfunc Float32IsInt(f float32) bool {\n\treturn Float64IsInt(float64(f))\n}\n\nfunc Complex128IsInt(c complex128) bool {\n\treturn imag(c) == 0 && Float64IsInt(real(c))\n}\n\nfunc Complex64IsInt(c complex64) bool {\n\treturn imag(c) == 0 && Float64IsInt(float64(real(c)))\n}\n\n// Usually just the above statically typed functions would be all that is used,\n// but if it is desired to have a single function that can test any arbitrary\n// type, including the standard math/big types, user defined types based on\n// an integer, float, or complex builtin types, or user defined types that\n// have an IsInt() method, then reflection can be used.\n\ntype hasIsInt interface {\n\tIsInt() bool\n}\n\nvar bigIntT = reflect.TypeOf((*big.Int)(nil))\n\nfunc IsInt(i interface{}) bool {\n\tif ci, ok := i.(hasIsInt); ok {\n\t\t// Handles things like *big.Rat\n\t\treturn ci.IsInt()\n\t}\n\tswitch v := reflect.ValueOf(i); v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t// Built-in types and any custom type based on them\n\t\treturn true\n\tcase reflect.Float32, reflect.Float64:\n\t\t// Built-in floats and anything based on them\n\t\treturn Float64IsInt(v.Float())\n\tcase reflect.Complex64, reflect.Complex128:\n\t\t// Built-in complexes and anything based on them\n\t\treturn Complex128IsInt(v.Complex())\n\tcase reflect.String:\n\t\t// Could also do strconv.ParseFloat then FloatIsInt but\n\t\t// big.Rat handles everything ParseFloat can plus more.\n\t\t// Note, there is no strconv.ParseComplex.\n\t\tif r, ok := new(big.Rat).SetString(v.String()); ok {\n\t\t\treturn r.IsInt()\n\t\t}\n\tcase reflect.Ptr:\n\t\t// Special case for math/big.Int\n\t\tif v.Type() == bigIntT {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// The rest is just demonstration and display\n\ntype intbased int16\ntype complexbased complex64\ntype customIntegerType struct {\n\t// Anything that stores or represents a sub-set\n\t// of integer values in any way desired.\n}\n\nfunc (customIntegerType) IsInt() bool { return true }\nfunc (customIntegerType) String() string { return \"<\u2026>\" }\n\nfunc main() {\n\thdr := fmt.Sprintf(\"%27s %-6s %s\\n\", \"Input\", \"IsInt\", \"Type\")\n\tshow2 := func(t bool, i interface{}, args ...interface{}) {\n\t\tistr := fmt.Sprint(i)\n\t\tfmt.Printf(\"%27s %-6t %T \", istr, t, i)\n\t\tfmt.Println(args...)\n\t}\n\tshow := func(i interface{}, args ...interface{}) {\n\t\tshow2(IsInt(i), i, args...)\n\t}\n\n\tfmt.Print(\"Using Float64IsInt with float64:\\n\", hdr)\n\tneg1 := -1.\n\tfor _, f := range []float64{\n\t\t0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,\n\t\tmath.Pi,\n\t\tmath.MinInt64, math.MaxUint64,\n\t\tmath.SmallestNonzeroFloat64, math.MaxFloat64,\n\t\tmath.NaN(), math.Inf(1), math.Inf(-1),\n\t} {\n\t\tshow2(Float64IsInt(f), f)\n\t}\n\n\tfmt.Print(\"\\nUsing Complex128IsInt with complex128:\\n\", hdr)\n\tfor _, c := range []complex128{\n\t\t3, 1i, 0i, 3.4,\n\t} {\n\t\tshow2(Complex128IsInt(c), c)\n\t}\n\n\tfmt.Println(\"\\nUsing reflection:\")\n\tfmt.Print(hdr)\n\tshow(\"hello\")\n\tshow(math.MaxFloat64)\n\tshow(\"9e100\")\n\tf := new(big.Float)\n\tshow(f)\n\tf.SetString(\"1e-3000\")\n\tshow(f)\n\tshow(\"(4+0i)\", \"(complex strings not parsed)\")\n\tshow(4 + 0i)\n\tshow(rune('\u00a7'), \"or rune\")\n\tshow(byte('A'), \"or byte\")\n\tvar t1 intbased = 5200\n\tvar t2a, t2b complexbased = 5 + 0i, 5 + 1i\n\tshow(t1)\n\tshow(t2a)\n\tshow(t2b)\n\tx := uintptr(unsafe.Pointer(&t2b))\n\tshow(x)\n\tshow(math.MinInt32)\n\tshow(uint64(math.MaxUint64))\n\tb, _ := new(big.Int).SetString(strings.Repeat(\"9\", 25), 0)\n\tshow(b)\n\tr := new(big.Rat)\n\tshow(r)\n\tr.SetString(\"2/3\")\n\tshow(r)\n\tshow(r.SetFrac(b, new(big.Int).SetInt64(9)))\n\tshow(\"12345/5\")\n\tshow(new(customIntegerType))\n}"} {"title": "Textonyms", "language": "Go", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \n[[Textonyms/wordlist]] or \nunixdict.txt.\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"textonyms: \")\n\n\twordlist := flag.String(\"wordlist\", \"wordlist\", \"file containing the list of words to check\")\n\tflag.Parse()\n\tif flag.NArg() != 0 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tt := NewTextonym(phoneMap)\n\t_, err := ReadFromFile(t, *wordlist)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.Report(os.Stdout, *wordlist)\n}\n\n// phoneMap is the digit to letter mapping of a typical phone.\nvar phoneMap = map[byte][]rune{\n\t'2': []rune(\"ABC\"),\n\t'3': []rune(\"DEF\"),\n\t'4': []rune(\"GHI\"),\n\t'5': []rune(\"JKL\"),\n\t'6': []rune(\"MNO\"),\n\t'7': []rune(\"PQRS\"),\n\t'8': []rune(\"TUV\"),\n\t'9': []rune(\"WXYZ\"),\n}\n\n// ReadFromFile is a generic convience function that allows the use of a\n// filename with an io.ReaderFrom and handles errors related to open and\n// closing the file.\nfunc ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := r.ReadFrom(f)\n\tif cerr := f.Close(); err == nil && cerr != nil {\n\t\terr = cerr\n\t}\n\treturn n, err\n}\n\ntype Textonym struct {\n\tnumberMap map[string][]string // map numeric string into words\n\tletterMap map[rune]byte // map letter to digit\n\tcount int // total number of words in numberMap\n\ttextonyms int // number of numeric strings with >1 words\n}\n\nfunc NewTextonym(dm map[byte][]rune) *Textonym {\n\tlm := make(map[rune]byte, 26)\n\tfor d, ll := range dm {\n\t\tfor _, l := range ll {\n\t\t\tlm[l] = d\n\t\t}\n\t}\n\treturn &Textonym{letterMap: lm}\n}\n\nfunc (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {\n\tt.numberMap = make(map[string][]string)\n\tbuf := make([]byte, 0, 32)\n\tsc := bufio.NewScanner(r)\n\tsc.Split(bufio.ScanWords)\nscan:\n\tfor sc.Scan() {\n\t\tbuf = buf[:0]\n\t\tword := sc.Text()\n\n\t\t// XXX we only bother approximating the number of bytes\n\t\t// consumed. This isn't used in the calling code and was\n\t\t// only included to match the io.ReaderFrom interface.\n\t\tn += int64(len(word)) + 1\n\n\t\tfor _, r := range word {\n\t\t\td, ok := t.letterMap[unicode.ToUpper(r)]\n\t\t\tif !ok {\n\t\t\t\t//log.Printf(\"ignoring %q\\n\", word)\n\t\t\t\tcontinue scan\n\t\t\t}\n\t\t\tbuf = append(buf, d)\n\t\t}\n\t\t//log.Printf(\"scanned %q\\n\", word)\n\t\tnum := string(buf)\n\t\tt.numberMap[num] = append(t.numberMap[num], word)\n\t\tt.count++\n\t\tif len(t.numberMap[num]) == 2 {\n\t\t\tt.textonyms++\n\t\t}\n\t\t//log.Printf(\"%q \u2192 %v\\t\u2192 %v\\n\", word, num, t.numberMap[num])\n\t}\n\treturn n, sc.Err()\n}\n\nfunc (t *Textonym) Most() (most int, subset map[string][]string) {\n\tfor k, v := range t.numberMap {\n\t\tswitch {\n\t\tcase len(v) > most:\n\t\t\tsubset = make(map[string][]string)\n\t\t\tmost = len(v)\n\t\t\tfallthrough\n\t\tcase len(v) == most:\n\t\t\tsubset[k] = v\n\t\t}\n\t}\n\treturn most, subset\n}\n\nfunc (t *Textonym) Report(w io.Writer, name string) {\n\t// Could be fancy and use text/template package but fmt is sufficient\n\tfmt.Fprintf(w, `\nThere are %v words in %q which can be represented by the digit key mapping.\nThey require %v digit combinations to represent them.\n%v digit combinations represent Textonyms.\n`,\n\t\tt.count, name, len(t.numberMap), t.textonyms)\n\n\tn, sub := t.Most()\n\tfmt.Fprintln(w, \"\\nThe numbers mapping to the most words map to\",\n\t\tn, \"words each:\")\n\tfor k, v := range sub {\n\t\tfmt.Fprintln(w, \"\\t\", k, \"maps to:\", strings.Join(v, \", \"))\n\t}\n}"} {"title": "The Name Game", "language": "Go from Kotlin", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc printVerse(name string) {\n x := strings.Title(strings.ToLower(name))\n y := x[1:]\n if strings.Contains(\"AEIOU\", x[:1]) {\n y = strings.ToLower(x)\n }\n b := \"b\" + y\n f := \"f\" + y\n m := \"m\" + y\n switch x[0] {\n case 'B':\n b = y\n case 'F':\n f = y\n case 'M':\n m = y\n }\n fmt.Printf(\"%s, %s, bo-%s\\n\", x, x, b)\n fmt.Printf(\"Banana-fana fo-%s\\n\", f)\n fmt.Printf(\"Fee-fi-mo-%s\\n\", m)\n fmt.Printf(\"%s!\\n\\n\", x)\n}\n\nfunc main() {\n names := [6]string{\"gARY\", \"Earl\", \"Billy\", \"Felix\", \"Mary\", \"SHIRley\"}\n for _, name := range names {\n printVerse(name)\n }\n}"} {"title": "The Twelve Days of Christmas", "language": "Go", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tdays := []string{\"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"sixth\",\n\t\t\"seventh\", \"eighth\", \"ninth\", \"tenth\", \"eleventh\", \"twelfth\"}\n\n\tgifts := []string{\"A Partridge in a Pear Tree\", \"Two Turtle Doves and\", \"Three French Hens\",\n\t\t\"Four Calling Birds\", \"Five Gold Rings\", \"Six Geese a-Laying\",\n\t\t\"Seven Swans a-Swimming\", \"Eight Maids a-Milking\", \"Nine Ladies Dancing\",\n\t\t\"Ten Lords a-Leaping\", \"Eleven Pipers Piping\", \"Twelve Drummers Drumming\"}\n\n\tfor i := 0; i < 12; i++ {\n\t\tfmt.Printf(\"On the %s day of Christmas,\\n\", days[i])\n\t\tfmt.Println(\"My true love sent to me:\")\n\n\t\tfor j := i; j >= 0; j-- {\n\t\t\tfmt.Println(gifts[j])\n\t\t}\n\t\tfmt.Println()\n\t}\n}\n"} {"title": "Thue-Morse", "language": "Go", "task": "Create a Thue-Morse sequence.\n\n\n;See also\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: [[Fairshare between two and more]]\n\n", "solution": "// prints the first few members of the Thue-Morse sequence\n\npackage main\n\nimport (\n \"fmt\"\n \"bytes\"\n)\n\n// sets tmBuffer to the next member of the Thue-Morse sequence\n// tmBuffer must contain a valid Thue-Morse sequence member before the call\nfunc nextTMSequenceMember( tmBuffer * bytes.Buffer ) {\n // \"flip\" the bytes, adding them to the buffer\n for b, currLength, currBytes := 0, tmBuffer.Len(), tmBuffer.Bytes() ; b < currLength; b ++ {\n if currBytes[ b ] == '1' {\n tmBuffer.WriteByte( '0' )\n } else {\n tmBuffer.WriteByte( '1' )\n }\n }\n}\n \nfunc main() {\n var tmBuffer bytes.Buffer\n // initial sequence member is \"0\"\n tmBuffer.WriteByte( '0' )\n fmt.Println( tmBuffer.String() )\n for i := 2; i <= 7; i ++ {\n nextTMSequenceMember( & tmBuffer )\n fmt.Println( tmBuffer.String() )\n }\n}"} {"title": "Tonelli-Shanks algorithm", "language": "Go", "task": "{{wikipedia}}\n\n\nIn computational number theory, the Tonelli-Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:\n\n:: x2 n (mod p)\n\nwhere '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n Fp''' where Fp = {0, 1, ..., p - 1}.\n\nIt is used in cryptography techniques.\n\n\nTo apply the algorithm, we need the Legendre symbol:\n\nThe Legendre symbol '''(a | p)''' denotes the value of a(p-1)/2 (mod p).\n* '''(a | p) 1''' if '''a''' is a square (mod p)\n* '''(a | p) -1''' if '''a''' is not a square (mod p)\n* '''(a | p) 0''' if '''a''' 0 (mod p) \n\n\n;Algorithm pseudo-code:\n\nAll are taken to mean (mod p) unless stated otherwise.\n\n* Input: '''p''' an odd prime, and an integer '''n''' .\n* Step 0: Check that '''n''' is indeed a square: (n | p) must be 1 .\n* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .\n** If p 3 (mod 4) (i.e. s = 1), output the two solutions r +- n(p+1)/4 .\n* Step 2: Select a non-square '''z''' such that (z | p) -1 and set c zq .\n* Step 3: Set r n(q+1)/2, t nq, m = s .\n* Step 4: Loop the following:\n** If t 1, output '''r''' and '''p - r''' .\n** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i 1 .\n** Let b c2(m - i - 1), and set r rb, t tb2, c b2 and m = i .\n\n\n\n;Task:\nImplement the above algorithm. \n\nFind solutions (if any) for \n* n = 10 p = 13\n* n = 56 p = 101\n* n = 1030 p = 10009\n* n = 1032 p = 10009\n* n = 44402 p = 100049 \n\n;Extra credit:\n* n = 665820697 p = 1000000009 \n* n = 881398088036 p = 1000000000039 \n* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 \t\n\n\n;See also:\n* [[Modular exponentiation]]\n* [[Cipolla's algorithm]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\n// Arguments n, p as described in WP\n// If Legendre symbol != 1, ok return is false. Otherwise ok return is true,\n// R1 is WP return value R and for convenience R2 is p-R1.\nfunc ts(n, p int) (R1, R2 int, ok bool) {\n // a^e mod p\n powModP := func(a, e int) int {\n s := 1\n for ; e > 0; e-- {\n s = s * a % p\n }\n return s\n }\n // Legendre symbol, returns 1, 0, or -1 mod p -- that's 1, 0, or p-1.\n ls := func(a int) int {\n return powModP(a, (p-1)/2)\n }\n // argument validation\n if ls(n) != 1 {\n return 0, 0, false\n }\n // WP step 1, factor out powers two.\n // variables Q, S named as at WP.\n Q := p - 1\n S := 0\n for Q&1 == 0 {\n S++\n Q >>= 1\n }\n // WP step 1, direct solution\n if S == 1 {\n R1 = powModP(n, (p+1)/4)\n return R1, p - R1, true\n }\n // WP step 2, select z, assign c\n z := 2\n for ; ls(z) != p-1; z++ {\n }\n c := powModP(z, Q)\n // WP step 3, assign R, t, M\n R := powModP(n, (Q+1)/2)\n t := powModP(n, Q)\n M := S\n // WP step 4, loop\n for {\n // WP step 4.1, termination condition\n if t == 1 {\n return R, p - R, true\n }\n // WP step 4.2, find lowest i...\n i := 0\n for z := t; z != 1 && i < M-1; {\n z = z * z % p\n i++\n }\n // WP step 4.3, using a variable b, assign new values of R, t, c, M\n b := c\n for e := M - i - 1; e > 0; e-- {\n b = b * b % p\n }\n R = R * b % p\n c = b * b % p // more convenient to compute c before t\n t = t * c % p\n M = i\n }\n}\n\nfunc main() {\n fmt.Println(ts(10, 13))\n fmt.Println(ts(56, 101))\n fmt.Println(ts(1030, 10009))\n fmt.Println(ts(1032, 10009))\n fmt.Println(ts(44402, 100049))\n}"} {"title": "Top rank per group", "language": "Go", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"sort\"\n)\n\n// language-native data description\ntype Employee struct {\n Name, ID string\n Salary int\n Dept string\n}\n\ntype EmployeeList []*Employee\n\nvar data = EmployeeList{\n {\"Tyler Bennett\", \"E10297\", 32000, \"D101\"},\n {\"John Rappl\", \"E21437\", 47000, \"D050\"},\n {\"George Woltman\", \"E00127\", 53500, \"D101\"},\n {\"Adam Smith\", \"E63535\", 18000, \"D202\"},\n {\"Claire Buckman\", \"E39876\", 27800, \"D202\"},\n {\"David McClellan\", \"E04242\", 41500, \"D101\"},\n {\"Rich Holcomb\", \"E01234\", 49500, \"D202\"},\n {\"Nathan Adams\", \"E41298\", 21900, \"D050\"},\n {\"Richard Potter\", \"E43128\", 15900, \"D101\"},\n {\"David Motsinger\", \"E27002\", 19250, \"D202\"},\n {\"Tim Sampair\", \"E03033\", 27000, \"D101\"},\n {\"Kim Arlich\", \"E10001\", 57000, \"D190\"},\n {\"Timothy Grove\", \"E16398\", 29900, \"D190\"},\n // Extra data to demonstrate ties\n {\"Tie A\", \"E16399\", 29900, \"D190\"},\n {\"Tie B\", \"E16400\", 29900, \"D190\"},\n {\"No Tie\", \"E16401\", 29899, \"D190\"},\n}\n\n// We only need one type of ordering/grouping for this task so we could directly\n// implement sort.Interface on EmployeeList (or a byDeptSalary alias type) with\n// the appropriate Less method.\n//\n// Instead, we'll add a bit here that makes it easier to use arbitrary orderings.\n// This is like the \"SortKeys\" Planet sorting example in the sort package\n// documentation, see https://golang.org/pkg/sort\n\ntype By func(e1, e2 *Employee) bool\ntype employeeSorter struct {\n list EmployeeList\n by func(e1, e2 *Employee) bool\n}\n\nfunc (by By) Sort(list EmployeeList) { sort.Sort(&employeeSorter{list, by}) }\nfunc (s *employeeSorter) Len() int { return len(s.list) }\nfunc (s *employeeSorter) Swap(i, j int) { s.list[i], s.list[j] = s.list[j], s.list[i] }\nfunc (s *employeeSorter) Less(i, j int) bool { return s.by(s.list[i], s.list[j]) }\n\n// For this specific task we could just write the data to an io.Writer\n// but in general it's better to return the data in a usable form (for\n// example, perhaps other code want's to do something like compare the\n// averages of the top N by department).\n//\n// So we go through the extra effort of returning an []EmployeeList, a\n// list of employee lists, one per deparment. The lists are trimmed to\n// to the top 'n', which can be larger than n if there are ties for the\n// nth salary (callers that don't care about ties could just trim more.)\nfunc (el EmployeeList) TopSalariesByDept(n int) []EmployeeList {\n if n <= 0 || len(el) == 0 {\n return nil\n }\n deptSalary := func(e1, e2 *Employee) bool {\n if e1.Dept != e2.Dept {\n return e1.Dept < e2.Dept\n }\n if e1.Salary != e2.Salary {\n return e1.Salary > e2.Salary\n }\n // Always have some unique field as the last one in a sort list\n return e1.ID < e2.ID\n }\n\n // We could just sort the data in place for this task. But\n // perhaps messing with the order is undesirable or there is\n // other concurrent access. So we'll make a copy and sort that.\n // It's just pointers so the amount to copy is relatively small.\n sorted := make(EmployeeList, len(el))\n copy(sorted, el)\n By(deptSalary).Sort(sorted)\n\n perDept := []EmployeeList{}\n var lastDept string\n var lastSalary int\n for _, e := range sorted {\n if e.Dept != lastDept || len(perDept) == 0 {\n lastDept = e.Dept\n perDept = append(perDept, EmployeeList{e})\n } else {\n i := len(perDept) - 1\n if len(perDept[i]) >= n && e.Salary != lastSalary {\n continue\n }\n perDept[i] = append(perDept[i], e)\n lastSalary = e.Salary\n }\n }\n return perDept\n}\n\nfunc main() {\n const n = 3\n top := data.TopSalariesByDept(n)\n if len(top) == 0 {\n fmt.Println(\"Nothing to show.\")\n return\n }\n fmt.Printf(\"Top %d salaries per department\\n\", n)\n for _, list := range top {\n fmt.Println(list[0].Dept)\n for _, e := range list {\n fmt.Printf(\" %s %16s %7d\\n\", e.ID, e.Name, e.Salary)\n }\n }\n}"} {"title": "Topic variable", "language": "Go", "task": "Several programming languages offer syntax shortcuts to deal with the notion of \"current\" or \"topic\" variable.\n\nA topic variable is a special variable with a very short name which can also often be omitted.\n\nDemonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.\n\nFor instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 to it and then computing its square and square root.\n\n", "solution": "package main\n\nimport (\n \"math\"\n \"os\"\n \"strconv\"\n \"text/template\"\n)\n\nfunc sqr(x string) string {\n f, err := strconv.ParseFloat(x, 64)\n if err != nil {\n return \"NA\"\n }\n return strconv.FormatFloat(f*f, 'f', -1, 64)\n}\n\nfunc sqrt(x string) string {\n f, err := strconv.ParseFloat(x, 64)\n if err != nil {\n return \"NA\"\n }\n return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64)\n}\n\nfunc main() {\n f := template.FuncMap{\"sqr\": sqr, \"sqrt\": sqrt}\n t := template.Must(template.New(\"\").Funcs(f).Parse(`. = {{.}}\nsquare: {{sqr .}}\nsquare root: {{sqrt .}}\n`))\n t.Execute(os.Stdout, \"3\")\n}"} {"title": "Topswops", "language": "Go", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "// Adapted from http://www-cs-faculty.stanford.edu/~uno/programs/topswops.w\n// at Donald Knuth's web site. Algorithm credited there to Pepperdine\n// and referenced to Mathematical Gazette 73 (1989), 131-133.\npackage main\n\nimport \"fmt\"\n\nconst ( // array sizes\n maxn = 10 // max number of cards\n maxl = 50 // upper bound for number of steps\n)\n\nfunc main() {\n for i := 1; i <= maxn; i++ {\n fmt.Printf(\"%d: %d\\n\", i, steps(i))\n }\n}\n\nfunc steps(n int) int {\n var a, b [maxl][maxn + 1]int\n var x [maxl]int\n a[0][0] = 1\n var m int\n for l := 0; ; {\n x[l]++\n k := int(x[l])\n if k >= n {\n if l <= 0 {\n break\n }\n l--\n continue\n }\n if a[l][k] == 0 {\n if b[l][k+1] != 0 {\n continue\n }\n } else if a[l][k] != k+1 {\n continue\n }\n a[l+1] = a[l]\n for j := 1; j <= k; j++ {\n a[l+1][j] = a[l][k-j]\n }\n b[l+1] = b[l]\n a[l+1][0] = k + 1\n b[l+1][k+1] = 1\n if l > m-1 {\n m = l + 1\n }\n l++\n x[l] = 0\n }\n return m\n}"} {"title": "Total circles area", "language": "Go from Raku", "task": "Example circles\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. \n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):\n\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n\nThe result is 21.56503660... .\n\n\n;Related task:\n* [[Circles of given radius through two points]].\n\n\n;See also:\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/\n* http://stackoverflow.com/a/1667789/10562\n\n", "solution": "package main\n\nimport (\n \"flag\"\n \"fmt\"\n \"math\"\n \"runtime\"\n \"sort\"\n)\n\n// Note, the standard \"image\" package has Point and Rectangle but we\n// can't use them here since they're defined using int rather than\n// float64.\n\ntype Circle struct{ X, Y, R, rsq float64 }\n\nfunc NewCircle(x, y, r float64) Circle {\n // We pre-calculate r\u00b2 as an optimization\n return Circle{x, y, r, r * r}\n}\n\nfunc (c Circle) ContainsPt(x, y float64) bool {\n return distSq(x, y, c.X, c.Y) <= c.rsq\n}\n\nfunc (c Circle) ContainsC(c2 Circle) bool {\n return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R)\n}\n\nfunc (c Circle) ContainsR(r Rect) (full, corner bool) {\n nw := c.ContainsPt(r.NW())\n ne := c.ContainsPt(r.NE())\n sw := c.ContainsPt(r.SW())\n se := c.ContainsPt(r.SE())\n return nw && ne && sw && se, nw || ne || sw || se\n}\n\nfunc (c Circle) North() (float64, float64) { return c.X, c.Y + c.R }\nfunc (c Circle) South() (float64, float64) { return c.X, c.Y - c.R }\nfunc (c Circle) West() (float64, float64) { return c.X - c.R, c.Y }\nfunc (c Circle) East() (float64, float64) { return c.X + c.R, c.Y }\n\ntype Rect struct{ X1, Y1, X2, Y2 float64 }\n\nfunc (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) }\nfunc (r Rect) NW() (float64, float64) { return r.X1, r.Y2 }\nfunc (r Rect) NE() (float64, float64) { return r.X2, r.Y2 }\nfunc (r Rect) SW() (float64, float64) { return r.X1, r.Y1 }\nfunc (r Rect) SE() (float64, float64) { return r.X2, r.Y1 }\n\nfunc (r Rect) Centre() (float64, float64) {\n return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0\n}\n\nfunc (r Rect) ContainsPt(x, y float64) bool {\n return r.X1 <= x && x < r.X2 &&\n r.Y1 <= y && y < r.Y2\n}\n\nfunc (r Rect) ContainsPC(c Circle) bool { // only N,W,E,S points of circle\n return r.ContainsPt(c.North()) ||\n r.ContainsPt(c.South()) ||\n r.ContainsPt(c.West()) ||\n r.ContainsPt(c.East())\n}\n\nfunc (r Rect) MinSide() float64 {\n return math.Min(r.X2-r.X1, r.Y2-r.Y1)\n}\n\nfunc distSq(x1, y1, x2, y2 float64) float64 {\n \u0394x, \u0394y := x2-x1, y2-y1\n return (\u0394x * \u0394x) + (\u0394y * \u0394y)\n}\n\ntype CircleSet []Circle\n\n// sort.Interface for sorting by radius big to small:\nfunc (s CircleSet) Len() int { return len(s) }\nfunc (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R }\n\nfunc (sp *CircleSet) RemoveContainedC() {\n s := *sp\n sort.Sort(s)\n for i := 0; i < len(s); i++ {\n for j := i + 1; j < len(s); {\n if s[i].ContainsC(s[j]) {\n s[j], s[len(s)-1] = s[len(s)-1], s[j]\n s = s[:len(s)-1]\n } else {\n j++\n }\n }\n }\n *sp = s\n}\n\nfunc (s CircleSet) Bounds() Rect {\n x1 := s[0].X - s[0].R\n x2 := s[0].X + s[0].R\n y1 := s[0].Y - s[0].R\n y2 := s[0].Y + s[0].R\n for _, c := range s[1:] {\n x1 = math.Min(x1, c.X-c.R)\n x2 = math.Max(x2, c.X+c.R)\n y1 = math.Min(y1, c.Y-c.R)\n y2 = math.Max(y2, c.Y+c.R)\n }\n return Rect{x1, y1, x2, y2}\n}\n\nvar nWorkers = 4\n\nfunc (s CircleSet) UnionArea(\u03b5 float64) (min, max float64) {\n sort.Sort(s)\n stop := make(chan bool)\n inside := make(chan Rect)\n outside := make(chan Rect)\n unknown := make(chan Rect, 5e7) // XXX\n\n for i := 0; i < nWorkers; i++ {\n go s.worker(stop, unknown, inside, outside)\n }\n r := s.Bounds()\n max = r.Area()\n unknown <- r\n for max-min > \u03b5 {\n select {\n case r = <-inside:\n min += r.Area()\n case r = <-outside:\n max -= r.Area()\n }\n }\n close(stop)\n return min, max\n}\n\nfunc (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) {\n for {\n select {\n case <-stop:\n return\n case r := <-unk:\n inside, outside := s.CategorizeR(r)\n switch {\n case inside:\n in <- r\n case outside:\n out <- r\n default:\n // Split\n midX, midY := r.Centre()\n unk <- Rect{r.X1, r.Y1, midX, midY}\n unk <- Rect{midX, r.Y1, r.X2, midY}\n unk <- Rect{r.X1, midY, midX, r.Y2}\n unk <- Rect{midX, midY, r.X2, r.Y2}\n }\n }\n }\n}\n\nfunc (s CircleSet) CategorizeR(r Rect) (inside, outside bool) {\n anyCorner := false\n for _, c := range s {\n full, corner := c.ContainsR(r)\n if full {\n return true, false // inside\n }\n anyCorner = anyCorner || corner\n }\n if anyCorner {\n return false, false // uncertain\n }\n for _, c := range s {\n if r.ContainsPC(c) {\n return false, false // uncertain\n }\n }\n return false, true // outside\n}\n\nfunc main() {\n flag.IntVar(&nWorkers, \"workers\", nWorkers, \"how many worker go routines to use\")\n maxproc := flag.Int(\"cpu\", runtime.NumCPU(), \"GOMAXPROCS setting\")\n flag.Parse()\n\n if *maxproc > 0 {\n runtime.GOMAXPROCS(*maxproc)\n } else {\n *maxproc = runtime.GOMAXPROCS(0)\n }\n\n circles := CircleSet{\n NewCircle(1.6417233788, 1.6121789534, 0.0848270516),\n NewCircle(-1.4944608174, 1.2077959613, 1.1039549836),\n NewCircle(0.6110294452, -0.6907087527, 0.9089162485),\n NewCircle(0.3844862411, 0.2923344616, 0.2375743054),\n NewCircle(-0.2495892950, -0.3832854473, 1.0845181219),\n NewCircle(1.7813504266, 1.6178237031, 0.8162655711),\n NewCircle(-0.1985249206, -0.8343333301, 0.0538864941),\n NewCircle(-1.7011985145, -0.1263820964, 0.4776976918),\n NewCircle(-0.4319462812, 1.4104420482, 0.7886291537),\n NewCircle(0.2178372997, -0.9499557344, 0.0357871187),\n NewCircle(-0.6294854565, -1.3078893852, 0.7653357688),\n NewCircle(1.7952608455, 0.6281269104, 0.2727652452),\n NewCircle(1.4168575317, 1.0683357171, 1.1016025378),\n NewCircle(1.4637371396, 0.9463877418, 1.1846214562),\n NewCircle(-0.5263668798, 1.7315156631, 1.4428514068),\n NewCircle(-1.2197352481, 0.9144146579, 1.0727263474),\n NewCircle(-0.1389358881, 0.1092805780, 0.7350208828),\n NewCircle(1.5293954595, 0.0030278255, 1.2472867347),\n NewCircle(-0.5258728625, 1.3782633069, 1.3495508831),\n NewCircle(-0.1403562064, 0.2437382535, 1.3804956588),\n NewCircle(0.8055826339, -0.0482092025, 0.3327165165),\n NewCircle(-0.6311979224, 0.7184578971, 0.2491045282),\n NewCircle(1.4685857879, -0.8347049536, 1.3670667538),\n NewCircle(-0.6855727502, 1.6465021616, 1.0593087096),\n NewCircle(0.0152957411, 0.0638919221, 0.9771215985),\n }\n fmt.Println(\"Starting with\", len(circles), \"circles.\")\n circles.RemoveContainedC()\n fmt.Println(\"Removing redundant ones leaves\", len(circles), \"circles.\")\n fmt.Println(\"Using\", nWorkers, \"workers with maxprocs =\", *maxproc)\n const \u03b5 = 0.0001\n min, max := circles.UnionArea(\u03b5)\n avg := (min + max) / 2.0\n rng := max - min\n fmt.Printf(\"Area = %v\u00b1%v\\n\", avg, rng)\n fmt.Printf(\"Area \u2248 %.*f\\n\", 5, avg)\n}"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Go", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n)\n\nfunc main() {\n // prompt\n fmt.Print(\"Enter 11 numbers: \")\n // accept sequence\n var s [11]float64\n for i := 0; i < 11; {\n if n, _ := fmt.Scan(&s[i]); n > 0 {\n i++\n }\n }\n // reverse sequence\n for i, item := range s[:5] {\n s[i], s[10-i] = s[10-i], item\n }\n // iterate\n for _, item := range s {\n if result, overflow := f(item); overflow {\n // send alerts to stderr\n log.Printf(\"f(%g) overflow\", item)\n } else {\n // send normal results to stdout\n fmt.Printf(\"f(%g) = %g\\n\", item, result)\n }\n }\n}\n\nfunc f(x float64) (float64, bool) {\n result := math.Sqrt(math.Abs(x)) + 5*x*x*x\n return result, result > 400\n}"} {"title": "Tree datastructures", "language": "Go", "task": "The following shows a tree of data with nesting denoted by visual levels of indentation:\nRosettaCode\n rocks\n code\n comparison\n wiki\n mocks\n trolling\n\nA common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this '''the nest form'''.\n# E.g. if child nodes are surrounded by brackets\n# and separated by commas then:\nRosettaCode(rocks(code, ...), ...)\n# But only an _example_\n\nAnother datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this '''the indent form'''.\n0 RosettaCode\n1 rocks\n2 code\n...\n\n;Task:\n# Create/use a nest datastructure format and textual representation for arbitrary trees.\n# Create/use an indent datastructure format and textual representation for arbitrary trees.\n# Create methods/classes/proceedures/routines etc to:\n## Change from a nest tree datastructure to an indent one.\n## Change from an indent tree datastructure to a nest one\n# Use the above to encode the example at the start into the nest format, and show it.\n# transform the initial nest format to indent format and show it.\n# transform the indent format to final nest format and show it.\n# Compare initial and final nest formats which should be the same.\n\n;Note:\n* It's all about showing aspects of the contrasting datastructures as they hold the tree.\n* Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier.\n\n\nShow all output on this page.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"io\"\n \"os\"\n \"strings\"\n)\n\ntype nNode struct {\n name string\n children []nNode\n}\n\ntype iNode struct {\n level int\n name string\n}\n\nfunc printNest(n nNode, level int, w io.Writer) {\n if level == 0 {\n fmt.Fprintln(w, \"\\n==Nest form==\\n\")\n }\n fmt.Fprintf(w, \"%s%s\\n\", strings.Repeat(\" \", level), n.name)\n for _, c := range n.children {\n fmt.Fprintf(w, \"%s\", strings.Repeat(\" \", level+1))\n printNest(c, level+1, w)\n }\n}\n\nfunc toNest(iNodes []iNode, start, level int, n *nNode) {\n if level == 0 {\n n.name = iNodes[0].name\n }\n for i := start + 1; i < len(iNodes); i++ {\n if iNodes[i].level == level+1 {\n c := nNode{iNodes[i].name, nil}\n toNest(iNodes, i, level+1, &c)\n n.children = append(n.children, c)\n } else if iNodes[i].level <= level {\n return\n }\n }\n}\n\nfunc printIndent(iNodes []iNode, w io.Writer) {\n fmt.Fprintln(w, \"\\n==Indent form==\\n\")\n for _, n := range iNodes {\n fmt.Fprintf(w, \"%d %s\\n\", n.level, n.name)\n }\n}\n\nfunc toIndent(n nNode, level int, iNodes *[]iNode) {\n *iNodes = append(*iNodes, iNode{level, n.name})\n for _, c := range n.children {\n toIndent(c, level+1, iNodes)\n }\n}\n\nfunc main() {\n n1 := nNode{\"RosettaCode\", nil}\n n2 := nNode{\"rocks\", []nNode{{\"code\", nil}, {\"comparison\", nil}, {\"wiki\", nil}}}\n n3 := nNode{\"mocks\", []nNode{{\"trolling\", nil}}}\n n1.children = append(n1.children, n2, n3)\n\n var sb strings.Builder\n printNest(n1, 0, &sb)\n s1 := sb.String()\n fmt.Print(s1)\n\n var iNodes []iNode\n toIndent(n1, 0, &iNodes)\n printIndent(iNodes, os.Stdout)\n\n var n nNode\n toNest(iNodes, 0, 0, &n)\n sb.Reset()\n printNest(n, 0, &sb)\n s2 := sb.String()\n fmt.Print(s2)\n\n fmt.Println(\"\\nRound trip test satisfied? \", s1 == s2)\n}"} {"title": "Tree from nesting levels", "language": "Go from Python", "task": "Given a flat list of integers greater than zero, representing object nesting\nlevels, e.g. [1, 2, 4],\ngenerate a tree formed from nested lists of those nesting level integers where:\n* Every int appears, in order, at its depth of nesting.\n* If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item\n\n\nThe generated tree data structure should ideally be in a languages nested list format that can\nbe used for further calculations rather than something just calculated for printing.\n\n\nAn input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]]\nwhere 1 is at depth1, 2 is two deep and 4 is nested 4 deep.\n\n[1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. \nAll the nesting integers are in the same order but at the correct nesting\nlevels.\n\nSimilarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1]\n\n;Task:\nGenerate and show here the results for the following inputs:\n:* []\n:* [1, 2, 4]\n:* [3, 1, 3, 1]\n:* [1, 2, 3, 1]\n:* [3, 2, 1, 3]\n:* [3, 3, 3, 1, 1, 3, 3, 3]\n", "solution": "package main\n\nimport \"fmt\"\n\ntype any = interface{}\n\nfunc toTree(list []int, index, depth int) (int, []any) {\n var soFar []any\n for index < len(list) {\n t := list[index]\n if t == depth {\n soFar = append(soFar, t)\n } else if t > depth {\n var deeper []any\n index, deeper = toTree(list, index, depth+1)\n soFar = append(soFar, deeper)\n } else {\n index = index - 1\n break\n }\n index = index + 1\n }\n if depth > 1 {\n return index, soFar\n }\n return -1, soFar\n}\n\nfunc main() {\n tests := [][]int{\n {},\n {1, 2, 4},\n {3, 1, 3, 1},\n {1, 2, 3, 1},\n {3, 2, 1, 3},\n {3, 3, 3, 1, 1, 3, 3, 3},\n }\n for _, test := range tests {\n _, nest := toTree(test, 0, 1)\n fmt.Printf(\"%17s => %v\\n\", fmt.Sprintf(\"%v\", test), nest)\n }\n}"} {"title": "Tropical algebra overloading", "language": "Go from Wren", "task": "In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring\n(R -Inf, , ) containing the ring of real numbers R augmented by negative infinity,\nthe max function (returns the greater of two real numbers), and addition.\n\nIn max tropical algebra, x y = max(x, y) and x y = x + y. The identity for \nis -Inf (the max of any number with -infinity is that number), and the identity for is 0.\n\n;Task:\n\n* Define functions or, if the language supports the symbols as operators, operators for and that fit the above description. If the language does not support and as operators but allows overloading operators for a new object type, you may instead overload + and * for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose. \n\nShow that 2 -2 is 0, -0.001 -Inf is -0.001, 0 -Inf is -Inf, 1.5 -1 is 1.5, and -0.5 0 is -0.5.\n\n* Define exponentiation as serial , and in general that a to the power of b is a * b, where a is a real number and b must be a positive integer. Use either | or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such \"exponentiation\" in the language being used. Calculate 5 | 7 using this definition.\n\n* Max tropical algebra is distributive, so that\n\n a (b c) equals a b b c, \n\nwhere has precedence over . Demonstrate that 5 (8 7) equals 5 8 5 7.\n\n* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).\n\n\n;See also\n:;*[Tropical algebra]\n:;*[Tropical geometry review article]\n:;*[Operator overloading]\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"log\"\n \"math\"\n)\n\nvar MinusInf = math.Inf(-1)\n\ntype MaxTropical struct{ r float64 }\n\nfunc newMaxTropical(r float64) MaxTropical {\n if math.IsInf(r, 1) || math.IsNaN(r) {\n log.Fatal(\"Argument must be a real number or negative infinity.\")\n }\n return MaxTropical{r}\n}\n\nfunc (t MaxTropical) eq(other MaxTropical) bool {\n return t.r == other.r\n}\n\n// equivalent to \u2295 operator\nfunc (t MaxTropical) add(other MaxTropical) MaxTropical {\n if t.r == MinusInf {\n return other\n }\n if other.r == MinusInf {\n return t\n }\n return newMaxTropical(math.Max(t.r, other.r))\n}\n\n// equivalent to \u2297 operator\nfunc (t MaxTropical) mul(other MaxTropical) MaxTropical {\n if t.r == 0 {\n return other\n }\n if other.r == 0 {\n return t\n }\n return newMaxTropical(t.r + other.r)\n}\n\n// exponentiation function\nfunc (t MaxTropical) pow(e int) MaxTropical {\n if e < 1 {\n log.Fatal(\"Exponent must be a positive integer.\")\n }\n if e == 1 {\n return t\n }\n p := t\n for i := 2; i <= e; i++ {\n p = p.mul(t)\n }\n return p\n}\n\nfunc (t MaxTropical) String() string {\n return fmt.Sprintf(\"%g\", t.r)\n}\n\nfunc main() {\n // 0 denotes \u2295 and 1 denotes \u2297\n data := [][]float64{\n {2, -2, 1},\n {-0.001, MinusInf, 0},\n {0, MinusInf, 1},\n {1.5, -1, 0},\n {-0.5, 0, 1},\n }\n for _, d := range data {\n a := newMaxTropical(d[0])\n b := newMaxTropical(d[1])\n if d[2] == 0 {\n fmt.Printf(\"%s \u2295 %s = %s\\n\", a, b, a.add(b))\n } else {\n fmt.Printf(\"%s \u2297 %s = %s\\n\", a, b, a.mul(b))\n }\n }\n\n c := newMaxTropical(5)\n fmt.Printf(\"%s ^ 7 = %s\\n\", c, c.pow(7))\n\n d := newMaxTropical(8)\n e := newMaxTropical(7)\n f := c.mul(d.add(e))\n g := c.mul(d).add(c.mul(e))\n fmt.Printf(\"%s \u2297 (%s \u2295 %s) = %s\\n\", c, d, e, f)\n fmt.Printf(\"%s \u2297 %s \u2295 %s \u2297 %s = %s\\n\", c, d, c, e, g)\n fmt.Printf(\"%s \u2297 (%s \u2295 %s) == %s \u2297 %s \u2295 %s \u2297 %s is %t\\n\", c, d, e, c, d, c, e, f.eq(g))\n}"} {"title": "Truncate a file", "language": "Go", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "import (\n \"fmt\"\n \"os\"\n)\n\nif err := os.Truncate(\"filename\", newSize); err != nil {\n fmt.Println(err)\n}"} {"title": "Truth table", "language": "Go", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* [[Boolean values]]\n* [[Ternary logic]]\n\n\n;See also:\n* Wolfram MathWorld entry on truth tables.\n* some \"truth table\" examples from Google.\n\n", "solution": "package main\n\nimport (\n \"bufio\"\n \"errors\"\n \"fmt\"\n \"go/ast\"\n \"go/parser\"\n \"go/token\"\n \"os\"\n \"reflect\"\n)\n\nfunc main() {\n in := bufio.NewScanner(os.Stdin)\n for {\n fmt.Print(\"Expr: \")\n in.Scan()\n if err := in.Err(); err != nil {\n fmt.Println(err)\n return\n }\n if !tt(in.Text()) {\n return\n }\n }\n}\n\nfunc tt(expr string) bool {\n // call library parser\n tree, err := parser.ParseExpr(expr)\n if err != nil {\n fmt.Println(err)\n return false\n }\n // create handy object to pass around\n e := &evaluator{nil, map[string]bool{}, tree}\n // library tree traversal function calls e.Visit for each node.\n // use this to collect variables of the expression.\n ast.Walk(e, tree)\n // print headings for truth table\n for _, n := range e.names {\n fmt.Printf(\"%-6s\", n)\n }\n fmt.Println(\" \", expr)\n // start recursive table generation function on first variable\n e.evalVar(0)\n return true\n}\n\ntype evaluator struct {\n names []string // variables, in order of appearance\n val map[string]bool // map variables to boolean values\n tree ast.Expr // parsed expression as ast\n}\n\n// visitor function called by library Walk function.\n// builds a list of unique variable names.\nfunc (e *evaluator) Visit(n ast.Node) ast.Visitor {\n if id, ok := n.(*ast.Ident); ok {\n if !e.val[id.Name] {\n e.names = append(e.names, id.Name)\n e.val[id.Name] = true\n }\n }\n return e\n}\n\n// method recurses for each variable of the truth table, assigning it to\n// false, then true. At bottom of recursion, when all variables are\n// assigned, it evaluates the expression and outputs one line of the\n// truth table\nfunc (e *evaluator) evalVar(nx int) bool {\n if nx == len(e.names) {\n // base case\n v, err := evalNode(e.tree, e.val)\n if err != nil {\n fmt.Println(\" \", err)\n return false\n }\n // print variable values\n for _, n := range e.names {\n fmt.Printf(\"%-6t\", e.val[n])\n }\n // print expression value\n fmt.Println(\" \", v)\n return true\n }\n // recursive case\n for _, v := range []bool{false, true} {\n e.val[e.names[nx]] = v\n if !e.evalVar(nx + 1) {\n return false\n }\n }\n return true\n}\n\n// recursively evaluate ast\nfunc evalNode(nd ast.Node, val map[string]bool) (bool, error) {\n switch n := nd.(type) {\n case *ast.Ident:\n return val[n.Name], nil\n case *ast.BinaryExpr:\n x, err := evalNode(n.X, val)\n if err != nil {\n return false, err\n }\n y, err := evalNode(n.Y, val)\n if err != nil {\n return false, err\n }\n switch n.Op {\n case token.AND:\n return x && y, nil\n case token.OR:\n return x || y, nil\n case token.XOR:\n return x != y, nil\n default:\n return unsup(n.Op)\n }\n case *ast.UnaryExpr:\n x, err := evalNode(n.X, val)\n if err != nil {\n return false, err\n }\n switch n.Op {\n case token.XOR:\n return !x, nil\n default:\n return unsup(n.Op)\n }\n case *ast.ParenExpr:\n return evalNode(n.X, val)\n }\n return unsup(reflect.TypeOf(nd))\n}\n\nfunc unsup(i interface{}) (bool, error) {\n return false, errors.New(fmt.Sprintf(\"%v unsupported\", i))\n}\n"} {"title": "Two bullet roulette", "language": "Go from Wren", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"strings\"\n \"time\"\n)\n\nvar cylinder = [6]bool{}\n\nfunc rshift() {\n t := cylinder[5]\n for i := 4; i >= 0; i-- {\n cylinder[i+1] = cylinder[i]\n }\n cylinder[0] = t\n}\n\nfunc unload() {\n for i := 0; i < 6; i++ {\n cylinder[i] = false\n }\n}\n\nfunc load() {\n for cylinder[0] {\n rshift()\n }\n cylinder[0] = true\n rshift()\n}\n\nfunc spin() {\n var lim = 1 + rand.Intn(6)\n for i := 1; i < lim; i++ {\n rshift()\n }\n}\n\nfunc fire() bool {\n shot := cylinder[0]\n rshift()\n return shot\n}\n\nfunc method(s string) int {\n unload()\n for _, c := range s {\n switch c {\n case 'L':\n load()\n case 'S':\n spin()\n case 'F':\n if fire() {\n return 1\n }\n }\n }\n return 0\n}\n\nfunc mstring(s string) string {\n var l []string\n for _, c := range s {\n switch c {\n case 'L':\n l = append(l, \"load\")\n case 'S':\n l = append(l, \"spin\")\n case 'F':\n l = append(l, \"fire\")\n }\n }\n return strings.Join(l, \", \")\n}\n\nfunc main() {\n rand.Seed(time.Now().UnixNano())\n tests := 100000\n for _, m := range []string{\"LSLSFSF\", \"LSLSFF\", \"LLSFSF\", \"LLSFF\"} {\n sum := 0\n for t := 1; t <= tests; t++ {\n sum += method(m)\n }\n pc := float64(sum) * 100 / float64(tests)\n fmt.Printf(\"%-40s produces %6.3f%% deaths.\\n\", mstring(m), pc)\n }\n}"} {"title": "UPC", "language": "Go", "task": "Goal: \nConvert UPC bar codes to decimal.\n\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... \n\nHere, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).\n\n\n;Sample input:\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\nSome of these were entered upside down, and one entry has a timing error.\n\n\n;Task:\nImplement code to find the corresponding decimal representation of each, rejecting the error. \n\nExtra credit for handling the rows entered upside down (the other option is to reject them).\n\n\n;Notes:\nEach digit is represented by 7 bits:\n\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\nOn the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. \nOn the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' \nAlternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.\n\n\n\n;The UPC-A bar code structure:\n::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* then has a ''' # # ''' sequence marking the start of the sequence, \n::* then has the six \"left hand\" digits, \n::* then has a ''' # # ''' sequence in the middle, \n::* then has the six \"right hand digits\", \n::* then has another ''' # # ''' (end sequence), and finally, \n::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\n\nFinally, the last digit is a checksum digit which may be used to help detect errors. \n\n\n;Verification:\nMultiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.\n\nThe sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"regexp\"\n)\n\nvar bits = []string{\n \"0 0 0 1 1 0 1 \",\n \"0 0 1 1 0 0 1 \",\n \"0 0 1 0 0 1 1 \",\n \"0 1 1 1 1 0 1 \",\n \"0 1 0 0 0 1 1 \",\n \"0 1 1 0 0 0 1 \",\n \"0 1 0 1 1 1 1 \",\n \"0 1 1 1 0 1 1 \",\n \"0 1 1 0 1 1 1 \",\n \"0 0 0 1 0 1 1 \",\n}\n\nvar (\n lhs = make(map[string]int)\n rhs = make(map[string]int)\n)\n\nvar weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}\n\nconst (\n s = \"# #\"\n m = \" # # \"\n e = \"# #\"\n d = \"(?:#| ){7}\"\n)\n\nfunc init() {\n for i := 0; i <= 9; i++ {\n lt := make([]byte, 7)\n rt := make([]byte, 7)\n for j := 0; j < 14; j += 2 {\n if bits[i][j] == '1' {\n lt[j/2] = '#'\n rt[j/2] = ' '\n } else {\n lt[j/2] = ' '\n rt[j/2] = '#'\n }\n }\n lhs[string(lt)] = i\n rhs[string(rt)] = i\n }\n}\n\nfunc reverse(s string) string {\n b := []byte(s)\n for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {\n b[i], b[j] = b[j], b[i]\n }\n return string(b)\n}\n\nfunc main() {\n barcodes := []string{\n \" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \",\n \" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \",\n \" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \",\n \" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \",\n \" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \",\n \" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \",\n \" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \",\n \" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \",\n \" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \",\n \" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \",\n }\n\n // Regular expression to check validity of a barcode and extract digits. However we accept any number\n // of spaces at the beginning or end i.e. we don't enforce a minimum of 9.\n expr := fmt.Sprintf(`^\\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\\s*$`,\n s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)\n rx := regexp.MustCompile(expr)\n fmt.Println(\"UPC-A barcodes:\")\n for i, bc := range barcodes {\n for j := 0; j <= 1; j++ {\n if !rx.MatchString(bc) {\n fmt.Printf(\"%2d: Invalid format\\n\", i+1)\n break\n }\n codes := rx.FindStringSubmatch(bc)\n digits := make([]int, 12)\n var invalid, ok bool // False by default.\n for i := 1; i <= 6; i++ {\n digits[i-1], ok = lhs[codes[i]]\n if !ok {\n invalid = true\n }\n digits[i+5], ok = rhs[codes[i+6]]\n if !ok {\n invalid = true\n }\n }\n if invalid { // Contains at least one invalid digit.\n if j == 0 { // Try reversing.\n bc = reverse(bc)\n continue\n } else {\n fmt.Printf(\"%2d: Invalid digit(s)\\n\", i+1)\n break\n }\n }\n sum := 0\n for i, d := range digits {\n sum += weights[i] * d\n }\n if sum%10 != 0 {\n fmt.Printf(\"%2d: Checksum error\\n\", i+1)\n break\n } else {\n ud := \"\"\n if j == 1 {\n ud = \"(upside down)\"\n }\n fmt.Printf(\"%2d: %v %s\\n\", i+1, digits, ud)\n break\n }\n }\n }\n}"} {"title": "URL decoding", "language": "Go", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, escaped := range []string{\n\t\t\"http%3A%2F%2Ffoo%20bar%2F\",\n\t\t\"google.com/search?q=%60Abdu%27l-Bah%C3%A1\",\n\t} {\n\t\tu, err := url.QueryUnescape(escaped)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(u)\n\t}\n}"} {"title": "URL encoding", "language": "Go", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"net/url\"\n)\n\nfunc main() {\n fmt.Println(url.QueryEscape(\"http://foo bar/\"))\n}"} {"title": "URL parser", "language": "Go", "task": "URLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...\n\n\nNote: this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded ('''%''') in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* Here is the official standard: https://tools.ietf.org/html/rfc3986, \n* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:\n::* scheme = foo\n::* domain = example.com\n::* port = :8042\n::* path = over/there\n::* query = name=ferret\n::* fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' should parse into:\n::* scheme = urn\n::* path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* mailto:John.Doe@example.com \n:* news:comp.infosystems.www.servers.unix \n:* tel:+1-816-555-1212 \n:* telnet://192.0.2.16:80/ \n:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net/url\"\n)\n\nfunc main() {\n\tfor _, in := range []string{\n\t\t\"foo://example.com:8042/over/there?name=ferret#nose\",\n\t\t\"urn:example:animal:ferret:nose\",\n\t\t\"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\",\n\t\t\"ftp://ftp.is.co.za/rfc/rfc1808.txt\",\n\t\t\"http://www.ietf.org/rfc/rfc2396.txt#header1\",\n\t\t\"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\",\n\t\t\"mailto:John.Doe@example.com\",\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet://192.0.2.16:80/\",\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\n\t\t\"ssh://alice@example.com\",\n\t\t\"https://bob:pass@example.com/place\",\n\t\t\"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\",\n\t} {\n\t\tfmt.Println(in)\n\t\tu, err := url.Parse(in)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tif in != u.String() {\n\t\t\tfmt.Printf(\"Note: reassmebles as %q\\n\", u)\n\t\t}\n\t\tprintURL(u)\n\t}\n}\n\nfunc printURL(u *url.URL) {\n\tfmt.Println(\" Scheme:\", u.Scheme)\n\tif u.Opaque != \"\" {\n\t\tfmt.Println(\" Opaque:\", u.Opaque)\n\t}\n\tif u.User != nil {\n\t\tfmt.Println(\" Username:\", u.User.Username())\n\t\tif pwd, ok := u.User.Password(); ok {\n\t\t\tfmt.Println(\" Password:\", pwd)\n\t\t}\n\t}\n\tif u.Host != \"\" {\n\t\tif host, port, err := net.SplitHostPort(u.Host); err == nil {\n\t\t\tfmt.Println(\" Host:\", host)\n\t\t\tfmt.Println(\" Port:\", port)\n\t\t} else {\n\t\t\tfmt.Println(\" Host:\", u.Host)\n\t\t}\n\t}\n\tif u.Path != \"\" {\n\t\tfmt.Println(\" Path:\", u.Path)\n\t}\n\tif u.RawQuery != \"\" {\n\t\tfmt.Println(\" RawQuery:\", u.RawQuery)\n\t\tm, err := url.ParseQuery(u.RawQuery)\n\t\tif err == nil {\n\t\t\tfor k, v := range m {\n\t\t\t\tfmt.Printf(\" Key: %q Values: %q\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tif u.Fragment != \"\" {\n\t\tfmt.Println(\" Fragment:\", u.Fragment)\n\t}\n}"} {"title": "UTF-8 encode and decode", "language": "Go", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"encoding/hex\"\n \"fmt\"\n \"log\"\n \"strings\"\n)\n\nvar testCases = []struct {\n rune\n string\n}{\n {'A', \"41\"},\n {'\u00f6', \"C3 B6\"},\n {'\u0416', \"D0 96\"},\n {'\u20ac', \"E2 82 AC\"},\n {'\ud834\udd1e', \"F0 9D 84 9E\"},\n}\n\nfunc main() {\n for _, tc := range testCases {\n // derive some things from test data\n u := fmt.Sprintf(\"U+%04X\", tc.rune)\n b, err := hex.DecodeString(strings.Replace(tc.string, \" \", \"\", -1))\n if err != nil {\n log.Fatal(\"bad test data\")\n }\n // exercise encoder and decoder on test data\n e := encodeUTF8(tc.rune)\n d := decodeUTF8(b)\n // show function return values\n fmt.Printf(\"%c %-7s %X\\n\", d, u, e)\n // validate return values against test data\n if !bytes.Equal(e, b) {\n log.Fatal(\"encodeUTF8 wrong\")\n }\n if d != tc.rune {\n log.Fatal(\"decodeUTF8 wrong\")\n }\n }\n}\n\nconst (\n // first byte of a 2-byte encoding starts 110 and carries 5 bits of data\n b2Lead = 0xC0 // 1100 0000\n b2Mask = 0x1F // 0001 1111\n\n // first byte of a 3-byte encoding starts 1110 and carries 4 bits of data\n b3Lead = 0xE0 // 1110 0000\n b3Mask = 0x0F // 0000 1111\n\n // first byte of a 4-byte encoding starts 11110 and carries 3 bits of data\n b4Lead = 0xF0 // 1111 0000\n b4Mask = 0x07 // 0000 0111\n\n // non-first bytes start 10 and carry 6 bits of data\n mbLead = 0x80 // 1000 0000\n mbMask = 0x3F // 0011 1111\n)\n\nfunc encodeUTF8(r rune) []byte {\n switch i := uint32(r); {\n case i <= 1<<7-1: // max code point that encodes into a single byte\n return []byte{byte(r)}\n case i <= 1<<11-1: // into two bytes\n return []byte{\n b2Lead | byte(r>>6),\n mbLead | byte(r)&mbMask}\n case i <= 1<<16-1: // three\n return []byte{\n b3Lead | byte(r>>12),\n mbLead | byte(r>>6)&mbMask,\n mbLead | byte(r)&mbMask}\n default:\n return []byte{\n b4Lead | byte(r>>18),\n mbLead | byte(r>>12)&mbMask,\n mbLead | byte(r>>6)&mbMask,\n mbLead | byte(r)&mbMask}\n }\n}\n\nfunc decodeUTF8(b []byte) rune {\n switch b0 := b[0]; {\n case b0 < 0x80:\n return rune(b0)\n case b0 < 0xE0:\n return rune(b0&b2Mask)<<6 |\n rune(b[1]&mbMask)\n case b0 < 0xF0:\n return rune(b0&b3Mask)<<12 |\n rune(b[1]&mbMask)<<6 |\n rune(b[2]&mbMask)\n default:\n return rune(b0&b4Mask)<<18 |\n rune(b[1]&mbMask)<<12 |\n rune(b[2]&mbMask)<<6 |\n rune(b[3]&mbMask)\n }\n}"} {"title": "Ukkonen\u2019s suffix tree construction", "language": "Go", "task": "Suffix Trees are very useful in numerous string processing and computational biology problems.\n\nThe task is to create a function which implements Ukkonen's algorithm to create a useful Suffix Tree as described:\n\n Part 1\n Part 2\n Part 3\n Part 4\n Part 5\n Part 6\n\nUsing [[Arithmetic-geometric mean/Calculate Pi]] generate the first 1000, 10000, and 100000 decimal places of pi. Using your implementation with an alphabet of 0 through 9 (plus $ say to make the tree explicit) find the longest repeated string in each list. Time your results and demonstrate that your implementation is linear (i.e. that 10000 takes approx. 10 times as long as 1000). You may vary the size of the lists of decimal places of pi to give reasonable answers.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/big\"\n \"time\"\n)\n\nvar maxChar = 128\n\ntype Node struct {\n children []*Node\n suffixLink *Node\n start int\n end *int\n suffixIndex int\n}\n\nvar (\n text string\n root *Node\n lastNewNode *Node\n activeNode *Node\n activeEdge = -1\n activeLength = 0\n remainingSuffixCount = 0\n leafEnd = -1\n rootEnd *int\n splitEnd *int\n size = -1\n)\n\nfunc newNode(start int, end *int) *Node {\n node := new(Node)\n node.children = make([]*Node, maxChar)\n node.suffixLink = root\n node.start = start\n node.end = end\n node.suffixIndex = -1\n return node\n}\n\nfunc edgeLength(n *Node) int {\n if n == root {\n return 0\n }\n return *(n.end) - n.start + 1\n}\n\nfunc walkDown(currNode *Node) bool {\n if activeLength >= edgeLength(currNode) {\n activeEdge += edgeLength(currNode)\n activeLength -= edgeLength(currNode)\n activeNode = currNode\n return true\n }\n return false\n}\n\nfunc extendSuffixTree(pos int) {\n leafEnd = pos\n remainingSuffixCount++\n lastNewNode = nil\n for remainingSuffixCount > 0 {\n if activeLength == 0 {\n activeEdge = pos\n }\n if activeNode.children[text[activeEdge]] == nil {\n activeNode.children[text[activeEdge]] = newNode(pos, &leafEnd)\n if lastNewNode != nil {\n lastNewNode.suffixLink = activeNode\n lastNewNode = nil\n }\n } else {\n next := activeNode.children[text[activeEdge]]\n if walkDown(next) {\n continue\n }\n if text[next.start+activeLength] == text[pos] {\n if lastNewNode != nil && activeNode != root {\n lastNewNode.suffixLink = activeNode\n lastNewNode = nil\n }\n activeLength++\n break\n }\n temp := next.start + activeLength - 1\n splitEnd = &temp\n split := newNode(next.start, splitEnd)\n activeNode.children[text[activeEdge]] = split\n split.children[text[pos]] = newNode(pos, &leafEnd)\n next.start += activeLength\n split.children[text[next.start]] = next\n if lastNewNode != nil {\n lastNewNode.suffixLink = split\n }\n lastNewNode = split\n }\n remainingSuffixCount--\n if activeNode == root && activeLength > 0 {\n activeLength--\n activeEdge = pos - remainingSuffixCount + 1\n } else if activeNode != root {\n activeNode = activeNode.suffixLink\n }\n }\n}\n\nfunc setSuffixIndexByDFS(n *Node, labelHeight int) {\n if n == nil {\n return\n }\n if n.start != -1 {\n // Uncomment line below to print suffix tree\n // fmt.Print(text[n.start: *(n.end) +1])\n }\n leaf := 1\n for i := 0; i < maxChar; i++ {\n if n.children[i] != nil {\n // Uncomment the 3 lines below to print suffix index\n //if leaf == 1 && n.start != -1 {\n // fmt.Printf(\" [%d]\\n\", n.suffixIndex)\n //}\n leaf = 0\n setSuffixIndexByDFS(n.children[i], labelHeight+edgeLength(n.children[i]))\n }\n }\n if leaf == 1 {\n n.suffixIndex = size - labelHeight\n // Uncomment line below to print suffix index\n //fmt.Printf(\" [%d]\\n\", n.suffixIndex)\n }\n}\n\nfunc buildSuffixTree() {\n size = len(text)\n temp := -1\n rootEnd = &temp\n root = newNode(-1, rootEnd)\n activeNode = root\n for i := 0; i < size; i++ {\n extendSuffixTree(i)\n }\n labelHeight := 0\n setSuffixIndexByDFS(root, labelHeight)\n}\n\nfunc doTraversal(n *Node, labelHeight int, maxHeight, substringStartIndex *int) {\n if n == nil {\n return\n }\n if n.suffixIndex == -1 {\n for i := 0; i < maxChar; i++ {\n if n.children[i] != nil {\n doTraversal(n.children[i], labelHeight+edgeLength(n.children[i]),\n maxHeight, substringStartIndex)\n }\n }\n } else if n.suffixIndex > -1 && (*maxHeight < labelHeight-edgeLength(n)) {\n *maxHeight = labelHeight - edgeLength(n)\n *substringStartIndex = n.suffixIndex\n }\n}\n\nfunc getLongestRepeatedSubstring(s string) {\n maxHeight := 0\n substringStartIndex := 0\n doTraversal(root, 0, &maxHeight, &substringStartIndex)\n // Uncomment line below to print maxHeight and substringStartIndex\n // fmt.Printf(\"maxHeight %d, substringStartIndex %d\\n\", maxHeight, substringStartIndex)\n if s == \"\" {\n fmt.Printf(\" %s is: \", text)\n } else {\n fmt.Printf(\" %s is: \", s)\n }\n k := 0\n for ; k < maxHeight; k++ {\n fmt.Printf(\"%c\", text[k+substringStartIndex])\n }\n if k == 0 {\n fmt.Print(\"No repeated substring\")\n }\n fmt.Println()\n}\n\nfunc calculatePi() *big.Float {\n one := big.NewFloat(1)\n two := big.NewFloat(2)\n four := big.NewFloat(4)\n prec := uint(325 * 1024) // enough to calculate Pi to 100,182 decimal digits\n\n a := big.NewFloat(1).SetPrec(prec)\n g := new(big.Float).SetPrec(prec)\n\n // temporary variables\n t := new(big.Float).SetPrec(prec)\n u := new(big.Float).SetPrec(prec)\n\n g.Quo(a, t.Sqrt(two))\n sum := new(big.Float)\n pow := big.NewFloat(2)\n\n for a.Cmp(g) != 0 {\n t.Add(a, g)\n t.Quo(t, two)\n g.Sqrt(u.Mul(a, g))\n a.Set(t)\n pow.Mul(pow, two)\n t.Sub(t.Mul(a, a), u.Mul(g, g))\n sum.Add(sum, t.Mul(t, pow))\n }\n\n t.Mul(a, a)\n t.Mul(t, four)\n pi := t.Quo(t, u.Sub(one, sum))\n return pi\n}\n\nfunc main() {\n tests := []string{\n \"GEEKSFORGEEKS$\",\n \"AAAAAAAAAA$\",\n \"ABCDEFG$\",\n \"ABABABA$\",\n \"ATCGATCGA$\",\n \"banana$\",\n \"abcpqrabpqpq$\",\n \"pqrpqpqabab$\",\n }\n fmt.Println(\"Longest Repeated Substring in:\\n\")\n for _, test := range tests {\n text = test\n buildSuffixTree()\n getLongestRepeatedSubstring(\"\")\n }\n fmt.Println()\n\n pi := calculatePi()\n piStr := fmt.Sprintf(\"%v\", pi)\n piStr = piStr[2:] // remove initial 3.\n numbers := []int{1e3, 1e4, 1e5}\n maxChar = 58\n for _, number := range numbers {\n start := time.Now()\n text = piStr[0:number] + \"$\"\n buildSuffixTree()\n getLongestRepeatedSubstring(fmt.Sprintf(\"first %d d.p. of Pi\", number))\n elapsed := time.Now().Sub(start)\n fmt.Printf(\" (this took %s)\\n\\n\", elapsed)\n }\n}"} {"title": "Unbias a random generator", "language": "Go", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n)\n\nconst samples = 1e6\n\nfunc main() {\n fmt.Println(\"Generator 1 count 0 count % 1 count\")\n for n := 3; n <= 6; n++ {\n // function randN, per task description\n randN := func() int {\n if rand.Intn(n) == 0 {\n return 1\n }\n return 0\n }\n var b [2]int\n for x := 0; x < samples; x++ {\n b[randN()]++\n }\n fmt.Printf(\"randN(%d) %7d %7d %5.2f%%\\n\",\n n, b[1], b[0], float64(b[1])*100/samples)\n\n // function unbiased, per task description\n unbiased := func() (b int) {\n for b = randN(); b == randN(); b = randN() {\n }\n return\n }\n var u [2]int\n for x := 0; x < samples; x++ {\n u[unbiased()]++\n }\n fmt.Printf(\"unbiased %7d %7d %5.2f%%\\n\",\n u[1], u[0], float64(u[1])*100/samples)\n }\n}"} {"title": "Unicode strings", "language": "Go", "task": "As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. \n\nIt is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. \n\nHow well prepared is your programming language for Unicode? \n\n\n;Task:\nDiscuss and demonstrate its unicode awareness and capabilities. \n\n\nSome suggested topics:\n:* How easy is it to present Unicode strings in source code? \n:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* How well can the language communicate with the rest of the world? \n:* Is it good at input/output with Unicode?\n:* Is it convenient to manipulate Unicode strings in the language?\n:* How broad/deep does the language support Unicode? \n:* What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* Does it support normalization?\n\n\n;Note:\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\n\n;See also:\n* [[Unicode variable names]]\n* [[Terminal control/Display an extended character]]\n\n", "solution": "var i int\n var u rune\n for i, u = range \"voil\u00e0\" {\n fmt.Println(i, u)\n }"} {"title": "Universal Turing machine", "language": "Go", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "package turing\n\ntype Symbol byte\n\ntype Motion byte\n\nconst (\n Left Motion = 'L'\n Right Motion = 'R'\n Stay Motion = 'N'\n)\n\ntype Tape struct {\n data []Symbol\n pos, left int\n blank Symbol\n}\n\n// NewTape returns a new tape filled with 'data' and position set to 'start'.\n// 'start' does not need to be range, the tape will be extended if required.\nfunc NewTape(blank Symbol, start int, data []Symbol) *Tape {\n t := &Tape{\n data: data,\n blank: blank,\n }\n if start < 0 {\n t.Left(-start)\n }\n t.Right(start)\n return t\n}\n\nfunc (t *Tape) Stay() {}\nfunc (t *Tape) Data() []Symbol { return t.data[t.left:] }\nfunc (t *Tape) Read() Symbol { return t.data[t.pos] }\nfunc (t *Tape) Write(s Symbol) { t.data[t.pos] = s }\n\nfunc (t *Tape) Dup() *Tape {\n t2 := &Tape{\n data: make([]Symbol, len(t.Data())),\n blank: t.blank,\n }\n copy(t2.data, t.Data())\n t2.pos = t.pos - t.left\n return t2\n}\n\nfunc (t *Tape) String() string {\n s := \"\"\n for i := t.left; i < len(t.data); i++ {\n b := t.data[i]\n if i == t.pos {\n s += \"[\" + string(b) + \"]\"\n } else {\n s += \" \" + string(b) + \" \"\n }\n }\n return s\n}\n\nfunc (t *Tape) Move(a Motion) {\n switch a {\n case Left:\n t.Left(1)\n case Right:\n t.Right(1)\n case Stay:\n t.Stay()\n }\n}\n\nconst minSz = 16\n\nfunc (t *Tape) Left(n int) {\n t.pos -= n\n if t.pos < 0 {\n // Extend left\n var sz int\n for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {\n }\n newd := make([]Symbol, sz)\n newl := len(newd) - cap(t.data[t.left:])\n n := copy(newd[newl:], t.data[t.left:])\n t.data = newd[:newl+n]\n t.pos += newl - t.left\n t.left = newl\n }\n if t.pos < t.left {\n if t.blank != 0 {\n for i := t.pos; i < t.left; i++ {\n t.data[i] = t.blank\n }\n }\n t.left = t.pos\n }\n}\n\nfunc (t *Tape) Right(n int) {\n t.pos += n\n if t.pos >= cap(t.data) {\n // Extend right\n var sz int\n for sz = minSz; t.pos >= sz; sz <<= 1 {\n }\n newd := make([]Symbol, sz)\n n := copy(newd[t.left:], t.data[t.left:])\n t.data = newd[:t.left+n]\n }\n if i := len(t.data); t.pos >= i {\n t.data = t.data[:t.pos+1]\n if t.blank != 0 {\n for ; i < len(t.data); i++ {\n t.data[i] = t.blank\n }\n }\n }\n}\n\ntype State string\n\ntype Rule struct {\n State\n Symbol\n Write Symbol\n Motion\n Next State\n}\n\nfunc (i *Rule) key() key { return key{i.State, i.Symbol} }\nfunc (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }\n\ntype key struct {\n State\n Symbol\n}\n\ntype action struct {\n write Symbol\n Motion\n next State\n}\n\ntype Machine struct {\n tape *Tape\n start, state State\n transition map[key]action\n l func(string, ...interface{}) // XXX\n}\n\nfunc NewMachine(rules []Rule) *Machine {\n m := &Machine{transition: make(map[key]action, len(rules))}\n if len(rules) > 0 {\n m.start = rules[0].State\n }\n for _, r := range rules {\n m.transition[r.key()] = r.action()\n }\n return m\n}\n\nfunc (m *Machine) Run(input *Tape) (int, *Tape) {\n m.tape = input.Dup()\n m.state = m.start\n for cnt := 0; ; cnt++ {\n if m.l != nil {\n m.l(\"%3d %4s: %v\\n\", cnt, m.state, m.tape)\n }\n sym := m.tape.Read()\n act, ok := m.transition[key{m.state, sym}]\n if !ok {\n return cnt, m.tape\n }\n m.tape.Write(act.write)\n m.tape.Move(act.Motion)\n m.state = act.next\n }\n}"} {"title": "Unix/ls", "language": "Go", "task": "Write a program that will list everything in the current folder, similar to:\n:::* the Unix utility \"ls\" [http://man7.org/linux/man-pages/man1/ls.1.html] or \n:::* the Windows terminal command \"DIR\" \n\n\nThe output must be sorted, but printing extended details and producing multi-column output is not required.\n\n\n;Example output\nFor the list of paths:\n\n/foo/bar\n/foo/bar/1\n/foo/bar/2\n/foo/bar/a\n/foo/bar/b\n\n\n\nWhen the program is executed in `/foo`, it should print:\n\nbar\n\nand when the program is executed in `/foo/bar`, it should print:\n\n1\n2\na\nb\n\n\n", "solution": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n)\n\nfunc main() {\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfiles, err := f.Readdirnames(0)\n\tf.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsort.Strings(files)\n\tfor _, n := range files {\n\t\tfmt.Println(n)\n\t}\n}"} {"title": "Validate International Securities Identification Number", "language": "Go", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "package main\n\nimport \"testing\"\n\nfunc TestValidISIN(t *testing.T) {\n\ttestcases := []struct {\n\t\tisin string\n\t\tvalid bool\n\t}{\n\t\t{\"US0378331005\", true},\n\t\t{\"US0373831005\", false},\n\t\t{\"U50378331005\", false},\n\t\t{\"US03378331005\", false},\n\t\t{\"AU0000XVGZA3\", true},\n\t\t{\"AU0000VXGZA3\", true},\n\t\t{\"FR0000988040\", true},\n\t}\n\n\tfor _, testcase := range testcases {\n\t\tactual := ValidISIN(testcase.isin)\n\t\tif actual != testcase.valid {\n\t\t\tt.Errorf(\"expected %v for %q, got %v\",\n\t\t\t\ttestcase.valid, testcase.isin, actual)\n\t\t}\n\t}\n}"} {"title": "Van Eck sequence", "language": "Go", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n const max = 1000\n a := make([]int, max) // all zero by default\n for n := 0; n < max-1; n++ {\n for m := n - 1; m >= 0; m-- {\n if a[m] == a[n] {\n a[n+1] = n - m\n break\n } \n }\n }\n fmt.Println(\"The first ten terms of the Van Eck sequence are:\")\n fmt.Println(a[:10])\n fmt.Println(\"\\nTerms 991 to 1000 of the sequence are:\")\n fmt.Println(a[990:])\n}"} {"title": "Van der Corput sequence", "language": "Go", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc v2(n uint) (r float64) {\n p := .5\n for n > 0 {\n if n&1 == 1 {\n r += p\n }\n p *= .5\n n >>= 1\n }\n return\n}\n\nfunc newV(base uint) func(uint) float64 {\n invb := 1 / float64(base)\n return func(n uint) (r float64) {\n p := invb\n for n > 0 {\n r += p * float64(n%base)\n p *= invb\n n /= base\n }\n return\n }\n}\n\nfunc main() {\n fmt.Println(\"Base 2:\")\n for i := uint(0); i < 10; i++ {\n fmt.Println(i, v2(i))\n }\n fmt.Println(\"Base 3:\")\n v3 := newV(3)\n for i := uint(0); i < 10; i++ {\n fmt.Println(i, v3(i))\n }\n}"} {"title": "Variable declaration reset", "language": "Go", "task": "A decidely non-challenging task to highlight a potential difference between programming languages.\n\nUsing a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. \nThe purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.\nThere is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.\nShould your first attempt bomb with \"unassigned variable\" exceptions, feel free to code it as (say)\n // int prev // crashes with unassigned variable\n int prev = -1 // predictably no output\nIf your programming language does not support block scope (eg assembly) it should be omitted from this task.\n\n", "solution": "package main\n\nimport \"fmt\"\n\nfunc main() {\n s := []int{1, 2, 2, 3, 4, 4, 5}\n\n // There is no output as 'prev' is created anew each time\n // around the loop and set implicitly to zero.\n for i := 0; i < len(s); i++ {\n curr := s[i]\n var prev int\n if i > 0 && curr == prev {\n fmt.Println(i)\n }\n prev = curr\n }\n\n // Now 'prev' is created only once and reassigned\n // each time around the loop producing the desired output.\n var prev int\n for i := 0; i < len(s); i++ {\n curr := s[i]\n if i > 0 && curr == prev {\n fmt.Println(i)\n }\n prev = curr\n }\n}"} {"title": "Vector products", "language": "Go", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "package main\n\nimport \"fmt\"\n\ntype vector struct {\n x, y, z float64\n}\n\nvar (\n a = vector{3, 4, 5}\n b = vector{4, 3, 5}\n c = vector{-5, -12, -13}\n)\n\nfunc dot(a, b vector) float64 {\n return a.x*b.x + a.y*b.y + a.z*b.z\n}\n\nfunc cross(a, b vector) vector {\n return vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}\n}\n\nfunc s3(a, b, c vector) float64 {\n return dot(a, cross(b, c))\n}\n\nfunc v3(a, b, c vector) vector {\n return cross(a, cross(b, c))\n}\n\nfunc main() {\n fmt.Println(dot(a, b))\n fmt.Println(cross(a, b))\n fmt.Println(s3(a, b, c))\n fmt.Println(v3(a, b, c))\n}"} {"title": "Verhoeff algorithm", "language": "Go from Wren", "task": "Description\nThe 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* [[Damm algorithm]]\n\n", "solution": "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\u1d62 p[i,n\u1d62] 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}"} {"title": "Visualize a tree", "language": "Go", "task": "A tree structure (i.e. a rooted, connected acyclic graph) 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:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* 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\n", "solution": "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}"} {"title": "Vogel's approximation method", "language": "Go from Kotlin", "task": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \"A\", \"B\", \"C\", \"D\", and \"E\". They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \"W\", \"X\", \"Y\", and \"Z\".\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is PS3100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is PS3100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\nvar supply = []int{50, 60, 50, 50}\nvar demand = []int{30, 20, 70, 30, 60}\n\nvar costs = make([][]int, 4)\n\nvar nRows = len(supply)\nvar nCols = len(demand)\n\nvar rowDone = make([]bool, nRows)\nvar colDone = make([]bool, nCols)\nvar results = make([][]int, nRows)\n\nfunc init() {\n costs[0] = []int{16, 16, 13, 22, 17}\n costs[1] = []int{14, 14, 13, 19, 15}\n costs[2] = []int{19, 19, 20, 23, 50}\n costs[3] = []int{50, 12, 50, 15, 11}\n\n for i := 0; i < len(results); i++ {\n results[i] = make([]int, nCols)\n }\n}\n\nfunc nextCell() []int {\n res1 := maxPenalty(nRows, nCols, true)\n res2 := maxPenalty(nCols, nRows, false)\n switch {\n case res1[3] == res2[3]:\n if res1[2] < res2[2] {\n return res1\n } else {\n return res2\n }\n case res1[3] > res2[3]:\n return res2\n default:\n return res1\n }\n}\n\nfunc diff(j, l int, isRow bool) []int {\n min1 := math.MaxInt32\n min2 := min1\n minP := -1\n for i := 0; i < l; i++ {\n var done bool\n if isRow {\n done = colDone[i]\n } else {\n done = rowDone[i]\n }\n if done {\n continue\n }\n var c int\n if isRow {\n c = costs[j][i]\n } else {\n c = costs[i][j]\n }\n if c < min1 {\n min2, min1, minP = min1, c, i\n } else if c < min2 {\n min2 = c\n }\n }\n return []int{min2 - min1, min1, minP}\n}\n\nfunc maxPenalty(len1, len2 int, isRow bool) []int {\n md := math.MinInt32\n pc, pm, mc := -1, -1, -1\n for i := 0; i < len1; i++ {\n var done bool\n if isRow {\n done = rowDone[i]\n } else {\n done = colDone[i]\n }\n if done {\n continue\n }\n res := diff(i, len2, isRow)\n if res[0] > md {\n md = res[0] // max diff\n pm = i // pos of max diff\n mc = res[1] // min cost\n pc = res[2] // pos of min cost\n }\n }\n if isRow {\n return []int{pm, pc, mc, md}\n }\n return []int{pc, pm, mc, md}\n}\n\nfunc main() {\n supplyLeft := 0\n for i := 0; i < len(supply); i++ {\n supplyLeft += supply[i]\n }\n totalCost := 0\n for supplyLeft > 0 {\n cell := nextCell()\n r, c := cell[0], cell[1]\n q := demand[c]\n if q > supply[r] {\n q = supply[r]\n }\n demand[c] -= q\n if demand[c] == 0 {\n colDone[c] = true\n }\n supply[r] -= q\n if supply[r] == 0 {\n rowDone[r] = true\n }\n results[r][c] = q\n supplyLeft -= q\n totalCost += q * costs[r][c]\n }\n\n fmt.Println(\" A B C D E\")\n for i, result := range results {\n fmt.Printf(\"%c\", 'W' + i)\n for _, item := range result {\n fmt.Printf(\" %2d\", item)\n }\n fmt.Println()\n }\n fmt.Println(\"\\nTotal cost =\", totalCost)\n}"} {"title": "Voronoi diagram", "language": "Go", "task": "A 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\n", "solution": "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}"} {"title": "War card game", "language": "Go from Wren", "task": "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: War game site\n\n:* Wikipedia: 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", "solution": "package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"time\"\n)\n\nvar suits = []string{\"\u2663\", \"\u2666\", \"\u2665\", \"\u2660\"}\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}"} {"title": "Water collected between towers", "language": "Go", "task": "In 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 \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\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 [[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\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "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}"} {"title": "Weird numbers", "language": "Go", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the 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.: '''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\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "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}"} {"title": "Word frequency", "language": "Go from Kotlin", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"regexp\"\n \"sort\"\n \"strings\"\n)\n\ntype keyval struct {\n key string\n val int\n}\n\nfunc main() {\n reg := regexp.MustCompile(`\\p{Ll}+`)\n bs, err := ioutil.ReadFile(\"135-0.txt\")\n if err != nil {\n log.Fatal(err)\n }\n text := strings.ToLower(string(bs))\n matches := reg.FindAllString(text, -1)\n groups := make(map[string]int)\n for _, match := range matches {\n groups[match]++\n }\n var keyvals []keyval\n for k, v := range groups {\n keyvals = append(keyvals, keyval{k, v})\n }\n sort.Slice(keyvals, func(i, j int) bool {\n return keyvals[i].val > keyvals[j].val\n })\n fmt.Println(\"Rank Word Frequency\")\n fmt.Println(\"==== ==== =========\")\n for rank := 1; rank <= 10; rank++ {\n word := keyvals[rank-1].key\n freq := keyvals[rank-1].val\n fmt.Printf(\"%2d %-4s %5d\\n\", rank, word, freq)\n }\n}"} {"title": "Word ladder", "language": "Go from Wren", "task": "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 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\n", "solution": "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}"} {"title": "Word search", "language": "Go from Java", "task": "A 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\n;Task \nCreate a 10 by 10 word search and fill it using words from the 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\n;Example\n\n\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\n\n", "solution": "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}"} {"title": "Word wrap", "language": "Go", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n)\n\nfunc wrap(text string, lineWidth int) (wrapped string) {\n words := strings.Fields(text)\n if len(words) == 0 {\n return\n }\n wrapped = words[0]\n spaceLeft := lineWidth - len(wrapped)\n for _, word := range words[1:] {\n if len(word)+1 > spaceLeft {\n wrapped += \"\\n\" + word\n spaceLeft = lineWidth - len(word)\n } else {\n wrapped += \" \" + word\n spaceLeft -= 1 + len(word)\n }\n }\n return\n}\n\nvar frog = `\nIn olden times when wishing still helped one, there lived a king\nwhose daughters were all beautiful, but the youngest was so beautiful\nthat the sun itself, which has seen so much, was astonished whenever\nit shone in her face. Close by the king's castle lay a great dark\nforest, and under an old lime-tree in the forest was a well, and when\nthe day was very warm, the king's child went out into the forest and\nsat down by the side of the cool fountain, and when she was bored she\ntook a golden ball, and threw it up on high and caught it, and this\nball was her favorite plaything.`\n\nfunc main() {\n fmt.Println(\"wrapped at 80:\")\n fmt.Println(wrap(frog, 80))\n fmt.Println(\"wrapped at 72:\")\n fmt.Println(wrap(frog, 72))\n}"} {"title": "World Cup group stage", "language": "Go from Kotlin", "task": "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. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. 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 plays all three other teams once. The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. 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:::* A win is worth three points.\n:::* A draw/tie is worth one point. \n:::* A loss is worth zero points.\n\n\n;Task:\n:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. \n:* Calculate the standings points for each team with each combination of outcomes. \n:* Show a histogram (graphical, 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. 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''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. Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "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}"} {"title": "Write float arrays to a text file", "language": "Go", "task": "Write two equal-sized numerical arrays 'x' and 'y' to \na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a \ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\nThe file should look like:\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "package main\n\nimport (\n \"fmt\"\n \"os\"\n)\n\nvar (\n x = []float64{1, 2, 3, 1e11}\n y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}\n\n xprecision = 3\n yprecision = 5\n)\n\nfunc main() {\n if len(x) != len(y) {\n fmt.Println(\"x, y different length\")\n return\n }\n f, err := os.Create(\"filename\")\n if err != nil {\n fmt.Println(err)\n return\n }\n for i := range x {\n fmt.Fprintf(f, \"%.*e, %.*e\\n\", xprecision-1, x[i], yprecision-1, y[i])\n }\n f.Close()\n}"} {"title": "Write language name in 3D ASCII", "language": "Go", "task": "Write/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\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar\n\n", "solution": "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}"} {"title": "Write to Windows event log", "language": "Go", "task": "Write script status to the Windows Event Log\n\n", "solution": "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}"} {"title": "Yellowstone sequence", "language": "Go", "task": "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 '''30''' 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:* Greatest common divisor.\n:* Plot coordinate pairs.\n\n\n;See also:\n:* The OEIS entry: A098550 The Yellowstone permutation.\n:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "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}"} {"title": "Zeckendorf number representation", "language": "Go", "task": "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* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "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}"} {"title": "Zero to the zero power", "language": "Go", "task": "Some computer programming languages are not exactly consistent (with other computer programming languages) \nwhen ''raising zero to the zeroth power'': 00\n\n\n;Task:\nShow the results of raising zero to the zeroth power.\n\n\nIf your computer language objects to '''0**0''' or '''0^0''' at compile time, 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.'''\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: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld(tm) entry: exponent laws.\n** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: The special case of zero to the zeroth power\n\n", "solution": "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}"} {"title": "Zhang-Suen thinning algorithm", "language": "Go", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "package main\n\nimport (\n \"bytes\"\n \"fmt\"\n \"strings\"\n)\n\nvar in = `\n00000000000000000000000000000000\n01111111110000000111111110000000\n01110001111000001111001111000000\n01110000111000001110000111000000\n01110001111000001110000000000000\n01111111110000001110000000000000\n01110111100000001110000111000000\n01110011110011101111001111011100\n01110001111011100111111110011100\n00000000000000000000000000000000`\n\nfunc main() {\n b := wbFromString(in, '1')\n b.zhangSuen()\n fmt.Println(b)\n}\n\nconst (\n white = 0\n black = 1\n)\n\ntype wbArray [][]byte // elements are white or black.\n\n// parameter blk is character to read as black. otherwise kinda rigid,\n// expects ascii, leading newline, no trailing newline,\n// takes color from low bit of character.\nfunc wbFromString(s string, blk byte) wbArray {\n lines := strings.Split(s, \"\\n\")[1:]\n b := make(wbArray, len(lines))\n for i, sl := range lines {\n bl := make([]byte, len(sl))\n for j := 0; j < len(sl); j++ {\n bl[j] = sl[j] & 1\n }\n b[i] = bl\n }\n return b\n}\n\n// rigid again, hard coded to output space for white, # for black,\n// no leading or trailing newline.\nvar sym = [2]byte{\n white: ' ',\n black: '#',\n}\n\nfunc (b wbArray) String() string {\n b2 := bytes.Join(b, []byte{'\\n'})\n for i, b1 := range b2 {\n if b1 > 1 {\n continue\n }\n b2[i] = sym[b1]\n }\n return string(b2)\n}\n\n// neighbor offsets\nvar nb = [...][2]int{\n 2: {-1, 0}, // p2 offsets\n 3: {-1, 1}, // ...\n 4: {0, 1},\n 5: {1, 1},\n 6: {1, 0},\n 7: {1, -1},\n 8: {0, -1},\n 9: {-1, -1}, // p9 offsets\n}\n\nfunc (b wbArray) reset(en []int) (rs bool) {\n var r, c int\n var p [10]byte\n\n readP := func() {\n for nx := 1; nx <= 9; nx++ {\n n := nb[nx]\n p[nx] = b[r+n[0]][c+n[1]]\n }\n }\n\n shiftRead := func() {\n n := nb[3]\n p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]\n n = nb[4]\n p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]\n n = nb[5]\n p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]\n }\n\n // returns \"A\", count of white->black transitions in circuit of neighbors\n // of an interior pixel b[r][c]\n countA := func() (ct byte) {\n bit := p[9]\n for nx := 2; nx <= 9; nx++ {\n last := bit\n bit = p[nx]\n if last == white {\n ct += bit\n }\n }\n return ct\n }\n\n // returns \"B\", count of black pixels neighboring interior pixel b[r][c].\n countB := func() (ct byte) {\n for nx := 2; nx <= 9; nx++ {\n ct += p[nx]\n }\n return ct\n }\n\n lastRow := len(b) - 1\n lastCol := len(b[0]) - 1\n\n mark := make([][]bool, lastRow)\n for r = range mark {\n mark[r] = make([]bool, lastCol)\n }\n\n for r = 1; r < lastRow; r++ {\n c = 1\n readP()\n for { // column loop\n m := false\n // test for failure of any of the five conditions,\n if !(p[1] == black) {\n goto markDone\n }\n if b1 := countB(); !(2 <= b1 && b1 <= 6) {\n goto markDone\n }\n if !(countA() == 1) {\n goto markDone\n }\n {\n e1, e2 := p[en[1]], p[en[2]]\n if !(p[en[0]]&e1&e2 == 0) {\n goto markDone\n }\n if !(e1&e2&p[en[3]] == 0) {\n goto markDone\n }\n }\n // no conditions failed, mark this pixel for reset\n m = true\n rs = true // and mark that image changes\n markDone:\n mark[r][c] = m\n c++\n if c == lastCol {\n break\n }\n shiftRead()\n }\n }\n if rs {\n for r = 1; r < lastRow; r++ {\n for c = 1; c < lastCol; c++ {\n if mark[r][c] {\n b[r][c] = white\n }\n }\n }\n }\n return rs\n}\n\nvar step1 = []int{2, 4, 6, 8}\nvar step2 = []int{4, 2, 8, 6}\n\nfunc (b wbArray) zhangSuen() {\n for {\n rs1 := b.reset(step1)\n rs2 := b.reset(step2)\n if !rs1 && !rs2 {\n break\n }\n }\n}"}