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/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
#D
D
import std.stdio: writeln;   void main() { auto collection1 = "ABC"; foreach (element; collection1) writeln(element);   auto collection2 = [1, 2, 3]; foreach (element; collection1) writeln(element);   auto collection3 = [1:10, 2:20, 3:30]; foreach (element; collection3) writeln(element);   foreach (key, value; collection3) writeln(key, " ", value); }
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
#Bracmat
Bracmat
( luhn = sum odd even . 0:?sum & rev$!arg:?arg & whl ' ( @( !arg  :  %?odd ( %?even ?arg | :?arg&0:?even ) ) & !odd+mod$(2*!even.10)+div$(!even.5)+!sum:?sum ) & mod$(!sum.10):0 ) & ( test = . out $ (!arg ":" (luhn$!arg&true|false)) ) & test$49927398716 & test$49927398717 & test$1234567812345678 & test$1234567812345670 & ;
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).
#Fortran
Fortran
PROGRAM LUCAS_LEHMER IMPLICIT NONE   INTEGER, PARAMETER :: i64 = SELECTED_INT_KIND(18) INTEGER(i64) :: s, n INTEGER :: i, exponent   DO exponent = 2, 31 IF (exponent == 2) THEN s = 0 ELSE s = 4 END IF n = 2_i64**exponent - 1 DO i = 1, exponent-2 s = MOD(s*s - 2, n) END DO IF (s==0) WRITE(*,"(A,I0,A)") "M", exponent, " is PRIME" END DO   END PROGRAM LUCAS_LEHMER
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.
#Liberty_BASIC
Liberty BASIC
DIM LZW(1, 1) DIM JDlzw(1) DIM JDch$(1) LET maxBits = 20 ' maximum bit width of the dictionary: minimum=12; maximum=21 LET resetDictionary = 1 ' flag to reset the dictionary when it gets full: 1=TRUE; 0=FALSE LET printDictionary = 0 ' output encoding and decoding dictionaries to files LET maxChunkSize = 2 ^ 14 ' maximum size of the data buffer LET dSize = 2 ^ maxBits ' maximum dictionary size LET JDext$ = ".lzw" ' file extension used for created archives FILEDIALOG "Select a file to test LZW...", "*.*", inputName$ IF inputName$ = "" THEN END DO ' get fullPath\ and fileName.ext P = X X = INSTR(inputName$, "\", (X + 1)) LOOP UNTIL X = 0 filePath$ = LEFT$(inputName$, P) fileName$ = MID$(inputName$, (P + 1)) DO ' get fileName and .ext P = X X = INSTR(fileName$, ".", (X + 1)) LOOP UNTIL X = 0 fileExt$ = MID$(fileName$, P) fileName$ = LEFT$(fileName$, (P - 1))   GOSUB [lzwEncode] GOSUB [lzwDecode]   END   '''''''''''''''''''''''''''''''''''''''' ' Start LZW Encoder '''''''''''''''''''' [lzwEncode] REDIM LZW(dSize, 4) LET EMPTY=-1:PREFIX=0:BYTE=1:FIRST=2:LESS=3:MORE=4:bmxCorrect=1 LET bitsRemain=0:remainIndex=0:tagCount=0:currentBitSize=8:fileTag$="" FOR dNext = 0 TO 255 ' initialize dictionary for LZW ' LZW(dNext, PREFIX) = EMPTY ' prefix index of '<index>' <B> ' LZW(dNext, BYTE) = dNext ' byte value of <index> '<B>' LZW(dNext, FIRST) = EMPTY ' first index to use <index><B> as prefix ' LZW(dNext, LESS) = EMPTY ' lesser index of binary search tree for <B> ' LZW(dNext, MORE) = EMPTY ' greater index of binary search tree for <B> NEXT dNext OPEN inputName$ FOR INPUT AS #lzwIN IF LOF(#lzwIN) < 2 THEN CLOSE #lzwIN END END IF OPEN fileName$ + fileExt$ + JDext$ FOR OUTPUT AS #lzwOUT GOSUB [StartFileChunk] chnkPoint = 1 IF maxBits < 12 THEN maxBits = 12 IF maxBits > 21 THEN maxBits = 21 settings = maxBits - 12 ' setting for dictionary size; 1st decimal +12 IF resetDictionary THEN settings = settings + 100 ' setting for dictionary type; 2nd decimal even=static, odd=adaptive #lzwOUT, CHR$(settings); ' save settings as 1st byte of output orgIndex = ASC(LEFT$(fileChunk$, 1)) ' read 1st byte into <index> WHILE fileChunk$ <> "" ' while the buffer is not empty DO ' begin the main encoder loop chnkPoint = chnkPoint + 1 savIndex = FIRST ' initialize the save-to index prvIndex = orgIndex ' initialize the previous index in search newByte = ASC(MID$(fileChunk$, chnkPoint, 1)) ' read <B> dSearch = LZW(orgIndex, FIRST) ' first search index for this <index> in the dictionary WHILE (dSearch > EMPTY) ' while <index> is present in the dictionary IF LZW(dSearch, BYTE) = newByte THEN EXIT WHILE ' if <index><B> is found IF newByte < LZW(dSearch, BYTE) THEN ' else if new <B> is less than <index><B> savIndex = LESS ' follow lesser binary tree ELSE savIndex = MORE ' else follow greater binary tree END IF prvIndex = dSearch ' set previous <index> dSearch = LZW(dSearch, savIndex) ' read next search <index> from binary tree WEND IF dSearch = EMPTY THEN ' if <index><B> was not found in the dictionary GOSUB [WriteIndex] ' write <index> to the output IF dNext < dSize THEN ' save <index><B> into the dictionary LZW(prvIndex, savIndex) = dNext LZW(dNext, PREFIX) = orgIndex LZW(dNext, BYTE) = newByte LZW(dNext, FIRST) = EMPTY LZW(dNext, LESS) = EMPTY LZW(dNext, MORE) = EMPTY IF dNext = (2 ^ currentBitSize) THEN currentBitSize = currentBitSize + 1 dNext = dNext + 1 ELSE ' else reset the dictionary... or maybe not IF resetDictionary THEN GOSUB [PrintEncode] REDIM LZW(dSize, 4) FOR dNext = 0 TO 255 LZW(dNext, FIRST) = EMPTY NEXT dNext currentBitSize = 8 bmxCorrect = 0 END IF END IF orgIndex = newByte ' set <index> = <B> ELSE ' if <index><B> was found in the dictionary, orgIndex = dSearch ' then set <index> = <index><B> END IF LOOP WHILE chnkPoint < chunk ' loop until the chunk has been processed GOSUB [GetFileChunk] ' refill the buffer WEND ' loop until the buffer is empty GOSUB [WriteIndex] IF bitsRemain > 0 THEN #lzwOUT, CHR$(remainIndex); CLOSE #lzwOUT CLOSE #lzwIN IF bmxCorrect THEN ' correct the settings, if needed IF (currentBitSize < maxBits) OR resetDictionary THEN IF currentBitSize < 12 THEN currentBitSize = 12 OPEN fileName$ + fileExt$ + JDext$ FOR BINARY AS #lzwOUT #lzwOUT, CHR$(currentBitSize - 12); CLOSE #lzwOUT END IF END IF GOSUB [PrintEncode] REDIM LZW(1, 1) RETURN   [WriteIndex] X = orgIndex ' add remaining bits to input IF bitsRemain > 0 THEN X = remainIndex + (X * (2 ^ bitsRemain)) bitsRemain = bitsRemain + currentBitSize ' add current bit size to output stack WHILE bitsRemain > 7 ' if 8 or more bits are to be written #lzwOUT, CHR$(X MOD 256); ' attatch lower 8 bits to output string X = INT(X / 256) ' shift input value down by 2^8 bitsRemain = bitsRemain - 8 ' adjust counters WEND remainIndex = X ' retain trailing bits for next write RETURN   ' End LZW Encoder '''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''   [StartFileChunk] sizeOfFile = LOF(#lzwIN) ' set EOF marker bytesRemaining = sizeOfFile ' set EOF counter chunk = maxChunkSize ' set max buffer size [GetFileChunk] fileChunk$ = "" IF bytesRemaining < 1 THEN RETURN IF chunk > bytesRemaining THEN chunk = bytesRemaining bytesRemaining = bytesRemaining - chunk fileChunk$ = INPUT$(#lzwIN, chunk) chnkPoint = 0 RETURN   '''''''''''''''''''''''''''''''''''''''' ' Start LZW Decoder '''''''''''''''''''' [lzwDecode] LET EMPTY=-1:bitsRemain=0:tagCount=0:fileTag$="" OPEN fileName$ + fileExt$ + JDext$ FOR INPUT AS #lzwIN OPEN fileName$ + ".Copy" + fileExt$ FOR OUTPUT AS #lzwOUT GOSUB [StartFileChunk] chnkPoint = 2 settings = ASC(fileChunk$) maxBits = VAL(RIGHT$(STR$(settings), 1)) + 12 dSize = 2 ^ maxBits IF settings > 99 THEN resetDictionary = 1 GOSUB [ResetLZW] oldIndex = orgIndex WHILE fileChunk$ <> "" ' decode current index and write to file GOSUB [GetIndex] IF JDch$(orgIndex) = "" THEN tmpIndex = oldIndex tmp$ = JDch$(tmpIndex) WHILE JDlzw(tmpIndex) > EMPTY tmpIndex = JDlzw(tmpIndex) tmp$ = JDch$(tmpIndex) + tmp$ WEND tmp$ = tmp$ + LEFT$(tmp$, 1) ELSE tmpIndex = orgIndex tmp$ = JDch$(tmpIndex) WHILE JDlzw(tmpIndex) > EMPTY tmpIndex = JDlzw(tmpIndex) tmp$ = JDch$(tmpIndex) + tmp$ WEND END IF #lzwOUT, tmp$; ' add next dictionary entry or reset dictionary IF dNext < dSize THEN JDlzw(dNext) = oldIndex JDch$(dNext) = LEFT$(tmp$, 1) dNext = dNext + 1 IF dNext = (2 ^ currentBitSize) THEN IF maxBits > currentBitSize THEN currentBitSize = currentBitSize + 1 ELSE IF resetDictionary THEN GOSUB [PrintDecode] GOSUB [ResetLZW] END IF END IF END IF END IF oldIndex = orgIndex WEND CLOSE #lzwOUT CLOSE #lzwIN GOSUB [PrintDecode] REDIM JDlzw(1) REDIM JDch$(1) RETURN   [GetIndex] byteCount = 0:orgIndex = 0 bitsToGrab = currentBitSize - bitsRemain IF bitsRemain > 0 THEN orgIndex = lastByte byteCount = 1 END IF WHILE bitsToGrab > 0 lastByte = ASC(MID$(fileChunk$, chnkPoint, 1)) orgIndex = orgIndex + (lastByte * (2 ^ (byteCount * 8))) IF chnkPoint = chunk THEN GOSUB [GetFileChunk] chnkPoint = chnkPoint + 1 byteCount = byteCount + 1 bitsToGrab = bitsToGrab - 8 WEND IF bitsRemain > 0 THEN orgIndex = orgIndex / (2 ^ (8 - bitsRemain)) orgIndex = orgIndex AND ((2 ^ currentBitSize) - 1) bitsRemain = bitsToGrab * (-1) RETURN   [ResetLZW] REDIM JDlzw(dSize) REDIM JDch$(dSize) FOR dNext = 0 TO 255 JDlzw(dNext) = EMPTY ' Prefix index JDch$(dNext) = CHR$(dNext) ' New byte value NEXT dNext currentBitSize = 8 GOSUB [GetIndex] #lzwOUT, JDch$(orgIndex); currentBitSize = 9 RETURN   ' End LZW Decoder '''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''   '''''''''''''''''''''''''''''''''''''''' [PrintEncode] IF printDictionary < 1 THEN RETURN OPEN "Encode_" + fileTag$ + fileName$ + ".txt" FOR OUTPUT AS #dictOUT FOR X = 0 TO 255 LZW(X, PREFIX) = EMPTY LZW(X, BYTE) = X NEXT X FOR X = dNext TO 0 STEP -1 tmpIndex = X tmp$ = CHR$(LZW(tmpIndex, BYTE)) WHILE LZW(tmpIndex, PREFIX) > EMPTY tmpIndex = LZW(tmpIndex, PREFIX) tmp$ = CHR$(LZW(tmpIndex, BYTE)) + tmp$ WEND #dictOUT, X; ":"; tmp$ NEXT X CLOSE #dictOUT tagCount = tagCount + 1 fileTag$ = STR$(tagCount) + "_" RETURN   [PrintDecode] IF printDictionary < 1 THEN RETURN OPEN "Decode_" + fileTag$ + fileName$ + ".txt" FOR OUTPUT AS #dictOUT FOR X = dNext TO 0 STEP -1 tmpIndex = X tmp$ = JDch$(tmpIndex) WHILE JDlzw(tmpIndex) > EMPTY tmpIndex = JDlzw(tmpIndex) tmp$ = JDch$(tmpIndex) + tmp$ WEND #dictOUT, X; ":"; tmp$ NEXT X CLOSE #dictOUT tagCount = tagCount + 1 fileTag$ = STR$(tagCount) + "_" RETURN ''''''''''''''''''''''''''''''''''''''''
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
#PL.2FI
PL/I
(subscriptrange, fofl, size): /* 2 Nov. 2013 */ LU_Decomposition: procedure options (main); declare a1(3,3) float (18) initial ( 1, 3, 5, 2, 4, 7, 1, 1, 0); declare a2(4,4) float (18) initial (11, 9, 24, 2, 1, 5, 2, 6, 3, 17, 18, 1, 2, 5, 7, 1); call check(a1); call check(a2);     /* In-situ decomposition */ LU: procedure(a, p); declare a(*,*) float (18); declare p(*) fixed binary; declare (maximum, rtemp) float (18); declare (n, i, j, k, ii, temp) fixed binary;   n = hbound(a,1); do i = 1 to n; p(i) = i; end;   do k = 1 to n-1;   maximum = 0; ii = k; do i = k to n; if maximum < abs(a(p(i),k)) then do; maximum = abs(a(p(i),k)); ii = i; end; end; if ii ^= k then do; temp = p(k); p(k) = p(ii); p(ii) = temp; end;   do i = k+1 to n; a(p(i),k) = a(p(i),k) / a(p(k),k); end;   do j = k+1 to n; do i = k+1 to n; a(p(i),j) = a(p(i),j) - a(p(i),k) * a(p(k),j); end; end;   end; end LU;   CHECK: procedure(a); declare a(*,*) float (18) nonassignable;   declare aa(hbound(a,1), hbound(a,2)) float (18); declare L(hbound(a,1), hbound(a,2)) float (18); declare U(hbound(a,1), hbound(a,2)) float (18); declare (p(hbound(a,1), hbound(a,2)), ipiv(hbound(a,1)) ) fixed binary; declare pp(hbound(a,1), hbound(a,2)) fixed binary; declare (i, j, n, temp(hbound(a,1))) fixed binary;   n = hbound(a,1); aa = A; /* work with a copy */ P = 0; L = 0; U = 0; do i = 1 to n; p(i,i) = 1; L(i,i) = 1; /* convert permutation vector to a matrix */ end;   call LU(aa, ipiv);   do i = 1 to n; do j = 1 to i-1; L(i,j) = aa(ipiv(i),j); end; do j = i to n; U(i,j) = aa(ipiv(i),j); end; end;   pp = p; do i = 1 to n; p(ipiv(i), *) = pp(i,*); end;   put skip list ('A'); put edit (A) (skip, (n) f(10,5));   put skip list ('P'); put edit (P) (skip, (n) f(11));   put skip list ('L'); put edit (L) (skip, (n) f(10,5));   put skip list ('U'); put edit (U) (skip, (n) f(10,5));   end CHECK;   end LU_Decomposition;  
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.
#Sidef
Sidef
var ( lychrels = [], palindromes = [], seeds = [], max = 500, )   for i in (1 .. 10_000) { var (test = [], count = 0)   func lychrel(l) { count++ > max && return true test << (var m = (l + Num(Str(l).flip))) Str(m).is_palindrome && return false lychrel(m) }   if (lychrel(i)) { lychrels << Pair(Str(i), test) } }   seeds << lychrels[0]   for l in lychrels { if (l.key.is_palindrome) { palindromes << l.key }   var h = Hash() h.set_keys(l.value...)   var trial = seeds.count_by { |s| s.value.any { |k| h.contains(k) } ? break : true }   if (trial == seeds.len) { seeds << l } }   say (" Number of Lychrel seed numbers < 10_000: ", seeds.len) say (" Lychrel seed numbers < 10_000: ", seeds.map{.key}.join(', ')) say ("Number of Lychrel related numbers < 10_000: ", lychrels.len - seeds.len) say (" Number of Lychrel palindromes < 10_000: ", palindromes.len) say (" Lychrel palindromes < 10_000: ", palindromes.join(', '))
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
#PowerShell
PowerShell
  function New-MadLibs { [CmdletBinding(DefaultParameterSetName='None')] [OutputType([string])] Param ( [Parameter(Mandatory=$false)] [AllowEmptyString()] [string] $Name = "",   [Parameter(Mandatory=$false, ParameterSetName='Male')] [switch] $Male,   [Parameter(Mandatory=$false, ParameterSetName='Female')] [switch] $Female,   [Parameter(Mandatory=$false)] [AllowEmptyString()] [string] $Item = "" )   if (-not $Name) { $Name = (Get-Culture).TextInfo.ToTitleCase((Read-Host -Prompt "`nEnter a name").ToLower()) } else { $Name = (Get-Culture).TextInfo.ToTitleCase(($Name).ToLower()) }   if ($Male) { $pronoun = "He" } elseif ($Female) { $pronoun = "She" } else { $title = "Gender" $message = "Select $Name's Gender" $_male = New-Object System.Management.Automation.Host.ChoiceDescription "&Male", "Selects male gender." $_female = New-Object System.Management.Automation.Host.ChoiceDescription "&Female", "Selects female gender." $options = [System.Management.Automation.Host.ChoiceDescription[]]($_male, $_female) $result = $host.UI.PromptForChoice($title, $message, $options, 0)   switch ($result) { 0 {$pronoun = "He"} 1 {$pronoun = "She"} } }   if (-not $Item) { $Item = Read-Host -Prompt "`nEnter an item" }   "`n{0} went for a walk in the park. {1} found a {2}. {0} decided to take it home.`n" -f $Name, $pronoun, $Item }  
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
#Haxe
Haxe
using StringTools; import haxe.Int64;   class PrimeNumberLoops { private static var limit = 42;   static function isPrime(i:Int64):Bool { if (i == 2 || i == 3) { return true; } else if (i % 2 == 0 || i % 3 ==0) { return false; } var idx:haxe.Int64 = 5; while (idx * idx <= i) { if (i % idx == 0) return false; idx += 2; if (i % idx == 0) return false; idx += 4; } return true; }   static function main() { var i:Int64 = 42; var n:Int64 = 0; while (n < limit) { if (isPrime(i)) { n++; Sys.println('n ${Int64.toStr(n).lpad(' ', 2)} ' + '= ${Int64.toStr(i).lpad(' ', 19)}'); i += i; continue; } 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
#J
J
  tacit_loop =: _1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x:  
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
#Befunge
Befunge
55+"MAPS",,,,,
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
#blz
blz
while true print("SPAM") end
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
#Phix
Phix
integer prod = 1, total = 0, -- (renamed as sum is a Phix builtin) x = +5, y = -5, z = -2, one = 1, three = 3, seven = 7 sequence loopset = {{ -three, power(3,3), three }, { -seven, +seven, x }, { 555, 550 - y, 1 }, { 22, -28, -three}, { 1927, 1939, 1 }, { x, y, z }, {power(11,x), power(11,x) + one, 1 }} for i=1 to length(loopset) do integer {f,t,s} = loopset[i] for j=f to t by s do total += abs(j) if abs(prod)<power(2,27) and j!=0 then prod *= j end if end for end for printf(1," sum = %,d\n",total) printf(1,"prod = %,d\n",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
#C
C
int i = 1024; while(i > 0) { printf("%d\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
#C.23
C#
int i = 1024; while(i > 0){ System.Console.WriteLine(i); 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
#Arturo
Arturo
loop 10..0 'i [ print i ]
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
#Asymptote
Asymptote
for(int i = 10; i >=0; --i) { write(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.
#ALGOL_60
ALGOL 60
'BEGIN' 'COMMENT' Loops DoWhile - Algol60 - 22/06/2018; 'INTEGER' I; I:=0; LOOP: I:=I+1; OUTINTEGER(1,I); 'IF' I=I'/'6*6 'THEN' 'GOTO' ENDLOOP; 'GOTO' LOOP; ENDLOOP: 'END'
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.
#ALGOL_W
ALGOL W
begin for i := 1 until 5 do begin write( "*" ); for j := 2 until i do begin writeon( "*" ) end j end i end.
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
#Arturo
Arturo
loop 0..10 .step:2 'i [ print 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.
#Prolog
Prolog
  % John Devou: 26-Nov-2021   d(_,_,[],[]). d(N,N,[_|Xs],Rs):- d(N,1,Xs,Rs). d(N,M,[X|Xs],[X|Rs]):- M < N, M_ is M+1, d(N,M_,Xs,Rs).   l([],[]). l([X|Xs],[X|Rs]):- d(X,1,Xs,Ys), l(Ys,Rs).   % g(N,L):- generate in L a list with Ludic numbers up to N   g(N,[1|X]):- numlist(2,N,L), l(L,X).   s(0,Xs,[],Xs). s(N,[X|Xs],[X|Ls],Rs):- N > 0, M is N-1, s(M,Xs,Ls,Rs).   t([X,Y,Z|_],[X,Y,Z]):- Y =:= X+2, Z =:= X+6. t([_,Y,Z|Xs],R):- t([Y,Z|Xs],R).   % tasks   t1:- g(500,L), s(25,L,X,_), write(X), !. t2:- g(1000,L), length(L,X), write(X), !. t3:- g(22000,L), s(1999,L,_,R), s(6,R,X,_), write(X), !. t4:- g(249,L), findall(A, t(L,A), X), write(X), !.  
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
#CoffeeScript
CoffeeScript
  # Loop plus half. This code shows how to break out of a loop early # on the last iteration. For the contrived example, there are better # ways to generate a comma-separated list, of course. start = 1 end = 10 s = '' for i in [start..end] # the top half of the loop executes every time s += i break if i == end # the bottom half of the loop is skipped for the last value s += ', ' console.log 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
#ColdFusion
ColdFusion
<cfloop index = "i" from = "1" to = "10"> #i# <cfif i EQ 10> <cfbreak /> </cfif> , </cfloop>
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
#Clojure
Clojure
(ns nested)   (defn create-matrix [width height] (for [_ (range width)] (for [_ (range height)] (inc (rand-int 20)))))   (defn print-matrix [matrix] (loop [[row & rs] matrix] (when (= (loop [[x & xs] row] (println x) (cond (= x 20) :stop xs (recur xs)  :else :continue))  :continue) (when rs (recur rs)))))   (print-matrix (create-matrix 10 10))
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
#Dao
Dao
items = { 1, 2, 3 } for( item in items ) io.writeln( item )
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
#Delphi
Delphi
program LoopForEach;   {$APPTYPE CONSOLE}   var s: string; begin for s in 'Hello' do Writeln(s); end.
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
#Brainf.2A.2A.2A
Brainf***
>>>>>>>>>+>,----------[ READ CHARACTERS UNTIL \N AND >++++++++[<----->-]<++>>>>>>+>,----------] SUBTRACT ASCII 0 FROM EACH <-<<<<<<< GO TO LAST DIGIT [ WHILE THERE ARE DIGITS >>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<< ADD RUNNING TOTAL TO ODD DGT <<<<<<< GO TO EVEN DIGIT [ IF THERE IS ONE >[->++<]>[-<+>] MUL BY TWO >>>++++++++++<<<<[ DIVMOD BY TEN >>>[-]+>-[<-<]<[<<] DECR DIVISOR >>[ IF ZERO >++++++++++>+<<-]<<< SET TO TEN; INCR QUOTIENT -] DECR DIVIDEND UNTIL ZERO ++++++++++>>>>[-<<<<->>>>] CALCULATE REMAINDER >[-<<<<<+>>>>>] ADD QUOTIENT TO IT >>[-<<<<<<<+>>>>>>>]<<<<<<<< THEN ADD RUNNING TOTAL <<<<< ZERO BEFORE NEXT ODD DIGIT ]<< GO TO NEXT ODD DIGIT ] >>>>>>>-[+>>-]> GO TO TOTAL >>>>++++++++++<<<<[ MODULO TEN >>>[-]+>-[<-<]<[<<] DECR DIVISOR >>[>++++++++++<-] IF ZERO SET BACK TO TEN <<<-] DECR DIVIDEND UNTIL ZERO >>>++++++++++>[-<->]< REMAINDER: TEN MINUS DIVISOR <<<<<<++++++++++[-> VALUES FOR ASCII OUTPUT +++++++++++> 110 ++++++++++> 100 ++++++++> 80 +++++++<<<<] 70 >>>>>+> GO BACK TO REMAINDER [<<.<<---.<-----.+++.<] IF NOT ZERO FAIL <[<<.<---.<+++++..<] IF ZERO PASS ++++++++++. NEWLINE  
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).
#FreeBASIC
FreeBASIC
' version 18-09-2015 ' compile with: fbc -s console   #Ifndef TRUE ' define true and false for older freebasic versions #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt ' returns a * b mod modulus   Dim As ULongInt x , y = a ' a mod modulus, but a is already smaller then modulus   While b > 0 If (b And 1) = 1 Then x = (x + y) Mod modulus End If y = (y Shl 1) Mod modulus b = b Shr 1 Wend Return x   End Function   Function LLT(p As UInteger) As Integer   Dim As ULongInt s = 4, m = 1 m = m Shl p : m = m - 1 ' m = 2 ^ p - 1   For i As Integer = 2 To p - 1 s = mul_mod(s, s, m) - 2 Next   If s = 0 Then Return TRUE Else Return FALSE   End Function   ' ------=< MAIN >=------   Dim As UInteger p   Print ' M2 can not be tested, we start with 3 for p = 3 To 63 If LLT(p) = TRUE Then Print " M";Str(p); Next   Print ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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.
#Lua
Lua
local function compress(uncompressed) -- string local dictionary, result, dictSize, w, c = {}, {}, 255, "" for i = 0, 255 do dictionary[string.char(i)] = i end for i = 1, #uncompressed do c = string.sub(uncompressed, i, i) if dictionary[w .. c] then w = w .. c else table.insert(result, dictionary[w]) dictSize = dictSize + 1 dictionary[w .. c] = dictSize w = c end end if w ~= "" then table.insert(result, dictionary[w]) end return result end   local function decompress(compressed) -- table local dictionary, dictSize, entry, w, k = {}, 256, "", string.char(compressed[1]) local result = {w} for i = 0, 255 do dictionary[i] = string.char(i) end for i = 2, #compressed do k = compressed[i] if dictionary[k] then entry = dictionary[k] elseif k == dictSize then entry = w .. string.sub(w, 1, 1) else return nil, i end table.insert(result, entry) dictionary[dictSize] = w .. string.sub(entry, 1, 1) dictSize = dictSize + 1 w = entry end return table.concat(result) end   local example = "TOBEORNOTTOBEORTOBEORNOT" local com = compress(example) local dec = decompress(com) print(table.concat(com, ", ")) print(dec)
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
#Python
Python
from pprint import pprint   def matrixMul(A, B): TB = zip(*B) return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]   def pivotize(m): """Creates the pivoting matrix for m.""" n = len(m) ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)] for j in xrange(n): row = max(xrange(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID   def lu(A): """Decomposes a nxn matrix A by PA=LU and returns L, U and P.""" n = len(A) L = [[0.0] * n for i in xrange(n)] U = [[0.0] * n for i in xrange(n)] P = pivotize(A) A2 = matrixMul(P, A) for j in xrange(n): L[j][j] = 1.0 for i in xrange(j+1): s1 = sum(U[k][j] * L[i][k] for k in xrange(i)) U[i][j] = A2[i][j] - s1 for i in xrange(j, n): s2 = sum(U[k][j] * L[i][k] for k in xrange(j)) L[i][j] = (A2[i][j] - s2) / U[j][j] return (L, U, P)   a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]] for part in lu(a): pprint(part, width=19) print print b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]] for part in lu(b): pprint(part) print
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.
#Swift
Swift
import BigInt   public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol { @usableFromInline let seed: T   @usableFromInline var done = false   @usableFromInline var n: T   @usableFromInline var iterations: T   @inlinable public init(seed: T, iterations: T = 500) { self.seed = seed self.n = seed self.iterations = iterations }   @inlinable public mutating func next() -> T? { guard !done && iterations != 0 else { return nil }   guard !isPalindrome(n) || n == seed else { done = true   return n }   defer { n += n.reversed() iterations -= 1 }   return n } }   @inlinable public func isPalindrome<T: CustomStringConvertible>(_ x: T) -> Bool { let asString = String(describing: x)   for (c, c1) in zip(asString, asString.reversed()) where c != c1 { return false }   return true }   public protocol ReversibleNumeric: Numeric { func reversed() -> Self }   extension BigInt: ReversibleNumeric { public func reversed() -> BigInt { return BigInt(String(description.reversed()))! } }   typealias LychrelReduce = (seen: Set<BigInt>, seeds: Set<BigInt>, related: Set<BigInt>)   let (seen, seeds, related): LychrelReduce = (1...10_000) .map({ BigInt($0) }) .reduce(into: LychrelReduce(seen: Set(), seeds: Set(), related: Set()), {res, cur in guard !res.seen.contains(cur) else { res.related.insert(cur)   return }   var seen = false   let seq = Lychrel(seed: cur).prefix(while: { seen = res.seen.contains($0); return !seen }) let last = seq.last!   guard !isPalindrome(last) || seen else { return }   res.seen.formUnion(seq)   if seq.count == 500 { res.seeds.insert(cur) } else { res.related.insert(cur) } })   print("Found \(seeds.count + related.count) Lychrel numbers between 1...10_000 when limited to 500 iterations") print("Number of Lychrel seeds found: \(seeds.count)") print("Lychrel seeds found: \(seeds.sorted())") print("Number of related Lychrel nums found: \(related.count)") print("Lychrel palindromes found: \(seeds.union(related).filter(isPalindrome).sorted())")
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
#PureBasic
PureBasic
  If OpenConsole()   cadena$ = "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home." k = FindString(cadena$, "<")   PrintN("La historia: ") Print(cadena$ + Chr(10)) While k reemplaza$ = Mid(cadena$, k, FindString(cadena$, ">") - k + 1) Print(Chr(10) + "What should replace " + reemplaza$ + " ") con$ = Input () While k cadena$ = Left(cadena$, k-1) + con$ + Mid(cadena$, k + Len(reemplaza$)) k = FindString(cadena$, reemplaza$, k) Wend k = FindString(cadena$, "<") Wend PrintN(Chr(10) + "La historia final: ") PrintN(cadena$) Input() CloseConsole() EndIf 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
#Java
Java
public class LoopIncrementWithinBody {   static final int LIMIT = 42;   static boolean isPrime(long n) { if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; long d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; }   public static void main(String[] args) { long i; int n; for (i = LIMIT, n = 0; n < LIMIT; i++) if (isPrime(i)) { n++; System.out.printf("n = %-2d  %,19d\n", n, i); i += i - 1; } } }
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
#bootBASIC
bootBASIC
10 print "SPAM" 20 goto 10
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
#BQN
BQN
{𝕊 •Out 𝕩}"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
#Picat
Picat
foreach(I in 1..3, J in 4..6, K in 7..9)  % ... end
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
#Prolog
Prolog
for(Lo,Hi,Step,Lo) :- Step>0, Lo=<Hi. for(Lo,Hi,Step,Val) :- Step>0, plus(Lo,Step,V), V=<Hi, !, for(V,Hi,Step,Val). for(Hi,Lo,Step,Hi) :- Step<0, Lo=<Hi. for(Hi,Lo,Step,Val) :- Step<0, plus(Hi,Step,V), Lo=<V, !, for(V,Lo,Step,Val).   sym(x,5). % symbolic lookups for values sym(y,-5). sym(z,-2). sym(one,1). sym(three,3). sym(seven,7).   range(-three,3^3,three). % as close as we can syntactically get range(-seven,seven,x). range(555,550-y,1). range(22,-28, -three). range(1927,1939,1). range(x,y,z). range(11^x,11^x+one,1).   translate(V, V) :- number(V), !. % difference list based parser translate(S, V) :- sym(S,V), !. translate(-S, V) :- translate(S,V0), !, V is -V0. translate(A+B, V) :- translate(A,A0), translate(B, B0), !, V is A0+B0. translate(A-B, V) :- translate(A,A0), translate(B, B0), !, V is A0-B0. translate(A^B, V) :- translate(A,A0), translate(B, B0), !, V is A0^B0.   range_value(Val) :- % enumerate values for all ranges in order range(From,To,Step), translate(From,F), translate(To,T), translate(Step,S), for(F,T,S,Val).   calc_values([], S, P, S, P). % calculate all values in generated order calc_values([J|Js], S, P, Sum, Product) :- S0 is S + abs(J), ((abs(P)< 2^27, J \= 0) -> P0 is P * J; P0=P), !, calc_values(Js, S0, P0, Sum, Product).   calc_values(Sum, Product) :- % Find the sum and product findall(V, range_value(V), Values), calc_values(Values, 0, 1, Sum, Product).
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
#C.2B.2B
C++
int i = 1024; while(i > 0){ std::cout << i << std::endl; 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
#Cach.C3.A9_ObjectScript
Caché ObjectScript
WHILELOOP set x = 1024 while (x > 0) { write x,! set x = (x \ 2)  ; using non-integer division will never get to 0 }   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
#AutoHotkey
AutoHotkey
x := 10 While (x >= 0) { output .= "`n" . x x-- } MsgBox % output  
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
#Avail
Avail
For each i from 10 to 0 by -1 do [Print: “i” ++ "\n";];
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.
#ALGOL_68
ALGOL 68
FOR value WHILE print(value); # WHILE # value MOD 6 /= 0 DO SKIP OD
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.
#ALGOL-M
ALGOL-M
BEGIN INTEGER I, J; FOR I := 1 STEP 1 UNTIL 5 DO BEGIN WRITE( "" ); FOR J := 1 STEP 1 UNTIL I DO WRITEON( "*" ); END; END
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
#AutoHotkey
AutoHotkey
SetBatchLines, -1 iterations := 5 step := 10 iterations *= step Loop,  % iterations { If Mod(A_Index, step) Continue MsgBox, % A_Index } ExitApp
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.
#PureBasic
PureBasic
EnableExplicit If Not OpenConsole() : End 1 : EndIf   #NMAX=25000   Dim ludic.b(#NMAX) FillMemory(@ludic(0),SizeOf(Byte)*#NMAX,#True,#PB_Byte)   Define.i i,j,n,c1,c2 Define r1$,r2$,r3$,r4$   For i=2 To Int(#NMAX/2) If ludic(i) n=0 For j=i+1 To #NMAX If ludic(j) : n+1 : EndIf If n=i : ludic(j)=#False : n=0 : EndIf Next j EndIf Next i   n=0 : c1=0 : c2=0 For i=1 To #NMAX If ludic(i) And n<25 : n+1 : r1$+Str(i)+" " : EndIf If i<=1000 : c1+Bool(ludic(i)) : EndIf c2+Bool(ludic(i)) If c2>=2000 And c2<=2005 And ludic(i) : r3$+Str(i)+" " : EndIf If i<243 And ludic(i) And ludic(i+2) And ludic(i+6) r4$+"["+Str(i)+" "+Str(i+2)+" "+Str(i+6)+"] " EndIf Next r2$=Str(c1)   PrintN("First 25 Ludic numbers: " +r1$) PrintN("Ludic numbers below 1000: " +r2$) PrintN("Ludic numbers 2000 to 2005: " +r3$) PrintN("Ludic Triplets below 250: " +r4$) Input() 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
#Common_Lisp
Common Lisp
  (loop for i from 1 below 10 do (princ i) (princ ", ") finally (princ i))  
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
#Cowgol
Cowgol
include "cowgol.coh";   var i: uint8 := 1; loop print_i8(i); if i == 10 then break; end if; print(", "); i := i + 1; end loop; print_nl();
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Nested-Loop.   DATA DIVISION. LOCAL-STORAGE SECTION. 78 Table-Size VALUE 10. 01 Table-Area. 03 Table-Row OCCURS Table-Size TIMES INDEXED BY Row-Index. 05 Table-Element PIC 99 OCCURS Table-Size TIMES INDEXED BY Col-Index.   01 Current-Time PIC 9(8). PROCEDURE DIVISION. * *> Seed RANDOM. ACCEPT Current-Time FROM TIME MOVE FUNCTION RANDOM(Current-Time) TO Current-Time   * *> Put random numbers in the table. * *> The AFTER clause is equivalent to a nested PERFORM VARYING * *> statement. PERFORM VARYING Row-Index FROM 1 BY 1 UNTIL Table-Size < Row-Index AFTER Col-Index FROM 1 BY 1 UNTIL Table-Size < Col-Index COMPUTE Table-Element (Row-Index, Col-Index) = FUNCTION MOD((FUNCTION RANDOM * 1000), 20) + 1 END-PERFORM   * *> Search through table for 20. * *> Using proper nested loops. PERFORM VARYING Row-Index FROM 1 BY 1 UNTIL Table-Size < Row-Index PERFORM VARYING Col-Index FROM 1 BY 1 UNTIL Table-Size < Col-Index IF Table-Element (Row-Index, Col-Index) = 20 EXIT PERFORM ELSE DISPLAY Table-Element (Row-Index, Col-Index) END-IF END-PERFORM END-PERFORM   GOBACK .
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
#Dragon
Dragon
  for value : array { showln value }  
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
#Dyalect
Dyalect
for i in [1,2,3] { print(i) }
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
#Burlesque
Burlesque
  tt "Remove whitespace"vv pe "Eval to number"vv <- "Reverse digits"vv XX "Split number into digits"vv   { { "Odd digits"vv 2EN }   { "Even digits"vv 2en { 2.* "Double"vv ^^ 9.> "<test>=Duplicate greater than 9"vv { XX++ "Sum digits"vv }if "If <test>"vv }m[ "For each even digit"vv } }M- "Cool map. Create array of each branch applied to argument."vv   {++}m[ "Sum each block (odd & even)"vv ++ "Sum these"vv [- "Last digit"vv 0== "Equal to zero"vv Q "Pretty print"vv  
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).
#Frink
Frink
  for n = primes[] if isPrime[2^n-1] println[n]  
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.
#M2000_Interpreter
M2000 Interpreter
  Module BBCtrans { \\ LZW compression plaintext$="TOBEORNOTTOBEORTOBEORNOT" Function encodeLZW$(i$) { Def long c, d, i, l, o$, w$ DIM dict$(0 to 4095) FOR i = 0 TO 255 : dict$(i) = CHR$(i) : NEXT i l = i i = 1 w$ = LEFT$(i$,1) REPEAT{ d = 0 REPEAT { c = d IF i > LEN(i$) THEN EXIT FOR d = 1 TO l-1 IF w$ = dict$(d) THEN EXIT NEXT d IF d < l Then i += 1 : w$ += MID$(i$, i, 1) } UNTIL d >= l dict$(l) = w$ : l += 1 : w$ = RIGHT$(w$, 1) o$ += CHR$(c MOD 256) + CHR$(c DIV 256) } UNTIL i > LEN(i$) = o$ } encodeLZW$ = encodeLZW$(plaintext$) FOR i = 1 TO LEN(encodeLZW$) STEP 2 PRINT ASC(MID$(encodeLZW$,i)) + 256*ASC(MID$(encodeLZW$,i+1));" "; NEXT i Print Function decodeLZW$(i$) { Def c, i, l, o$, t$, w$ DIM dict$(0 to 4095) FOR i = 0 TO 255 : dict$(i) = CHR$(i) : NEXT i l = i c = ASC(i$) + 256*ASC(MID$(i$,2)) w$ = dict$(c) o$ = w$ IF LEN(i$) < 4 THEN = o$ FOR i = 3 TO LEN(i$) STEP 2 c = ASC(MID$(i$,i)) + 256*ASC(MID$(i$,i+1)) IF c < l Then { t$ = dict$(c) } ELSE t$ = w$ + LEFT$(w$,1) o$ += t$ dict$(l) = w$ + LEFT$(t$,1) l += 1 w$ = t$ NEXT i = o$ } Print decodeLZW$(encodeLZW$) } BBCtrans  
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
#R
R
library(Matrix) A <- matrix(c(1, 3, 5, 2, 4, 7, 1, 1, 0), 3, 3, byrow=T) dim(A) <- c(3, 3) expand(lu(A))
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.
#Tcl
Tcl
proc pal? {n} { expr {$n eq [string reverse $n]} }   proc step {n} { set n_ [string reverse $n] set n_ [string trimleft $n_ 0] expr {$n + $n_} }   proc lychrels {{max 10000} {iters 500}} {   set lychrels {} ;# true Lychrels set visited {} ;# visited numbers for Related test set nRelated 0 ;# count of related numbers seen set pals {} ;# palindromic Lychrels and related   puts "Searching for Lychrel numbers in \[1,$max\]" puts "With a maximum of $iters iterations"   for {set i 1} {$i <= $max} {incr i} { set n $i ;# seed the sequence set seq {} ;# but don't check the seed, nor remember it for the Related test for {set j 0} {$j < $iters} {incr j} { set n [step $n] dict set seq $n {} if {[dict exists $visited $n]} { incr nRelated if {[pal? $i]} { lappend pals $i } break ;# bail out if it's Related } if {[pal? $n]} { break ;# bail out if it's a palindrome } } if {$j >= $iters} { ;# the loop was exhausted: must be a Lychrel! if {[pal? $i]} { lappend pals $i } lappend lychrels $i set visited [dict merge $visited $seq] } }   puts "[llength $lychrels] Lychrel numbers found:" puts $lychrels puts "Count of related numbers: $nRelated" puts "Palindromic Lychrel and related numbers: $pals" }   lychrels
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
#Python
Python
import re   # Optional Python 2.x compatibility #try: input = raw_input #except: pass   template = '''<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.'''   def madlibs(template): print('The story template is:\n' + template) fields = sorted(set( re.findall('<[^>]+>', template) )) values = input('\nInput a comma-separated list of words to replace the following items' '\n  %s: ' % ','.join(fields)).split(',') story = template for f,v in zip(fields, values): story = story.replace(f, v) print('\nThe story becomes:\n\n' + story)   madlibs(template)
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
#jq
jq
{i:42, count:0} | while( .count <= 42; .emit = null | .i += 1 | if .i|is_prime then .count += 1 | .emit = "count at \(.i) is \(.count)" | .i = .i + .i - 1 else . end ) | select(.emit).emit
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
#Julia
Julia
using Primes, Formatting   function doublemyindex(n=42) shown = 0 i = BigInt(n) while shown < n if isprime(i + 1) shown += 1 println("The index is ", format(shown, commas=true), " and ", format(i + 1, commas=true), " is prime.") i += i end i += 1 end end   doublemyindex()  
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
#Bracmat
Bracmat
whl'out$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
#Brainf.2A.2A.2A
Brainf***
++++++++++[->++++++>++++++++>+<<<]>+++++> [+++.---.<.>---.+++>.<]
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
#PureBasic
PureBasic
#X = 5 : #Y = -5 : #Z = -2 #ONE = 1 : #THREE = 3 : #SEVEN = 7 Define j.i Global prod.i = 1, sum.i = 0   Macro ipow(n, e) Int(Pow(n, e)) EndMacro   Macro ifn(x) FormatNumber(x,0,".",",") EndMacro   Macro loop_for(start, stop, step_for=1) For j = start To stop Step step_for proc(j) Next EndMacro   Procedure proc(j.i) sum + Abs(j) If (Abs(prod) < ipow(2 , 27)) And (j<>0) prod * j EndIf EndProcedure   loop_for(-#THREE, ipow(3, 3), #THREE) loop_for(-#SEVEN, #SEVEN, #X) loop_for(555, 550 - #Y) loop_for(22, -28, -#THREE) loop_for(1927, 1939) loop_for(#X, #Y, #Z) loop_for(ipow(11, #X), ipow(11, #X) + 1)   If OpenConsole("Loops/with multiple ranges") PrintN("sum = " + ifn(sum)) PrintN("prod = " + ifn(prod)) Input() EndIf
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
#Chapel
Chapel
var val = 1024; while val > 0 { writeln(val); val /= 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
#ChucK
ChucK
  1024 => int value;   while(value > 0) { <<<value>>>; value / 2 => value; }  
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
#AWK
AWK
BEGIN { for(i=10; i>=0; i--) { print i } }
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
#Axe
Axe
For(I,0,10) Disp 10-I▶Dec,i End
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.
#ALGOL_W
ALGOL W
begin integer i; i := 0; while begin i := i + 1; write( i ); ( i rem 6 ) not = 0 end do begin end end.
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.
#Alore
Alore
for i in 0 to 6 for j in 0 to i Write('*') end WriteLn() end  
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
#Avail
Avail
For each i from 0 to 100 by 7 do [Print: “i” ++ " is a multiple of 7!\n";];
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.
#Python
Python
def ludic(nmax=100000): yield 1 lst = list(range(2, nmax + 1)) while lst: yield lst[0] del lst[::lst[0]]   ludics = [l for l in ludic()]   print('First 25 ludic primes:') print(ludics[:25]) print("\nThere are %i ludic numbers <= 1000"  % sum(1 for l in ludics if l <= 1000)) print("\n2000'th..2005'th ludic primes:") print(ludics[2000-1: 2005])   n = 250 triplets = [(x, x+2, x+6) for x in ludics if x+6 < n and x+2 in ludics and x+6 in ludics] print('\nThere are %i triplets less than %i:\n  %r'  % (len(triplets), n, triplets))
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
#D
D
import std.stdio;   void main() { for (int i = 1; ; i++) { write(i); if (i >= 10) break; write(", "); }   writeln(); }
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
#Dart
Dart
String loopPlusHalf(start, end) { var result = ''; for(int i = start; i <= end; i++) { result += '$i'; if(i == end) { break; } result += ', '; } return result; }   void main() { print(loopPlusHalf(1, 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
#ColdFusion
ColdFusion
  <Cfset RandNum = 0> <Cfloop condition="randNum neq 20"> <Cfloop from="1" to="5" index="i"> <Cfset randNum = RandRange(1, 20)> <Cfoutput>#randNum# </Cfoutput> <Cfif RandNum eq 20><cfbreak></Cfif> </Cfloop> <br> </Cfloop>  
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
#E
E
for e in theCollection { println(e) }
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
#EchoLisp
EchoLisp
  (define my-list '( albert simon antoinette)) (for ((h my-list)) (write h)) albert simon antoinette   (define my-vector #(55 66 soixante-dix-sept)) (for (( u my-vector)) (write u)) 55 66 soixante-dix-sept   (define my-string "Longtemps") (for ((une-lettre my-string)) (write une-lettre)) "L" "o" "n" "g" "t" "e" "m" "p" "s"   ;; etc ... for other collections like Streams, Hashes, Graphs, ...  
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
C
#include <string.h> #include <stdio.h>   int luhn(const char* cc) { const int m[] = {0,2,4,6,8,1,3,5,7,9}; // mapping for rule 3 int i, odd = 1, sum = 0;   for (i = strlen(cc); i--; odd = !odd) { int digit = cc[i] - '0'; sum += odd ? digit : m[digit]; }   return sum % 10 == 0; }   int main() { const char* cc[] = { "49927398716", "49927398717", "1234567812345678", "1234567812345670", 0 }; int i;   for (i = 0; cc[i]; i++) printf("%16s\t%s\n", cc[i], luhn(cc[i]) ? "ok" : "not ok");   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).
#FunL
FunL
def mersenne( p ) = if p == 2 then return true   var s = 4 var M = 2^p - 1   repeat p - 2 s = (s*s - 2) mod M   s == 0   import integers.primes   for p <- primes().filter( mersenne ).take( 20 ) println( 'M' + 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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
compress[uncompressed_] := Module[{dictsize, dictionary, w, result, wc}, dictsize = 256; dictionary = # -> # & /@ FromCharacterCode /@ Range@dictsize; w = ""; result = {}; Do[wc = w <> c; If[MemberQ[dictionary[[All, 1]], wc], w = wc, AppendTo[result, w /. dictionary]; AppendTo[dictionary, wc -> dictsize]; dictsize++; w = c], {c, Characters[uncompressed]}]; AppendTo[result, w /. dictionary]; result]; decompress::bc = "Bad compressed `1`"; decompress[compressed_] := Module[{dictsize, dictionary, w, result, entry}, dictsize = 256; dictionary = # -> # & /@ FromCharacterCode /@ Range@dictsize; w = result = compressed[[1]]; Do[Which[MemberQ[dictionary[[All, 1]], k], entry = k /. dictionary, k == dictsize, entry = w <> StringTake[w, 1], True, Message[decompress::bc, k]]; result = result <> entry; AppendTo[dictionary, dictsize -> w <> StringTake[entry, 1]]; dictsize++; w = entry, {k, compressed[[2 ;;]]}]; result]; (*How to use:*) compress["TOBEORNOTTOBEORTOBEORNOT"] decompress[%]
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
#Racket
Racket
  #lang racket (require math) (define A (matrix [[1 3 5] [2 4 7] [1 1 0]]))   (matrix-lu A) ; result: ; (mutable-array #[#[1 0 0] ; #[2 1 0] ; #[1 1 1]]) ; (mutable-array #[#[1 3 5] ; #[0 -2 -3] ; #[0 0 -2]])  
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.
#Wren
Wren
import "/big" for BigInt import "/set" for Set   var iterations = 500 var limit = 10000 var bigLimit = BigInt.new(limit)   // In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel var lychrelSieve = List.filled(limit + 1, 0) var seedLychrels = [] var relatedLychrels = Set.new()   var isPalindrome = Fn.new { |bi| var s = bi.toString return s == s[-1..0] }   var lychrelTest = Fn.new { |i, seq| if (i < 1) return var bi = BigInt.new(i) for (j in 1..iterations) { bi = bi + BigInt.new(bi.toString[-1..0]) seq.add(bi) if (isPalindrome.call(bi)) return } for (j in 0...seq.count) { if (seq[j] <= bigLimit) { lychrelSieve[seq[j].toSmall] = 2 } else { break } } var sizeBefore = relatedLychrels.count // if all of these can be added 'i' must be a seed Lychrel relatedLychrels.addAll(seq.map { |i| i.toString }) // can't add BigInts directly to a Set if (relatedLychrels.count - sizeBefore == seq.count) { seedLychrels.add(i) lychrelSieve[i] = 1 } else { relatedLychrels.add(i.toString) lychrelSieve[i] = 2 } }   var seq = [] for (i in 1..limit) { if (lychrelSieve[i] == 0) { seq.clear() lychrelTest.call(i, seq) } } var related = lychrelSieve.count { |i| i == 2 } System.print("Lychrel numbers in the range [1, %(limit)]") System.print("Maximum iterations = %(iterations)") System.print("\nThere are %(seedLychrels.count) seed Lychrel numbers, namely:") System.print(seedLychrels) System.print("\nThere are also %(related) related Lychrel numbers in this range.") var palindromes = [] for (i in 1..limit) { if (lychrelSieve[i] > 0 && isPalindrome.call(BigInt.new(i))) palindromes.add(i) } System.print("\nThere are %(palindromes.count) palindromic Lychrel numbers, namely:") System.print(palindromes)
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
#Racket
Racket
(define (get-mad-libs file) (with-input-from-file file (lambda () (for/fold ((text "")) ((line (in-lines))) (string-append text line "\n")))))     (define (replace-context mad-libs) (define matches (regexp-match* #rx"<[a-zA-Z0-9 ]*>" mad-libs)) (map (lambda (context) (display (format "~a?" context)) (cons context (read-line))) (remove-duplicates matches)))   (define (play-mad-libs) (display "Tell me a file to play Mad Libs: ") (define text (get-mad-libs (read-line))) (define matches (replace-context text))   (display (for/fold ((mad-story text)) ((change (in-list matches))) (string-replace mad-story (car change) (cdr change)))))   (play-mad-libs)
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
#Kotlin
Kotlin
// version 1.2.60   fun isPrime(n: Long): Boolean { if (n % 2L == 0L) return n == 2L if (n % 3L == 0L) return n == 3L var d = 5L while (d * d <= n) { if (n % d == 0L) return false d += 2L if (n % d == 0L) return false d += 4L } return true }   fun main(args: Array<String>) { var i = 42L var n = 0 do { if (isPrime(i)) { n++ System.out.printf("n = %-2d  %,19d\n", n, i) i += i - 1 } i++ } while (n < 42) }
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
#Brat
Brat
loop { p "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
C
while(1) puts("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
#Python
Python
from itertools import chain   prod, sum_, x, y, z, one,three,seven = 1, 0, 5, -5, -2, 1, 3, 7   def _range(x, y, z=1): return range(x, y + (1 if z > 0 else -1), z)   print(f'list(_range(x, y, z)) = {list(_range(x, y, z))}') print(f'list(_range(-seven, seven, x)) = {list(_range(-seven, seven, x))}')   for j in chain(_range(-three, 3**3, three), _range(-seven, seven, x), _range(555, 550 - y), _range(22, -28, -three), _range(1927, 1939), _range(x, y, z), _range(11**x, 11**x + 1)): sum_ += abs(j) if abs(prod) < 2**27 and (j != 0): prod *= j print(f' sum= {sum_}\nprod= {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
#Clojure
Clojure
(def i (ref 1024))   (while (> @i 0) (println @i) (dosync (ref-set i (quot @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
#CLU
CLU
start_up = proc () po: stream := stream$primary_output() n: int := 1024 while n>0 do stream$putl(po, int$unparse(n)) n := n/2 end end start_up
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
#BASIC
BASIC
FOR I = 10 TO 0 STEP -1 : PRINT I : NEXT I
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
#Batch_File
Batch File
@echo off for /l %%D in (10,-1,0) do echo %%D
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.
#AmigaE
AmigaE
PROC main() DEF i = 0 REPEAT i := i + 1 WriteF('\d\n', i) UNTIL Mod(i, 6) = 0 ENDPROC
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.
#AmigaE
AmigaE
PROC main() DEF i, j FOR i := 1 TO 5 FOR j := 1 TO i DO WriteF('*') WriteF('\n') ENDFOR ENDPROC
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
#AWK
AWK
BEGIN { for (i= 2; i <= 8; i = i + 2) { print i } print "Ain't never too late!" }
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.
#Racket
Racket
#lang racket (define lucid-sieve-size 25000) ; this should be enough to do me! (define lucid? (let ((lucid-bytes-sieve (delay (define sieve-bytes (make-bytes lucid-sieve-size 1)) (bytes-set! sieve-bytes 0 0) ; not a lucid number (define (sieve-pass L) (let loop ((idx (add1 L)) (skip (sub1 L))) (cond [(= idx lucid-sieve-size) (for/first ((rv (in-range (add1 L) lucid-sieve-size)) #:unless (zero? (bytes-ref sieve-bytes rv))) rv)] [(zero? (bytes-ref sieve-bytes idx)) (loop (add1 idx) skip)] [(= skip 0) (bytes-set! sieve-bytes idx 0) (loop (add1 idx) (sub1 L))] [else (loop (add1 idx) (sub1 skip))]))) (let loop ((l 2)) (when l (loop (sieve-pass l)))) sieve-bytes)))   (λ (n) (= 1 (bytes-ref (force lucid-bytes-sieve) n)))))   (define (dnl . things) (for-each displayln things))   (dnl "Generate and show here the first 25 ludic numbers." (for/list ((_ 25) (l (sequence-filter lucid? (in-naturals)))) l) "How many ludic numbers are there less than or equal to 1000?" (for/sum ((n 1001) #:when (lucid? n)) 1) "Show the 2000..2005'th ludic numbers." (for/list ((i 2006) (l (sequence-filter lucid? (in-naturals))) #:when (>= i 2000)) l) #<<EOS A triplet is any three numbers x, x + 2, x + 6 where all three numbers are also ludic numbers. Show all triplets of ludic numbers < 250 (Stretch goal) EOS (for/list ((x (in-range 250)) #:when (and (lucid? x) (lucid? (+ x 2)) (lucid? (+ x 6)))) (list x (+ x 2) (+ x 6))))
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
#Delphi
Delphi
program LoopsNPlusOneHalf;   {$APPTYPE CONSOLE}   var i: integer; const MAXVAL = 10; begin for i := 1 to MAXVAL do begin Write(i); if i < MAXVAL then Write(', '); end; Writeln; 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
#Draco
Draco
proc nonrec main() void: byte i; i := 1; while write(i); i := i + 1; i <= 10 do write(", ") od corp
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
#Common_Lisp
Common Lisp
(let ((a (make-array '(10 10)))) (dotimes (i 10) (dotimes (j 10) (setf (aref a i j) (1+ (random 20)))))   (block outer (dotimes (i 10) (dotimes (j 10) (princ " ") (princ (aref a i j)) (if (= 20 (aref a i j)) (return-from outer))) (terpri)) (terpri)))
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
#Efene
Efene
io.format("~p~n", [Collection])
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
#Eiffel
Eiffel
across my_list as ic loop print (ic.item) end
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.23
C#
  public static class Luhn { public static bool LuhnCheck(this string cardNumber) { return LuhnCheck(cardNumber.Select(c => c - '0').ToArray()); }   private static bool LuhnCheck(this int[] digits) { return GetCheckValue(digits) == 0; }   private static int GetCheckValue(int[] digits) { return digits.Select((d, i) => i % 2 == digits.Length % 2 ? ((2 * d) % 10) + d / 5 : d).Sum() % 10; } }   public static class TestProgram { public static void Main() { long[] testNumbers = {49927398716, 49927398717, 1234567812345678, 1234567812345670}; foreach (var testNumber in testNumbers) Console.WriteLine("{0} is {1}valid", testNumber, testNumber.ToString().LuhnCheck() ? "" : "not "); } }  
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).
#GAP
GAP
LucasLehmer := function(n) local i, m, s; if n = 2 then return true; elif not IsPrime(n) then return false; else m := 2^n - 1; s := 4; for i in [3 .. n] do s := RemInt(s*s, m) - 2; od; return s = 0; fi; end;   Filtered([1 .. 2000], LucasLehmer); [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279]
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.
#Nim
Nim
import tables   proc compress*(uncompressed: string): seq[int] =   # Build the dictionary. var dictionary: Table[string, int] for i in 0..255: dictionary[$chr(i)] = i   var w = "" for c in uncompressed: var wc = w & c if wc in dictionary: w = wc else: # Writes "w" to output. result.add dictionary[w] # "wc" is a new sequence: add it to the dictionary. dictionary[wc] = dictionary.len w = $c   # Write remaining output if necessary. if w.len > 0: result.add dictionary[w]     proc decompress*(compressed: var seq[int]): string =   # Build the dictionary. var dictionary: Table[int, string] for i in 0..255: dictionary[i] = $chr(i)   var w = dictionary[compressed[0]] compressed.delete(0)   result = w for k in compressed: var entry: string if k in dictionary: entry = dictionary[k] elif k == dictionary.len: entry = w & w[0] else: raise newException(ValueError, "Bad compressed k: " & $k) result.add entry # New sequence: add it to the dictionary. dictionary[dictionary.len] = w & entry[0] w = entry     when isMainModule: var compressed = compress("TOBEORNOTTOBEORTOBEORNOT") echo compressed var decompressed = decompress(compressed) echo decompressed
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
#Raku
Raku
for ( [1, 3, 5], # Test Matrices [2, 4, 7], [1, 1, 0] ), ( [11, 9, 24, 2], [ 1, 5, 2, 6], [ 3, 17, 18, 1], [ 2, 5, 7, 1] ) -> @test { say-it 'A Matrix', @test; say-it( $_[0], @($_[1]) ) for 'P Matrix', 'Aʼ Matrix', 'L Matrix', 'U Matrix' Z, lu @test; }   sub lu (@a) { die unless @a.&is-square; my $n = +@a; my @P = pivotize @a; my @Aʼ = mmult @P, @a; my @L = matrix-ident $n; my @U = matrix-zero $n; for ^$n -> $i { for ^$n -> $j { if $j >= $i { @U[$i][$j] = @Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$i } else { @L[$i][$j] = (@Aʼ[$i][$j] - [+] map { @U[$_][$j] * @L[$i][$_] }, ^$j) / @U[$j][$j]; } }   } return @P, @Aʼ, @L, @U; }   sub pivotize (@m) { my $size = +@m; my @id = matrix-ident $size; for ^$size -> $i { my $max = @m[$i][$i]; my $row = $i; for $i ..^ $size -> $j { if @m[$j][$i] > $max { $max = @m[$j][$i]; $row = $j; } } if $row != $i { @id[$row, $i] = @id[$i, $row] } } @id }   sub is-square (@m) { so @m == all @m[*] }   sub matrix-zero ($n, $m = $n) { map { [ flat 0 xx $n ] }, ^$m }   sub matrix-ident ($n) { map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n }   sub mmult(@a,@b) { my @p; for ^@a X ^@b[0] -> ($r, $c) { @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b; } @p }   sub rat-int ($num) { return $num unless $num ~~ Rat; return $num.narrow if $num.narrow.WHAT ~~ Int; $num.nude.join: '/'; }   sub say-it ($message, @array) { say "\n$message"; $_».&rat-int.fmt("%7s").say for @array; }