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/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. Example If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens   after   an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called Lychrel numbers. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. Seed and related Lychrel numbers Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. Task   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).   Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.   Print any seed Lychrel or related number that is itself a palindrome. Show all output here. References   What's special about 196? Numberphile video.   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).   Status of the 196 conjecture? Mathoverflow.
#zkl
zkl
var BN=Import("zklBigNum");   // 192-->"887\01675\07436\013783\0..." ~60k bytes fcn lychrel(n,returnListof=False){ n=BN(n); //-->Bool|Data(==StringBuf) sink:=(if(returnListof) Data(0,String) else Void); nls:=(500).pump(sink,'wrap(){ ns:=n.add(BN(n.toString().reverse())).toString(); if(ns==ns.reverse()) return(Void.Stop,False); // not a Lychrel number ns }); if(nls) if(returnListof) return(sink.mode(Int).howza(2)) else return(True); False; } fcn isPalindrome(n){ n==n.toString().reverse().toInt() } fcn findSeeds(lychrels){ seeds:=List(lychrels[0]); foreach n,lnns in ([1..].zip(lychrels[1,*])){ ln,seq:=lnns; foreach _,s2 in (seeds){ foreach s3 in (seq){ if(Void!=(z:=s2.findString(s3)) and 0==s2[z-1]) break(2); } } fallthrough{ seeds.append(lnns) } } seeds.apply("get",0) }
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp;
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Ksh
Ksh
  #!/bin/ksh   # Increment loop index within loop body   # # Variables: # integer INDX_START=42 N_PRIMES=42   # # Functions: #   # # Function _isprime(n) return 1 for prime, 0 for not prime # function _isprime { typeset _n ; integer _n=$1 typeset _i ; integer _i   (( _n < 2 )) && return 0 for (( _i=2 ; _i*_i<=_n ; _i++ )); do (( ! ( _n % _i ) )) && return 0 done return 1 }   ###### # main # ###### integer i n=0 for ((i=INDX_START; n<N_PRIMES; i++)); do _isprime ${i} if (( $? )); then printf "%,18d is prime, %2d primes found(so far)\n" ${i} $((++n)) (( i+=$i )) fi done
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Lua
Lua
-- Returns boolean indicate whether x is prime function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end   -- Main procedure local n, i = 0, 42 while n < 42 do if isPrime(i) then n = n + 1 print("n = " .. n, i) i = 2 * i - 1 end i = i + 1 end
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#C.23
C#
while (true) { Console.WriteLine("SPAM"); }
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#C.2B.2B
C++
while (true) std::cout << "SPAM\n";
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#QB64
QB64
  'Task 'Simulate/translate the above PL/I program snippet as best as possible ' in your language, with particular emphasis on the do loop ' construct. 'The do index must be incremented/decremented in the same order shown. 'If feasible, add commas to the two output numbers (being displayed). 'Show all output here.   'Unknown DO multiple conditions behaviour: ' this code implements a sequential/serial set of ranges mode for DO condition   Dim As Integer prod, sum, x, y, z, one, three, seven Dim As _Integer64 Count(1 To 7) Dim As Integer Index, IndexCondition   prod = 1 sum = 0 x = 5 y = -5 z = -2 one = 1 three = 3 seven = 7 Count(1) = -three Count(2) = -seven Count(3) = 555 Count(4) = 22 Count(5) = 1927 Count(6) = x Count(7) = 11 ^ x IndexCondition = 1 Do If IndexCondition = 1 Then If Count(1) + three < 3 ^ 3 Then Count(1) = Count(1) + three Else IndexCondition = 2 ElseIf IndexCondition = 2 Then If Count(2) + x < seven Then Count(2) = Count(2) + x Else IndexCondition = 3 ElseIf IndexCondition = 3 Then If Count(3) - 1 > 550 - y Then Count(3) = Count(3) - 1 Else IndexCondition = 4 ElseIf IndexCondition = 4 Then If Count(4) - three > -28 Then Count(4) = Count(4) - three Else IndexCondition = 5 ElseIf IndexCondition = 5 Then If Count(5) + 1 < 1939 Then Count(5) = Count(5) + 1 Else IndexCondition = 6 ElseIf IndexCondition = 6 Then If Count(6) + z < y Then Count(6) = Count(6) + z Else IndexCondition = 7 ElseIf IndexCondition = 7 Then If Count(7) + 1 < 11 ^ (x + one) Then Count(7) = Count(7) + 1 Else Exit Do End If   sum = sum + Abs(Count(IndexCondition)) If Abs(prod) < 2 ^ 27 And (j <> 0) Then prod = prod * Count(IndexCondition) Print sum Print prod   Loop  
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Raku
Raku
sub comma { ($^i < 0 ?? '-' !! '') ~ $i.abs.flip.comb(3).join(',').flip }   my \x = 5; my \y = -5; my \z = -2; my \one = 1; my \three = 3; my \seven = 7;   my $j = flat ( -three, *+three … 3³ ), ( -seven, *+x …^ * > seven ), ( 555 .. 550 - y ), ( 22, *-three …^ * < -28 ), ( 1927 .. 1939 ), ( x, *+z …^ * < y ), ( 11**x .. 11**x + one );   put 'j sequence: ', $j; put ' Sum: ', comma [+] $j».abs; put ' Product: ', comma ([\*] $j.grep: so +*).first: *.abs > 2²⁷;   # Or, an alternate method for generating the 'j' sequence, employing user-defined # operators to preserve the 'X to Y by Z' layout of the example code. # Note that these operators will only work for monotonic sequences.   sub infix:<to> { $^a ... $^b } sub infix:<by> { $^a[0, $^b.abs ... *] }   $j = cache flat -three to 3**3 by three , -seven to seven by x , 555 to (550 - y) , 22 to -28 by -three , 1927 to 1939 by one , x to y by z , 11**x to (11**x + one) ;   put "\nLiteral minded variant:"; put ' Sum: ', comma [+] $j».abs; put ' Product: ', comma ([\*] $j.grep: so +*).first: *.abs > 2²⁷;
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Loop-While.   DATA DIVISION. WORKING-STORAGE SECTION. 01 I PIC 9999 VALUE 1024.   PROCEDURE DIVISION. PERFORM UNTIL NOT 0 < I DISPLAY I DIVIDE 2 INTO I END-PERFORM   GOBACK .
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ColdFusion
ColdFusion
<cfset i = 1024 /><cfloop condition="i GT 0"> #i#< br /> <cfset i /= 2 /> </cfloop>
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#bc
bc
for (i = 10; i >= 0; i--) i quit
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Befunge
Befunge
55+>:.:v @ ^ -1_
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program loopdowhile.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .ascii "Counter = " @ message result sMessValeur: .fill 12, 1, ' ' .asciz "\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program push {fp,lr} @ saves 2 registers mov r4,#0 1: @ begin loop mov r0,r4   ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function with 2 parameter (r0,r1) ldr r0,iAdrszMessResult bl affichageMess @ display message add r4,#1 @ increment counter mov r0,r4 mov r1,#6 @ division conuter by 6 bl division cmp r3,#0 @ remainder = zéro ? bne 1b @ no ->begin loop one   100: @ standard end of the program mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrszMessResult: .int szMessResult /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal */ /******************************************************************/ /* r0 contains value and r1 address area */ conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#10   1: @ start loop bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area sub r2,#1 @ previous position cmp r0,#0 @ stop if quotient = 0 */ bne 1b @ else loop @ and move spaces in first on area mov r1,#' ' @ space 2: strb r1,[r3,r2] @ store space in area subs r2,#1 @ @ previous position bge 2b @ loop if r2 >= zéro   100: pop {r1-r4,lr} @ restaur registres bx lr @return /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save registers */ mov r4,r0 mov r3,#0x6667 @ r3 <- magic_number lower movt r3,#0x6666 @ r3 <- magic_number upper smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ /***************************************************/ /* integer division unsigned */ /***************************************************/ division: /* r0 contains dividend */ /* r1 contains divisor */ /* r2 returns quotient */ /* r3 returns remainder */ push {r4, lr} mov r2, #0 @ init quotient mov r3, #0 @ init remainder mov r4, #32 @ init counter bits b 2f 1: @ loop movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C cmp r3, r1 @ compute r3 - r1 and update cpsr subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 ? r3 - r1 adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 2: subs r4, r4, #1 @ r4 <- r4 - 1 bpl 1b @ if r4 >= 0 (N=0) then loop pop {r4, lr} bx lr  
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#Apex
Apex
for (Integer i = 0; i < 5; i++) { String line = '';   for (Integer j = 0; j < i; j++) { line += '*'; }   System.debug(line); }   List<String> lines = new List<String> { '*', '**', '***', '****', '*****' };   for (String line : lines) { System.debug(line); }
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Axe
Axe
For(I,0,10) Disp I▶Dec,i I++ End
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Raku
Raku
constant @ludic = gather { my @taken = take 1; my @rotor;   for 2..* -> $i { loop (my $j = 0; $j < @rotor; $j++) { --@rotor[$j] or last; } if $j < @rotor { @rotor[$j] = @taken[$j+1]; } else { push @taken, take $i; push @rotor, @taken[$j+1]; } } }   say @ludic[^25]; say "Number of Ludic numbers <= 1000: ", +(@ludic ...^ * > 1000); say "Ludic numbers 2000..2005: ", @ludic[1999..2004];   my \l250 = set @ludic ...^ * > 250; say "Ludic triples < 250: ", gather for l250.keys.sort -> $a { my $b = $a + 2; my $c = $a + 6; take "<$a $b $c>" if $b ∈ l250 and $c ∈ l250; }
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#DWScript
DWScript
var i : Integer;   for i := 1 to 10 do begin Print(i); if i < 10 then Print(', '); end;
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#E
E
var i := 1 while (true) { print(i) if (i >= 10) { break } print(", ") i += 1 }
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#D
D
import std.stdio, std.random;   void main() { int[10][10] mat; foreach (ref row; mat) foreach (ref item; row) item = uniform(1, 21);   outer: foreach (row; mat) foreach (item; row) { write(item, ' '); if (item == 20) break outer; }   writeln(); }
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Ela
Ela
open monad io   each [] = do return () each (x::xs) = do putStrLn $ show x each xs
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Elena
Elena
import system'routines; import extensions;   public program() { var things := new string[]{"Apple", "Banana", "Coconut"};   things.forEach:(thing) { console.printLine:thing } }
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#C.2B.2B
C++
#include <iostream> using namespace std;   int toInt(const char c) { return c-'0'; }   int confirm( const char *id) { bool is_odd_dgt = true; int s = 0; const char *cp;   for(cp=id; *cp; cp++); while(cp > id) { --cp; int k = toInt(*cp); if (is_odd_dgt) { s += k; } else { s += (k!=9)? (2*k)%9 : 9; } is_odd_dgt = !is_odd_dgt; } return 0 == s%10; }   int main( ) { const char * t_cases[] = { "49927398716", "49927398717", "1234567812345678", "1234567812345670", NULL, }; for ( const char **cp = t_cases; *cp; cp++) { cout << *cp << ": " << confirm(*cp) << endl; } return 0; }
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Go
Go
package main   import ( "fmt" "math/big" )   var primes = []uint{3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127}   var mersennes = []uint{521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583}   func main() { llTest(primes) fmt.Println() llTest(mersennes) }   func llTest(ps []uint) { var s, m big.Int one := big.NewInt(1) two := big.NewInt(2) for _, p := range ps { m.Sub(m.Lsh(one, p), one) s.SetInt64(4) for i := uint(2); i < p; i++ { s.Mod(s.Sub(s.Mul(&s, &s), two), &m) } if s.BitLen() == 0 { fmt.Printf("M%d ", p) } } }
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Objeck
Objeck
use Collection;   class LZW { function : Main(args : String[]) ~ Nil { compressed := Compress("TOBEORNOTTOBEORTOBEORNOT"); Show(compressed); decompressed := Decompress(compressed); decompressed->PrintLine(); }   function : native : Compress(uncompressed : String) ~ IntVector { # Build the dictionary. dictSize := 256; dictionary := StringMap->New(); for (i := 0; i < 256; i+=1;) { key := ""; key->Append(i->As(Char)); dictionary->Insert(key, IntHolder->New(i)); };   w := ""; result := IntVector->New();   each (i : uncompressed) { c := uncompressed->Get(i); wc := String->New(w); wc->Append(c); if (dictionary->Has(wc)) { w := wc; } else { value := dictionary->Find(w)->As(IntHolder); result->AddBack(value->Get()); # Add wc to the dictionary. dictionary->Insert(wc, IntHolder->New(dictSize)); dictSize+=1; w := ""; w->Append(c); }; };   # Output the code for w. if (w->Size() > 0) { value := dictionary->Find(w)->As(IntHolder); result->AddBack(value->Get()); };   return result; }   function : Decompress(compressed : IntVector) ~ String { # Build the dictionary. dictSize := 256; dictionary := IntMap->New(); for (i := 0; i < 256; i+=1;) { value := ""; value->Append(i->As(Char)); dictionary->Insert(i, value); };   w := ""; found := compressed->Remove(0); w->Append(found->As(Char));   result := String->New(w); each (i : compressed) { k := compressed->Get(i);   entry : String; if (dictionary->Has(k)) { entry := dictionary->Find(k); } else if (k = dictSize) { entry := String->New(w); entry->Append(w->Get(0)); } else { return ""; }; result->Append(entry);   # Add w+entry[0] to the dictionary. value := String->New(w); value->Append(entry->Get(0)); dictionary->Insert(dictSize, value); dictSize+=1;   w := entry; };   return result; }   function : Show(results : IntVector) ~ Nil { "["->Print(); each(i : results) { results->Get(i)->Print(); if(i + 1 < results->Size()) { ", "->Print(); }; }; "]"->PrintLine(); } }
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#REXX
REXX
/*REXX program creates a matrix from console input, performs/shows LU decomposition.*/ #= 0; P.= 0; PA.= 0; L.= 0; U.= 0 /*initialize some variables to zero. */ parse arg x /*obtain matrix elements from the C.L. */ call bldAMat; call showMat 'A' /*build and display A matrix.*/ call bldPmat; call showMat 'P' /* " " " P " */ call multMat; call showMat 'PA' /* " " " PA " */ do y=1 for N; call bldUmat; call bldLmat /*build U and L " */ end /*y*/ call showMat 'L'; call showMat 'U' /*display L and U " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bldAMat: ?= words(x); do N=1 for ? until N**2>=? /*find matrix size. */ end /*N*/ if N**2\==? then do; say '***error*** wrong # of elements entered:'  ?; exit 9 end do r=1 for N /*build A matrix.*/ do c=1 for N; #= # + 1; _= word(x, #); A.r.c= _ if \datatype(_, 'N') then call er "element isn't numeric: " _ end /*c*/ end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ bldLmat: do r=1 for N /*build lower matrix.*/ do c=1 for N; if r==c then do; L.r.c= 1; iterate; end if c\==y | r==c | c>r then iterate _= PA.r.c do k=1 for c-1; _= _ - U.k.c * L.r.k end /*k*/ L.r.c= _ / U.c.c end /*c*/ end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ bldPmat: c= N; do r=N by -1 for N; P.r.c= 1; c= c + 1 /*build perm. matrix.*/ if c>N then c= N%2; if c==N then c= 1 end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ bldUmat: do r=1 for N; if r\==y then iterate /*build upper matrix.*/ do c=1 for N; if c<r then iterate _= PA.r.c do k=1 for r-1; _= _ - U.k.c * L.r.k end /*k*/ U.r.c= _ / 1 end /*c*/ end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ multMat: do i=1 for N /*multiply matrix P and A ──► PA */ do j=1 for N do k=1 for N; pa.i.j= (pa.i.j + p.i.k * a.k.j) / 1 end /*k*/ end /*j*/ /*÷ by one does normalization [↑]. */ end /*i*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ showMat: parse arg mat,rows,cols; say; rows= word(rows N,1); cols= word(cols rows,1) w= 0; do r=1 for rows do c=1 for cols; w= max(w, length( value( mat'.'r"."c ) ) ) end /*c*/ end /*r*/ say center(mat 'matrix', cols * (w + 1) + 7, "─") /*display the header.*/ do r=1 for rows; _= do c=1 for cols; _= _ right( value(mat'.'r"."c), w + 1) end /*c*/ say _ end /*r*/; return
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#REBOL
REBOL
  t: {<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.} view layout [a: area wrap t btn "Done" [x: a/text unview]] parse x [any [to "<" copy b thru ">" (append w: [] b)] to end] foreach i unique w [replace/all x i ask join i ": "] alert x  
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Function IsPrime (x) { if x<=5 OR frac(x) then { if x = 2 OR x = 3 OR x = 5 then =true Break } if x mod 2 else exit if x mod 3 else exit x1=sqrt(x): d=5@ {if x mod d else exit d += 2@: if d>x1 then =true : exit if x mod d else exit d += 4@: if d<= x1 else =true: exit loop } } \\ For Next loops or For {} loops can't change iterator variable (variable has a copy of real iterator) \\ In those loops we have to use Continue to skip lines and repeat the loop. \\ so we have to use Block iterator, using Loop which set a flag current block to repeat itself once. def long Limit=42, n def decimal i i=Limit { if n<Limit Else exit if isPrime(i) then n++ : Print format$("n={0::2}: {1:-20}", n, str$(i,"#,###")) : i+=i-1 i++ loop } } CheckIt  
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Maple
Maple
i := 42: count := 0: while(count < 42) do i := i+1: if type(i,prime) then count := count + 1: printf("n=%-2d  %19d\n", count,i): i := 2*i -1: end if: end do:
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Chapel
Chapel
while true do writeln("SPAM");
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ChucK
ChucK
  while(true) <<<"SPAM">>>;  
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Red
Red
Red ["For loop with multiple ranges"]   ->: make op! function [start end][ res: copy [] repeat n 1 + absolute to-integer end - start [ append res start + either start > end [1 - n][n - 1] ] ] by: make op! function [s w] [extract s absolute w]   for: function ['word ranges body][ inp: copy [] foreach c reduce ranges [append inp c] foreach i inp [set word i do body] ]   prod: 1 sum: 0 x: +5 y: -5 z: -2 one: 1 three: 3 seven: 7   for j [ 0 - three -> (3 ** 3) by three 0 - seven -> seven by x 555 -> (550 - y) 22 -> -28 by (0 - three) 1927 -> 1939 x -> y by z 11 ** x -> (11 ** x + one) ] [ sum: sum + absolute j; if all [(absolute prod) < power 2 27 j <> 0] [prod: prod * j] ] print ["sum: " sum "^/prod:" prod]
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#REXX
REXX
/*REXX program emulates a multiple─range DO loop (all variables can be any numbers). */ prod= 1; sum= 0; x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7;   do j= -three to 3**3 by three  ; call meat; end; do j= -seven to seven by x  ; call meat; end; do j= 555 to 550 - y  ; call meat; end; do j= 22 to -28 by -three ; call meat; end; do j= 1927 to 1939  ; call meat; end; do j= x to y by z  ; call meat; end; do j= 11**x to 11**x + one  ; call meat; end;   say ' sum= ' || commas( sum); /*display SUM with commas. */ say 'prod= ' || commas(prod); /* " PROD " " */ exit; /*stick a fork in it, we're done.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M") e= verify(n, #'0', , verify(n, #"0.", 'M') ) - 4 do j=e to b by -3; _= insert(',', _, j); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ meat: sum= sum + abs(j); if abs(prod)<2**27 & j\==0 then prod= prod * j; return;
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Common_Lisp
Common Lisp
(let ((i 1024)) (loop while (plusp i) do (print i) (setf i (floor i 2))))   (loop with i = 1024 while (plusp i) do (print i) (setf i (floor i 2)))   (defparameter *i* 1024) (loop while (plusp *i*) do (print *i*) (setf *i* (floor *i* 2)))  
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#BQN
BQN
•Show¨⌽↕11
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Bracmat
Bracmat
10:?i & whl'(out$!i&!i+-1:~<0:?i)
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#AppleScript
AppleScript
  on printConsole(x) return x as string end printConsole   set {i, table} to {0, {return}} repeat while (i mod 6 is not 0 or i is not 6) set i to i + 1 set end of table to i & return printConsole(table) end repeat  
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#APL
APL
{⎕←⍵/'*'}¨⍳5
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#BASIC
BASIC
FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?"
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#REXX
REXX
/*REXX program gens/shows (a range of) ludic numbers, or a count when a range is used.*/ parse arg N count bot top triples . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ if count=='' | count=="," then count= 1000 /* " " " " " " */ if bot=='' | bot=="," then bot= 2000 /* " " " " " " */ if top=='' | top=="," then top= 2005 /* " " " " " " */ if triples=='' | triples=="," then triples= 249 /* " " " " " " */ #= 0 /*the number of ludic numbers (so far).*/ $= ludic( max(N, count, bot, top, triples) ) /*generate enough ludic nums*/ say 'The first ' N " ludic numbers: " subword($,1,25) /*display 1st N ludic nums*/ do j=1 until word($, j) > count /*search up to a specific #.*/ end /*j*/ say say "There are " j - 1 ' ludic numbers that are ≤ ' count say say "The " bot '───►' top ' (inclusive) ludic numbers are: ' subword($, bot) @= /*list of ludic triples found (so far).*/ do j=1 for words($) _= word($, j) /*it is known that ludic _ exists. */ if _>=triples then leave /*only process up to a specific number.*/ if wordpos(_+2, $)==0 | wordpos(_+6, $)==0 then iterate /*Not triple? Skip it.*/ #= # + 1 /*bump the triple counter. */ @= @ '◄'_ _+2 _+6"► " /*append the newly found triple ──► @ */ end /*j*/ say if @=='' then say 'From 1──►'triples", no triples found." else say 'From 1──►'triples", " # ' triples found:' @ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ludic: procedure; parse arg m,,@; $= 1 2 /*$≡ludic numbers superset; @≡sequence*/ do j=3 by 2 to m*15; @= @ j /*construct an initial list of numbers.*/ end /*j*/ @= @' '; n= words(@) /*append a blank to the number sequence*/ do while n\==0; f= word(@, 1) /*examine the first word in the @ list.*/ $= $ f /*add the word to the $ list. */ do d=1 by f while d<=n; n= n-1 /*use 1st number, elide all occurrences*/ @= changestr(' 'word(@, d)" ", @, ' . ') /*cross─out a number in @ */ end /*d*/ /* [↑] done eliding the "1st" number. */ @= translate(@, , .) /*change dots to blanks; count numbers.*/ end /*while*/ /* [↑] done eliding ludic numbers. */ return subword($, 1, m) /*return a range of ludic numbers. */
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#EchoLisp
EchoLisp
  (string-delimiter "")   (for ((i (in-range 1 11))) (write i) #:break (= i 10) (write ",")) → 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10   ;; or   (string-join (range 1 11) ",") → 1,2,3,4,5,6,7,8,9,10  
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#dc
dc
1 ss [Seed of the random number generator.]sz   [* * lrx -- (number) * Push a random number from 1 to 20. *]sz [ [ [If preventing modulo bias:]sz sz [Drop this random number.]sz lLx [Loop.]sz ]SI [ [Loop:]sz [* * Formula (from POSIX) for random numbers of low quality. * Push a random number from 0 to 32767. *]sz ls 1103515245 * 12345 + 4294967296 % ss ls 65536 / 32768 %   d 32768 20 % >I [Prevent modulo bias.]sz ]d SL x 20 % 1 + [Be from 1 to 20.]sz LLsz LIsz [Restore L, I.]sz ]sr     5 sb [b = Total rows]sz 5 sc [c = Total columns]sz   [Fill array a[] with random numbers from 1 to 20.]sz [ [Inner loop for j:]sz lrx [Push random number.]sz li lc * lj + [Push index of a[i, j].]sz  :a [Put in a[].]sz lj 1 + d sj [j += 1]sz lc >I [Loop while c > j.]sz ]sI [ [Outer loop for i:]sz 0 d sj [j = 0]sz lc >I [Enter inner loop.]sz li 1 + d si [i += 1]sz lb >L [Loop while b > i.]sz ]sL 0 d si [i = 0]sz lb >L [Enter outer loop.]sz   [Find a 20.]sz [ [If detecting a 20:]sz li lj + 3 + Q [Break outer loop.]sz ]sD [ [Inner loop for j:]sz li lc * lj + [Push index of a[i,j].]sz  ;a [Push value from a[].]sz p [Print value and a newline.]sz 20 =D [Detect a 20.]sz lj 1 + d sj [j += 1]sz lc >I [Loop while c > j.]sz ]sI [ [Outer loop for i:]sz 0 d sj [j = 0]sz lc >I [Enter inner loop.]sz [== ]P [Print "==" and a newline.]sz li 1 + d si [i += 1]sz lb >L [Loop while b > i.]sz ]sL 0 d si [i = 0]sz lb >L [Enter outer loop.]sz
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Delphi.2FPascal
Delphi/Pascal
var matrix: array[1..10,1..10] of Integer; row, col: Integer; broken: Boolean; begin // Launch random number generator randomize; // Filling matrix with random numbers for row := 1 to 10 do for col := 1 to 10 do matrix[row, col] := Succ(Random(20)); // Displaying values one by one, until at the end or reached number 20 Broken := False; for row := 1 to 10 do begin for col := 1 to 10 do begin ShowMessage(IntToStr(matrix[row, col])); if matrix[row, col] = 20 then begin Broken := True; break; end; end; if Broken then break; end; end;
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Elixir
Elixir
iex(1)> list = [1,3.14,"abc",[3],{0,5}] [1, 3.14, "abc", [3], {0, 5}] iex(2)> Enum.each(list, fn x -> IO.inspect x end) 1 3.14 "abc" [3] {0, 5} :ok
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Utils.Check [ Abstract ] {   ClassMethod Luhn(x As %String) As %Boolean { // https://www.simple-talk.com/sql/t-sql-programming/calculating-and-verifying-check-digits-in-t-sql/ SET x=$TRANSLATE(x," "), cd=$EXTRACT(x,*) SET x=$REVERSE($EXTRACT(x,1,*-1)), t=0 FOR i=1:1:$LENGTH(x) { SET n=$EXTRACT(x,i) IF i#2 SET n=n*2 IF $LENGTH(n)>1 SET n=$EXTRACT(n,1)+$EXTRACT(n,2) SET t=t+n } QUIT cd=((t*9)#10) }   }
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#Haskell
Haskell
module Main where   main = printMersennes $ take 45 $ filter lucasLehmer $ sieve [2..]   s mp 1 = 4 `mod` mp s mp n = ((s mp $ n-1)^2-2) `mod` mp   lucasLehmer 2 = True lucasLehmer p = s (2^p-1) (p-1) == 0   printMersennes = mapM_ (\x -> putStrLn $ "M" ++ show x)
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Objective-C
Objective-C
#import <Foundation/Foundation.h> #import <stdio.h>   @interface LZWCompressor : NSObject { @private NSMutableArray *iostream; NSMutableDictionary *dict; NSUInteger codemark; }   -(instancetype) init; -(instancetype) initWithArray: (NSMutableArray *) stream; -(BOOL) compressData: (NSData *) string; -(void) setArray: (NSMutableArray *) stream; -(NSArray *) getArray; @end   @implementation LZWCompressor : NSObject   -(instancetype) init { self = [super init]; if ( self ) { iostream = nil; codemark = 256; dict = [[NSMutableDictionary alloc] initWithCapacity: 512]; } return self; }   -(instancetype) initWithArray: (NSMutableArray *) stream { self = [self init]; if ( self ) { [self setArray: stream]; } return self; }   -(void) setArray: (NSMutableArray *) stream { iostream = stream; }   -(BOOL) compressData: (NSData *) string; { // prepare dict for(NSUInteger i=0; i < 256; i++) { unsigned char j = i; NSData *s = [NSData dataWithBytes: &j length: 1]; dict[s] = @(i); }   NSData *w = [NSData data];   for(NSUInteger i=0; i < [string length]; i++) { NSMutableData *wc = [NSMutableData dataWithData: w]; [wc appendData: [string subdataWithRange: NSMakeRange(i, 1)]]; if ( dict[wc] != nil ) { w = wc; } else { [iostream addObject: dict[w]]; dict[wc] = @(codemark); codemark++; w = [string subdataWithRange: NSMakeRange(i, 1)]; } } if ( [w length] != 0 ) { [iostream addObject: dict[w]]; } return YES; }   -(NSArray *) getArray { return iostream; }   @end
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#Ruby
Ruby
require 'matrix'   class Matrix def lu_decomposition p = get_pivot tmp = p * self u = Matrix.zero(row_size).to_a l = Matrix.identity(row_size).to_a (0 ... row_size).each do |i| (0 ... row_size).each do |j| if j >= i # upper u[i][j] = tmp[i,j] - (0 ... i).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]} else # lower l[i][j] = (tmp[i,j] - (0 ... j).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j] end end end [ Matrix[*l], Matrix[*u], p ] end   def get_pivot raise ArgumentError, "must be square" unless square? id = Matrix.identity(row_size).to_a (0 ... row_size).each do |i| max = self[i,i] row = i (i ... row_size).each do |j| if self[j,i] > max max = self[j,i] row = j end end id[i], id[row] = id[row], id[i] end Matrix[*id] end   def pretty_print(format, head=nil) puts head if head puts each_slice(column_size).map{|row| format*row_size % row} end end   puts "Example 1:" a = Matrix[[1, 3, 5], [2, 4, 7], [1, 1, 0]] a.pretty_print(" %2d", "A") l, u, p = a.lu_decomposition l.pretty_print(" %8.5f", "L") u.pretty_print(" %8.5f", "U") p.pretty_print(" %d", "P")   puts "\nExample 2:" a = Matrix[[11, 9,24,2], [ 1, 5, 2,6], [ 3,17,18,1], [ 2, 5, 7,1]] a.pretty_print(" %2d", "A") l, u, p = a.lu_decomposition l.pretty_print(" %8.5f", "L") u.pretty_print(" %8.5f", "U") p.pretty_print(" %d", "P")
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#Red
Red
phrase: ask "Enter phrase, leave line empty to terminate:^/" while [not empty? line: input] [append phrase rejoin ["^/" line]] words: parse phrase [collect [any [to "<" copy b thru ">" keep (b)]]] foreach w unique words [replace/all phrase w ask rejoin [w ": "]] print phrase
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
{i, n} = {42, 0}; While[n < 42, If[PrimeQ[i], Print["n=", n++, "\t", i]; i += i - 1; ]; i++; ]
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Microsoft_Small_Basic
Microsoft Small Basic
'Loops Increment loop index within loop body - 16/07/2018 imax=42 i=0 n=42 While i<imax isprime_n() If ret_isprime_n Then i=i+1 format_i() format_n() TextWindow.WriteLine("i="+ret_format_i+" : "+ret_format_n) n=n+n-1 EndIf n=n+1 EndWhile   Sub isprime_n If n=2 Or n=3 Then ret_isprime_n="True" ElseIf Math.Remainder(n,2)=0 Or Math.Remainder(n,3)=0 Then ret_isprime_n="False" Else j=5 While j*j<=n If Math.Remainder(n,j)=0 Or Math.Remainder(n,j+2)=0 Then ret_isprime_n="False" Goto exitsub EndIf j=j+6 EndWhile ret_isprime_n="True" EndIf exitsub: EndSub 'isprime_n   Sub format_i ret_format_i=Text.GetSubText(" ",1,3-Text.GetLength(i))+i EndSub 'format_i   Sub format_n nn="" l=-1 For k=Text.GetLength(n) To 1 Step -1 l=l+1 cc=Text.GetSubText(n,k,1) If l=3 Then cv="," l=0 Else cv="" EndIf nn=Text.Append(cc,Text.Append(cv,nn)) EndFor space=" " nn=Text.GetSubText(space,1,Text.GetLength(space)-Text.GetLength(nn))+nn ret_format_n=nn EndSub 'format_n
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Clojure
Clojure
(loop [] (println "SPAM") (recur))
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Spam.   PROCEDURE DIVISION. PERFORM UNTIL 1 <> 1 DISPLAY "SPAM" END-PERFORM   GOBACK .
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Ring
Ring
  prod = 1 total = 0 x = 5 y = -5 z = -2 one = 1 three = 3 seven = 7   loopset = [[-three,pow(3,3),three], [-seven,seven,x], [555,550 - y,1], [22,-28,-three], [1927,1939,1], [x,y,z], [pow(11,x),pow(11,x) + one,1]]   for i=1 to len(loopset) f = loopset[i][1] t = loopset[i][2] s = loopset[i][3] for j=f to t step s total += fabs(j) if fabs(prod)<pow(2,27) and j!=0 prod *= j ok next next   see "total = " + total + nl see "product = " + prod + nl  
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Ruby
Ruby
x, y, z, one, three, seven = 5, -5, -2, 1, 3, 7   enums = (-three).step(3**3, three) + (-seven).step(seven, x) + 555 .step(550-y, -1) + 22 .step(-28, -three) + (1927..1939) + # just toying, 1927.step(1939) is fine too x .step(y, z) + (11**x) .step(11**x + one) # enums is an enumerator, consisting of a bunch of chained enumerators, # none of which has actually produced a value.   puts "Sum of absolute numbers: #{enums.sum(&:abs)}" prod = enums.inject(1){|prod, j| ((prod.abs < 2**27) && j!=0) ? prod*j : prod} puts "Product (but not really): #{prod}"  
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Cowgol
Cowgol
include "cowgol.coh";   var n: uint16 := 1024; while n > 0 loop print_i16(n); print_nl(); n := n/2; end loop;
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Brainf.2A.2A.2A
Brainf***
>++++++++[-<++++++>] //cell 0 now contains 48 the ASCII code for "0" <+.-. //print the digits 1 and 0 >++++++++++. //cell 1 now contains the carriage return; print it! >+++++++++ //cell 2 now contains the number 9; this is our counter <<+++++++++>> //cell 0 now contains 57 the ASCII code for "9" [<<.->.>-] //print and decrement the display digit; print a newline; decrement the loop variable <<.>. //print the final 0 and a final newline
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#Arturo
Arturo
value: 0 until [ value: value + 1 print value ] [ 0 = value%6 ]
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#AppleScript
AppleScript
set x to linefeed repeat with i from 1 to 5 repeat with j from 1 to i set x to x & "*" end repeat set x to x & linefeed end repeat return x
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Batch_File
Batch File
@echo off for /l %%A in (1,2,10) do ( echo %%A )
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Ring
Ring
  # Project : Ludic numbers   ludic = list(300) resludic = [] nr = 1 for n = 1 to len(ludic) ludic[n] = n+1 next see "the first 25 Ludic numbers are:" + nl ludicnumbers(ludic) showarray(resludic) see nl   see "Ludic numbers below 1000: " ludic = list(3000) resludic = [] for n = 1 to len(ludic) ludic[n] = n+1 next ludicnumbers(ludic) showarray2(resludic) see nr see nl + nl   see "the 2000..2005th Ludic numbers are:" + nl ludic = list(60000) resludic = [] for n = 1 to len(ludic) ludic[n] = n+1 next ludicnumbers(ludic) showarray3(resludic)   func ludicnumbers(ludic) for n = 1 to len(ludic) delludic = [] for m = 1 to len(ludic) step ludic[1] add(delludic, m) next add(resludic, ludic[1]) for p = len(delludic) to 1 step -1 del(ludic, delludic[p]) next next   func showarray(vect) see "[1, " svect = "" for n = 1 to 24 svect = svect + vect[n] + ", " next svect = left(svect, len(svect) - 2) see svect see "]" + nl   func showarray2(vect) for n = 1 to len(vect) if vect[n] <= 1000 nr = nr + 1 ok next return nr   func showarray3(vect) see "[" svect = "" for n = 1999 to 2004 svect = svect + vect[n] + ", " next svect = left(svect, len(svect) - 2) see svect see "]" + nl  
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#EDSAC_order_code
EDSAC order code
[ N and a half times loop =======================   A program for the EDSAC   Works with Initial Orders 2 ]   T56K GK   O16@ [ 1 ] T24@ A25@ A18@ U25@ S23@ E11@   O25@ O19@ O20@ G1@   [ 11 ] O18@ O17@ O21@ O22@ ZF   [ 16 ] #F [ 17 ] PF [ 18 ] QF [ 19 ] NF [ 20 ]  !F [ 21 ] @F [ 22 ] &F [ 23 ] JF [ 24 ] PF [ 25 ] PF   EZPF
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Elixir
Elixir
defmodule Loops do def n_plus_one_half([]), do: IO.puts "" def n_plus_one_half([x]), do: IO.puts x def n_plus_one_half([h|t]) do IO.write "#{h}, " n_plus_one_half(t) end end   Enum.to_list(1..10) |> Loops.n_plus_one_half
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Dyalect
Dyalect
let array = [[2, 12, 10, 4], [18, 11, 20, 2]]   for row in array { break when { for element in row { print("\(element)") if element == 20 { break true } } } } print("*Done")
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#E
E
def array := accum [] for i in 1..5 { _.with(accum [] for i in 1..5 { _.with(entropy.nextInt(20) + 1) }) }   escape done { for row in array { for x in row { print(`$x$\t`) if (x == 20) { done() } } println() } } println("done.")
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Emacs_Lisp
Emacs Lisp
(dolist (x '(1 2 3 4)) (message "x=%d" x))
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Erlang
Erlang
io:format("~p~n",[Collection]).
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#Ceylon
Ceylon
shared void run() { value numbers = "49927398716 49927398717 1234567812345678 1234567812345670"; for(number in numbers.lines) { print("``number`` passes? ``luhn(number)``"); } }   shared Boolean luhn(String number) { value digits = number .reversed .map(Character.string) .map(Integer.parse) .narrow<Integer>(); value s1 = sum { 0, *digits.by(2) }; value s2 = sum { 0, *digits .skip(1) .by(2) .map(curry(times<Integer>)(2)) .map((Integer element) => element / 10 + element % 10) }; return (s1 + s2) % 10 == 0; }
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#HicEst
HicEst
s = 0 DO exponent = 2, 31 IF(exponent > 2) s = 4 n = 2^exponent - 1 DO i = 1, exponent-2 s = MOD(s*s - 2, n) ENDDO IF(s == 0) WRITE(Messagebox) 'M', exponent, ' is prime;', n ENDDO   END
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#OCaml
OCaml
#directory "+extlib" (* or maybe "+site-lib/extlib/" *) #load "extLib.cma" open ExtString   (** compress a string to a list of output symbols *) let compress ~uncompressed = (* build the dictionary *) let dict_size = 256 in let dictionary = Hashtbl.create 397 in for i=0 to 255 do let str = String.make 1 (char_of_int i) in Hashtbl.add dictionary str i done;   let f = (fun (w, dict_size, result) c -> let c = String.make 1 c in let wc = w ^ c in if Hashtbl.mem dictionary wc then (wc, dict_size, result) else begin (* add wc to the dictionary *) Hashtbl.add dictionary wc dict_size; let this = Hashtbl.find dictionary w in (c, dict_size + 1, this::result) end ) in let w, _, result = String.fold_left f ("", dict_size, []) uncompressed in   (* output the code for w *) let result = if w = "" then result else (Hashtbl.find dictionary w) :: result in   (List.rev result) ;;   exception ValueError of string   (** decompress a list of output symbols to a string *) let decompress ~compressed = (* build the dictionary *) let dict_size = 256 in let dictionary = Hashtbl.create 397 in for i=0 to pred dict_size do let str = String.make 1 (char_of_int i) in Hashtbl.add dictionary i str done;   let w, compressed = match compressed with | hd::tl -> (String.make 1 (char_of_int hd)), tl | [] -> failwith "empty input" in   let result = [w] in   let result, _, _ = List.fold_left (fun (result, w, dict_size) k -> let entry = if Hashtbl.mem dictionary k then Hashtbl.find dictionary k else if k = Hashtbl.length dictionary then w ^ (String.make 1 w.[0]) else raise(ValueError(Printf.sprintf "Bad compressed k: %d" k)) in let result = entry :: result in   (* add (w ^ entry.[0]) to the dictionary *) Hashtbl.add dictionary dict_size (w ^ (String.make 1 entry.[0])); (result, entry, dict_size + 1) ) (result, w, dict_size) compressed in (List.rev result) ;;
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#Rust
Rust
  #![allow(non_snake_case)] use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};   fn main() { println!("Example 1:"); let A: Array2<f64> = arr2(&[ [1.0, 3.0, 5.0], [2.0, 4.0, 7.0], [1.0, 1.0, 0.0], ]); println!("A \n {}", A); let (L, U, P) = lu_decomp(A); println!("L \n {}", L); println!("U \n {}", U); println!("P \n {}", P);   println!("\nExample 2:"); let A: Array2<f64> = arr2(&[ [11.0, 9.0, 24.0, 2.0], [1.0, 5.0, 2.0, 6.0], [3.0, 17.0, 18.0, 1.0], [2.0, 5.0, 7.0, 1.0], ]); println!("A \n {}", A); let (L, U, P) = lu_decomp(A); println!("L \n {}", L); println!("U \n {}", U); println!("P \n {}", P); }   fn pivot<T>(A: &Array2<T>) -> Array2<T> where T: NdFloat { let matrix_dimension = A.rows(); let mut P: Array2<T> = Array::eye(matrix_dimension); for (i, column) in A.axis_iter(Axis(1)).enumerate() { // find idx of maximum value in column i let mut max_pos = i; for j in i..matrix_dimension { if column[max_pos].abs() < column[j].abs() { max_pos = j; } } // swap rows of P if necessary if max_pos != i { swap_rows(&mut P, i, max_pos); } } P }   fn swap_rows<T>(A: &mut Array2<T>, idx_row1: usize, idx_row2: usize) where T: NdFloat { // to swap rows, get two ArrayViewMuts for the corresponding rows // and apply swap elementwise using ndarray::Zip let (.., mut matrix_rest) = A.view_mut().split_at(Axis(0), idx_row1); let (row0, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), 1); let (_matrix_helper, mut matrix_rest) = matrix_rest.view_mut().split_at(Axis(0), idx_row2 - idx_row1 - 1); let (row1, ..) = matrix_rest.view_mut().split_at(Axis(0), 1); Zip::from(row0).and(row1).apply(std::mem::swap); }   fn lu_decomp<T>(A: Array2<T>) -> (Array2<T>, Array2<T>, Array2<T>) where T: NdFloat {   let matrix_dimension = A.rows(); assert_eq!(matrix_dimension, A.cols(), "Tried LU decomposition with a non-square matrix."); let P = pivot(&A); let pivotized_A = P.dot(&A);   let mut L: Array2<T> = Array::eye(matrix_dimension); let mut U: Array2<T> = Array::zeros((matrix_dimension, matrix_dimension)); for idx_col in 0..matrix_dimension { // fill U for idx_row in 0..idx_col+1 { U[[idx_row, idx_col]] = pivotized_A[[idx_row, idx_col]] - U.slice(s![0..idx_row,idx_col]).dot(&L.slice(s![idx_row,0..idx_row])); } // fill L for idx_row in idx_col+1..matrix_dimension { L[[idx_row, idx_col]] = (pivotized_A[[idx_row, idx_col]] - U.slice(s![0..idx_col,idx_col]).dot(&L.slice(s![idx_row,0..idx_col]))) / U[[idx_col, idx_col]]; } } (L, U, P) }  
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#REXX
REXX
/*REXX program prompts the user for a template substitutions within a story (MAD LIBS).*/ parse arg iFID . /*allow user to specify the input file.*/ if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/ @.= /*assign defaults to some variables. */ $=; do recs=1 while lines(iFID)\==0 /*read the input file until it's done. */ @.recs=linein(iFID); $=$ @.recs /*read a record; and append it to @ */ if @.recs='' then leave /*Read a blank line? Then we're done.*/ end /*recs*/ recs=recs-1 /*adjust for a E─O─F or a blank line.*/ pm= 'please enter a word or phrase to replace: ' /*this is part of the Prompt Message. */ !.=0 /*placeholder for phrases in MAD LIBS.*/ #=0; do forever /*look for templates within the text. */ parse var $ '<'  ? ">" $ /*scan for <ααα> stuff in the text.*/ if ?='' then leave /*No ααα ? Then we're all finished.*/ if !.? then iterate /*Already asked? Then keep scanning. */  !.?=1 /*mark this ααα as being "found". */ do until ans\='' /*prompt user for a replacement. */ say '───────────' pm  ? /*prompt the user with a prompt message*/ parse pull ans /*PULL obtains the text from console. */ end /*forever*/ #=#+1 /*bump the template counter. */ old.# = '<'?">"; new.# = ans /*assign the "old" name and "new" name.*/ end /*forever*/ say /*display a blank line for a separator.*/ say; say copies('═', 79) /*display a blank line and a fence. */   do m=1 for recs /*display the text, line for line. */ do n=1 for # /*perform substitutions in the text. */ @.m=changestr(old.n, @.m, new.n) /*maybe replace text in @.m haystack.*/ end /*n*/ say @.m /*display the (new) substituted text. */ end /*m*/   say copies('═', 79) /*display a final (output) fence. */ say /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Nanoquery
Nanoquery
limit = 42   def isPrime(n) if ((n % 2) = 0) or ((n % 3) = 0) return false end d = 5 while (d * d) <= n if (n % d) = 0 return false end d += 2 if (n % d) = 0 return false end d += 4 end return true end   i = limit for (n = 0) (n < limit) (i += 1) if isPrime(i) n += 1 print format("n = %-2d  %,19d\n", n, i) i += i - 1 end end
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#NewLISP
NewLISP
  #! /usr/local/bin/newlisp   (define (prime? n) (and (set 'lst (factor n)) (= (length lst) 1)))   (define (thousands_separator i) (setq i (string i)) (setq len (length i)) (setq i (reverse (explode i))) (setq o "") (setq count3 0) (dolist (x i) (setq o (string o x)) (inc count3) (if (and (= 3 count3) (< (+ $idx 1) len)) (begin (setq o (string o "_")) (setq count3 0))))   (reverse o))     ;- - - Main begins here (setq i 42) (setq n 0) (while (< n 42) (if (prime? i) (begin (inc n) (println (string "n = " n " -> " (thousands_separator i))) (setq i (+ i i -1)))) (inc i) )   (exit)  
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#CoffeeScript
CoffeeScript
loop console.log 'SPAM'  
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ColdFusion
ColdFusion
<cfloop condition = "true NEQ false"> SPAM </cfloop>
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Smalltalk
Smalltalk
prod := 1. sum := 0. x := 5. y := -5. z := -2. one := 1. three := 3. seven := 7.   (three negated to: 3**3 by: three ) , (seven negated to: seven by: x ) , (555 to: 550-y ) , (22 to: -28 by: three negated) , (1927 to: 1939 ) , (x to: y by:z ) , (11**x to: 11**x + one ) do:[:j | sum := sum + j abs. ((prod abs < (2**27)) and:[ j ~= 0 ]) ifTrue:[ prod := prod*j ]. ]. Transcript show:' sum = '; showCR:sum. Transcript show:'prod = '; showCR:prod
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Crack
Crack
i = 1024; while( i > 0 ) { cout ` $i\n`; i = i/2; }
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Crystal
Crystal
i = 1024 while i > 0 puts i i //= 2 end
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Brat
Brat
10.to 0 { n | p n }
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#C
C
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#Asymptote
Asymptote
int i = 0; do { ++i; write(" ", i, suffix=none); } while (i % 6 != 0);
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program loop1.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessX: .asciz "X" szCarriageReturn: .asciz "\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */   mov r2,#0 @ counter loop 1 1: @ loop start 1 mov r1,#0 @ counter loop 2 2: @ loop start 2 ldr r0,iAdrszMessX bl affichageMess add r1,#1 @ r1 + 1 cmp r1,r2 @ compare r1 r2 ble 2b @ loop label 2 before ldr r0,iAdrszCarriageReturn bl affichageMess add r2,#1 @ r2 + 1 cmp r2,#5 @ for five loop blt 1b @ loop label 1 before     100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call   iAdrszMessX: .int szMessX iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */    
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#bc
bc
for (i = 2; i <= 10; i += 2) { i }
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#Ruby
Ruby
def ludic(nmax=100000) Enumerator.new do |y| y << 1 ary = *2..nmax until ary.empty? y << (n = ary.first) (0...ary.size).step(n){|i| ary[i] = nil} ary.compact! end end end   puts "First 25 Ludic numbers:", ludic.first(25).to_s   puts "Ludics below 1000:", ludic(1000).count   puts "Ludic numbers 2000 to 2005:", ludic.first(2005).last(6).to_s   ludics = ludic(250).to_a puts "Ludic triples below 250:", ludics.select{|x| ludics.include?(x+2) and ludics.include?(x+6)}.map{|x| [x, x+2, x+6]}.to_s
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Erlang
Erlang
%% Implemented by Arjun Sunel -module(loop). -export([main/0]).   main() -> for_loop(1).   for_loop(N) -> if N < 10 -> io:format("~p, ",[N] ), for_loop(N+1); true -> io:format("~p\n",[N]) end.  
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ERRE
ERRE
  FOR I=1 TO 10 DO PRINT(I;) EXIT IF I=10 PRINT(", ";) END FOR  
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task also shows how to break out of nested loops. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#EchoLisp
EchoLisp
  (lib 'math) ;; for 2D-arrays (define array (build-array 42 42 (lambda(i j) (1+ (random 20))))) → array   ;; (for* ((row array) (aij row)) (write aij) #:break (= aij 20)) → 9 8 11 1 14 11 1 9 16 1 10 5 5 6 5 4 13 17 14 13 6 10 16 4 8 5 1 17 16 19 4 6 18 1 15 3 4 13 19 6 12 5 5 17 19 16 3 7 2 15 16 14 16 16 19 18 14 16 6 18 14 17 20  
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#ERRE
ERRE
  FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO PRINT(INDEX$;" ";) END FOR PRINT  
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Euphoria
Euphoria
  include std/console.e   sequence s = {-2,-1,0,1,2} --print elements of a numerical list for i = 1 to length(s) do ? s[i] end for   puts(1,'\n')   s = {"Name","Date","Field1","Field2"} -- print elements of a list of 'strings' for i = 1 to length(s) do printf(1,"%s\n",{s[i]}) end for   puts(1,'\n')   for i = 1 to length(s) do -- print subelements of elements of a list of 'strings' for j = 1 to length(s[i]) do printf(1,"%s\n",s[i][j]) end for puts(1,'\n') end for   if getc(0) then end if  
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#Clojure
Clojure
(defn luhn? [cc] (let [factors (cycle [1 2]) numbers (map #(Character/digit % 10) cc) sum (reduce + (map #(+ (quot % 10) (mod % 10)) (map * (reverse numbers) factors)))] (zero? (mod sum 10))))   (doseq [n ["49927398716" "49927398717" "1234567812345678" "1234567812345670"]] (println (luhn? n)))
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#J
J
import java.math.BigInteger; public class Mersenne {   public static boolean isPrime(int p) { if (p == 2) return true; else if (p <= 1 || p % 2 == 0) return false; else { int to = (int)Math.sqrt(p); for (int i = 3; i <= to; i += 2) if (p % i == 0) return false; return true; } }   public static boolean isMersennePrime(int p) { if (p == 2) return true; else { BigInteger m_p = BigInteger.ONE.shiftLeft(p).subtract(BigInteger.ONE); BigInteger s = BigInteger.valueOf(4); for (int i = 3; i <= p; i++) s = s.multiply(s).subtract(BigInteger.valueOf(2)).mod(m_p); return s.equals(BigInteger.ZERO); } }   // an arbitrary upper bound can be given as an argument public static void main(String[] args) { int upb; if (args.length == 0) upb = 500; else upb = Integer.parseInt(args[0]);   System.out.print(" Finding Mersenne primes in M[2.." + upb + "]:\nM2 "); for (int p = 3; p <= upb; p += 2) if (isPrime(p) && isMersennePrime(p)) System.out.print(" M" + p); System.out.println(); } }
http://rosettacode.org/wiki/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Ol
Ol
  (define (compress str) (let loop ((dc (fold (lambda (f x) ; dictionary (simplest, not optimized), with reversed codes (cons (list x) (cons x f))) '() (iota 256))) (w '()) ; output sequence (reversed) (s 256) ; maximal dictionary code value + 1 (x '()) ; current sequence (r (str-iter str))); input stream (cond ((null? r) (reverse (cons (cadr (member x dc)) w))) ((pair? r) (let ((xy (cons (car r) x))) (if (member xy dc) (loop dc w s xy (cdr r)) (loop (cons xy (cons s dc)) ; update dictionary with xy . s (cons (cadr (member x dc)) w) ; add code to output stream (+ s 1) ; increase code (list (car r)) ; new current sequence (cdr r))))) ; next input (else (loop dc w s x (r))))) )   (print (compress "TOBEORNOTTOBEORTOBEORNOT")) ; => (84 79 66 69 79 82 78 79 84 256 258 260 265 259 261 263)  
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#Sidef
Sidef
func is_square(m) { m.all { .len == m.len } } func matrix_zero(n, m=n) { m.of { n.of(0) } } func matrix_ident(n) { n.of {|i| n.of {|j| i==j ? 1 : 0 } } }   func pivotize(m) { var size = m.len var id = matrix_ident(size) for i (^size) { var max = m[i][i] var row = i for j (i .. size-1) { if (m[j][i] > max) { max = m[j][i] row = j } } if (row != i) { id.swap(row, i) } } return id }   func mmult(a, b) { var p = [] for r,c (^a ~X ^b[0]) { for i (^b) { p[r][c] := 0 += (a[r][i] * b[i][c]) } } return p }   func lu(a) { is_square(a) || die "Defined only for square matrices!"; var n = a.len var P = pivotize(a) var Aʼ = mmult(P, a) var L = matrix_ident(n) var U = matrix_zero(n) for i,j (^n ~X ^n) { if (j >= i) { U[i][j] = (Aʼ[i][j] - ({ U[_][j] * L[i][_] }.map(^i).sum)) } else { L[i][j] = (Aʼ[i][j] - ({ U[_][j] * L[i][_] }.map(^j).sum))/U[j][j] } } return [P, Aʼ, L, U] }   func say_it(message, array) { say "\n#{message}" array.each { |row| say row.map{"%7s" % .as_rat}.join(' ') } }   var t = [[ %n(1 3 5), %n(2 4 7), %n(1 1 0), ],[ %n(11 9 24 2), %n( 1 5 2 6), %n( 3 17 18 1), %n( 2 5 7 1), ]]   for test (t) { say_it('A Matrix', test); for a,b (['P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix'] ~Z lu(test)) { say_it(a, b) } }
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). 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
#Ring
Ring
  temp="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home." k = substr(temp,"<") while k replace = substr(temp,k,substr(temp,">")-k + 1) see "replace:" + replace + " with: " give with while k temp = left(temp,k-1) + with + substr(temp,k + len(replace)) k = substr(temp,replace) end k = substr(temp,"<") end see temp + nl  
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Nim
Nim
  import strformat from strutils import insertSep   func isPrime(i: int): bool = if i == 2 or i == 3: return true elif i mod 2 == 0 or i mod 3 == 0: return false var idx = 5 while idx*idx <= i: if i mod idx == 0: return false idx.inc 2 if i mod idx == 0: return false idx.inc 4 result = true   const limit = 42 proc main = var i = 42 n = 0 while n < limit: if i.isPrime: inc n echo &"""n {n:>2} = {($i).insertSep(sep=','):>19}""" i.inc i continue inc i   main()  
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Perl
Perl
use ntheory qw(is_prime);   $i = 42; while ($n < 42) { if (is_prime($i)) { $n++; printf "%2d %21s\n", $n, commatize($i); $i += $i - 1; } $i++; }   sub commatize { (my $s = reverse shift) =~ s/(.{3})/$1,/g; $s =~ s/,$//; $s = reverse $s; }
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Comal
Comal
LOOP PRINT "SPAM" ENDLOOP
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#Common_Lisp
Common Lisp
(loop (write-line "SPAM"))
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#True_BASIC
True BASIC
  SUB process(x) LET sum = sum + ABS(x) IF ABS(prod) < (2 ^ 27) AND x <> 0 THEN LET prod = prod * x END SUB   LET prod = 1 LET sum = 0 LET x = 5 LET y = -5 LET z = -2 LET one = 1 LET three = 3 LET seven = 7   FOR j = -three TO (3 ^ 3) STEP three CALL process(j) NEXT j FOR j = -seven TO seven STEP x CALL process(j) NEXT j FOR j = 555 TO 550 - y CALL process(j) NEXT j FOR j = 22 TO -28 STEP -three CALL process(j) NEXT j FOR j = 1927 TO 1939 CALL process(j) NEXT j FOR j = x TO y STEP z CALL process(j) NEXT j FOR j = (11 ^ x) TO (11 ^ x) + one CALL process(j) NEXT j PRINT " sum= "; sum PRINT "prod= "; prod END  
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#D
D
import std.stdio;   void main() { int i = 1024;   while (i > 0) { writeln(i); i >>= 1; } }