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/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.
| #JavaScript | JavaScript | //LZW Compression/Decompression for Strings
var LZW = {
compress: function (uncompressed) {
"use strict";
// Build the dictionary.
var i,
dictionary = {},
c,
wc,
w = "",
result = [],
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[String.fromCharCode(i)] = i;
}
for (i = 0; i < uncompressed.length; i += 1) {
c = uncompressed.charAt(i);
wc = w + c;
//Do not use dictionary[wc] because javascript arrays
//will return values for array['pop'], array['push'] etc
// if (dictionary[wc]) {
if (dictionary.hasOwnProperty(wc)) {
w = wc;
} else {
result.push(dictionary[w]);
// Add wc to the dictionary.
dictionary[wc] = dictSize++;
w = String(c);
}
}
// Output the code for w.
if (w !== "") {
result.push(dictionary[w]);
}
return result;
},
decompress: function (compressed) {
"use strict";
// Build the dictionary.
var i,
dictionary = [],
w,
result,
k,
entry = "",
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[i] = String.fromCharCode(i);
}
w = String.fromCharCode(compressed[0]);
result = w;
for (i = 1; i < compressed.length; i += 1) {
k = compressed[i];
if (dictionary[k]) {
entry = dictionary[k];
} else {
if (k === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
w = entry;
}
return result;
}
}, // For Test Purposes
comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT"),
decomp = LZW.decompress(comp);
document.write(comp + '<br>' + decomp); |
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
| #Nim | Nim | import macros, strutils
import strfmt
type
Matrix[M, N: static int] = array[1..M, array[1..N, float]]
SquareMatrix[N: static int] = Matrix[N, N]
# Templates to allow to use more natural notation for indexing.
template `[]`(m: Matrix; i, j: int): float = m[i][j]
template `[]=`(m: Matrix; i, j: int; val: float) = m[i][j] = val
func `*`[M, N, P: static int](a: Matrix[M, N]; b: Matrix[N, P]): Matrix[M, P] =
## Matrix multiplication.
for i in 1..M:
for j in 1..P:
for k in 1..N:
result[i, j] += a[i, k] * b[k, j]
func pivotize[N: static int](m: SquareMatrix[N]): SquareMatrix[N] =
for i in 1..N: result[i, i] = 1
for i in 1..N:
var max = m[i, i]
var row = i
for j in i..N:
if m[j, i] > max:
max = m[j, i]
row = j
if i != row:
swap result[i], result[row]
func lu[N: static int](m: SquareMatrix[N]): tuple[l, u, p: SquareMatrix[N]] =
result.p = m.pivotize()
let m2 = result.p * m
for j in 1..N:
result.l[j, j] = 1
for i in 1..j:
var sum = 0.0
for k in 1..<i: sum += result.u[k, j] * result.l[i, k]
result.u[i, j] = m2[i, j] - sum
for i in j..N:
var sum = 0.0
for k in 1..<j: sum += result.u[k, j] * result.l[i, k]
result.l[i, j] = (m2[i, j] - sum) / result.u[j, j]
proc print(m: Matrix; title, f: string) =
echo '\n', title
for i in 1..m.N:
for j in 1..m.N:
stdout.write m[i, j].format(f), " "
stdout.write '\n'
when isMainModule:
const A1: SquareMatrix[3] = [[1.0, 3.0, 5.0],
[2.0, 4.0, 7.0],
[1.0, 1.0, 0.0]]
let (l1, u1, p1) = A1.lu()
echo "\nExample 2:"
A1.print("A:", "1.0f")
l1.print("L:", "8.5f")
u1.print("U:", "8.5f")
p1.print("P:", "1.0f")
const A2: SquareMatrix[4] = [[11.0, 9.0, 24.0, 2.0],
[ 1.0, 5.0, 2.0, 6.0],
[ 3.0, 17.0, 18.0, 1.0],
[ 2.0, 5.0, 7.0, 1.0]]
let (l2, u2, p2) = A2.lu()
echo "Example 1:"
A2.print("A:", "2.0f")
l2.print("L:", "8.5f")
u2.print("U:", "8.5f")
p2.print("P:", "1.0f") |
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.
| #REXX | REXX | /*REXX program finds and displays Lychrel numbers, related numbers, and palindromes. */
parse arg high limit . /*obtain optional argument from the CL.*/
if high='' | high=="," then high= 10000 /*Not specified? Then use the default.*/
if limit='' | limit=="," then limit= 500 /* " " " " " " */
numeric digits limit % 2 /*ensure enough decimal digits for adds*/
T.= 0; @.= T.; #.=@.; w= length(high) /*W: is used for formatting numbers. */
$= /*the list of Lychrel numbers. */
do j=1 for high; call Lychrel j /*find the Lychrel numbers. */
end /*j*/
p=; R= /*P: list of palindromes; R: related #s*/
do k=1 for high
if #.k then $= $ k /*build a list of Lychrel numbers. */
if T.k then R= R k /* " " " " " related nums.*/
if T.k & k==reverse(k) then p= p k /* " " " " " palindromes. */
end /*k*/
say 'Found in the range 1 to ' high " (limiting searches to " limit ' steps):'
say
say right( words($) , w) 'Lychrel numbers:' $
say right( words(R) - words($), w) 'Lychrel related numbers.'
say right( words(p) , w) 'Lychrel palindromes:' p
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Lychrel: procedure expose limit @. #. T.; parse arg x 1 z /*set X and Z to argument 1.*/
rels= 0 /*# related numbers (so far)*/
do limit; z= z + reverse(z) /*add the reverse of Z ··· */
if z==reverse(z) then return /*is the new Z a palindrome?*/
rels= rels + 1; !.rels= z /*add to the related numbers*/
end /*limit*/ /* [↑] only DO limit times.*/
#.x= 1 /*mark number as a Lychrel.*/
T.x= 1; do a=1 for rels; _= !.a /*process "related" numbers.*/
if @._ then #.x= 0 /*unmark number as Lychrel.*/
else @._= 1 /* mark " " " */
T._= 1 /*mark number as "related".*/
end /*a*/
return |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Picat | Picat | import util.
go =>
Story = read_story(),
println("Fill in the proper values:"),
nl,
Map = get_info(get_tags(Story)) ,
println("\nHere is the story:\n"),
println(replace_tags(Story,Map)),
nl.
read_story() = Story =>
println("Write the story template with <tag> for the tags and finish with an empty line."),
nl,
Story1 = read_line(),
while (Line = read_line(), Line != "")
Story1 := Story1 ++ " " ++ Line
end,
Story = Story1.
%
% Get the tags between <...>.
%
get_tags(S) = Tags =>
Len = S.length,
StartPos = [P: {C,P} in zip(S,1..Len), C = '<'],
EndPos = [P: {C,P} in zip(S,1..Len), C = '>'],
Tags = [slice(S,Start,End) : {Start,End} in zip(StartPos,EndPos)].remove_dups().
%
% Get the tag info from user and return a map
%
get_info(Tags) = Map =>
Map = new_map(),
foreach(Tag in Tags)
printf("%w: ", Tag),
Map.put(Tag,readln())
end.
% Replace all the <tags> with user values.
replace_tags(S,Map) = S =>
foreach(Tag=Value in Map)
S := replace_string(T,Tag,Value)
end.
% Picat's replace/3 does not handle substrings well,
% so we roll our own...
replace_string(List,Old,New) = Res =>
Res = copy_term(List),
while (find(Res,Old,_,_))
once(append(Before,Old,After,Res)),
Res := Before ++ New ++ After
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
| #Factor | Factor | USING: formatting kernel math math.primes
tools.memory.private ;
IN: rosetta-code.loops-inc-body
42
0
[ dup 42 < ] [
over prime? [
1 + 2dup swap commas
"n = %-2d %19s\n" printf
[ dup + 1 - ] dip
] when
[ 1 + ] dip
] while
2drop |
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
| #Fortran | Fortran | do i=1,10
write(*,*) i
i=i+1
end do |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AWK | AWK | BEGIN {
while(1) {
print "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
| #Axe | Axe | While 1
Disp "SPAM",i
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
| #jq | jq |
# If using gojq, one may want to preserve integer precision, so:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
{ prod: 1, # start with a product of unity.
sum: 0, # henceforth skip redundant comments.
x: 5,
y: -5,
z: -2,
one: 1,
three: 3,
seven: 7 }
| .x as $x
| reduce (range(-.three; 1 + 3|power(3); .three),
range(-.seven; 1 + .seven; .x),
range( 555; 1 + 550 - .y),
range( 22; -1 -28; -.three),
range(1927 ; 1 + 1939),
range(.x ; .y; .z),
range(11|power($x); 1 + ( 11 | power($x)) + .one)) as $j (.;
.sum += ($j|length) # add absolute value of $j (!)
| if (.prod|length) < (2|power(27)) and $j != 0
then .prod *= $j
else .
end )
| "sum= \(.sum)",
"prod= \(.prod)"
|
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Julia | Julia | using Formatting
function PL1example()
# 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
for j in [ -three : three : 3^3 ;
-seven : x : +seven ;
555 : 550 - y ;
22 : -three : -28 ;
1927 : 1939 ;
x : z : y ;
11^x : 11^x + one ]
# ABS(n) = absolute value
sum = sum + abs(j); # add absolute value of J.
if abs(prod) < 2^27 && j !=0 prod = prod*j # PROD is small enough & J
end; # not 0, then multiply it.
end # SUM and PROD are used for verification of J incrementation.
println(" sum = $(format(sum, commas=true))"); # display strings to term.
println("prod = $(format(prod, commas=true))"); # " " " "
end
PL1example()
|
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
| #Axe | Axe | 1024→A
While A>0
Disp A▶Dec,i
A/2→A
End |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BASIC | BASIC | i = 1024
WHILE i > 0
PRINT i
i = i / 2
WEND |
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
| #Agena | Agena | for i from 10 downto 0 do
print( i )
od |
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
| #ALGOL_60 | ALGOL 60 | begin
integer i;
for i:=10 step -1 until 0 do
outinteger(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.
| #ActionScript | ActionScript | var val:int = 0;
do
{
trace(++val);
} while (val % 6); |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Ada | Ada | for I in 1..5 loop
for J in 1..I loop
Put("*");
end loop;
New_Line;
end loop; |
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
| #ALGOL_W | ALGOL W | begin
for i := 3 step 2 until 9 do write( i )
end. |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #PicoLisp | PicoLisp | (de drop (Lst)
(let N (car Lst)
(make
(for (I . X) (cdr Lst)
(unless (=0 (% I N)) (link X)) ) ) ) )
(de comb (M Lst)
(cond
((=0 M) '(NIL))
((not Lst))
(T
(conc
(mapcar
'((Y) (cons (car Lst) Y))
(comb (dec M) (cdr Lst)) )
(comb M (cdr Lst)) ) ) ) )
(de ludic (N)
(let Ludic (range 1 100000)
(make
(link (pop 'Ludic))
(do (dec N)
(link (car Ludic))
(setq Ludic (drop Ludic)) ) ) ) )
(let L (ludic 2005)
(println (head 25 L))
(println (cnt '((X) (< X 1000)) L))
(println (tail 6 L))
(println
(filter
'((Lst)
(and
(= (+ 2 (car Lst)) (cadr Lst))
(= (+ 6 (car Lst)) (caddr Lst)) ) )
(comb
3
(filter '((X) (< X 250)) L) ) ) ) )
(bye) |
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
| #Befunge | Befunge | 1+>::.9`#@_" ,",, |
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
| #Bracmat | Bracmat | 1:?i
& whl
' ( put$!i
& !i+1:~>10:?i
& put$", "
) |
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
| #C | C | #include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf("\n");
}
Done:
printf("\n");
return 0;
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #Vala | Vala | static void example(int start, int stop, int increment, string comment) {
const int MAX_ITER = 9;
int iteration = 0;
stdout.printf("%-50s", comment);
for (int i = start; i <= stop; i += increment) {
stdout.printf("%3d ", i);
if (++iteration > MAX_ITER) break;
}
stdout.printf("\n");
}
void main () {
example(-2, 2, 1, "Normal");
example(-2, 2, 0, "Zero increment");
example(-2, 2, -1, "Increments away from stop value");
example(-2, 2, 10, "First increment is beyond stop value");
example(2, -2, 1, "Start more than stop: positive increment");
example(2, 2, 1, "Start equals stop: positive increment");
example(2, 2, -1, "Start equals stop: negative increment");
example(2, 2, 0, "Start equals stop: zero increment");
example(0, 0, 0, "Start equals stop equal zero: zero increment");
} |
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
| #Chapel | Chapel | var food = ["Milk", "Bread", "Butter"];
for f in food do writeln(f); |
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
| #Clojure | Clojure | (doseq [item collection] (println item)) |
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
| #BCPL | BCPL | get "libhdr"
let luhn(s) = valof
$( let sum=0 and fac=1
for i = s%0 to 1 by -1
$( unless '0' <= s%i <= '9' resultis false
sum := sum + fac*(s%i - '0') rem 10 + fac*(s%i - '0')/10
fac := 3 - fac
$)
resultis sum rem 10 = 0
$)
let show(s) be
writef("%S: %S*N", s, luhn(s) -> "pass", "fail")
let start() be
$( show("49927398716")
show("49927398717")
show("1234567812345678")
show("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).
| #Factor | Factor | USING: io math.primes.lucas-lehmer math.ranges prettyprint
sequences ;
47 [1,b] [ lucas-lehmer ] filter
"Mersenne primes:" print
[ "M" write pprint bl ] each nl |
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.
| #jq | jq | # LZW compression/decompression for strings
def lzw_compress:
def decode: [.] | implode;
# Build the dictionary:
256 as $dictSize
| (reduce range(0; $dictSize) as $i ({}; .[ $i | decode ] = $i)) as $dictionary
| reduce explode[] as $i
( [$dictionary, $dictSize, "", []]; # state: [dictionary, dictSize, w, result]
.[0] as $dictionary
| .[1] as $dictSize
| .[2] as $w
| ($i | decode) as $c
| ($w + $c ) as $wc
| if $dictionary[$wc] then .[2] = $wc
else
.[2] = $c # w = c
| .[3] += [$dictionary[$w]] # result += dictionary[w]
| .[0][$wc] = $dictSize # Add wc to the dictionary
| .[1] += 1 # dictSize ++
end
)
# Output the code for w unless w == "":
| if .[2] == "" then .[3]
else .[3] + [.[0][.[2]]]
end
;
def lzw_decompress:
def decode: [.] | implode;
# Build the dictionary - an array of strings
256 as $dictSize
| (reduce range(0; $dictSize) as $i ([]; .[ $i ] = ($i|decode))) as $dictionary
| (.[0]|decode) as $w
| reduce .[1:][] as $k
( [ $dictionary, $dictSize, $w, $w]; # state: [dictionary, dictSize, w, result]
.[0][$k] as $entry
| (if $entry then $entry
elif $k == .[1] then .[2] + .[2][0:1]
else error("lzw_decompress: k=\($k)")
end) as $entry
| .[3] += $entry # result += entry
| .[0][.[1]] = .[2] + $entry[0:1] # dictionary[dictSize] = w + entry.charAt(0);
| .[1] += 1 # dictSize++
| .[2] = $entry # w = entry
) | .[3]
; |
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
| #PARI.2FGP | PARI/GP | matlup(M) =
{
my (L = matid(#M), U = M, P = L);
for (i = 1, #M-1, \\ pivoting
p = M[z=i,i];
for (k = i, #M, if (M[k,i] > p, p = M[z=k,i]));
if (i != z, \\ swap rows
k = U[i,]; U[i,] = U[z,]; U[z,] = k;
k = P[i,]; P[i,] = P[z,]; P[z,] = k;
);
);
for (i = 1, #M-1, \\ decompose
for (k = i+1, #M,
L[k,i] = U[k,i] / U[i,i];
for (j = i, #M, U[k,j] -= L[k,i] * U[i,j])
)
);
[L,U,P] \\ return L,U,P triple matrix
} |
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.
| #Ruby | Ruby | require 'set'
def add_reverse(num, max_iter=1000)
(1..max_iter).each_with_object(Set.new([num])) do |_,nums|
num += reverse_int(num)
nums << num
return nums if palindrome?(num)
end
end
def palindrome?(num)
num == reverse_int(num)
end
def reverse_int(num)
num.to_s.reverse.to_i
end
def split_roots_from_relateds(roots_and_relateds)
roots = roots_and_relateds.dup
i = 1
while i < roots.length
this = roots[i]
if roots[0...i].any?{|prev| this.intersect?(prev)}
roots.delete_at(i)
else
i += 1
end
end
root = roots.map{|each_set| each_set.min}
related = roots_and_relateds.map{|each_set| each_set.min}
related = related.reject{|n| root.include?(n)}
return root, related
end
def find_lychrel(maxn, max_reversions)
series = (1..maxn).map{|n| add_reverse(n, max_reversions*2)}
roots_and_relateds = series.select{|s| s.length > max_reversions}
split_roots_from_relateds(roots_and_relateds)
end
maxn, reversion_limit = 10000, 500
puts "Calculations using n = 1..#{maxn} and limiting each search to 2*#{reversion_limit} reverse-digits-and-adds"
lychrel, l_related = find_lychrel(maxn, reversion_limit)
puts " Number of Lychrel numbers: #{lychrel.length}"
puts " Lychrel numbers: #{lychrel}"
puts " Number of Lychrel related: #{l_related.length}"
pals = (lychrel + l_related).select{|x| palindrome?(x)}.sort
puts " Number of Lychrel palindromes: #{pals.length}"
puts " Lychrel palindromes: #{pals}" |
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
| #PicoLisp | PicoLisp | (de madlib (Template)
(setq Template (split (chop Template) "<" ">"))
(let (Reps () Text ())
(while Template
(push 'Text (pop 'Template))
(let? Rep (mapcar pack (split (pop 'Template) ":"))
(if (assoc (car Rep) Reps)
(push 'Text (cdr @))
(until (and
(prin "Gimme a(n) " (or (cadr Rep) (car Rep)) ": ")
(clip (in NIL (line)))
(push 'Text @)
(push 'Reps (cons (car Rep) @)) )
(prinl "Huh? I got nothing.") ) ) ) )
(prinl (need 30 '-))
(prinl (flip Text)) ) )
|
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
| #FreeBASIC | FreeBASIC | ' version 18-01-2019
' compile with: fbc -s console
Function isprime(number As ULongInt) As UInteger
If number Mod 2 = 0 Then Return 0
If number Mod 3 = 0 Then Return 0
Dim As UInteger i, max = Sqr(number)
For i = 5 To max Step 2
If number Mod i = 0 Then Return 0
Next
Return 1
End Function
' ------=< MAIN >=------
Dim As UInteger counter
Dim As ULongInt i
Print : Print
counter = 0
For i = 42 To &HFFFFFFFFFFFFFFFF ' for next loop, loop maximum = 2^64-1
If isprime(i) Then
counter += 1
Print Using "n =### ##################,"; counter; i
If counter >= 42 Then Exit for
i += i -1
End If
Next
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BASIC | BASIC | WHILE 1
PRINT "SPAM"
WEND |
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
| #Batch_File | Batch File | @echo off
:loop
echo SPAM
goto loop |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Kotlin | Kotlin | // Version 1.2.70
import kotlin.math.abs
infix fun Int.pow(e: Int): Int {
if (e == 0) return 1
var prod = this
for (i in 2..e) {
prod *= this
}
return prod
}
fun main(args: Array<String>) {
var prod = 1
var sum = 0
val x = 5
val y = -5
val z = -2
val one = 1
val three = 3
val seven = 7
val p = 11 pow x
fun process(j: Int) {
sum += abs(j)
if (abs(prod) < (1 shl 27) && j != 0) prod *= j
}
for (j in -three..(3 pow 3) step three) process(j)
for (j in -seven..seven step x) process(j)
for (j in 555..550-y) process(j)
for (j in 22 downTo -28 step three) process(j)
for (j in 1927..1939) process(j)
for (j in x downTo y step -z) process(j)
for (j in p..p + one) process(j)
System.out.printf("sum = % ,d\n", sum)
System.out.printf("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
| #bc | bc | i = 1024
while (i > 0) {
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
| #Befunge | Befunge | 84*:*> :v
^/2,*25.:_@ |
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
| #ALGOL_68 | ALGOL 68 | FOR i FROM 10 BY -1 TO 0 DO
print((i,new line))
OD |
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
| #ALGOL_W | ALGOL W | begin
for i := 10 step -1 until 0 do
begin
write( i )
end
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.
| #Ada | Ada | loop
Value := Value + 1;
Put (Value);
exit when Value mod 6 = 0;
end loop; |
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.
| #Agena | Agena | for i to 5 do
for j to i do
write( "*" )
od;
print()
od |
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
| #ALGOL-M | ALGOL-M | BEGIN
INTEGER I;
FOR I := 1 STEP 3 UNTIL 19 DO
WRITE( I );
END |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #PL.2FI | PL/I | Ludic_numbers: procedure options (main); /* 18 April 2014 */
declare V(2:22000) fixed, L(2200) fixed;
declare (step, i, j, k, n) fixed binary;
Ludic: procedure;
n = hbound(V,1); k = 1; L(1) = 1;
do i = 2 to n; V(i) = i; end;
do forever;
k = k + 1; L(k), step = V(2);
do i = 2 to n by step;
V(i) = 0;
end;
call compress;
if L(k) >= 21511 then leave;
end;
put skip list ('The first 25 Ludic numbers are:');
put skip edit ( (L(i) do i = 1 to 25) ) (F(4));
k = 0;
do i = 1 by 1;
if L(i) < 1000 then k = k + 1; else leave;
end;
put skip list ('There are ' || trim(k) || ' Ludic numbers < 1000');
put skip list ('Six Ludic numbers from the 2000-th:');
put skip edit ( (L(i) do i = 2000 to 2005) ) (f(7));
/* Triples are values of the form x, x+2, x+6 */
put skip list ('Triples are:');
put skip;
i = 1;
put edit ('(', L(1), L(3), L(5), ') ' ) (A, 3 F(4), A);
do i = 1 by 1 while (L(i+2) <= 250);
if (L(i) = L(i+1) - 2) & (L(i) = L(i+2) - 6) then
put edit ('(', L(i), L(i+1), L(i+2), ') ' ) (A, 3 F(4), A);
end;
compress: procedure;
j = 2;
do i = 2 to n;
if V(i) ^= 0 then do; V(j) = V(i); j = j + 1; end;
end;
n = j-1;
end compress;
end Ludic;
call Ludic;
end Ludic_numbers; |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C | C | #include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) {
printf("%d", i);
printf(i == 10 ? "\n" : ", ");
}
return 0;
} |
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
| #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; ; i++)
{
Console.Write(i);
if (i == 10) break;
Console.Write(", ");
}
Console.WriteLine();
}
} |
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
| #C.23 | C# | using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #VBA | VBA | Public Sub LoopsWrongRanges()
Call Example(-2, 2, 1, "Normal")
Call Example(-2, 2, 0, "Zero increment")
Call Example(-2, 2, -1, "Increments away from stop value")
Call Example(-2, 2, 10, "First increment is beyond stop value")
Call Example(2, -2, 1, "Start more than stop: positive increment")
Call Example(2, 2, 1, "Start equal stop: positive increment")
Call Example(2, 2, -1, "Start equal stop: negative increment")
Call Example(2, 2, 0, "Start equal stop: zero increment")
Call Example(0, 0, 0, "Start equal stop equal zero: zero increment")
End Sub
Private Sub Example(start As Integer, stop_ As Integer, by As Integer, comment As String)
Dim i As Integer
Dim c As Integer
Const limit = 10
c = 0
Debug.Print start; " "; stop_; " "; by; " | ";
For i = start To stop_ Step by
Debug.Print i & ",";
c = c + 1
If c > limit Then Exit For
Next i
Debug.Print
Debug.Print comment & vbCrLf
End Sub
|
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main()
Example(-2, 2, 1, "Normal")
Example(-2, 2, 0, "Zero increment")
Example(-2, 2, -1, "Increments away from stop value")
Example(-2, 2, 10, "First increment is beyond stop value")
Example(2, -2, 1, "Start more than stop: positive increment")
Example(2, 2, 1, "Start equal stop: positive increment")
Example(2, 2, -1, "Start equal stop: negative increment")
Example(2, 2, 0, "Start equal stop: zero increment")
Example(0, 0, 0, "Start equal stop equal zero: zero increment")
End Sub
' Stop is a keyword and must be escaped using brackets.
Iterator Function Range(start As Integer, [stop] As Integer, increment As Integer) As IEnumerable(Of Integer)
For i = start To [stop] Step increment
Yield i
Next
End Function
Sub Example(start As Integer, [stop] As Integer, increment As Integer, comment As String)
' Add a space, pad to length 50 with hyphens, and add another space.
Console.Write((comment & " ").PadRight(50, "-"c) & " ")
Const MAX_ITER = 9
Dim iteration = 0
' The For Each loop enumerates the IEnumerable.
For Each i In Range(start, [stop], increment)
Console.Write("{0,2} ", i)
iteration += 1
If iteration > MAX_ITER Then Exit For
Next
Console.WriteLine()
End Sub
End Module |
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
| #CLU | CLU | start_up = proc ()
po: stream := stream$primary_output()
words: array[string] := array[string]$
["enemy", "lasagna", "robust", "below", "wax"]
for word: string in array[string]$elements(words) do
stream$putl(po, word)
end
end start_up |
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
| #CMake | CMake | set(list one.c two.c three.c)
foreach(file ${list})
message(${file})
endforeach(file) |
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
| #Befunge | Befunge | v 1 >$0 v v <
>&:19+`|v < >v 5 6 7 8
^ \ <>09p19p>09g+09p:|>2*:19+%19g+19p19+/19g+19p:|
2 3 4 > v
v"invalid"<10 9
|%+91+g91g90<
v "valid"<
>:#,_@
11
|
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).
| #Forth | Forth | : lucas-lehmer
1+ 2 do
4 i 2 <> * abs swap 1+ dup + 1- swap
i 1- 1 ?do dup * 2 - over mod loop 0= if ." M" i . then
loop cr
;
1 15 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.
| #Julia | Julia | function compressLZW(decompressed::String)
dictsize = 256
dict = Dict{String,Int}(string(Char(i)) => i for i in 0:dictsize)
result = Vector{Int}(undef, 0)
w = ""
for c in decompressed
wc = string(w, c)
if haskey(dict, wc)
w = wc
else
push!(result, dict[w])
dict[wc] = dictsize
dictsize += 1
w = string(c)
end
end
if !isempty(w) push!(result, dict[w]) end
return result
end
function decompressLZW(compressed::Vector{Int})
dictsize = 256
dict = Dict{Int,String}(i => string('\0' + i) for i in 0:dictsize)
result = IOBuffer()
w = string(Char(popfirst!(compressed)))
write(result, w)
for k in compressed
if haskey(dict, k)
entry = dict[k]
elseif k == dictsize
entry = string(w, w[1])
else
error("bad compressed k: $k")
end
write(result, entry)
dict[dictsize] = string(w, entry[1])
dictsize += 1
w = entry
end
return String(take!(result))
end
original = ["0123456789", "TOBEORNOTTOBEORTOBEORNOT", "dudidudidudida"]
compressed = compressLZW.(original)
decompressed = decompressLZW.(compressed)
for (word, comp, decomp) in zip(original, compressed, decompressed)
comprate = (length(word) - length(comp)) / length(word) * 100
println("Original: $word\n-> Compressed: $comp (compr.rate: $(round(comprate, digits=2))%)\n-> Decompressed: $decomp")
end |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Perl | Perl | use List::Util qw(sum);
for $test (
[[1, 3, 5],
[2, 4, 7],
[1, 1, 0]],
[[11, 9, 24, 2],
[ 1, 5, 2, 6],
[ 3, 17, 18, 1],
[ 2, 5, 7, 1]]
) {
my($P, $AP, $L, $U) = lu(@$test);
say_it('A matrix', @$test);
say_it('P matrix', @$P);
say_it('AP matrix', @$AP);
say_it('L matrix', @$L);
say_it('U matrix', @$U);
}
sub lu {
my (@a) = @_;
my $n = +@a;
my @P = pivotize(@a);
my $AP = mmult(\@P, \@a);
my @L = matrix_ident($n);
my @U = matrix_zero($n);
for $i (0..$n-1) {
for $j (0..$n-1) {
if ($j >= $i) {
$U[$i][$j] = $$AP[$i][$j] - sum map { $U[$_][$j] * $L[$i][$_] } 0..$i-1;
} else {
$L[$i][$j] = ($$AP[$i][$j] - sum map { $U[$_][$j] * $L[$i][$_] } 0..$j-1) / $U[$j][$j];
}
}
}
return \@P, $AP, \@L, \@U;
}
sub pivotize {
my(@m) = @_;
my $size = +@m;
my @id = matrix_ident($size);
for $i (0..$size-1) {
my $max = $m[$i][$i];
my $row = $i;
for $j ($i .. $size-2) {
if ($m[$j][$i] > $max) {
$max = $m[$j][$i];
$row = $j;
}
}
($id[$row],$id[$i]) = ($id[$i],$id[$row]) if $row != $i;
}
@id
}
sub matrix_zero { my($n) = @_; map { [ (0) x $n ] } 0..$n-1 }
sub matrix_ident { my($n) = @_; map { [ (0) x $_, 1, (0) x ($n-1 - $_) ] } 0..$n-1 }
sub mmult {
local *a = shift;
local *b = shift;
my @p = [];
my $rows = @a;
my $cols = @{ $b[0] };
my $n = @b - 1;
for (my $r = 0 ; $r < $rows ; ++$r) {
for (my $c = 0 ; $c < $cols ; ++$c) {
$p[$r][$c] += $a[$r][$_] * $b[$_][$c] foreach 0 .. $n;
}
}
return [@p];
}
sub say_it {
my($message, @array) = @_;
print "$message\n";
$line = sprintf join("\n" => map join(" " => map(sprintf("%8.5f", $_), @$_)), @{+\@array})."\n";
$line =~ s/\.00000/ /g;
$line =~ s/0000\b/ /g;
print "$line\n";
}
|
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.
| #Rust | Rust | [package]
name = "lychrel"
version = "0.1.0"
authors = ["monsieursquirrel"]
[dependencies]
num = "0.1.27" |
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
| #Pike | Pike | #!/usr/bin/pike
Stdio.Readline readln = Stdio.Readline();
void print_help()
{
write(#"Write a Story.
Names or objects in the story can be made variable by
referencing them as <person> <object>, etc.
End the story with an empty line.
Type show to read the story. You will be asked to fill the variables,
and the the story will be shown.
Type help to see this message again.
Type exit to quit.
");
}
void add_line(string input)
{
array variables = parse_for_variables(input);
write("Found variables: %{\"%s\" %}\n", variables);
story += input+"\n";
}
array parse_for_variables(string input)
{
array vars = Array.flatten(array_sscanf(input, "%*[^<>]%{<%[^<>]>%*[^<>]%}%*[^<>]"));
return Array.uniq(vars);
}
mapping fill_variables(string story)
{
array vars = parse_for_variables(story);
mapping variables = ([]);
foreach(vars;; string name)
{
string value = readln->read(sprintf("Please name a%s %s: ", (<'a','e','i','o','u'>)[name[1]]?"":"n", name));
if (value != "")
variables["<"+name+">"] = value;
}
return variables;
}
void show_story(string story)
{
mapping variables = fill_variables(story);
write("\n"+replace(story, variables));
}
void do_exit()
{
exit(0);
}
mapping functions = ([ "help":print_help,
"show":show_story,
"exit":do_exit,
]);
string story = "";
void main()
{
Stdio.Readline.History readline_history = Stdio.Readline.History(512);
readln->enable_history(readline_history);
string prompt="> ";
print_help();
while(1)
{
string input=readln->read(prompt);
if(!input)
exit(0);
if(input == "")
show_story(story);
else if (functions[input])
functions[input]();
else add_line(input);
}
} |
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
| #Go | Go | package main
import(
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func isPrime(n uint64) bool {
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
d := uint64(5)
for d * d <= n {
if n % d == 0 {
return false
}
d += 2
if n % d == 0 {
return false
}
d += 4
}
return true
}
const limit = 42
func main() {
p := message.NewPrinter(language.English)
for i, n := uint64(limit), 0; n < limit; i++ {
if isPrime(i) {
n++
p.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
| #BBC_BASIC | BBC BASIC | REPEAT
PRINT "SPAM"
UNTIL FALSE |
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
| #bc | bc | while (1) "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
| #M2000_Interpreter | M2000 Interpreter | Module MultipleLoop {
def long prod=1, sum=0, x=+5,y=-5, z=-2, one=1, three=3, seven=7, j
Range=lambda (a, b, c=1) ->{
=lambda a, b, c (&f)-> {
if compare(a,b)=sgn(c) then =false else =true: f=a: a+=c
}
}
MultipleRange=Lambda -> {
a=array([]) ' convert stack items in current stack [] to an array of items
=lambda a, k=0 (&f) ->{
do : if k<len(a) Else exit
if a#eval(k, &f) then =true: exit
k++ : always
}
}
Exec=MultipleRange(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+one))
j=0
while Exec(&j)
sum+=abs(j)
if abs(prod) < 2^27 And j <> 0 then prod*=j
End While
Print "sum=";sum
Print "prod=";prod
}
MultipleLoop
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | prod = 1;
sum = 0;
x = 5;
y = -5;
z = -2;
one = 1;
three = 3;
seven = 7;
Do[
sum += Abs[j];
If[Abs[prod] < 2^27 \[And] j != 0, prod *= j];
,
{j,
Join[
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 + one]
]
}
]
sum
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
| #blz | blz | num = 1024
while num > 1 # blz will automatically cast num to a fraction when dividing 1/2, so this is necessary to stop an infinite loop
print(num)
num = num / 2
end |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #BQN | BQN | _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(⌊∘÷⟜2 •Show) _while_ (>⟜0) 1024 |
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
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
DEF-MAIN
CLR-SCR
SET(i, 10)
LOOP(ciclo abajo)
PRNL(i)
BACK-IF-NOT-ZERO(i--, ciclo abajo)
END
|
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AmigaE | AmigaE | PROC main()
DEF i
FOR i := 10 TO 0 STEP -1
WriteF('\d\n', i)
ENDFOR
ENDPROC |
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.
| #Agena | Agena | scope
local i := 0;
do
inc i, 1;
print( i )
as ( i % 6 ) <> 0
epocs |
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_60 | ALGOL 60 | INTEGER I,J;
FOR I:=1 STEP 1 UNTIL 5 DO
BEGIN
FOR J:=1 STEP 1 UNTIL I DO
OUTTEXT("*");
OUTLINE
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
| #AppleScript | AppleScript | repeat with i from 2 to 10 by 2
log i
end repeat |
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.
| #PL.2FSQL | PL/SQL | SET SERVEROUTPUT ON
DECLARE
c_limit CONSTANT PLS_INTEGER := 25000;
TYPE t_nums IS TABLE OF PLS_INTEGER INDEX BY PLS_INTEGER;
v_nums t_nums;
v_ludic t_nums;
v_count_ludic PLS_INTEGER;
v_count_pos PLS_INTEGER;
v_pos PLS_INTEGER;
v_next_ludic PLS_INTEGER;
FUNCTION is_ludic(p_num PLS_INTEGER) RETURN BOOLEAN IS
BEGIN
FOR i IN 1..v_ludic.COUNT LOOP
EXIT WHEN v_ludic(i) > p_num;
IF v_ludic(i) = p_num THEN
RETURN TRUE;
END IF;
END LOOP;
RETURN FALSE;
END;
BEGIN
FOR i IN 1..c_limit LOOP
v_nums(i) := i;
END LOOP;
v_count_ludic := 1;
v_next_ludic := 1;
v_ludic(v_count_ludic) := v_next_ludic;
v_nums.DELETE(1);
WHILE v_nums.COUNT > 0 LOOP
v_pos := v_nums.FIRST;
v_next_ludic := v_nums(v_pos);
v_count_ludic := v_count_ludic + 1;
v_ludic(v_count_ludic) := v_next_ludic;
v_count_pos := 0;
WHILE v_pos IS NOT NULL LOOP
IF MOD(v_count_pos, v_next_ludic) = 0 THEN
v_nums.DELETE(v_pos);
END IF;
v_pos := v_nums.NEXT(v_pos);
v_count_pos := v_count_pos + 1;
END LOOP;
END LOOP;
DBMS_OUTPUT.put_line('Generate and show here the first 25 ludic numbers.');
FOR i IN 1..25 LOOP
DBMS_OUTPUT.put(v_ludic(i) || ' ');
END LOOP;
DBMS_OUTPUT.put_line('');
DBMS_OUTPUT.put_line('How many ludic numbers are there less than or equal to 1000?');
v_count_ludic := 0;
FOR i IN 1..v_ludic.COUNT LOOP
EXIT WHEN v_ludic(i) > 1000;
v_count_ludic := v_count_ludic + 1;
END LOOP;
DBMS_OUTPUT.put_line(v_count_ludic);
DBMS_OUTPUT.put_line('Show the 2000..2005''th ludic numbers.');
FOR i IN 2000..2005 LOOP
DBMS_OUTPUT.put(v_ludic(i) || ' ');
END LOOP;
DBMS_OUTPUT.put_line('');
DBMS_OUTPUT.put_line('A triplet is any three numbers x, x + 2, x + 6 where all three numbers are also ludic numbers.');
DBMS_OUTPUT.put_line('Show all triplets of ludic numbers < 250 (Stretch goal)');
FOR i IN 1..v_ludic.COUNT LOOP
EXIT WHEN (v_ludic(i)+6) >= 250;
IF is_ludic(v_ludic(i)+2) AND is_ludic(v_ludic(i)+6) THEN
DBMS_OUTPUT.put_line(v_ludic(i) || ', ' || (v_ludic(i)+2) || ', ' || (v_ludic(i)+6));
END IF;
END LOOP;
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
| #C.2B.2B | C++ | #include <iostream>
int main()
{
int i;
for (i = 1; i<=10 ; i++){
std::cout << i;
if (i < 10)
std::cout << ", ";
}
return 0;
}
|
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
| #Chapel | Chapel | for i in 1..10 do
write(i, if i % 10 > 0 then ", " else "\n") |
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
| #C.2B.2B | C++ | #include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #Vlang | Vlang | struct Seq {
start int
stop int
incr int
comment string
}
const examples = [
Seq{-2, 2, 1, "Normal"},
Seq{-2, 2, 0, "Zero increment"},
Seq{-2, 2, -1, "Increments away from stop value"},
Seq{-2, 2, 10, "First increment is beyond stop value"},
Seq{2, -2, 1, "Start more than stop: positive increment"},
Seq{2, 2, 1, "Start equal stop: positive increment"},
Seq{2, 2, -1, "Start equal stop: negative increment"},
Seq{2, 2, 0, "Start equal stop: zero increment"},
Seq{0, 0, 0, "Start equal stop equal zero: zero increment"},
]
fn sequence(s Seq, limit int) []int {
mut seq := []int{}
for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
seq << i
}
return seq
}
fn main() {
limit := 10
for ex in examples {
println(ex.comment)
print("Range($ex.start, $ex.stop, $ex.incr) -> ")
println(sequence(ex, limit))
println('')
}
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #Wren | Wren | import "/fmt" for Fmt
var loop = Fn.new { |start, stop, inc|
System.write("%(Fmt.v("dm", 3, [start, stop, inc], 0, " ", "[]")) -> ")
var count = 0
var limit = 10
var i = start
while (i <= stop) {
System.write("%(i) ")
count = count + 1
if (count == limit) break
i = i + inc
}
System.print()
}
var tests = [
[-2, 2, 1], [-2, 2, 0], [-2, 2, -1], [-2, 2, 10], [2, -2, 1], [2, 2, 1], [2, 2, -1], [2, 2, 0], [0, 0, 0]
]
for (test in tests) loop.call(test[0], test[1], test[2]) |
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
| #COBOL | COBOL | 01 things occurs 3.
...
set content of things to ("Apple", "Banana", "Coconut")
perform varying thing as string through things
display thing
end-perform |
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
| #ColdFusion | ColdFusion |
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfoutput>#i#!</Cfoutput>
</Cfloop>
|
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
| #BQN | BQN | Luhn ← (0=10|⊢)∘(+´(10|⊢)+⊢≥10˙)∘(⊢×≠⥊1‿2˙)∘(⌽•Fmt-'0'˙)
(⍉⊢≍Luhn¨) ⟨49927398716,49927398717,1234567812345678,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).
| #Alternate_version_to_handle_64_and_128_bit_integers. | Alternate version to handle 64 and 128 bit integers. |
18 constant π-64 \ count of primes < 64
31 constant π-128 \ count of primes < 128
create primes
2 c, 3 c, 5 c, 7 c, 11 c, 13 c, 17 c, 19 c, 23 c, 29 c,
31 c, 37 c, 41 c, 43 c, 47 c, 53 c, 59 c, 61 c, 67 c, 71 c,
73 c, 79 c, 83 c, 89 c, 97 c, 101 c, 103 c, 107 c, 109 c, 113 c,
127 c,
\ Lucas-Lehmer single precision test for 64 bit integers.
\
: *mod >r um* r> ud/mod 2drop ;
: 3rd s" 2 pick" evaluate ; immediate
: 2^ 1 swap lshift ;
: lucas-lehmer? ( n -- n )
dup 3 <
if 2 =
else
dup 2^ 1- 4
rot 2 do dup 3rd *mod 2 - loop 0= nip
then ;
: .mersenne64 ( -- )
primes π-64 bounds do
i c@ lucas-lehmer?
if 'M emit i c@ . then
loop ;
\ Lucas-Lehmer double precision test for 128 bit integers.
\
: 4dup 2over 2over ;
: 2-3rd 5 pick 5 pick ;
: d2^ ( n -- d )
dup 64 <
if 2^ 0
else 0 swap 64 - 2^
then ;
: d+mod ( d1 d2 d3 -- d ) \ d1 + d2 (mod d3); d1, d2 < d3
2-3rd 2over 2swap d- \ d1 d2 d3 -- d1 d2 d3 d3-d1
2-3rd d> \ if d2 < d3-d1 then don't subtract the modulus.
if 2drop 0.
then d- d+ ;
: d-even? ( d -- f )
drop 1 and 0= ;
: d*mod ( d1 d2 d3 -- d )
2>r 0. \ result
begin 2over d0> while
2over d-even? invert if 2-3rd 2r@ d+mod then
2swap d2/ 2swap
2rot 2dup 2r@ d+mod 2rot 2rot
repeat 2rdrop 2nip 2nip ;
: d-lucas-lehmer? ( n -- n )
dup 3 <
if 2 =
else
dup d2^ 1. d- 4.
4 roll 2 do 2dup 2-3rd d*mod 2. d- loop d0= nip nip
then ;
: .mersenne128 ( -- )
primes π-128 bounds do
i c@ d-lucas-lehmer?
if 'M emit i c@ . then
loop ;
|
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.
| #Kotlin | Kotlin | // version 1.1.2
object Lzw {
/** Compress a string to a list of output symbols. */
fun compress(uncompressed: String): MutableList<Int> {
// Build the dictionary.
var dictSize = 256
val dictionary = mutableMapOf<String, Int>()
(0 until dictSize).forEach { dictionary.put(it.toChar().toString(), it)}
var w = ""
val result = mutableListOf<Int>()
for (c in uncompressed) {
val wc = w + c
if (dictionary.containsKey(wc))
w = wc
else {
result.add(dictionary[w]!!)
// Add wc to the dictionary.
dictionary.put(wc, dictSize++)
w = c.toString()
}
}
// Output the code for w
if (!w.isEmpty()) result.add(dictionary[w]!!)
return result
}
/** Decompress a list of output symbols to a string. */
fun decompress(compressed: MutableList<Int>): String {
// Build the dictionary.
var dictSize = 256
val dictionary = mutableMapOf<Int, String>()
(0 until dictSize).forEach { dictionary.put(it, it.toChar().toString())}
var w = compressed.removeAt(0).toChar().toString()
val result = StringBuilder(w)
for (k in compressed) {
var entry: String
if (dictionary.containsKey(k))
entry = dictionary[k]!!
else if (k == dictSize)
entry = w + w[0]
else
throw IllegalArgumentException("Bad compressed k: $k")
result.append(entry)
// Add w + entry[0] to the dictionary.
dictionary.put(dictSize++, w + entry[0])
w = entry
}
return result.toString()
}
}
fun main(args: Array<String>) {
val compressed = Lzw.compress("TOBEORNOTTOBEORTOBEORNOT")
println(compressed)
val decompressed = Lzw.decompress(compressed)
println(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
| #Phix | Phix | with javascript_semantics
function matrix_mul(sequence a, sequence b)
if length(a[1]) != length(b) then
return 0
end if
sequence c = repeat(repeat(0,length(b[1])),length(a))
for i=1 to length(a) do
for j=1 to length(b[1]) do
for k=1 to length(a[1]) do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end function
function pivotize(sequence m)
integer n = length(m)
sequence im = repeat(repeat(0,n),n)
for i=1 to n do
im[i][i] = 1
end for
for i=1 to n do
atom mx = m[i][i]
integer row = i
for j=i to n do
if m[j][i]>mx then
mx = m[j][i]
row = j
end if
end for
if i!=row then
{im[i],im[row]} = {im[row],im[i]}
end if
end for
return im
end function
function lu(sequence a)
integer n = length(a)
sequence l = repeat(repeat(0,n),n),
u = repeat(repeat(0,n),n),
p = pivotize(a),
a2 = matrix_mul(p,a)
for j=1 to n do
l[j][j] = 1.0
for i=1 to j do
atom sum1 = 0.0
for k=1 to i do
sum1 += u[k][j] * l[i][k]
end for
u[i][j] = a2[i][j] - sum1
end for
for i=j+1 to n do
atom sum2 = 0.0
for k=1 to j do
sum2 += u[k][j] * l[i][k]
end for
l[i][j] = (a2[i][j] - sum2) / u[j][j]
end for
end for
return {a, l, u, p}
end function
constant a = {{{1, 3, 5},
{2, 4, 7},
{1, 1, 0}},
{{11, 9,24, 2},
{ 1, 5, 2, 6},
{ 3,17,18, 1},
{ 2, 5, 7, 1}}}
for i=1 to length(a) do
?"== a,l,u,p: =="
pp(lu(a[i]),{pp_Nest,2,pp_Pause,0})
end for
|
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.
| #Scala | Scala | import scala.collection.mutable.LinkedHashMap
val range = 1 to 10000
val maxIter = 500;
def lychrelSeq( seed:BigInt ) : Stream[BigInt] = {
def reverse( v:BigInt ) = BigInt(v.toString.reverse)
def isPalindromic( v:BigInt ) = { val s = (v + reverse(v)).toString; s == s.reverse }
def loop( v:BigInt ):Stream[BigInt] = v #:: loop( v + reverse(v) )
val seq = loop(seed)
seq.take( seq.take(maxIter).indexWhere( isPalindromic(_) ) match {
case -1 => maxIter
case n => n + 1
})
}
// A quick test
assert( lychrelSeq(56).length == 1 )
assert( lychrelSeq(57).length == 2 )
assert( lychrelSeq(59).length == 3 )
assert( lychrelSeq(89).length == 24 )
assert( lychrelSeq(10911).length == 55 )
val lychrelNums = for( n <- range if lychrelSeq(n).length == maxIter ) yield n
val (seeds,related) = {
val lycs = LinkedHashMap[BigInt,Int]()
// Fill the Map not allowing duplicate values
lychrelNums.foreach{ n => val ll = lychrelSeq(n).map( (_ -> n) ); LinkedHashMap( ll:_* ) ++= lycs }
for( n <- lychrelNums ) {
val ll = lychrelSeq(n).map( (_ -> n) )
val mm = LinkedHashMap( ll:_* )
lycs ++= (mm ++= lycs)
}
// Group by the Lychrel Number
val zz = lycs.groupBy{ _._2 }.map{ case (k,m) => k -> m.keys.toList.sorted }
// Now, group by size, seeds will have 500 or maxIter
val yy = lychrelNums.groupBy( n => zz.filterKeys(_==n).values.flatten.size < maxIter )
// Results: seeds are false, related true
(yy.filterKeys(_ == false).values.toVector.flatten,
yy.filterKeys(_ == true).values.toVector.flatten)
}
val lychrelPals = for( n <- lychrelNums; if n.toString == n.toString.reverse ) yield n
// Show the results
{
println( s"There are ${lychrelNums.size} Lychrel Numbers between ${range.min} and ${range.max} \n when limited to $maxIter iterations:" )
println
println( s"\t Seeds: ${seeds.size} (${seeds.mkString(", ")})" )
println( s"\tRelated Count: ${related.size}" )
println( s"\t Palindromes: (${lychrelPals.mkString(", ")})")
} |
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
| #PL.2FI | PL/I | (stringrange, stringsize): /* 2 Nov. 2013 */
Mad_Libs: procedure options (main);
declare (line, left, right) character (100) varying;
declare true bit(1) value ('1'b), false bit (1) value ('0'b);
declare name character (20) varying, seen_name bit (1) initial (false);
declare pronoun character (20) varying, seen_pronoun bit (1) initial (false);
declare noun character (20) varying, seen_noun bit (1) initial (false);
declare replaced_all bit (1);
declare in file input;
open file (in) title ('/MADLIBS.DAT,type(text),recsize(100)');
do forever;
get file (in) edit (line) (L);
if line = '' then leave;
do until (replaced_all);
replaced_all = true;
if index(line, '<name>') > 0 then
if seen_name then
do until (index(line, '<name>') = 0);
call split(line, '<name>', left, right);
line = left || name || right;
replaced_all = false;
end;
else
do;
put skip list ('Please type a name:');
get edit (name) (L);
seen_name = true; replaced_all = false;
end;
if index(line, '<he or she>') > 0 then
if seen_pronoun then
do until (index(line, '<he or she>') = 0);
call split(line, '<he or she>', left, right);
line = left || pronoun || right;
replaced_all = false;
end;
else
do;
put skip list ('Please type a pronoun (he or she):');
get edit (pronoun) (L);
seen_pronoun = true; replaced_all = false;
end;
if index(line, '<noun>') > 0 then
if seen_noun then
do until (index(line, '<noun>') = 0);
call split(line, '<noun>', left, right);
line = left || noun || right;
replaced_all = false;
end;
else
do;
put skip list ('Please type a noun:');
get edit (noun) (L);
seen_noun = true; replaced_all = false;
end;
end;
put skip list (line);
end;
split: procedure (line, text, Left, Right);
declare (line, text, left, right) character (*) varying;
declare i fixed binary;
i = index(line, text);
left = substr(line, 1, i-1);
right = substr(line, i+length(text), length(line) - (i + length(text)) + 1 );
end split;
end 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
| #Haskell | Haskell | import Data.List
import Control.Monad (guard)
isPrime :: Int -> Bool
isPrime n
| n <= 3 = n > 1
| n `mod` 2 == 0 || n `mod` 3 == 0 = False
| otherwise = l2 5 n
where l2 d n = x > n || l3 d n
where x = d * d
l3 d n
| n `mod` d == 0 = False
| n `mod` (d + 2) == 0 = False
| otherwise = l2 (d + 6) n
showPrime :: Int -> Int -> [(Int, Int)]
showPrime i n = if isPrime i
then (n, i) : showPrime (i+i) (n+1)
else showPrime (i+1) n
digitGroup :: Int -> String
digitGroup = intercalate "," . reverse . map show . unfoldr (\n -> guard (n /= 0) >> pure (n `mod` 1000, n `div` 1000))
display :: (Int, Int) -> String
display (i, p) = show i ++ " " ++ digitGroup p
main = mapM_ (putStrLn . display) $ take 42 $ showPrime 42 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
| #BCPL | BCPL | get "libhdr"
let start() be writes("SPAM*N") repeat |
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
| #beeswax | beeswax | _>`SPA`p
bN`M`< |
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
| #Nim | Nim |
import math, strutils
var
prod = 1
sum = 0
let
x = +5
y = -5
z = -2
one = 1
three = 3
seven = 7
proc body(j: int) =
sum += abs(j)
if abs(prod) < 2^27 and j != 0: prod *= j
for j in countup(-three, 3^3, three): body(j)
for j in countup(-seven, seven, x): body(j)
for j in countup(555, 550 - y): body(j)
for j in countdown(22, -28, three): body(j)
for j in countup(1927, 1939): body(j)
for j in countdown(x, y, -z): body(j)
for j in countup(11^x, 11^x + one): body(j)
let s = ($sum).insertSep(',')
let p = ($prod).insertSep(',')
let m = max(s.len, p.len)
echo " sum = ", s.align(m)
echo "prod = ", p.align(m) |
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
| #Perl | Perl | use constant one => 1;
use constant three => 3;
use constant seven => 7;
use constant x => 5;
use constant yy => -5; # 'y' conflicts with use as equivalent to 'tr' operator (a carry-over from 'sed')
use constant z => -2;
my $prod = 1;
sub from_to_by {
my($begin,$end,$skip) = @_;
my $n = 0;
grep{ !($n++ % abs $skip) } $begin <= $end ? $begin..$end : reverse $end..$begin;
}
sub commatize {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,(-?)$/$1/;
$s = reverse $s;
}
for my $j (
from_to_by(-three,3**3,three),
from_to_by(-seven,seven,x),
555 .. 550 - yy,
from_to_by(22,-28,-three),
1927 .. 1939,
from_to_by(x,yy,z),
11**x .. 11**x+one,
) {
$sum += abs($j);
$prod *= $j if $j and abs($prod) < 2**27;
}
printf "%-8s %12s\n", 'Sum:', commatize $sum;
printf "%-8s %12s\n", 'Product:', commatize $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
| #Bracmat | Bracmat | 1024:?n & whl'(!n:>0 & out$!n & div$(!n.2):?n) |
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
| #Brat | Brat | i = 1024
while { i > 0 } {
p i
i = (i / 2).to_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
| #AppleScript | AppleScript | repeat with i from 10 to 0 by -1
log i
end repeat |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopdownward.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .ascii "Counter = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
mov r4,#10
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
subs r4,#1 @ decrement counter
bge 1b @ loop if greather
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#10
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaces in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
|
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.
| #Aime | Aime | integer a;
a = 0;
do {
a += 1;
o_integer(a);
o_byte('\n');
} while (a % 6 != 0); |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #ALGOL_68 | ALGOL 68 | FOR i TO 5 DO
TO i DO
print("*")
OD;
print(new line)
OD |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopstep2.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ MAXI, 20
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .ascii "Counter = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
mov r4,#0
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
add r4,#2 @ increment counter by 2
cmp r4,#MAXI @
ble 1b @ loop
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#10
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaces in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 ? r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr
|
http://rosettacode.org/wiki/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.
| #PowerShell | PowerShell |
# Start with a pool large enough to meet the requirements
$Pool = [System.Collections.ArrayList]( 2..22000 )
# Start with 1, because it's grandfathered in
$Ludic = @( 1 )
# While the size of the pool is still larger than the next Ludic number...
While ( $Pool.Count -gt $Pool[0] )
{
# Add the next Ludic number to the list
$Ludic += $Pool[0]
# Remove from the pool all entries whose index is a multiple of the next Ludic number
[math]::Truncate( ( $Pool.Count - 1 )/ $Pool[0])..0 | ForEach { $Pool.RemoveAt( $_ * $Pool[0] ) }
}
# Add the rest of the numbers in the pool to the list of Ludic numbers
$Ludic += $Pool.ToArray()
|
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
| #Clojure | Clojure |
; Functional version
(apply str (interpose ", " (range 1 11)))
; Imperative version
(loop [n 1]
(printf "%d" n)
(if (< n 10)
(do
(print ", ")
(recur (inc n)))))
|
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Loop-N-And-Half.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 99.
01 List PIC X(45).
PROCEDURE DIVISION.
PERFORM FOREVER
*> The list to display must be built up because using
*> DISPLAY adds an endline at the end automatically.
STRING FUNCTION TRIM(List) " " I INTO List
IF I = 10
EXIT PERFORM
END-IF
STRING FUNCTION TRIM(List) "," INTO List
ADD 1 TO I
END-PERFORM
DISPLAY List
GOBACK
. |
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
| #Chapel | Chapel | use Random;
var nums:[1..10, 1..10] int;
var rnd = new RandomStream();
[ n in nums ] n = floor(rnd.getNext() * 21):int;
delete rnd;
// this shows a clumsy explicit way of iterating, to actually create nested loops:
label outer for i in nums.domain.dim(1) {
for j in nums.domain.dim(2) {
write(" ", nums(i,j));
if nums(i,j) == 20 then break outer;
}
writeln();
} |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #Yabasic | Yabasic | data -2,2,1,"Normal",-2,2,0,"Zero increment",-2,2,-1,"Increments away from stop value"
data -2,2,10,"First increment is beyond stop value",2,-2,1,"Start more than stop: positive increment"
data 2,2,1,"Start equal stop: positive increment",2,2,-1,"Start equal stop: negative increment"
data 2,2,0,"Start equal stop: zero increment",0,0,0,"Start equal stop equal zero: zero increment"
for i = 1 to 9
contar = 0
read start, fin, inc, cmt$
print cmt$
print " Bucle de ", start, " a ", fin, " en incrementos de ", inc
for vr = start to fin step inc
print " Indice del bucle = ", vr
contar = contar + 1
if contar = 10 then
print " Saliendo de un bucle infinito"
break
endif
next vr
print " Bucle terminado\n\n"
next i
end |
http://rosettacode.org/wiki/Loops/Wrong_ranges | Loops/Wrong ranges | Loops/Wrong ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment.
The purpose of this task is to select the range syntax/function that would generate at least two increasing numbers when given a stop value more than the start value and a positive increment of less than half the difference. You are then to use that same syntax/function but with different parameters; and show, here, what would happen.
Use these values if possible:
start
stop
increment
Comment
-2
2
1
Normal
-2
2
0
Zero increment
-2
2
-1
Increments away from stop value
-2
2
10
First increment is beyond stop value
2
-2
1
Start more than stop: positive increment
2
2
1
Start equal stop: positive increment
2
2
-1
Start equal stop: negative increment
2
2
0
Start equal stop: zero increment
0
0
0
Start equal stop equal zero: zero increment
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
| #zkl | zkl | // zero increment (ie infnite loop) throws an error
// if stop is "*", the loop is has no end (ie infinite)
// stop is included unless step steps skips it
// if start > stop is a dead loop
// ranges ([a..b,c]) are lazy lists
fcn looper([(start,stop,increment)]){
print(" %3s %3s\t%2d --> ".fmt(start,stop,increment));
try{ foreach n in ([start..stop,increment]){ print(n," ") } }
catch{ print(__exception) }
println();
}
println("start stop increment");
T( T(-2,2,1),T(-2,2,0),T(-2,2,-1),T(-2,2,10),T( 2,-2,1),
T( 2,2,1),T( 2,2,-1),T( 2,2,0),T( 0,0,0),
T(0.0, (0.0).pi, 0.7853981633974483), T("a","e",1), T("e","a",1) )
.apply2(looper); // apply2 is apply (map) without saving results |
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
| #Common_Lisp | Common Lisp | (loop for i in list do (print i)) |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.