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/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Java
Java
  import java.util.LinkedList;   public class DoublyLinkedList {   public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); traverseList(list);   list.removeFirstOccurrence("Add Last 1"); traverseList(list); }   private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); }   }  
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#AWK
AWK
# Multiplicative Digital Roots   BEGIN {   printMdrAndMp( 123321 ); printMdrAndMp( 7739 ); printMdrAndMp( 893 ); printMdrAndMp( 899998 );   tabulateMdr( 5 );   } # BEGIN   function printMdrAndMp( n ) { calculateMdrAndMp( n ); printf( "%6d: MDR: %d, MP: %2d\n", n, MDR, MP ); } # printMdrAndMp   function calculateMdrAndMp( n, mdrStr, digit ) {   MP = 0; # global Multiplicative Persistence MDR = ( n < 0 ? -n : n ); # global Multiplicative Digital Root   while( MDR > 9 ) { MP ++; mdrStr = "" MDR; MDR = 1; for( digit = 1; digit <= length( mdrStr ); digit ++ ) { MDR *= ( substr( mdrStr, digit, 1 ) * 1 ); } # for digit } # while MDR > 9   } # calculateMdrAndMp   function tabulateMdr( n, rqdValues, valueCount, value, pos ) {   # generate a table of the first n numbers with each possible MDR   rqdValues = n * 10; valueCount = 0;   for( value = 0; valueCount < rqdValues; value ++ ) { calculateMdrAndMp( value ); if( mdrCount[ MDR ] < n ) { # still need another value with this MDR valueCount ++; mdrCount[ MDR ] ++; mdrValues[ MDR ":" mdrCount[ MDR ] ] = value; } # if mdrCount[ MDR ] < n } # for value   # print the table   printf( "MDR: [n0..n%d]\n", n - 1 ); printf( "=== ========\n" );   for( pos = 0; pos < 10; pos ++ ) { printf( "%3d:", pos ); separator = " ["; for( value = 1; value <= n; value ++ ) { printf( "%s%d", separator, mdrValues[ pos ":" value ] ); separator = ", " } # for value printf( "]\n" ); } # for pos   } # tabulateMdr
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Scala
Scala
import javax.swing.JFrame import java.awt.Graphics   class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") {   setBounds(100, 100, 800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   val len = 400 / Math.pow(2, depth / 2.0); val startingAngle = -depth * (Math.PI / 4); val steps = getSteps(depth).filterNot(c => c == 'X' || c == 'Y')   def getSteps(depth: Int): Stream[Char] = { if (depth == 0) { "FX".toStream } else { getSteps(depth - 1).flatMap{ case 'X' => "XRYFR" case 'Y' => "LFXLY" case c => c.toString } } }   override def paint(g: Graphics): Unit = { var (x, y) = (230, 350) var (dx, dy) = ((Math.cos(startingAngle) * len).toInt, (Math.sin(startingAngle) * len).toInt) for (c <- steps) c match { case 'F' => { g.drawLine(x, y, x + dx, y + dy) x = x + dx y = y + dy } case 'L' => { val temp = dx dx = dy dy = -temp } case 'R' => { val temp = dx dx = -dy dy = temp } } }   }   object DragonCurve extends App { new DragonCurve(14).setVisible(true); }
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#11l
11l
-V BAKER = 0 COOPER = 1 FLETCHER = 2 MILLER = 3 SMITH = 4 names = [‘Baker’, ‘Cooper’, ‘Fletcher’, ‘Miller’, ‘Smith’]   V floors = Array(1..5)   L I floors[BAKER] != 5 & floors[COOPER] != 1 & floors[FLETCHER] !C (1, 5) & floors[MILLER] > floors[COOPER] & abs(floors[SMITH] - floors[FLETCHER]) != 1 & abs(floors[FLETCHER] - floors[COOPER]) != 1 L(floor) floors print(names[L.index]‘ lives on floor ’floor) L.break   I !floors.next_permutation() print(‘No solution found.’) L.break
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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 sentenceType(s) I s.empty R ‘’   [Char] types L(c) s I c == ‘?’ types.append(Char(‘Q’)) E I c == ‘!’ types.append(Char(‘E’)) E I c == ‘.’ types.append(Char(‘S’))   I s.last !C ‘?!.’ types.append(Char(‘N’))   R types.join(‘|’)   V s = ‘hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it’ print(sentenceType(s))
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing the linear combination ∑ i α i e i {\displaystyle \sum _{i}\alpha ^{i}e_{i}} in an explicit format often used in mathematics, that is: α i 1 e i 1 ± | α i 2 | e i 2 ± | α i 3 | e i 3 ± … {\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots } where α i k ≠ 0 {\displaystyle \alpha ^{i_{k}}\neq 0} The output must comply to the following rules:   don't show null terms, unless the whole combination is null. e(1)     is fine,     e(1) + 0*e(3)     or     e(1) + 0     is wrong.   don't show scalars when they are equal to one or minus one. e(3)     is fine,     1*e(3)     is wrong.   don't prefix by a minus sign if it follows a preceding term.   Instead you use subtraction. e(4) - e(5)     is fine,     e(4) + -e(5)     is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
#Vlang
Vlang
import strings   fn linear_combo(c []int) string { mut sb := strings.new_builder(128) for i, n in c { if n == 0 { continue } mut op := '' match true { n < 0 && sb.len == 0 { op = "-" } n < 0{ op = " - " } n > 0 && sb.len == 0 { op = "" } else{ op = " + " } } mut av := n if av < 0 { av = -av } mut coeff := "$av*" if av == 1 { coeff = "" } sb.write_string("$op${coeff}e(${i+1})") } if sb.len == 0 { return "0" } else { return sb.str() } }   fn main() { combos := [ [1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1], ] for c in combos { println("${c:-15} -> ${linear_combo(c)}") } }
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing the linear combination ∑ i α i e i {\displaystyle \sum _{i}\alpha ^{i}e_{i}} in an explicit format often used in mathematics, that is: α i 1 e i 1 ± | α i 2 | e i 2 ± | α i 3 | e i 3 ± … {\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots } where α i k ≠ 0 {\displaystyle \alpha ^{i_{k}}\neq 0} The output must comply to the following rules:   don't show null terms, unless the whole combination is null. e(1)     is fine,     e(1) + 0*e(3)     or     e(1) + 0     is wrong.   don't show scalars when they are equal to one or minus one. e(3)     is fine,     1*e(3)     is wrong.   don't prefix by a minus sign if it follows a preceding term.   Instead you use subtraction. e(4) - e(5)     is fine,     e(4) + -e(5)     is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
#Wren
Wren
import "/fmt" for Fmt   var linearCombo = Fn.new { |c| var sb = "" var i = 0 for (n in c) { if (n != 0) { var op = (n < 0 && sb == "") ? "-" : (n < 0) ? " - " : (n > 0 && sb == "") ? "" : " + " var av = n.abs var coeff = (av == 1) ? "" : "%(av)*" sb = sb + "%(op)%(coeff)e(%(i + 1))" } i = i + 1 } return (sb == "") ? "0" : sb }   var combos = [ [1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1] ] for (c in combos) { Fmt.print("$-15s -> $s", c.toString, linearCombo.call(c)) }
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#BASIC
BASIC
  100 : 110 REM DOT PRODUCT 120 : 130 REM INITIALIZE VECTORS OF LENGTH N 140 N = 3 150 DIM V1(N): DIM V2(N) 160 FOR I = 1 TO N 170 V1(I) = INT ( RND (1) * 20 - 9.5) 180 V2(I) = INT ( RND (1) * 20 - 9.5) 190 NEXT I 300 : 310 REM CALCULATE THE DOT PRODUCT 320 : 330 FOR I = 1 TO N:DP = DP + V1(I) * V2(I): NEXT I 400 : 410 REM DISPLAY RESULT 420 : 430 PRINT "[";: FOR I = 1 TO N: PRINT " ";V1(I);: NEXT I 440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I 450 PRINT "] = ";DP  
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#JavaScript
JavaScript
show(DLNode)
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Bracmat
Bracmat
( & ( MP/MDR = prod L n . ( prod = d . @(!arg:%@?d ?arg)&!d*prod$!arg | 1 ) & !arg:?L & whl ' ( @(!arg:? [>1) & (prod$!arg:?arg) !L:?L ) & !L:? [?n & (!n+-1.!arg) ) & ( test = n .  !arg:%?n ?arg & out$(!n "\t:" MP/MDR$!n) & test$!arg | ) & test$(123321 7739 893 899998) & 0:?i & 1:?collecting:?done & whl ' ( !i+1:?i & MP/MDR$!i:(?MP.?MDR) & ( !done:?*(!MDR.)^((?.)+?)*? | (!MDR.)^(!i.)*!collecting:?collecting & (  !collecting:?A*(!MDR.)^(?is+[5)*?Z & !A*!Z:?collecting & (!MDR.)^!is*!done:?done | ) ) & !collecting:~1 ) & whl ' ( !done:(?MDR.)^?is*?done & put$(!MDR ":") & whl'(!is:(?i.)+?is&put$(!i " ")) & put$\n ) );
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Scilab
Scilab
n_folds=10   folds=[]; folds=[0 1];   old_folds=[]; vectors=[];   i=[];   for i=2:n_folds+1   curve_length=length(folds);   vectors=folds(1:curve_length-1)-folds(curve_length);   vectors=vectors.*exp(90/180*%i*%pi);   new_folds=folds(curve_length)+vectors;   j=curve_length;   while j>1 folds=[folds new_folds(j-1)] j=j-1; end   end   scf(0); clf(); xname("Dragon curve: "+string(n_folds)+" folds")   plot2d(real(folds),imag(folds),5);   set(gca(),"isoview","on"); set(gca(),"axes_visible",["off","off","off"]);
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Dinesman is subtype Floor is Positive range 1 .. 5; type People is (Baker, Cooper, Fletcher, Miller, Smith); type Floors is array (People'Range) of Floor; type PtFloors is access all Floors;   function Constrained (f : PtFloors) return Boolean is begin if f (Baker) /= Floor'Last and f (Cooper) /= Floor'First and Floor'First < f (Fletcher) and f (Fletcher) < Floor'Last and f (Miller) > f (Cooper) and abs (f (Smith) - f (Fletcher)) /= 1 and abs (f (Fletcher) - f (Cooper)) /= 1 then return True; end if; return False; end Constrained;   procedure Solve (list : PtFloors; n : Natural) is procedure Swap (I : People; J : Natural) is temp : constant Floor := list (People'Val (J)); begin list (People'Val (J)) := list (I); list (I) := temp; end Swap; begin if n = 1 then if Constrained (list) then for p in People'Range loop Put_Line (p'Img & " on floor " & list (p)'Img); end loop; end if; return; end if; for i in People'First .. People'Val (n - 1) loop Solve (list, n - 1); if n mod 2 = 1 then Swap (People'First, n - 1); else Swap (i, n - 1); end if; end loop; end Solve;   thefloors : aliased Floors; begin for person in People'Range loop thefloors (person) := People'Pos (person) + Floor'First; end loop; Solve (thefloors'Access, Floors'Length); end Dinesman;
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
BEGIN # determuine the type of a sentence by looking at the final punctuation # CHAR exclamation = "E"; # classification codes... # CHAR question = "Q"; CHAR serious = "S"; CHAR neutral = "N"; # returns the type(s) of the sentence(s) in s - exclamation, question, # # serious or neutral; if there are multiple sentences # # the types are separated by | # PROC classify = ( STRING s )STRING: BEGIN STRING result := ""; BOOL pending neutral := FALSE; FOR s pos FROM LWB s TO UPB s DO IF pending neutral := FALSE; CHAR c = s[ s pos ]; c = "?" THEN result +:= question + "|" ELIF c = "!" THEN result +:= exclamation + "|" ELIF c = "." THEN result +:= serious + "|" ELSE pending neutral := TRUE FI OD; IF pending neutral THEN result +:= neutral + "|" FI; # if s was empty, then return an empty string, otherwise remove the final separator # IF result = "" THEN "" ELSE result[ LWB result : UPB result - 1 ] FI END # classify # ; # task test case # print( ( classify( "hi there, how are you today? I'd like to present to you the washing machine 9001. " + "You have been nominated to win one of these! Just make sure you don't break it" ) , newline ) ) END
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
Sentence := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" Msgbox, % SentenceType(Sentence)   SentenceType(Sentence) { Sentence := Trim(Sentence) Loop, Parse, Sentence, .?! { N := (!E && !Q && !S) , S := (InStr(SubStr(Sentence, InStr(Sentence, A_LoopField)+StrLen(A_LoopField), 3), ".")) , Q := (InStr(SubStr(Sentence, InStr(Sentence, A_LoopField)+StrLen(A_LoopField), 3), "?")) , E := (InStr(SubStr(Sentence, InStr(Sentence, A_LoopField)+StrLen(A_LoopField), 3), "!")) , type .= (E) ? ("E|") : ((Q) ? ("Q|") : ((S) ? ("S|") : "N|")) , D := SubStr(Sentence, InStr(Sentence, A_LoopField)+StrLen(A_LoopField), 3) } return (D = SubStr(Sentence, 1, 3)) ? RTrim(RTrim(type, "|"), "N|") : RTrim(type, "|") }
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing the linear combination ∑ i α i e i {\displaystyle \sum _{i}\alpha ^{i}e_{i}} in an explicit format often used in mathematics, that is: α i 1 e i 1 ± | α i 2 | e i 2 ± | α i 3 | e i 3 ± … {\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots } where α i k ≠ 0 {\displaystyle \alpha ^{i_{k}}\neq 0} The output must comply to the following rules:   don't show null terms, unless the whole combination is null. e(1)     is fine,     e(1) + 0*e(3)     or     e(1) + 0     is wrong.   don't show scalars when they are equal to one or minus one. e(3)     is fine,     1*e(3)     is wrong.   don't prefix by a minus sign if it follows a preceding term.   Instead you use subtraction. e(4) - e(5)     is fine,     e(4) + -e(5)     is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
#zkl
zkl
fcn linearCombination(coeffs){ [1..].zipWith(fcn(n,c){ if(c==0) "" else "%s*e(%s)".fmt(c,n) },coeffs) .filter().concat("+").replace("+-","-").replace("1*","") or 0 }
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#BASIC256
BASIC256
dim zero3d = {0.0, 0.0, 0.0} dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0} dim x = {1.0, 0.0, 0.0} dim y = {0.0, 1.0, 0.0} dim z = {0.0, 0.0, 1.0} dim q = {1.0, 1.0, 3.14159} dim r = {-1.0, 2.618033989, 3.0}   print " q dot r = "; dot(q, r) print " zero3d dot zero5d = "; dot(zero3d, zero5d) print " zero3d dot x = "; dot(zero3d, x) print " z dot z = "; dot(z, z) print " y dot z = "; dot(y, z) end   function dot(a, b) if a[?] <> b[?] then return "NaN"   dp = 0.0 for i = 0 to a[?]-1 dp += a[i] * b[i] next i return dp end function
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#bc
bc
/* Calculate the dot product of two vectors a and b (represented as * arrays) of size n. */ define d(a[], b[], n) { auto d, i   for (i = 0; i < n; i++) { d += a[i] * b[i] } return(d) }   a[0] = 1 a[1] = 3 a[2] = -5 b[0] = 4 b[1] = -2 b[2] = -1 d(a[], b[], 3)
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Julia
Julia
show(DLNode)
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#C
C
  #include <stdio.h>   #define twidth 5 #define mdr(rmdr, rmp, n)\ do { *rmp = 0; _mdr(rmdr, rmp, n); } while (0)   void _mdr(int *rmdr, int *rmp, long long n) { /* Adjust r if 0 case, so we don't return 1 */ int r = n ? 1 : 0; while (n) { r *= (n % 10); n /= 10; }   (*rmp)++; if (r >= 10) _mdr(rmdr, rmp, r); else *rmdr = r; }   int main(void) { int i, j, vmdr, vmp; const int values[] = { 123321, 7739, 893, 899998 }; const int vsize = sizeof(values) / sizeof(values[0]);   /* Initial test values */ printf("Number MDR MP\n"); for (i = 0; i < vsize; ++i) { mdr(&vmdr, &vmp, values[i]); printf("%6d  %3d  %3d\n", values[i], vmdr, vmp); }   /* Determine table values */ int table[10][twidth] = { 0 }; int tfill[10] = { 0 }; int total = 0; for (i = 0; total < 10 * twidth; ++i) { mdr(&vmdr, &vmp, i); if (tfill[vmdr] < twidth) { table[vmdr][tfill[vmdr]++] = i; total++; } }   /* Print calculated table values */ printf("\nMDR: [n0..n4]\n"); for (i = 0; i < 10; ++i) { printf("%3d: [", i); for (j = 0; j < twidth; ++j) printf("%d%s", table[i][j], j != twidth - 1 ? ", " : ""); printf("]\n"); }   return 0; }  
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i";   var float: angle is 0.0; var integer: x is 220; var integer: y is 220;   const proc: turn (in integer: degrees) is func begin angle +:= flt(degrees) * PI / 180.0 end func;   const proc: forward (in float: length) is func local var integer: x2 is 0; var integer: y2 is 0; begin x2 := x + trunc(cos(angle) * length); y2 := y + trunc(sin(angle) * length); lineTo(x, y, x2, y2, black); x := x2; y := y2; end func;   const proc: dragon (in float: length, in integer: split, in integer: direct) is func begin if split = 0 then forward(length); else turn(direct * 45); dragon(length/1.4142136, pred(split), 1); turn(-direct * 90); dragon(length/1.4142136, pred(split), -1); turn(direct * 45); end if; end func;   const proc: main is func begin screen(976, 654); clear(curr_win, white); KEYBOARD := GRAPH_KEYBOARD; dragon(768.0, 14, 1); ignore(getc(KEYBOARD)); end func;
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#ALGOL_68
ALGOL 68
# attempt to solve the dinesman Multiple Dwelling problem #   # SETUP #   # special floor values # INT top floor = 4; INT bottom floor = 0;   # mode to specify the persons floor constraint # MODE PERSON = STRUCT( STRING name, REF INT floor, PROC( INT )BOOL ok );   # yields TRUE if the floor of the specified person is OK, FALSE otherwise # OP OK = ( PERSON p )BOOL: ( ok OF p )( floor OF p );   # yields TRUE if floor is adjacent to other persons floor, FALSE otherwise # PROC adjacent = ( INT floor, other persons floor )BOOL: floor >= ( other persons floor - 1 ) AND floor <= ( other persons floor + 1 );   # displays the floor of an occupant # PROC print floor = ( PERSON occupant )VOID: print( ( whole( floor OF occupant, -1 ), " ", name OF occupant, newline ) );   # PROBLEM STATEMENT #   # the inhabitants with their floor and constraints # PERSON baker = ( "Baker", LOC INT := 0, ( INT floor )BOOL: floor /= top floor ); PERSON cooper = ( "Cooper", LOC INT := 0, ( INT floor )BOOL: floor /= bottom floor ); PERSON fletcher = ( "Fletcher", LOC INT := 0, ( INT floor )BOOL: floor /= top floor AND floor /= bottom floor AND NOT adjacent( floor, floor OF cooper ) ); PERSON miller = ( "Miller", LOC INT := 0, ( INT floor )BOOL: floor > floor OF cooper ); PERSON smith = ( "Smith", LOC INT := 0, ( INT floor )BOOL: NOT adjacent( floor, floor OF fletcher ) );   # SOLUTION #   # "brute force" solution - we run through the possible 5^5 configurations # # we cold optimise this by e.g. restricting f to bottom floor + 1 TO top floor - 1 # # at the cost of reducing the flexibility of the constraints # # alternatively, we could add minimum and maximum allowed floors to the PERSON # # STRUCT and loop through these instead of bottom floor TO top floor #   FOR b FROM bottom floor TO top floor DO floor OF baker := b; FOR c FROM bottom floor TO top floor DO IF b /= c THEN floor OF cooper := c; FOR f FROM bottom floor TO top floor DO IF b /= f AND c /= f THEN floor OF fletcher := f; FOR m FROM bottom floor TO top floor DO IF b /= m AND c /= m AND f /= m THEN floor OF miller := m; FOR s FROM bottom floor TO top floor DO IF b /= s AND c /= s AND f /= s AND m /= s THEN floor OF smith := s; IF OK baker AND OK cooper AND OK fletcher AND OK miller AND OK smith THEN # found a solution # print floor( baker ); print floor( cooper ); print floor( fletcher ); print floor( miller ); print floor( smith ) FI FI OD FI OD FI OD FI OD OD
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#AWK
AWK
  # syntax: GAWK -f DETERMINE_SENTENCE_TYPE.AWK BEGIN { str = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" main(str) main("Exclamation! Question? Serious. Neutral") exit(0) } function main(str, c) { while (length(str) > 0) { c = substr(str,1,1) sentence = sentence c if (c == "!") { prn("E") } else if (c == ".") { prn("S") } else if (c == "?") { prn("Q") } str = substr(str,2) } prn("N") print("") } function prn(type) { gsub(/^ +/,"",sentence) printf("%s %s\n",type,sentence) sentence = "" }  
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#CLU
CLU
% This iterator takes a string and yields one of 'E', 'Q', % 'S' or 'N' for every sentence found. % Because sentences are separated by punctuation, only the % last one can be 'N'.   sentence_types = iter (s: string) yields (char) own punct: string := "!?."  % relevant character classes own space: string := " \t\n" own types: string := "EQS"  % sentence type characters   prev_punct: bool := false  % whether the previous character was punctuation last_punct: int := 0  % index of last punctuation character encountered sentence: bool := true  % whether there are words since the last punctuation   for c: char in string$chars(s) do pu: int := string$indexc(c, punct) sp: int := string$indexc(c, space) if pu ~= 0 then prev_punct := true last_punct := pu elseif sp ~= 0 then if prev_punct then  % a space after punctuation means a sentence has ended here yield(types[last_punct]) sentence := false end prev_punct := false sentence := false else sentence := true end end    % handle the last sentence if prev_punct then yield(types[last_punct]) elseif sentence then yield('N') end end sentence_types   % Test start_up = proc () po: stream := stream$primary_output() test: string := "hi there, how are you today? I'd like to " || "present to you the washing machine 9001. You " || "have been nominated to win one of these! Just " || "make sure you don't break it"    % print the type of each sentence for c: char in sentence_types(test) do stream$putc(po, c) end end start_up
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Epoxy
Epoxy
const SentenceTypes: { ["?"]:"Q", ["."]:"S", ["!"]:"E" }   fn DetermineSentenceType(Char) return SentenceTypes[Char]||"N" cls   fn GetSentences(Text) var Sentences: [], Index: 0, Length: #Text loop i:0;i<Length;i+:1 do var Char: string.subs(Text,i,1) var Type: DetermineSentenceType(Char) if Type != "N" || i==Length-1 then log(string.sub(Text,Index,i+1)+" ("+Type+")") Index:i+2; cls cls cls   GetSentences("hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it")
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#BCPL
BCPL
get "libhdr"   let dotproduct(A, B, len) = valof $( let acc = 0 for i=0 to len-1 do acc := acc + A!i * B!i resultis acc $)   let start() be $( let A = table 1, 3, -5 let B = table 4, -2, -1 writef("%N*N", dotproduct(A, B, 3)) $)
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Kotlin
Kotlin
// version 1.1.2   class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append(" -> ", node.data.toString()) node = node.next } return sb.toString() } }   var first: Node<E>? = null var last: Node<E>? = null   fun addFirst(value: E) { if (first == null) { first = Node(value) last = first } else { val node = first!! first = Node(value, null, node) node.prev = first } }   fun addLast(value: E) { if (last == null) { last = Node(value) first = last } else { val node = last!! last = Node(value, node, null) node.next = last } }   fun insert(after: Node<E>?, value: E) { if (after == null) addFirst(value) else if (after == last) addLast(value) else { val next = after.next val new = Node(value, after, next) after.next = new if (next != null) next.prev = new } }   override fun toString() = first.toString() }   fun main(args: Array<String>) { val ll = LinkedList<Int>() ll.addFirst(1) ll.addLast(4) ll.insert(ll.first, 2) ll.insert(ll.last!!.prev, 3) println(ll) }
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { static Tuple<int, int> DigitalRoot(long num) { int mp = 0; while (num > 9) { num = num.ToString().ToCharArray().Select(x => x - '0').Aggregate((a, b) => a * b); mp++; } return new Tuple<int, int>(mp, (int)num); } static void Main(string[] args) { foreach (long num in new long[] { 123321, 7739, 893, 899998 }) { var t = DigitalRoot(num); Console.WriteLine("{0} has multiplicative persistence {1} and multiplicative digital root {2}", num, t.Item1, t.Item2); }   const int twidth = 5; List<long>[] table = new List<long>[10]; for (int i = 0; i < 10; i++) table[i] = new List<long>(); long number = -1; while (table.Any(x => x.Count < twidth)) { var t = DigitalRoot(++number); if (table[t.Item2].Count < twidth) table[t.Item2].Add(number); } for (int i = 0; i < 10; i++) Console.WriteLine(" {0} : [{1}]", i, string.Join(", ", table[i])); } }
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#SequenceL
SequenceL
import <Utilities/Math.sl>; import <Utilities/Conversion.sl>;   initPoints := [[0,0],[1,0]];   f1(point(1)) := let matrix := [[cos(45 * (pi/180)), -sin(45 * (pi/180))], [sin(45 * (pi/180)), cos(45 * (pi/180))]]; in head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point]))));   f2(point(1)) := let matrix := [[cos(135 * (pi/180)), -sin(135 * (pi/180))], [sin(135 * (pi/180)), cos(135 * (pi/180))]]; in head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point])))) + initPoints[2];   matmul(X(2),Y(2))[i,j] := sum(X[i,all]*Y[all,j]);   entry(steps(0), maxX(0), maxY(0)) := let scaleX := maxX / 1.5; scaleY := maxY;   shiftX := maxX / 3.0 / 1.5; shiftY := maxY / 3.0; in round(run(steps, initPoints) * [scaleX, scaleY] + [shiftX, shiftY]);   run(steps(0), result(2)) := let next := f1(result) ++ f2(result); in result when steps <= 0 else run(steps - 1, next);
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#AutoHotkey
AutoHotkey
  # syntax: GAWK -f DINESMANS_MULTIPLE-DWELLING_PROBLEM.AWK BEGIN { for (Baker=1; Baker<=5; Baker++) { for (Cooper=1; Cooper<=5; Cooper++) { for (Fletcher=1; Fletcher<=5; Fletcher++) { for (Miller=1; Miller<=5; Miller++) { for (Smith=1; Smith<=5; Smith++) { if (rules() ~ /^1+$/) { printf("%d Baker\n",Baker) printf("%d Cooper\n",Cooper) printf("%d Fletcher\n",Fletcher) printf("%d Miller\n",Miller) printf("%d Smith\n",Smith) } } } } } } exit(0) } function rules( stmt1,stmt2,stmt3,stmt4,stmt5,stmt6,stmt7) { # The following problem statements may be changed: # # Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house # that contains only five floors numbered 1 (ground) to 5 (top) stmt1 = Baker!=Cooper && Baker!=Fletcher && Baker!=Miller && Baker!=Smith && Cooper!=Fletcher && Cooper!=Miller && Cooper!=Smith && Fletcher!=Miller && Fletcher!=Smith && Miller!=Smith stmt2 = Baker != 5 # Baker does not live on the top floor stmt3 = Cooper != 1 # Cooper does not live on the bottom floor stmt4 = Fletcher != 5 && Fletcher != 1 # Fletcher does not live on either the top or the bottom floor stmt5 = Miller > Cooper # Miller lives on a higher floor than does Cooper stmt6 = abs(Smith-Fletcher) != 1 # Smith does not live on a floor adjacent to Fletcher's stmt7 = abs(Fletcher-Cooper) != 1 # Fletcher does not live on a floor adjacent to Cooper's return(stmt1 stmt2 stmt3 stmt4 stmt5 stmt6 stmt7) } function abs(x) { if (x >= 0) { return x } else { return -x } }  
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Factor
Factor
USING: combinators io kernel regexp sequences sets splitting wrap.strings ;   ! courtesy of https://www.infoplease.com/common-abbreviations   CONSTANT: common-abbreviations { "A.B." "abbr." "Acad." "A.D." "alt." "A.M." "Assn." "at. no." "at. wt." "Aug." "Ave." "b." "B.A." "B.C." "b.p." "B.S." "c." "Capt." "cent." "co." "Col." "Comdr." "Corp." "Cpl." "d." "D.C." "Dec." "dept." "dist." "div." "Dr." "ed." "est." "et al." "Feb." "fl." "gal." "Gen." "Gov." "grad." "Hon." "i.e." "in." "inc." "Inst." "Jan." "Jr." "lat." "Lib." "long." "Lt." "Ltd." "M.D." "Mr." "Mrs." "mt." "mts." "Mus." "no." "Nov." "Oct." "Op." "pl." "pop." "pseud." "pt." "pub." "Rev." "rev." "R.N." "Sept." "Ser." "Sgt." "Sr." "St." "uninc." "Univ." "U.S." "vol." "vs." "wt." }   : sentence-enders ( str -- newstr ) R/ \)/ "" re-replace " " split harvest unclip-last swap [ common-abbreviations member? ] reject [ last ".!?" member? ] filter swap suffix ;   : serious? ( str -- ? ) last CHAR: . = ; : neutral? ( str -- ? ) last ".!?" member? not ; : mixed? ( str -- ? ) "?!" intersect length 2 = ; : exclamation? ( str -- ? ) last CHAR: ! = ; : question? ( str -- ? ) last CHAR: ? = ;   : type ( str -- newstr ) { { [ dup serious? ] [ drop "S" ] } { [ dup neutral? ] [ drop "N" ] } { [ dup mixed? ] [ drop "EQ" ] } { [ dup exclamation? ] [ drop "E" ] } { [ dup question? ] [ drop "Q" ] } [ drop "UNKNOWN" ] } cond ;   : sentences ( str -- newstr ) sentence-enders [ type ] map "|" join ;   : show ( str -- ) dup sentences " -> " glue 60 wrap-string print ;   "Hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" show nl "(There was nary a mouse stirring.) But the cats were going bonkers!" show nl "\"Why is the car so slow?\" she said." show nl "Hello, Mr. Anderson!" show nl "Are you sure?!?! How can you know?" show
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#FreeBASIC
FreeBASIC
function sentype( byref s as string ) as string 'determines the sentence type of the first sentence in the string 'returns "E" for an exclamation, "Q" for a question, "S" for serious 'and "N" for neutral. 'modifies the string to remove the first sentence for i as uinteger = 1 to len(s) if mid(s, i, 1) = "!" then s=right(s,len(s)-i) return "E" end if if mid(s, i, 1) = "." then s=right(s,len(s)-i) return "S" end if if mid(s, i, 1) = "?" then s=right(s,len(s)-i) return "Q" end if next i 'if we get to the end without encountering punctuation, this 'must be a neutral sentence, which can only happen as the last one s="" return "N" end function   dim as string spam = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"   while len(spam)>0 print sentype(spam) wend
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Go
Go
package main   import ( "fmt" "strings" )   func sentenceType(s string) string { if len(s) == 0 { return "" } var types []string for _, c := range s { if c == '?' { types = append(types, "Q") } else if c == '!' { types = append(types, "E") } else if c == '.' { types = append(types, "S") } } if strings.IndexByte("?!.", s[len(s)-1]) == -1 { types = append(types, "N") } return strings.Join(types, "|") }   func main() { s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" fmt.Println(sentenceType(s)) }
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#Befunge_93
Befunge 93
  v Space for variables v Space for vector1 v Space for vector2 v http://rosettacode.org/wiki/Dot_product >00pv >>55+":htgneL",,,,,,,,&:0` | v,,,,,,,"Length can't be negative."+55< >,,,,,,,,,,,,,,,,,,,@ |!`-10< >0.@ v,")".g00,,,,,,,,,,,,,,"Vector a(size " < 0v01g00,")".g00,,,,,,,,,,,,,,"Vector b"< 0pvp2g01&p01-1g01< " g>> 10g0`| @.g30<( 1 >03g:-03p>00g1-` |s 0 vp00-1g00p30+g30*g2-1g00g1-1g00<i p > v # z vp1g01&p01-1g01<> ^ e > 10g0` | vp01-1g01.g1< >00g1-10p>10g:01-` | " > ^  
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Lua
Lua
-- Doubly Linked List in Lua 6/15/2020 db ------------------- -- IMPLEMENTATION: -------------------   local function Node(data) return { data=data } --implied: return { data=data, prev=nil, next=nil } end   local List = { head = nil, tail = nil, insertHead = function(self, data) local node = Node(data) if (self.head) then self.head.prev = node node.next = self.head self.head = node else self.head = node self.tail = node end return node end, insertTail = function(self, data) local node = Node(data) if self.tail then self.tail.next = node node.prev = self.tail self.tail = node else self.head = node self.tail = node end return node end, insertBefore = function(self,mark,data) if (mark) then local node = Node(data) if (mark == self.head) then self.head.next = node node.next = self.head self.head = node else mark.prev.next = node node.prev = mark.prev mark.prev = node node.next = mark end return node else -- if no mark given, then insertBefore()==insertHead() return self:insertHead(data) end end, insertAfter = function(self,mark,data) if (mark) then local node = Node(data) if (mark == self.tail) then self.tail.next = node node.prev = self.tail self.tail = node else mark.next.prev = node node.next = mark.next mark.next = node node.prev = mark end return node else -- if no mark given, then insertAfter()==insertTail() return self:insertTail(data) end end, values = function(self) local result, node = {}, self.head while (node) do result[#result+1], node = node.data, node.next end return result end, } List.__index = List setmetatable(List, {__call=function(self) return setmetatable({},self) end })   --------- -- TEST: --------- local function validate(list, expected) local values = list:values() local actual = table.concat(values, ",") print(actual==expected, actual) end local list = List() validate(list, "") local n1 = list:insertTail(1) validate(list, "1") local n2 = list:insertTail(2) validate(list, "1,2") local n3 = list:insertTail(3) validate(list, "1,2,3") local n4 = list:insertTail(4) validate(list, "1,2,3,4") local n33 = list:insertAfter(n3, 33) validate(list, "1,2,3,33,4") local n22 = list:insertAfter(n2, 22) validate(list, "1,2,22,3,33,4") local n11 = list:insertAfter(n1, 11) validate(list, "1,11,2,22,3,33,4") local n44 = list:insertAfter(n4, 44) validate(list, "1,11,2,22,3,33,4,44") local n5 = list:insertTail(5) validate(list, "1,11,2,22,3,33,4,44,5") local n444 = list:insertBefore(n5, 444) validate(list, "1,11,2,22,3,33,4,44,444,5") local n55 = list:insertAfter(nil, 55) validate(list, "1,11,2,22,3,33,4,44,444,5,55") local n0 = list:insertHead(0) validate(list, "0,1,11,2,22,3,33,4,44,444,5,55") local nm1 = list:insertBefore(nil, -1) validate(list, "-1,0,1,11,2,22,3,33,4,44,444,5,55") local n111 = list:insertBefore(n2, 111) validate(list, "-1,0,1,11,111,2,22,3,33,4,44,444,5,55") local n222 = list:insertAfter(n22, 222) validate(list, "-1,0,1,11,111,2,22,222,3,33,4,44,444,5,55") local n333 = list:insertBefore(n4, 333) validate(list, "-1,0,1,11,111,2,22,222,3,33,333,4,44,444,5,55") local n555 = list:insertAfter(n55, 555) validate(list, "-1,0,1,11,111,2,22,222,3,33,333,4,44,444,5,55,555")
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#8080_Assembly
8080 Assembly
;; On the 44th day of Discord in the YOLD 3186, ddate ;; has finally come to CP/M. bdos: equ 5 ; CP/M syscalls puts: equ 9 putch: equ 2 fcb: equ 5ch month: equ fcb + 1 ; use the FCB as the date argument day: equ month + 2 year: equ day + 2 org 100h ;; CP/M will try to parse the command line arguments as if ;; they are filenames. As luck would have it, MMDDYYYY is ;; 8 characters. It would be a shame not to use this. lxi h,month ; check that the 'filename' is lxi b,0800h ; all digits (and zero out C) argcheck: mov a,m call isdigit jnc argerror ; if not, give an error and exit inx h dcr b jnz argcheck ;; Fix the year (add 1166 to it, digit by digit) lxi d,year + 3 lxi h,yearoffset + 3 mvi b,4 ana a ; Clear carry yeardgt: ldax d ; Get digit adc m ; Add offset digit cpi '9' + 1 ; Did we overshoot? cmc ; Carry is opposite of what we need jnc yearnextdgt ; No carry = no adjustment sui 10 ; Compensate stc ; Carry the one yearnextdgt: stax d ; Save digit dcx d ; Look at more significant digit dcx h dcr b ; Until we're out of digits jnz yeardgt lxi h,year + 4 ; Terminate the year with a $ mvi m,'$' ; for easy output. ;; Is it St. Tib's Day? lxi d,month ; Check month and day lxi h,leap ; Against '0229' mvi b,4 tibcheck: ldax d ; Get date byte cmp m ; Match against leap day jnz notibs ; No match = not Tibs inx h inx d dcr b jnz tibcheck ; if they all match it _is_ Tibs ;; Print "St. Tib's Day in the YOLD NNNN." lxi d,tibsday call outs ; fall through into printyear ;; Print " in the YOLD NNNN." printyear: lxi d,yold call outs lxi d,year jmp outs ; if Tibs, this ends the program ;; It isn't St. Tib's Day. We'll need to do real work :( notibs: lxi h,month ; Find days at beginning of month call parsenum ; (not counting Tibs) dcr a ; subtract one (table is 0-indexed) cpi 12 ; check that month < 12 jnc argerror ; otherwise, argument error ana a ; multiply month by 2 ral ; (entries are 2 bytes wide) lxi h,monthdays ; get days table mov d,c ; look up the entry (C is zero here) mov e,a dad d mov e,m ; load the 16-bit entry into DE inx h mov d,m lxi h,day ; Find day number call parsenum mov l,a ; Add it to the start of the month mov h,c ; (C is still zero) - to get the day dad d ; number (still not counting Tibs) dcx h ; One less (so we have day numbering at 0) push h ; Keep day number lxi d,-365 ; Make sure it isn't >365 dad d jc argerror ; Give an error otherwise pop h ; Restore day number push h ; Keep it around ;; Calculate Erisian weekday lxi d,-5 ; It's not worth it being clever here weekcalc: dad d jc weekcalc lxi d,5 dad d mov b,l lxi h,weekdays ; Print the day of the week call strselect lxi d,commaday ; Print ", day " call outs ;; Calculate season and season day number pop h ; Restore day number mvi b,-1 ; B will be season lxi d,-73 ; L will be day seasoncalc: inr b ; One season further on dad d ; Is 73 days less jc seasoncalc lxi d,73 ; Correct overshoot dad d mov h,b ; H:L = season:day inr l ; One based for output push h ; Push season and day mov a,l ; Print day of season mvi c,'0'-1 ; Tens digit in C seasondgts: inr c sui 10 jnc seasondgts adi '0' + 10 ; Ones digit in A mov e,c ; Tens digit call oute mov e,a ; Ones digit call oute lxi d,of ; Print " of " call outs pop b ; Retrieve season:day push b lxi h,seasons ; Print the season name call strselect call printyear ; "... in the YOLD NNNN ..." ;; Is there any reason to celebrate? (day=5 or day=50) pop b ; Retrieve season:day mov a,c ; Day. cpi 5 ; is it 5? jz party ; Then we party cpi 50 ; otherwise, is it 50? rnz ; If not, we're done party: push b ; Keep day lxi d,celebrate ; "... Celebrate ..." call outs pop b ; Retrieve day push b lxi h,holydays5 ; Get holyday from 5 or 50 table mov a,c cpi 50 jnz dayname lxi h,holydays50 dayname: call strselect ; the season is still in B lxi d,xday pop b ; Retrieve day once more mov a,c cpi 50 jnz outs ; Print 'day' or 'flux' depending lxi d,xflux jmp outs ;; Parse the 2-digit number in HL. Return in B (and A) parsenum: mvi b,0 ; zero accumulator call parsedigit ; this runs it twice parsedigit: mov a,b ; B *= 10 add a mov b,a add a add a add b add m ; Add the digit sui '0' ; Subtract '0' mov b,a inx h ret ;; Print the B'th string from HL strselect: mvi a,'$' strsearcho: dcr b jm strfound strsearchi: cmp m inx h jnz strsearchi jmp strsearcho strfound: xchg jmp outs ;; Print the argument error, and exit argerror: lxi d,argfmt ;; Print the string in DE and exit error: call outs rst 0 ;; Returns with carry flag set if A is a digit ('0'-'9'). isdigit: cpi '0' cmc rnc cpi '9' + 1 ret ;; Print the string in D. outs: mvi c,puts jmp bdos ;; Print character in E, keeping registers. oute: push psw push b push d push h mvi c,putch call bdos pop h pop d pop b pop psw ret ;; Accumulated days at start of Gregorian months ;; (in a non-leap year) monthdays: dw 0,31,59,90,120,151,181,212,243,273,304,334 ;; Difference between Gregorian and Erisian year count ;; (we don't need to bother with the year otherwise) yearoffset: db 1,1,6,6 ;; This is matched to MMDD to handle St. Tib's Day leap: db '0229' ;; Strings argfmt: db 'DDATE MMDDYYYY$' weekdays: db 'Sweetmorn$Boomtime$Pungenday$Prickle-Prickle$' db 'Setting Orange$' commaday: db ', day $' of: db ' of $' seasons: db 'Chaos$Discord$Confusion$Bureaucracy$The Aftermath$' celebrate: db ': celebrate $' holydays5: db 'Mung$Mojo$Sya$Zara$Mala$' xday: db 'day!$' holydays50: db 'Chao$Disco$Confu$Bure$Af$' xflux: db 'flux!$' tibsday: db 'Saint Tib',39,'s Day$' yold: db ' in the YOLD $'  
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#C.2B.2B
C++
  #include <iomanip> #include <map> #include <vector> #include <iostream> using namespace std;   void calcMDR( int n, int c, int& a, int& b ) { int m = n % 10; n /= 10; while( n ) { m *= ( n % 10 ); n /= 10; } if( m >= 10 ) calcMDR( m, ++c, a, b ); else { a = m; b = c; } }   void table() { map<int, vector<int> > mp; int n = 0, a, b; bool f = true; while( f ) { f = false; calcMDR( n, 1, a, b ); mp[a].push_back( n ); n++; for( int x = 0; x < 10; x++ ) if( mp[x].size() < 5 ) { f = true; break; } }   cout << "| MDR | [n0..n4]\n+-------+------------------------------------+\n"; for( int x = 0; x < 10; x++ ) { cout << right << "| " << setw( 6 ) << x << "| "; for( vector<int>::iterator i = mp[x].begin(); i != mp[x].begin() + 5; i++ ) cout << setw( 6 ) << *i << " "; cout << "|\n"; } cout << "+-------+------------------------------------+\n\n"; }   int main( int argc, char* argv[] ) { cout << "| NUMBER | MDR | MP |\n+----------+----------+----------+\n"; int numbers[] = { 123321, 7739, 893, 899998 }, a, b; for( int x = 0; x < 4; x++ ) { cout << right << "| " << setw( 9 ) << numbers[x] << "| "; calcMDR( numbers[x], 1, a, b ); cout << setw( 9 ) << a << "| " << setw( 9 ) << b << "|\n"; } cout << "+----------+----------+----------+\n\n"; table(); return system( "pause" ); }  
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Sidef
Sidef
var rules = Hash( x => 'x+yF+', y => '-Fx-y', )   var lsys = LSystem( width: 600, height: 600,   xoff: -430, yoff: -380,   len: 8, angle: 90, color: 'dark green', )   lsys.execute('Fx', 11, "dragon_curve.png", rules)
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#AWK
AWK
  # syntax: GAWK -f DINESMANS_MULTIPLE-DWELLING_PROBLEM.AWK BEGIN { for (Baker=1; Baker<=5; Baker++) { for (Cooper=1; Cooper<=5; Cooper++) { for (Fletcher=1; Fletcher<=5; Fletcher++) { for (Miller=1; Miller<=5; Miller++) { for (Smith=1; Smith<=5; Smith++) { if (rules() ~ /^1+$/) { printf("%d Baker\n",Baker) printf("%d Cooper\n",Cooper) printf("%d Fletcher\n",Fletcher) printf("%d Miller\n",Miller) printf("%d Smith\n",Smith) } } } } } } exit(0) } function rules( stmt1,stmt2,stmt3,stmt4,stmt5,stmt6,stmt7) { # The following problem statements may be changed: # # Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house # that contains only five floors numbered 1 (ground) to 5 (top) stmt1 = Baker!=Cooper && Baker!=Fletcher && Baker!=Miller && Baker!=Smith && Cooper!=Fletcher && Cooper!=Miller && Cooper!=Smith && Fletcher!=Miller && Fletcher!=Smith && Miller!=Smith stmt2 = Baker != 5 # Baker does not live on the top floor stmt3 = Cooper != 1 # Cooper does not live on the bottom floor stmt4 = Fletcher != 5 && Fletcher != 1 # Fletcher does not live on either the top or the bottom floor stmt5 = Miller > Cooper # Miller lives on a higher floor than does Cooper stmt6 = abs(Smith-Fletcher) != 1 # Smith does not live on a floor adjacent to Fletcher's stmt7 = abs(Fletcher-Cooper) != 1 # Fletcher does not live on a floor adjacent to Cooper's return(stmt1 stmt2 stmt3 stmt4 stmt5 stmt6 stmt7) } function abs(x) { if (x >= 0) { return x } else { return -x } }  
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#jq
jq
  # Input: a string # Output: a stream of sentence type indicators def sentenceTypes: def trim: sub("^ +";"") | sub(" +$";""); def parse: capture("(?<s>[^?!.]*)(?<p>[?!.])(?<remainder>.*)" ) // {p:"", remainder:""}; def encode: if . == "?" then "Q" elif . == "!" then "E" elif . == "." then "S" else "N" end; trim | select(length>0) | parse | (.p | encode), (.remainder | sentenceTypes);   def s: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it";   s | sentenceTypes
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Julia
Julia
const text = """ Hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"""   haspunctotype(s) = '.' in s ? "S" : '!' in s ? "E" : '?' in s ? "Q" : "N"   text = replace(text, "\n" => " ") parsed = strip.(split(text, r"(?:(?:(?<=[\?\!\.])(?:))|(?:(?:)(?=[\?\!\.])))")) isodd(length(parsed)) && push!(parsed, "") # if ends without pnctuation for i in 1:2:length(parsed)-1 println(rpad(parsed[i] * parsed[i + 1], 52), " ==> ", haspunctotype(parsed[i + 1])) end  
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Lua
Lua
text = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" p2t = { [""]="N", ["."]="S", ["!"]="E", ["?"]="Q" } for s, p in text:gmatch("%s*([^%!%?%.]+)([%!%?%.]?)") do print(s..p..": "..p2t[p]) end
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Perl
Perl
use strict; use warnings; use feature 'say'; use Lingua::Sentence;   my $para1 = <<'EOP'; hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it EOP   my $para2 = <<'EOP'; Just because there are punctuation characters like "?", "!" or especially "." present, it doesn't necessarily mean you have reached the end of a sentence, does it Mr. Magoo? The syntax highlighting here for Perl isn't bad at all. EOP   my $splitter = Lingua::Sentence->new("en"); for my $text ($para1, $para2) { for my $s (split /\n/, $splitter->split( $text =~ s/\n//gr ) { print "$s| "; if ($s =~ /!$/) { say 'E' } elsif ($s =~ /\?$/) { say 'Q' } elsif ($s =~ /\.$/) { say 'S' } else { say 'N' } } }
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#BQN
BQN
•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1   # as a tacit function DotP ← +´× •Show 1‿3‿¯5 DotP 4‿¯2‿¯1
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Form 80, 50 Class Null {} Global Null->Null() Class Node { group pred, succ dat=0 Remove { Print "destroyed", .dat } class: module Node { .pred->Null .succ->Null if match("N") Then Read .dat } } Class LList { Group Head, Tail Module PushTail(k as pointer) { if .Tail is Null then { .Head<=k .Tail<=k } else { n=.Tail .Tail<=k k=>pred=n=>pred n=>pred=k k=>succ=n } } Function RemoveTail { n=.Tail if n is .Head then { .Head->Null .Tail->Null } Else { .Tail<=n=>succ .Tail=>pred=n=>pred n=>pred->Null } for n { .succ->Null .pred->Null } =n } Module PushHead(k as pointer) { if .head is Null then { .Head<=k .Tail<=k } else { n=.head .head<=k k=>succ=n=>succ n=>succ=k k=>pred=n } } Function RemoveHead { n=.Head if n is .Tail then { .Head->Null .Tail->Null } Else { .Head<=n=>pred .Head=>succ=n=>succ n=>succ->Null } for n { .succ->Null .pred->Null } =n } Module RemoveNode(k as pointer) { pred=k=>pred succ=k=>succ if pred is succ then { if .head is k else Error "Can't remove this node" k=.RemoveHead() clear k } else { pred=>succ=succ succ=>pred=pred } } Module InsertAfter(k as pointer, n as pointer) { pred=k=>pred n=>pred=pred n=>succ=k pred=>succ=n k=>pred=n } Function IsEmpty { = .Head is null or .tail is null } class: Module LList { .Head->Null .Tail->Null } } m->Node(100)   L=LList() L.PushTail m If not L.Head is Null then Print L.Head=>dat=100 for i=101 to 103 { m->Node(i) L.PushTail m Print "ok....", i } for i=104 to 106 { m->Node(i) L.PushHead m Print "ok....", i }   Print "Use Head to display from last to first" m=L.Head do { Print m=>dat m=m=>pred } Until m is null Print "ok, now find 3rd and remove it" m1=L.Head i=1 Index=3 While i<Index { if m1 is null then exit m1=m1=>pred i++ } If i<>Index then { Print "List has less than "; Index;" Items" } Else { Print "First add one new node" newNode->Node(1000) L.InsertAfter m1, newNode L.RemoveNode m1 clear m1 ' last time m1 used here newNode=Null Print "ok.............." } Print "Use Tail to display from first to last" m=L.Tail do { Print m=>dat m=m=>succ } Until m is null     useother=True While not L.IsEmpty(){ For This { \\ we have to use a temporary variable name, here A A=If(useother->L.RemoveTail(),L.RemoveHead())  ? A=>dat useother~ \\ now we can try to perform removing clear A } } Print "list is empty:"; L.IsEmpty() } Checkit  
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#8086_Assembly
8086 Assembly
;; DDATE for MS-DOS (assembles using nasm) bits 16 cpu 8086 tlength: equ 80h cmdtail: equ 81h putch: equ 2 puts: equ 9 getdate: equ 2Ah org 100h section .text ;; Check if a date was given mov bl,[tlength] ; Length of command line and bl,bl ; Is it zero? jz gettoday ; Then get today's date ;; Parse the date given on the command line cmp bl,10+1 ; MM/DD/YYYY is ten characters long jne printusage ; If it doesn't match, print usage. xor bh,bh add bx,cmdtail mov byte [bx],0 ; Zero terminate the date mov si,cmdtail+1 ; Get month, call atoi mov dh,al ; store in DH, inc si ; get day, call atoi mov dl,al ; store in DL, inc si ; get year, call atoi mov cx,ax ; and store in CX. jmp convertdate ;; Ask MS-DOS for the date gettoday: mov ah,puts ; Prefix output with 'Today is ' mov dx,todayis int 21h mov ah,getdate ; And get the current date. int 21h ;; Convert the date to the Discordian calendar ;; (DL=day, DH=month, CX=year) convertdate: add cx,1166 ; Erisian year is 1166 years onwards. cmp dx,21dh ; Is it St. Tib's Day? jne notibs mov dx,tibsday ; If yes, print "St. Tib's Day" mov ah,puts int 21h ;; Print "in the YOLD NNNN" and then end. intheyold: mov dx,yold ; In the YOLD mov ah,puts int 21h mov ax,cx ; print the year call printn ret ; If Tibs, this ends the program. ;; It isn't St. Tib's Day. notibs: cmp dh,1 ; Month < 1 = error jb printinval cmp dl,1 ; Day < 1 = error jb printinval cmp dh,12 ; Month > 12 = error ja printinval mov bx,monthlengths-1 xor ah,ah ; Day higher than it should be mov al,dh ; (according to month table) add bx,ax ; = error cmp dl,[bx] ja printinval mov bx,monthdays-2 ; Calculate day of year mov al,dh ; Cumulative months sal al,1 ; Multiply by 2 (2 bits per entry) add bx,ax mov ax,[bx] ; Days since start of month xor dh,dh add dx,ax ; Add day of month dec dx ; Start at 0 (For array lookup) mov ax,dx ; Get weekday mov bl,5 ; Divide by 5 div bl ; AH = weekday (modulo) mov bl,ah mov di,weekdays call strselect ; Print the weekday mov bx,dx ; Keep day of year in bx for now mov dx,commaday ; ... ', day ' call printstr mov dl,73 ; Each season is 73 days long mov ax,bx ; Divide day of year by 73 div dl ; DH=AH=day of season (modulo) mov dx,ax ; DL=AL=season number xor ah,ah ; Print day of season mov al,dh inc al ; One more (days do start at 1) call printn mov bx,dx ; Store day and season in bx mov dx,of ; Print ... ' of ' call printstr mov dx,bx ; Day and season in dx again mov di,seasons ; Print season call strselect ; BL is still season number mov bx,dx ; Day and season in BX again. call intheyold ; Print the year cmp bh,5-1 ; Something to celebrate? je party ; (Day 5 or 50? cmp bh,50-1 je party ret ; If not, stop. party: mov al,bh ; Day in AL. mov bx,holydays5 ; Day 5 holydays. mov cx,xday cmp al,50-1 ; Unless it's 50 jne holyday mov bx,holydays50 ; Then we need day 50 holydays. mov cx,xflux holyday: mov dx,celebrate ; Print ... ', celebrate: ' call printstr mov dx,bx call printstr mov dx,cx jmp printstr ;; Print "invalid date". printinval: mov dx,inval jmp printstr ;; Print usage. printusage: mov dx,usage ;; Print DX. printstr: mov ah,puts int 21h ret ;; Subroutine: print the BL'th string from DI strselect: inc bl ; Counter the 'dec bl' later mov al,'$' ; String end push cx ; Keep registers push dx .search dec bl ; Are we there yet? jz .found mov cx,-1 repne scasb ; Scan to end of string jmp .search .found mov dx,di ; Found the string, print it mov ah,puts int 21h pop dx ; Restore registers pop cx ret ;; Subroutine: print number in AX. printn: push cx ; Don't trample registers push dx mov si,numend ; End of number string. mov cx,10 ; Divisor, ten. .loop xor dx,dx ; Zero DX. dec si ; Back up one digit. div cx ; Divide AX by ten. add dl,'0' ; Remainder is now in DX; make ASCII mov [si],dl ; and store. and ax,ax ; Quotient is in AX, check if zero jnz .loop ; loop for next digit if there is one. mov dx,si ; Print SI - move it to DX, mov ah,puts ; and then call the DOS print function int 21h pop dx ; Restore the registers pop cx ret ;; Subroutine: parse number at [SI], store in AX. atoi: push bx ; Don't trample registers push cx push dx xor ax,ax ; Zero AX. xor bh,bh ; BH as well. mov cx,10 ; Multiplier, ten. .loop mov bl,[si] ; Current number. sub bl,'0' ; Subtract '0'. jc .done ; If <0, then done. cmp bl,9 ; If it's higher than 9, jnbe .done ; also done. mul cx ; Multiply accumulator by 10 add ax,bx ; Add the digit in. inc si ; Next digit jmp .loop .done pop dx ; Restore registers pop cx pop bx ret section .data ;; Accumulated days at start of Gregorian months monthdays: dw 0,31,59,90,120,151,181,212,243,273,304,334 ;; Days per month monthlengths: db 31,28,31,30,31,30,31,31,30,31,30,31 ;; Strings inval: db 'Invalid date.$' usage: db `DDATE [MM/DD/YYYY]\r\n` db `\r\n\tPrint today's date or the given date in the` db ` Discordian calendar.$` number: db '00000' numend: db '$' todayis: db 'Today is $' weekdays: db 'Sweetmorn$Boomtime$Pungenday$Prickle-Prickle$' db 'Setting Orange$' commaday: db ', day $' of: db ' of $' seasons: db 'Chaos$Discord$Confusion$Bureaucracy$The Aftermath$' celebrate: db ': celebrate $' holydays5: db 'Mung$Mojo$Sya$Zara$Mala$' xday: db 'day!$' holydays50: db 'Chao$Disco$Confu$Bure$Af$' xflux: db 'flux!$' tibsday: db "Saint Tib's Day$" yold: db ' in the YOLD $'
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#11l
11l
T Edge String start String end Int cost   F (start, end, cost) .start = start .end = end .cost = cost   T Graph [Edge] edges Set[String] vertices   F (edges) .edges = edges.map((s, e, c) -> Edge(s, e, c)) .vertices = Set(.edges.map(e -> e.start)).union(Set(.edges.map(e -> e.end)))   F dijkstra(source, dest) assert(source C .vertices) V dist = Dict(.vertices, vertex -> (vertex, Float.infinity)) V previous = Dict(.vertices, vertex -> (vertex, ‘’)) dist[source] = 0 V q = copy(.vertices) V neighbours = Dict(.vertices, vertex -> (vertex, [(String, Int)]())) L(start, end, cost) .edges neighbours[start].append((end, cost))   L !q.empty V u = min(q, key' vertex -> @dist[vertex]) q.remove(u) I dist[u] == Float.infinity | u == dest L.break L(v, cost) neighbours[u] V alt = dist[u] + cost I alt < dist[v] dist[v] = alt previous[v] = u   Deque[String] s V u = dest L previous[u] != ‘’ s.append_left(u) u = previous[u] s.append_left(u) R s   V graph = Graph([(‘a’, ‘b’, 7), (‘a’, ‘c’, 9), (‘a’, ‘f’, 14), (‘b’, ‘c’, 10), (‘b’, ‘d’, 15), (‘c’, ‘d’, 11), (‘c’, ‘f’, 2), (‘d’, ‘e’, 6), (‘e’, ‘f’, 9)]) print(graph.dijkstra(‘a’, ‘e’))
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#11l
11l
F digital_root(=n) V ap = 0 L n >= 10 n = sum(String(n).map(digit -> Int(digit))) ap++ R (ap, n)   L(n) [Int64(627615), 39390, 588225, 393900588225, 55] Int64 persistance, root (persistance, root) = digital_root(n) print(‘#12 has additive persistance #2 and digital root #..’.format(n, persistance, root))
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#CLU
CLU
digits = iter (n: int) yields (int) while n>0 do yield(n//10) n := n/10 end end digits   mdr = proc (n: int) returns (int,int) i: int := 0 while n>=10 do m: int := 1 for d: int in digits(n) do m := m * d end n := m i := i+1 end return (i,n) end mdr   first_mdr = iter (target_mdr, n: int) yields (int) i: int := 0 while n>0 do x, m: int := mdr(i) if m=target_mdr then yield(i) n := n -1 end i := i+1 end end first_mdr   start_up = proc () po: stream := stream$primary_output() nums: sequence[int] := sequence[int]$[123321, 7739, 893, 899998]   stream$putl(po, " N MDR MP") stream$putl(po, "====== === ==") for num: int in sequence[int]$elements(nums) do stream$putright(po, int$unparse(num), 6) stream$puts(po, " ") i, m: int := mdr(num) stream$putright(po, int$unparse(m), 3) stream$puts(po, " ") stream$putright(po, int$unparse(i), 3) stream$putl(po, "") end   stream$putl(po, "\nMDR: [n0..n4]") stream$putl(po, "=== ========") for dgt: int in int$from_to(0,9) do stream$putright(po, int$unparse(dgt), 3) stream$puts(po, ": ") for num: int in first_mdr(dgt, 5) do stream$puts(po, int$unparse(num) || " ") end stream$putl(po, "") end end start_up
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Smalltalk
Smalltalk
levels = 16 level = 0 step = 1 > draw(level) level += step  ? level>levels step = -1 level += step*2 .  ? level=0, step = 1 #.delay(1) <   draw(level)= mx,my = #.scrsize() fs = #.min(mx,my)/2 r = fs/2^((level-1)/2) x = mx/2+fs*#.sqrt(2)/2 y = my/2+fs/4 a = #.pi/4*(level-2) #.scroff() #.scrclear() #.drawline(x,y,x,y) ss = 2^level-1 > i, 0..ss  ? #.and(#.and(i,-i)*2,i) a += #.pi/2  ! a -= #.pi/2 . x += r*#.cos(a) y += r*#.sin(a) #.drawcolor(#.hsv2rgb(i/(ss+1)*360,1,1):3) #.drawline(x,y) < #.scr() .
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#BASIC
BASIC
print "Los apartamentos están numerados del 0 (bajo) al 4 (ático)." print "Baker, Cooper, Fletcher, Miller y Smith viven en apartamentos diferentes." print "- Baker no vive en el último apartamento (ático)." print "- Cooper no vive en el piso inferior (bajo)." print "- Fletcher no vive ni en el ático ni en el bajo." print "- Miller vive en un apartamento más alto que Cooper." print "- Smith no vive en un apartamento adyacente al de Fletcher." print "- Fletcher no vive en un apartamento adyacente al de Cooper." & chr(10)   for Baker = 0 to 3 for Cooper = 1 to 4 for Fletcher = 1 to 3 for Miller = 0 to 4 for Smith = 0 to 4 if Baker<>Cooper and Baker<>Fletcher and Baker<>Miller and Baker<>Smith and Cooper<>Fletcher and Cooper<>Miller and Cooper<>Smith and Fletcher<>Miller and Fletcher<>Smith and Miller<>Smith and Miller>Cooper and abs(Smith-Fletcher)<>1 and abs(Fletcher-Cooper)<>1 then print "Baker vive en el piso "; Baker print "Cooper vive en el piso "; Cooper print "Fletcher vive en el piso "; Fletcher print "Miller vive en el piso "; Miller print "Smith vive en el piso "; Smith end if next Smith next Miller next Fletcher next Cooper next Baker end
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Phix
Phix
with javascript_semantics constant s = `hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it` sequence t = split_any(trim(s),"?!."), u = substitute_all(s,t,repeat("|",length(t))), v = substitute_all(u,{"|?","|!","|.","|"},"QESN"), w = join(v,'|') ?w
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Python
Python
import re   txt = """ Hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"""   def haspunctotype(s): return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N'   txt = re.sub('\n', '', txt) pars = [s.strip() for s in re.split("(?:(?:(?<=[\?\!\.])(?:))|(?:(?:)(?=[\?\!\.])))", txt)] if len(pars) % 2: pars.append('') # if ends without punctuation for i in range(0, len(pars)-1, 2): print((pars[i] + pars[i + 1]).ljust(54), "==>", haspunctotype(pars[i + 1]))  
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#Bracmat
Bracmat
( dot = a A z Z .  !arg:(%?a ?z.%?A ?Z) & !a*!A+dot$(!z.!Z) | 0 ) & out$(dot$(1 3 -5.4 -2 -1));
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#C
C
#include <stdio.h> #include <stdlib.h>   int dot_product(int *, int *, size_t);   int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1};   printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));   return EXIT_SUCCESS; }   int dot_product(int *a, int *b, size_t n) { int sum = 0; size_t i;   for (i = 0; i < n; i++) { sum += a[i] * b[i]; }   return sum; }
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ds = CreateDataStructure["DoublyLinkedList"]; ds["Append", #] & /@ {1, 5, 7, 0, 3, 2}; ds["Prepend", 9]; ds["Append", 4]; (* This is adding at the end and then swap to insert in to the middle: *) ds["Append", 14]; ds["SwapPart", Round[ds["Length"]/2], ds["Length"]]; ds["Elements"]
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#11l
11l
F throw_die(n_sides, n_dice, s, [Int] &counts) I n_dice == 0 counts[s]++ R L(i) 1..n_sides throw_die(n_sides, n_dice - 1, s + i, counts)   F beating_probability(n_sides1, n_dice1, n_sides2, n_dice2) V len1 = (n_sides1 + 1) * n_dice1 V C1 = [0] * len1 throw_die(n_sides1, n_dice1, 0, &C1)   V len2 = (n_sides2 + 1) * n_dice2 V C2 = [0] * len2 throw_die(n_sides2, n_dice2, 0, &C2)   Float p12 = (n_sides1 ^ n_dice1) * (n_sides2 ^ n_dice2)   V tot = 0.0 L(i) 0 .< len1 L(j) 0 .< min(i, len2) tot += Float(C1[i]) * C2[j] / p12 R tot   print(‘#.16’.format(beating_probability(4, 9, 6, 6))) print(‘#.16’.format(beating_probability(10, 5, 7, 6)))
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Ada
Ada
with Ada.Calendar.Arithmetic; with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Text_IO; with Ada.Command_Line;   procedure Discordian is use Ada.Calendar; use Ada.Strings.Unbounded; use Ada.Command_Line; package UStr_IO renames Ada.Strings.Unbounded.Text_IO;   subtype Year_Number is Integer range 3067 .. 3565; type Seasons is (Chaos, Discord, Confusion, Bureaucracy, The_Aftermath); type Days_Of_Week is (Sweetmorn, Boomtime, Pungenday, Prickle_Prickle, Setting_Orange); subtype Day_Number is Integer range 1 .. 73;   type Discordian_Date is record Year  : Year_Number; Season  : Seasons; Day  : Day_Number; Week_Day  : Days_Of_Week; Is_Tibs_Day : Boolean := False; end record;   function Week_Day_To_Str(Day : Days_Of_Week) return Unbounded_String is s : Unbounded_String; begin case Day is when Sweetmorn => s := To_Unbounded_String("Sweetmorn"); when Boomtime => s := To_Unbounded_String("Boomtime"); when Pungenday => s := To_Unbounded_String("Pungenday"); when Prickle_Prickle => s := To_Unbounded_String("Prickle-Prickle"); when Setting_Orange => s := To_Unbounded_String("Setting Orange"); end case; return s; end Week_Day_To_Str;   function Holiday(Season: Seasons) return Unbounded_String is s : Unbounded_String; begin case Season is when Chaos => s := To_Unbounded_String("Chaoflux"); when Discord => s := To_Unbounded_String("Discoflux"); when Confusion => s := To_Unbounded_String("Confuflux"); when Bureaucracy => s := To_Unbounded_String("Bureflux"); when The_Aftermath => s := To_Unbounded_String("Afflux"); end case; return s; end Holiday;   function Apostle(Season: Seasons) return Unbounded_String is s : Unbounded_String; begin case Season is when Chaos => s := To_Unbounded_String("Mungday"); when Discord => s := To_Unbounded_String("Mojoday"); when Confusion => s := To_Unbounded_String("Syaday"); when Bureaucracy => s := To_Unbounded_String("Zaraday"); when The_Aftermath => s := To_Unbounded_String("Maladay"); end case; return s; end Apostle;   function Season_To_Str(Season: Seasons) return Unbounded_String is s : Unbounded_String; begin case Season is when Chaos => s := To_Unbounded_String("Chaos"); when Discord => s := To_Unbounded_String("Discord"); when Confusion => s := To_Unbounded_String("Confusion"); when Bureaucracy => s := To_Unbounded_String("Bureaucracy"); when The_Aftermath => s := To_Unbounded_String("The Aftermath"); end case; return s; end Season_To_Str;   procedure Convert (From : Time; To : out Discordian_Date) is use Ada.Calendar.Arithmetic; First_Day  : Time; Number_Days : Day_Count; Leap_Year  : boolean; begin First_Day  := Time_Of (Year => Year (From), Month => 1, Day => 1); Number_Days := From - First_Day;   To.Year  := Year (Date => From) + 1166; To.Is_Tibs_Day := False; Leap_Year := False; if Year (Date => From) mod 4 = 0 then if Year (Date => From) mod 100 = 0 then if Year (Date => From) mod 400 = 0 then Leap_Year := True; end if; else Leap_Year := True; end if; end if; if Leap_Year then if Number_Days > 59 then Number_Days := Number_Days - 1; elsif Number_Days = 59 then To.Is_Tibs_Day := True; end if; end if; To.Day := Day_Number (Number_Days mod 73 + 1); case Number_Days / 73 is when 0 => To.Season := Chaos; when 1 => To.Season := Discord; when 2 => To.Season := Confusion; when 3 => To.Season := Bureaucracy; when 4 => To.Season := The_Aftermath; when others => raise Constraint_Error; end case; case Number_Days mod 5 is when 0 => To.Week_Day := Sweetmorn; when 1 => To.Week_Day := Boomtime; when 2 => To.Week_Day := Pungenday; when 3 => To.Week_Day := Prickle_Prickle; when 4 => To.Week_Day := Setting_Orange; when others => raise Constraint_Error; end case; end Convert;   procedure Put (Item : Discordian_Date) is begin if Item.Is_Tibs_Day then Ada.Text_IO.Put ("St. Tib's Day"); else UStr_IO.Put (Week_Day_To_Str(Item.Week_Day)); Ada.Text_IO.Put (", day" & Integer'Image (Item.Day)); Ada.Text_IO.Put (" of "); UStr_IO.Put (Season_To_Str (Item.Season)); if Item.Day = 5 then Ada.Text_IO.Put (", "); UStr_IO.Put (Apostle(Item.Season)); elsif Item.Day = 50 then Ada.Text_IO.Put (", "); UStr_IO.Put (Holiday(Item.Season)); end if; end if; Ada.Text_IO.Put (" in the YOLD" & Integer'Image (Item.Year)); Ada.Text_IO.New_Line; end Put;   Test_Day  : Time; Test_DDay : Discordian_Date; Year : Integer; Month : Integer; Day : Integer; YYYYMMDD : Integer; begin   if Argument_Count = 0 then Test_Day := Clock; Convert (From => Test_Day, To => Test_DDay); Put (Test_DDay); end if;   for Arg in 1..Argument_Count loop   if Argument(Arg)'Length < 8 then Ada.Text_IO.Put("ERROR: Invalid Argument : '" & Argument(Arg) & "'"); Ada.Text_IO.Put("Input format YYYYMMDD"); raise Constraint_Error; end if;   begin YYYYMMDD := Integer'Value(Argument(Arg)); exception when Constraint_Error => Ada.Text_IO.Put("ERROR: Invalid Argument : '" & Argument(Arg) & "'"); raise; end;   Day := YYYYMMDD mod 100; if Day < Day_Number'First or Day > Day_Number'Last then Ada.Text_IO.Put("ERROR: Invalid Day:" & Integer'Image(Day)); raise Constraint_Error; end if;   Month := ((YYYYMMDD - Day) / 100) mod 100; if Month < Month_Number'First or Month > Month_Number'Last then Ada.Text_IO.Put("ERROR: Invalid Month:" & Integer'Image(Month)); raise Constraint_Error; end if;   Year := ((YYYYMMDD - Day - Month * 100) / 10000); if Year < 1901 or Year > 2399 then Ada.Text_IO.Put("ERROR: Invalid Year:" & Integer'Image(Year)); raise Constraint_Error; end if;   Test_Day := Time_Of (Year => Year, Month => Month, Day => Day);   Convert (From => Test_Day, To => Test_DDay); Put (Test_DDay);   end loop;   end Discordian;  
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#Ada
Ada
private with Ada.Containers.Ordered_Maps; generic type t_Vertex is (<>); package Dijkstra is   type t_Graph is limited private;   -- Defining a graph (since limited private, only way to do this is to use the Build function) type t_Edge is record From, To : t_Vertex; Weight  : Positive; end record; type t_Edges is array (Integer range <>) of t_Edge; function Build (Edges : in t_Edges; Oriented : in Boolean := True) return t_Graph;   -- Computing path and distance type t_Path is array (Integer range <>) of t_Vertex; function Shortest_Path (Graph  : in out t_Graph; From, To : in t_Vertex) return t_Path; function Distance (Graph  : in out t_Graph; From, To : in t_Vertex) return Natural;   private package Neighbor_Lists is new Ada.Containers.Ordered_Maps (Key_Type => t_Vertex, Element_Type => Positive); type t_Vertex_Data is record Neighbors : Neighbor_Lists.Map; -- won't be affected after build -- Updated each time a function is called with a new source Previous  : t_Vertex; Distance  : Natural; end record; type t_Graph is array (t_Vertex) of t_Vertex_Data; end Dijkstra;
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#360_Assembly
360 Assembly
* Digital root 21/04/2017 DIGROOT CSECT USING DIGROOT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R6,1 i=1 DO WHILE=(C,R6,LE,=A((PG-T)/4)) do i=1 to hbound(t) LR R1,R6 i SLA R1,2 *4 L R10,T-4(R1) nn=t(i) LR R7,R10 n=nn SR R9,R9 ap=0 DO WHILE=(C,R7,GE,=A(10)) do while(n>=10) SR R8,R8 x=0 DO WHILE=(C,R7,GE,=A(10)) do while(n>=10) LR R4,R7 n SRDA R4,32 >>r5 D R4,=A(10) m=n//10 LR R7,R5 n=n/10 AR R8,R4 x=x+m ENDDO , end AR R7,R8 n=x+n LA R9,1(R9) ap=ap+1 ENDDO , end XDECO R10,XDEC nn MVC PG+7(10),XDEC+2 XDECO R9,XDEC ap MVC PG+31(3),XDEC+9 XDECO R7,XDEC n MVC PG+41(1),XDEC+11 XPRNT PG,L'PG print LA R6,1(R6) i++ ENDDO , enddo i L R13,4(0,R13) restore previous savearea pointer LM R14,R12,12(R13) restore previous context XR R15,R15 rc=0 BR R14 exit T DC F'627615',F'39390',F'588225',F'2147483647' PG DC CL80'number=xxxxxxxxxx persistence=xxx root=x' XDEC DS CL12 YREGS END DIGROOT
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Ada
Ada
package Generic_Root is type Number is range 0 .. 2**63-1; type Number_Array is array(Positive range <>) of Number; type Base_Type is range 2 .. 16; -- any reasonable base to write down numb   generic with function "&"(X, Y: Number) return Number; -- instantiate with "+" for additive digital roots -- instantiate with "*" for multiplicative digital roots procedure Compute_Root(N: Number; Root, Persistence: out Number; Base: Base_Type := 10); -- computes Root and Persistence of N;   end Generic_Root;
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Common_Lisp
Common Lisp
  (defun mdr/p (n) "Return a list with MDR and MP of n" (if (< n 10) (list n 0) (mdr/p-aux n 1 1)))   (defun mdr/p-aux (n a c) (cond ((and (zerop n) (< a 10)) (list a c)) ((zerop n) (mdr/p-aux a 1 (+ c 1))) (t (mdr/p-aux (floor n 10) (* (rem n 10) a) c))))   (defun first-n-number-for-each-root (n &optional (r 0) (lst nil) (c 0)) "Return the first m number with MDR = 0 to 9" (cond ((and (= (length lst) n) (= r 9)) (format t "~3@a: ~a~%" r (reverse lst))) ((= (length lst) n) (format t "~3@a: ~a~%" r (reverse lst)) (first-n-number-for-each-root n (+ r 1) nil 0)) ((= (first (mdr/p c)) r) (first-n-number-for-each-root n r (cons c lst) (+ c 1))) (t (first-n-number-for-each-root n r lst (+ c 1)))))   (defun start () (format t "Number: MDR MD~%") (loop for el in '(123321 7739 893 899998) do (format t "~6@a: ~{~3@a ~}~%" el (mdr/p el))) (format t "~%MDR: [n0..n4]~%") (first-n-number-for-each-root 5))
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#SPL
SPL
levels = 16 level = 0 step = 1 > draw(level) level += step  ? level>levels step = -1 level += step*2 .  ? level=0, step = 1 #.delay(1) <   draw(level)= mx,my = #.scrsize() fs = #.min(mx,my)/2 r = fs/2^((level-1)/2) x = mx/2+fs*#.sqrt(2)/2 y = my/2+fs/4 a = #.pi/4*(level-2) #.scroff() #.scrclear() #.drawline(x,y,x,y) ss = 2^level-1 > i, 0..ss  ? #.and(#.and(i,-i)*2,i) a += #.pi/2  ! a -= #.pi/2 . x += r*#.cos(a) y += r*#.sin(a) #.drawcolor(#.hsv2rgb(i/(ss+1)*360,1,1):3) #.drawline(x,y) < #.scr() .
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#Bracmat
Bracmat
( Baker Cooper Fletcher Miller Smith:?people & ( constraints = .  !arg  : ~(? Baker)  : ~(Cooper ?)  : ~(Fletcher ?|? Fletcher)  : ? Cooper ? Miller ?  : ~(? Smith Fletcher ?|? Fletcher Smith ?)  : ~(? Cooper Fletcher ?|? Fletcher Cooper ?) ) & ( solution = floors persons A Z person .  !arg:(?floors.?persons) & (  !persons: & constraints$!floors & out$("Inhabitants, from bottom to top:" !floors) & ~ { The ~ always fails on evaluation. Here, failure forces Bracmat to backtrack and find all solutions, not just the first one. } |  !persons  :  ?A  %?`person (?Z&solution$(!floors !person.!A !Z)) ) ) & solution$(.!people) | { After outputting all solutions, the lhs of the | operator fails. The rhs of the | operator, here an empty string, is the final result. } );
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Raku
Raku
use Lingua::EN::Sentence;   my $paragraph = q:to/PARAGRAPH/; hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it     Just because there are punctuation characters like "?", "!" or especially "." present, it doesn't necessarily mean you have reached the end of a sentence, does it Mr. Magoo? The syntax highlighting here for Raku isn't the best. PARAGRAPH   say join "\n\n", $paragraph.&get_sentences.map: { /(<:punct>)$/; $_ ~ ' | ' ~ do given $0 { when '!' { 'E' }; when '?' { 'Q' }; when '.' { 'S' }; default { 'N' }; } }
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Vlang
Vlang
fn sentence_type(s string) string { if s.len == 0 { return "" } mut types := []string{} for c in s.split('') { if c == '?' { types << "Q" } else if c == '!' { types << "E" } else if c == '.' { types << "S" } } if s[s.len-1..s.len].index_any('?!.') == -1 { types << "N" } return types.join("|") }   fn main() { s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" println(sentence_type(s)) }
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#Wren
Wren
var sentenceType = Fn.new { |s| if (s.count == 0) return "" var types = [] for (c in s) { if (c == "?") { types.add("Q") } else if (c == "!") { types.add("E") } else if (c == ".") { types.add("S") } } if (!"?!.".contains(s[-1])) types.add("N") return types.join("|") }   var s = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" System.print(sentenceType.call(s))
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#C.23
C#
static void Main(string[] args) { Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 })); Console.Read(); }   private static decimal DotProduct(decimal[] vec1, decimal[] vec2) { if (vec1 == null) return 0;   if (vec2 == null) return 0;   if (vec1.Length != vec2.Length) return 0;   decimal tVal = 0; for (int x = 0; x < vec1.Length; x++) { tVal += vec1[x] * vec2[x]; }   return tVal; }
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Nim
Nim
type List[T] = object head, tail: Node[T]   Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T   proc initList[T](): List[T] = discard   proc newNode[T](data: T): Node[T] = new(result) result.data = data   proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.head != nil: l.head.prev = n l.head = n if l.tail == nil: l.tail = n   proc append[T](l: var List[T], n: Node[T]) = n.next = nil n.prev = l.tail if l.tail != nil: l.tail.next = n l.tail = n if l.head == nil: l.head = n   proc insertAfter[T](l: var List[T], r, n: Node[T]) = n.prev = r n.next = r.next n.next.prev = n r.next = n if r == l.tail: l.tail = n   proc remove[T](l: var List[T], n: Node[T]) = if n == l.tail: l.tail = n.prev if n == l.head: l.head = n.next if n.next != nil: n.next.prev = n.prev if n.prev != nil: n.prev.next = n.next   proc `$`[T](l: var List[T]): string = result = "" var n = l.head while n != nil: if result.len > 0: result.add(" -> ") result.add($n.data) n = n.next   var l = initList[int]() var n = newNode(12) var m = newNode(13) var i = newNode(14) var j = newNode(15) l.append(n) l.prepend(m) l.insertAfter(m, i) l.prepend(j) l.remove(m) echo l   var l2 = initList[string]() l2.prepend newNode("hello") l2.append newNode("world") echo l2
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   BYTE FUNC Roll(BYTE sides,dices) BYTE i,sum   sum=0 FOR i=1 TO dices DO sum==+Rand(sides)+1 OD RETURN (sum)   PROC Test(BYTE sides1,dices1,sides2,dices2) INT i,count=[10000],sum1,sum2,wins1,wins2,draws REAL r1,r2,p   wins1=0 wins2=0 draws=0 FOR i=1 TO count DO sum1=Roll(sides1,dices1) sum2=Roll(sides2,dices2) IF sum1>sum2 THEN wins1==+1 ELSEIF sum1<sum2 THEN wins2==+1 ELSE draws==+1 FI OD   IntToReal(wins1,r1) IntToReal(wins2,r2) RealDiv(r2,r1,p)   PrintF("Tested %I times%E",count) PrintF("Player 1 with %B dice of %B sides%E",dices1,sides1) PrintF("Player 2 with %B dice of %B sides%E",dices2,sides2) PrintF("Player 1 wins %I times%E",wins1) PrintF("Player 2 wins %I times%E",wins2) PrintF("Draw %I times%E",draws) Print("Player 1 beating Player 2 probability:") PrintRE(p) PutE() RETURN   PROC Main() Put(125) PutE() ;clear the screen   Test(4,9,6,6) Test(10,5,7,6) RETURN
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random;   procedure Main is package real_io is new Float_IO (Long_Float); use real_io;   type Dice is record Faces  : Positive; Num_Dice : Positive; end record;   procedure Roll_Dice (The_Dice : in Dice; Count : out Natural) is subtype Faces is Integer range 1 .. The_Dice.Faces; package Die_Random is new Ada.Numerics.Discrete_Random (Faces); use Die_Random; Seed : Generator; begin Reset (Seed); Count := 0; for I in 1 .. The_Dice.Num_Dice loop Count := Count + Random (Seed); end loop; end Roll_Dice;   function Win_Prob (Dice_1 : Dice; Dice_2 : Dice; Tries : Positive) return Long_Float is Count_1  : Natural := 0; Count_2  : Natural := 0; Count_1_Wins : Natural := 0; begin for I in 1 .. Tries loop Roll_Dice (Dice_1, Count_1); Roll_Dice (Dice_2, Count_2); if Count_1 > Count_2 then Count_1_Wins := Count_1_Wins + 1; end if; end loop; return Long_Float (Count_1_Wins) / Long_Float (Tries); end Win_Prob;   D1 : Dice := (Faces => 4, Num_Dice => 9); D2 : Dice := (Faces => 6, Num_Dice => 6); D3 : Dice := (Faces => 10, Num_Dice => 5); D4 : Dice := (Faces => 7, Num_Dice => 6);   P1 : Long_Float := Win_Prob (D1, D2, 1_000_000); P2 : Long_Float := Win_Prob (D3, D4, 1_000_000); begin Put ("Dice D1 wins = "); Put (Item => P1, Fore => 1, Aft => 7, Exp => 0); New_Line; Put ("Dice D2 wins = "); Put (Item => P2, Fore => 1, Aft => 7, Exp => 0); New_Line; end Main;  
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#Ada
Ada
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Text_IO; use Ada.Text_IO;   with Synchronization.Generic_Mutexes_Array;   procedure Test_Dining_Philosophers is type Philosopher is (Aristotle, Kant, Spinoza, Marx, Russel); package Fork_Arrays is new Synchronization.Generic_Mutexes_Array (Philosopher); use Fork_Arrays;   Life_Span : constant := 20; -- In his life a philosopher eats 20 times Forks : aliased Mutexes_Array; -- Forks for hungry philosophers   function Left_Of (Fork : Philosopher) return Philosopher is begin if Fork = Philosopher'First then return Philosopher'Last; else return Philosopher'Pred (Fork); end if; end Left_Of;   task type Person (ID : Philosopher); task body Person is Cutlery : aliased Mutexes_Set := ID or Left_Of (ID); Dice  : Generator; begin Reset (Dice); for Life_Cycle in 1..Life_Span loop Put_Line (Philosopher'Image (ID) & " is thinking"); delay Duration (Random (Dice) * 0.100); Put_Line (Philosopher'Image (ID) & " is hungry"); declare Lock : Set_Holder (Forks'Access, Cutlery'Access); begin Put_Line (Philosopher'Image (ID) & " is eating"); delay Duration (Random (Dice) * 0.100); end; end loop; Put_Line (Philosopher'Image (ID) & " is leaving"); end Person;   Ph_1 : Person (Aristotle); -- Start philosophers Ph_2 : Person (Kant); Ph_3 : Person (Spinoza); Ph_4 : Person (Marx); Ph_5 : Person (Russel); begin null; -- Nothing to do in the main task, just sit and behold end Test_Dining_Philosophers;
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_68
ALGOL 68
BEGIN # DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD VIA ALGOL W # INT greg, gmonth, gday, gyear; []STRING holys = []STRING( "MUNG", "MOJO", "SYA", "ZARA", "MALA" )[ AT 0 ]; []STRING holys0 = []STRING( "CHAO", "DISCO", "CONFU", "BURE", "AF" )[ AT 0 ]; []STRING disday = []STRING( "SWEETMORN", "BOOMTIME", "PUNGENday", "PRICKLE-PRICKLE", "SETTING ORANGE" )[ AT 0 ]; []STRING disssn = []STRING( "CHAOS", "DISCORD", "CONFUSION", "BUREAUCRACY", "THE AFTERMATH" )[ AT 0 ]; []INT mlengt = []INT( 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 )[ AT 0 ]; CHAR slash1, slash2;   # input date should contain MM/DD/YYYY in the gregorian calendar # read( ( gmonth, slash1, gday, slash2, gyear ) ); IF slash1 /= "/" OR slash2 /= "/" THEN print( ( "Invalid date format", newline ) ); stop FI;   IF gmonth = 2 AND gday = 29 THEN print( ( "SAINT TIB'S DAY IN THE Y.O.L.D. ", whole( gyear + 1166, -4 ), newline ) ) ELSE INT yrday := mlengt[ gmonth ] + gday; INT season := yrday OVER 73; INT day := yrday - ( season * 73 ); INT wkday := ( yrday - 1 ) MOD 5; print( ( disday[ wkday ], ", DAY ", whole( day, -2 ), " OF ", disssn[ season ] , " IN THE Y.O.L.D ", whole( gyear + 1166, 0 ), newline ) ); IF day = 5 THEN print( ( "CELEBRATE ", holys[ season ], "DAY" ) ) ELIF day = 50 THEN print( ( "CELEBRATE ", holys0[ season ], "FLUX" ) ) FI FI END
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_dijkstras_algorithm.a68" CO MODE ROUTELEN = ~; ROUTELEN route len infinity = max ~; PROC route len add = (VERTEX v, ROUTE r)ROUTELEN: route len OF v + route len OF r; # or MAX(v,r) # MODE VERTEXPAYLOAD = ~; PROC dijkstra fix value error = (STRING msg)BOOL: (put(stand error, (msg, new line)); FALSE); #PROVIDES:# # VERTEX*=~* # # ROUTE*=~* # # vertex route*=~* # END COMMENT   MODE VALVERTEX = STRUCT( ROUTELEN route len, FLEX[0]ROUTE route, ROUTE shortest route, VERTEXPAYLOAD vertex data );   MODE VERTEX = REF VALVERTEX; MODE VERTEXYIELD = PROC(VERTEX)VOID; # used to "generate" VERTEX path # PRIO INIT = 1; # The same PRIOrity as +:= etc # OP INIT = (VERTEX self, VERTEXPAYLOAD vertex data)VERTEX: self := (route len infinity, (), NIL, vertex data);   # It may be faster to preallocate "queue", rather then grow a FLEX # OP +:= = (REF FLEX[]VERTEX in list, VERTEX rhs)REF FLEX[]VERTEX: ( [UPB in list+1]VERTEX out list; out list[:UPB in list] := in list; out list[UPB out list] := rhs; in list := out list # EXIT # );   MODE VALROUTE = STRUCT(VERTEX from, to, ROUTELEN route len#, ROUTEPAYLOAD#); MODE ROUTE = REF VALROUTE;   OP +:= = (REF FLEX[]ROUTE in list, ROUTE rhs)REF FLEX[]ROUTE: ( [UPB in list+1]ROUTE out list; out list[:UPB in list] := in list; out list[UPB out list] := rhs; in list := out list # EXIT # );   MODE VERTEXROUTE = UNION(VERTEX, ROUTE); MODE VERTEXROUTEYIELD = PROC(VERTEXROUTE)VOID;   ################################################################ # Finally: now the strong typing is in place, the task code... # ################################################################ PROC vertex route gen dijkstra = ( VERTEX source, target, REF[]VALROUTE route list, VERTEXROUTEYIELD yield )VOID:(   # initialise the route len for BOTH directions on each route # FOR this TO UPB route list DO ROUTE route = route list[this]; route OF from OF route +:= route; # assume route lens is the same in both directions, this i.e. NO A-B gradient NOR 1-way streets # route OF to OF route +:= (HEAP VALROUTE := (to OF route, from OF route, route len OF route)) OD;   COMMENT Algorithium Performance "about" O(n**2)... Optimisations: a) bound index in [lwb queue:UPB queue] for search b) delay adding vertices until they are actually encountered It may be faster to preallocate "queue" vertex list, rather then grow a FLEX END COMMENT   PROC vertex gen nearest = (REF FLEX[]VERTEX queue, VERTEXYIELD yield)VOID: ( INT vertices done := 0, lwb queue := 1; ROUTELEN shortest route len done := -route len infinity; WHILE vertices done <= UPB queue ANDF shortest route len done NE route len infinity DO ROUTELEN shortest route len := route len infinity; # skip done elements: # FOR this FROM lwb queue TO UPB queue DO VERTEX this vertex := queue[this]; IF NOT(shortest route len done < route len OF this vertex) THEN lwb queue := this; # remember for next time # break FI OD; break: # find vertex with shortest path attached # FOR this FROM lwb queue TO UPB queue DO VERTEX this vertex := queue[this]; IF shortest route len done < route len OF this vertex ANDF route len OF this vertex < shortest route len THEN shortest route len := route len OF this vertex FI OD; # update the other vertices with shortest path found # FOR this FROM lwb queue TO UPB queue DO VERTEX this vertex := queue[this]; IF route len OF this vertex = shortest route len THEN vertices done +:= 1; yield(this vertex) FI OD; shortest route len done := shortest route len OD );   route len OF target := 0; FLEX[0]VERTEX queue := target;   # FOR VERTEX this vertex IN # vertex gen nearest(queue#) DO (#, ## (VERTEX this vertex)VOID: ( FOR this TO UPB route OF this vertex DO ROUTE this route = (route OF this vertex)[this];   # If this vertex has not been encountered before, then add to queue # IF route len OF to OF this route = route len infinity THEN queue +:= to OF this route FI;   ROUTELEN route len = route len add(this vertex, this route); IF route len < route len OF to OF this route THEN route len OF to OF this route := route len; shortest route OF to OF this route := this route FI OD;   IF this vertex IS source THEN done FI # OD#)); IF NOT dijkstra fix value error("no path found") THEN stop FI;   ############################ # Now: generate the result # ############################ done: ( VERTEX this vertex := source; WHILE yield(this vertex); ROUTE this route = shortest route OF this vertex; # WHILE # this route ISNT ROUTE(NIL) DO yield(this route); this vertex := from OF this route OD ) );   SKIP
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#ALGOL_68
ALGOL 68
# calculates the digital root and persistance of n # PROC digital root = ( LONG LONG INT n, REF INT root, persistance )VOID: BEGIN LONG LONG INT number := ABS n; persistance := 0; WHILE persistance PLUSAB 1; LONG LONG INT digit sum := 0; WHILE number > 0 DO digit sum PLUSAB number MOD 10; number OVERAB 10 OD; number := digit sum; number > 9 DO SKIP OD; root := SHORTEN SHORTEN number END; # digital root #   # calculates and prints the digital root and persistace of number # PROC print digital root and persistance = ( LONG LONG INT number )VOID: BEGIN INT root, persistance; digital root( number, root, persistance ); print( ( whole( number, -15 ), " root: ", whole( root, 0 ), " persistance: ", whole( persistance, -3 ), newline ) ) END; # print digital root and persistance #   # test the digital root proc # BEGIN print digital root and persistance( 627615 ) ; print digital root and persistance( 39390 ) ; print digital root and persistance( 588225 ) ; print digital root and persistance( 393900588225 ) END
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Component_Pascal
Component Pascal
  MODULE MDR; IMPORT StdLog, Strings, TextMappers, DevCommanders;   PROCEDURE CalcMDR(x: LONGINT; OUT mdr, mp: LONGINT); VAR str: ARRAY 64 OF CHAR; i: INTEGER; BEGIN mdr := 1; mp := 0; LOOP Strings.IntToString(x,str); IF LEN(str$) = 1 THEN mdr := x; EXIT END; i := 0;mdr := 1; WHILE i < LEN(str$) DO mdr := mdr * (ORD(str[i]) - ORD('0')); INC(i) END; INC(mp); x := mdr END END CalcMDR;   PROCEDURE Do*; VAR mdr,mp: LONGINT; s: TextMappers.Scanner; BEGIN s.ConnectTo(DevCommanders.par.text); s.SetPos(DevCommanders.par.beg); REPEAT s.Scan; IF (s.type = TextMappers.int) OR (s.type = TextMappers.lint) THEN CalcMDR(s.int,mdr,mp); StdLog.Int(s.int); StdLog.String(" MDR: ");StdLog.Int(mdr); StdLog.String(" MP: ");StdLog.Int(mp);StdLog.Ln END UNTIL s.rider.eot; END Do;   PROCEDURE Show(i: INTEGER; x: ARRAY OF LONGINT); VAR k: INTEGER; BEGIN StdLog.Int(i);StdLog.String(": "); FOR k := 0 TO LEN(x) - 1 DO StdLog.Int(x[k]) END; StdLog.Ln END Show;   PROCEDURE FirstFive*; VAR i,j: INTEGER; five: ARRAY 5 OF LONGINT; x,mdr,mp: LONGINT; BEGIN FOR i := 0 TO 9 DO j := 0;x := 0; WHILE (j < LEN(five)) DO CalcMDR(x,mdr,mp); IF mdr = i THEN five[j] := x; INC(j) END; INC(x) END; Show(i,five) END END FirstFive;   END MDR.  
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#SVG
SVG
<?xml version="1.0" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:l="http://www.w3.org/1999/xlink" width="400" height="400"> <style type="text/css"><![CDATA[ line { stroke: black; stroke-width: .05; } circle { fill: black; } ]]></style>   <defs>   <g id="marks"> <circle cx="0" cy="0" r=".03"/> <circle cx="1" cy="0" r=".03"/> </g>   <g id="l0"> <line x1="0" y1="0" x2="1" y2="0"/> <!-- useful for studying the transformation stages: <line x1="0.1" y1="0" x2="0.9" y2="0.1"/> --> </g>   <!-- These are identical except for the id and href. --> <g id="l1"> <use l:href="#l0" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l0" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l2"> <use l:href="#l1" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l1" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l3"> <use l:href="#l2" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l2" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l4"> <use l:href="#l3" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l3" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l5"> <use l:href="#l4" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l4" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l6"> <use l:href="#l5" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l5" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l7"> <use l:href="#l6" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l6" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l8"> <use l:href="#l7" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l7" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> <g id="l9"> <use l:href="#l8" transform="matrix( .5 .5 -.5 .5 0 0)"/> <use l:href="#l8" transform="matrix(-.5 .5 -.5 -.5 1 0)"/> <use l:href="#marks"/></g> </defs>   <g transform="translate(100, 200) scale(200)"> <use l:href="#marks"/> <use l:href="#l9"/> </g>   </svg>
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#C
C
#include <stdio.h> #include <stdlib.h>   int verbose = 0; #define COND(a, b) int a(int *s) { return (b); } typedef int(*condition)(int *);   /* BEGIN problem specific setup */ #define N_FLOORS 5 #define TOP (N_FLOORS - 1) int solution[N_FLOORS] = { 0 }; int occupied[N_FLOORS] = { 0 };   enum tenants { baker = 0, cooper, fletcher, miller, smith, phantom_of_the_opera, };   const char *names[] = { "baker", "cooper", "fletcher", "miller", "smith", };   COND(c0, s[baker] != TOP); COND(c1, s[cooper] != 0); COND(c2, s[fletcher] != 0 && s[fletcher] != TOP); COND(c3, s[miller] > s[cooper]); COND(c4, abs(s[smith] - s[fletcher]) != 1); COND(c5, abs(s[cooper] - s[fletcher]) != 1); #define N_CONDITIONS 6   condition cond[] = { c0, c1, c2, c3, c4, c5 };   /* END of problem specific setup */   int solve(int person) { int i, j; if (person == phantom_of_the_opera) { /* check condition */ for (i = 0; i < N_CONDITIONS; i++) { if (cond[i](solution)) continue;   if (verbose) { for (j = 0; j < N_FLOORS; j++) printf("%d %s\n", solution[j], names[j]); printf("cond %d bad\n\n", i); } return 0; }   printf("Found arrangement:\n"); for (i = 0; i < N_FLOORS; i++) printf("%d %s\n", solution[i], names[i]); return 1; }   for (i = 0; i < N_FLOORS; i++) { if (occupied[i]) continue; solution[person] = i; occupied[i] = 1; if (solve(person + 1)) return 1; occupied[i] = 0; } return 0; }   int main() { verbose = 0; if (!solve(0)) printf("Nobody lives anywhere\n"); return 0; }
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these letters "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral). Extra Make your code able to determine multiple sentences. Don't leave any errors! 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
#XPL0
XPL0
include xpllib; \for StrLen int Sentence, N, Len; char Str; [Sentence:= ["hi there, how are you today?", "I'd like to present to you the washing machine 9001.", "You have been nominated to win one of these!", "Just make sure you don't break it"]; for N:= 0 to 3 do [Str:= Sentence(N); Len:= StrLen(Str); case Str(Len-1) of ^!: ChOut(0, ^E); ^?: ChOut(0, ^Q); ^.: ChOut(0, ^S) other ChOut(0, ^N); if N < 3 then ChOut(0, ^|); ]; ]
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#C.2B.2B
C++
#include <iostream> #include <numeric>   int main() { int a[] = { 1, 3, -5 }; int b[] = { 4, -2, -1 };   std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;   return 0; }
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Oberon-2
Oberon-2
  IMPORT Basic; TYPE Node* = POINTER TO NodeDesc; NodeDesc* = (* ABSTRACT *) RECORD prev-,next-: Node; END;   DLList* = POINTER TO DLListDesc; DLListDesc* = RECORD first-,last-: Node; size-: INTEGER; END;  
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#BASIC
BASIC
dado1 = 9: lado1 = 4 dado2 = 6: lado2 = 6 total1 = 0: total2 = 0   for i = 0 to 1 for cont = 1 to 100000 jugador1 = lanzamiento(dado1, lado1) jugador2 = lanzamiento(dado2, lado2) if jugador1 > jugador2 then total1 = total1 + 1 else if jugador1 <> jugador2 then total2 = total2 + 1 endif next cont   print "Lanzado el dado "; (cont - 1); " veces" print "jugador1 con "; dado1; " dados de "; lado1; " lados" print "jugador2 con "; dado2; " dados de "; lado2; " lados" print "Total victorias jugador1 = "; total1; " => "; left(string(total2 / total1), 9) print "Total victorias jugador2 = "; total2 print (cont - 1) - (total1 + total2); " empates" + chr(10)   dado1 = 5: lado1 = 10 dado2 = 6: lado2 = 7 total1 = 0: total2 = 0 next i end   function lanzamiento(dado, lado) total = 0   for lanza = 1 to dado total = total + int(rand * lado) + 1 next lanza return total end function
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#C
C
#include <stdio.h> #include <stdint.h>   typedef uint32_t uint; typedef uint64_t ulong;   ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; }   uint min(const uint x, const uint y) { return (x < y) ? x : y; }   void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; }   for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); }   double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1);   const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2);   const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));   double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; }   int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#AutoHotkey
AutoHotkey
#Persistent SetWorkingDir, %A_ScriptDir% FileDelete, output.txt EnoughForks := 2 ; required forks to begin eating Fork1 := Fork2 := Fork3 := Fork4 := Fork5 := 1 ; fork supply per philosopher SetTimer, AristotleWaitForLeftFork SetTimer, KantWaitForLeftFork SetTimer, SpinozaWaitForLeftFork SetTimer, MarxWaitForLeftFork SetTimer, RussellWaitForLeftFork Return ;---------------------------------------------------------------   AristotleWaitForLeftFork: WaitForFork("Aristotle", "left", Fork1, Fork2, AristotleLeftForkCount, AristotleRightForkCount, AristotleWaitCount, EnoughForks) Return AristotleWaitForRightFork: WaitForFork("Aristotle", "right", Fork2, Fork1, AristotleRightForkCount, AristotleLeftForkCount, AristotleWaitCount, EnoughForks) Return AristotleFinishEating: ReturnForks("Aristotle", Fork1, Fork2, AristotleLeftForkCount, AristotleRightForkCount, EnoughForks) Return   KantWaitForLeftFork: WaitForFork("Kant", "left", Fork2, Fork3, KantLeftForkCount, KantRightForkCount, KantWaitCount, EnoughForks) Return KantWaitForRightFork: WaitForFork("Kant", "right", Fork3, Fork2, KantRightForkCount, KantLeftForkCount, KantWaitCount, EnoughForks) Return KantFinishEating: ReturnForks("Kant", Fork2, Fork3, KantLeftForkCount, KantRightForkCount, EnoughForks) Return   SpinozaWaitForLeftFork: WaitForFork("Spinoza", "left", Fork3, Fork4, SpinozaLeftForkCount, SpinozaRightForkCount, SpinozaWaitCount, EnoughForks) Return SpinozaWaitForRightFork: WaitForFork("Spinoza", "right", Fork4, Fork3, SpinozaRightForkCount, SpinozaLeftForkCount, SpinozaWaitCount, EnoughForks) Return SpinozaFinishEating: ReturnForks("Spinoza", Fork3, Fork4, SpinozaLeftForkCount, SpinozaRightForkCount, EnoughForks) Return   MarxWaitForLeftFork: WaitForFork("Marx", "left", Fork4, Fork5, MarxLeftForkCount, MarxRightForkCount, MarxWaitCount, EnoughForks) Return MarxWaitForRightFork: WaitForFork("Marx", "right", Fork5, Fork4, MarxRightForkCount, MarxLeftForkCount, MarxWaitCount, EnoughForks) Return MarxFinishEating: ReturnForks("Marx", Fork4, Fork5, MarxLeftForkCount, MarxRightForkCount, EnoughForks) Return   RussellWaitForLeftFork: WaitForFork("Russell", "left", Fork5, Fork1, RussellLeftForkCount, RussellRightForkCount, RussellWaitCount, EnoughForks) Return RussellWaitForRightFork: WaitForFork("Russell", "right", Fork1, Fork5, RussellRightForkCount, RussellLeftForkCount, RussellWaitCount, EnoughForks) Return RussellFinishEating: ReturnForks("Russell", Fork5, Fork1, RussellLeftForkCount, RussellRightForkCount, EnoughForks) Return   ReturnForks(Philosopher, ByRef ThisFork, ByRef OtherFork, ByRef CurrentThisForkCount, ByRef CurrentOtherForkCount, EnoughForks) { OutputDebug, %Philosopher% finishes eating. FileAppend, %Philosopher% finishes eating.`n,output.txt ThisFork += CurrentThisForkCount ; return this fork OtherFork += CurrentOtherForkCount ; return other fork CurrentThisForkCount := 0 ; release this fork CurrentOtherForkCount := 0 ; release other fork OutputDebug, %Philosopher% returns all forks. FileAppend, %Philosopher% returns all forks.`n,output.txt   ; do something while resting   Random, Rand, 0, 1 Rand := Rand ? "Left" : "Right" SetTimer, %Philosopher%WaitFor%Rand%Fork }   WaitForFork(Philosopher, This, ByRef ThisFork, ByRef OtherFork, ByRef CurrentThisForkCount, ByRef CurrentOtherForkCount, ByRef CurrentWaitCount, EnoughForks) { If This not in Left,Right Return Error Other := (This="right") ? "left" : "right" OutputDebug, %Philosopher% is hungry. FileAppend, %Philosopher% is hungry.`n,output.txt If (ThisFork) ; if this fork available { SetTimer, %Philosopher%WaitFor%This%Fork, Off CurrentWaitCount := 0 ThisFork-- ; take this fork CurrentThisForkCount++ ; receive this fork OutputDebug, %Philosopher% grabs %This% fork. FileAppend, %Philosopher% grabs %This% fork.`n,output.txt If (CurrentThisForkCount + CurrentOtherForkCount = EnoughForks) ; if philosopher has enough forks { OutputDebug, %Philosopher% starts eating. FileAppend, %Philosopher% starts eating.`n,output.txt   ; do something while eating   SetTimer, %Philosopher%FinishEating, -250 } Else If (EnoughForks=2) { SetTimer, %Philosopher%WaitFor%Other%Fork } Else { Random, Rand, 0, 1 Rand := Rand ? "Left" : "Right" SetTimer, %Philosopher%WaitFor%Rand%Fork } } Else If (CurrentOtherForkCount and CurrentWaitCount > 5) ; if we've been holding other fork too long { SetTimer, %Philosopher%WaitFor%This%Fork, Off CurrentWaitCount := 0 OtherFork++ ; return other fork CurrentOtherForkCount-- ; release other fork OutputDebug, %Philosopher% drops %Other% fork. FileAppend, %Philosopher% drops %Other% fork.`n,output.txt Random, Rand, 0, 1 Rand := Rand ? "Left" : "Right" SetTimer, %Philosopher%WaitFor%Rand%Fork } Else If (CurrentThisForkCount and CurrentWaitCount > 5) ; if we've been holding one of this fork too long { SetTimer, %Philosopher%WaitFor%This%Fork, Off CurrentWaitCount := 0 ThisFork++ ; return other fork CurrentThisForkCount-- ; release other fork OutputDebug, %Philosopher% drops %This% fork. FileAppend, %Philosopher% drops %This% fork.`n,output.txt Random, Rand, 0, 1 Rand := Rand ? "Left" : "Right" SetTimer, %Philosopher%WaitFor%Rand%Fork } Else { CurrentWaitCount++ } }
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_W
ALGOL W
BEGIN % DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD  % INTEGER GREG, GMONTH, GDAY, GYEAR; STRING(16) ARRAY HOLY5 ( 0 :: 4 ); STRING(16) ARRAY HOLY50 ( 0 :: 4 ); STRING(16) ARRAY DISDAY ( 0 :: 4 ); STRING(16) ARRAY DISSSN ( 0 :: 4 ); INTEGER ARRAY MLENGT ( 0 :: 12 ); INTEGER APOS; STRING(1) SLASH1, SLASH2;    % WRITES A "$" TERMINATED STRING  % PROCEDURE WRITEONTEXT( STRING(16) VALUE TEXT ) ; BEGIN INTEGER TPOS; TPOS := 0; WHILE TPOS < 16 DO BEGIN IF TEXT( TPOS // 1 ) = "$" THEN TPOS := 32 ELSE WRITEON( TEXT( TPOS // 1 ) );  ; TPOS := TPOS + 1 END WHILE_TPOS_LT_16 END WRITEONTEXT;   APOS := 0; FOR M := 0,0,31,59,90,120,151,181,212,243,273,304,334 DO BEGIN MLENGT(APOS) := M; APOS := APOS + 1 END; HOLY5 (0) := "MUNG$";HOLY5 (1) := "MOJO$"; HOLY5 (2) := "SYA$"; HOLY5 (3) := "ZARA$"; HOLY5 (4) := "MALA$"; HOLY50(0) := "CHAO$";HOLY50(1) := "DISCO$";HOLY50(2) := "CONFU$";HOLY50(3) := "BURE$"; HOLY50(4) := "AF$"; DISDAY(0) := "SWEETMORN$"; DISDAY(1) := "BOOMTIME$"; DISDAY(2) := "PUNGENDAY$"; DISDAY(3) := "PRICKLE-PRICKLE$"; DISDAY(4) := "SETTING ORANGE$"; DISSSN(0) := "CHAOS$"; DISSSN(1) := "DISCORD$"; DISSSN(2) := "CONFUSION$"; DISSSN(3) := "BUREAUCRACY$"; DISSSN(4) := "THE AFTERMATH$";    % INPUT DATE SHOULD CONTAIN MM/DD/YYYY IN GREGORIAN CALENDAR  % READ( GMONTH, SLASH1, GDAY, SLASH2, GYEAR );   IF GMONTH = 2 AND GDAY = 29 THEN WRITE( I_W := 4, S_W := 0, "SAINT TIB'S DAY IN THE Y.O.L.D. ", GYEAR + 1166 ) ELSE BEGIN INTEGER YRDAY, SEASON, DAY, WKDAY; YRDAY  := MLENGT(GMONTH)+GDAY; SEASON := YRDAY DIV 73; DAY  := YRDAY-SEASON*73; WKDAY  := (YRDAY-1) REM 5; WRITEONTEXT( DISDAY(WKDAY) ); WRITEON( S_W := 0, ", DAY ", I_W := 2, DAY, " OF " ); WRITEONTEXT( DISSSN(SEASON) ); WRITEON( S_W := 0, " IN THE Y.O.L.D ", I_W := 4, GYEAR + 1166 ); IF DAY = 5 THEN BEGIN WRITE( "CELEBRATE " );WRITEONTEXT( HOLY5(SEASON) ); WRITEON( "DAY" ) END ELSE IF DAY = 50 THEN BEGIN WRITE( "CELEBRATE " );WRITEONTEXT( HOLY50(SEASON) ); WRITEON( "FLUX" ) END IF_FAY_EQ_5__DAY_EQ_50 END END.
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#Applesoft_BASIC
Applesoft BASIC
100 O$ = "A" : T$ = "EF" 110 DEF FN N(P) = ASC(MID$(N$,P+(P=0),1))-64 120 DIM D(26),UNVISITED(26) 130 DIM PREVIOUS(26) : TRUE = 1 140 LET M = -1 : INFINITY = M 150 FOR I = 0 TO 26 160 LET D(I) = INFINITY : NEXT 170 FOR NE = M TO 1E38 STEP .5 180 READ C$ 190 IF LEN(C$) THEN NEXT 200 DIM C(NE),FROM(NE),T(NE) 210 DIM PC(NE) : RESTORE 220 FOR I = 0 TO NE 230 READ C(I), N$ 240 LET FROM(I) = FN N(1) 250 LET UNVISITED(FR(I)) = TRUE 260 LET T(I) = FN N(3) 270 LET UNVISITED(T(I)) = TRUE 290 NEXT 300 N$ = O$ : O = FN N(0) 310 D(O) = 0 320 FOR CV = O TO EMPTY STEP 0 330 FOR I = 0 TO NE 340 IF FROM(I) = CV THEN N = T(I) : D = D(CV) + C(I) : IF (D(N) = INFINITY) OR (D < D(N)) THEN D(N) = D : PREVIOUS(N) = CV : PC(N) = C(I) 350 NEXT I 360 LET UNVISITED(CV) = FALSE 370 LET MV = EMPTY 380 FOR I = 1 TO 26 390 IF UNVISITED(I) THEN MD = D(MV) * (MV <> INFINITY) + INFINITY * (MV = INFINITY) : IF (D(I) <> INFINITY) AND ((MD = INFINITY) OR (D(I) < MD)) THEN MV = I 400 NEXT I 410 LET CV = MV * (MD <> INF) 420 NEXT CV : M$ = CHR$(13) 430 PRINT "SHORTEST PATH"; 440 FOR I = 1 TO LEN(T$) 450 LET N$ = MID$(T$, I, 1) 460 PRINT M$ " FROM " O$; 470 PRINT " TO "; : N = FN N(0) 480 IF D(N) = INFINITY THEN PRINT N$" DOES NOT EXIST."; 490 IF D(N) <> INFINITY THEN FOR N = N TO FALSE STEP 0 : PRINT CHR$(N + 64); : IF N < > O THEN PRINT " <- "; : N = PREVIOUS(N): NEXT N 500 IF D(N) <> INFINITY THEN PRINT : PRINT " IS "; : N = FN N(0) : PRINT D(N); : H = 15 : FOR N = N TO O STEP 0: IF N < > O THEN P = PREVIOUS(N): PRINT TAB(H)CHR$(43+18*(h=15));TAB(H+2)PC(N); :N = P: H=H+5: NEXT N 510 NEXT I 600 DATA 7,A-B 610 DATA 9,A-C 620 DATA 14,A-F 630 DATA 10,B-C 640 DATA 15,B-D 650 DATA 11,C-D 660 DATA 2,C-F 670 DATA 6,D-E 680 DATA 9,E-F 690 DATA
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#ALGOL_W
ALGOL W
begin    % calculates the digital root and persistence of an integer in base 10  %  % in order to allow for numbers larger than 2^31, the number is passed  %  % as the lower and upper digits e.g. 393900588225 can be processed by  %  % specifying upper = 393900, lower = 58825  % procedure findDigitalRoot( integer value upper, lower  ; integer result digitalRoot, persistence ) ; begin   integer procedure sumDigits( integer value n ) ; begin integer digits, sum;   digits := abs n; sum  := 0;   while digits > 0 do begin sum  := sum + ( digits rem 10 ); digits := digits div 10 end % while digits > 0 % ;    % result: % sum end sumDigits;   digitalRoot := sumDigits( upper ) + sumDigits( lower ); persistence := 1;   while digitalRoot > 9 do begin persistence := persistence + 1; digitalRoot := sumDigits( digitalRoot ); end % while digitalRoot > 9 % ;   end findDigitalRoot ;    % calculates and prints the digital root and persistence  % procedure printDigitalRootAndPersistence( integer value upper, lower ) ; begin integer digitalRoot, persistence; findDigitalRoot( upper, lower, digitalRoot, persistence ); write( s_w := 0  % set field saeparator width for this statement % , i_w := 8  % set integer field width for this statement  % , upper , ", " , lower , i_w := 2  % change integer field width % , ": digital root: " , digitalRoot , ", persistence: " , persistence ) end printDigitalRootAndPersistence ;    % test the digital root and persistence procedures % printDigitalRootAndPersistence( 0, 627615 ); printDigitalRootAndPersistence( 0, 39390 ); printDigitalRootAndPersistence( 0, 588225 ); printDigitalRootAndPersistence( 393900, 588225 )   end.
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#AppleScript
AppleScript
on digitalroot(N as integer) script math to sum(L) if L = {} then return 0 (item 1 of L) + sum(rest of L) end sum end script   set i to 0 set M to N   repeat until M < 10 set digits to the characters of (M as text) set M to math's sum(digits) set i to i + 1 end repeat   {N:N, persistences:i, root:M} end digitalroot     digitalroot(627615)
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#D
D
import std.stdio, std.algorithm, std.typecons, std.range, std.conv;   /// Multiplicative digital root. auto mdRoot(in int n) pure /*nothrow*/ { auto mdr = [n]; while (mdr.back > 9) mdr ~= reduce!q{a * b}(1, mdr.back.text.map!(d => d - '0')); //mdr ~= mdr.back.text.map!(d => d - '0').mul; //mdr ~= mdr.back.reverseDigits.mul; return tuple(mdr.length - 1, mdr.back); }   void main() { "Number: (MP, MDR)\n====== =========".writeln; foreach (immutable n; [123321, 7739, 893, 899998]) writefln("%6d: (%s, %s)", n, n.mdRoot[]);   auto table = (int[]).init.repeat.enumerate!int.take(10).assocArray; auto n = 0; while (table.byValue.map!walkLength.reduce!min < 5) { table[n.mdRoot[1]] ~= n; n++; } "\nMP: [n0..n4]\n== ========".writeln; foreach (const mp; table.byKey.array.sort()) writefln("%2d: %s", mp, table[mp].take(5)); }
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Tcl
Tcl
package require Tk   set pi [expr acos(-1)] set r2 [expr sqrt(2)]   proc turn {degrees} { global a pi set a [expr {$a + $degrees*$pi/180}] } proc forward {len} { global a coords lassign [lrange $coords end-1 end] x y lappend coords [expr {$x + cos($a)*$len}] [expr {$y + sin($a)*$len}] } proc dragon {len split {d 1}} { global r2 coords if {$split == 0} { forward $len return }   # This next part is only necessary to allow the illustration of progress if {$split == 10 && [llength $::coords]>2} { .c coords dragon $::coords update }   incr split -1 set sublen [expr {$len/$r2}] turn [expr {$d*45}] dragon $sublen $split 1 turn [expr {$d*-90}] dragon $sublen $split -1 turn [expr {$d*45}] }   set coords {150 180} set a 0.0 pack [canvas .c -width 700 -height 500] .c create line {0 0 0 0} -tag dragon dragon 400 17 .c coords dragon $coords
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. The problem Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.   Baker does not live on the top floor.   Cooper does not live on the bottom floor.   Fletcher does not live on either the top or the bottom floor.   Miller lives on a higher floor than does Cooper.   Smith does not live on a floor adjacent to Fletcher's.   Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?
#C.2B.2B
C++
#include <algorithm> #include <array> #include <cmath> #include <functional> #include <string> #include <iostream> #include <list>   int main() { constexpr auto floors = 5u; constexpr auto top = floors - 1u, bottom = 0u;   using namespace std; array<string, floors> tenants = { "Baker", "Cooper", "Fletcher", "Miller", "Smith" }; const auto floor_of = [&tenants](string t) { for (int i = bottom; i <= top; i++) if (tenants[i] == t) return i; throw "invalid tenant"; };   const list<function<bool()>> constraints = { [&tenants]() { return tenants[top] != "Baker"; }, [&tenants]() { return tenants[bottom] != "Cooper"; }, [&tenants]() { return tenants[top] != "Fletcher"; }, [&tenants]() { return tenants[bottom] != "Fletcher"; }, [&floor_of]() { return floor_of("Miller") > floor_of("Cooper"); }, [&floor_of]() { return abs(floor_of("Fletcher") - floor_of("Smith")) != 1; }, [&floor_of]() { return abs(floor_of("Fletcher") - floor_of("Cooper")) != 1; } };   sort(tenants.begin(), tenants.end()); do { if (all_of(constraints.begin(), constraints.end(), [](auto f) { return f(); } )) { for (const auto &t : tenants) cout << t << ' '; cout << endl; } } while (next_permutation(tenants.begin(), tenants.end()));   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#Clojure
Clojure
(defn dot-product [& matrix] {:pre [(apply == (map count matrix))]} (apply + (apply map * matrix)))   (defn dot-product2 [x y] (->> (interleave x y) (partition 2 2) (map #(apply * %)) (reduce +)))   (defn dot-product3 "Dot product of vectors. Tested on version 1.8.0." [v1 v2] {:pre [(= (count v1) (count v2))]} (reduce + (map * v1 v2)))   ;Example Usage (println (dot-product [1 3 -5] [4 -2 -1])) (println (dot-product2 [1 3 -5] [4 -2 -1])) (println (dot-product3 [1 3 -5] [4 -2 -1]))  
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Objeck
Objeck
  use Collection;   class Program { function : Main(args : String[]) ~ Nil { list := List->New(); list->AddFront("first"); list->AddBack("last"); list->Insert("middle");   list->Forward(); do { list->Get()->As(String)->PrintLine(); list->Previous(); } while(list->Get() <> Nil); } }
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#C.2B.2B
C++
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map>   // Returns map from sum of faces to number of ways it can happen std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; }   double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; }   int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right. There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"TIMERLIB"   nSeats% = 5 DIM Name$(nSeats%-1), Fork%(nSeats%-1), tID%(nSeats%-1), Leftie%(nSeats%-1)   Name$() = "Aristotle", "Kant", "Spinoza", "Marx", "Russell" Fork%() = TRUE : REM All forks are initially on the table Leftie%(RND(nSeats%)-1) = TRUE : REM One philosopher is lefthanded   tID%(0) = FN_ontimer(10, PROCphilosopher0, 1) tID%(1) = FN_ontimer(10, PROCphilosopher1, 1) tID%(2) = FN_ontimer(10, PROCphilosopher2, 1) tID%(3) = FN_ontimer(10, PROCphilosopher3, 1) tID%(4) = FN_ontimer(10, PROCphilosopher4, 1)   ON CLOSE PROCcleanup : QUIT ON ERROR PRINT REPORT$ : PROCcleanup : END   DEF PROCphilosopher0 : PROCtask(0) : ENDPROC DEF PROCphilosopher1 : PROCtask(1) : ENDPROC DEF PROCphilosopher2 : PROCtask(2) : ENDPROC DEF PROCphilosopher3 : PROCtask(3) : ENDPROC DEF PROCphilosopher4 : PROCtask(4) : ENDPROC   REPEAT WAIT 0 UNTIL FALSE END   DEF PROCtask(n%) PRIVATE state%(), lh%(), rh%() DIM state%(nSeats%-1), lh%(nSeats%-1), rh%(nSeats%-1) REM States: 0 = waiting for forks, > 0 = eating, < 0 = left the room CASE TRUE OF WHEN state%(n%) < 0: state%(n%) += 1 : REM Waiting to get hungry again IF state%(n%) = 0 PRINT Name$(n%) " is hungry again" WHEN state%(n%) > 0: state%(n%) -= 1 : REM Eating IF state%(n%) = 0 THEN SWAP Fork%((n%-1+nSeats%) MOD nSeats%), lh%(n%) SWAP Fork%((n% + 1) MOD nSeats%), rh%(n%) state%(n%) = -RND(100) PRINT Name$(n%) " is leaving the room" ENDIF WHEN state%(n%) = 0: IF Leftie%(n%) THEN IF NOT lh%(n%) SWAP Fork%((n%-1+nSeats%) MOD nSeats%), lh%(n%) IF lh%(n%) IF NOT rh%(n%) SWAP Fork%((n% + 1) MOD nSeats%), rh%(n%) ELSE IF NOT rh%(n%) SWAP Fork%((n% + 1) MOD nSeats%), rh%(n%) IF rh%(n%) IF NOT lh%(n%) SWAP Fork%((n%-1+nSeats%) MOD nSeats%), lh%(n%) ENDIF IF lh%(n%) AND rh%(n%) THEN state%(n%) = RND(100) PRINT Name$(n%) " is eating (" ; state%(n%) " ticks)" ENDIF ENDCASE ENDPROC   DEF PROCcleanup LOCAL I% FOR I% = 0 TO nSeats%-1 PROC_killtimer(tID%(I%)) NEXT ENDPROC
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#AppleScript
AppleScript
on gregorianToDiscordian(inputDate) -- Input: AppleScript date object. (* Discordian years are aligned with, and the same length as, Gregorian years. Each has 73 5-day weeks and 5 73-day seasons. (73 * 5 = 365.) The first day of a Discordian year is also that of its first week and first season. In leap years, an extra day called "St. Tib's Day", is inserted between days 59 and 60. It's considered to be outside the calendar, so the day after it is Setting Orange, Chaos 60, not Sweetmorn, Chaos 61. Year 1 YOLD is 1166 BC, but this handler takes an AS date object as its input and is only good for AD Gregorian dates. Since the Discordian calendar's an American invention, the output here's in the US style: "Weekday, Season day, year". *) -- Calculate the input date's day-of-year number. copy inputDate to startOfYear tell startOfYear to set {its day, its month} to {1, January} set dayOfYear to (inputDate - startOfYear) div days + 1   -- If it's a leap year, special-case St. Tib's Day, or adjust the day-of-year number if the day comes after that. set y to inputDate's year if ((y mod 4 is 0) and ((y mod 100 > 0) or (y mod 400 is 0))) then if (dayOfYear is 60) then set dayOfYear to "St. Tib's Day" else if (dayOfYear > 60) then set dayOfYear to dayOfYear - 1 end if end if   -- Start the output text with either "St. Tib's Day" or the weekday, season, and day-of-season number. if (dayOfYear is "St. Tib's Day") then set outputText to dayOfYear else tell dayOfYear - 1 set dayOfWeek to it mod 5 + 1 set seasonNumber to it div 73 + 1 set dayOfSeason to it mod 73 + 1 end tell set theWeekdays to {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"} set theSeasons to {"Chaos ", "Discord ", "Confusion ", "Bureaucracy ", "The Aftermath "} set outputText to (item dayOfWeek of theWeekdays) & ", " & (item seasonNumber of theSeasons) & dayOfSeason end if   -- Append the Discordian year number and return the result. return outputText & ", " & (y + 1166) end gregorianToDiscordian   set ASDate to (current date) set gregorianDate to ASDate's date string set discordianDate to gregorianToDiscordian(ASDate) return {Gregorian:gregorianDate, Discordian:discordianDate}
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. For instance If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road,   Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably:   IS-IS   (Intermediate System to Intermediate System)   and   OSPF   (Open Shortest Path First). Important note The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:   an adjacency matrix or list,   and   a start node. A destination node is not specified. The output is a set of edges depicting the shortest path to each destination node. An example, starting with a──►b, cost=7, lastNode=a a──►c, cost=9, lastNode=a a──►d, cost=NA, lastNode=a a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►b so a──►b is added to the output.   There is a connection from b──►d so the input is updated to: a──►c, cost=9, lastNode=a a──►d, cost=22, lastNode=b a──►e, cost=NA, lastNode=a a──►f, cost=14, lastNode=a   The lowest cost is a──►c so a──►c is added to the output.   Paths to d and f are cheaper via c so the input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a a──►f, cost=11, lastNode=c   The lowest cost is a──►f so c──►f is added to the output.   The input is updated to: a──►d, cost=20, lastNode=c a──►e, cost=NA, lastNode=a   The lowest cost is a──►d so c──►d is added to the output.   There is a connection from d──►e so the input is updated to: a──►e, cost=26, lastNode=d   Which just leaves adding d──►e to the output.   The output should now be: [ d──►e c──►d c──►f a──►c a──►b ] Task Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin. Run your program with the following directed graph starting at node   a. Write a program which interprets the output from the above and use it to output the shortest path from node   a   to nodes   e   and f. Vertices Number Name 1 a 2 b 3 c 4 d 5 e 6 f Edges Start End Cost a b 7 a c 9 a f 14 b c 10 b d 15 c d 11 c f 2 d e 6 e f 9 You can use numbers or names to identify vertices in your program. See also Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
#Arturo
Arturo
define :graph [vertices, neighbours][]   initGraph: function [edges][ vs: [] ns: #[] loop edges 'e [ [src, dst, cost]: e vs: sort unique append vs src vs: sort unique append vs dst if not? key? ns src -> ns\[src]: []   ns\[src]: ns\[src] ++ @[@[dst, cost]] ] to :graph @[vs ns] ]   Inf: 1234567890   dijkstraPath: function [gr, fst, lst][ dist: #[] prev: #[] result: new [] notSeen: new gr\vertices loop gr\vertices 'vertex -> dist\[vertex]: Inf   dist\[fst]: 0   while [0 < size notSeen][ vertex1: "" mindist: Inf loop notSeen 'vertex [ if dist\[vertex] < mindist [ vertex1: vertex mindist: dist\[vertex] ] ] if vertex1 = lst -> break 'notSeen -- vertex1   if key? gr\neighbours vertex1 [ loop gr\neighbours\[vertex1] 'v [ [vertex2, cost]: v   if contains? notSeen vertex2 [ altdist: dist\[vertex1] + cost if altdist < dist\[vertex2][ dist\[vertex2]: altdist prev\[vertex2]: vertex1 ] ] ] ] ]   vertex: lst while [not? empty? vertex][ 'result ++ vertex vertex: (key? prev vertex)? -> prev\[vertex] -> null ] reverse 'result return result ]   graph: initGraph [ ["a" "b" 7] ["a" "c" 9] ["a" "f" 14] ["b" "c" 10] ["b" "d" 15] ["c" "d" 11] ["c" "f" 2] ["d" "e" 6] ["e" "f" 9] ]   print ["Shortest path from 'a' to 'e': " join.with:" -> " dijkstraPath graph "a" "e"] print ["Shortest path from 'a' to 'f': " join.with:" -> " dijkstraPath graph "a" "f"]
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Applesoft_BASIC
Applesoft BASIC
1 GOSUB 430"BASE SETUP 2 FOR E = 0 TO 1 STEP 0 3 GOSUB 7"READ 4 ON E + 1 GOSUB 50, 10 5 NEXT E 6 END   7 READ N$ 8 E = N$ = "" 9 RETURN   10 GOSUB 7"READ BASE 20 IF E THEN RETURN 30 BASE = VAL(N$) 40 READ N$   50 GOSUB 100"DIGITAL ROOT 60 GOSUB 420: PRINT " HAS AD"; 70 PRINT "DITIVE PERSISTENCE"; 80 PRINT " "P" AND DIGITAL R"; 90 PRINT "OOT "X$";" : RETURN   REM DIGITAL ROOT OF N$, RETURNS X$ AND P   100 P = 0 : L = LEN(N$) 110 X$ = MID$(N$, 2, L - 1) 120 N = LEFT$(X$, 1) = "-" 130 IF NOT N THEN X$ = N$ 140 FOR P = 0 TO 1E38 150 L = LEN(X$) 160 IF L < 2 THEN RETURN 170 GOSUB 200"DIGIT SUM 180 X$ = S$ 190 NEXT P : STOP   REM DIGIT SUM OF X$, RETURNS S$   200 S$ = "0" 210 R$ = X$ 220 L = LEN(R$) 230 FOR L = L TO 1 STEP -1 240 E$ = "" : V$ = RIGHT$(R$, 1) 250 GOSUB 400 : S = LEN(S$) 260 ON R$ <> "0" GOSUB 300 270 R$ = MID$(R$, 1, L - 1) 280 NEXT L 290 RETURN   REM ADD V TO S$   300 FOR C = V TO 0 STEP 0 310 V$ = RIGHT$(S$, 1) 320 GOSUB 400 : S = S - 1 330 S$ = MID$(S$, 1, S) 340 V = V + C : C = V >= BASE 350 IF C THEN V = V - BASE 360 GOSUB 410 : E$ = V$ + E$ 370 IF S THEN NEXT C 380 IF C THEN S$ = "1" 390 S$ = S$ + E$ : RETURN   REM BASE VAL 400 V = V(ASC(V$)) : RETURN   REM BASE STR$ 410 V$ = V$(V) : RETURN   REM BASE DISPLAY 420 PRINT N$; 421 IF BASE = 10 THEN RETURN 422 PRINT "("BASE")"; 423 RETURN   REM BASE SETUP 430 IF BASE = 0 THEN BASE = 10 440 DIM V(127), V$(35) 450 FOR I = 0 TO 35 460 V = 55 + I - (I < 10) * 7 470 V$(I) = CHR$(V) 480 V(V) = I 490 NEXT I : RETURN   500 DATA627615,39390,588225 510 DATA393900588225 1000 DATA,30 1010 DATADIGITALROOT 63999DATA,
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displaystyle X} has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: 627615 {\displaystyle 627615} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; 39390 {\displaystyle 39390} has additive persistence 2 {\displaystyle 2} and digital root of 6 {\displaystyle 6} ; 588225 {\displaystyle 588225} has additive persistence 2 {\displaystyle 2} and digital root of 3 {\displaystyle 3} ; 393900588225 {\displaystyle 393900588225} has additive persistence 2 {\displaystyle 2} and digital root of 9 {\displaystyle 9} ; The digital root may be calculated in bases other than 10. See Casting out nines for this wiki's use of this procedure. Digital root/Multiplicative digital root Sum digits of an integer Digital root sequence on OEIS Additive persistence sequence on OEIS Iterated digits squaring
#Arturo
Arturo
droot: function [num][ persistence: 0 until [ num: sum to [:integer] split to :string num persistence: persistence + 1 ][ num < 10 ] return @[num, persistence] ]   loop [627615, 39390, 588225, 393900588225] 'i [ a: droot i print [i "has additive persistence" a\0 "and digital root of" a\1] ]
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 {\displaystyle 0} . While m {\displaystyle m} has more than one digit: Find a replacement m {\displaystyle m} as the multiplication of the digits of the current value of m {\displaystyle m} . Increment i {\displaystyle i} . Return i {\displaystyle i} (= MP) and m {\displaystyle m} (= MDR) Task Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998 Tabulate MDR versus the first five numbers having that MDR, something like: MDR: [n0..n4] === ======== 0: [0, 10, 20, 25, 30] 1: [1, 11, 111, 1111, 11111] 2: [2, 12, 21, 26, 34] 3: [3, 13, 31, 113, 131] 4: [4, 14, 22, 27, 39] 5: [5, 15, 35, 51, 53] 6: [6, 16, 23, 28, 32] 7: [7, 17, 71, 117, 171] 8: [8, 18, 24, 29, 36] 9: [9, 19, 33, 91, 119] Show all output on this page. Similar The Product of decimal digits of n page was redirected here, and had the following description Find the product of the decimal digits of a positive integer   n,   where n <= 100 The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them. References Multiplicative Digital Root on Wolfram Mathworld. Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences. What's special about 277777788888899? - Numberphile video
#Elixir
Elixir
defmodule Digital do def mdroot(n), do: mdroot(n, 0)   defp mdroot(n, persist) when n < 10, do: {n, persist} defp mdroot(n, persist), do: mdroot(product(n, 1), persist+1)   defp product(0, prod), do: prod defp product(n, prod), do: product(div(n, 10), prod*rem(n, 10))   def task1(data) do IO.puts "Number: MDR MP\n====== === ==" Enum.each(data, fn n -> {mdr, persist} = mdroot(n)  :io.format "~6w: ~w ~2w~n", [n, mdr, persist] end) end   def task2(m \\ 5) do IO.puts "\nMDR: [n0..n#{m-1}]\n=== ========" map = add_map(0, m, Map.new) Enum.each(0..9, fn i -> first = map[i] |> Enum.reverse |> Enum.take(m) IO.puts " #{i}: #{inspect first}" end) end   defp add_map(n, m, map) do {mdr, _persist} = mdroot(n) new_map = Map.update(map, mdr, [n], fn vals -> [n | vals] end) min_len = Map.values(new_map) |> Enum.map(&length(&1)) |> Enum.min if min_len < m, do: add_map(n+1, m, new_map), else: new_map end end   Digital.task1([123321, 7739, 893, 899998]) Digital.task2
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. *---R----* expands to * * \ / R L \ / * * / \ L R / \ *---L---* expands to * * The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. The curl direction right or left can be a parameter instead of two separate routines. Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. *------->* becomes * * Recursive copies drawn \ / from the ends towards \ / the centre. v v * This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen. Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, * *-----* becomes / \ bend to left / \ if N odd * * * * *-----* becomes \ / bend to right \ / if N even * Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this. Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. n = 1010110000 ^ bit above lowest 1-bit, turn left or right as 0 or 1 LowMask = n BITXOR (n-1) # eg. giving 0000011111 AboveMask = LowMask + 1 # eg. giving 0000100000 BitAboveLowestOne = n BITAND AboveMask The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction. If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. Absolute direction to move at point n can be calculated by the number of bit-transitions in n. n = 11 00 1111 0 1 ^ ^ ^ ^ 4 places where change bit value so direction=4*90degrees=East This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently. Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this. A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code. Axiom F, angle 90 degrees F -> F+S S -> F-S This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page. Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around. The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
#Plain_TeX
Plain TeX
\input tikz.tex \usetikzlibrary{lindenmayersystems}   \pgfdeclarelindenmayersystem{Dragon curve}{ \symbol{S}{\pgflsystemdrawforward} \rule{F -> F+S} \rule{S -> F-S} } \tikzpicture \draw [lindenmayer system={Dragon curve, step=10pt, axiom=F, order=8}] lindenmayer system; \endtikzpicture \bye