task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#C.2B.2B
C++
#include <iostream> #include <sstream>   int main() { int num;   std::istringstream("0123459") >> num; std::cout << num << std::endl; // prints 123459   std::istringstream("0123459") >> std::dec >> num; std::cout << num << std::endl; // prints 123459   std::istringstream("abcf123") >> std::hex >> num; std::cout << num << std::endl; // prints 180154659   std::istringstream("7651") >> std::oct >> num; std::cout << num << std::endl; // prints 4009   // binary not supported   return 0; }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Arturo
Arturo
loop 0..33 'i -> print [ pad as.binary i 6 pad as.octal i 2 pad to :string i 2 pad as.hex i 2 ]
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#AWK
AWK
$ awk '{printf("%d 0%o 0x%x\n",$1,$1,$1)}' 10 10 012 0xa 16 16 020 0x10 255 255 0377 0xff
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PowerShell
PowerShell
  function Get-NumberName { <# .SYNOPSIS Spells out a number in English. .DESCRIPTION Spells out a number in English in the range of 0 to 999,999,999. .NOTES The code for this function was copied (almost word for word) from the C# example on this page to show how similar Powershell is to C#. .PARAMETER Number One or more integers in the range of 0 to 999,999,999. .EXAMPLE Get-NumberName -Number 666 .EXAMPLE Get-NumberName 1, 234, 31337, 987654321 .EXAMPLE 1, 234, 31337, 987654321 | Get-NumberName #> [CmdletBinding()] [OutputType([string])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [ValidateRange(0,999999999)] [int[]] $Number )   Begin { [string[]]$incrementsOfOne = "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"   [string[]]$incrementsOfTen = "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"   [string]$millionName = "million" [string]$thousandName = "thousand" [string]$hundredName = "hundred" [string]$andName = "and"   function GetName([int]$i) { [string]$output = ""   if ($i -ge 1000000) { $remainder = $null $output += (ParseTriplet ([Math]::DivRem($i,1000000,[ref]$remainder))) + " " + $millionName $i = $remainder   if ($i -eq 0) { return $output } }   if ($i -ge 1000) { if ($output.Length -gt 0) { $output += ", " }   $remainder = $null $output += (ParseTriplet ([Math]::DivRem($i,1000,[ref]$remainder))) + " " + $thousandName $i = $remainder   if ($i -eq 0) { return $output } }   if ($output.Length -gt 0) { $output += ", " }   $output += (ParseTriplet $i)   return $output }   function ParseTriplet([int]$i) { [string]$output = ""   if ($i -ge 100) { $remainder = $null $output += $incrementsOfOne[([Math]::DivRem($i,100,[ref]$remainder))] + " " + $hundredName $i = $remainder   if ($i -eq 0) { return $output } }   if ($output.Length -gt 0) { $output += " " + $andName + " " }   if ($i -ge 20) { $remainder = $null $output += $incrementsOfTen[([Math]::DivRem($i,10,[ref]$remainder))] $i = $remainder   if ($i -eq 0) { return $output } }   if ($output.Length -gt 0) { $output += " " }   $output += $incrementsOfOne[$i]   return $output } } Process { foreach ($n in $Number) { [PSCustomObject]@{ Number = $n Name = GetName $n } } } }   1, 234, 31337, 987654321 | Get-NumberName  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Quackery
Quackery
[ 0 temp put [] 9 times [ i^ 1+ join ] dup [ shuffle 2dup != until ] [ dup echo cr 2dup != while [ $ "Reverse how many? " input $->n not iff drop again ] split dip reverse join 1 temp tally again ] drop cr say "That took " temp take echo say " reversals." ] is play ( --> )
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Vedit_macro_language
Vedit macro language
IT("Gen 0: ..###.##.#.#.#.#..#.....") // initial pattern #9 = Cur_Col   for (#8 = 1; #8 < 10; #8++) { // 10 generations Goto_Col(7) Reg_Empty(20) while (Cur_Col < #9-1) { if (Match("|{##|!#,#.#,|!###}")==0) { Reg_Set(20, "#", APPEND) } else { Reg_Set(20, ".", APPEND) } Char } EOL IN IT("Gen ") Num_Ins(#8, LEFT+NOCR) IT(": ") Reg_Ins(20) }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#JavaScript
JavaScript
const compose = (...fn) => (...x) => fn.reduce((a, b) => c => a(b(c)))(...x); const inv = b => !b; const arrJoin = str => arr => arr.join(str); const mkArr = (l, f) => Array(l).fill(f); const sumArr = arr => arr.reduce((a, b) => a + b, 0); const sumsTo = val => arr => sumArr(arr) === val; const zipper = arr => (p, c, i) => arr[i] ? [...p, c, arr[i]] : [...p, c]; const zip = (a, b) => a.reduce(zipper(b), []); const zipArr = arr => a => zip(a, arr); const hasInner = v => arr => arr.slice(1, -1).indexOf(v) >= 0; const choose = (even, odd) => n => n % 2 === 0 ? even : odd; const toBin = f => arr => arr.reduce( (p, c, i) => [...p, ...mkArr(c, f(i))], []);     const looper = (arr, max, acc = [[...arr]], idx = 0) => { if (idx !== arr.length) { const b = looper([...arr], max, acc, idx + 1)[0]; if (b[idx] !== max) { b[idx] = b[idx] + 1; acc.push(looper([...b], max, acc, idx)[0]); } } return [arr, acc]; };   const gapPerms = (grpSize, numGaps, minVal = 0) => { const maxVal = numGaps - grpSize * minVal + minVal; return maxVal <= 0 ? (grpSize === 2 ? [[0]] : []) : looper(mkArr(grpSize, minVal), maxVal)[1]; }   const test = (cells, ...blocks) => { const grpSize = blocks.length + 1; const numGaps = cells - sumArr(blocks);   // Filter functions const sumsToTrg = sumsTo(numGaps); const noInnerZero = compose(inv, hasInner(0));   // Output formatting const combine = zipArr([...blocks]); const choices = toBin(choose(0, 1)); const output = compose(console.log, arrJoin(''), choices, combine);   console.log(`\n${cells} cells. Blocks: ${blocks}`); gapPerms(grpSize, numGaps) .filter(noInnerZero) .filter(sumsToTrg) .map(output); };   test(5, 2, 1); test(5); test(5, 5); test(5, 1, 1, 1); test(10, 8); test(15, 2, 3, 2, 3); test(10, 4, 3); test(5, 2, 3);  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#J
J
NB. unique list of all y faced dice udice=: {{ 1+~./:~"1 (#: ,@i.)y#y }}   NB. which dice are less than which other dice? NB. y here is a result of udice lthan=: {{ 0>*@(+/)@,@:*@(-/)"1/~ y}}   NB. "less than loops" length x, for y sided non-transitive dice cycles=: {{ ud=. udice y lt=. lthan ud extend=. [:; lt{{< y,"1 0 y-.~I.m{~{:y }}"1 r=. ; extend^:(x-1)&.> i.#ud ud{~ ~.((i.<./)|.])"1 r #~ lt{~({:,&.>{.)|:r }}
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Java
Java
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream;   public class Main { private static List<List<Integer>> fourFaceCombos() { List<List<Integer>> res = new ArrayList<>(); Set<Integer> found = new HashSet<>();   for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { for (int k = 1; k <= 4; k++) { for (int l = 1; l <= 4; l++) { List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());   int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1); if (found.add(key)) { res.add(c); } } } } }   return res; }   private static int cmp(List<Integer> x, List<Integer> y) { int xw = 0; int yw = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x.get(i) > y.get(j)) { xw++; } else if (x.get(i) < y.get(j)) { yw++; } } } return Integer.compare(xw, yw); }   private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) { int c = cs.size(); List<List<List<Integer>>> res = new ArrayList<>();   for (int i = 0; i < c; i++) { for (int j = 0; j < c; j++) { if (cmp(cs.get(i), cs.get(j)) == -1) { for (List<Integer> kl : cs) { if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) { res.add(List.of(cs.get(i), cs.get(j), kl)); } } } } }   return res; }   private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) { int c = cs.size(); List<List<List<Integer>>> res = new ArrayList<>();   for (int i = 0; i < c; i++) { for (int j = 0; j < c; j++) { if (cmp(cs.get(i), cs.get(j)) == -1) { for (int k = 0; k < cs.size(); k++) { if (cmp(cs.get(j), cs.get(k)) == -1) { for (List<Integer> ll : cs) { if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) { res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll)); } } } } } } }   return res; }   public static void main(String[] args) { List<List<Integer>> combos = fourFaceCombos(); System.out.printf("Number of eligible 4-faced dice: %d%n", combos.size()); System.out.println();   List<List<List<Integer>>> it3 = findIntransitive3(combos); System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size()); for (List<List<Integer>> a : it3) { System.out.println(a); } System.out.println();   List<List<List<Integer>>> it4 = findIntransitive4(combos); System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size()); for (List<List<Integer>> a : it4) { System.out.println(a); } } }
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
F ncsub(seq, s = 0) I seq.empty R I s >= 3 {[[Int]()]} E [[Int]]() E V x = seq[0.<1] V xs = seq[1..] V p2 = s % 2 V p1 = !p2 R ncsub(xs, s + p1).map(ys -> @x + ys) [+] ncsub(xs, s + p2)   print(ncsub(Array(1..3))) print(ncsub(Array(1..4))) print(ncsub(Array(1..5)))
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Common_Lisp
Common Lisp
(parse-integer "abc" :radix 20 :junk-allowed t) ; => 4232
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#D
D
import std.stdio, std.conv;   void main() { immutable text = "100"; foreach (base; 2 .. 21) writefln("String '%s' in base %d is  %d in base 10" , text, base, to!int(text, base)); }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#BBC_BASIC
BBC BASIC
REM STR$ converts to a decimal string: PRINT STR$(0) PRINT STR$(123456789) PRINT STR$(-987654321)   REM STR$~ converts to a hexadecimal string: PRINT STR$~(43981) PRINT STR$~(-1)
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Bc
Bc
  for(i=1;i<10;i++) { obase=10; print i," " obase=8; print i," " obase=3; print i," " obase=2; print i print "\n" }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#C
C
#include <stdio.h>   int main() { int i;   for(i=1; i <= 33; i++) printf("%6d %6x %6o\n", i, i, i);   return 0; }
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Prolog
Prolog
  :- module(spell, [spell/2]).   % % spell numbers up to the nonillions. %   ones(1, "one"). ones(2, "two"). ones(3, "three"). ones(4, "four"). ones( 5, "five"). ones(6, "six"). ones(7, "seven"). ones(8, "eight"). ones(9, "nine"). ones(10, "ten").   ones(11, "eleven"). ones(12, "twelve"). ones(13, "thirteen"). ones(14, "fourteen"). ones(15, "fifteen"). ones(16, "sixteen"). ones(17, "seventeen"). ones(18, "eighteen"). ones(19, "nineteen").   tens(2, "twenty"). tens(3, "thirty"). tens(4, "forty"). tens(5, "fifty"). tens(6, "sixty"). tens(7, "seventy"). tens(8, "eighty"). tens(9, "ninety").   group( 1, "thousand"). group( 2, "million"). group(3, "bilion"). group( 4, "trillion"). group( 5, "quadrillion"). group(6, "quintillion"). group( 7, "sextilion"). group( 8, "septillion"). group(9, "octillion"). group(10, "nonillion"). group(11, "decillion").   spellgroup(N, G) :- G is floor(log10(N) / 3).   spell(N, S) :- N < 0, !, NegN is -N, spell(NegN, S0), string_concat("negative ", S0, S). spell(0, "zero") :- !. spell(N, S) :- between(1, 19, N), ones(N, S), !. spell(N, S) :- N < 100, !, divmod(N, 10, Tens, Ones), tens(Tens, StrTens), ones_part(Ones, StrOnes), string_concat(StrTens, StrOnes, S). spell(N, S) :- N < 1000, !, divmod(N, 100, Hundreds, Tens), ones(Hundreds, H), string_concat(H, " hundred", StrHundreds), tens_part(Tens, StrTens), string_concat(StrHundreds, StrTens, S). spell(N, S) :- spellgroup(N, G), group(G, StrG), M is 10**(3*G), divmod(N, M, Group, Rest), spell(Group, S1), spell_remaining(Rest, S2), format(string(S), "~w ~w~w", [S1, StrG, S2]).   ones_part(0, "") :- !. ones_part(N, S) :- ones(N, StrN), string_concat("-", StrN, S).   tens_part(0, "") :- !. tens_part(N, S) :- spell(N, Tens), string_concat(" and ", Tens, S).   spell_remaining(0, "") :- !. spell_remaining(N, S) :- spell(N, Rest), string_concat(", ", Rest, S).  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#R
