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/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Nim | Nim | import os, strformat, strutils
type LuckyKind {.pure.} = enum Lucky = "lucky", EvenLucky = "evenlucky"
const NoValue = 0 # Indicates that no value have been specified.
####################################################################################################
# Lucky numbers generation.
func initLuckyNumbers(nelems: int; kind: LuckyKind): seq[int] =
## Initialize a list of lucky numbers.
result = newSeqOfCap[int](nelems)
for i in 0..<nelems:
var k = i
for j in countdown(result.high, 1):
k = k * result[j] div (result[j] - 1)
result.add 2 * k + 1 + ord(kind)
####################################################################################################
# Printing.
template name(kind: LuckyKind): string =
if kind == Lucky: "Lucky" else: "Even lucky"
proc printSingle(j: int; kind: LuckyKind) =
## Print the lucky number at a given index.
let luckySeq = initLuckyNumbers(j, kind)
echo &"{name(kind)} number at index {j} is {luckySeq[j - 1]}"
proc printRange(j, k: int; kind: LuckyKind) =
## print the luck numbers in a range of indexes.
let luckySeq = initLuckyNumbers(k, kind)
var list = &"{name(kind)} numbers at indexes {j} to {k} are: "
let start = list.len
for idx in (j - 1)..(k - 1):
list.addSep(", ", start)
list.add $luckySeq[idx]
echo list
proc printInRange(j, k: int; kind: LuckyKind) =
## Print the lucky numbers in a range of values.
let luckySeq = initLuckyNumbers(k, kind) # "k" is greater than needed.
var list = &"{name(kind)} numbers between {j} to {k} are: "
let start = list.len
for val in luckySeq:
if val > k: break
if val > j:
list.addSep(", ", start)
list.add $val
echo list
####################################################################################################
# Command line parsing.
proc parseCommandLine(): tuple[j, k: int; kind: LuckyKind] =
## Parse the command line.
# Internal exception to catch invalid argument value.
type InvalidArgumentError = object of ValueError
template raiseError(message, value = "") =
## Raise an InvalidArgumentError.
raise newException(InvalidArgumentError, message & value & '.')
result = (Novalue, Novalue, Lucky)
try:
if paramCount() notin 1..3: raiseError "Wrong number of arguments"
# First argument: "j" value.
let p1 = paramStr(1)
try:
result.j = parseInt(p1)
if result.j <= 0: raiseError "Expected a positive number, got: ", p1
except ValueError:
raiseError "Expected an integer, got: ", p1
# Second argument: "k" value or a comma.
if paramCount() > 1:
let p2 = paramStr(2)
if p2 == ",":
# Must be followed by the kind of lucky number.
if paramCount() != 3: raiseError "Missing kind argument"
else:
try:
result.k = parseInt(p2)
if result.k == 0: raiseError "Expected a non null number, got: ", p2
except ValueError:
raiseError "Expected an integer, got: ", p2
# Third argument: number kind.
if paramCount() == 3:
let p3 = paramStr(3)
try:
result.kind = parseEnum[LuckyKind](p3.toLowerAscii())
except ValueError:
raiseError "Wrong kind: ", p3
except InvalidArgumentError:
quit getCurrentExceptionMsg()
#———————————————————————————————————————————————————————————————————————————————————————————————————
# Main program.
let (j, k, kind) = parseCommandLine()
if k == NoValue:
# Print jth value.
printSingle(j, kind)
elif k > 0:
# Print jth to kth values.
printRange(j, k, kind)
else:
# Print values in range j..(-k).
printInRange(j, -k, kind) |
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.
| #D | D | import std.stdio, std.array;
auto compress(in string original) pure nothrow {
int[string] dict;
foreach (immutable char c; char.min .. char.max + 1)
dict[[c]] = c;
string w;
int[] result;
foreach (immutable ch; original)
if (w ~ ch in dict)
w = w ~ ch;
else {
result ~= dict[w];
dict[w ~ ch] = dict.length;
w = [ch];
}
return w.empty ? result : (result ~ dict[w]);
}
auto decompress(in int[] compressed) pure nothrow {
auto dict = new string[char.max - char.min + 1];
foreach (immutable char c; char.min .. char.max + 1)
dict[c] = [c];
auto w = dict[compressed[0]];
auto result = w;
foreach (immutable k; compressed[1 .. $]) {
auto entry = (k < dict.length) ? dict[k] : w ~ w[0];
result ~= entry;
dict ~= w ~ entry[0];
w = entry;
}
return result;
}
void main() {
auto comp = "TOBEORNOTTOBEORTOBEORNOT".compress;
writeln(comp, "\n", comp.decompress);
} |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Haskell | Haskell |
import Data.List
import Data.Maybe
import Text.Printf
-- a matrix is represented as a list of columns
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult a b = [ [ sum $ zipWith (*) ak bj | ak <- (transpose a) ] | bj <- b ]
nth mA i j = (mA !! j) !! i
idMatrixPart n m k = [ [if (i==j) then 1 else 0 | i <- [1..n]] | j <- [k..m]]
idMatrix n = idMatrixPart n n 1
permMatrix n ix1 ix2 =
[ [ if ((i==ix1 && j==ix2) || (i==ix2 && j==ix1) || (i==j && j /= ix1 && i /= ix2))
then 1 else 0| i <- [0..n-1]] | j <- [0..n-1]]
permMatrix_inv n ix1 ix2 = permMatrix n ix2 ix1
-- count k from zero
elimColumn :: Int -> [[Rational]] -> Int -> [Rational]
elimMatrix :: Int -> [[Rational]] -> Int -> [[Rational]]
elimMatrix_inv :: Int -> [[Rational]] -> Int -> [[Rational]]
elimColumn n mA k = [(let mAkk = (nth mA k k) in if (i>k) then (-(nth mA i k)/mAkk)
else if (i==k) then 1 else 0) | i <- [0..n-1]]
elimMatrix n mA k = (idMatrixPart n k 1) ++ [elimColumn n mA k] ++ (idMatrixPart n n (k+2))
elimMatrix_inv n mA k = (idMatrixPart n k 1) ++ --mA is elimMatrix there
[let c = (mA!!k) in [if (i==k) then 1 else if (i<k) then 0 else (-(c!!i)) | i <- [0..n-1]]]
++ (idMatrixPart n n (k+2))
swapIndx :: [[Rational]] -> Int -> Int
swapIndx mA k = fromMaybe k (findIndex (>0) (drop k (mA!!k)))
-- LUP; lupStep returns [L:U:P]
paStep_recP :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
paStep_recM :: Int -> [[Rational]] -> [[Rational]] -> [[Rational]] -> Int -> [[[Rational]]]
lupStep :: Int -> [[Rational]] -> [[[Rational]]]
paStep_recP n mP mA mL cnt =
let mPt = permMatrix n cnt (swapIndx mA cnt) in
let mPtInv = permMatrix_inv n cnt (swapIndx mA cnt) in
if (cnt >= n) then [(mmult mP mL),mA,mP] else
(paStep_recM n (mmult mPt mP) (mmult mPt mA) (mmult mL mPtInv) cnt)
paStep_recM n mP mA mL cnt =
let mMt = elimMatrix n mA cnt in
let mMtInv = elimMatrix_inv n mMt cnt in
paStep_recP n mP (mmult mMt mA) (mmult mL mMtInv) (cnt + 1)
lupStep n mA = paStep_recP n (idMatrix n) mA (idMatrix n) 0
--IO
matrixFromRationalToString m = concat $ intersperse "\n"
(map (\x -> unwords $ printf "%8.4f" <$> (x::[Double]))
(transpose (matrixFromRational m))) where
matrixFromRational m = map (\x -> map fromRational x) m
solveTask mY = let mLUP = lupStep (length mY) mY in
putStrLn ("A: \n" ++ matrixFromRationalToString mY) >>
putStrLn ("L: \n" ++ matrixFromRationalToString (mLUP!!0)) >>
putStrLn ("U: \n" ++ matrixFromRationalToString (mLUP!!1)) >>
putStrLn ("P: \n" ++ matrixFromRationalToString (mLUP!!2)) >>
putStrLn ("Verify: PA\n" ++ matrixFromRationalToString (mmult (mLUP!!2) mY)) >>
putStrLn ("Verify: LU\n" ++ matrixFromRationalToString (mmult (mLUP!!0) (mLUP!!1)))
mY1 = [[1, 2, 1], [3, 4, 7], [5, 7, 0]] :: [[Rational]]
mY2 = [[11, 1, 3, 2], [9, 5, 17, 5], [24, 2, 18, 7], [2, 6, 1, 1]] :: [[Rational]]
main = putStrLn "Task1: \n" >> solveTask mY1 >>
putStrLn "Task2: \n" >> solveTask mY2
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | palindromeQ[n_Integer] :=
Block[{digits = IntegerDigits[n]}, digits == Reverse@digits]
nextNumber[n_Integer] := n + FromDigits[Reverse@IntegerDigits@n]
lychrelQ[n_Integer] := !
palindromeQ@
Catch[Nest[If[palindromeQ[#], Throw[#], nextNumber[#]] &,
nextNumber[n], 500]] |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | import "random" for Random
import "io" for Stdin, Stdout
var answers = [
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
]
var rand = Random.new()
System.print("Please enter your question or a blank line to quit.")
while (true) {
System.write("\n? : ")
Stdout.flush()
var question = Stdin.readLine()
if (question.trim() == "") return
var answer = answers[rand.int(20)]
System.print("\n%(answer)")
} |
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
| #J | J | require 'general/misc/prompt regex'
madlib=:3 :0
smoutput 'Please enter the story template'
smoutput 'See http://rosettacode.org/wiki/Mad_Libs for details'
t=.''
while.#l=.prompt '' do. t=.t,l,LF end.
repl=. ~.'<[^<>]*>' rxall t
for_bef. repl do.
aft=. prompt (}.}:;bef),': '
t=.t rplc bef,<aft
end.
t
) |
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
| #11l | 11l | F is_prime(n)
L(x) (2, 3)
I n % x == 0
R n == x
Int64 d = 5
L d * d <= n
L(x) (2, 4)
I n % d == 0
R 0B
d += x
R 1B
Int64 i = 42
V n = 0
L n < 42
I is_prime(i)
n++
print(‘n = #2 #16’.format(n, i))
i += i - 1
i++ |
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
| #11l | 11l | L
print(‘SPAM’) |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #AWK | AWK |
# syntax: GAWK -f LOOPS_WITH_MULTIPLE_RANGES.AWK
BEGIN {
prod = 1
sum = 0
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
for (j=-three; j<=(3^3); j+=three) { main(j) }
for (j=-seven; j<=seven; j+=x) { main(j) }
for (j=555; j<=550-y; j++) { main(j) }
for (j=22; j>=-28; j+=-three) { main(j) }
for (j=1927; j<=1939; j++) { main(j) }
for (j=x; j>=y; j+=z) { main(j) }
for (j=(11^x); j<=(11^x)+1; j++) { main(j) }
printf("sum = %d\n",sum)
printf("prod = %d\n",prod)
exit(0)
}
function main(x) {
sum += abs(x)
if (abs(prod) < (2^27) && x != 0) {
prod *= x
}
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
|
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
| #6502_Assembly | 6502 Assembly | LoopsWhile: PHA ;push accumulator onto stack
LDA #$00 ;the 6502 is an 8-bit processor
STA Ilow ;and so 1024 ($0400) must be stored in two memory locations
LDA #$04
STA Ihigh
WhileLoop: LDA Ilow
BNE NotZero
LDA Ihigh
BEQ EndLoop
NotZero: JSR PrintI ;routine not implemented
LSR Ihigh ;shift right
ROR Ilow ;rotate right
JMP WhileLoop
EndLoop: PLA ;restore accumulator from stack
RTS ;return from subroutine |
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
| #68000_Assembly | 68000 Assembly | main:
MOVE.W #1024,D0
WhileLoop:
jsr PrintHexWord
LSR.W #1,D0
BNE WhileLoop |
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.
| #jq | jq | # This method for sieving turns out to be the fastest in jq.
# Input: an array to be sieved.
# Output: if the array length is less then $n then empty, else the sieved array.
def sieve($n):
if length<$n then empty
else . as $in
| reduce range(0;length) as $i ([]; if $i % $n == 0 then . else . + [$in[$i]] end)
end;
# Generate a stream of ludic numbers based on sieving range(2; $nmax+1)
def ludic($nmax):
def l:
.[0] as $next
| $next, (sieve($next)|l);
1, ([range(2; $nmax+1)] | l);
# Output: an array of the first . ludic primes (including 1)
def first_ludic_primes:
. as $n
| def l:
. as $k
| [ludic(10*$k)] as $a
| if ($a|length) >= $n then $a[:$n]
else (10*$k) | l
end;
l;
# Output: an array of the ludic numbers less than .
def ludic_primes:
. as $n
| def l:
. as $k
| [ludic(10*$k)] as $a
| if $a[-1] >= $n then $a | map(select(. < $n))
else (10*$k) | l
end;
l;
# Output; a stream of triplets of ludic numbers, where each member of the triplet is less than .
def triplets:
ludic_primes as $primes
| $primes[] as $p
| $primes
| bsearch($p) as $i
| if $i >= 0
then $primes[$i+1:]
| select( bsearch($p+2) >= 0 and
bsearch($p+6) >= 0)
| [$p, $p+2, $p+6]
else empty
end;
"First 25 ludic primes:", (25|first_ludic_primes),
"\nThere are \(1000|ludic_primes|length) ludic numbers <= 1000",
( "The \n2000th to 2005th ludic primes are:",
(2005|first_ludic_primes)[2000:]),
( [250 | triplets]
| "\nThere are \(length) triplets less than 250:",
.[] ) |
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
| #Fermat | Fermat | for a = -2 to 2 by 1 do !(a,' '); od;
for a = -2 to 2 by 0 do !(a,' '); od;
for a = -2 to 2 by -1 do !(a,' '); od;
for a = -2 to 2 by 10 do !(a,' '); od;
for a = 2 to -2 by 1 do !(a,' '); od;
for a = 2 to 2 by 1 do !(a,' '); od;
for a = 2 to 2 by -1 do !(a,' '); od;
for a = 2 to 2 by 0 do !(a,' '); od;
for a = 0 to 0 by 0 do !(a,' '); od; |
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
| #Forth | Forth | : test-seq ( start stop inc -- )
cr rot dup ." start: " 2 .r
rot dup ." stop: " 2 .r
rot dup ." inc: " 2 .r ." | "
-rot swap do i . dup +loop drop ;
-2 2 1 test-seq
-2 2 0 test-seq
-2 2 -1 test-seq
-2 2 10 test-seq
2 -2 1 test-seq
2 2 1 test-seq
2 2 -1 test-seq
2 2 0 test-seq
0 0 0 test-seq |
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
| #FreeBASIC | FreeBASIC | data -2,2,1,"Normal",-2,2,0,"Zero increment",-2,2,-1,"Increments away from stop value"
data -2,2,10,"First increment is beyond stop value",2,-2,1,"Start more than stop: positive increment"
data 2,2,1,"Start equal stop: positive increment",2,2,-1,"Start equal stop: negative increment"
data 2,2,0,"Start equal stop: zero increment",0,0,0,"Start equal stop equal zero: zero increment"
dim as integer i, start, fin, inc, vr, count
dim as string cmt
for i = 1 to 9
count = 0
read start, fin, inc, cmt
print cmt
print using " Looping from ### to ### in increments of ##"; start; fin; inc
for vr = start to fin step inc
print " Loop index = ",vr
count += 1
if count = 10 then
print " Breaking infinite loop"
exit for
end if
next vr
print " Loop finished"
print
print
next 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
| #ALGOL_W | ALGOL W | % returns true if ccNumber passes the Luhn test, false otherwise %
% as Algol W has fixed length strings, the length of the number %
% must be specified in ccLength %
logical procedure LuhnTest ( string(32) value ccNumber
; integer value ccLength
) ;
begin
integer checkSum;
logical oddDigit, isValid;
checkSum := 0;
isValid := oddDigit := true;
for cPos := ccLength step -1 until 1 do begin
integer digit;
digit := decode( ccNumber( cPos - 1 // 1 ) ) - decode( "0" );
if digit < 0 or digit > 9 then isValid := false
else if oddDigit
then checkSum := checkSum + digit
else checkSum := checkSum + ( case digit + 1 of ( 0, 2, 4, 6, 8
, 1, 3, 5, 7, 9
)
);
oddDigit := not oddDigit
end for_cPos ;
isValid and ( ( checkSum rem 10 ) = 0 )
end LuhnTest |
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).
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
namespace LucasLehmerTestForRosettaCode
{
public class LucasLehmerTest
{
static BigInteger ZERO = new BigInteger(0);
static BigInteger ONE = new BigInteger(1);
static BigInteger TWO = new BigInteger(2);
static BigInteger FOUR = new BigInteger(4);
private static bool isMersennePrime(int p)
{
if (p % 2 == 0) return (p == 2);
else {
for (int i = 3; i <= (int)Math.Sqrt(p); i += 2)
if (p % i == 0) return false; //not prime
BigInteger m_p = BigInteger.Pow(TWO, p) - ONE;
BigInteger s = FOUR;
for (int i = 3; i <= p; i++)
s = (s * s - TWO) % m_p;
return s == ZERO;
}
}
public static int[] GetMersennePrimeNumbers(int upTo)
{
List<int> response = new List<int>();
Parallel.For(2, upTo + 1, i => {
if (isMersennePrime(i)) response.Add(i);
});
response.Sort();
return response.ToArray();
}
static void Main(string[] args)
{
int[] mersennePrimes = LucasLehmerTest.GetMersennePrimeNumbers(11213);
foreach (int mp in mersennePrimes)
Console.Write("M" + mp+" ");
Console.ReadLine();
}
}
} |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Perl | Perl | use Perl6::GatherTake;
sub luck {
my($a,$b) = @_;
gather {
my $i = $b;
my(@taken,@rotor,$j);
take 0; # 0th index is a placeholder
push @taken, take $a;
while () {
for ($j = 0; $j < @rotor; $j++) {
--$rotor[$j] or last;
}
if ($j < @rotor) {
$rotor[$j] = $taken[$j+1];
}
else {
take $i;
push @taken, $i;
push @rotor, $i - @taken;
}
$i += 2;
}
}
}
# fiddle with user input
$j = shift || usage();
$k = shift || ',';
$l = shift || 'lucky';
usage() unless $k =~ /,|-?\d+/;
usage() unless $l =~ /^(even)?lucky$/i;
sub usage { print "Args must be: j [,|k|-k] [lucky|evenlucky]\n" and exit }
# seed the iterator
my $lucky = $l =~ /^l/i ? luck(1,3) : luck(2,4);
# access values from 'lazy' list
if ($k eq ',') {
print $lucky->[$j]
} elsif ($k > $j) {
print $lucky->[$_] . ' ' for $j..$k
} elsif ($k < 0) {
while () { last if abs($k) < $lucky->[$i++] } # must first extend the array
print join ' ', grep { $_ >= $j and $_ <= abs($k) } @$lucky
}
print "\n" |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Dylan | Dylan | Module: LZW
Synopsis: LZW implementation for Rosetta code
define method output(n :: <integer>)
format-out("%d ", n);
end;
define method contains?(dict, var)
let x = element(dict, var, default: #f);
x ~= #f;
end;
define method byte->string(c)
add("", as(<character>, c));
end;
define method compress(input :: <string>) => <vector>;
let result = make(<vector>);
let dict = make(<string-table>);
for (x from 0 to 255)
dict[byte->string(x)] := x;
end;
let next-code = 256;
let cur-seq = "";
for (c in input)
let wc = add(cur-seq, c);
if (contains?(dict, wc))
cur-seq := wc;
else
result := add(result, dict[cur-seq]);
dict[wc] := next-code;
next-code := next-code + 1;
cur-seq := add("", c);
end
end;
unless (empty?(cur-seq))
result := add(result, dict[cur-seq]);
end;
result
end;
format-out("%=\n", compress("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
| #Idris | Idris |
module Main
import Data.Vect
Matrix : Nat -> Nat -> Type -> Type
Matrix m n t = Vect m (Vect n t)
-- Creates list from 0 to n (not including n)
upTo : (m : Nat) -> Vect m (Fin m)
upTo Z = []
upTo (S n) = 0 :: (map FS (upTo n))
-- Creates list from 0 to n-1 (not including n-1)
upToM1 : (m : Nat) -> (sz ** Vect sz (Fin m))
upToM1 m = case (upTo m) of
(y::ys) => (_ ** init(y::ys))
[] => (_ ** [])
-- Creates list from i to n (not including n)
fromUpTo : {n : Nat} -> Fin n -> (sz ** Vect sz (Fin n))
fromUpTo {n} m = filter (>= m) (upTo n)
-- Creates list from i+1 to n (not including n)
fromUpTo1 : {n : Nat} -> Fin n -> (sz ** Vect sz (Fin n))
fromUpTo1 {n} m with (fromUpTo m)
| (_ ** xs) = case xs of
(y::ys) => (_ ** ys)
[] => (_ ** [])
-- Create Zero Matrix of size m by n
zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double
zeros m n = replicate m (replicate n 0.0)
replaceAtM : (Fin m, Fin n) -> t -> Matrix m n t -> Matrix m n t
replaceAtM (i, j) e a = replaceAt i (replaceAt j e (index i a)) a
-- Create Identity Matrix of size m by m
eye : (m : Nat) -> Matrix m m Double
eye m = map create1Vec (upTo m)
where
set1 : Vect m Double -> Fin m -> Vect m Double
set1 a n = replaceAt n 1.0 a
create1Vec : Fin m -> Vect m Double
create1Vec n = set1 (replicate m 0.0) n
indexM : (Fin m, Fin n) -> Matrix m n t -> t
indexM (i, j) a = index j (index i a)
-- Obtain index for the row containing the
-- largest absolute value for the given column
colAbsMaxIndex : Fin m -> Fin m -> Matrix m m Double -> Fin m
colAbsMaxIndex startRow col a {m} with (fromUpTo startRow)
| (_ ** xs) =
snd $ foldl (\(absMax, idx), curIdx =>
let curAbsVal = abs(indexM (curIdx, col) a) in
if (curAbsVal > absMax)
then (curAbsVal, curIdx)
else (absMax, idx)
) (0.0, startRow) xs
-- Swaps two rows in a given matrix
swapRows : Fin m -> Fin m -> Matrix m n t -> Matrix m n t
swapRows r1 r2 a = replaceAt r2 tempRow $ replaceAt r1 (index r2 a) a
where tempRow = index r1 a
-- Swaps two individual values in a matrix
swapValues : (Fin m, Fin m) -> (Fin m, Fin m) -> Matrix m m Double -> Matrix m m Double
swapValues (i1, j1) (i2, j2) m = replaceAtM (i2, j2) v1 $ replaceAtM (i1, j1) v2 m
where
v1 = indexM (i1, j1) m
v2 = indexM (i2, j2) m
-- Perform row Swap on Lower Triangular Matrix
lSwapRow : Fin m -> Fin m -> Matrix m m Double -> Matrix m m Double
lSwapRow row1 row2 l {m} with (filter (< row1) (upTo m))
| (_ ** xs) = foldl (\l',col => swapValues (row1, col) (row2, col) l') l xs
rowSwap : Fin m -> (Matrix m m Double, Matrix m m Double, Matrix m m Double) ->
(Matrix m m Double, Matrix m m Double, Matrix m m Double)
rowSwap col (l,u,p) = (lSwapRow col row l, swapRows col row u, swapRows col row p)
where row = colAbsMaxIndex col col u
calc : (Fin m) -> (Fin m) -> (Matrix m m Double, Matrix m m Double) ->
(Matrix m m Double, Matrix m m Double)
calc i j (l, u) {m} = (l', u')
where
l' : Matrix m m Double
l' = replaceAtM (j, i) ((indexM (j, i) u) / indexM (i, i) u) l
u'' : (Fin m) -> (Matrix m m Double) -> (Matrix m m Double)
u'' k u = replaceAtM (j, k) ((indexM (j, k) u) -
((indexM (j, i) l') * (indexM (i, k) u))) u
u' : (Matrix m m Double)
u' with (fromUpTo i) | (_ ** xs) = foldl (\curU, idx => u'' idx curU) u xs
-- Perform a single iteration of the algorithm for the given column
iteration : Fin m -> (Matrix m m Double, Matrix m m Double, Matrix m m Double) ->
(Matrix m m Double, Matrix m m Double, Matrix m m Double)
iteration i lup {m} = iterate' (rowSwap i lup)
where
modify : (Matrix m m Double, Matrix m m Double) ->
(Matrix m m Double, Matrix m m Double)
modify lu with (fromUpTo1 i) | (_ ** xs) =
foldl (\lu',j => calc i j lu') lu xs
iterate' : (Matrix m m Double, Matrix m m Double, Matrix m m Double) ->
(Matrix m m Double, Matrix m m Double, Matrix m m Double)
iterate' (l, u, p) with (modify (l, u)) | (l', u') = (l', u', p)
-- Generate L, U, P matricies from a given square matrix.
-- Where L * U = A, and P is the permutation matrix
luDecompose : Matrix m m Double -> (Matrix m m Double, Matrix m m Double, Matrix m m Double)
luDecompose a {m} with (upToM1 m)
| (_ ** xs) = foldl (\lup,idx => iteration idx lup) (eye m,a,eye m) xs
ex1 : (Matrix 3 3 Double, Matrix 3 3 Double, Matrix 3 3 Double)
ex1 = luDecompose [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
ex2 : (Matrix 4 4 Double, Matrix 4 4 Double, Matrix 4 4 Double)
ex2 = luDecompose [[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]]
printEx : (Matrix n n Double, Matrix n n Double, Matrix n n Double) -> IO ()
printEx (l, u, p) = do
putStr "l:"
print l
putStrLn "\n"
putStr "u:"
print u
putStrLn "\n"
putStr "p:"
print p
putStrLn "\n"
main : IO()
main = do
putStrLn "Solution 1:"
printEx ex1
putStrLn "Solution 2:"
printEx ex2
|
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.
| #Nim | Nim | import algorithm, sequtils, strformat, strutils, tables
type
Digit = range[0..9]
Number = seq[Digit] # Number as a sequence of digits (unit at index 0).
# Structure used to find the candidates for Lychrel numbers.
Candidates = object
seeds: seq[Number] # List of possible seeds.
linked: Table[Number, Number] # Maps a number to a smallest number in a sequence.
####################################################################################################
# Conversions.
func toInt(n: Number): Natural =
## Convert a Number to an int. No check is done for overflow.
for i in countdown(n.high, 0):
result = 10 * result + n[i]
func `$`(n: Number): string =
## Return the string representation of a Number.
reversed(n).join()
func `$`(s: seq[Number]): string =
## Return the string representation of a sequence of Numbers.
s.mapIt($it).join(" ")
####################################################################################################
# Operations on Numbers.
func addReverse(n: var Number) =
## Add a Number to its reverse.
var carry = 0
var high = n.high
var r = reversed(n)
for i in 0..high:
var sum = n[i] + r[i] + carry
if sum >= 10:
n[i] = sum - 10
carry = 1
else:
n[i] = sum
carry = 0
if carry != 0: n.add carry
func inc(a: var Number) =
## Increment a Number by one.
for item in a.mitems:
let sum = item + 1
if sum >= 10:
item = sum - 10
else:
item = sum
return # No carry: stop adding.
a.add 1 # Add last carry.
####################################################################################################
# Operations related to Lychrel numbers.
func isPalindromic(n: Number): bool =
## Check if a Number is palindromic.
for i in 0..(n.high div 2):
if n[i] != n[n.high - i]: return false
result = true
func isRelatedLychrel(candidates: Candidates; n: Number): bool =
## Check if a Number is a Lychrel related number.
var val = candidates.linked[n]
# Search for the first value in a list of linked values.
while val in candidates.linked: val = candidates.linked[val]
# If the first value is a seed, "n" is related to it.
result = val in candidates.seeds
func relatedCount(candidates: Candidates; maxlen: Positive): int =
## Return the number of related Lychrel numbers with length <= maxlen.
# Loop on values which are linked to a smallest value.
for n in candidates.linked.keys:
if n.len <= maxlen and candidates.isRelatedLychrel(n): inc result
func palindromicLychrel(candidates: Candidates; maxlen: Positive): seq[int] =
## Return the list of palindromic Lychrel numbers with length <= maxlen.
# Search among seed Lychrel numbers.
for n in candidates.seeds:
if n.len <= maxlen and n.isPalindromic:
result.add n.toInt
# Search among related Lychrel numbers.
for n in candidates.linked.keys:
if n.len <= maxlen and n.isPalindromic and candidates.isRelatedLychrel(n):
result.add n.toInt
# Sort the whole list.
result.sort()
proc check(candidates: var Candidates; num: Number) =
## Check if a Number is a possible Lychrel number.
if num in candidates.linked: return # Already encountered: nothing to do.
var val = num
for _ in 1..500:
val.addReverse()
if val in candidates.linked:
# Set the linked value of "num" to that of "val".
candidates.linked[num] = candidates.linked[val]
return
if val.isPalindromic(): return # Don't store palindromic values as they may be seeds.
candidates.linked[val] = num
candidates.seeds.add num
#———————————————————————————————————————————————————————————————————————————————————————————————————
var cand: Candidates
var num: Number = @[Digit(0)] # The Number to test.
for n in 1..10_000:
inc num
cand.check(num)
echo &"Found {cand.seeds.len} candidate seed Lychrel numbers between 1 and 10000."
echo "These candidate seed Lychrel numbers are: ", cand.seeds
echo &"Found {cand.relatedCount(4)} candidate related Lychrel numbers between 1 and 10000."
echo "Palindromic candidate Lychrel numbers between 1 and 10000 are: ", cand.palindromicLychrel(4) |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #XBS | XBS | set Responses = ["It is Certain.","It is decidedly so.","Without a doubt.","Yes definitely.","You may rely on it","As I see it, yes.","Most likely.","Outlook good.","Yes.","Sign points to yes.","Reply hazy, try again.","Ask again later.","Better not tell you now.","Cannot predict now.","Concentrate and ask again.","Don't count on it.","My reply is no.","My sources say no.","Outlook not so good.","Very doubtful."];
while(true){
window->prompt("Ask 8-Ball a question");
log(Responses[rnd(0,?Responses-1)]);
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #XPL0 | XPL0 | int Answers, Answer, Question;
[Answers:= [
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"];
Text(0, "Please enter your question or a blank line to quit.
");
while true do
[CrLf(0); Text(0, "? : ");
Question:= ChIn(0);
if Question = \CR\$0D then return;
OpenI(0); \discard any remaining chars in keyboard buffer
Answer:= Answers(Ran(20));
Text(0, Answer); CrLf(0);
]
] |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.util.*;
public class MadLibs {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String name, gender, noun;
System.out.print("Enter a name: ");
name = input.next();
System.out.print("He or she: ");
gender = input.next();
System.out.print("Enter a noun: ");
noun = input.next();
System.out.println("\f" + name + " went for a walk in the park. " + gender + "\nfound a " + noun + ". " + name + " decided to take it home.");
}
}
|
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
| #360_Assembly | 360 Assembly | * Loops/Increment loop index within loop body - 16/07/2018
LOOPILWB PROLOG
SR R6,R6 i=0
ZAP N,=P'42' n=42
DO WHILE=(C,R6,LT,IMAX) do while(i<imax)
BAL R14,ISPRIME call isprime(n)
IF C,R0,EQ,=F'1' THEN if n is prime then
LA R6,1(R6) i=i+1
XDECO R6,XDEC edit i
MVC PG+2(2),XDEC+10 output i
MVC ZN,EM load edit mask
ED ZN,N edit n
MVC PG+7(L'ZN),ZN output n
XPRNT PG,L'PG print buffer
ZAP WP,N n
AP WP,N +n
SP WP,=P'1' +1
ZAP N,WP n=n+n-1
ENDIF , endif
ZAP WP,N n
AP WP,=P'1' +1
ZAP N,WP n=n+1
ENDDO , enddo
EPILOG
ISPRIME EQU * isprime(n) -----------------------
CP N,=P'2' if n=2
BE RETURN1 then return(1)
CP N,=P'3' if n=3
BE RETURN1 then return(1)
ZAP WDP,N n
DP WDP,=PL8'2' /2
CP WDP+8(8),=P'0' if mod(n,2)=0
BE RETURN0 then return(0)
ZAP WDP,N n
DP WDP,=PL8'3' /3
CP WDP+8(8),=P'0' if mod(n,3)=0
BE RETURN0 then return(0)
ZAP J,=P'5' j=5
LWHILE ZAP WP,J j
MP WP,J *j
CP WP,N while(j*j<=n)
BH EWHILE ~
ZAP WDP,N n
DP WDP,J /j
CP WDP+8(8),=P'0' if mod(n,j)=0
BE RETURN0 then return(0)
ZAP WP,J j
AP WP,=P'2' +2
ZAP WDP,N n
DP WDP,WP n/(j+2)
CP WDP+8(8),=P'0' if mod(n,j+2)=0
BE RETURN0 then return(0)
ZAP WP,J j
AP WP,=P'6' +6
ZAP J,WP j=j+6
B LWHILE loopwhile
EWHILE B RETURN1 return(1)
RETURN0 LA R0,0 rc=0
B RETURNX
RETURN1 LA R0,1 rc=1
RETURNX BR R14 return to caller -----------------
IMAX DC F'42' limit
EM DC XL20'402020206B2020206B2020206B2020206B202120' mask
N DS PL8 n
J DS PL8 j
PG DC CL80'i=00 : 000,000,000,000,000' buffer
XDEC DS CL12 temp for XDECO
WP DS PL8 temp for AP,SP,MP
WDP DS PL16 temp for DP
CW DS CL16 temp for UNPK
ZN DS CL20
REGEQU
END LOOPILWB |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopinc64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessOverflow: .asciz "Error: overflow !!!!"
sMessResult: .asciz "Index : @ Value : @ \n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,0 // counter
mov x21,42 // start index
1: // begin loop
mov x0,x21
bl isPrime // prime ?
bcs 100f // error overflow ?
cbnz x0,2f // is prime ?
add x21,x21,1 // no -> increment index
b 1b // and loop
2: // display index and prime
add x20,x20,1 // increment counter
mov x0,x20
ldr x1,qAdrsZoneConv // conversion index
bl conversion10
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first @ character
mov x10,x0
mov x0,x21 // conversion value
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion ascii
mov x0,x10
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at second @ character
bl affichageMess
add x21,x21,x21
cmp x20,42 // end ?
blt 1b // no loop
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
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
/***************************************************/
/* Verification si un nombre est premier */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier 0 sinon */
isPrime:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
sub x1,x0,#1
cmp x2,0
beq 99f // retourne zéro
cmp x2,2 // pour 1 et 2 retourne 1
ble 2f
mov x0,#2
bl moduloPuR64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,3
beq 2f
mov x0,#3
bl moduloPuR64
blt 100f // erreur overflow
cmp x0,#1
bne 99f
cmp x2,5
beq 2f
mov x0,#5
bl moduloPuR64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,7
beq 2f
mov x0,#7
bl moduloPuR64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,11
beq 2f
mov x0,#11
bl moduloPuR64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,13
beq 2f
mov x0,#13
bl moduloPuR64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
2:
cmn x0,0 // carry à zero pas d'erreur
mov x0,1 // premier
b 100f
99:
cmn x0,0 // carry à zero pas d'erreur
mov x0,#0 // Pas premier
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/********************************************************/
/* x0 nombre */
/* x1 exposant */
/* x2 modulo */
moduloPuR64:
stp x1,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
stp x9,x10,[sp,-16]! // save registres
cbz x0,100f
cbz x1,100f
mov x8,x0
mov x7,x1
mov x6,1 // resultat
udiv x4,x8,x2
msub x9,x4,x2,x8 // contient le reste
1:
tst x7,1
beq 2f
mul x4,x9,x6
umulh x5,x9,x6
mov x6,x4
mov x0,x6
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x6,x3
2:
mul x8,x9,x9
umulh x5,x9,x9
//cbnz x5,99f
mov x0,x8
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x9,x3
lsr x7,x7,1
cbnz x7,1b
mov x0,x6 // result
cmn x0,0 // carry à zero pas d'erreur
b 100f
99:
ldr x0,qAdrszMessOverflow
bl affichageMess
cmp x0,0 // carry à un car erreur
mov x0,-1 // code erreur
100:
ldp x9,x10,[sp],16 // restaur des 2 registres
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessOverflow: .quad szMessOverflow
/***************************************************/
/* division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
stp x6,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x5,#0 // raz du reste R
mov x3,#128 // compteur de boucle
mov x4,#0 // dernier bit
1:
lsl x5,x5,#1 // on decale le reste de 1
tst x1,1<<63 // test du bit le plus à gauche
lsl x1,x1,#1 // on decale la partie haute du quotient de 1
beq 2f
orr x5,x5,#1 // et on le pousse dans le reste R
2:
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 3f
orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute
3:
orr x0,x0,x4 // position du dernier bit du quotient
mov x4,#0 // raz du bit
cmp x5,x2
blt 4f
sub x5,x5,x2 // on enleve le diviseur du reste
mov x4,#1 // dernier bit à 1
4:
// et boucle
subs x3,x3,#1
bgt 1b
lsl x1,x1,#1 // on decale le quotient de 1
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 5f
orr x1,x1,#1
5:
orr x0,x0,x4 // position du dernier bit du quotient
mov x3,x5
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x6,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #360_Assembly | 360 Assembly |
INFINITE CSECT , this PGM control section
INFINITE AMODE 31 addressing mode 31 bit
INFINITE RMODE ANY loader can load either 24 or 31
BAKR 14,0 stack caller's register contents
LR 12,15 establish base
LA 13,0 no savearea
USING INFINITE,12 base to assembler
LA 10,1 1 in reg 10
LA 11,2 2 in reg 11
LOOP EQU *
CR 10,11 1==2?
BE RETURN Yes, exit.
WTO 'SPAM',ROUTCDE=11 print SPAM to syslog
B LOOP No, check again.
RETURN PR , return to caller
END INFINITE
|
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
| #4DOS_Batch | 4DOS Batch | @echo off
do forever
echo SPAM
enddo |
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
| #BASIC256 | BASIC256 |
global sum, prod
subroutine process(x)
sum += abs(x)
if abs(prod) < (2 ^ 27) and x <> 0 then prod *= x
end subroutine
prod = 1
sum = 0
x = 5 : y = -5 : z = -2
one = 1 : three = 3 : seven = 7
for j = -three to (3 ^ 3) step three: call process(j): next j
for j = -seven to seven step x: call process(j): next j
for j = 555 to 550 - y: call process(j): next j
for j = 22 to -28 step -three: call process(j): next j
for j = 1927 to 1939: call process(j): next j
for j = x to y step z: call process(j): next j
for j = (11 ^ x) to (11 ^ x) + one: call process(j): next j
print " sum= "; int(sum)
print "prod= "; int(prod)
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
long prod = 1L, sum = 0L;
void process(int j) {
sum += abs(j);
if (labs(prod) < (1 << 27) && j) prod *= j;
}
long ipow(int n, uint e) {
long pr = n;
int i;
if (e == 0) return 1L;
for (i = 2; i <= e; ++i) pr *= n;
return pr;
}
int main() {
int j;
const int x = 5, y = -5, z = -2;
const int one = 1, three = 3, seven = 7;
long p = ipow(11, x);
for (j = -three; j <= ipow(3, 3); j += three) process(j);
for (j = -seven; j <= seven; j += x) process(j);
for (j = 555; j <= 550 - y; ++j) process(j);
for (j = 22; j >= -28; j -= three) process(j);
for (j = 1927; j <= 1939; ++j) process(j);
for (j = x; j >= y; j -= -z) process(j);
for (j = p; j <= p + one; ++j) process(j);
setlocale(LC_NUMERIC, "");
printf("sum = % 'ld\n", sum);
printf("prod = % 'ld\n", prod);
return 0;
} |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopwhile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@" // message result
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,#1024 // loop counter
1: // begin loop
mov x0,x20
ldr x1,qAdrsZoneConv // display value
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess // display return line
lsr x20,x20,1 // division by 2
cmp x20,0 // end ?
bgt 1b // no ->begin loop one
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
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/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.
| #Julia | Julia |
function ludic_filter{T<:Integer}(n::T)
0 < n || throw(DomainError())
slud = trues(n)
for i in 2:(n-1)
slud[i] || continue
x = 0
for j in (i+1):n
slud[j] || continue
x += 1
x %= i
x == 0 || continue
slud[j] = false
end
end
return slud
end
ludlen = 10^5
slud = ludic_filter(ludlen)
ludics = collect(1:ludlen)[slud]
n = 25
println("Generate and show here the first ", n, " ludic numbers.")
print(" ")
crwid = 76
wid = 0
for i in 1:(n-1)
s = @sprintf "%d, " ludics[i]
wid += length(s)
if crwid < wid
print("\n ")
wid = 0
end
print(s)
end
println(ludics[n])
n = 10^3
println()
println("How many ludic numbers are there less than or equal to ", n, "?")
println(" ", sum(slud[1:n]))
lo = 2000
hi = lo+5
println()
println("Show the ", lo, "..", hi, "'th ludic numbers.")
for i in lo:hi
println(" Ludic(", i, ") = ", ludics[i])
end
n = 250
println()
println("Show all triplets of ludic numbers < ", n)
for i = 1:n-7
slud[i] || continue
j = i+2
slud[j] || continue
k = i+6
slud[k] || continue
println(" ", i, ", ", j, ", ", k)
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
| #11l | 11l | L(i) 1..10
print(i, end' ‘’)
I !L.last_iteration
print(‘, ’, 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
| #11l | 11l | [[Int]] mat
L 10
mat [+]= (1..10).map(x -> random:(1..20))
L(row) mat
L(el) row
print(el, end' ‘ ’)
I el == 20
L(row).break |
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
| #Go | Go | package main
import "fmt"
type S struct {
start, stop, incr int
comment string
}
var examples = []S{
{-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"},
}
func sequence(s S, limit int) []int {
var seq []int
for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
seq = append(seq, i)
}
return seq
}
func main() {
const limit = 10
for _, ex := range examples {
fmt.Println(ex.comment)
fmt.Printf("Range(%d, %d, %d) -> ", ex.start, ex.stop, ex.incr)
fmt.Println(sequence(ex, limit))
fmt.Println()
}
} |
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
| #11l | 11l | V things = [‘Apple’, ‘Banana’, ‘Coconut’]
L(thing) things
print(thing) |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #APL | APL | LuhnTest←{
digits←⍎¨⍵ ⍝ Characters to digits
doubled←2∘×@(⌽⍤~1 0⍴⍨≢)⊢digits ⍝ Double every other digit
partial←-∘9@(9∘<)⊢doubled ⍝ Subtract 9 is equivalent to sum of digits for the domain 10≤x≤19
0=10|+/partial ⍝ Valid if sum is a multiple of 10
} |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(S(n))^{2}-2}
, and
S
(
1
)
=
4
{\displaystyle S(1)=4}
.
Task
Calculate all Mersenne primes up to the implementation's
maximum precision, or the 47th Mersenne prime (whichever comes first).
| #C.2B.2B | C++ | #include <iostream>
#include <gmpxx.h>
static bool is_mersenne_prime(mpz_class p)
{
if( 2 == p )
return true;
else
{
mpz_class s(4);
mpz_class div( (mpz_class(1) << p.get_ui()) - 1 );
for( mpz_class i(3); i <= p; ++i )
{
s = (s * s - mpz_class(2)) % div ;
}
return ( s == mpz_class(0) );
}
}
int main()
{
mpz_class maxcount(45);
mpz_class found(0);
mpz_class check(0);
for( mpz_nextprime(check.get_mpz_t(), check.get_mpz_t());
found < maxcount;
mpz_nextprime(check.get_mpz_t(), check.get_mpz_t()))
{
//std::cout << "P" << check << " " << std::flush;
if( is_mersenne_prime(check) )
{
++found;
std::cout << "M" << check << " " << std::flush;
}
}
} |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Phix | Phix | with javascript_semantics
constant luckyMax = 120000
sequence lucky
procedure filterLucky()
integer n = 2
while n<=length(lucky) do
integer m = lucky[n],
l = m-1
for k=m+1 to length(lucky) do
if mod(k,m)!=0 then
l += 1
lucky[l] = lucky[k]
end if
end for
if l>=length(lucky) then exit end if
lucky = lucky[1..l]
n += 1
end while
end procedure
constant helptxt = """
argument(s) | what is displayed
=======================================
j | jth lucky number
j [,] lucky | jth lucky number
j [,] evenLucky | jth even lucky number
j k | jth through kth (inclusive) lucky numbers
j k lucky | jth through kth (inclusive) lucky numbers
j k evenLucky | jth through kth (inclusive) even lucky numbers
j -k | all lucky numbers in the range j to k
j -k lucky | all lucky numbers in the range j to k
j -k evenLucky | all even lucky numbers in the range j to k
"""
procedure fatal(string msg)
puts(1,msg)
puts(1,helptxt)
{} = wait_key()
abort(0)
end procedure
procedure process(sequence cl)
--
-- Allow eg "lucky j , evenLucky" to be == "lucky j evenLucky"
--
if length(cl)=3 and cl[2]="," then cl[2..2] = {} end if
integer j, k
bool single = true, range = true, oddluck = true
for i=1 to length(cl) do
string cli = cl[i]
if cli[1]<='9' then -- (includes '-')
sequence d = scanf(cl[i],"%d")
if length(d)!=1 then
fatal("unrecognised "&cli)
end if
if i>2 then
fatal("too many numbers")
end if
integer n = d[1][1]
if i=1 then
if n<1 then
fatal("first argument must be a positive integer")
end if
j = n
else
single = false
if n<0 then
range = false
n = -n
end if
if n<j then
fatal("second argument cannot be less than first")
end if
k = n
end if
else
integer l = find(cli,{"lucky","evenLucky"})
if l=0 then
fatal("unrecognised "&cli)
end if
if i!=length(cl) then
fatal(cli&" must be last parameter")
end if
oddluck = (l=1)
end if
end for
lucky = tagset(luckyMax,2-oddluck,2)
filterLucky()
printf(1,"Output when args are %s\n",{join(cl)})
string evenstr = iff(oddluck?"":"even ")
if single then
if j>length(lucky) then
fatal(sprintf("the argument, %d, is too big", j))
end if
printf(1,"Lucky %snumber %d = %d\n",{evenstr,j, lucky[j]})
elsif range then
if k>length(lucky) then
fatal(sprintf("the argument, %d, is too big", k))
end if
printf(1,"Lucky %snumbers %d to %d are: %v\n",{evenstr,j,k,lucky[j..k]})
else
if j>lucky[$] then
fatal("start of range is too big")
elsif k>lucky[$] then
fatal("end of range is too big")
end if
integer m = abs(binary_search(j,lucky)),
n = binary_search(k,lucky)
if n<0 then n = -n-1 end if
printf(1,"Lucky %snumbers between %d and %d are: %v\n", {evenstr,j,k,lucky[m..n]})
end if
end procedure
procedure main()
sequence cl = command_line()
if length(cl)=2 then
-- fatal("at least one argument must be supplied") -- (if preferred)
sequence tests = {"1 20",
"1 20 evenLucky",
"20 lucky",
"20 evenLucky",
"6000 -6100",
"6000 -6100 evenLucky",
"10000 lucky",
"10000 evenLucky"}
-- (done this way to exercise the real command line handling...)
if cl[1]=cl[2] then -- (compiled)
cl = cl[1..1]
elsif platform()=WINDOWS then -- (and interpreted)
cl[1] = substitute(cl[1],"pw","p") -- (pw.exe -> p.exe)
end if
for i=1 to length(cl) do
if find(' ',cl[i]) then cl[i] = sprintf("\"%s\"",{cl[i]}) end if
end for
for t=1 to length(tests) do
if platform()=JS then
-- (...except when we can't do that, of course)
process(split(tests[t]))
else
string cmd = join(append(deep_copy(cl),tests[t]))
-- printf(1,"running %s\n",{cmd})
{} = system_exec(cmd)
end if
end for
puts(1, "tests complete\n")
{} = wait_key()
else
cl = cl[3..$] -- ({1,2} are {interperter,source} or {exe,exe})
process(cl)
end if
end procedure
main()
|
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.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE}
make
local
test: LINKED_LIST [INTEGER]
do
create test.make
test := compress ("TOBEORNOTTOBEORTOBEORNOT")
across
test as t
loop
io.put_string (t.item.out + " ")
end
io.new_line
io.put_string (decompress (test))
end
decompress (compressed: LINKED_LIST [INTEGER]): STRING
--Decompressed version of 'compressed'.
local
dictsize, i, k: INTEGER
dictionary: HASH_TABLE [STRING, INTEGER]
w, entry: STRING
char: CHARACTER_8
do
dictsize := 256
create dictionary.make (300)
create entry.make_empty
create Result.make_empty
from
i := 0
until
i > 256
loop
char := i.to_character_8
dictionary.put (char.out, i)
i := i + 1
end
w := compressed.first.to_character_8.out
compressed.go_i_th (1)
compressed.remove
Result := w
from
k := 1
until
k > compressed.count
loop
if attached dictionary.at (compressed [k]) as ata then
entry := ata
elseif compressed [k] = dictsize then
entry := w + w.at (1).out
else
io.put_string ("EXEPTION")
end
Result := Result + entry
dictsize := dictsize + 1
dictionary.put (w + entry.at (1).out, dictsize)
w := entry
k := k + 1
end
end
compress (uncompressed: STRING): LINKED_LIST [INTEGER]
-- Compressed version of 'uncompressed'.
local
dictsize: INTEGER
dictionary: HASH_TABLE [INTEGER, STRING]
i: INTEGER
w, wc: STRING
char: CHARACTER_8
do
dictsize := 256
create dictionary.make (256)
create w.make_empty
from
i := 0
until
i > 256
loop
char := i.to_character_8
dictionary.put (i, char.out)
i := i + 1
end
create Result.make
from
i := 1
until
i > uncompressed.count
loop
wc := w + uncompressed [i].out
if dictionary.has (wc) then
w := wc
else
Result.extend (dictionary.at (w))
dictSize := dictSize + 1
dictionary.put (dictSize, wc)
w := "" + uncompressed [i].out
end
i := i + 1
end
if w.count > 0 then
Result.extend (dictionary.at (w))
end
end
end
|
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #J | J | mp=: +/ .*
LU=: 3 : 0
'm n'=. $ A=. y
if. 1=m do.
p ; (=1) ; p{"1 A [ p=. C. (n-1);~.0,(0~:,A)i.1
else.
m2=. >.m%2
'p1 L1 U1'=. LU m2{.A
D=. (/:p1) {"1 m2}.A
F=. m2 {."1 D
E=. m2 {."1 U1
FE1=. F mp %. E
G=. m2}."1 D - FE1 mp U1
'p2 L2 U2'=. LU G
p3=. (i.m2),m2+p2
H=. (/:p3) {"1 U1
(p1{p3) ; (L1,FE1,.L2) ; H,(-n){."1 U2
end.
)
permtomat=: 1 {.~"0 -@>:@:/:
LUdecompose=: (permtomat&.>@{. , }.)@:LU |
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.
| #Pascal | Pascal | program p196;
{$IFDEF FPC}
{$R-}
{$MODE DELPHI}
{$Optimization ON}
{$Else}
{$APPTYPE console}
{$Endif}
{
nativeUint = LongWord;//Uint64
nativeInt = LongInt;//Int64
}
uses
SysUtils,classes;
const
cMAXNUM = 100*1000*1000;//100*1000*1000;
cMaxCycle = 1500;
cChkDigit = 10;//first check lychrel found
MaxLen = 256;//maximal count of digits
cMaxDigit = MAXLEN-1;
type
TDigit = byte;
tpDigit =^TDigit;
tDigitArr = array[0..0] of tDigit;
tpDigitArr = ^tDigitArr;
//LSB at position 0
TNumber = record
nNum : array [0..cMaxDigit] of TDigit;
nMaxPos : LongInt;
end;
tRelated = array[0..cMAXNUM] of byte;
procedure NumberFromString(var Number: TNumber; S: string);
var
i,le: integer;
begin
le := Length(s);
IF le > cMaxDigit then
le := cMaxDigit;
Number.nMaxPos:= le-1;
for i:= 0 to le-1 do
Number.nNum[i]:= Ord(s[le- i]) - Ord('0');
end;
function NumberToString(var Number: TNumber): string;
var
i,l: integer;
begin
i := Number.nMaxPos;
If i <= MAXLEN then
begin
SetLength(Result, i+1);
l := i+1;
i := 0;
repeat
Result[l]:= Chr(Ord('0') + Number.nNum[i]);
inc(i);
dec(l);
until l <= 0;
end
else
begin
SetLength(Result, MAXLEN);
fillchar(Result[1],MAXLEN,'.');
For l := 1 to MAXLEN DIV 2-1 do
Begin
Result[l] := Chr(Ord('0') + Number.nNum[i-l+1]);
Result[l+MAXLEN DIV 2+1] := Chr(Ord('0') + Number.nNum[24-l]);
end;
end;
end;
procedure CorrectCarry(var Number : TNumber);
//correct sum of digit to digit and carry
//without IF d>10 then...
var
d,i,carry: nativeInt;
p: tpDigitArr;
begin
carry := 0;
i := Number.nMaxPos;
p := @Number.nNum[i];
i := -i;
For i := i to 0 do
Begin
d := p^[i]+carry;
carry := ord(d>=10);//0, 1-> (-10 AND(-carry) = 0 ,-10
p^[i] := d+(-10 AND(-carry));
end;
//correct length
IF carry >0 then
begin
i := Number.nMaxPos+1;
Number.nNum[i] :=1;
NUmber.nMaxPos := i;
end;
end;
procedure NumberAdd(var Number : TNumber);
// first add than correct carry
var
//pointer, for fpc is a little bit slow with dynamic array
loIdx,hiIdx: integer;
sum: nativeUint;
begin
loIdx := 0;
hiIdx := Number.nMaxPos;
while loIdx< hiIdx do
Begin
sum := Number.nNum[loIdx]+Number.nNum[hiIdx];
Number.nNum[loIdx] := sum;
Number.nNum[hiIdx] := sum;
inc(loIdx);
dec(HiIdx);
end;
IF loIdx = hiIdx then
Number.nNum[loIdx] := 2*Number.nNum[loIdx];
CorrectCarry(Number);
end;
function PalinCheck(var A: TNumber): boolean;
var
loIdx,hiIdx: integer;
begin
loIdx := 0;
hiIdx := A.nMaxPos;
repeat
Result:= A.nNum[loIdx]=A.nNum[hiIdx];
inc(loIdx);
dec(hiIdx);
until Not(Result) OR (hiIdx<loIdx);
end;
procedure ShowPalinLychrel(var Related:tRelated);
var
i : NativeInt;
s : string;
slRes : TStringList;
Work: TNumber;
Begin
slRes := TStringList.create;
For i := 0 to High(Related) do
begin
IF Related[i] <> 0 then
Begin
s := IntToSTr(i);
NumberFromString(Work,s);
If PalinCheck(Work) then
slRes.Add(s);
end;
end;
Writeln('number of palindromatic lychrel ',slRes.count:8);
IF slRes.Count < 10 then
Begin
For i := 0 to slRes.count-2 do
write(slRes[i]:8,',');
writeln(slRes[slRes.count-1]:8);
end;
slRes.free;
end;
var
Related : tRelated;
slSeedCache,
slFirstChkCache : TStringList;
Seeds : array of LongInt;
Work: TNumber;
num,findpos,InsPos : LongInt;
relCount : NativeUint;
s,f: string;
procedure FirstCheckCache;
//Test if Work is already in Cache
//if not it will be inserted
//Inspos saves the position
var
i : LongInt;
Begin
f:= NumberToString(Work);
IF slFirstChkCache.find(f,i) then
Begin
IF slFirstChkCache.Objects[i]<> NIL then
Begin
Related[num] := 2;
inc(RelCount);
end;
end
else
Begin
//memorize the number as Object
InsPos := slFirstChkCache.addObject(f,TObject(num));
end;
end;
begin
fillchar(Related[1],Length(Related),#0);
relCount := 0;
slSeedCache := TStringList.create;
slSeedCache.sorted := true;
slSeedCache.duplicates := dupIgnore;
slFirstChkCache := TStringList.create;
slFirstChkCache.sorted := true;
slFirstChkCache.duplicates := dupIgnore;
setlength(Seeds,0);
num := 1;
repeat
s := IntToStr(num);
NumberFromString(Work, s);
findPos := -1;
InsPos := -1;
//early test if already in Cache
repeat
NumberAdd(Work);
IF (Work.nMaxPos = cChkDigit) then
Begin
FirstCheckCache;
BREAK;
end;
until PalinCheck(Work);
//IF new number of cChkDigit length inserted in Cache
IF (InsPos >= 0) AND NOT (PalinCheck(Work)) then
Begin
//check for lychrel
while Work.nMaxPos < cMaxDigit do
Begin
NumberAdd(Work);
if PalinCheck(Work) then
BREAK;
end;
if Work.nMaxPos >= cMaxDigit then
Begin
f := NumberToString(Work);
//new lychrel seed found
IF NOT(slSeedCache.find(f,findPos)) then
Begin
//memorize the number by misusing of Object
slSeedCache.addObject(f,TObject(num));
setlength(Seeds,length(Seeds)+1);
Seeds[High(Seeds)] := num;
Related[num] := 1;
end
else
Begin
//a new way to known lycrel seed found, so memorize it
Related[num] := 2;
inc(RelCount)
end
end
else
//mark slFirstChkCache[InsPos] as not_lychrel
slFirstChkCache.Objects[InsPos] := NIL;
end;
inc(num);
until num > cMAXNUM;
writeln ('Lychrel from 1 to ',cMAXNUM);
writeln('number of cached ',cChkDigit,' digit ',slFirstChkCache.Count);
writeln('number of lychrel seed ',length(Seeds):8);
IF length(Seeds) < 10 then
Begin
For InsPos:= 0 to High(Seeds)-1 do
write(Seeds[InsPos],',');
writeln(Seeds[High(seeds)]);
end;
writeln('number of lychrel related ',RelCount:8);
ShowPalinLychrel(Related);
slFirstChkCache.free;
slSeedCache.free;
setlength(Seeds,0);
end.
{
...
Lychrel from 1 to 100000000
number of cached 10 digit 7008
number of lychrel seed 3552
number of lychrel related 28802508
number of palindromatic lychrel 5074
real 0m48.634s
user 0m48.579s
sys 0m0.012s
} |
http://rosettacode.org/wiki/Magic_8-ball | Magic 8-ball | Task
Create Magic 8-Ball.
See details at: Magic 8-Ball.
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
| #zkl | zkl | answers:=T(
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
);
println("Please enter your question or a blank line to quit.");
while(ask("? : ")){ println(answers[(0).random(answers.len())]) } |
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
| #Julia | Julia |
function madlibs(template)
println("The story template is:\n", template)
fields = Set(getfield.(collect(eachmatch(r"<[^>]+>", template)), :match))
print("\nInput a comma-separated list of words to replace the following items:",
join(fields, ", "), "\n -> ")
values = split(readline(STDIN), ",")
for (m, v) in zip(fields, values)
template = replace(template, m, v)
end
println("\nThe story becomes:\n", template)
end
const template = """
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
"""
madlibs(template) |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable) at 42
(at iteration time) increments the index by unity
if the index is prime:
displays the count of primes found (so far) and the prime (to the terminal)
increments the index such that the new index is now the (old) index plus that prime
terminates the loop when 42 primes are shown
Extra credit: because of the primes get rather large, use commas
within the displayed primes to ease comprehension.
Show all output here.
Note
Not all programming languages allow the modification of a
loop's index. If that is the case, then use whatever method that
is appropriate or idiomatic for that language. Please add a note
if the loop's index isn't modifiable.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO.Editing; use Ada.Text_IO.Editing;
with Ada.Numerics.Generic_Elementary_Functions;
procedure Main is
type nums is delta 0.1 digits 15;
format : String := "zz_zzz_zzz_zzz_zzz_zz9.9";
pic : picture := To_Picture (format);
package Nums_io is new Decimal_Output (Nums);
use Nums_IO;
type U_64 is mod 2**64;
package mod_io is new Modular_IO (U_64);
use mod_io;
function Is_Prime (Num : U_64) return boolean is
package Flt_Funcs is new Ada.Numerics.Generic_Elementary_Functions
(Float);
use Flt_Funcs;
T : U_64 := 2;
Limit : constant U_64 := U_64 (Sqrt (Float (Num)));
begin
if Num = 2 then
return True;
end if;
while T <= Limit loop
if Num mod T = 0 then
return False;
end if;
T := T + (if T > 2 then 2 else 1);
end loop;
return True;
end Is_Prime;
Prime_Count : natural := 0;
Prime_Test : U_64 := 42;
begin
loop
if Is_Prime (Prime_Test) then
Prime_Count := Prime_Count + 1;
Put ("n =");
Put (Item => Prime_Count, Width => 3);
Put (Item => Nums (Prime_Test), Pic => pic);
New_Line;
Prime_Test := (Prime_Test * 2) - 1;
end if;
Prime_Test := Prime_Test + 1;
exit when Prime_Count = 42;
end loop;
end Main;
|
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
| #6502_Assembly | 6502 Assembly | InfiniteLoop LDX #0
PrintLoop: LDA MSG,x
JSR PrintAccumulator ;routine not implemented
INX
CPX #5
BNE PrintLoop
BEQ InfiniteLoop
MSG .byte "SPAM", $0A |
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
| #6800_Assembly | 6800 Assembly | .cr 6800
.tf spam6800.obj,AP1
.lf spam6800
;=====================================================;
; Infinite SPAM loop for the Motorola 6800 ;
; by barrym 2013-04-10 ;
;-----------------------------------------------------;
; Prints the message "SPAM" repeatedly to an ascii ;
; terminal (console) connected to a 1970s vintage ;
; SWTPC 6800 system, which is the target device for ;
; this assembly. ;
; Many thanks to: ;
; swtpc.com for hosting Michael Holley's documents! ;
; sbprojects.com for a very nice assembler! ;
; swtpcemu.com for a very capable emulator! ;
; reg x is the string pointer ;
; reg a holds the ascii char to be output ;
;-----------------------------------------------------;
outeee = $e1d1 ;ROM: console putchar routine
.or $0f00
;-----------------------------------------------------;
main ldx #string ;Point to the string
bra puts ; and print it
outs jsr outeee ;Emit a as ascii
inx ;Advance the string pointer
puts ldaa ,x ;Load a string character
bne outs ;Print it if non-null
bra main ;else restart
;=====================================================;
string .as "SPAM",#13,#10,#0
.en |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public static class LoopsWithMultipleRanges
{
public static void Main() {
int prod = 1;
int sum = 0;
int x = 5;
int y = -5;
int z = -2;
int one = 1;
int three = 3;
int seven = 7;
foreach (int j in Concat(
For(-three, 3.Pow(3), three),
For(-seven, seven, x),
For(555, 550 - y),
For(22, -28, -three),
For(1927, 1939),
For(x, y, z),
For(11.Pow(x), 11.Pow(x) + one)
)) {
sum += Math.Abs(j);
if (Math.Abs(prod) < (1 << 27) && j != 0) prod *= j;
}
Console.WriteLine($" sum = {sum:N0}");
Console.WriteLine($"prod = {prod:N0}");
}
static IEnumerable<int> For(int start, int end, int by = 1) {
for (int i = start; by > 0 ? (i <= end) : (i >= end); i += by) yield return i;
}
static IEnumerable<int> Concat(params IEnumerable<int>[] ranges) => ranges.Aggregate((acc, r) => acc.Concat(r));
static int Pow(this int b, int e) => (int)Math.Pow(b, e);
} |
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
| #Action.21 | Action! | PROC Main()
CARD i=[1024]
WHILE i>0
DO
PrintCE(i)
i=i/2
OD
RETURN |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ActionScript | ActionScript | var i:int = 1024;
while (i > 0) {
trace(i);
i /= 2;
} |
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.
| #Kotlin | Kotlin | // version 1.0.6
/* Rather than remove elements from a MutableList which would be a relatively expensive operation
we instead use two arrays:
1. An array of the Ludic numbers to be returned.
2. A 'working' array of a suitable size whose elements are set to 0 to denote removal. */
fun ludic(n: Int): IntArray {
if (n < 1) return IntArray(0)
val lu = IntArray(n) // array of Ludic numbers required
lu[0] = 1
if (n == 1) return lu
var count = 1
var count2: Int
var j: Int
var k = 1
var ub = n * 11 // big enough to deal with up to 2005 ludic numbers
val a = IntArray(ub) { it } // working array
while (true) {
k += 1
for (i in k until ub) {
if (a[i] > 0) {
count +=1
lu[count - 1] = a[i]
if (n == count) return lu
a[i] = 0
k = i
break
}
}
count2 = 0
j = k + 1
while (j < ub) {
if (a[j] > 0) {
count2 +=1
if (count2 == k) {
a[j] = 0
count2 = 0
}
}
j += 1
}
}
}
fun main(args: Array<String>) {
val lu: IntArray = ludic(2005)
println("The first 25 Ludic numbers are :")
for (i in 0 .. 24) print("%4d".format(lu[i]))
val count = lu.count { it <= 1000 }
println("\n\nThere are $count Ludic numbers <= 1000" )
println("\nThe 2000th to 2005th Ludics are :")
for (i in 1999 .. 2004) print("${lu[i]} ")
println("\n\nThe Ludic triplets below 250 are : ")
var k: Int = 0
var ldc: Int
var b: Boolean
for (i in 0 .. 247) {
ldc = lu[i]
if (ldc >= 244) break
b = false
for (j in i + 1 .. 248) {
if (lu[j] == ldc + 2) {
b = true
k = j
break
}
else if (lu[j] > ldc + 2) break
}
if (!b) continue
for (j in k + 1 .. 249) {
if (lu[j] == ldc + 6) {
println("($ldc, ${ldc + 2}, ${ldc + 6})")
break
}
else if (lu[j] > ldc + 6) break
}
}
} |
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
| #360_Assembly | 360 Assembly |
* Loops/N plus one half 13/08/2015
LOOPHALF CSECT USING LOOPHALF,R12
LR R12,R15
BEGIN LA R3,MVC
SR R5,R5
LA R6,1
LA R7,10
LOOPI BXH R5,R6,ELOOPI for i=1 to 10
XDECO R5,XDEC
MVC 0(4,R3),XDEC+8
LA R3,4(R3)
CH R5,=H'10'
BNL NEXTI
MVC 0(2,R3),=C', '
LA R3,2(R3)
NEXTI B LOOPI next i
ELOOPI XPRNT MVC,80
XR R15,R15
BR R14
MVC DC CL80' '
XDEC DS CL12
YREGS
END LOOPHALF
|
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
| #360_Assembly | 360 Assembly | * Loop nested 12/08/2015
LOOPNEST CSECT
USING LOOPNEST,R12
LR R12,R15
BEGIN LA R6,0 i
LA R8,1
LA R9,20
LOOPI1 BXH R6,R8,ELOOPI1 do i=1 to hbound(x,1)
LA R7,0 j
LA R10,1
LA R11,20
LOOPJ1 BXH R7,R10,ELOOPJ1 do j=1 to hbound(x,2)
L R5,RANDSEED n
M R4,=F'397204094' r4r5=n*const
D R4,=X'7FFFFFFF' r5=r5 div (2^31-1)
ST R4,RANDSEED r4=r5 mod (2^31-1) ; n=r4
LR R5,R4 r5=n
LA R4,0
D R4,=F'20' r5=n div nn; r4=n mod nn
LR R2,R4 r2=randint(nn) [0:nn-1]
LA R2,1(R2) randint(nn)+1
LR R1,R6 i
BCTR R1,0
MH R1,=H'20'
LR R5,R7 j
BCTR R5,0
AR R1,R5
SLA R1,2
ST R2,X(R1) x(i,j)=randint(20)+1
B LOOPJ1
ELOOPJ1 B LOOPI1
ELOOPI1 MVC MVCZ,=CL80' '
LA R6,0 i
LA R8,1
LA R9,20
LOOPI2 BXH R6,R8,ELOOPI2 do i=1 to hbound(x,1)
LA R7,0 j
LA R10,1
LA R11,20
LOOPJ2 BXH R7,R10,ELOOPJ2 do j=1 to hbound(x,2)
LR R1,R6
BCTR R1,0
MH R1,=H'20'
LR R5,R7
BCTR R5,0
AR R1,R5
SLA R1,2
L R5,X(R1) x(i,j)
LR R2,R5
LA R3,MVCZ
AH R3,MVCI
XDECO R2,XDEC
MVC 0(4,R3),XDEC+8
LH R3,MVCI
LA R3,4(R3)
STH R3,MVCI
L R5,X(R1)
C R5,=F'20' if x(i,j)=20
BE ELOOPI2 then exit
B LOOPJ2
ELOOPJ2 XPRNT MVCZ,80
MVC MVCI,=H'0'
MVC MVCZ,=CL80' '
B LOOPI2
ELOOPI2 XPRNT MVCZ,80
RETURN XR R15,R15
BR R14
X DS 400F
MVCZ DS CL80
MVCI DC H'0'
XDEC DS CL16
RANDSEED DC F'16807' running n
YREGS
END LOOPNEST |
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
| #Haskell | Haskell | import Data.List
main = putStrLn $ showTable True '|' '-' '+' table
table = [["start","stop","increment","Comment","Code","Result/Analysis"]
,["-2","2","1","Normal","[-2,-1..2] or [-2..2]",show [-2,-1..2]]
,["-2","2","0","Zero increment","[-2,-2..2]","Infinite loop of -2 <=> repeat -2"]
,["-2","2","-1","Increments away from stop value","[-2,-3..2]",show [-2,-3..2]]
,["-2","2","10","First increment is beyond stop value","[-2,8..2]",show [-2,8..2]]
,["2","-2","1","Start more than stop: positive increment","[2,3.. -2]",show [2,3.. -2]]
,["2","2","1","Start equal stop: positive increment","[2,3..2]",show [2,3..2]]
,["2","2","-1","Start equal stop: negative increment","[2,1..2]",show [2,1..2]]
,["2","2","0","Start equal stop: zero increment","[2,2..2]","Infinite loop of 2 <=> repeat 2"]
,["0","0","0","Start equal stop equal zero: zero increment","[0,0..0]", "Infinite loop of 0 <=> repeat 0"]]
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss |
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
| #ACL2 | ACL2 | (defun print-list (xs)
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-list (rest xs))))) |
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
| #AppleScript | AppleScript | -- luhn :: String -> Bool
on luhn(s)
-- True if the digit string represents
-- a valid Luhn credit card number.
script divMod10Sum
on |λ|(a, x)
a + x div 10 + x mod 10
end |λ|
end script
0 = foldl(divMod10Sum, 0, ¬
zipWith(my mul, ¬
map(my int, reverse of (characters of s)), ¬
cycle({1, 2}))) mod 10
end luhn
--------------------------- TEST ---------------------------
on run
map(luhn, ¬
{"49927398716", "49927398717", ¬
"1234567812345678", "1234567812345670"})
--> {true, false, false, true}
end run
---------------- REUSABLE GENERIC FUNCTIONS ----------------
-- cycle :: [a] -> Generator [a]
on cycle(xs)
script
property lng : 1 + (length of xs)
property i : missing value
on |λ|()
if missing value is i then
set i to 1
else
set nxt to (1 + i) mod lng
if 0 = ((1 + i) mod lng) then
set i to 1
else
set i to nxt
end if
end if
return item i of xs
end |λ|
end script
end cycle
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- int :: String -> Int
on int(s)
s as integer
end int
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mul (*) :: Num a => a -> a -> a
on mul(a, b)
a * b
end mul
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith |
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).
| #Clojure | Clojure | (defn prime? [i]
(cond (< i 4) (>= i 2)
(zero? (rem i 2)) false
:else (not-any? #(zero? (rem i %)) (range 3 (inc (Math/sqrt i))))))))
(defn mersenne? [p] (or (= p 2)
(let [mp (dec (bit-shift-left 1 p))]
(loop [n 3 s 4]
(if (> n p)
(zero? s)
(recur (inc n) (rem (- (* s s) 2) mp)))))))
(filter mersenne? (filter prime? (iterate inc 1))) |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #PicoLisp | PicoLisp | (off *Even)
(de nn (Lst N)
(seek
'((L)
(when (car L) (=0 (dec 'N))) )
Lst ) )
(de lucky (B)
(let Lst (range (if *Even 2 1) B 2)
(for A (cdr Lst)
(for (L (nn Lst A) L (nn (cdr L) A))
(set L) ) )
(filter bool Lst) ) )
(argv . *Argv) # without validations
(when (= "evenLucky" (last *Argv)) (on *Even))
(setq *Lst (lucky 7000))
(let (A (format (car *Argv)) B (format (cadr *Argv)))
(println
(if (lt0 B)
(filter '((N) (<= A N (abs B))) *Lst)
(head B (nth *Lst A)) ) ) ) |
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Python | Python | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]
lenlst = len(lst)
# drain
for i in lst[n:]:
yield i |
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.
| #Elixir | Elixir | defmodule LZW do
@encode_map Enum.into(0..255, Map.new, &{[&1],&1})
@decode_map Enum.into(0..255, Map.new, &{&1,[&1]})
def encode(str), do: encode(to_char_list(str), @encode_map, 256, [])
defp encode([h], d, _, out), do: Enum.reverse([d[[h]] | out])
defp encode([h|t], d, free, out) do
val = d[[h]]
find_match(t, [h], val, d, free, out)
end
defp find_match([h|t], l, lastval, d, free, out) do
case Map.fetch(d, [h|l]) do
{:ok, val} -> find_match(t, [h|l], val, d, free, out)
:error -> d1 = Map.put(d, [h|l], free)
encode([h|t], d1, free+1, [lastval | out])
end
end
defp find_match([], _, lastval, _, _, out), do: Enum.reverse([lastval | out])
def decode([h|t]) do
val = @decode_map[h]
decode(t, val, 256, @decode_map, val)
end
defp decode([], _, _, _, l), do: Enum.reverse(l) |> to_string
defp decode([h|t], old, free, d, l) do
val = if h == free, do: old ++ [List.first(old)], else: d[h]
add = [List.last(val) | old]
d1 = Map.put(d, free, add)
decode(t, val, free+1, d1, val++l)
end
end
str = "TOBEORNOTTOBEORTOBEORNOT"
IO.inspect enc = LZW.encode(str)
IO.inspect dec = LZW.decode(enc)
IO.inspect str == dec |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
While the Cholesky decomposition only works for symmetric,
positive definite matrices, the more general LU decomposition
works for any square matrix.
There are several algorithms for calculating L and U.
To derive Crout's algorithm for a 3x3 example,
we have to solve the following system:
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
l
11
0
0
l
21
l
22
0
l
31
l
32
l
33
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU}
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of
L
{\displaystyle L}
are set to 1
l
11
=
1
{\displaystyle l_{11}=1}
l
22
=
1
{\displaystyle l_{22}=1}
l
33
=
1
{\displaystyle l_{33}=1}
so we get a solvable system of 9 unknowns and 9 equations.
A
=
(
a
11
a
12
a
13
a
21
a
22
a
23
a
31
a
32
a
33
)
=
(
1
0
0
l
21
1
0
l
31
l
32
1
)
(
u
11
u
12
u
13
0
u
22
u
23
0
0
u
33
)
=
(
u
11
u
12
u
13
u
11
l
21
u
12
l
21
+
u
22
u
13
l
21
+
u
23
u
11
l
31
u
12
l
31
+
u
22
l
32
u
13
l
31
+
u
23
l
32
+
u
33
)
=
L
U
{\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU}
Solving for the other
l
{\displaystyle l}
and
u
{\displaystyle u}
, we get the following equations:
u
11
=
a
11
{\displaystyle u_{11}=a_{11}}
u
12
=
a
12
{\displaystyle u_{12}=a_{12}}
u
13
=
a
13
{\displaystyle u_{13}=a_{13}}
u
22
=
a
22
−
u
12
l
21
{\displaystyle u_{22}=a_{22}-u_{12}l_{21}}
u
23
=
a
23
−
u
13
l
21
{\displaystyle u_{23}=a_{23}-u_{13}l_{21}}
u
33
=
a
33
−
(
u
13
l
31
+
u
23
l
32
)
{\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})}
and for
l
{\displaystyle l}
:
l
21
=
1
u
11
a
21
{\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}}
l
31
=
1
u
11
a
31
{\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}}
l
32
=
1
u
22
(
a
32
−
u
12
l
31
)
{\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})}
We see that there is a calculation pattern, which can be expressed as the following formulas, first for
U
{\displaystyle U}
u
i
j
=
a
i
j
−
∑
k
=
1
i
−
1
u
k
j
l
i
k
{\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}}
and then for
L
{\displaystyle L}
l
i
j
=
1
u
j
j
(
a
i
j
−
∑
k
=
1
j
−
1
u
k
j
l
i
k
)
{\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})}
We see in the second formula that to get the
l
i
j
{\displaystyle l_{ij}}
below the diagonal, we have to divide by the diagonal element (pivot)
u
j
j
{\displaystyle u_{jj}}
, so we get problems when
u
j
j
{\displaystyle u_{jj}}
is either 0 or very small, which leads to numerical instability.
The solution to this problem is pivoting
A
{\displaystyle A}
, which means rearranging the rows of
A
{\displaystyle A}
, prior to the
L
U
{\displaystyle LU}
decomposition, in a way that the largest element of each column gets onto the diagonal of
A
{\displaystyle A}
. Rearranging the rows means to multiply
A
{\displaystyle A}
by a permutation matrix
P
{\displaystyle P}
:
P
A
⇒
A
′
{\displaystyle PA\Rightarrow A'}
Example:
(
0
1
1
0
)
(
1
4
2
3
)
⇒
(
2
3
1
4
)
{\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}}
The decomposition algorithm is then applied on the rearranged matrix so that
P
A
=
L
U
{\displaystyle PA=LU}
Task description
The task is to implement a routine which will take a square nxn matrix
A
{\displaystyle A}
and return a lower triangular matrix
L
{\displaystyle L}
, a upper triangular matrix
U
{\displaystyle U}
and a permutation matrix
P
{\displaystyle P}
,
so that the above equation is fulfilled.
You should then test it on the following two examples and include your output.
Example 1
A
1 3 5
2 4 7
1 1 0
L
1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000
U
2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000
P
0 1 0
1 0 0
0 0 1
Example 2
A
11 9 24 2
1 5 2 6
3 17 18 1
2 5 7 1
L
1.00000 0.00000 0.00000 0.00000
0.27273 1.00000 0.00000 0.00000
0.09091 0.28750 1.00000 0.00000
0.18182 0.23125 0.00360 1.00000
U
11.00000 9.00000 24.00000 2.00000
0.00000 14.54545 11.45455 0.45455
0.00000 0.00000 -3.47500 5.68750
0.00000 0.00000 0.00000 0.51079
P
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
| #Java | Java | import static java.util.Arrays.stream;
import java.util.Locale;
import static java.util.stream.IntStream.range;
public class Test {
static double dotProduct(double[] a, double[] b) {
return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();
}
static double[][] matrixMul(double[][] A, double[][] B) {
double[][] result = new double[A.length][B[0].length];
double[] aux = new double[B.length];
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < B.length; k++)
aux[k] = B[k][j];
for (int i = 0; i < A.length; i++)
result[i][j] = dotProduct(A[i], aux);
}
return result;
}
static double[][] pivotize(double[][] m) {
int n = m.length;
double[][] id = range(0, n).mapToObj(j -> range(0, n)
.mapToDouble(i -> i == j ? 1 : 0).toArray())
.toArray(double[][]::new);
for (int i = 0; i < n; i++) {
double maxm = m[i][i];
int row = i;
for (int j = i; j < n; j++)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row) {
double[] tmp = id[i];
id[i] = id[row];
id[row] = tmp;
}
}
return id;
}
static double[][][] lu(double[][] A) {
int n = A.length;
double[][] L = new double[n][n];
double[][] U = new double[n][n];
double[][] P = pivotize(A);
double[][] A2 = matrixMul(P, A);
for (int j = 0; j < n; j++) {
L[j][j] = 1;
for (int i = 0; i < j + 1; i++) {
double s1 = 0;
for (int k = 0; k < i; k++)
s1 += U[k][j] * L[i][k];
U[i][j] = A2[i][j] - s1;
}
for (int i = j; i < n; i++) {
double s2 = 0;
for (int k = 0; k < j; k++)
s2 += U[k][j] * L[i][k];
L[i][j] = (A2[i][j] - s2) / U[j][j];
}
}
return new double[][][]{L, U, P};
}
static void print(double[][] m) {
stream(m).forEach(a -> {
stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n));
System.out.println();
});
System.out.println();
}
public static void main(String[] args) {
double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};
double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},
{2.0, 5, 7, 1}};
for (double[][] m : lu(a))
print(m);
System.out.println();
for (double[][] m : lu(b))
print(m);
}
} |
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.
| #Perl | Perl | use strict;
use warnings;
use English;
use Const::Fast;
use Math::AnyNum qw(:overload);
const my $n_max => 10_000;
const my $iter_cutoff => 500;
my(@seq_dump, @seed_lychrels, @related_lychrels);
for (my $n=1; $n<=$n_max; $n++) {
my @seq = lychrel_sequence($n);
if ($iter_cutoff == scalar @seq) {
if (has_overlap(\@seq, \@seq_dump)) { push @related_lychrels, $n }
else { push @seed_lychrels, $n }
@seq_dump = set_union(\@seq_dump, \@seq);
}
}
printf "%45s %s\n", "Number of seed Lychrels <= $n_max:", scalar @seed_lychrels;
printf "%45s %s\n", "Seed Lychrels <= $n_max:", join ', ', @seed_lychrels;
printf "%45s %s\n", "Number of related Lychrels <= $n_max:", scalar @related_lychrels;
printf "%45s %s\n", "Palindromes among seed and related <= $n_max:",
join ', ', sort {$a <=> $b} grep { is_palindrome($ARG) } @seed_lychrels, @related_lychrels;
sub lychrel_sequence {
my $n = shift;
my @seq;
for (1 .. $iter_cutoff) {
return if is_palindrome($n = next_n($n));
push @seq, $n;
}
@seq;
}
sub next_n { my $n = shift; $n + reverse($n) }
sub is_palindrome { my $n = shift; $n eq reverse($n) }
sub has_overlap {
my ($a, $b) = @ARG;
my %h;
$h{$_}++ for @{$a};
exists $h{$_} and return 1 for @{$b};
0;
}
sub set_union {
my ($a, $b) = @ARG;
my %h;
$h{$_}++ for @{$a}, @{$b};
keys %h;
} |
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
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
println("Please enter a multi-line story template terminated by a blank line\n")
val sb = StringBuilder()
while (true) {
val line = readLine()!!
if (line.isEmpty()) break
sb.append("$line\n") // preserve line breaks
}
var story = sb.toString()
// identify blanks
val r = Regex("<.*?>")
val blanks = r.findAll(story).map { it.value }.distinct()
println("Please enter your replacements for the following 'blanks' in the story:")
for (blank in blanks) {
print("${blank.drop(1).dropLast(1)} : ")
val repl = readLine()!!
story = story.replace(blank, repl)
}
println("\n$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
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns TRUE if n is prime, FALSE otherwise #
PROC is prime = ( LONG INT n )BOOL:
IF n MOD 2 = 0 THEN n = 2
ELIF n MOD 3 = 0 THEN n = 3
ELSE
LONG INT d := 5;
BOOL result := TRUE;
WHILE IF d * d > n THEN FALSE
ELIF n MOD d = 0 THEN result := FALSE
ELIF d +:= 2;
n MOD d = 0 THEN result := FALSE
ELSE d +:= 4; TRUE
FI
DO SKIP OD;
result
FI # is prime # ;
LONG INT i := 42;
LONG INT n := 0;
WHILE n < 42 DO
IF is prime( i ) THEN
n +:= 1;
print( ( "n = "
, whole( n, -2 )
, " "
, whole( i, -19 )
, newline
)
);
i +:= i - 1
FI;
i +:= 1
OD
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
| #68000_Assembly | 68000 Assembly | doSPAM:
LEA Message,A0
JSR PrintString
JMP doSPAM
Message:
DC.B "SPAM",13,10,0
EVEN |
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
| #8086_Assembly | 8086 Assembly | Spam:
mov ah,02h
mov dl,'S' ;VASM replaces a character in single quotes with its ascii equivalent
int 21h ;Print Char routine
mov dl,'P'
int 21h
mov dl, 'A'
int 21h
mov dl, 'M'
int 21h
mov dl,13 ;Carriage Return
int 21h
mov dl,10 ;New Line
int 21h
jmp Spam |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <vector>
using std::abs;
using std::cout;
using std::pow;
using std::vector;
int main()
{
int prod = 1,
sum = 0,
x = 5,
y = -5,
z = -2,
one = 1,
three = 3,
seven = 7;
auto summingValues = vector<int>{};
for(int n = -three; n <= pow(3, 3); n += three)
summingValues.push_back(n);
for(int n = -seven; n <= seven; n += x)
summingValues.push_back(n);
for(int n = 555; n <= 550 - y; ++n)
summingValues.push_back(n);
for(int n = 22; n >= -28; n -= three)
summingValues.push_back(n);
for(int n = 1927; n <= 1939; ++n)
summingValues.push_back(n);
for(int n = x; n >= y; n += z)
summingValues.push_back(n);
for(int n = pow(11, x); n <= pow(11, x) + one; ++n)
summingValues.push_back(n);
for(auto j : summingValues)
{
sum += abs(j);
if(abs(prod) < pow(2, 27) && j != 0)
prod *= j;
}
cout << "sum = " << sum << "\n";
cout << "prod = " << prod << "\n";
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ada | Ada | declare
I : Integer := 1024;
begin
while I > 0 loop
Put_Line(Integer'Image(I));
I := I / 2;
end loop;
end; |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Agena | Agena | scope
local i := 1024;
while i > 0 do
print( i );
i := i \ 2
od
epocs |
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
| #11l | 11l | L(i) (1..9).step(2)
print(i) |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Lua | Lua | -- Return table of ludic numbers below limit
function ludics (limit)
local ludList, numList, index = {1}, {}
for n = 2, limit do table.insert(numList, n) end
while #numList > 0 do
index = numList[1]
table.insert(ludList, index)
for key = #numList, 1, -1 do
if key % index == 1 then table.remove(numList, key) end
end
end
return ludList
end
-- Return true if n is found in t or false otherwise
function foundIn (t, n)
for k, v in pairs(t) do
if v == n then return true end
end
return false
end
-- Display msg followed by all values in t
function show (msg, t)
io.write(msg)
for _, v in pairs(t) do io.write(" " .. v) end
print("\n")
end
-- Main procedure
local first25, under1k, inRange, tripList, triplets = {}, 0, {}, {}, {}
for k, v in pairs(ludics(30000)) do
if k <= 25 then table.insert(first25, v) end
if v <= 1000 then under1k = under1k + 1 end
if k >= 2000 and k <= 2005 then table.insert(inRange, v) end
if v < 250 then table.insert(tripList, v) end
end
for _, x in pairs(tripList) do
if foundIn(tripList, x + 2) and foundIn(tripList, x + 6) then
table.insert(triplets, "\n{" .. x .. "," .. x+2 .. "," .. x+6 .. "}")
end
end
show("First 25:", first25)
print(under1k .. " are less than or equal to 1000\n")
show("2000th to 2005th:", inRange)
show("Triplets:", triplets) |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #8086_Assembly | 8086 Assembly | .model small
.stack 1024
.data ;no data needed
.code
start:
mov ax,0000h
mov cx,0FFFFh ;this value doesn't matter as long as it's greater than decimal 10.
repeatPrinting:
add ax,1 ;it was easier to start at zero and add here than to start at 1 and add after printing.
aaa ;ascii adjust for addition, corrects 0009h+1 from 000Ah to 0100h
call PrintBCD_IgnoreLeadingZeroes
cmp ax,0100h ;does AX = BCD 10?
je exitLoopEarly ;if so, we're done now. Don't finish the loop.
push ax
mov dl,"," ;print a comma
mov ah,02h
int 21h
mov dl,20h ;print a blank space
mov ah,02h
int 21h
pop ax
loop repeatPrinting
exitLoopEarly:
mov ax,4C00h
int 21h ;return to DOS
PrintBCD_IgnoreLeadingZeroes:
push ax
cmp ah,0
jz skipLeadingZero
or ah,30h ;converts a binary-coded-decimal value to an ASCII numeral
push dx
push ax
mov al,ah
mov ah,0Eh
int 10h ;prints AL to screeen
pop ax
pop dx
skipLeadingZero:
or al,30h
push dx
push ax
mov ah,0Eh
int 10h ;prints AL to screen
pop ax
pop dx
pop ax
ret
end start ;EOF |
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
| #Action.21 | Action! | PROC Main()
DEFINE PTR="CARD"
BYTE i,j,found
PTR ARRAY a(10)
BYTE ARRAY tmp,
a0(10),a1(10),a2(10),a3(10),a4(10),
a5(10),a6(10),a7(10),a8(10),a9(10)
a(0)=a0 a(1)=a1 a(2)=a2 a(3)=a3 a(4)=a4
a(5)=a5 a(6)=a6 a(7)=a7 a(8)=a8 a(9)=a9
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
tmp(i)=Rand(20)+1
OD
OD
found=0
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
PrintB(tmp(i)) Put(32)
IF tmp(i)=20 THEN
found=1 EXIT
FI
OD
IF found THEN
EXIT
FI
PutE()
OD
RETURN |
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
| #Huginn | Huginn | import Algorithms as algo;
class Example {
_start = none;
_stop = none;
_step = none;
_comment = none;
}
main() {
examples = [
Example( -2, 2, 1, "Normal" ),
Example( 2, 2, 0, "Start equal stop: zero increment" ),
Example( 0, 0, 0, "Start equal stop equal zero: zero increment" ),
Example( 2, 2, 1, "Start equal stop: positive increment" ),
Example( 2, 2, -1, "Start equal stop: negative increment" ),
Example( -2, 2, 10, "First increment is beyond stop value" ),
Example( -2, 2, 0, "Zero increment, stop greater than start" ),
Example( -2, 2, -1, "Increments away from stop value" ),
Example( 2, -2, 1, "Start more than stop: positive increment" )
];
for ( ex : examples ) {
print(
"{}\nRange( {}, {}, {} ) -> ".format(
ex._comment, ex._start, ex._stop, ex._step
)
);
r = algo.range( ex._start, ex._stop, ex._step );
print(
"{}\n\n".format(
algo.materialize( algo.slice( r, 22 ), list )
)
);
}
} |
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
| #J | J | NB. rank 3 integers with a bit of inversion
i. 2 _3 6
12 13 14 15 16 17
6 7 8 9 10 11
0 1 2 3 4 5
30 31 32 33 34 35
24 25 26 27 28 29
18 19 20 21 22 23
NB. from _3 to 3 in 12 steps
i: 3j12
_3 _2.5 _2 _1.5 _1 _0.5 0 0.5 1 1.5 2 2.5 3
|
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
| #Java | Java |
import java.util.ArrayList;
import java.util.List;
public class LoopsWrongRanges {
public static void main(String[] args) {
runTest(new LoopTest(-2, 2, 1, "Normal"));
runTest(new LoopTest(-2, 2, 0, "Zero increment"));
runTest(new LoopTest(-2, 2, -1, "Increments away from stop value"));
runTest(new LoopTest(-2, 2, 10, "First increment is beyond stop value"));
runTest(new LoopTest(2, -2, 1, "Start more than stop: positive increment"));
runTest(new LoopTest(2, 2, 1, "Start equal stop: positive increment"));
runTest(new LoopTest(2, 2, -1, "Start equal stop: negative increment"));
runTest(new LoopTest(2, 2, 0, "Start equal stop: zero increment"));
runTest(new LoopTest(0, 0, 0, "Start equal stop equal zero: zero increment"));
}
private static void runTest(LoopTest loopTest) {
List<Integer> values = new ArrayList<>();
for (int i = loopTest.start ; i <= loopTest.stop ; i += loopTest.increment ) {
values.add(i);
if ( values.size() >= 10 ) {
break;
}
}
System.out.printf("%-45s %s%s%n", loopTest.comment, values, values.size()==10 ? " (loops forever)" : "");
}
private static class LoopTest {
int start;
int stop;
int increment;
String comment;
public LoopTest(int start, int stop, int increment, String comment) {
this.start = start;
this.stop = stop;
this.increment = increment;
this.comment = comment;
}
}
}
|
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
| #Action.21 | Action! | PROC Main()
DEFINE PTR="CARD"
BYTE i
PTR ARRAY items(10)
items(0)="First" items(1)="Second"
items(2)="Third" items(3)="Fourth"
items(4)="Fifth" items(5)="Sixth"
items(6)="Seventh" items(7)="Eighth"
items(8)="Ninth" items(9)="Tenth"
PrintE("In Action! there is no for-each loop")
PutE()
FOR i=0 TO 9
DO
PrintE(items(i))
OD
RETURN |
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
| #Ada | Ada | with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
procedure For_Each is
A : array (1..5) of Integer := (-1, 0, 1, 2, 3);
begin
for Num in A'Range loop
Put( A (Num) );
end loop;
end For_Each; |
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
| #ARM_Assembly | ARM Assembly | .text
.global _start
_start:
ldr r0, =example_numbers
bl test_number
add r1, r0, #1
bl length
add r0, r1, r0
bl test_number
add r1, r0, #1
bl length
add r0, r1, r0
bl test_number
add r1, r0, #1
bl length
add r0, r1, r0
bl test_number
mov r0, #0
mov r7, #1
swi 0
test_number:
push {r0, lr}
bl print_string
bl luhn_test
cmp r0, #1
ldreq r0, =valid_message
ldrne r0, =invalid_message
bl print_string
pop {r0, lr}
mov pc, lr
print_string:
push {r0-r7, lr}
mov r1, r0 @ string to print
bl length
mov r2, r0 @ length of string
mov r0, #1 @ write to stdout
mov r7, #4 @ SYS_WRITE
swi 0 @ call system interupt
pop {r0-r7, lr}
mov pc, lr
@ r0 address of credit card number string
@ returns result in r0
luhn_test:
push {r1-r7, lr}
mov r1, r0
bl isNumerical @ check if string is a number
cmp r0, #1
bne .luhn_test_end @ exit if not number
mov r0, r1
ldr r1, =reversed_string @ address to store reversed string
bl reverse @ reverse string
push {r0}
bl length @ get length of string
mov r4, r0 @ store string length in r4
pop {r0}
mov r2, #0 @ string index
mov r6, #0 @ sum of odd digits
mov r7, #0 @ sum of even digits
.loadNext:
ldrb r3, [r1, r2] @ load byte into r3
sub r3, #'0' @ convert letter to digit
and r5, r2, #1 @ test if index is even or odd
cmp r5, #0
beq .odd_digit
bne .even_digit
.odd_digit:
add r6, r3 @ add digit to sum if odd
b .continue @ skip next step
.even_digit:
lsl r3, #1 @ multiply digit by 2
cmp r3, #10 @ sum digits
subge r3, #10 @ get digit in 1s place
addge r3, #1 @ add 1 for the 10s place
add r7, r3 @ add digit sum to the total
.continue:
add r2, #1 @ increment digit index
cmp r2, r4 @ check if at end of string
blt .loadNext
add r0, r6, r7 @ add even and odd sum
mov r3, r0 @ copy sum to r3
ldr r1, =429496730 @ (2^32-1)/10
sub r0, r0, r0, lsr #30 @ divide by 10
umull r2, r0, r1, r0
mov r1, #10
mul r0, r1 @ multiply the r0 by 10 to see if divisible
cmp r0, r3 @ compare with the original value in r3
.luhn_test_end:
movne r0, #0 @ return false if invalid card number
moveq r0, #1 @ return true if valid card number
pop {r1-r7, lr}
mov pc, lr
length:
push {r1-r2, lr}
mov r2, r0 @ start of string address
.loop:
ldrb r1, [r2], #1 @ load byte from address r2 and increment
cmp r1, #0 @ check for end of string
bne .loop @ load next byte if not 0
sub r0, r2, r0 @ subtract end of string address from start
sub r0, #1 @ end of line from count
pop {r1-r2, lr}
mov pc, lr
@ reverses a string
@ r0 address of string to reverse
@ r1 address to store reversed string
reverse:
push {r0-r5, lr}
push {r0, lr}
bl length @ get length of string to reverse
mov r3, r0 @ backword index
pop {r0, lr}
mov r4, #0 @ fowrard index
.reverse_next:
sub r3, #1 @ decrement backword index
ldrb r5, [r0, r3] @ load byte from original string at index
strb r5, [r1, r4] @ copy byte to reversed string
add r4, #1 @ increment fowrard index
cmp r3, #0 @ check if any characters are left
bge .reverse_next
mov r5, #0
strb r5, [r1, r4] @ write null byte to terminate reversed string
pop {r0-r5, lr}
mov pc, lr
isNumerical:
push {r1, lr}
.isNumerical_checkNext:
ldrb r1, [r0], #1
cmp r1, #0
beq .isNumerical_true
cmp r1, #'0'
blt .isNumerical_false
cmp r1, #'9'
bgt .isNumerical_false
b .isNumerical_checkNext
.isNumerical_false:
mov r0, #0
b .isNumerical_end
.isNumerical_true:
mov r0, #1
.isNumerical_end:
pop {r1, lr}
mov pc, lr
.data
valid_message:
.asciz " valid card number\n"
invalid_message:
.asciz " invalid card number\n"
reversed_string:
.space 32
example_numbers:
.asciz "49927398716"
.asciz "49927398717"
.asciz "1234567812345678"
.asciz "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).
| #CoffeeScript | CoffeeScript |
sorenson = require('sieve').primes # Sorenson's extensible sieve from task: Extensible Prime Number Generator
# Test if 2^n-1 is a Mersenne prime.
# assumes that the argument p is prime.
#
isMersennePrime = (p) ->
if p is 2 then yes
else
n = (1n << BigInt p) - 1n
s = 4n
s = (s*s - 2n) % n for _ in [1..p-2]
s is 0n
primes = sorenson()
mersennes = []
while (p = primes.next().value) < 3000
if isMersennePrime(p)
mersennes.push p
console.log "Some Mersenne primes: #{"M" + String p for p in mersennes}"
|
http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers | Lucky and even lucky numbers | Note that in the following explanation list indices are assumed to start at one.
Definition of lucky numbers
Lucky numbers are positive integers that are formed by:
Form a list of all the positive odd integers > 0
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
,
17
,
19
,
21
,
23
,
25
,
27
,
29
,
31
,
33
,
35
,
37
,
39...
{\displaystyle 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...}
Return the first number from the list (which is 1).
(Loop begins here)
Note then return the second number from the list (which is 3).
Discard every third, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
19
,
21
,
25
,
27
,
31
,
33
,
37
,
39
,
43
,
45
,
49
,
51
,
55
,
57...
{\displaystyle 1,3,7,9,13,15,19,21,25,27,31,33,37,39,43,45,49,51,55,57...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 7).
Discard every 7th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
27
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
57
,
63
,
67...
{\displaystyle 1,3,7,9,13,15,21,25,27,31,33,37,43,45,49,51,55,57,63,67...}
Note then return the 4th number from the list (which is 9).
Discard every 9th, (as noted), number from the list to form the new list
1
,
3
,
7
,
9
,
13
,
15
,
21
,
25
,
31
,
33
,
37
,
43
,
45
,
49
,
51
,
55
,
63
,
67
,
69
,
73...
{\displaystyle 1,3,7,9,13,15,21,25,31,33,37,43,45,49,51,55,63,67,69,73...}
Take the 5th, i.e. 13. Remove every 13th.
Take the 6th, i.e. 15. Remove every 15th.
Take the 7th, i.e. 21. Remove every 21th.
Take the 8th, i.e. 25. Remove every 25th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above except for the very first step:
Form a list of all the positive even integers > 0
2
,
4
,
6
,
8
,
10
,
12
,
14
,
16
,
18
,
20
,
22
,
24
,
26
,
28
,
30
,
32
,
34
,
36
,
38
,
40...
{\displaystyle 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40...}
Return the first number from the list (which is 2).
(Loop begins here)
Note then return the second number from the list (which is 4).
Discard every 4th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
14
,
18
,
20
,
22
,
26
,
28
,
30
,
34
,
36
,
38
,
42
,
44
,
46
,
50
,
52...
{\displaystyle 2,4,6,10,12,14,18,20,22,26,28,30,34,36,38,42,44,46,50,52...}
(Expanding the loop a few more times...)
Note then return the third number from the list (which is 6).
Discard every 6th, (as noted), number from the list to form the new list
2
,
4
,
6
,
10
,
12
,
18
,
20
,
22
,
26
,
28
,
34
,
36
,
38
,
42
,
44
,
50
,
52
,
54
,
58
,
60...
{\displaystyle 2,4,6,10,12,18,20,22,26,28,34,36,38,42,44,50,52,54,58,60...}
Take the 4th, i.e. 10. Remove every 10th.
Take the 5th, i.e. 12. Remove every 12th.
(Rule for the loop)
Note the
n
{\displaystyle n}
th, which is
m
{\displaystyle m}
.
Remove every
m
{\displaystyle m}
th.
Increment
n
{\displaystyle n}
.
Task requirements
Write one or two subroutines (functions) to generate lucky numbers and even lucky numbers
Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
missing arguments
too many arguments
number (or numbers) aren't legal
misspelled argument (lucky or evenLucky)
The command line handling should:
support mixed case handling of the (non-numeric) arguments
support printing a particular number
support printing a range of numbers by their index
support printing a range of numbers by their values
The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
╔═══════════════════╦════════════════════════════════════════════════════╗
║ j ║ Jth lucky number ║
║ j , lucky ║ Jth lucky number ║
║ j , evenLucky ║ Jth even lucky number ║
║ ║ ║
║ j k ║ Jth through Kth (inclusive) lucky numbers ║
║ j k lucky ║ Jth through Kth (inclusive) lucky numbers ║
║ j k evenLucky ║ Jth through Kth (inclusive) even lucky numbers ║
║ ║ ║
║ j -k ║ all lucky numbers in the range j ──► |k| ║
║ j -k lucky ║ all lucky numbers in the range j ──► |k| ║
║ j -k evenLucky ║ all even lucky numbers in the range j ──► |k| ║
╚═══════════════════╩════════════════════════════════════════════════════╝
where |k| is the absolute value of k
Demonstrate the program by:
showing the first twenty lucky numbers
showing the first twenty even lucky numbers
showing all lucky numbers between 6,000 and 6,100 (inclusive)
showing all even lucky numbers in the same range as above
showing the 10,000th lucky number (extra credit)
showing the 10,000th even lucky number (extra credit)
See also
This task is related to the Sieve of Eratosthenes task.
OEIS Wiki Lucky numbers.
Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| #Raku | Raku | sub luck(\a,\b) {
gather {
my @taken = take a;
my @rotor;
my $i = b;
loop {
loop (my $j = 0; $j < @rotor; $j++) {
--@rotor[$j] or last;
}
if $j < @rotor {
@rotor[$j] = @taken[$j+1];
}
else {
push @taken, take $i;
push @rotor, $i - @taken;
}
$i += 2;
}
}
}
constant @lucky = luck(1,3);
constant @evenlucky = luck(2,4);
subset Luck where m:i/^ 'even'? 'lucky' $/;
multi MAIN (Int $num where * > 0) {
say @lucky[$num-1];
}
multi MAIN (Int $num where * > 0, ',', Luck $howlucky = 'lucky') {
say @::(lc $howlucky)[$num-1];
}
multi MAIN (Int $first where * > 0, Int $last where * > 0, Luck $howlucky = 'lucky') {
say @::(lc $howlucky)[$first-1 .. $last - 1];
}
multi MAIN (Int $min where * > 0, Int $neg-max where * < 0, Luck $howlucky = 'lucky') {
say grep * >= $min, (@::(lc $howlucky) ...^ * > abs $neg-max);
} |
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.
| #Erlang | Erlang | -module(lzw).
-export([test/0, encode/1, decode/1]).
-import(lists, [reverse/1, reverse/2]).
test() ->
Str = "TOBEORNOTTOBEORTOBEORNOT",
[84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263] =
encode(Str),
Str = decode(encode(Str)),
ok.
encode(Str) ->
D = init(dict:new()),
encode(Str, D, 256, []).
encode([H], D, _, Out) ->
Val = dict:fetch([H], D),
reverse([Val|Out]);
encode([H|T], D, Free, Out) ->
Val = dict:fetch([H], D),
find_match(T, [H], Val, D, Free, Out).
find_match([H|T], L, LastVal, D, Free, Out) ->
case dict:find([H|L], D) of
{ok, Val} ->
find_match(T, [H|L], Val, D, Free, Out);
error ->
D1 = dict:store([H|L], Free, D),
encode([H|T], D1, Free+1, [LastVal|Out])
end;
find_match([], _, LastVal, _, _, Out) ->
reverse([LastVal|Out]).
decode([H|T]) ->
D = init1(dict:new()),
Val = dict:fetch(H, D),
decode(T, Val, 256, D, Val).
decode([], _, _, _, L) ->
reverse(L);
decode([H|T], Old, Free, D, L) ->
Val = dict:fetch(H, D),
Add = [lists:last(Val)|Old],
D1 = dict:store(Free, Add, D),
decode(T, Val, Free+1, D1, Val ++ L).
init(D) -> init(255, D).
init(0, D) -> D;
init(N, D) -> D1 = dict:store([N],N,D), init(N-1, D1).
init1(D) -> init1(255, D).
init1(0, D) -> D;
init1(N, D) -> D1 = dict:store(N,[N],D), init1(N-1, D1). |
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
| #JavaScript | JavaScript |
const mult=(a, b)=>{
let res = new Array(a.length);
for (let r = 0; r < a.length; ++r) {
res[r] = new Array(b[0].length);
for (let c = 0; c < b[0].length; ++c) {
res[r][c] = 0;
for (let i = 0; i < a[0].length; ++i)
res[r][c] += a[r][i] * b[i][c];
}
}
return res;
}
const lu = (mat) => {
let lower = [],upper = [],n=mat.length;;
for(let i=0;i<n;i++){
lower.push([]);
upper.push([]);
for(let j=0;j<n;j++){
lower[i].push(0);
upper[i].push(0);
}
}
for (let i = 0; i < n; i++) {
for (let k = i; k < n; k++){
let sum = 0;
for (let j = 0; j < i; j++)
sum += (lower[i][j] * upper[j][k]);
upper[i][k] = mat[i][k] - sum;
}
for (let k = i; k < n; k++) {
if (i == k)
lower[i][i] = 1;
else{
let sum = 0;
for (let j = 0; j < i; j++)
sum += (lower[k][j] * upper[j][i]);
lower[k][i] = (mat[k][i] - sum) / upper[i][i];
}
}
}
return [lower,upper];
}
const pivot = (m) =>{
let n = m.length;
let id = [];
for(let i=0;i<n;i++){
id.push([]);
for(let j=0;j<n;j++){
if(i===j)
id[i].push(1);
else
id[i].push(0);
}
}
for (let i = 0; i < n; i++) {
let maxm = m[i][i];
let row = i;
for (let j = i; j < n; j++)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row) {
let tmp = id[i];
id[i] = id[row];
id[row] = tmp;
}
}
return id;
}
const luDecomposition=(A)=>{
const P = pivot(A);
A = mult(P,A);
return [...lu(A),P];
}
|
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.
| #Phix | Phix | with javascript_semantics
constant iterations = 500,
limit = 10000
sequence seeds = {},
cache = {}
sequence temp = repeat(0,iterations)
sequence palin = {}
integer related = 0
for n=1 to limit do
string num = sprintf("%d",n),
rev = reverse(num)
bool palindrome = (num=rev)
for i=1 to iterations do
integer digit, carry = 0
for x=length(num) to 1 by -1 do
digit = num[x]+rev[x]+carry-'0'
carry = digit>'9'
num[x] = digit-carry*10
end for
if carry then num = "1" & num end if
temp[i] = num
rev = reverse(num)
if num=rev then exit end if
end for
if num!=rev then
bool no_match = true
num = sprintf("%d",n)
if palindrome then
palin = append(palin, num)
end if
for c=1 to length(cache) do
string seed = cache[c]
-- check against previous found seeds
for i=iterations to 1 by -1 do
string ti = temp[i]
if length(seed)>length(ti) then
exit
elsif seed=ti then
no_match = false
related += 1
exit
end if
end for
if no_match=false then exit end if
end for
if no_match then
seeds = append(seeds,num)
cache = append(cache,temp[$])
end if
end if
end for
printf(1,"%d lychrel seeds: %s\n",{length(seeds),join(seeds, ", ")})
printf(1,"related lychrel: %d\n",related)
printf(1,"%d lychrel palindromes: %s\n", {length(palin),join(palin, ", ")})
|
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
| #Liberty_BASIC | Liberty BASIC | temp$="<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home."
k = instr(temp$,"<")
while k
replace$ = mid$(temp$,k,instr(temp$,">")-k + 1)
print "Replace:";replace$;" with:"; :input with$
while k
temp$ = left$(temp$,k-1) + with$ + mid$(temp$,k + len(replace$))
k = instr(temp$,replace$,k)
wend
k = instr(temp$,"<")
wend
print temp$
wait
|
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program loopinc96.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessMultOver: .asciz "Multiplication 64 : Dépassement de capacité.\n"
sMessResult: .ascii "Index : "
sMessIndex: .fill 11, 1, ' ' @ size => 11
.ascii "Value : "
sMessValeur: .fill 21, 1, ' ' @ size => 21
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r7,#0 @ counter
mov r5,#42 @ start index low bits
mov r6,#0 @ start index high bits
1: @ begin loop
mov r0,r5
mov r1,r6
bl isPrime @ prime ?
bcs 100f @ error overflow ?
cmp r0,#1 @ is prime ?
beq 2f @ yes
adds r5,#1 @ no -> increment index
addcs r6,#1
b 1b @ and loop
2: @ display index and prime
add r7,#1 @ increment counter
mov r0,r7
ldr r1,iAdrsMessIndex @ conversion index
bl conversion10
mov r0,r5
mov r1,r6 @ conversion value
ldr r2,iAdrsMessValeur
bl conversionRegDoubleU @ conversion double -> ascii
ldr r0,iAdrsMessResult
bl affichageMess
adds r5,r5
add r6,r6
addcs r6,#1
cmp r7,#42 @ end ?
blt 1b @ no loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessIndex: .int sMessIndex
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned 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 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* number is prime ? */
/***************************************************/
/* r0 contains low bytes of double */
/* r1 contains high bytes of double */
/* r0 returns 1 if prime else 0 */
@2147483647
@4294967297
@131071
isPrime:
push {r1-r5,lr} @ save registers
mov r4,r0 @ save double
mov r5,r1
subs r2,r0,#1 @ exposant n - 1
sbcs r3,r1,#0
mov r0,#2 @ base 2
mov r1,#0
bl moduloPuR96 @ compute modulo
bcs 100f @ overflow error
cmp r0,#1 @ modulo <> 1 -> no prime
bne 90f
mov r0,#3 @ base 3
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#5 @ base 5
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#7 @ base 7
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#11 @ base 11
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#13 @ base 13
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#17 @ base 17
mov r1,#0
bl moduloPuR96
bcs 100f @ overflow error
cmp r0,#1
bne 90f
mov r0,#1 @ is prime
msr cpsr_f, #0 @ no error overflow zero -> flags
b 100f
90:
mov r0,#0 @ no prime
msr cpsr_f, #0 @ no error overflow zero -> flags
100: @ fin standard de la fonction
pop {r1-r5,lr} @ restaur registers
bx lr @ return
/********************************************************/
/* compute b pow e modulo m */
/* */
/********************************************************/
/* r0 base double low bits */
/* r1 base double high bits */
/* r2 exposant low bitss */
/* r3 exposant high bits */
/* r4 modulo low bits */
/* r5 modulo high bits */
/* r0 returns result low bits */
/* r1 returns result high bits */
/* if overflow , flag carry is set else is clear */
moduloPuR96:
push {r2-r12,lr} @ save registers
cmp r0,#0 @ control low byte <> zero
bne 1f
cmp r1,#0 @ control high bytes <> zero
beq 100f
1:
mov r9,r4 @ modulo PB
mov r10,r5 @ modulo PH
mov r5,r2 @ exposant **
mov r6,r3 @ exposant
mov r7,r0 @ base PB
mov r8,r1 @ base PH
mov r2,#0
mov r3,r9
mov r4,r10
mov r11,#1 @ result PB
mov r12,#0 @ result PH
/* r0 contient partie basse dividende */
/* r1 contient partie moyenne dividende */
/* r2 contient partie haute du diviseur */
/* r3 contient partie basse diviseur */
/* r4 contient partie haute diviseur */
/* r0 retourne partie basse du quotient */
/* r1 retourne partie moyenne du quotient */
/* r2 retourne partie haute du quotient */
/* r3 retourne partie basse du reste */
/* r4 retourne partie haute du reste */
bl divisionReg96DU
mov r7,r3 @ base <- remainder
mov r8,r4
2:
tst r5,#1 @ test du bit 0
beq 3f
mov r0,r7
mov r1,r8
mov r2,r11
mov r3,r12
bl multiplicationR96U
bcs 100f @ error overflow
mov r3,r9
mov r4,r10
bl divisionReg96DU
mov r11,r3 @ result <- remainder
mov r12,r4
3:
mov r0,r7
mov r1,r8
mov r2,r7
mov r3,r8
bl multiplicationR96U
bcs 100f @ error overflow
mov r3,r9
mov r4,r10
bl divisionReg96DU
mov r7,r3 @ base <- remainder
mov r8,r4
lsr r5,#1
lsrs r6,#1
orrcs r5,#0x80000000
cmp r5,#0
bne 2b
cmp r6,#0
bne 2b
mov r0,r11
mov r1,r12
msr cpsr_f, #0 @ no error overflow zero -> flags
100: @ end function
pop {r2-r12,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* multiplication 2 registers (64 bits) unsigned */
/* result in 3 registers 96 bits */
/***************************************************/
/* r0 low bits number 1 */
/* r1 high bits number 1 */
/* r2 low bits number 2 */
/* r3 high bits number 2 */
/* r0 returns low bits résult */
/* r1 returns median bits résult */
/* r2 returns high bits résult */
/* if overflow , flag carry is set else is clear */
multiplicationR96U:
push {r3-r8,lr} @ save registers
umull r5,r6,r0,r2 @ mult low bits
umull r4,r8,r0,r3 @ mult low bits 1 high bits 2
mov r0,r5 @ result low bits ok
adds r4,r6 @ add results
addcs r8,#1 @ carry
umull r6,r7,r1,r2 @ mult high bits 1 low bits 2
adds r4,r6 @ add results
addcs r8,#1 @ carry
adds r8,r7 @ add results
bcs 99f @ overflow ?
umull r6,r7,r1,r3 @ mult high bits 1 high bits 2
cmp r7,#0 @ error overflow ?
bne 99f
adds r8,r6 @ add results
bcs 99f @ error overflow
mov r1,r4 @ return median bytes
mov r2,r8 @ return high bytes
msr cpsr_f, #0 @ no error overflow zero -> flags
b 100f
99: @ display message overflow
ldr r0,iAdrszMessMultOver @
bl affichageMess
mov r0,#0
mov r1,#0
msr cpsr_f, #1<<29 @ maj flag carry à 1 et tous les autres à 0
100: @ end function
pop {r3-r8,lr} @ restaur registers
bx lr @ return
iAdrszMessMultOver: .int szMessMultOver
/***************************************************/
/* division number (3 registers) 92 bits by number (2 registers) 64 bits */
/* unsigned */
/***************************************************/
/* r0 low bits dividende */
/* r1 median bits dividende */
/* r2 high bits dividende */
/* r3 low bits divisor */
/* r4 high bits divis0r */
/* r0 returns low bits quotient */
/* r1 returns median bits quotient */
/* r2 returns high bits quotien */
/* r3 returns low bits remainder */
/* r4 returns high bits remainder */
/* remainder do not is 3 registers */
divisionReg96DU:
push {r5-r10,lr} @ save registers
mov r7,r3 @ low bits divisor
mov r8,r4 @ high bits divisor
mov r4,r0 @ low bits dividende -> low bits quotient
mov r5,r1 @ median bits dividende -> median bits quotient
mov r6,r2 @ high bits dividende -> high bits quotient
@
mov r0,#0 @ low bits remainder
mov r1,#0 @ median bits remainder
mov r2,#0 @ high bits remainder (not useful)
mov r9,#96 @ counter loop (32 bits * 3)
mov r10,#0 @ last bit
1:
lsl r2,#1 @ shift left high bits remainder
lsls r1,#1 @ shift left median bits remainder
orrcs r2,#1 @ left bit median -> right bit high
lsls r0,#1 @ shift left low bits remainder
orrcs r1,#1 @ left bit low -> right bit median
lsls r6,#1 @ shift left high bits quotient
orrcs r0,#1 @ left bit high -> right bit low remainder
lsls r5,#1 @ shift left median bits quotient
orrcs r6,#1 @ left bit median -> right bit high
lsls r4,#1 @ shift left low bits quotient
orrcs r5,#1 @ left bit low -> right bit median
orr r4,r10 @ last bit -> bit 0 quotient
mov r10,#0 @ raz du bit
@ compare remainder and divisor
cmp r2,#0 @ high bit remainder
bne 2f
cmp r1,r8 @ compare median bits
blo 3f @ lower
bhi 2f @ highter
cmp r0,r7 @ equal -> compare low bits
blo 3f @ lower
2: @ remainder > divisor
subs r0,r7 @ sub divisor of remainder
sbcs r1,r8
mov r10,#0 @ reuse ponctuelle r10
sbc r2,r2,r10 @ carry
mov r10,#1 @ last bit à 1
3:
subs r9,#1 @ increment counter loop
bgt 1b @ and loop
lsl r6,#1 @ shift left high bits quotient
lsls r5,#1 @ shift left median bits quotient
orrcs r6,#1 @ left bit median -> right bit high
lsls r4,#1 @ shift left low bits quotient
orrcs r5,#1 @ left bit low -> right bit median
orr r4,r10 @ last bit -> bit 0 quotient
mov r3,r0 @ low bits remainder
mov r0,r4 @ low bits quotient
mov r4,r1 @ high bits remainder
mov r1,r5 @ median bits quotient
//mov r5,r2
mov r2,r6 @ high bits quotient
100: @ end function
pop {r5-r10,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* Conversion double integer 64bits in ascii */
/***************************************************/
/* r0 contains low bits */
/* r1 contains high bits */
/* r2 contains address area */
conversionRegDoubleU:
push {r0-r5,lr} @ save registers
mov r5,r2
mov r4,#19 @ start location
mov r2,#10 @ conversion decimale
1: @ begin loop
bl divisionReg64U @ division by 10
add r3,#48 @ -> digit ascii
strb r3,[r5,r4] @ store digit in area index r4
sub r4,r4,#1 @ decrement index
cmp r0,#0 @ low bits quotient = zero ?
bne 1b @ no -> loop
cmp r1,#0 @ high bits quotient = zero ?
bne 1b @ no -> loop
@ spaces -> begin area
mov r3,#' ' @ space
2:
strb r3,[r5,r4] @ store space in area
subs r4,r4,#1 @ decrement index
bge 2b @ and loop if > zéro
100: @ end fonction
pop {r0-r5,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* division number 64 bits / number 32 bits */
/***************************************************/
/* r0 contains low bits dividende */
/* r1 contains high bits dividente */
/* r2 contains divisor */
/* r0 returns low bits quotient */
/* r1 returns high bits quotient */
/* r3 returns remainder */
divisionReg64U:
push {r4,r5,lr} @ save registers
mov r5,#0 @ raz remainder R
mov r3,#64 @ loop counter
mov r4,#0 @ last bit
1:
lsl r5,#1 @ shift left remainder one bit
lsls r1,#1 @ shift left high bits quotient one bit
orrcs r5,#1 @ and bit -> remainder
lsls r0,#1 @ shift left low bits quotient one bit
orrcs r1,#1 @ and left bit -> high bits
orr r0,r4 @ last bit quotient
mov r4,#0 @ raz last bit
cmp r5,r2 @ compare remainder divisor
subhs r5,r2 @ if highter sub divisor of remainder
movhs r4,#1 @ and 1 -> last bit
3:
subs r3,#1 @ decrement counter loop
bgt 1b @ and loop if not zero
lsl r1,#1 @ else shift left higt bits quotient
lsls r0,#1 @ and shift left low bits
orrcs r1,#1
orr r0,r4 @ last bit quotient
mov r3,r5
100: @ end function
pop {r4,r5,lr} @ restaur registers
bx lr @ return
|
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
| #8th | 8th |
: inf "SPAM\n" . recurse ;
|
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program infinite64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessage: .asciz "SPAM\n"
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
loop:
ldr x0,qAdrszMessage
bl affichageMess
b loop
qAdrszMessage: .quad szMessage
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Common_Lisp | Common Lisp |
(let ((prod 1) ; Initialize aggregator
(sum 0)
(x 5) ; Initialize variables
(y -5)
(z -2)
(one 1)
(three 3)
(seven 7))
(flet ((loop-body (j) ; Set the loop function
(incf sum (abs j))
(if (and (< (abs prod) (expt 2 27))
(/= j 0))
(setf prod (* prod j)))))
(do ((i (- three) (incf i three))) ; Just a serie of individual loops
((> i (expt 3 3)))
(loop-body i))
(do ((i (- seven) (incf i x)))
((> i seven))
(loop-body i))
(do ((i 555 (incf i -1)))
((< i (- 550 y)))
(loop-body i))
(do ((i 22 (incf i (- three))))
((< i -28))
(loop-body i))
(do ((i 1927 (incf i)))
((> i 1939))
(loop-body i))
(do ((i x (incf i z)))
((< i y))
(loop-body i))
(do ((i (expt 11 x) (incf i)))
((> i (+ (expt 11 x) one)))
(loop-body i)))
(format t "~&sum = ~14<~:d~>" sum)
(format t "~&prod = ~14<~:d~>" 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
| #Aime | Aime | integer i;
i = 1024;
while (i) {
o_plan(i, "\n");
i /= 2;
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ALGOL_60 | ALGOL 60 | begin
comment Loops/While - algol60 - 21/10/2014;
integer i;
for i:=1024,i div 2 while i>0 do outinteger(1,i)
end
|
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #360_Assembly | 360 Assembly | * Loops/For with a specified step 12/08/2015
LOOPFORS CSECT
USING LOOPFORS,R12
LR R12,R15
* == Algol style ================ test at the beginning
LA R3,BUF idx=0
LA R5,0 from 5 (from-step=0)
LA R6,5 step 5
LA R7,25 to 25
LOOPI BXH R5,R6,ELOOPI for i=5 to 25 step 5
XDECO R5,XDEC edit i
MVC 0(4,R3),XDEC+8 output i
LA R3,4(R3) idx=idx+4
B LOOPI next i
ELOOPI XPRNT BUF,80 print buffer
BR R14
BUF DC CL80' ' buffer
XDEC DS CL12 temp for edit
YREGS
END LOOPFORS |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | n=10^5;
Ludic={1};
seq=Range[2,n];
ClearAll[DoStep]
DoStep[seq:{f_,___}]:=Module[{out=seq},
AppendTo[Ludic,f];
out[[;;;;f]]=Sequence[];
out
]
Nest[DoStep,seq,2500];
Ludic[[;; 25]]
LengthWhile[Ludic, # < 1000 &]
Ludic[[2000 ;; 2005]]
Select[Subsets[Select[Ludic, # < 250 &], {3}], Differences[#] == {2, 4} &] |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopnplusone64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@" // message result
szMessComma: .asciz ", "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,1 // loop counter
1: // begin loop
mov x0,x20
ldr x1,qAdrsZoneConv // display value
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display value
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszMessComma
bl affichageMess // display comma
add x20,x20,1 // increment counter
cmp x20,10 // end ?
blt 1b // no ->begin loop one
mov x0,x20
ldr x1,qAdrsZoneConv // display value
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display value
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess // display return line
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
qAdrszMessComma: .quad szMessComma
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/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
| #ACL2 | ACL2 | (defun print-list (xs)
(progn$ (cw "~x0" (first xs))
(if (endp (rest xs))
(cw (coerce '(#\Newline) 'string))
(progn$ (cw ", ")
(print-list (rest xs)))))) |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Test_Loop_Nested is
type Value_Type is range 1..20;
package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
use Random_Values;
Dice : Generator;
A : array (1..10, 1..10) of Value_Type :=
(others => (others => Random (Dice)));
begin
Outer :
for I in A'Range (1) loop
for J in A'Range (2) loop
Put (Value_Type'Image (A (I, J)));
exit Outer when A (I, J) = 20;
end loop;
New_Line;
end loop Outer;
end Test_Loop_Nested; |
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
| #jq | jq | [range(-2; 2; 1)] #=> [-2,-1,0,1]
[range(-2; 2; 0)] #=> []
[range(-2; 2; -1)] #=> []
[range(-2; 2; 10)] # [-2]
[range(2; -2; 1)] #=> []
[range(2; 2; 1)] #=> []
[range(2; 2; 0)] #=> []
[range(0; 0; -1)] #=> []
|
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
| #Julia | Julia |
collect(-2:1:2) # → [-2, -1, 0, 1, 2]
collect(-2:0:2) # fails
collect(-2:-1:2) # → []
collect(-2:10:2) # → [-2]
collect(2:1:-2) # → []
collect(2:1:2) # → [2]
collect(2:-1:2) # → [2]
collect(2:0:2) # fails
collect(0:0:0) # fails
|
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
| #Kotlin | Kotlin | // Version 1.2.70
class Example(val start: Int, val stop: Int, val incr: Int, val comment: String)
var examples = listOf(
Example(-2, 2, 1, "Normal"),
Example(-2, 2, 0, "Zero increment"),
Example(-2, 2, -1, "Increments away from stop value"),
Example(-2, 2, 10, "First increment is beyond stop value"),
Example(2, -2, 1, "Start more than stop: positive increment"),
Example(2, 2, 1, "Start equal stop: positive increment"),
Example(2, 2, -1, "Start equal stop: negative increment"),
Example(2, 2, 0, "Start equal stop: zero increment"),
Example(0, 0, 0, "Start equal stop equal zero: zero increment")
)
fun sequence(ex: Example, limit: Int) =
if (ex.incr == 0) {
List(limit) { ex.start }
}
else {
val res = mutableListOf<Int>()
var c = 0
var i = ex.start
while (i <= ex.stop && c < limit) {
res.add(i)
i += ex.incr
c++
}
res
}
fun main(args: Array<String>) {
for (ex in examples) {
println(ex.comment)
System.out.printf("Range(%d, %d, %d) -> ", ex.start, ex.stop, ex.incr)
println(sequence(ex, 10))
println()
}
} |
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
| #Aikido | Aikido | var str = "hello world"
foreach ch str { // you can also use an optional 'in'
println (ch) // one character at a time
} |
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.