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.
| #Groovy | Groovy | def compress = { text ->
def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map }
def w = '', compressed = []
text.each { ch ->
def wc = "$w$ch"
if (dictionary[wc]) {
w = wc
} else {
compressed << dictionary[w]
dictionary[wc] = dictionary.size()
w = "$ch"
}
}
if (w) { compressed << dictionary[w] }
compressed
}
def decompress = { compressed ->
def dictionary = (0..<256).inject([:]) { map, ch -> map[ch] = "${(char)ch}"; map }
int dictSize = 128;
String w = "${(char)compressed[0]}"
StringBuffer result = new StringBuffer(w)
compressed.drop(1).each { k ->
String entry = dictionary[k]
if (!entry) {
if (k != dictionary.size()) throw new IllegalArgumentException("Bad compressed k $k")
entry = "$w${w[0]}"
}
result << entry
dictionary[dictionary.size()] = "$w${entry[0]}"
w = entry
}
result.toString()
} |
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
| #Maple | Maple |
A:=<<1.0|3.0|5.0>,<2.0|4.0|7.0>,<1.0|1.0|0.0>>:
LinearAlgebra:-LUDecomposition(A);
|
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Python | Python | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
#@functools.lru_cache(maxsize=2**20)
def reverse_int(num):
return int(str(num)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds"
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
#print(' Lychrel related:', ', '.join(str(n) for n in l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in 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
| #Pascal | Pascal |
Program Madlib; Uses DOS, crt; {See, for example, https://en.wikipedia.org/wiki/Mad_Libs}
{Reads the lines of a story but which also contain <xxx> sequences. For each value of xxx,
found as the lines of the story are read, a request is made for a replacement text.
The story is then written out with the corresponding replacements made.}
{Concocted by R.N.McLean (whom God preserve), Victoria university, NZ.}
Procedure Croak(gasp: string); {A dying message.}
Begin
Writeln(' Eurghfff...');
Writeln(Gasp);
HALT;
End;
var inf: text; {Drivelstuff.}
const StoryLimit = 66;TableLimit = 65; {Big enough.}
var Story: array[1..StoryLimit] of string; {Otherwise, use a temporary disc file.}
var Target,Replacement: array[1..TableLimit] of string;
var StoryLines,TableCount: integer; {Usage.}
Function Reading(var inf: text;var Aline: string): boolean;
Begin
Aline:='';
Reading:=true;
if eoln(inf) then Reading:=false {Agh! Why can't the read statement return true/false?}
else ReadLn(inf,Aline);
if Aline = '' then Reading:=false; {Specified that a blank line ends the story.}
End;
Procedure Inspect(text: string); Forward;{I'd rather have multi-pass compilation than deal with this.}
Procedure Table(it: string); {Check it as a target, and obtain its replacement.}
var i: integer; {A stepper.}
Begin
for i:=1 to TableCount do if it = Target[i] then exit; {Already in the table?}
if TableCount >= TableLimit then Croak('Too many table entries!'); {No. Room for another?}
inc(TableCount); {Yes.}
Target[TableCount]:=it; {Include the < and > to preclude partial matches.}
write('Enter your text for ',it,': '); {Pretty please?}
readln(Replacement[TableCount]); {Thus.}
Inspect(Replacement[TableCount]); {Enable full utilisation.}
End; {of Table.}
var InDeep: integer; {Counts inspection recursion.}
Procedure Inspect(text: string); {Look for <...> in text.}
var i: integer; {A stepper.}
var mark: integer; {Fingers the latest < in Aline.}
Begin
inc(InDeep); {Supply an opportunity, and fear the possibilities.}
if InDeep > 28 then Croak('Excessive recursion! Inspecting ' + text);
for i:=1 to Length(text) do {Now scan the line for trouble.}
if text[i] = '<' then mark:=i {Trouble starts here? Just mark its place.}
else if text[i] = '>' then {Trouble ends here?}
Table(copy(text,mark,i - mark + 1)); {Deal with it.}
dec(InDeep); {I'm done.}
End; {of Inspect.}
Procedure Swallow(Aline: string); {Add a line to the story, and inspect it for <...>.}
Begin
if StoryLines >= StoryLimit then Croak('Too many lines in the story!'); {Suspicion forever.}
inc(StoryLines); {Otherwise, this is safe.}
Story[StoryLines]:=Aline; {So save another line.}
Inspect(Aline); {Look for any <...> inclusions.}
End; {of Swallow.}
var Rolling: integer; {Counts rolling rolls.}
Procedure Roll(bumf: string); {Write a line, with amendments.}
var last,mark: integer; {Fingers for the scan.}
var hit: string; {Copied once.}
var i,it: integer; {Steppers.}
label hic; {Oh dear.}
Begin
inc(Rolling); {Here I go.}
if Rolling > 28 then Croak('Excessive recursion! Rolling ' + bumf); {Self-expansion is out.}
last:=0; {Where the previous text ended.}
for i:=1 to Length(bumf) do {Scan the text.}
if bumf[i] = '<' then mark:=i {Remember where a <...> starts.}
else if bumf[i] = '>' then {So that when the stopper is found,}
begin {It can be recognised.}
Write(copy(bumf,last + 1,mark - last - 1)); {Text up to the <.}
hit:=copy(bumf,mark,i - mark + 1); {Grab this once.}
for it:=1 to TableCount do {Search my table.}
if Target[it] = hit then {A match?}
begin {Yes!}
Roll(Replacement[it]); {Write this instead.}
goto hic; {There is no "exit loop" style statement.}
end; {"Exit" exits the procedure or function.}
hic:last:=i; {Advance the trailing finger.}
end; {On to the next character.}
Write(copy(bumf,last + 1,Length(bumf) - last)); {Text after the last >, possibly null.}
dec(Rolling); {I'm done.}
if Rolling <= 0 then WriteLn; {And if this is the first level, add a end-of-line.}
End; {of Roll.}
var inname: string; {For a file name.}
var Aline: string; {A scratchpad.}
var i: integer; {A stepper.}
BEGIN
InDeep:=0; {No inspections yet.}
Rolling:=0; {No output.}
inname:=ParamStr(1); {Perhaps the file name is specified as a run-time parameter.}
if inname = '' then inname:='Madlib.txt'; {If not, this will do.}
Assign(inf,inname); Reset(inf); {Open the input file.}
StoryLines:=0; TableCount:=0; {Prepare the counters.}
while reading(inf,Aline) do Swallow(Aline); {Read and inspect the story.}
close(inf); {Finished with input.}
for i:=1 to StoryLines do Roll(Story[i]); {Write the amended story.}
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
| #C.2B.2B | C++ |
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(double number)
{
for (double i = number - 1; i >= 2; i--) {
if (fmod(number, i) == 0)
return false;
}
return true;
}
int main()
{
double i = 42;
int n = 0;
while (n < 42)
{
if (isPrime(i))
{
n++;
cout.width(1); cout << left << "n = " << n;
//Only for Text Alignment
if (n < 10)
{
cout.width(40); cout << right << i << endl;
}
else
{
cout.width(39); cout << right << i << endl;
}
i += i - 1;
}
i++;
}
return 0;
} |
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
| #ALGOL_68 | ALGOL 68 | DO
printf($"SPAM"l$)
OD |
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
| #ALGOL_W | ALGOL W | begin
for i := 1 step 0 until 2 do write( "SPAM" )
end. |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #FutureBasic | FutureBasic |
window 1, @"Loops with Ranges", ( 0, 0, 400, 400 )
begin globals
NSInteger sum = 0
float prod = 1
end globals
local fn process( x as float )
sum += abs(x)
if abs(prod) < (2 ^ 27) and x <> 0 then prod = prod * x
end fn
NSInteger j
NSInteger x = 5, y = -5, z = -2
NSInteger one = 1, three = 3, seven = 7
for j = -three to (3 ^ 3) step three: fn process(j): next j
for j = -seven to seven step x: fn process(j): next j
for j = 555 to 550 - y: fn process(j): next j
for j = 22 to -28 step -three: fn process(j): next j
for j = 1927 to 1939: fn process(j): next j
for j = x to y step z: fn process(j): next j
for j = (11 ^ x) to (11 ^ x) + one: fn process(j): next j
print using " sum = ###,###"; sum
print using "prod =-####,###,###"; prod
HandleEvents
|
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
| #Go | Go | package main
import "fmt"
func pow(n int, e uint) int {
if e == 0 {
return 1
}
prod := n
for i := uint(2); i <= e; i++ {
prod *= n
}
return prod
}
func abs(n int) int {
if n >= 0 {
return n
}
return -n
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return " " + s
}
return "-" + s
}
func main() {
prod := 1
sum := 0
const (
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
)
p := pow(11, x)
var j int
process := func() {
sum += abs(j)
if abs(prod) < (1<<27) && j != 0 {
prod *= j
}
}
for j = -three; j <= pow(3, 3); j += three {
process()
}
for j = -seven; j <= seven; j += x {
process()
}
for j = 555; j <= 550-y; j++ {
process()
}
for j = 22; j >= -28; j -= three {
process()
}
for j = 1927; j <= 1939; j++ {
process()
}
for j = x; j >= y; j -= -z {
process()
}
for j = p; j <= p+one; j++ {
process()
}
fmt.Println("sum = ", commatize(sum))
fmt.Println("prod = ", 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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopwhile.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .ascii "" @ message result
sMessValeur: .fill 11, 1, ' '
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r4,#1024 @ loop counter
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display return line
lsr r4,#1 @ division by 2
cmp r4,#0 @ end ?
bgt 1b @ no ->begin loop one
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* 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 registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#0 @ final zero
strb r1,[r3,r4]
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 @ return
|
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
| #360_Assembly | 360 Assembly | * Loops/Downward for 27/07/2015
LOOPDOWN CSECT
USING LOOPDOWN,R12
LR R12,R15 set base register
BEGIN EQU *
* fisrt loop with a BXLE BXLE: Branch on indeX Low or Equal
LH R2,=H'11' from 10 (R2=11) index
LH R4,=H'-1' step -1 (R4=-1)
LH R5,=H'-1' to 0 (R5=-1)
LOOPI BXLE R2,R4,ELOOPI R2=R2+R4 if R2<=R5 goto ELOOPI
XDECO R2,BUFFER edit R2
XPRNT BUFFER,L'BUFFER print
B LOOPI
ELOOPI EQU *
* second loop with a BCT BCT: Branch on CounT
LA R2,10 index R2=10
LA R3,11 counter R3=11
LOOPJ XDECO R2,BUFFER edit R2
XPRNT BUFFER,L'BUFFER print
BCTR R2,0 R2=R2-1
ELOOPJ BCT R3,LOOPJ R3=R3-1 if R3<>0 goto LOOPI
RETURN XR R15,R15 set return code
BR R14 return to caller
BUFFER DC CL80' '
YREGS
END LOOPDOWN |
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.
| #360_Assembly | 360 Assembly | * Do-While
DOWHILE CSECT , This program's control section
BAKR 14,0 Caller's registers to linkage stack
LR 12,15 load entry point address into Reg 12
USING DOWHILE,12 tell assembler we use Reg 12 as base
XR 9,9 clear Reg 9 - divident value
LA 6,6 load divisor value 6 in Reg 6
LA 8,WTOLEN address of WTO area in Reg 8
LOOP DS 0H
LA 9,1(,9) add 1 to divident Reg 9
ST 9,FW2 store it
LM 4,5,FDOUBLE load into even/odd register pair
STH 9,WTOTXT store divident in text area
MVI WTOTXT,X'F0' first of two bytes zero
OI WTOTXT+1,X'F0' make second byte printable
WTO TEXT=(8) print it (Write To Operator macro)
DR 4,6 divide Reg pair 4,5 by Reg 6
LTR 5,5 test quotient (remainder in Reg 4)
BNZ RETURN if one: 6 iterations, exit loop.
B LOOP if zero: loop again.
RETURN PR , return to caller.
FDOUBLE DC 0FD
DC F'0'
FW2 DC F'0'
WTOLEN DC H'2' fixed WTO length of two
WTOTXT DC CL2' '
END DOWHILE |
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.
| #8th | 8th |
( ( '* putc ) swap times cr ) 1 5 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
| #Agena | Agena | for i from 2 to 8 by 2 do
print( i )
od |
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.
| #Pascal | Pascal | program lucid;
{$IFDEF FPC}
{$MODE objFPC} // useful for x64
{$ENDIF}
const
//66164 -> last < 1000*1000;
maxLudicCnt = 2005;//must be > 1
type
tDelta = record
dNum,
dCnt : LongInt;
end;
tpDelta = ^tDelta;
tLudicList = array of tDelta;
tArrdelta =array[0..0] of tDelta;
tpLl = ^tArrdelta;
function isLudic(plL:tpLl;maxIdx:nativeInt):boolean;
var
i,
cn : NativeInt;
Begin
//check if n is 'hit' by a prior ludic number
For i := 1 to maxIdx do
with plL^[i] do
Begin
//Mask read modify write reread
//dec(dCnt);IF dCnt= 0
cn := dCnt;
IF cn = 1 then
Begin
dcnt := dNum;
isLudic := false;
EXIT;
end;
dcnt := cn-1;
end;
isLudic := true;
end;
procedure CreateLudicList(var Ll:tLudicList);
var
plL : tpLl;
n,LudicCnt : NativeUint;
begin
// special case 1
n := 1;
Ll[0].dNum := 1;
plL := @Ll[0];
LudicCnt := 0;
repeat
inc(n);
If isLudic(plL,LudicCnt ) then
Begin
inc(LudicCnt);
with plL^[LudicCnt] do
Begin
dNum := n;
dCnt := n;
end;
IF (LudicCnt >= High(LL)) then
BREAK;
end;
until false;
end;
procedure firstN(var Ll:tLudicList;cnt: NativeUint);
var
i : NativeInt;
Begin
writeln('First ',cnt,' ludic numbers:');
For i := 0 to cnt-2 do
write(Ll[i].dNum,',');
writeln(Ll[cnt-1].dNum);
end;
procedure triples(var Ll:tLudicList;max: NativeUint);
var
i,
chk : NativeUint;
Begin
// special case 1,3,7
writeln('Ludic triples below ',max);
write('(',ll[0].dNum,',',ll[2].dNum,',',ll[4].dNum,') ');
For i := 1 to High(Ll) do
Begin
chk := ll[i].dNum;
If chk> max then
break;
If (ll[i+2].dNum = chk+6) AND (ll[i+1].dNum = chk+2) then
write('(',ll[i].dNum,',',ll[i+1].dNum,',',ll[i+2].dNum,') ');
end;
writeln;
writeln;
end;
procedure LastLucid(var Ll:tLudicList;start,cnt: NativeUint);
var
limit,i : NativeUint;
Begin
dec(start);
limit := high(Ll);
IF cnt >= limit then
cnt := limit;
if start+cnt >limit then
start := limit-cnt;
writeln(Start+1,'.th to ',Start+cnt+1,'.th ludic number');
For i := 0 to cnt-1 do
write(Ll[i+start].dNum,',');
writeln(Ll[start+cnt].dNum);
writeln;
end;
function CountLudic(var Ll:tLudicList;Limit: NativeUint):NativeUint;
var
i,res : NativeUint;
Begin
res := 0;
For i := 0 to High(Ll) do begin
IF Ll[i].dnum <= Limit then
inc(res)
else
BREAK;
CountLudic:= res;
end;
end;
var
LudicList : tLudicList;
BEGIN
setlength(LudicList,maxLudicCnt);
CreateLudicList(LudicList);
firstN(LudicList,25);
writeln('There are ',CountLudic(LudicList,1000),' ludic numbers below 1000');
LastLucid(LudicList,2000,5);
LastLucid(LudicList,maxLudicCnt,5);
triples(LudicList,250);//all-> (LudicList,LudicList[High(LudicList)].dNum);
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
| #ArnoldC | ArnoldC | IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE lessThanTen
YOU SET US UP @NO PROBLEMO
STICK AROUND lessThanTen
TALK TO THE HAND n
GET TO THE CHOPPER lessThanTen
HERE IS MY INVITATION 10
LET OFF SOME STEAM BENNET n
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE lessThanTen
TALK TO THE HAND ", "
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED |
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
| #Arturo | Arturo | print join.with:", " map 1..10 => [to :string] |
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
| #AWK | AWK | BEGIN {
rows = 5
columns = 5
# Fill ary[] with random numbers from 1 to 20.
for (r = 1; r <= rows; r++) {
for (c = 1; c <= columns; c++)
ary[r, c] = int(rand() * 20) + 1
}
# Find a 20.
b = 0
for (r = 1; r <= rows; r++) {
for (c = 1; c <= columns; c++) {
v = ary[r, c]
printf " %2d", v
if (v == 20) {
print
b = 1
break
}
}
if (b) break
print
}
} |
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
| #R | R | seq(from = -2, to = 2, by = 1)#Output: -2 -1 0 1 2
seq(from = -2, to = 2, by = 0)#Fails: "invalid '(to - from)/by'"
seq(from = -2, to = 2, by = -1)#Fails: As in the notes above - "Specifying to - from and by of opposite signs is an error."
seq(from = -2, to = 2, by = 10)#Output: -2
seq(from = 2, to = -2, by = 1)#Fails: Same as the third case.
seq(from = 2, to = 2, by = 1)#Output: 2
seq(from = 2, to = 2, by = -1)#Output: 2
seq(from = 2, to = 2, by = 0)#Output: 2
seq(from = 0, to = 0, by = 0)#Output: 0 |
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
| #AWK | AWK |
BEGIN {
split("Mary had a little lamb", strs, " ")
for(el in strs) {
print strs[el]
}
} |
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
| #BASIC | BASIC | OPTION COLLAPSE TRUE
FOR x$ IN "Hello cruel world"
PRINT x$
NEXT
FOR y$ IN "1,2,\"3,4\",5" STEP ","
PRINT y$
NEXT |
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
| #BASIC | BASIC | dim card$(5)
card$[1]="49927398716"
card$[2]="49927398717"
card$[3]="1234567812345678"
card$[4]="1234567812345670"
for test = 1 to 4
odd = True
sum = 0
for n = length(card$[test]) to 1 step -1
num = int(mid(card$[test],n,1))
if odd then
sum += num
odd = False
else
num *= 2
if num <= 9 then
sum += num
else
sum += int(left(string(num),1)) + int(right(string(num),1))
end if
odd = True
end if
next
if sum mod 10 = 0 then
print card$[test], "True"
else
print card$[test], "False"
end if
next test |
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).
| #Elixir | Elixir | defmodule LucasLehmer do
use Bitwise
def test do
for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} "
end
defp s(mp, 1), do: rem(4, mp)
defp s(mp, n) do
x = s(mp, n-1)
rem(x*x-2, mp)
end
end
LucasLehmer.test |
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.
| #Haskell | Haskell | import Data.List (elemIndex, tails)
import Data.Maybe (fromJust)
doLZW :: Eq a => [a] -> [a] -> [Int]
doLZW _ [] = []
doLZW as (x:xs) = lzw (return <$> as) [x] xs
where
lzw a w [] = [fromJust $ elemIndex w a]
lzw a w (x:xs)
| w_ `elem` a = lzw a w_ xs
| otherwise = fromJust (elemIndex w a) : lzw (a ++ [w_]) [x] xs
where
w_ = w ++ [x]
undoLZW :: [a] -> [Int] -> [a]
undoLZW _ [] = []
undoLZW a cs =
cs >>=
(!!)
(foldl
((.) <$> (++) <*>
(\x xs -> return (((++) <$> head <*> take 1 . last) ((x !!) <$> xs))))
(return <$> a)
(take2 cs))
take2 :: [a] -> [[a]]
take2 xs = filter ((2 ==) . length) (take 2 <$> tails xs)
main :: IO ()
main = do
print $ doLZW ['\0' .. '\255'] "TOBEORNOTTOBEORTOBEORNOT"
print $
undoLZW
['\0' .. '\255']
[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]
print $
((==) <*> ((.) <$> undoLZW <*> doLZW) ['\NUL' .. '\255'])
"TOBEORNOTTOBEORTOBEORNOT" |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | (*Ex1*)a = {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}};
{lu, p, c} = LUDecomposition[a];
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]];
u = UpperTriangularize[lu];
P = Part[IdentityMatrix[Length[p]], p] ;
MatrixForm /@ {P.a , P, l, u, l.u}
(*Ex2*)a = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
{lu, p, c} = LUDecomposition[a];
l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]];
u = UpperTriangularize[lu];
P = Part[IdentityMatrix[Length[p]], p] ;
MatrixForm /@ {P.a , P, l, u, l.u}
|
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.
| #R | R |
library(gmp)
library(magrittr)
cache <- NULL
cache_reset <- function() { cache <<- new.env(TRUE, emptyenv()) }
cache_set <- function(key, value) { assign(key, value, envir = cache) }
cache_get <- function(key) { get(key, envir = cache, inherits = FALSE) }
cache_has_key <- function(key) { exists(key, envir = cache, inherits = FALSE) }
# Initialize the cache
cache_reset()
isPalindromic <- function(num) {
paste0(unlist(strsplit(num,"")), collapse = "") ==
paste0(rev(unlist(strsplit(num,""))),collapse = "")
}
aStep <- function(num) {
num %>%
strsplit("") %>%
unlist() %>%
rev() %>%
paste0(collapse = "") %>%
sub("^0+","",.) %>%
as.bigz() %>%
'+'(num) %>%
as.character
}
max_search <- 10000
limit <- 500
related <- 0
lychrel <- vector("numeric")
palindrome_lychrel <- vector("numeric")
for (candidate in 1:max_search) {
n <- as.character(candidate)
found <- TRUE
for (iteration in 1:limit) {
n <- aStep(n)
if (cache_has_key(n)) {
related <- related + 1
found <- FALSE
if (isPalindromic(as.character(candidate))) palindrome_lychrel <- append(palindrome_lychrel, candidate)
break
}
if (isPalindromic(n)) {
found <- FALSE
break
}
}
if (found) {
if (isPalindromic(as.character(candidate))) palindrome_lychrel <- append(palindrome_lychrel, candidate)
lychrel <- append(lychrel,candidate)
seeds <- seeds + 1
n <- as.character(candidate)
for (iteration in 1:limit) {
cache_set(n,"seen")
n <- aStep(n)
}
}
}
cat("Lychrel numbers in the range [1, ",max_search,"]\n", sep = "")
cat("Maximum iterations =",limit,"\n")
cat("Number of Lychrel seeds:",length(lychrel),"\n")
cat("Lychrel numbers:",lychrel,"\n")
cat("Number of related Lychrel numbers found:",related,"\n")
cat("Number of palindromic Lychrel numbers:",length(palindrome_lychrel),"\n")
cat("Palindromic Lychrel numbers:",palindrome_lychrel,"\n")
|
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
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
my $template = shift;
open my $IN, '<', $template or die $!;
my $story = do { local $/ ; <$IN> };
my %blanks;
undef $blanks{$_} for $story =~ m/<(.*?)>/g;
for my $blank (sort keys %blanks) {
print "$blank: ";
chomp (my $replacement = <>);
$blanks{$blank} = $replacement;
}
$story =~ s/<(.*?)>/$blanks{$1}/g;
print $story; |
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
| #Common_Lisp | Common Lisp |
(defun primep (n) ; https://stackoverflow.com/questions/15817350/
(cond ((= 2 n) t) ; Hard-code "2 is a prime"
((= 3 n) t) ; Hard-code "3 is a prime"
((evenp n) nil) ; If we're looking at an even now, it's not a prime
(t ; If it is divisible by an odd number below its square root, it's not prime
(do* ((i 3 (incf i 2))) ; Initialize to 3 and increment by 2 on every loop
((or (> i (isqrt n)) ; Break condition index exceeds its square root
(zerop (mod n i))) ; Break condition it is divisible
(not (zerop (mod n i)))))))) ; Returns not divisible, aka prime
(do ((i 42) ; Initialize index to 42
(c 0)) ; Initialize count of primes to 0
((= c 42)) ; Break condition when there are 42 primes
(incf i) ; Increments index by unity
(if (primep i)(progn (incf c) ; If prime increment count of primes
(format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime
(incf i (decf i))))) ; Increment index to previous index plus the prime
|
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
| #AmigaE | AmigaE | PROC main()
LOOP
WriteF('SPAM')
ENDLOOP
ENDPROC |
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
| #AppleScript | AppleScript | repeat
log "SPAM"
end repeat |
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
| #Groovy | Groovy | def (prod, sum, x, y, z, one, three, seven) = [1, 0, +5, -5, -2, 1, 3, 7]
for (
j in (
((-three) .. (3**3) ).step(three)
+ ((-seven) .. (+seven) ).step(x)
+ (555 .. (550-y) )
+ (22 .. (-28) ).step(three) // This is correct!
// Groovy interprets positive step size as stride through the LIST ELEMENTS as ordered
// and negative step size as stride through the REVERSED LIST ELEMENTS as ordered
// so step(-3) gives: -28, -25, -22, ... , 20
// while step(3) gives: 22, 19, 16, ... , -26
+ (1927 .. 1939 )
+ (x .. y ).step(z)
+ (11**x .. (11**x + one))
)
) {
sum = sum + j.abs()
if ( prod.abs() < 2**27 && j != 0) prod *= j
}
println " sum= ${sum}"
println "prod= ${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
| #ArnoldC | ArnoldC | IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 1024
STICK AROUND n
TALK TO THE HAND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
HE HAD TO SPLIT 2
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED |
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
| #Arturo | Arturo | i: 1024
while [i>0] [
print i
i: i/2
] |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #6502_Assembly | 6502 Assembly | ;An OS/hardware specific routine that is setup to display the Ascii character
;value contained in the Accumulator
Send = $9000 ;routine not implemented here
PrintNewLine = $9050 ;routine not implemented here
*= $8000 ;set base address
Start PHA ;push Accumulator and Y register onto stack
TYA
PHA
LDY #10 ;set Y register to loop start value
TYA ;place loop value in the Accumulator
Loop JSR PrintTwoDigits
JSR PrintNewLine
DEY ;decrement loop value
BPL Loop ;continue loop if sign flag is clear
PLA ;pop Y register and Accumulator off of stack
TAY
PLA
RTS ;exit
;Print value in Accumulator as two hex digits
PrintTwoDigits
PHA
LSR
LSR
LSR
LSR
JSR PrintDigit
PLA
AND #$0F
JSR PrintDigit
RTS
;Convert value in Accumulator to an Ascii hex digit
PrintDigit
ORA #$30
JSR Send ;routine not implemented here
RTS |
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
| #68000_Assembly | 68000 Assembly | ForLoop:
MOVE.W #10,D0
loop:
JSR Print_D0_As_Ascii ;some routine that converts the digits of D0 into ascii characters and prints them to screen.
DBRA D0,loop ;repeat until D0.W = $FFFF
rts |
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.
| #6502_Assembly | 6502 Assembly | DoWhileSub: PHA
TYA
PHA ;push accumulator and Y register onto stack
LDY #0
DoWhileLoop: INY
JSR DisplayValue ;routine not implemented
TYA
SEC
Modulus: SBC #6
BCS Modulus
ADC #6
BNE DoWhileLoop
PLA
TAY
PLA ;restore Y register and accumulator from stack
RTS ;return from subroutine |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loop64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessX: .asciz "X"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
mov x2,0 // counter loop 1
1: // loop start 1
mov x1,0 // counter loop 2
2: // loop start 2
ldr x0,qAdrszMessX
bl affichageMess
add x1,x1,1 // x1 + 1
cmp x1,x2 // compare x1 x2
ble 2b // loop label 2 before
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x2,x2,1 // x2 + 1
cmp x2,#5 // for five loop
blt 1b // loop label 1 before
100: // standard end of the program */
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessX: .quad szMessX
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Aime | Aime | integer i;
i = 0;
while (i < 10) {
o_winteger(2, i);
i += 2;
}
o_newline(); |
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.
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
{ my @ludic = (1);
my $max = 3;
my @candidates;
sub sieve {
my $l = shift;
for (my $i = 0; $i <= $#candidates; $i += $l) {
splice @candidates, $i, 1;
}
}
sub ludic {
my ($type, $n) = @_;
die "Arg0 Type must be 'count' or 'max'\n"
unless grep $_ eq $type, qw( count max );
die "Arg1 Number must be > 0\n" if 0 >= $n;
return (@ludic[ 0 .. $n - 1 ]) if 'count' eq $type and @ludic >= $n;
return (grep $_ <= $n, @ludic) if 'max' eq $type and $ludic[-1] >= $n;
while (1) {
if (@candidates) {
last if ('max' eq $type and $candidates[0] > $n)
or ($n == @ludic);
push @ludic, $candidates[0];
sieve($ludic[-1] - 1);
} else {
$max *= 2;
@candidates = 2 .. $max;
for my $l (@ludic) {
sieve($l - 1) unless 1 == $l;
}
}
}
return (@ludic)
}
}
my @triplet;
my %ludic;
undef @ludic{ ludic(max => 250) };
for my $i (keys %ludic) {
push @triplet, $i if exists $ludic{ $i + 2 } and exists $ludic { $i + 6 };
}
say 'First 25: ', join ' ', ludic(count => 25);
say 'Count < 1000: ', scalar ludic(max => 1000);
say '2000..2005th: ', join ' ', (ludic(count => 2005))[1999 .. 2004];
say 'triplets < 250: ', join ' ',
map { '(' . join(' ',$_, $_ + 2, $_ + 6) . ')' }
sort { $a <=> $b } @triplet; |
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
| #AutoHotkey | AutoHotkey | Loop, 9 ; loop 9 times
{
output .= A_Index ; append the index of the current loop to the output var
If (A_Index <> 9) ; if it isn't the 9th iteration of the loop
output .= ", " ; append ", " to the output var
}
MsgBox, %output% |
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
| #AutoIt | AutoIt | #cs ----------------------------------------------------------------------------
AutoIt Version: 3.3.8.1
Author: Alexander Alvonellos
Script Function:
Output a comma separated list from 1 to 10, and on the tenth iteration of the
output loop, only perform half of the loop.
#ce ----------------------------------------------------------------------------
Func doLoopIterative()
Dim $list = ""
For $i = 1 To 10 Step 1
$list = $list & $i
If($i = 10) Then ExitLoop
$list = $list & ", "
Next
return $list & @CRLF
EndFunc
Func main()
ConsoleWrite(doLoopIterative())
EndFunc
main() |
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
| #BASIC | BASIC | DIM a(1 TO 10, 1 TO 10) AS INTEGER
CLS
FOR row = 1 TO 10
FOR col = 1 TO 10
a(row, col) = INT(RND * 20) + 1
NEXT col
NEXT row
FOR row = LBOUND(a, 1) TO UBOUND(a, 1)
FOR col = LBOUND(a, 2) TO UBOUND(a, 2)
PRINT a(row, col)
IF a(row, col) = 20 THEN END
NEXT col
NEXT row |
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
| #Racket | Racket | #lang racket
(require racket/sandbox)
(define tests '([-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"]))
(for ([test (in-list tests)])
(match-define (list st ed inc desc) test)
(printf "~a:\n (in-range ~a ~a ~a) = ~a\n\n"
desc st ed inc
(with-handlers ([exn:fail:resource? (thunk* 'timeout)])
(with-limits 1 #f
(sequence->list (in-range st ed inc)))))) |
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
| #Raku | Raku | # Given sequence definitions
# start stop inc. Comment
for -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
# Additional "problematic" sequences
1, Inf, 3, # Endpoint literally at infinity
0, π, τ/8, # Floating point numbers
1.4, *, -7.1 # Whatever
-> $start, $stop, $inc {
my $seq = flat ($start, *+$inc … $stop);
printf "Start: %3s, Stop: %3s, Increment: %3s | ", $start, $stop.Str, $inc;
# only show up to the first 15 elements of possibly infinite sequences
put $seq[^15].grep: +*.defined
}
# For that matter the start and end values don't need to be numeric either. Both
# or either can be a function, list, or other object. Really anything that a
# "successor" function can be defined for and produces a value.
say "\nDemonstration of some other specialized sequence operator functionality:";
# Start with a list, iterate by multiplying the previous 3 terms together
# and end with a term defined by a function.
put 1, -.5, 2.sqrt, * × * × * … *.abs < 1e-2;
# Start with an array, iterate by rotating, end when 0 is in the last place.
say [0,1,2,3,4,5], *.rotate(-1).Array … !*.tail;
# Iterate strings backwards.
put 'xp' … 'xf'; |
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
| #Batch_File | Batch File | @echo off
for %%A in (This is a sample collection) do (
echo %%A
) |
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
| #bc | bc | a[0] = .123
a[1] = 234
a[3] = 95.6
for (i = 0; i < 4; i++) {
a[i]
} |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call :luhn 49927398716
call :luhn 49927398717
call :luhn 1234567812345678
call :luhn 1234567812345670
exit /b 0
:luhn
set "input=%1"
set "cnt=0"
set "s1=0"
set "s2=0"
:digit_loop
set /a "cnt-=1"
set /a "isOdd=(-%cnt%)%%2"
if !isodd! equ 1 (
set /a "s1+=!input:~%cnt%,1!"
) else (
set /a "twice=!input:~%cnt%,1!*2"
if !twice! geq 10 (
set /a "s2+=!twice:~0,1!+!twice:~1,1!"
) else (
set /a "s2+=!twice!"
)
)
if "!input:~%cnt%!"=="!input!" (
set /a "sum=(!s1!+!s2!)%%10"
if !sum! equ 0 (echo !input! is valid.) else (echo !input! is not valid.)
goto :EOF
)
goto digit_loop |
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).
| #Erlang | Erlang | -module(mp).
-export([main/0]).
main() -> [ io:format("M~p ", [P]) || P <- lists:seq(2,700), (P == 2) orelse (s((1 bsl P) - 1, P-1) == 0) ].
s(MP,1) -> 4 rem MP;
s(MP,N) -> X=s(MP,N-1), (X*X - 2) rem MP. |
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.
| #J | J | encodeLZW =: 4 : 0
d=. ;/x
r=.0$0
wc=.w=.{.y
for_c. }.y do.
wc=.w,c
if. d e.~ <wc do. w=.wc else.
r=. r, d i.<w
d=.d,<wc
w=.c
end.
end.
r, d i.<w
) |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | A = [
1 3 5
2 4 7
1 1 0];
[L,U,P] = lu(A) |
http://rosettacode.org/wiki/Lychrel_numbers | Lychrel numbers | Take an integer n, greater than zero.
Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
Example
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens after an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called Lychrel numbers.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
Seed and related Lychrel numbers
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number might converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true Seed Lychrel number candidates, and Related numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
Task
Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
Print the number of seed Lychrels found; the actual seed Lychrels; and just the number of relateds found.
Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
References
What's special about 196? Numberphile video.
A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
Status of the 196 conjecture? Mathoverflow.
| #Racket | Racket | #lang racket
(require racket/splicing)
(define (reverse-digits_10 N)
(let inr ((n N) (m 0))
(match n
[0 m]
[(app (curryr quotient/remainder 10) q r)
(inr q (+ r (* 10 m)))])))
(define (palindrome?_10 n)
(= n (reverse-digits_10 n)))
;; hash of integer? -> one of 'seed 'related #f
(splicing-let ((memo# (make-hash)))
(define (generate-lychrel?-chain i i-rev n acc)
(cond
[(zero? n) ; out of steam
(cons 'seed acc)]
[else
(let* ((i+ (+ i i-rev)) (i+-rev (reverse-digits_10 i+)))
(cond
[(= i+ i+-rev) ; palindrome breaks the chain
(cons #f acc)]
[(eq? 'related (hash-ref memo# i+ #f)) ; deja vu
(cons 'related acc)]
[else ; search some more
(generate-lychrel?-chain i+ i+-rev (sub1 n) (cons i+ acc))]))]))
;; returns 'seed, 'related or #f depending of the Lychrel-ness of a number
(define (lychrel-number? i #:n (n 500))
(match (hash-ref memo# i 'unfound)
['unfound
(match (generate-lychrel?-chain i (reverse-digits_10 i) n null)
[(cons 'related chain) 'related]
[(cons (and seed (or (and 'seed (app (λ (_) 'related) related?))
(and #f (app (λ (_) #f) related?))))
chain)
(for ((c (in-list chain))) (hash-set! memo# c related?))
(hash-set! memo# i seed)
seed])]
[seed/related/false seed/related/false])))
(module+ main
(define-values (seeds/r n-relateds palindromes/r)
(for/fold ((s/r null) (r 0) (p/r null))
((i (in-range 1 (add1 10000))))
(define lych? (lychrel-number? i))
(define p/r+ (if (and lych? (palindrome?_10 i)) (cons (list i (list lych?)) p/r) p/r))
(match lych?
['seed (values (cons i s/r) r p/r+)]
['related (values s/r (add1 r) p/r+)]
[#f (values s/r r p/r+)])))
(printf #<<EOS
Seed Lychrel numbers: ~a count:~a
Related Lychrel numbers: count:~a
Palindromic Lychrel numbers: ~a~%
EOS
(reverse seeds/r) (length seeds/r) n-relateds (reverse palindromes/r))) |
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
| #Phix | Phix | without js -- file i/o, prompt_string
string mlfile = "", -- eg story.txt
mltxt = iff(length(mlfile)?join(read_lines(mlfile),"\n"):"""
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
""")
sequence strings = {}, replacements = {}
integer startpos, endpos=1
while 1 do
startpos = find('<',mltxt,endpos)
if startpos=0 then exit end if
endpos = find('>',mltxt,startpos)
if endpos=0 then ?"missing >" abort(0) end if
string s = mltxt[startpos..endpos]
if not find(s,strings) then
strings = append(strings,s)
replacements = append(replacements,prompt_string(sprintf("Enter replacement for %s:",{s})))
end if
end while
puts(1,substitute_all(mltxt,strings,replacements))
|
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
| #Delphi | Delphi |
program Increment_loop_index_within_loop_body;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function IsPrime(const a: UInt64): Boolean;
var
d: UInt64;
begin
if (a < 2) then
exit(False);
if (a mod 2) = 0 then
exit(a = 2);
if (a mod 3) = 0 then
exit(a = 3);
d := 5;
while (d * d <= a) do
begin
if (a mod d = 0) then
Exit(false);
inc(d, 2);
if (a mod d = 0) then
Exit(false);
inc(d, 4);
end;
Result := True;
end;
var
i, n: UInt64;
begin
FormatSettings.ThousandSeparator:= ',';
i := 42;
n := 0;
while (n < 42) do
begin
if (isPrime(i)) then
begin
inc(n);
Writeln('n = ', n: -20, ' ', floattostrF(i, ffNumber, 20,0):20);
i := 2 * i - 1;
end;
inc(i);
end;
readln;
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
| #ARM_Assembly | ARM Assembly |
.global main
main:
loop:
ldr r0, =message
bl printf
b loop
message:
.asciz "SPAM\n"
|
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ArnoldC | ArnoldC | IT'S SHOWTIME
STICK AROUND @NO PROBLEMO
TALK TO THE HAND "SPAM"
CHILL
YOU HAVE BEEN TERMINATED |
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
| #Haskell | Haskell | loop :: (b -> a -> b) -> b -> [[a]] -> b
loop = foldl . foldl
example = let
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
in
loop
-- body
(
\(sum, prod) j ->
(
sum + abs j,
if abs prod < 2^27 && j /= 0
then prod * j else prod
)
)
-- initial state
(0, 1)
-- ranges
[ [-three, -three + three .. 3^3]
, [-seven, -seven + x .. seven]
, [555 .. 550 - y]
, [22, 22 - three .. -28]
, [1927 .. 1939]
, [x, x + z .. y]
, [11^x .. 11^x + one] ] |
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
| #Asymptote | Asymptote | int i = 1024;
while(i > 0) {
write(i);
i = i # 2; //or also i = quotient(i, 2);
}
//# Integer division; equivalent to quotient(x,y).
//Noting that the Python3 community adopted the comment symbol (//) for integer division, the
//Asymptote community decided to reciprocate and use their comment symbol for integer division! |
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
| #ATS | ATS | #include "share/atspre_staload.hats"
fn
loop_while () : void =
let
fun
loop {n : int | 0 <= n} .<n>.
(n : uint n) : void =
if n <> 0U then
begin
println! (n);
loop (n / 2U)
end
in
loop 1024U
end
implement
main0 () =
loop_while () |
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
| #8086_Assembly | 8086 Assembly | .model small ;.exe file, max 128 KB
.stack 1024 ;reserve 1 KB for the stack pointer.
.data
;no data needed
.code
start:
mov ax,0100h ;UNPACKED BCD "10"
mov cx,0Bh ;loop counter
repeat_countdown:
call PrintBCD_IgnoreLeadingZeroes
sub ax,1
aas
;ascii adjust for subtraction, normally 0100h - 1 = 0FFh but this corrects it to 0009h
push ax
mov dl,13
mov ah,02h
int 21h
mov dl,10
mov ah,02h
int 21h
;these 6 lines of code are the "new line" function
pop ax
loop repeat_countdown ;decrement CX and jump back to the label "repeat_countdown" if CX != 0
mov ax,4C00h
int 21h ;return to DOS
PrintBCD_IgnoreLeadingZeroes:
push ax
cmp ah,0
jz skipLeadingZero
or ah,30h ;convert a binary-coded decimal quantity to an ASCII numeral
push dx
push ax
mov al,ah
mov ah,0Eh
int 10h ;prints AL to screen
pop ax
pop dx
skipLeadingZero:
or al,30h
push dx
push ax
mov ah,0Eh
int 10h
pop ax
pop dx
pop ax
ret
end start ;EOF |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopdowhile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Counter = @ \n" // message result
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,0 // indice
mov x21,6
1: // begin loop
mov x0,x20
ldr x1,qAdrsZoneConv // conversion value value
bl conversion10 // decimal
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display conversion
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x20,x20,1 // increment counter
udiv x0,x20,x21 // divide by 6
msub x1,x0,x21,x20 // compute remainder
cbnz x1,1b // loop if remainder <> zéro
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #Action.21 | Action! | Proc Main()
byte I,J
For I=1 to 5
Do
For J=1 to I
Do
Print("*")
Od
PrintE("")
Od
Return |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_60 | ALGOL 60 | for i:=5 step 5 until 25 do
OUTINTEGER(i)
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Phix | Phix | constant LUMAX = 25000
sequence ludic = repeat(1,LUMAX)
integer n
for i=2 to LUMAX/2 do
if ludic[i] then
n = 0
for j=i+1 to LUMAX do
n += ludic[j]
if n=i then
ludic[j] = 0
n = 0
end if
end for
end if
end for
sequence s = {}
for i=1 to LUMAX do
if ludic[i] then
s &= i
if length(s)=25 then exit end if
end if
end for
printf(1,"First 25 Ludic numbers: %s\n",{sprint(s)})
printf(1,"Ludic numbers below 1000: %d\n",{sum(ludic[1..1000])})
s = {}
n = 0
for i=1 to LUMAX do
if ludic[i] then
n += 1
if n>=2000 then
s &= i
if n=2005 then exit end if
end if
end if
end for
printf(1,"Ludic numbers 2000 to 2005: %s\n",{sprint(s)})
s = {}
for i=1 to 243 do
if ludic[i] and ludic[i+2] and ludic[i+6] then
s = append(s,{i,i+2,i+6})
end if
end for
printf(1,"There are %d Ludic triplets below 250: %s\n",{length(s),sprint(s)})
|
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AWK | AWK | $ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}' |
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
| #Axe | Axe | For(I,1,10)
Disp I▶Dec
If I=10
Disp i
Else
Disp ","
End
End |
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
| #BASIC256 | BASIC256 | dim a(20, 20)
for i = 0 to 19
for j = 0 to 19
a[i, j] = int(rand * 20) + 1
next j
next i
for i = 0 to 19
for j = 0 to 19
print a[i, j];" ";
if a[i, j] = 20 then end
next j
next i
end |
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
| #BBC_BASIC | BBC BASIC | DIM array(10,10)
FOR row% = 0 TO 10
FOR col% = 0 TO 10
array(row%,col%) = RND(20) + 1
NEXT
NEXT row%
FOR row% = 0 TO 10
FOR col% = 0 TO 10
PRINT "row "; row%, "col ";col%, "value "; array(row%,col%)
IF array(row%,col%) = 20 EXIT FOR row%
NEXT
NEXT row%
|
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
| #REXX | REXX | /*REXX program demonstrates several versions of DO loops with "unusual" iterations. */
@.=; @.1= ' -2 2 1 ' /*"normal". */
@.2= ' -2 2 0 ' /*"normal", zero increment.*/
@.3= ' -2 2 -1 ' /*increases away from stop, neg increment.*/
@.4= ' -2 2 10 ' /*1st increment > stop, positive increment.*/
@.5= ' 2 -2 1 ' /*start > stop, positive increment.*/
@.6= ' 2 2 1 ' /*start equals stop, positive increment.*/
@.7= ' 2 2 -1 ' /*start equals stop, negative increment.*/
@.8= ' 2 2 0 ' /*start equals stop, zero increment.*/
@.9= ' 0 0 0 ' /*start equals stop, zero increment.*/
zLim= 10 /*a limit to check for runaway (race) loop.*/
/*a zero increment is not an error in REXX.*/
do k=1 while @.k\=='' /*perform a DO loop with several ranges. */
parse var @.k x y z . /*obtain the three values for a DO loop. */
say
say center('start of performing DO loop number ' k " with range: " x y z, 79, '═')
zz= 0
do j=x to y by z until zz>=zLim /* ◄─── perform the DO loop.*/
say ' j ───►' right(j, max(3, length(j) ) ) /*right justify J for alignment*/
if z==0 then zz= zz + 1 /*if zero inc, count happenings*/
end /*j*/
if zz>=zLim then say 'the DO loop for the ' k " entry was terminated (runaway)."
say center(' end of performing DO loop number ' k " with range: " x y z, 79, '─')
say
end /*k*/ /*stick a fork in it, we're all done. */ |
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
| #Ruby | Ruby | examples = [
[ -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]
]
examples.each do |start, stop, step|
as = (start..stop).step(step)
puts "#{as.inspect} size: #{as.size}"
end
|
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Bracmat | Bracmat | ( list
= Afrikaans
Ελληνικά
עברית
മലയാളം
ئۇيغۇرچە
) |
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
| #C | C | #include <stdio.h>
...
const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))
int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
} |
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
| #BBC_BASIC | BBC BASIC | FOR card% = 1 TO 4
READ cardnumber$
IF FNluhn(cardnumber$) THEN
PRINT "Card number " cardnumber$ " is valid"
ELSE
PRINT "Card number " cardnumber$ " is invalid"
ENDIF
NEXT card%
END
DATA 49927398716, 49927398717, 1234567812345678, 1234567812345670
DEF FNluhn(card$)
LOCAL I%, L%, N%, S%
L% = LEN(card$)
FOR I% = 1 TO L%
N% = VAL(MID$(card$, L%-I%+1, 1))
IF I% AND 1 THEN
S% += N%
ELSE
N% *= 2
S% += N% MOD 10 + N% DIV 10
ENDIF
NEXT
= (S% MOD 10) = 0 |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #ERRE | ERRE | PROGRAM LL_TEST
!$DOUBLE
PROCEDURE LUCAS_LEHMER(P%->RES)
LOCAL I%,MP,SN
IF P%=2 THEN RES%=TRUE EXIT PROCEDURE END IF
IF (P% AND 1)=0 THEN RES%=FALSE EXIT PROCEDURE END IF
MP=2^P%-1
SN=4
FOR I%=3 TO P% DO
SN=SN^2-2
SN-=(MP*INT(SN/MP))
END FOR
RES%=(SN=0)
END PROCEDURE
BEGIN
PRINT("Mersenne Primes:")
FOR P%=2 TO 23 DO
LUCAS_LEHMER(P%->RES%)
IF RES% THEN PRINT("M";P%) END IF
END FOR
END PROGRAM
|
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.
| #Java | Java | import java.util.*;
public class LZW {
/** Compress a string to a list of output symbols. */
public static List<Integer> compress(String uncompressed) {
// Build the dictionary.
int dictSize = 256;
Map<String,Integer> dictionary = new HashMap<String,Integer>();
for (int i = 0; i < 256; i++)
dictionary.put("" + (char)i, i);
String w = "";
List<Integer> result = new ArrayList<Integer>();
for (char c : uncompressed.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc))
w = wc;
else {
result.add(dictionary.get(w));
// Add wc to the dictionary.
dictionary.put(wc, dictSize++);
w = "" + c;
}
}
// Output the code for w.
if (!w.equals(""))
result.add(dictionary.get(w));
return result;
}
/** Decompress a list of output ks to a string. */
public static String decompress(List<Integer> compressed) {
// Build the dictionary.
int dictSize = 256;
Map<Integer,String> dictionary = new HashMap<Integer,String>();
for (int i = 0; i < 256; i++)
dictionary.put(i, "" + (char)i);
String w = "" + (char)(int)compressed.remove(0);
StringBuffer result = new StringBuffer(w);
for (int k : compressed) {
String entry;
if (dictionary.containsKey(k))
entry = dictionary.get(k);
else if (k == dictSize)
entry = w + w.charAt(0);
else
throw new IllegalArgumentException("Bad compressed k: " + k);
result.append(entry);
// Add w+entry[0] to the dictionary.
dictionary.put(dictSize++, w + entry.charAt(0));
w = entry;
}
return result.toString();
}
public static void main(String[] args) {
List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT");
System.out.println(compressed);
String decompressed = decompress(compressed);
System.out.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
| #Maxima | Maxima | /* LU decomposition is built-in */
a: hilbert_matrix(4)$
/* LU in "packed" form */
lup: lu_factor(a);
/* [matrix([1, 1/2, 1/3, 1/4 ],
[1/2, 1/12, 1/12, 3/40 ],
[1/3, 1, 1/180, 1/120 ],
[1/4, 9/10, 3/2, 1/2800]),
[1, 2, 3, 4], generalring] */
/* extract actual factors */
get_lu_factors(lup);
/* [matrix([1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]),
matrix([1, 0, 0, 0],
[1/2, 1, 0, 0],
[1/3, 1, 1, 0],
[1/4, 9/10, 3/2, 1]),
matrix([1, 1/2, 1/3, 1/4 ],
[0, 1/12, 1/12, 3/40 ],
[0, 0, 1/180, 1/120 ],
[0, 0, 0, 1/2800])
] */
/* solve for a given right-hand side */
lu_backsub(lup, transpose([1, 1, -1, -1]));
/* matrix([-204], [2100], [-4740], [2940]) */ |
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.
| #Raku | Raku | my %lychrels;
my @seeds;
my @palindromes;
my $count;
my $max = 500;
my $limit = '10_000';
my %seen;
for 1 .. $limit -> $int {
my @test;
my $index = 0;
if $int.&is-lychrel {
%lychrels.push: ($int => @test).invert;
@palindromes.push: $int if $int == $int.flip;
$count++;
}
sub is-lychrel (Int $l) {
if %seen{$l} or $index++ > $max {
%seen{$_} = True for @test;
return True;
}
@test.push: my $m = $l + $l.flip;
return False if $m == $m.flip;
$m.&is-lychrel;
}
}
for %lychrels{*}»[0].unique.sort -> $ly {
my $next = False;
for %lychrels -> $l {
for $l.value[1..*] -> $lt {
$next = True and last if $ly == $lt;
last if $ly < $lt;
}
last if $next;
}
next if $next;
@seeds.push: $ly;
}
say " Number of Lychrel seed numbers < $limit: ", +@seeds;
say " Lychrel seed numbers < $limit: ", join ", ", @seeds;
say "Number of Lychrel related numbers < $limit: ", +$count - @seeds;
say " Number of Lychrel palindromes < $limit: ", +@palindromes;
say " Lychrel palindromes < $limit: ", join ", ", @palindromes; |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phixmonti | Phixmonti | "<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
true
while
"<" find dup var ini
if
">" find ini - 1 + ini swap slice var replace
"Replace: " replace " with: " chain chain input var with nl
true
while
replace with subst
replace find
endwhile
true
else
false
endif
endwhile
print
|
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
| #Dyalect | Dyalect | func isPrime(number) {
if number <= 1 {
return false
}
else if number % 2 == 0 {
return number == 2
}
var i = 3
while (i * i) < number {
if number % i == 0 {
return false
}
i += 2
}
return true
}
var i = 42
var n = 0
while n < 42 {
if isPrime(i) {
n += 1
print("n = \(n)\t\(i)")
i += i - 1
}
i += 1
} |
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
| #F.23 | F# |
// Well I don't do loops. Nigel Galloway: March 17th., 2019. Let me try to explain where the loopy variables are, for the imperatively constrained.
// cUL allows me to claim the rather trivial extra credit (commas in the numbers)
let cUL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:uint64)->n.ToString("N0",g))
// fN is primality by trial division
let fN g=pCache|>Seq.map uint64|>Seq.takeWhile(fun n->n*n<g)|>Seq.forall(fun n->g%n>0UL)
// unfold is sort of a loop incremented by 1 in this case
let fG n=Seq.unfold(fun n->Some(n,(n+1UL))) n|>Seq.find(fN)
// unfold is sort of a loop with fG as an internal loop incremented by the exit value of the internal loop in this case.
Seq.unfold(fun n->let n=fG n in Some(n,n+n)) 42UL|>Seq.take 42|>Seq.iteri(fun n g->printfn "%2d -> %s" (n+1) (cUL g))
|
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
| #Arturo | Arturo | while [true] [
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
| #AutoHotkey | AutoHotkey | Loop
MsgBox SPAM `n |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #J | J |
NB. http://rosettacode.org/wiki/Loops/Wrong_ranges#J
NB. define range as a linear polynomial
start =: 0&{
stop =: 1&{
increment =: 2&{ :: 1: NB. on error use 1
range =: (start , increment) p. [: i. [: >: [: <. (stop - start) % increment
f =: 3 :0
input =. y
'prod sum x y z one three seven' =. 1 0 5 _5 _2 1 3 7
J =. ([: ; range&.>) ". input
for_j. J do.
sum =. sum + | j
if. ((|prod)<2^27) *. (0 ~: j) do.
prod =. prod * j
end.
end.
sum , 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
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class LoopsWithMultipleRanges {
private static long sum = 0;
private static long prod = 1;
public static void main(String[] args) {
long x = 5;
long y = -5;
long z = -2;
long one = 1;
long three = 3;
long seven = 7;
List<Long> jList = new ArrayList<>();
for ( long j = -three ; j <= pow(3, 3) ; j += three ) jList.add(j);
for ( long j = -seven ; j <= seven ; j += x ) jList.add(j);
for ( long j = 555 ; j <= 550-y ; j += 1 ) jList.add(j);
for ( long j = 22 ; j >= -28 ; j += -three ) jList.add(j);
for ( long j = 1927 ; j <= 1939 ; j += 1 ) jList.add(j);
for ( long j = x ; j >= y ; j += z ) jList.add(j);
for ( long j = pow(11, x) ; j <= pow(11, x) + one ; j += 1 ) jList.add(j);
List<Long> prodList = new ArrayList<>();
for ( long j : jList ) {
sum += Math.abs(j);
if ( Math.abs(prod) < pow(2, 27) && j != 0 ) {
prodList.add(j);
prod *= j;
}
}
System.out.printf(" sum = %,d%n", sum);
System.out.printf("prod = %,d%n", prod);
System.out.printf("j values = %s%n", jList);
System.out.printf("prod values = %s%n", prodList);
}
private static long pow(long base, long exponent) {
return (long) Math.pow(base, exponent);
}
}
|
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
| #AutoHotkey | AutoHotkey | i = 1024
While (i > 0)
{
output = %output%`n%i%
i := Floor(i / 2)
}
MsgBox % output |
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
| #AWK | AWK | BEGIN {
v = 1024
while(v > 0) {
print v
v = int(v/2)
}
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopdownward64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "Counter = @ \n" // message result
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x4,#10
1: // begin loop
mov x0,x4
ldr x1,qAdrsZoneConv // display value
bl conversion10 // call decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display value
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
subs x4,x4,1 // decrement counter
bge 1b // loop if greather
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Ada | Ada | for I in reverse 0..10 loop
Put_Line(Integer'Image(I));
end loop; |
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.
| #Action.21 | Action! | Proc Main()
byte A
A=0
Do
A==+1
PrintBE(A)
Until A Mod 6=0
Od
Return |
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.
| #ActionScript | ActionScript | var str:String = "";
for (var i:int = 1; i <= 5; i++) {
for (var j:int = 1; j <= i; j++)
str += "*";
trace(str);
str = "";
} |
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_68 | ALGOL 68 | [ for index ] [ from first ] [ by increment ] [ to last ] [ while condition ] do statements od
The minimum form of a "loop clause" is thus: do statements od # an infinite loop #
|
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.
| #Picat | Picat | ludic(N) = Ludic =>
ludic(2..N, [1], Ludic).
ludic([], Ludic0, Ludic) =>
Ludic = Ludic0.reverse().
ludic(T, Ludic0, Ludic) =>
T2 = ludic_keep(T),
ludic(T2,[T[1]|Ludic0],Ludic).
% which elements to keep
ludic_keep([]) = [].
ludic_keep([H|List]) = Ludic =>
ludic_keep(H,1,List,[],Ludic).
ludic_keep(_H,_C,[],Ludic0,Ludic) ?=>
Ludic = Ludic0.reverse().
ludic_keep(H,C,[H1|T],Ludic0,Ludic) =>
(
C mod H > 0 ->
ludic_keep(H,C+1,T,[H1|Ludic0],Ludic)
;
ludic_keep(H,C+1,T,Ludic0,Ludic)
). |
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
| #BASIC | BASIC | DIM i AS INTEGER
FOR i=1 TO 10
PRINT i;
IF i=10 THEN EXIT FOR
PRINT ", ";
NEXT i |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #bc | bc | while (1) {
print ++i
if (i == 10) {
print "\n"
break
}
print ", "
} |
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
| #bc | bc | s = 1 /* Seed of the random number generator */
/* Random number from 1 to 20. */
define r() {
auto r
while (1) {
/*
* Formula (from POSIX) for random numbers of low
* quality, from 0 to 32767.
*/
s = (s * 1103515245 + 12345) % 4294967296
r = (s / 65536) % 32768
/* Prevent modulo bias. */
if (r >= 32768 % 20) break
}
return ((r % 20) + 1)
}
r = 5 /* Total rows */
c = 5 /* Total columns */
/* Fill array a[] with random numbers from 1 to 20. */
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
a[i * c + j] = r()
}
}
/* Find a 20. */
b = 0
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
v = a[i * c + j]
v /* Print v and a newline. */
if (v == 20) {
b = 1
break
}
}
if (b) break
/* Print "==" and a newline. */
"==
"
}
quit |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: testLoop (in integer: start, in integer: stop, in integer: incr, in string: comment) is func
local
const integer: limit is 10;
var integer: number is 0;
var integer: count is 0;
begin
writeln(comment);
write("Range(" <& start <& ", " <& stop <& ", " <& incr <& ") -> [ ");
block
for number range start to stop step incr do
write(number <& " ");
incr(count);
if count >= limit then
raise RANGE_ERROR;
end if;
end for;
exception
catch RANGE_ERROR: noop;
end block;
writeln("]");
writeln;
end func;
const proc: main is func
begin
testLoop(-2, 2, 1, "Normal");
testLoop(-2, 2, 0, "Zero increment");
testLoop(-2, 2, -1, "Increments away from stop value");
testLoop(-2, 2, 10, "First increment is beyond stop value");
testLoop( 2, -2, 1, "Start more than stop: positive increment");
testLoop( 2, 2, 1, "Start equal stop: positive increment");
testLoop( 2, 2, -1, "Start equal stop: negative increment");
testLoop( 2, 2, 0, "Start equal stop: zero increment");
testLoop( 0, 0, 0, "Start equal stop equal zero: zero increment");
end func; |
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
| #Smalltalk | Smalltalk | startExpr to:stopExpr by:incExpr do:[..] |
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
| #C.23 | C# | string[] things = {"Apple", "Banana", "Coconut"};
foreach (string thing in things)
{
Console.WriteLine(thing);
} |
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
| #C.2B.2B | C++ | for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
std::cout << *i << "\n";
} |
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
| #bc | bc | /* Return 1 if number passes Luhn test, else 0 */
define l(n) {
auto m, o, s, x
o = scale
scale = 0
m = 1
while (n > 0) {
x = (n % 10) * m
if (x > 9) x -= 9
s += x
m = 3 - m
n /= 10
}
s %= 10
scale = o
if (s) return(0)
return(1)
}
l(49927398716)
l(49927398717)
l(1234567812345678)
l(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).
| #F.23 | F# | let rec s mp n =
if n = 1 then 4I % mp else ((s mp (n - 1)) ** 2 - 2I) % mp
[ for p in 2..47 do
if p = 2 || s ((1I <<< p) - 1I) (p - 1) = 0I then
yield p ] |
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.