R
reversalGame <- function(){ cat("Welcome to the Number Reversal Game! \n") cat("Sort the numbers into ascending order by repeatedly \n", "reversing the first n digits, where you specify n. \n \n", sep="")   # Generate a list that's definitely not in ascending order, per instuctions data <- sample(1:9, 9) while (all(data == 1:9)){ cat("What were the chances...? \n") data <- sample(1:9, 9) } trials <- 0   # Play the game while (any(data != 1:9)){ trials <- trials + 1 cat("Trial", sprintf("%02d", trials), " # ", data, " # ") answer <- readline(paste("Flip how many? ")) data[1:answer] <- data[answer:1] }   # Victory! cat("Well done. You needed", trials, "flips. \n") }
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module CellularAutomata   Private Enum PetriStatus Active Stable Dead End Enum   Function Main(ByVal cmdArgs() As String) As Integer If cmdArgs.Length = 0 Or cmdArgs.Length > 1 Then Console.WriteLine("Command requires string of either 1s and 0s or #s and _s.") Return 1 End If   Dim petriDish As BitArray   Try petriDish = InitialisePetriDish(cmdArgs(0)) Catch ex As Exception Console.WriteLine(ex.Message) Return 1 End Try   Dim generation As Integer = 0 Dim ps As PetriStatus = PetriStatus.Active   Do While True If ps = PetriStatus.Stable Then Console.WriteLine("Sample stable after {0} generations.", generation - 1) Exit Do Else Console.WriteLine("{0}: {1}", generation.ToString("D3"), BuildDishString(petriDish)) If ps = PetriStatus.Dead Then Console.WriteLine("Sample dead after {0} generations.", generation) Exit Do End If End If   ps = GetNextGeneration(petriDish) generation += 1 Loop   Return 0 End Function   Private Function InitialisePetriDish(ByVal Sample As String) As BitArray Dim PetriDish As New BitArray(Sample.Length) Dim dead As Boolean = True   For i As Integer = 0 To Sample.Length - 1 Select Case Sample.Substring(i, 1) Case "1", "#" PetriDish(i) = True dead = False Case "0", "_" PetriDish(i) = False Case Else Throw New Exception("Illegal value in string position " & i) Return Nothing End Select Next   If dead Then Throw New Exception("Entered sample is dead.") Return Nothing End If   Return PetriDish End Function   Private Function GetNextGeneration(ByRef PetriDish As BitArray) As PetriStatus Dim petriCache = New BitArray(PetriDish.Length) Dim neighbours As Integer Dim stable As Boolean = True Dim dead As Boolean = True   For i As Integer = 0 To PetriDish.Length - 1 neighbours = 0 If i > 0 AndAlso PetriDish(i - 1) Then neighbours += 1 If i < PetriDish.Length - 1 AndAlso PetriDish(i + 1) Then neighbours += 1   petriCache(i) = (PetriDish(i) And neighbours = 1) OrElse (Not PetriDish(i) And neighbours = 2) If PetriDish(i) <> petriCache(i) Then stable = False If petriCache(i) Then dead = False Next   PetriDish = petriCache   If dead Then Return PetriStatus.Dead If stable Then Return PetriStatus.Stable Return PetriStatus.Active   End Function   Private Function BuildDishString(ByVal PetriDish As BitArray) As String Dim sw As New StringBuilder() For Each b As Boolean In PetriDish sw.Append(IIf(b, "#", "_")) Next   Return sw.ToString() End Function End Module
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Wart
Wart
def (gens n l) prn l repeat n zap! gen l prn l   def (gen l) with (a nil b nil c l.0) collect nil # won't insert paren without second token each x cdr.l shift! a b c x yield (next a b c) yield (next b c nil)   def (next a b c) # next state of b given neighbors a and c if (and a c) not.b (or a c) b
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Julia
Julia
minsized(arr) = join(map(x->"#"^x, arr), ".") minlen(arr) = sum(arr) + length(arr) - 1   function sequences(blockseq, numblanks) if isempty(blockseq) return ["." ^ numblanks] elseif minlen(blockseq) == numblanks return minsized(blockseq) else result = Vector{String}() allbuthead = blockseq[2:end] for leftspace in 0:(numblanks - minlen(blockseq)) header = "." ^ leftspace * "#" ^ blockseq[1] * "." rightspace = numblanks - length(header) if isempty(allbuthead) push!(result, rightspace <= 0 ? header[1:numblanks] : header * "." ^ rightspace) elseif minlen(allbuthead) == rightspace push!(result, header * minsized(allbuthead)) else map(x -> push!(result, header * x), sequences(allbuthead, rightspace)) end end end result end   function nonoblocks(bvec, len) println("With blocks $bvec and $len cells:") len < minlen(bvec) ? println("No solution") : for seq in sequences(bvec, len) println(seq) end end   nonoblocks([2, 1], 5) nonoblocks(Vector{Int}([]), 5) nonoblocks([8], 10) nonoblocks([2, 3, 2, 3], 15) nonoblocks([2, 3], 5)  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Julia
Julia
import Base.>, Base.< using Memoize, Combinatorics   struct Die name::String faces::Vector{Int} end   """ Compares two die returning 1, -1 or 0 for operators >, < == """ function cmpd(die1, die2) # Numbers of times one die wins against the other for all combinations # cmp(x, y) is `(x > y) - (y > x)` to return 1, 0, or -1 for numbers tot = [0, 0, 0] for d in Iterators.product(die1.faces, die2.faces) tot[2 + (d[1] > d[2]) - (d[2] > d[1])] += 1 end return (tot[3] > tot[1]) - (tot[1] > tot[3]) end   Base.:>(d1::Die, d2::Die) = cmpd(d1, d2) == 1 Base.:<(d1::Die, d2::Die) = cmpd(d1, d2) == -1   """ True iff ordering of die in dice is non-transitive """ isnontrans(dice) = all(x -> x[1] < x[2], zip(dice[1:end-1], dice[2:end])) && dice[1] > dice[end]   findnontrans(alldice, n=3) = [perm for perm in permutations(alldice, n) if isnontrans(perm)]   function possible_dice(sides, mx) println("\nAll possible 1..$mx $sides-sided dice") dice = [Die("D $(n+1)", [i for i in f]) for (n, f) in enumerate(Iterators.product(fill(1:mx, sides)...))] println(" Created $(length(dice)) dice") println(" Remove duplicate with same bag of numbers on different faces") uniquedice = collect(values(Dict(sort(d.faces) => d for d in dice))) println(" Return $(length(uniquedice)) filtered dice") return uniquedice end   """ Compares two die returning their relationship of their names as a string """ function verbosecmp(die1, die2) # Numbers of times one die wins against the other for all combinations win1 = sum(p[1] > p[2] for p in Iterators.product(die1.faces, die2.faces)) win2 = sum(p[2] > p[1] for p in Iterators.product(die1.faces, die2.faces)) n1, n2 = die1.name, die2.name return win1 > win2 ? "$n1 > $n2" : win1 < win2 ? "$n1 < $n2" : "$n1 = $n2" end   """ Dice cmp function with verbose extra checks """ function verbosedicecmp(dice) return join([[verbosecmp(x, y) for (x, y) in zip(dice[1:end-1], dice[2:end])]; [verbosecmp(dice[1], dice[end])]], ", ") end   function testnontransitivedice(faces) dice = possible_dice(faces, faces) for N in (faces < 5 ? [3, 4] : [3]) # length of non-transitive group of dice searched for nontrans = unique(map(x -> sort!(x, lt=(x, y)->x.name<y.name), findnontrans(dice, N))) println("\n Unique sorted non_transitive length-$N combinations found: $(length(nontrans))") for list in (faces < 5 ? nontrans : [nontrans[end]]) println(faces < 5 ? "" : " Only printing last example for brevity") for (i, die) in enumerate(list) println(" $die$(i < N - 1 ? "," : "]")") end end if !isempty(nontrans) println("\n More verbose comparison of last non_transitive result:") println(" ", verbosedicecmp(nontrans[end])) end println("\n ====") end end   @time testnontransitivedice(3) @time testnontransitivedice(4) @time testnontransitivedice(5) @time testnontransitivedice(6)  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Kotlin
Kotlin
fun fourFaceCombos(): List<Array<Int>> { val res = mutableListOf<Array<Int>>() val found = mutableSetOf<Int>() for (i in 1..4) { for (j in 1..4) { for (k in 1..4) { for (l in 1..4) { val c = arrayOf(i, j, k, l) c.sort() val key = 64 * (c[0] - 1) + 16 * (c[1] - 1) + 4 * (c[2] - 1) + (c[3] - 1) if (!found.contains(key)) { found.add(key) res.add(c) } } } } } return res }   fun cmp(x: Array<Int>, y: Array<Int>): Int { var xw = 0 var yw = 0 for (i in 0 until 4) { for (j in 0 until 4) { if (x[i] > y[j]) { xw++ } else if (y[j] > x[i]) { yw++ } } } if (xw < yw) { return -1 } if (xw > yw) { return 1 } return 0 }   fun findIntransitive3(cs: List<Array<Int>>): List<Array<Array<Int>>> { val c = cs.size val res = mutableListOf<Array<Array<Int>>>()   for (i in 0 until c) { for (j in 0 until c) { if (cmp(cs[i], cs[j]) == -1) { for (k in 0 until c) { if (cmp(cs[j], cs[k]) == -1 && cmp(cs[k], cs[i]) == -1) { res.add(arrayOf(cs[i], cs[j], cs[k])) } } } } }   return res }   fun findIntransitive4(cs: List<Array<Int>>): List<Array<Array<Int>>> { val c = cs.size val res = mutableListOf<Array<Array<Int>>>()   for (i in 0 until c) { for (j in 0 until c) { if (cmp(cs[i], cs[j]) == -1) { for (k in 0 until c) { if (cmp(cs[j], cs[k]) == -1) { for (l in 0 until c) { if (cmp(cs[k], cs[l]) == -1 && cmp(cs[l], cs[i]) == -1) { res.add(arrayOf(cs[i], cs[j], cs[k], cs[l])) } } } } } } }   return res }   fun main() { val combos = fourFaceCombos() println("Number of eligible 4-faced dice: ${combos.size}") println()   val it3 = findIntransitive3(combos) println("${it3.size} ordered lists of 3 non-transitive dice found, namely:") for (a in it3) { println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") }) } println()   val it4 = findIntransitive4(combos) println("${it4.size} ordered lists of 4 non-transitive dice found, namely:") for (a in it4) { println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") }) } }
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Non_Continuous is type Sequence is array (Positive range <>) of Integer; procedure Put_NCS ( Tail : Sequence; -- To generate subsequences of Head : Sequence := (1..0 => 1); -- Already generated Contiguous : Boolean := True -- It is still continuous ) is begin if not Contiguous and then Head'Length > 1 then for I in Head'Range loop Put (Integer'Image (Head (I))); end loop; New_Line; end if; if Tail'Length /= 0 then declare New_Head : Sequence (Head'First..Head'Last + 1); begin New_Head (Head'Range) := Head; for I in Tail'Range loop New_Head (New_Head'Last) := Tail (I); Put_NCS ( Tail => Tail (I + 1..Tail'Last), Head => New_Head, Contiguous => Contiguous and then (I = Tail'First or else Head'Length = 0) ); end loop; end; end if; end Put_NCS; begin Put_NCS ((1,2,3)); New_Line; Put_NCS ((1,2,3,4)); New_Line; Put_NCS ((1,2,3,4,5)); New_Line; end Test_Non_Continuous;
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#11l
11l
print(Int(‘1A’, radix' 16)) // prints the integer 26
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#E
E
? __makeInt("200", 16) # value: 512   ? __makeInt("200", 10) # value: 200
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Elixir
Elixir
iex(1)> String.to_integer("1000") 1000 iex(2)> String.to_integer("1000",2) 8 iex(3)> String.to_integer("1000",8) 512 iex(4)> String.to_integer("1000",16) 4096 iex(5)> String.to_integer("ffff",16) 65535
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#C.23
C#
  using System;   namespace NonDecimalRadicesOutput { class Program { static void Main(string[] args) { for (int i = 0; i < 42; i++) { string binary = Convert.ToString(i, 2); string octal = Convert.ToString(i, 8); string hexadecimal = Convert.ToString(i, 16); Console.WriteLine(string.Format("Decimal: {0}, Binary: {1}, Octal: {2}, Hexadecimal: {3}", i, binary, octal, hexadecimal)); }   Console.ReadKey(); } } }  
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PureBasic
PureBasic
DataSection numberNames: ;small Data.s "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" Data.s "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ;tens Data.s "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" ;big, non-Chuquet system Data.s "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion" Data.s "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion" Data.s "tredecillion" EndDataSection   Procedure.s numberWords(number.s) ;handles integers from -1E45 to +1E45 Static isInitialized = #False Static Dim small.s(19) Static Dim tens.s(9) Static Dim big.s(14)   If Not isInitialized Restore numberNames For i = 1 To 19 Read.s small(i) Next For i = 2 To 9 Read.s tens(i) Next For i = 1 To 14 Read.s big(i) Next isInitialized = #True EndIf   For i = 1 To Len(number) If Not FindString("- 0123456789", Mid(number,i,1), 1) number = Left(number, i - 1) ;trim number to the last valid character Break ;exit loop EndIf Next   Protected IsNegative = #False number = Trim(number) If Left(number,1) = "-" IsNegative = #True number = Trim(Mid(number, 2)) EndIf   If CountString(number, "0") = Len(number) ProcedureReturn "zero" EndIf   If Len(number) > 45 ProcedureReturn "Number is too big!" EndIf   Protected num.s = number, output.s, unit, unitOutput.s, working   Repeat working = Val(Right(num, 2)) unitOutput = "" Select working Case 1 To 19 unitOutput = small(working) Case 20 To 99 If working % 10 unitOutput = tens(working / 10) + "-" + small(working % 10) Else unitOutput = tens(working / 10) EndIf EndSelect   working = Val(Right(num, 3)) / 100 If working If unitOutput <> "" unitOutput = small(working) + " hundred " + unitOutput Else unitOutput = small(working) + " hundred" EndIf EndIf   If unitOutput <> "" And unit > 0 unitOutput + " " + big(unit) If output <> "" unitOutput + ", " EndIf EndIf   output = unitOutput + output   If Len(num) > 3 num = Left(num, Len(num) - 3) unit + 1 Else Break ;exit loop EndIf ForEver   If IsNegative output = "negative " + output EndIf   ProcedureReturn output EndProcedure   Define n$ If OpenConsole() Repeat Repeat Print("Give me an integer (or q to quit)! ") n$ = Input() Until n$ <> ""   If Left(Trim(n$),1) = "q" Break ;exit loop EndIf PrintN(numberWords(n$)) ForEver CloseConsole() EndIf  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Racket
Racket
#lang racket (let loop ([nums (range 1 10)] [n 0]) (cond [(apply < nums) (if (zero? n) (loop (shuffle nums) 0) (printf "Done in ~s steps.\n" n))] [else (printf "Step #~s: ~s\nFlip how many? " n nums) (define-values (l r) (split-at nums (read))) (loop (append (reverse l) r) (add1 n))]))
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Wren
Wren
var trans = "___#_##_"   var v = Fn.new { |cell, i| (cell[i] != "_") ? 1 : 0 }   var evolve = Fn.new { |cell, backup| var len = cell.count - 2 var diff = 0 for (i in 1...len) { /* use left, self, right as binary number bits for table index */ backup[i] = trans[v.call(cell, i - 1) * 4 + v.call(cell, i) * 2 + v.call(cell, i + 1)] diff = diff + ((backup[i] != cell[i]) ? 1 : 0) } cell.clear() cell.addAll(backup) return diff != 0 }   var c = "_###_##_#_#_#_#__#__".toList var b = "____________________".toList while(true) { System.print(c[1..-1].join()) if (!evolve.call(c,b)) break }
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This 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). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#11l
11l
F gen_row(w, s) ‘Create all patterns of a row or col that match given runs.’ F gen_seg([[Int]] o, Int sp) -> [[Int]] I o.empty R [[2] * sp] [[Int]] r L(x) 1 .< sp - o.len + 2 L(tail) @gen_seg(o[1..], sp - x) r [+]= [2] * x [+] o[0] [+] tail R r   R gen_seg(s.map(i -> [1] * i), w + 1 - sum(s)).map(x -> x[1..])   F deduce(hr, vr) ‘Fix inevitable value of cells, and propagate.’ F allowable(row) R row.reduce((a, b) -> zip(a, b).map((x, y) -> x [|] y))   F fits(a, b) R all(zip(a, b).map((x, y) -> x [&] y))   V (w, h) = (vr.len, hr.len) V rows = hr.map(x -> gen_row(@w, x)) V cols = vr.map(x -> gen_row(@h, x)) V can_do = rows.map(allowable)   V mod_rows = Set[Int]() V mod_cols = Set(0 .< w)   F fix_col(n) ‘See if any value in a given column is fixed; if so, mark its corresponding row for future fixup.’ V c = @can_do.map(x -> x[@n]) @cols[n] = @cols[n].filter(x -> @@fits(x, @c)) L(x) @allowable(@cols[n]) V i = L.index I x != @can_do[i][n] @mod_rows.add(i) @can_do[i][n] [&]= x   F fix_row(n) ‘Ditto, for rows.’ V c = @can_do[n] @rows[n] = @rows[n].filter(x -> @@fits(x, @c)) L(x) @allowable(@rows[n]) V i = L.index I x != @can_do[n][i] @mod_cols.add(i) @can_do[n][i] [&]= x   F show_gram(m) L(x) m print(x.map(i -> ‘x#.?’[i]).join(‘ ’)) print()   L !mod_cols.empty L(i) mod_cols fix_col(i) mod_cols.clear() L(i) mod_rows fix_row(i) mod_rows.clear()   I all(multiloop((0 .< w), (0 .< h), (j, i) -> @can_do[i][j] C (1, 2))) print(‘Solution would be unique’) E print(‘Solution may not be unique, doing exhaustive search:’)   V out = [[Int]()] * h   F try_all(Int n) -> Int I n >= @h L(j) 0 .< @w I @out.map(x -> x[@j]) !C @cols[j] R 0 @show_gram(@out) R 1 V sol = 0 L(x) @rows[n] @out[n] = x sol += @try_all(n + 1) R sol   V n = try_all(0) I n == 0 print(‘No solution.’) E I n == 1 print(‘Unique solution.’) E print(n‘ solutions.’) print()   F solve(p, show_runs = 1B) [[[Int]]] s L(l) p.split("\n") s [+]= l.split(‘ ’).map(w -> w.map(c -> c.code - ‘A’.code + 1)) I show_runs print(‘Horizontal runs: ’s[0]) print(‘Vertical runs: ’s[1]) deduce(s[0], s[1])   L(p) File(‘nonogram_problems.txt’).read().split("\n\n") solve(p)   print(‘Extra example not solvable by deduction alone:’) solve("B B A A\nB B A A")   print(‘Extra example where there is no solution:’) solve("B A A\nA A A")
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Kotlin
Kotlin
// version 1.2.0   fun printBlock(data: String, len: Int) { val a = data.toCharArray() val sumChars = a.map { it.toInt() - 48 }.sum() println("\nblocks ${a.asList()}, cells $len") if (len - sumChars <= 0) { println("No solution") return } val prep = a.map { "1".repeat(it.toInt() - 48) } for (r in genSequence(prep, len - sumChars + 1)) println(r.substring(1)) }   fun genSequence(ones: List<String>, numZeros: Int): List<String> { if (ones.isEmpty()) return listOf("0".repeat(numZeros)) val result = mutableListOf<String>() for (x in 1 until numZeros - ones.size + 2) { val skipOne = ones.drop(1) for (tail in genSequence(skipOne, numZeros - x)) { result.add("0".repeat(x) + ones[0] + tail) } } return result }   fun main(args: Array<String>) { printBlock("21", 5) printBlock("", 5) printBlock("8", 10) printBlock("2323", 15) printBlock("23", 5) }
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#MiniZinc
MiniZinc
  %Non transitive dice. Nigel Galloway, September 14th., 2020 int: die; int: faces; set of int: values; predicate pN(array[1..faces] of var values: n, array[1..faces] of var values: g) = sum(i in 1..faces,j in 1..faces)(if n[i]<g[j] then 1 elseif n[i]>g[j] then -1 else 0 endif)>0; predicate pG(array[1..faces] of var values: n) = forall(g in 1..faces-1)(n[g]<=n[g+1]); array[1..die,1..faces] of var values: g; constraint forall(n in 1..die)(pG(g[n,1..faces])); constraint forall(n in 1..die-1)(pN(g[n,1..faces],g[n+1,1..faces])); constraint pN(g[die,1..faces],g[1,1..faces]); output[join(" ",[show(g[n,1..faces])++"<"++show(g[n+1,1..faces]) | n in 1..die-1])," "++show(g[die,1..faces])++">"++show(g[1,1..faces])];  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Nim
Nim
  import algorithm, sequtils, sets, strformat import itertools   type Die = object name: string faces: seq[int]     #################################################################################################### # Die functions.     func `$`(die: Die): string = ## Return the string representation of a Die. &"({die.name}: {($die.faces)[1..^1]})"     func cmp(die1, die2: Die): int = ## Compare two die returning 1, -1 or 0 for operators >, < ==. var tot: array[3, int] for d in product(die1.faces, die2.faces): inc tot[1 + ord(d[1] < d[0]) - ord(d[0] < d[1])] result = ord(tot[0] < tot[2]) - ord(tot[2] < tot[0])     func verboseCmp(die1, die2: Die): string = ## Compare tow die returning a string. var win1, win2 = 0 for (d1, d2) in product(die1.faces, die2.faces): inc win1, ord(d1 > d2) inc win2, ord(d2 > d1) result = if win1 > win2: &"{die1.name} > {die2.name}" elif win1 < win2: &"{die1.name} < {die2.name}" else: &"{die1.name} = {die2.name}"     func `>`(die1, die2: Die): bool = cmp(die1, die2) > 0 func `<=`(die1, die2: Die): bool = cmp(die1, die2) <= 0     #################################################################################################### # Added a permutation iterator as that of "itertools" doesn't allow to specify the length.     iterator permutations[T](values: openArray[T]; r: int): seq[T] {.closure} = ## Yield permutations of length "r" with elements taken from "values". let n = values.len if r > n: return var indices = toSeq(0..<n) var cycles = toSeq(countdown(n, n - r + 1)) var perm = values[0..<r] yield perm if n == 0: return while true: var exit = true for i in countdown(r - 1, 0): dec cycles[i] if cycles[i] == 0: discard indices.rotateLeft(i..indices.high, 1) cycles[i] = n - i else: let j = cycles[i] swap indices[i], indices[^j] for iperm, ivalues in indices[0..<r]: perm[iperm] = values[ivalues] yield perm exit = false break if exit: return     #################################################################################################### # Dice functions.     func isNonTrans(dice: openArray[Die]): bool = ## Return true if ordering of die in dice is non-transitive. for i in 1..dice.high: if dice[i] <= dice[i-1]: return false result = dice[0] > dice[^1]     func findNonTrans(allDice: openArray[Die]; n = 3): seq[seq[Die]] = ## Return the list of non-transitive dice. for perm in permutations(allDice, n): if perm.isNontrans: result.add perm     proc possibleDice(sides, maxval: Positive): seq[Die] = ## Return the list of possible dice with given number of sides and maximum value.   echo &"All possible 1..{maxval} {sides}-sided dice." var dice: seq[Die] var n = 1 for faces in product(toSeq(1..maxval), repeat = sides): dice.add Die(name: &"D{n}", faces: faces) inc n echo &" Created {dice.len} dice." echo " Remove duplicate with same bag of numbers on different faces." var found: HashSet[seq[int]] for d in dice: let count = sorted(d.faces) if count notin found: found.incl count result.add d echo &" Return {result.len} filtered dice."     func verboseDiceCmp(dice: openArray[Die]): string = ## Return the verbose comparison of dice. for i in 1..dice.high: result.add verboseCmp(dice[i-1], dice[i]) & ", " result.add verboseCmp(dice[0], dice[^1])     #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   let dice = possibleDice(sides = 4, maxval = 4) for n in [3, 4]: let nonTrans = dice.findNonTrans(n) echo &"\n Non-transitive length-{n} combinations found: {nonTrans.len}." for list in nonTrans: echo "" for i, die in list: echo " ", if i == 0: '[' else: ' ', die, if i == list.high: "]" else: "," if nonTrans.len != 0: echo &"\n More verbose comparison of last non-transitive result:" echo " ", verboseDiceCmp(nonTrans[^1]) echo "\n ===="
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_68
ALGOL 68
PROC test non continuous = VOID: BEGIN MODE SEQMODE = CHAR; MODE SEQ = [1:0]SEQMODE; MODE YIELDSEQ = PROC(SEQ)VOID;   PROC gen ncs = ( SEQ tail, # To generate subsequences of # SEQ head, # Already generated # BOOL contiguous,# It is still continuous # YIELDSEQ yield ) VOID: BEGIN IF NOT contiguous ANDTH UPB head > 1 THEN yield (head) FI; IF UPB tail /= 0 THEN [UPB head+1]SEQMODE new head; new head [:UPB head] := head; FOR i TO UPB tail DO new head [UPB new head] := tail [i]; gen ncs ( tail[i + 1:UPB tail], new head, contiguous ANDTH (i = LWB tail OREL UPB head = 0), yield ) OD FI END # put ncs #;   # FOR SEQ seq IN # gen ncs(("a","e","i","o","u"), (), TRUE, # ) DO ( # ## (SEQ seq)VOID: print((seq, new line)) # OD # ) END; test non continuous
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#8086_Assembly
8086 Assembly
mov ah,02h mov al,00h ;this is the unpacked encoding of octal "20" aka 10 in hexadecimal, 16 in decimal. Ignore the leading zeroes. byte 0D5h,08h ;most assemblers don't allow you to encode a base so we have to inline the bytecode.
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Erlang
Erlang
<12> erlang:list_to_integer("ffff", 17). 78300
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#F.23
F#
let value = "100" let fromBases = [ 2; 8; 10; 16 ] let values = Seq.initInfinite (fun i -> value) Seq.zip fromBases (Seq.zip values fromBases |> Seq.map (System.Convert.ToInt32)) |> Seq.iter ( fun (fromBase, valueFromBaseX) -> printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX)
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#C.2B.2B
C++
#include <iostream> #include <iomanip>   int main() { for (int i = 0; i <= 33; i++) std::cout << std::setw(6) << std::dec << i << " " << std::setw(6) << std::hex << i << " " << std::setw(6) << std::oct << i << std::endl;   return 0; }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Clojure
Clojure
(Integer/toBinaryString 25) ; returns "11001" (Integer/toOctalString 25) ; returns "31" (Integer/toHexString 25) ; returns "19"   (dotimes [i 20] (println (Integer/toHexString i)))
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Python
Python
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")]   def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n)   def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num   def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e]   def base1000_rev(n): # generates the value of the digits of n in base 1000 # (i.e. 3-digit chunks), in reverse. while n != 0: n, r = divmod(n, 1000) yield r   def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)   if __name__ == '__main__': # examples for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('')   n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Raku
Raku
repeat while [<] my @jumbled-list { @jumbled-list = (1..9).pick(*) }   my $turn = 0; repeat until [<] @jumbled-list { my $d = prompt $turn.=succ.fmt('%2d: ') ~ @jumbled-list ~ " - Flip how many digits? " or exit; @jumbled-list[^$d] .= reverse; }   say " @jumbled-list[]"; say "You won in $turn turns.";
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#XPL0
XPL0
code ChOut=8, CrLf=9; int Gen, Now, New, I; [Now:= $076A_A400; for Gen:= 1 to 10 do [for I:= 31 downto 0 do ChOut(0, if Now & 1<<I then ^# else ^_); CrLf(0); New:= 0; for I:= 30 downto 1 do case Now>>(I-1) & 7 of %011, %101, %110: New:= New ! 1<<I other; Now:= New; ]; ]
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Yabasic
Yabasic
10 n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT 20 FOR k=1 TO n 30 FOR j=1 TO w 40 IF x(j) THEN PRINT "#"; ELSE PRINT "_"; END IF 50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0 END IF 60 NEXT:PRINT 70 FOR j=1 TO w:x(j)=x2(j):NEXT 80 NEXT 90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This 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). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } }   static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); }   static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } }   static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; }   static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } }   static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } }   static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } }   static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); }   static string Spaced(this IEnumerable<char> s) => string.Join(" ", s);   struct BitSet //Unused functionality elided. { public static BitSet Empty => default; private readonly int bits; public int Value => bits;   private BitSet(int bits) => this.bits = bits;   public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2);   public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); }   }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Lua
Lua
local examples = { {5, {2, 1}}, {5, {}}, {10, {8}}, {15, {2, 3, 2, 3}}, {5, {2, 3}}, }   function deep (blocks, iBlock, freedom, str) if iBlock == #blocks then -- last for takenFreedom = 0, freedom do print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreedom)) total = total + 1 end else for takenFreedom = 0, freedom do local str2 = str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. "0" deep (blocks, iBlock+1, freedom-takenFreedom, str2) end end end   function main (cells, blocks) -- number, list local str = " " print (cells .. ' cells and {' .. table.concat(blocks, ', ') .. '} blocks') local freedom = cells - #blocks + 1 -- freedom for iBlock = 1, #blocks do freedom = freedom - blocks[iBlock] end if #blocks == 0 then print ('no blocks') print (str..string.rep("0", cells)) total = 1 elseif freedom < 0 then print ('no solutions') else print ('Possibilities:') deep (blocks, 1, freedom, str) end end   for i, example in ipairs (examples) do print ("\n--") total = 0 main (example[1], example[2]) print ('A total of ' .. total .. ' possible configurations.') end
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Perl
Perl
use strict; use warnings;   sub fourFaceCombs { my %found = (); my @res = (); for (my $i = 1; $i <= 4; $i++) { for (my $j = 1; $j <= 4; $j++) { for (my $k = 1; $k <= 4; $k++) { for (my $l = 1; $l <= 4; $l++) { my @c = sort ($i, $j, $k, $l); my $key = 0; for my $p (@c) { $key = 10 * $key + $p; } if (not exists $found{$key}) { $found{$key} = 1; push @res, \@c; } } } } } return @res; }   sub compare { my $xref = shift; my $yref = shift;   my @x = @$xref; my $xw = 0;   my @y = @$yref; my $yw = 0;   for my $i (@x) { for my $j (@y) { if ($i < $j) { $yw++; } if ($j < $i) { $xw++; } } }   if ($xw < $yw) { return -1; } if ($yw < $xw) { return 1; } return 0; }   sub findIntransitive3 { my $dice_ref = shift; my @dice = @$dice_ref; my $len = scalar @dice;   my @res = (); for (my $i = 0; $i < $len; $i++) { for (my $j = 0; $j < $len; $j++) { my $first = compare($dice[$i], $dice[$j]); if ($first == 1) { for (my $k = 0; $k < $len; $k++) { my $second = compare($dice[$j], $dice[$k]); if ($second == 1) { my $third = compare($dice[$k], $dice[$i]); if ($third == 1) { my $d1r = $dice[$i]; my $d2r = $dice[$j]; my $d3r = $dice[$k]; my @itd = ($d1r, $d2r, $d3r); push @res, \@itd; } } } } } } return @res; }   sub findIntransitive4 { my $dice_ref = shift; my @dice = @$dice_ref; my $len = scalar @dice;   my @res = (); for (my $i = 0; $i < $len; $i++) { for (my $j = 0; $j < $len; $j++) { for (my $k = 0; $k < $len; $k++) { for (my $l = 0; $l < $len; $l++) { my $first = compare($dice[$i], $dice[$j]); if ($first == 1) { my $second = compare($dice[$j], $dice[$k]); if ($second == 1) { my $third = compare($dice[$k], $dice[$l]); if ($third == 1) { my $fourth = compare($dice[$l], $dice[$i]); if ($fourth == 1) { my $d1r = $dice[$i]; my $d2r = $dice[$j]; my $d3r = $dice[$k]; my $d4r = $dice[$l]; my @itd = ($d1r, $d2r, $d3r, $d4r); push @res, \@itd; } } } } } } } } return @res; }   sub main { my @dice = fourFaceCombs(); my $len = scalar @dice; print "Number of eligible 4-faced dice: $len\n\n";   my @it3 = findIntransitive3(\@dice); my $count3 = scalar @it3; print "$count3 ordered lists of 3 non-transitive dice found, namely:\n"; for my $itref (@it3) { print "[ "; for my $r (@$itref) { print "[@$r] "; } print "]\n"; } print "\n";   my @it4 = findIntransitive4(\@dice); my $count = scalar @it4; print "$count ordered lists of 4 non-transitive dice found, namely:\n"; for my $itref (@it4) { print "[ "; for my $r (@$itref) { print "[@$r] "; } print "]\n"; } }   main();
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AutoHotkey
AutoHotkey
MsgBox % noncontinuous("a,b,c,d,e", ",") MsgBox % noncontinuous("1,2,3,4", ",")   noncontinuous(list, delimiter) { stringsplit, seq, list, %delimiter% n := seq0 ; sequence length Loop % x := (1<<n) - 1 { ; try all 0-1 candidate sequences If !RegExMatch(b:=ToBin(A_Index,n),"^0*1*0*$") { ; drop continuous subsequences Loop Parse, b t .= A_LoopField ? seq%A_Index% " " : "" ; position -> number t .= "`n" ; new sequences in new lines } } return t }   ToBin(n,W=16) { ; LS W-bits of Binary representation of n Return W=1 ? n&1 : ToBin(n>>1,W-1) . n&1 }
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#ACL2
ACL2
(defun digit-value (chr) (cond ((and (char>= chr #\0) (char<= chr #\9)) (- (char-code chr) (char-code #\0))) ((and (char>= chr #\A) (char<= chr #\Z)) (+ (- (char-code chr) (char-code #\A)) 10)) ((and (char>= chr #\a) (char<= chr #\z)) (+ (- (char-code chr) (char-code #\a)) 10))))   (defun value-digit (n) (if (< n 10) (code-char (+ n (char-code #\0))) (code-char (+ (- n 10) (char-code #\A)))))   (defun num-from-cs (cs base) (if (endp cs) 0 (+ (digit-value (first cs)) (* base (num-from-cs (rest cs) base)))))   (defun parse-num (str base) (num-from-cs (reverse (coerce str 'list)) base))   (include-book "arithmetic-3/top" :dir :system)   (defun num-to-cs (num base) (if (or (zp num) (zp base) (= base 1)) nil (cons (value-digit (mod num base)) (num-to-cs (floor num base) base))))   (defun show-num (num base) (coerce (reverse (num-to-cs num base)) 'string))
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Factor
Factor
( scratchpad ) "ff" hex> . ! base 16 255 ( scratchpad ) "777" oct> . ! base 8 511 ( scratchpad ) "1111" bin> . ! base 2 15 ( scratchpad ) "99" string>number . ! base 10 99
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Forth
Forth
: parse# ( str len -- u true | false ) 0. 2SWAP DUP >R >NUMBER NIP NIP R> <> DUP 0= IF NIP THEN ;   : base# ( str len base -- u true | false ) BASE @ >R BASE ! parse# R> BASE ! ;
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Common_Lisp
Common Lisp
(loop for n from 0 to 33 do (format t " ~6B ~3O ~2D ~2X~%" n n n n))
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#D
D
import std.stdio;   void main() { writeln("Base: 2 8 10 16"); writeln("----------------------------"); foreach (i; 0 .. 34) writefln(" %6b %6o %6d %6x", i, i, i, i); }
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Quackery
Quackery
  [ [ table $ "zero" $ "one" $ "two" $ "three" $ "four" $ "five" $ "six" $ "seven" $ "eight" $ "nine" $ "ten" $ "eleven" $ "twelve" $ "thirteen" $ "fourteen" $ "fifteen" $ "sixteen" $ "seventeen" $ "eighteen" $ "nineteen" ] do ] is units ( n --> $ )   [ [ table $ "nonety" $ "tenty" $ "twenty" $ "thirty" $ "fourty" $ "fifty" $ "sixty" $ "seventy" $ "eighty" $ "ninety" ] do ] is tens ( n --> $ )   [ $ "" swap dup 99 > if [ 100 /mod swap units $ " hundred" join swap dip join dup 0 = iff drop ]done[ ] over size 0 > if [ dip [ $ " and " join ] ] dup 19 > if [ 10 /mod swap tens swap dip join dup 0 = iff drop ]done[ ] over size 0 > if [ over -1 peek space != if [ dip [ space join ] ] ] units join ] is triplet ( n --> $ )   [ $ "" swap dup 999999 > if [ 1000000 /mod swap triplet $ " million" join swap dip join dup 0 = iff drop ]done[ ] dup 999 > if [ over size 0 > if [ dip [ $ ", " join ] ] 1000 /mod swap triplet $ " thousand" join swap dip join dup 0 = iff drop ]done[ ] over size 0 > if [ dip [ $ ", " join ] ] triplet join ] is name$ ( n --> $ )   10 times [ 10 9 random 1+ ** random dup echo say " is:" name$ nest$ 60 wrap$ cr cr ]  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Rascal
Rascal
import Prelude; import vis::Figure; import vis::Render;   public void NumberReversalGame(){   //generate randomlist L = [1..9]; score = 0; randomlist = []; while (L != []){ temp = takeOneFrom(L); randomlist += temp[0]; L = temp[1]; }   // user interaction score = 0; text1 = ""; figure = box(vcat([ box(text(str(){ return "<randomlist>";})), box(textfield("Insert number of digits you would like to reverse here.", void(str s){ score += 1; n = toInt(s); spliced = slice(randomlist, 0, n); randomlist = reverse(spliced) + (randomlist - spliced); }, fillColor("lightblue"))), box(text(str(){ return ((randomlist == [1 .. 9]) ? "Well done! Your score: <score>." : "Keep going!");})) ]));   render(figure); }
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#zkl
zkl
fcn life1D(line){ right:=line[1,*] + False; // shift left, False fill left :=T(False).extend(line[0,-1]); // shift right left.zip(line,right).apply(fcn(hood){ hood.sum(0)==2 }); }
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#11l
11l
V tokens = 12   F getTokens(curTokens) -> N print(‘How many tokens would you like to take? ’, end' ‘’) V take = Int(input())   I (take < 1 | take > 3) print("Number must be between 1 and 3.\n") getTokens(curTokens) R    :tokens = curTokens - take print(‘You take #. tokens.’.format(take)) print("#. tokens remaining.\n".format(:tokens))   F compTurn(curTokens) V take = curTokens % 4  :tokens = curTokens - take print(‘Computer takes #. tokens.’.format(take)) print("#. tokens remaining.\n".format(:tokens))   L tokens > 0 getTokens(tokens) compTurn(tokens)   print(‘Computer wins!’)
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This 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). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#C.2B.2B
C++
  // A class to solve Nonogram (Hadje) Puzzles // Nigel Galloway - January 23rd., 2017 template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; // end of N std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};  
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#M2000_Interpreter
M2000 Interpreter
  Module NonoBlock { Form 80,40 Flush Print "Nonoblock" Data 5, (2, 1) Data 5, (,) Data 10, (8,) Data 15, (2,3,2,3) Data 5, (2,3) Def BLen(a$)=(Len(a$)-1)/2 Function UseLetter(arr) { Dim Base 0, Res$(Len(arr)) Link Res$() to Res() Def Ord$(a$)=ChrCode$(Chrcode(a$)+1) L$="A" i=each(arr) While i { Res$(i^)=String$("|"+L$, Array(i))+"|" L$=Ord$(L$) } =Res() } Count=0 For i=1 to 5 Read Cells, Blocks Blocks=UseLetter(Blocks) Print str$(i,"")+".", "Cells=";Cells, "", iF(len(Blocks)=0->("Empty",), Blocks) PrintRow( "|", Cells, Blocks, &Count) CheckCount() Next I Sub CheckCount() If count=0 Then Print " Impossible" count=0 End Sub Sub PrintRow(Lpart$, Cells, Blocks, &Comp) If len(Blocks)=0 Then Comp++ :Print Format$("{0::-3} {1}", Comp, lpart$+String$("_|", Cells)): Exit Sub If Cells<=0 Then Exit Sub Local TotalBlocksLength=0, Sep_Spaces=-1 Local Block=Each(Blocks), block$ While Block { Block$=Array$(Block) TotalBlocksLength+=Blen(Block$) Sep_Spaces++ } Local MaxLengthNeed=TotalBlocksLength+Sep_Spaces If MaxLengthNeed>Cells Then Exit Sub block$=Array$(Car(Blocks)) local temp=Blen(block$) block$=Mid$(Block$, 2) If Len(Blocks)>1 Then block$+="_|" :temp++ PrintRow(Lpart$+block$, Cells-temp, Cdr(Blocks), &Comp) PrintRow(lpart$+String$("_|", 1), Cells-1,Blocks, &Comp) End Sub } NonoBlock  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Phix
Phix
with javascript_semantics requires("0.8.2") -- (added sq_cmp() builtin that returns nested -1/0/+1 compare() results, just like the existing sq_eq() does for equal().) integer mx = 4, -- max number of a die side (later set to 6) mn = 1 -- min number of a die side (later set to 0) function possible_dice(integer sides) -- -- construct all non-descending permutes of mn..mx, -- ie/eg {1,1,1,1}..{4,4,4,4} with (say), amongst -- others, {1,1,2,4} but not {1,1,4,2}. -- sequence die = repeat(mn,sides), -- (main work area) res = {deep_copy(die)} while true do -- find rightmost incrementable side -- ie/eg {1,2,4,4} -> set rdx to 2 (if 1-based indexing) integer rdx = rfind(true,sq_lt(die,mx)) if rdx=0 then exit end if -- set that and all later to that incremented -- ie/eg {1,2,4,4} -> {1,3,3,3} die[rdx..$] = die[rdx]+1 res = append(res,deep_copy(die)) end while printf(1,"There are %d possible %d..%d %d-sided dice\n",{length(res),mn,mx,sides}) return res end function function Dnn(sequence die) -- reconstruct the python die numbering (string) -- essentially just treat it as a base-N number. integer l = length(die), -- (sides) N = mx-mn+1, -- (base) n = 0 -- (result) for k=1 to l do n += (die[k]-mn)*power(N,l-k) end for return sprintf("D%d",n+1) end function function cmpd(sequence die1, die2) -- compares two die returning -1, 0, or +1 for <, =, > integer res = 0 for i=1 to length(die1) do res += sum(sq_cmp(die1[i],die2)) end for return sign(res) end function function low_rotation(sequence set) integer k = find(min(set),set) return set[k..$]&set[1..k-1] end function integer rotations function find_non_trans(sequence dice, integer n=3) atom t1 = time()+1 integer l = length(dice), sk, sk1, c sequence set = repeat(1,n), -- (indexes to dice) cache = repeat(repeat(-2,l),l), res = {} while true do bool valid = true for k=1 to n-1 do sk = set[k] sk1 = set[k+1] c = cache[sk][sk1] if c=-2 then c = cmpd(dice[sk],dice[sk1]) cache[sk][sk1] = c end if if c!=-1 then valid = false -- force k+1 to be incremented next: set[k+2..$] = l exit end if end for if valid then sk = set[1] sk1 = set[$] c = cache[sk][sk1] if c=-2 then c = cmpd(dice[sk],dice[sk1]) cache[sk][sk1] = c end if if c=+1 then res = append(res,low_rotation(set)) end if end if -- find rightmost incrementable die index -- ie/eg if l is 35 and set is {1,2,35,35} -- -> set rdx to 2 (if 1-based indexing) integer rdx = rfind(true,sq_lt(set,l)) if rdx=0 then exit end if -- increment that and reset all later -- ie/eg {1,2,35,35} -> {1,3,1,1} set[rdx] += 1 set[rdx+1..$] = 1 if time()>t1 and platform()!=JS then progress("working... (%d/%d)\r",{set[1],l}) t1 = time()+1 end if end while if platform()!=JS then progress("") end if rotations = length(res) res = unique(res) rotations -= length(res) return res end function function verbose_cmp(sequence die1, die2) -- compares two die returning their relationship of their names as a string integer c = cmpd(die1,die2) string op = {"<","=",">"}[c+2], n1 = Dnn(die1), n2 = Dnn(die2) return sprintf("%s %s %s",{n1,op,n2}) end function function verbose_dice_cmp(sequence dice, set) sequence c = {}, d1, d2 for j=1 to length(set)-1 do d1 = dice[set[j]] d2 = dice[set[j+1]] c = append(c,verbose_cmp(d1,d2)) end for d1 = dice[set[1]] d2 = dice[set[$]] c = append(c,verbose_cmp(d1,d2)) return join(c,", ") end function procedure show_dice(sequence dice, non_trans, integer N) integer l = length(non_trans), omissions = 0, last = 0 if N then printf(1,"\n Non_transitive length-%d combinations found: %d\n",{N,l+rotations}) end if for i=1 to l do object ni = non_trans[i] if sequence(ni) then if i<5 then printf(1,"\n") for j=1 to length(ni) do sequence d = dice[ni[j]] printf(1,"  %s:%v\n",{Dnn(d),d}) end for last = i else omissions += 1 end if end if end for if omissions then printf(1," (%d omitted)\n",omissions) end if if rotations then printf(1," (%d rotations omitted)\n",rotations) end if if last then printf(1,"\n") if mx<=6 and mn=1 then printf(1," More verbose comparison of last result:\n") end if printf(1,"  %s\n",{verbose_dice_cmp(dice,non_trans[last])}) printf(1,"\n ====\n") end if printf(1,"\n") end procedure atom t0 = time() sequence dice = possible_dice(4) for N=3 to 4 do show_dice(dice,find_non_trans(dice,N),N) end for -- From the numberphile video (Efron's dice): mx = 6 mn = 0 dice = possible_dice(6) --show_dice(dice,find_non_trans(dice,4),4) -- ok, dunno about you but I'm not waiting for power(924,4) permutes... -- limit to the ones discussed, plus another 4 random ones -- (hopefully it'll just pick out the right ones...) printf(1,"\nEfron's dice\n") dice = {{0,0,4,4,4,4}, {1,1,1,1,1,1}, -- (rand) {1,1,1,5,5,5}, {1,2,3,4,5,6}, -- (rand) {2,2,2,2,6,6}, {5,5,5,6,6,6}, -- (rand) {3,3,3,3,3,3}, {6,6,6,6,6,6}} -- (rand) show_dice(dice,find_non_trans(dice,4),0) -- and from wp: mx = 9 mn = 1 dice = possible_dice(6) printf(1,"\nFrom wp\n") dice = {{1,1,6,6,8,8}, {2,2,4,4,9,9}, {3,3,5,5,7,7}} show_dice(dice,find_non_trans(dice,3),0) -- Miwin's dice printf(1,"Miwin's dice\n") dice = {{1,2,5,6,7,9}, {1,3,4,5,8,9}, {2,3,4,6,7,8}} show_dice(dice,find_non_trans(dice,3),0) printf(1,"%s\n\n",elapsed(time()-t0))
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BBC_BASIC
BBC BASIC
DIM list1$(3) list1$() = "1", "2", "3", "4" PRINT "For [1, 2, 3, 4] non-continuous subsequences are:" PROCnon_continuous_subsequences(list1$()) DIM list2$(4) list2$() = "1", "2", "3", "4", "5" PRINT "For [1, 2, 3, 4, 5] non-continuous subsequences are:" PROCnon_continuous_subsequences(list2$()) END   DEF PROCnon_continuous_subsequences(l$()) LOCAL i%, j%, g%, n%, r%, s%, w%, a$, b$ n% = DIM(l$(),1) FOR s% = 0 TO n%-2 FOR g% = s%+1 TO n%-1 a$ = "[" FOR i% = s% TO g%-1 a$ += l$(i%) + ", " NEXT FOR w% = 1 TO n%-g% r% = n%+1-g%-w% FOR i% = 1 TO 2^r%-1 STEP 2 b$ = a$ FOR j% = 0 TO r%-1 IF i% AND 2^j% b$ += l$(g%+w%+j%) + ", " NEXT PRINT LEFT$(LEFT$(b$)) + "]" NEXT i% NEXT w% NEXT g% NEXT s% ENDPROC
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Action.21
Action!
CHAR ARRAY digits="0123456789abcdefghijklmnopqrstuvwxyz"   PROC CheckBase(BYTE b) IF b<2 OR b>digits(0) THEN PrintE("Base is out of range!") Break() FI RETURN   PROC Encode(CARD v BYTE b CHAR ARRAY s) CARD d BYTE i,len CHAR tmp   CheckBase(b) len=0 DO d=v MOD b len==+1 s(len)=digits(d+1) v==/b UNTIL v=0 OD s(0)=len   FOR i=1 to len/2 DO tmp=s(i) s(i)=s(len-i+1) s(len-i+1)=tmp OD RETURN   CARD FUNC Decode(CHAR ARRAY s BYTE b) CARD res BYTE i,j,found   CheckBase(b) res=0 FOR i=1 TO s(0) DO found=0 FOR j=1 TO digits(0) DO IF digits(j)=s(i) THEN found=1 EXIT FI OD IF found=0 THEN PrintE("Unrecognized character!") Break() FI res==*b res==+j-1 OD RETURN (res)   PROC Main() CARD v=[6502],v2 BYTE b CHAR ARRAY s(256)   FOR b=2 TO 23 DO Encode(v,b,s) v2=Decode(s,b) PrintF("%U -> base %B %S -> %U%E",v,b,s,v2) OD RETURN
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Fortran
Fortran
program Example implicit none   integer :: num character(32) :: str   str = "0123459" read(str, "(i10)") num ! Decimal write(*,*) num ! Prints 123459   str = "abcf123" read(str, "(z8)") num ! Hexadecimal write(*,*) num ! Prints 180154659   str = "7651" read(str, "(o11)") num ! Octal write(*,*) num ! Prints 4009   str = "1010011010" read(str, "(b32)") num ! Binary write(*,*) num ! Prints 666   end program
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s(1 To 4) As String = {"&H1a", "26", "&O32", "&B11010"} '' 26 in various bases For i As Integer = 1 To 4 Print s(i); Tab(9); "="; CInt(s(i)) Next   Sleep
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Dc
Dc
[ dn [ ]P ]sp [ 2o lpx 8o lpx 10o lpx 16o lpx 17o lpx AP 1+ d21>b ]sb 1 lbx
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#E
E
for value in 0..33 { for base in [2, 8, 10, 12, 16, 36] { def s := value.toString(base) print(" " * (8 - s.size()), s) } println() }
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#R
R
# Number Names   ones <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen") tens <- c("ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") mags <- c("", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion")     return_hund <- function(input_number){ if (input_number == 0) return("") num_text <- as.character() input_hund <- trunc(input_number / 100) input_ten <- trunc((input_number - input_hund * 100) / 10) input_one <- input_number %% 10 if (input_number > 99) num_text <- paste0(ones[trunc(input_number / 100) + 1], "-hundred") if (input_ten < 2){ if (input_ten == 0 & input_one == 0) return(num_text) if (input_hund > 0) return(paste0(num_text, " ", ones[input_ten * 10 + input_one + 1])) return(paste0(ones[input_ten * 10 + input_one + 1])) } ifelse(input_hund > 0, num_text <- paste0(num_text, " ", tens[input_ten]), num_text <- paste0(tens[input_ten]) ) if (input_one != 0) num_text <- paste0(num_text, "-", ones[input_one + 1]) return(num_text) }     make_number <- function(number){ if (number == 0) return("zero") a <- abs(number) num_text <- as.character() g <- trunc(log(a, 10)) + 1 for (i in c(seq(g, 1))){ b <- floor(a / 1000 ^ (i - 1)) x <- return_hund(b) if (x != "") num_text <- paste0(num_text, return_hund(b), " ", mags[i], " ") a <- a - b * 1000 ^ (i - 1) } return(ifelse(sign(number) > 0, num_text, paste("negative", num_text))) }   my_num <- data.frame(nums = c( 0, 1, -11, 13, 99, 100, -101, 113, -120, 450, -999, 1000, 1001, 1017, 3000, 3001, 9999, 10000, 10001, 10100, 10101, 19000, 20001, 25467, 99999, 100000, 1056012, -200000, 200001, -200012, 2012567, -5685436, 5000201, -11627389, 100067652, 456000342) )   my_num$text <- as.character(lapply(my_num$nums, make_number)) print(my_num, right=F)  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#REBOL
REBOL
rebol []   print "NUMBER REVERSAL GAME"   tries: 0 goal: [1 2 3 4 5 6 7 8 9] random/seed now   until [ jumble: random goal jumble != goal ; repeat in the unlikely case that jumble isn't jumbled ]   while [jumble != goal] [ prin jumble prin " How many to flip? " flip-index: to-integer input ; no validation! reverse/part jumble flip-index tries: tries + 1 ]   print rejoin ["You took " tries " attempts."]
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#8080_Assembly
8080 Assembly
bdos: equ 5 ; CP/M syscalls puts: equ 9 putch: equ 2 getch: equ 1   maxtokens: equ 12 ; you can change this for more tokens   org 100h lxi d,nim call outs mvi b,maxtokens ; 12 tokens gameloop: lxi d,tokens ; Show tokens call outs mov c,b showtokens: dcr c jm tokensdone mvi a,'|' call outa jmp showtokens tokensdone: lxi d,nl call outs lxi d,prompt ; Show prompt call outs readinput: call ina ; Read input sui '1' ; Subtract '1' (lowest acceptable jc wrong ; input) cpi 3 ; range of values is [0..2] jnc wrong cmp b ; can't take more than there are either jnc wrong cma ; negate; -a = ~(a-1) mov c,a ; keep value add b ; subtract from tokens mov b,a mvi a,4 ; computer take 4-X tokens add c mov c,a lxi d,response ; print how many I take call outs mvi a,'0' add c call outa mov a,b ; subtract the ones I take sub c jz done ; if I took the last one, I won mov b,a lxi d,nl call outs call outs jmp gameloop done: lxi d,lose ; there's no win condition jmp outs ;; Invalid input wrong: lxi d,wronginp call outs jmp readinput ;; Read character into A and keep registers ina: push b push d push h mvi c,getch call bdos jmp restore ;; Print A and keep registers outa: push b push d push h mvi c,putch mov e,a call bdos jmp restore ;; Print string and keep registers outs: push b push d push h mvi c,puts call bdos ;; Restore registers restore: pop h pop d pop b ret nim: db 'Nim',13,10,13,10,'$' prompt: db 'How many will you take (1-3)? $' response: db 13,10,'I take $' tokens: db 'Tokens: $' lose: db 13,10,'You lose!$' nl: db 13,10,'$' wronginp: db 8,7,32,8,'$' ; beep and erase choice
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#8086_Assembly
8086 Assembly
;; MS-DOS Nim; assembles with nasm. bits 16 cpu 8086 getch: equ 1 putch: equ 2 puts: equ 9 ; INT 21h calls maxtokens: equ 12 ; Amount of tokens there are section .text org 100h mov dx,nim ; Print sign-on call outs mov ch,maxtokens ; CH = amount of tokens we have loop: mov dx,tokens ; Tokens: |||... call outs mov ah,putch ; Print a | for each token mov dl,'|' mov dh,ch puttoks: int 21h dec dh jnz puttoks mov dx,prompt ; Ask the user how many to take call outs ask: mov ah,getch ; Read keypress int 21h sub al,'1' ; Make number (minus one) jc bad ; Carry, it was <1 (bad) inc al ; Add 1 (because we subtracted '1') cmp al,3 ja bad ; If it was >3, it is bad cmp al,ch ja bad ; If it was > amount left, it is bad sub ch,al ; Remove your tokens from pile mov cl,4 ; I take 4-N, which is 3-N-1 sub cl,al sub ch,cl ; Remove my tokens from pile mov dx,response ; Tell the user how many I took. call outs mov dl,'0' add dl,cl mov ah,putch int 21h cmp ch,0 ; Are there any tokens left? jne loop ; If not, prompt again mov dx,lose ; But otherwise, you've lost ; Fall through into print string routine and then stop. ;; Print string in DX. (This saves a byte each CALL) outs: mov ah,puts int 21h ret ;; Input is bad; beep, erase, ask again bad: mov dx,wronginp call outs jmp ask section .data nim: db 'Nim$' prompt: db 13,10,'How many will you take (1-3)? $' response: db 13,10,'I take $' tokens: db 13,10,13,10,'Tokens: $' lose: db 13,10,'You lose!$' wronginp: db 8,7,32,8,'$'
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This 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). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#Common_Lisp
Common Lisp
(defpackage :ac3 (:use :cl) (:export :var :domain :satisfies-p :constraint-possible-p :ac3) (:documentation "Implements the AC3 algorithm. Extend VAR with the variable types for your particular problem and implement SATISFIES-P and CONSTRAINT-POSSIBLE-P for your variables. Initialize the DOMAIN of your variables with unary constraints already satisfied and then pass them to AC3 in a list."))   (in-package :ac3)   (defclass var () ((domain :initarg :domain :accessor domain)) (:documentation "The base variable type from which all other variables should extend."))   (defgeneric satisfies-p (a b va vb) (:documentation "Determine if constrainted variables A and B are satisfied by the instantiation of their respective values VA and VB."))   (defgeneric constraint-possible-p (a b) (:documentation "Determine if variables A and B can even be checked for a binary constraint."))   (defun arc-reduce (a b) "Assuming A and B truly form a constraint, prune all values from A that do not satisfy any value in B. Return T if the domain of A changed by any amount, NIL otherwise." (let (change) (setf (domain a) (loop for va in (domain a) when (loop for vb in (domain b) do (when (satisfies-p a b va vb) (return t)) finally (setf change t) (return nil)) collect va)) change))   (defun binary-constraint-p (a b) "Check if variables A and B could form a constraint, then return T if any of their values form a contradiction, NIL otherwise." (when (constraint-possible-p a b) (block found (loop for va in (domain a) do (loop for vb in (domain b) do (unless (satisfies-p a b va vb) (return-from found t)))))))   (defun ac3 (vars) "Run the Arc Consistency 3 algorithm on the given set of variables. Assumes unary constraints have already been satisfied." ;; Form a worklist of the constraints of every variable to every other variable. (let ((worklist (loop for x in vars append (loop for y in vars when (and (not (eq x y)) (binary-constraint-p x y)) collect (cons x y))))) ;; Prune the worklist of satisfied arcs until it is empty. (loop while worklist do (destructuring-bind (x . y) (pop worklist) (when (arc-reduce x y) (if (domain x) ;; If the current arc's domain was reduced, then append any arcs it ;; is still constrained with to the end of the worklist, as they ;; need to be rechecked. (setf worklist (nconc worklist (loop for z in vars when (and (not (eq x z)) (not (eq y z)) (binary-constraint-p x z)) collect (cons z x)))) (error "No values left in ~a" x)))) finally (return vars))))   (defpackage :nonogram (:use :cl :ac3) (:documentation "Utilize the AC3 package to solve nonograms."))   (in-package :nonogram)   (defclass line (var) ((depth :initarg :depth :accessor depth)) (:documentation "A LINE is a variable that represents either a column or row of cells and all of the permutations of values those cells can assume"))   (defmethod print-object ((o line) s) (print-unreadable-object (o s :type t) (with-slots (depth domain) o (format s ":depth ~a :domain ~a" depth domain))))   (defclass row (line) ())   (defclass col (line) ())   (defmethod satisfies-p ((a line) (b line) va vb) (eq (aref va (depth b)) (aref vb (depth a))))   (defmethod constraint-possible-p ((a line) (b line)) (not (eq (type-of a) (type-of b))))   (defun make-line-domain (runs length &optional (start 0) acc) "Enumerate all valid permutations of a line's values." (if runs (loop for i from start to (- length (reduce #'+ (cdr runs)) (length (cdr runs)) (car runs)) append (make-line-domain (cdr runs) length (+ 1 i (car runs)) (cons i acc))) (list (reverse acc))))   (defun make-line (type runs depth length) "Create and initialize a ROW or COL instance." (make-instance type :depth depth :domain (loop for value in (make-line-domain runs length) collect (let ((arr (make-array length :initial-element nil))) (loop for pos in value for run in runs do (loop for i from pos below (+ pos run) do (setf (aref arr i) t))) arr))))   (defun make-lines (type run-set length) "Initialize a set of lines." (loop for runs across run-set for depth from 0 collect (make-line type runs depth length)))   (defun nonogram (problem) "Given a nonogram problem description, solve it and print the result." (let* ((nrows (length (aref problem 0))) (ncols (length (aref problem 1))) (vars (ac3 (append (make-lines 'row (aref problem 0) ncols) (make-lines 'col (aref problem 1) nrows))))) (loop for var in vars while (eq 'row (type-of var)) do (terpri) (loop for cell across (car (domain var)) do (format t "~a " (if cell #\# #\.))))))   (defparameter *test-set* '("C BA CB BB F AE F A B" "AB CA AE GA E C D C"))   ;; Helper functions to read and parse problems from a file.   (defun parse-word (word) (map 'list (lambda (c) (- (digit-char-p c 36) 9)) word))   (defun parse-line (line) (map 'vector #'parse-word (uiop:split-string (string-upcase line))))   (defun parse-nonogram (rows columns) (vector (parse-line rows) (parse-line columns)))   (defun read-until-line (stream) (loop (let ((line (read-line stream))) (when (> (length (string-trim '(#\space) line)) 0) (print line) (return line)))))   (defun solve-from-file (file) (handler-case (with-open-file (s file) (loop (terpri) (nonogram (parse-nonogram (read-until-line s) (read-until-line s))))) (end-of-file ())))
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[SpacesDistributeOverN, Possibilities] SpacesDistributeOverN[s_, p_] := Flatten[ Permutations /@ (Join[#, ConstantArray[0, p - Length[#]]] & /@ IntegerPartitions[s, p]), 1] Possibilities[hint_, len_] := Module[{p = hint, l = len, b = Length[hint], Spaces, out}, Spaces = # + (Prepend[Append[ConstantArray[1, b - 1], 0], 0]) & /@ (SpacesDistributeOverN[l - Total@p - (b - 1), b + 1]); out = Flatten /@ ( Riffle[#, Map[Table[1, {#}] &, p, {1}]] & /@ Map[Table[0, {#}] &, Spaces, {2}]); StringJoin @@@ (out /. {0 -> ".", 1 -> "#"}) ] Possibilities[{}, len_] := Module[{}, {StringJoin[ConstantArray[".", len]]} ] Possibilities[{2, 1}, 5] Possibilities[{}, 5] Possibilities[{8}, 10] Possibilities[{2, 3, 2, 3}, 15] Possibilities[{2, 3}, 5]
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Nim
Nim
import math, sequtils, strformat, strutils     proc genSequence(ones: seq[string]; numZeroes: Natural): seq[string] = if ones.len == 0: return @[repeat('0', numZeroes)] for x in 1..(numZeroes - ones.len + 1): let skipOne = ones[1..^1] for tail in genSequence(skipOne, numZeroes - x): result.add repeat('0', x) & ones[0] & tail     proc printBlock(data: string; length: Positive) =   let a = mapIt(data, ord(it) - ord('0')) let sumBytes = sum(a)   echo &"\nblocks {($a)[1..^1]} cells {length}" if length - sumBytes <= 0: echo "No solution" return   var prep: seq[string] for b in a: prep.add repeat('1', b)   for r in genSequence(prep, length - sumBytes + 1): echo r[1..^1]     when isMainModule: printBlock("21", 5) printBlock("", 5) printBlock("8", 10) printBlock("2323", 15) printBlock("23", 5)
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Python
Python
from collections import namedtuple from itertools import permutations, product from functools import lru_cache     Die = namedtuple('Die', 'name, faces')   @lru_cache(maxsize=None) def cmpd(die1, die2): 'compares two die returning 1, -1 or 0 for >, < ==' # Numbers of times one die wins against the other for all combinations # cmp(x, y) is `(x > y) - (y > x)` to return 1, 0, or -1 for numbers tot = [0, 0, 0] for d1, d2 in product(die1.faces, die2.faces): tot[1 + (d1 > d2) - (d2 > d1)] += 1 win2, _, win1 = tot return (win1 > win2) - (win2 > win1)   def is_non_trans(dice): "Check if ordering of die in dice is non-transitive returning dice or None" check = (all(cmpd(c1, c2) == -1 for c1, c2 in zip(dice, dice[1:])) # Dn < Dn+1 and cmpd(dice[0], dice[-1]) == 1) # But D[0] > D[-1] return dice if check else False   def find_non_trans(alldice, n=3): return [perm for perm in permutations(alldice, n) if is_non_trans(perm)]   def possible_dice(sides, mx): print(f"\nAll possible 1..{mx} {sides}-sided dice") dice = [Die(f"D{n+1}", faces) for n, faces in enumerate(product(range(1, mx+1), repeat=sides))] print(f' Created {len(dice)} dice') print(' Remove duplicate with same bag of numbers on different faces') found = set() filtered = [] for d in dice: count = tuple(sorted(d.faces)) if count not in found: found.add(count) filtered.append(d) l = len(filtered) print(f' Return {l} filtered dice') return filtered   #%% more verbose extra checks def verbose_cmp(die1, die2): 'compares two die returning their relationship of their names as a string' # Numbers of times one die wins against the other for all combinations win1 = sum(d1 > d2 for d1, d2 in product(die1.faces, die2.faces)) win2 = sum(d2 > d1 for d1, d2 in product(die1.faces, die2.faces)) n1, n2 = die1.name, die2.name return f'{n1} > {n2}' if win1 > win2 else (f'{n1} < {n2}' if win1 < win2 else f'{n1} = {n2}')   def verbose_dice_cmp(dice): c = [verbose_cmp(x, y) for x, y in zip(dice, dice[1:])] c += [verbose_cmp(dice[0], dice[-1])] return ', '.join(c)     #%% Use if __name__ == '__main__': dice = possible_dice(sides=4, mx=4) for N in (3, 4): # length of non-transitive group of dice searched for non_trans = find_non_trans(dice, N) print(f'\n Non_transitive length-{N} combinations found: {len(non_trans)}') for lst in non_trans: print() for i, die in enumerate(lst): print(f" {' ' if i else '['}{die}{',' if i < N-1 else ']'}") if non_trans: print('\n More verbose comparison of last non_transitive result:') print(' ', verbose_dice_cmp(non_trans[-1])) print('\n ====')
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Bracmat
Bracmat
( ( noncontinuous = sub . ( sub = su a nc .  !arg:(?su.?nc) &  !su  :  %  %?a ( %:[%(sub$(!sjt.!nc !a)) |  ? & !nc:~ & out$(!nc !a) & ~ ) ) & sub$(dummy !arg.) | ) & noncontinuous$(e r n i t) );  
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C
C
#include <assert.h> #include <stdio.h>   int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n);   while (i--) { if (!(i & (i + (i & -(int)i)))) // consecutive 1s continue;   for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]);   putchar('\n'); }   return 0; }
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io; with Ada.Strings.Fixed; With Ada.Strings.Unbounded;   procedure Number_Base_Conversion is Max_Base : constant := 36; subtype Base_Type is Integer range 2..Max_Base; Num_Digits : constant String := "0123456789abcdefghijklmnopqrstuvwxyz"; Invalid_Digit : exception;   function To_Decimal(Value : String; Base : Base_Type) return Integer is use Ada.Strings.Fixed; Result : Integer := 0; Decimal_Value : Integer; Radix_Offset : Natural := 0; begin for I in reverse Value'range loop Decimal_Value := Index(Num_Digits, Value(I..I)) - 1; if Decimal_Value < 0 then raise Invalid_Digit; end if; Result := Result + (Base**Radix_Offset * Decimal_Value); Radix_Offset := Radix_Offset + 1; end loop; return Result; end To_Decimal;   function To_Base(Value : Natural; Base : Base_Type) return String is use Ada.Strings.Unbounded; Result : Unbounded_String := Null_Unbounded_String; Temp : Natural := Value; Base_Digit : String(1..1); begin if Temp = 0 then return "0"; end if; while Temp > 0 loop Base_Digit(1) := Num_Digits((Temp mod Base) + 1); if Result = Null_Unbounded_String then Append(Result, Base_Digit); else Insert(Source => Result, Before => 1, New_Item => Base_Digit); end if; Temp := Temp / Base; end loop; return To_String(Result); end To_Base;   begin Put_Line("26 converted to base 16 is " & To_Base(26, 16)); Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16))); end Number_Base_Conversion;
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Free_Pascal
Free Pascal
  program readIntegers(input, output); var i: aluSInt; begin while not EOF(input) do begin readLn(i); writeLn(i:24); end; end.  
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Go
Go
package main   import ( "fmt" "math/big" "strconv" )   func main() { // package strconv: the most common string to int conversion, // base 10 only. x, _ := strconv.Atoi("13") fmt.Println(x)   // ParseInt handles arbitrary bases from 2 to 36, and returns // a result of the requested size (64 bits shown here.) // If the base argument is zero the base is determined by prefix // as with math/big below. x64, _ := strconv.ParseInt("3c2", 19, 64) fmt.Println(x64)   // package fmt: allows direct conversion from strings, standard // input, or from an io.Reader (file, buffer, etc) to integer types // for bases 2, 8, 10, and 16 or to any type that implements the // fmt.Scanner interface (e.g. a big.Int). // (Fscanf and Scanf are more common for reading from // an io.Reader or stdin than Sscanf for reading from strings.) fmt.Sscanf("1101", "%b", &x) fmt.Println(x)   fmt.Sscanf("15", "%o", &x) fmt.Println(x)   fmt.Sscanf("13", "%d", &x) fmt.Println(x)   fmt.Sscanf("d", "%x", &x) fmt.Println(x)   // package math/big: allows conversion from string to big integer. // any base from 2 to 36 can be specified as second parameter. var z big.Int z.SetString("111", 3) fmt.Println(&z)   // if second parameter is 0, base is determined by prefix, if any z.SetString("0b1101", 0) // 0b -> base 2 fmt.Println(&z)   z.SetString("015", 0) // 0 -> base 8 fmt.Println(&z)   z.SetString("13", 0) // no prefix -> base 10 fmt.Println(&z)   z.SetString("0xd", 0) // 0x -> base 16 fmt.Println(&z)   // As mentioned, a big.Int (or any type implementing fmt.Scanner) // can also be use with any of the fmt scanning functions. fmt.Sscanf("15", "%o", &z) fmt.Println(&z) }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Elixir
Elixir
Enum.each(0..32, fn i -> :io.format "~2w :~6.2B, ~2.8B, ~2.16B~n", [i,i,i,i] end)
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Erlang
Erlang
4> [io:fwrite("~s ", [erlang:integer_to_list(63, X)]) || X <- [3,8,16,26]]. 2100 77 3F 2B
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Euphoria
Euphoria
for i = 1 to 33 do printf(1,"%6d %6x %6o\n",{i,i,i}) end for
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Racket
Racket
  #lang racket   (define smalls (map symbol->string '(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)))   (define tens (map symbol->string '(zero ten twenty thirty forty fifty sixty seventy eighty ninety)))   (define larges (map symbol->string '(thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion undecillion duodecillion tredecillion quattuordecillion quindecillion sexdecillion septendecillion octodecillion novemdecillion vigintillion)))   (define (integer->english n) (define (step div suffix separator [subformat integer->english]) (define-values [q r] (quotient/remainder n div)) (define S (if suffix (~a (subformat q) " " suffix) (subformat q))) (if (zero? r) S (~a S separator (integer->english r)))) (cond [(< n 0) (~a "negative " (integer->english (- n)))] [(< n 20) (list-ref smalls n)] [(< n 100) (step 10 #f "-" (curry list-ref tens))] [(< n 1000) (step 100 "hundred" " and ")] [else (let loop ([N 1000000] [D 1000] [unit larges]) (cond [(null? unit) (error 'integer->english "number too big: ~e" n)] [(< n N) (step D (car unit) ", ")] [else (loop (* 1000 N) (* 1000 D) (cdr unit))]))]))   (for ([n 10]) (define e (expt 10 n)) (define r (+ (* e (random e)) (random e))) (printf "~s: ~a\n" r (integer->english r)))  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#REXX
REXX
/*REXX program (a game): reverse a jumbled set of decimal digits 'til they're in order.*/ signal on halt /*allows the CBLF to HALT the program.*/ ___= copies('─', 9); pad=left('', 9) /*a fence used for computer's messages.*/ say ___ "This game will show you nine random unique digits (1 ──► 9), and you'll enter" say ___ "one of those digits which will reverse all the digits from the left-most digit" say ___ "up to (and including) that decimal digit. The game's objective is to get all" say ___ "of the digits in ascending order with the fewest tries. Here're your digits:" ok= 123456789 /*the result that the string should be.*/ $= /* ◄─── decimal target to be generated.*/ do until length($)==9; _=random(1, 9) /*build a random unique numeric string.*/ if pos(_, $) \== 0 then iterate /*¬ unique? Only use a decimal dig once*/ $=$ || _ /*construct a string of unique digits. */ if $==ok then $= /*string can't be in order, start over.*/ end /*until*/   do score=1 until $==ok; say /* [↓] display the digits & the prompt*/ say ___ $ right('please enter a digit (or Quit):', 50) parse pull ox . 1 ux . 1 x .; upper ux /*get a decimal digit (maybe) from CBLF*/ if abbrev('QUIT', ux, 1) then signal halt /*does the CBLF want to quit this game?*/ if length(x)>1 then do; say ___ pad '***error*** invalid input: ' ox; iterate; end if x='' then iterate /*try again, CBLF didn't enter anything*/ g=pos(x, $) /*validate if the input digit is legal.*/ if g==0 then say ___ pad '***error*** invalid digit: ' ox else $=strip(reverse(left($,g))substr($,g+1)) /*reverse some (or all) digits*/ end /*score*/   say; say ___ $; say; say center(' Congratulations! ', 70, "═"); say say ___ pad 'Your score was' score; exit /*stick a fork in it, we're all done. */ halt: say ___ pad 'quitting.'; exit /* " " " " " " " " */
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#Action.21
Action!
BYTE FUNC PlayerTurn(BYTE tokens) BYTE t,max   IF tokens<3 THEN max=tokens ELSE max=3 FI   DO PrintF("How many tokens would you like to take (1-%B)? ",max) t=InputB() UNTIL t>=1 AND t<=max OD PrintF("Player takes %B tokens.%E",t) t=tokens-t IF t=0 THEN PrintE("Player wins.") FI RETURN (t)   BYTE FUNC ComputerTurn(BYTE tokens) BYTE t   t=tokens MOD 4 PrintF("Computer takes %B tokens.%E",t) t=tokens-t IF t=0 THEN PrintE("Computer wins.") FI RETURN (t)   PROC Main() BYTE tokens=[12],t BYTE player=[1]   WHILE tokens>0 DO PrintF("Available tokens: %B%E",tokens) IF player THEN tokens=PlayerTurn(tokens) ELSE tokens=ComputerTurn(tokens) FI player=1-player OD RETURN
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#Ada
Ada
with Ada.Text_IO;   procedure Nim is subtype Token_Range is Positive range 1 .. 3;   package TIO renames Ada.Text_IO; package Token_IO is new TIO.Integer_IO(Token_Range);   procedure Get_Tokens(remaining : in Natural; how_many : out Token_Range) is begin loop TIO.Put("How many tokens would you like to take? "); begin Token_IO.Get(TIO.Standard_Input, how_many); exit when how_many < remaining; raise Constraint_Error; exception when TIO.Data_Error | Constraint_Error => if not TIO.End_Of_Line(TIO.Standard_Input) then TIO.Skip_Line(TIO.Standard_Input); end if; TIO.Put_Line("Invalid input."); end; end loop; end;   tokens : Natural := 12; how_many : Token_Range; begin loop TIO.Put_Line(tokens'Img & " tokens remain."); -- no exit condition here: human cannot win. Get_Tokens(tokens, how_many); TIO.Put_Line("Human takes" & how_many'Img & " tokens."); tokens := tokens - how_many; -- computer's turn: take the remaining N tokens to amount to 4. how_many := tokens mod 4; TIO.Put_Line("Computer takes" & how_many'Img & " tokens."); tokens := tokens - how_many; Ada.Text_IO.New_Line; exit when tokens = 0; end loop;   TIO.Put_Line("Computer won!"); end Nim;
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Task Detail Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]]   p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. Optional Extended tasks 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. Show output on this page.
#AutoHotkey
AutoHotkey
;----------------------------------------------------------- Nested_templated_data(template, Payload){ UsedP := [], UnusedP := [], UnusedI := [] result := template.Clone() x := ArrMap(template, Payload, result, UsedP, UnusedI, []) for i, v in Payload if !UsedP[v] UnusedP.Push(v) return [x.1, x.2, UnusedP] } ;----------------------------------------------------------- ArrMap(Template, Payload, result, UsedP, UnusedI, pth){ for i, index in Template { if IsObject(index) pth.Push(i), Arrmap(index, Payload, result, UsedP, UnusedI, pth) else{ pth.Push(i), ArrSetPath(result, pth, Payload[index]) if Payload[index] UsedP[Payload[index]] := 1 else UnusedI.Push(index) } pth.Pop() } return [result, UnusedI, UsedP] } ;----------------------------------------------------------- ArrSetPath(Arr, pth, newVal){ temp := [] for k, v in pth{ temp.push(v) if !IsObject(Arr[temp*]) Arr[temp*] := [] } return Arr[temp*] := newVal } ;----------------------------------------------------------- objcopy(obj){ nobj := obj.Clone() for k, v in nobj if IsObject(v) nobj[k] := objcopy(v) return nobj } ;-----------------------------------------------------------
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" Task For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM Extra credit: generate nonograms with unique solutions, of desired height and width. This 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). Related tasks Nonoblock. See also Arc Consistency Algorithm http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) http://twanvl.nl/blog/haskell/Nonograms (Haskell) http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
#D
D
import std.stdio, std.range, std.file, std.algorithm, std.string;   /// Create all patterns of a row or col that match given runs. auto genRow(in int w, in int[] s) pure nothrow @safe { static int[][] genSeg(in int[][] o, in int sp) pure nothrow @safe { if (o.empty) return [[2].replicate(sp)];   typeof(return) result; foreach (immutable x; 1 .. sp - o.length + 2) foreach (const tail; genSeg(o[1 .. $], sp - x)) result ~= [2].replicate(x) ~ o[0] ~ tail; return result; }   const ones = s.map!(i => [1].replicate(i)).array; return genSeg(ones, w + 1 - s.sum).map!dropOne; }   /// Fix inevitable value of cells, and propagate. void deduce(in int[][] hr, in int[][] vr) { static int[] allowable(in int[][] row) pure nothrow @safe { //return row.dropOne.fold!q{ a[] |= b[] }(row[0].dup); return reduce!q{ a[] |= b[] }(row[0].dup, row.dropOne); }   static bool fits(in int[] a, in int[] b) pure /*nothrow*/ @safe /*@nogc*/ { return zip(a, b).all!(xy => xy[0] & xy[1]); }   immutable int w = vr.length, h = hr.length; auto rows = hr.map!(x => genRow(w, x).array).array; auto cols = vr.map!(x => genRow(h, x).array).array; auto canDo = rows.map!allowable.array;   // Initially mark all columns for update. bool[uint] modRows, modCols; modCols = true.repeat.enumerate!uint.take(w).assocArray;   /// See if any value a given column is fixed; if so, /// mark its corresponding row for future fixup. void fixCol(in int n) /*nothrow*/ @safe { const c = canDo.map!(x => x[n]).array; cols[n] = cols[n].remove!(x => !fits(x, c)); // Throws. foreach (immutable i, immutable x; allowable(cols[n])) if (x != canDo[i][n]) { modRows[i] = true; canDo[i][n] &= x; } }   /// Ditto, for rows. void fixRow(in int n) /*nothrow*/ @safe { const c = canDo[n]; rows[n] = rows[n].remove!(x => !fits(x, c)); // Throws. foreach (immutable i, immutable x; allowable(rows[n])) if (x != canDo[n][i]) { modCols[i] = true; canDo[n][i] &= x; } }   void showGram(in int[][] m) { // If there's 'x', something is wrong. // If there's '?', needs more work. m.each!(x => writefln("%-(%c %)", x.map!(i => "x#.?"[i]))); writeln; }   while (modCols.length > 0) { modCols.byKey.each!fixCol; modCols = null; modRows.byKey.each!fixRow; modRows = null; }   if (cartesianProduct(h.iota, w.iota) .all!(ij => canDo[ij[0]][ij[1]] == 1 || canDo[ij[0]][ij[1]] == 2)) "Solution would be unique".writeln; else "Solution may not be unique, doing exhaustive search:".writeln;   // We actually do exhaustive search anyway. Unique // solution takes no time in this phase anyway. auto out_ = new const(int)[][](h);   uint tryAll(in int n = 0) { if (n >= h) { foreach (immutable j; 0 .. w) if (!cols[j].canFind(out_.map!(x => x[j]).array)) return 0; showGram(out_); return 1; } typeof(return) sol = 0; foreach (const x; rows[n]) { out_[n] = x; sol += tryAll(n + 1); } return sol; }   immutable n = tryAll; switch (n) { case 0: "No solution.".writeln; break; case 1: "Unique solution.".writeln; break; default: writeln(n, " solutions."); break; } writeln; }   void solve(in string p, in bool showRuns=true) { immutable s = p.splitLines.map!(l => l.split.map!(w => w.map!(c => int(c - 'A' + 1)).array).array).array; //w.map!(c => c - 'A' + 1))).to!(int[][][]);   if (showRuns) { writeln("Horizontal runs: ", s[0]); writeln("Vertical runs: ", s[1]); } deduce(s[0], s[1]); }   void main() { // Read problems from file. immutable fn = "nonogram_problems.txt"; fn.readText.split("\n\n").filter!(p => !p.strip.empty).each!(p => p.strip.solve);   "Extra example not solvable by deduction alone:".writeln; "B B A A\nB B A A".solve;   "Extra example where there is no solution:".writeln; "B A A\nA A A".solve; }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given 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: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm 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). 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. 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. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Pascal
Pascal
  program Nonoblock; uses SysUtils;   // Working through solutions to the problem: // Fill an array z[] with non-negative integers // whose sum is the passed-in integer s. function GetFirstSolution( var z : array of integer; s : integer) : boolean; var j : integer; begin result := (s >= 0) and (High(z) >= 0); // failed if s < 0 or array is empty if result then begin // else initialize to solution 0, ..., 0, s j := High(z); z[j] := s; while (j > 0) do begin dec(j); z[j] := 0; end; end; end;   // Next solution: return true for success, false if no more solutions. // Solutions are generated in lexicographic order. function GetNextSolution( var z : array of integer) : boolean; var h, j : integer; begin h := High(z); j := h; // find highest index j such that z[j] > 0. while (j > 0) and (z[j] = 0) do dec(j); result := (j > 0); // if index is 0, or there is no such index, failed if result then begin // else update caller's array to give next solution inc(z[j - 1]); z[h] := z[j] - 1; if (j < h) then z[j] := 0; end; end;   // Procedure to print solutions to nonoblock task on RosettaCode procedure PrintSolutions( nrCells : integer; blockSizes : array of integer); const // cosmetic MARGIN = 4; GAP_CHAR = '.'; BLOCK_CHAR = '#'; var sb : SysUtils.TStringBuilder; nrBlocks, blockSum, gapSum : integer; gapSizes : array of integer; i, nrSolutions : integer; begin nrBlocks := Length( blockSizes);   // Print a title, showing the number of cells and the block sizes sb := SysUtils.TStringBuilder.Create(); sb.AppendFormat('%d cells; blocks [', [nrCells]); for i := 0 to nrBlocks - 1 do begin if (i > 0) then sb.Append(','); sb.Append( blockSizes[i]); end; sb.Append(']'); WriteLn( sb.ToString());   blockSum := 0; // total of block sizes for i := 0 to nrBlocks - 1 do inc( blockSum, blockSizes[i]);   gapSum := nrCells - blockSum; // Except in the trivial case of no blocks, // we reduce the size of each inner gap by 1. if nrBlocks > 0 then dec( gapSum, nrBlocks - 1);   // Work through all solutions and print them nicely. nrSolutions := 0; SetLength( gapSizes, nrBlocks + 1); // include the gap at each end if GetFirstSolution( gapSizes, gapSum) then begin repeat inc( nrSolutions); sb.Clear(); sb.Append( ' ', MARGIN); for i := 0 to nrBlocks - 1 do begin sb.Append( GAP_CHAR, gapSizes[i]); // We reduced the inner gaps by 1; now we restore the deleted char. if (i > 0) then sb.Append( GAP_CHAR); sb.Append( BLOCK_CHAR, blockSizes[i]); end; sb.Append( GAP_CHAR, gapSizes[nrBlocks]); WriteLn( sb.ToString()); until not GetNextSolution( gapSizes); end; sb.Free(); WriteLn( SysUtils.Format( 'Number of solutions = %d', [nrSolutions])); WriteLn(''); end;   // Main program begin PrintSolutions( 5, [2,1]); PrintSolutions( 5, []); PrintSolutions( 10, [8]); PrintSolutions( 15, [2,3,2,3]); PrintSolutions( 5, [2,3]); end.  
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. 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. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes 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). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 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. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#R
R
findNonTrans <- function() { diceSet <- unique(t(apply(expand.grid(1:4, 1:4, 1:4, 1:4), 1, sort))) #By construction, each row is a unique dice. winningDice <- function(X, Y) #Recall 'Example 1' in the task. { comparisonTable <- data.frame(X = rep(X, each = length(X)), Y = rep(Y, times = length(Y))) rowWinner <- ifelse(comparisonTable["X"] > comparisonTable["Y"], "X", ifelse(comparisonTable["X"] == comparisonTable["Y"], "-", "Y")) netXWins <- sum(rowWinner == "X") - sum(rowWinner == "Y") if(netXWins > 0) "X" else if(netXWins == 0) "Draw" else "Y" } rows <- seq_len(nrow(diceSet)) #Recall that each row of diceSet is a dice. XvsAllY <- function(X) sapply(rows, function(i) winningDice(X, diceSet[i, ])) winners <- as.data.frame(lapply(rows, function(i) XvsAllY(diceSet[i, ])), row.names = paste("Y=Dice", rows), col.names = paste("X=Dice", rows), check.names = FALSE) solutionCount <- 0 for(S in rows) { beatsS <- which(winners[paste("X=Dice", S)] == "Y") #Finds the indices of all T such that S<T. beatsT <- lapply(beatsS, function(X) which(winners[paste("X=Dice", X)] == "Y")) #To begin finding U such that T<U. beatenByS <- which(winners[paste("X=Dice", S)] == "X") #Finds the indices of all U such that S>U. potentialU <- lapply(beatsT, function(X) intersect(X, beatenByS)) #Combining previous two lines. nonEmptyIndices <- lengths(potentialU) != 0 #Most of potentialU is usually empty lists. if(any(nonEmptyIndices)) #If any lists in potentialU are non-empty, then their entry is the index of a U with S>U & T<U. { solutionCount <- solutionCount + 1 diceUIndex <- potentialU[nonEmptyIndices][[1]] #Assumes that there is only one valid U for this S. diceTIndex <- beatsS[nonEmptyIndices][[1]] #Finds the T corresponding to the chosen U. cat("Solution", solutionCount, "is:\n") output <- rbind(S = diceSet[S,], T = diceSet[diceTIndex,], U = diceSet[diceUIndex,]) colnames(output) <- paste("Dice", 1:4) print(output) } } } findNonTrans()
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. Note: Subsequences are defined structurally, not by their contents. So a sequence a,b,c,d will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. Task: Find all non-continuous subsequences for a given sequence. Example For the sequence   1,2,3,4,   there are five non-continuous subsequences, namely:   1,3   1,4   2,4   1,3,4   1,2,4 Goal There are different ways to calculate those subsequences. Demonstrate algorithm(s) that are natural for the language. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } }   static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } }   static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;   }
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#Aime
Aime
o_text(bfxa(0, 0, 16, 1000000)); o_byte('\n'); o_text(bfxa(0, 0, 5, 1000000)); o_byte('\n'); o_text(bfxa(0, 0, 2, 1000000)); o_byte('\n');   o_integer(alpha("f4240", 16)); o_byte('\n'); o_integer(alpha("224000000", 5)); o_byte('\n'); o_integer(alpha("11110100001001000000", 2)); o_byte('\n');
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal. Task Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base. It should return a string containing the digits of the resulting number, without leading zeros except for the number   0   itself. For the digits beyond 9, one should use the lowercase English alphabet, where the digit   a = 9+1,   b = a+1,   etc. For example:   the decimal number   26   expressed in base   16   would be   1a. Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base. The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
#ALGOL_68
ALGOL 68
INT base = 16, from dec = 26; BITS to bits;   FORMAT hex repr = $n(base)r2d$;   FILE f; STRING str;   associate(f, str); putf(f, (hex repr, BIN from dec)); print(("Hex: ",str, new line));   reset(f); getf(f, (hex repr, to bits)); print(("Int: ",ABS to bits, new line))
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Haskell
Haskell
Prelude> read "123459" :: Integer 123459 Prelude> read "0xabcf123" :: Integer 180154659 Prelude> read "0o7651" :: Integer 4009
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#HicEst
HicEst
READ(Text="123459 ", Format="i10") dec ! 123459 READ(Text=" abcf123 ", Format="Z10") hex ! 180154659 READ(Text=" 7651 ", Format="o10") oct ! 4009 READ(Text=" 101011001", Format="B10.10") bin ! 345
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#F.23
F#
let ns = [30..33] ns |> Seq.iter (fun n -> printfn " %3o %2d %2X" n n n)
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Factor
Factor
1234567 2 36 [a,b] [ >base print ] with each
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Raku
Raku
constant @I = <zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen>; constant @X = <0 X twenty thirty forty fifty sixty seventy eighty ninety>; constant @C = @I X~ ' hundred'; constant @M = (<0 thousand>, ((<m b tr quadr quint sext sept oct non>, (map { ('', <un duo tre quattuor quin sex septen octo novem>).flat X~ $_ }, <dec vigint trigint quadragint quinquagint sexagint septuagint octogint nonagint>), 'cent').flat X~ 'illion')).flat;   sub int-name ($num) { if $num.substr(0,1) eq '-' { return "negative {int-name($num.substr(1))}" } if $num eq '0' { return @I[0] } my $m = 0; return join ', ', reverse gather for $num.flip.comb(/\d ** 1..3/) { my ($i,$x,$c) = .comb».Int; if $i or $x or $c { take join ' ', gather { if $c { take @C[$c] } if $x and $x == 1 { take @I[$i+10] } else { if $x { take @X[$x] } if $i { take @I[$i] } } take @M[$m] // die "WOW! ZILLIONS!\n" if $m; } } $m++; } }   while '' ne (my $n = prompt("Number: ")) { say int-name($n); }
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Ring
Ring
  # Project : Number reversal game   rever = 1:9 leftrever = [] for n = 1 to len(rever) rnd = random(8) + 1 temp = rever[n] rever[n] = rever[rnd] rever[rnd] = temp next see rever see nl while true num = 0 leftrever = [] showarray(rever) see " : Reverse how many = " give r r = number(r) for n = 1 to r add(leftrever, rever[n]) next leftrever = reverse(leftrever) for pos = 1 to r rever[pos] = leftrever[pos] next for m = 1 to len(rever) if rever[m] = m num = num + 1 ok next if num = len(rever) exit ok end see "You took " + num + " attempts." + nl   func swap(a, b) temp = a a = b b = temp return [a, b]   func showarray(vect) svect = "" for n = 1 to len(vect) svect = svect + vect[n] + " " next svect = left(svect, len(svect) - 1) see svect  
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in turn  the player who takes the last token wins. To 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. Task Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#ALGOL_68
ALGOL 68
BEGIN # play Nim # # gets a single character answer from standin and returns it # PROC answer = ( STRING prompt )CHAR: BEGIN STRING s; INT left := 0; WHILE print( ( prompt, "> " ) ); read( ( s, newline ) ); left := LWB s; INT right := UPB s; WHILE IF left > right THEN FALSE ELSE s[ left ] = " " FI DO left +:= 1 OD; WHILE IF right < left THEN FALSE ELSE s[ right ] = " " FI DO right -:= 1 OD; left /= right DO print( ( "Please reply with a single character", newline ) ) OD; s[ left ] END # answer # ; # play one game # INT tokens := 12; STRING suffix := ""; WHILE CHAR user; WHILE user := answer( "There are " + whole( tokens, 0 ) + " tokens" + suffix + ", how many do you want to take (1, 2 or 3)" ); user /= "1" AND user /= "2" AND user /= "3" DO print( ( "please answer 1, 2 or 3", newline ) ) OD; INT move = ABS user - ABS "0"; print( ( "I take ", whole( 4 - move, 0 ), newline ) ); suffix := " left"; tokens -:= 4; tokens > 0 DO SKIP OD; print( ( "I win!", newline ) ) END