task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Loops/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
| #Dao | Dao | i = 1024;
while( i > 0 ) i = i / 2; |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C.23 | C# | for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #C.2B.2B | C++ | for(int i = 10; i >= 0; --i)
std::cout << i << "\n"; |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #AutoHotkey | AutoHotkey | While mod(A_Index, 6) ;comment:everything but 0 is considered true
output = %output%`n%A_Index%
MsgBox % output |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Arturo | Arturo | loop 0..5 'x [
loop 0..x 'y [
prints "*"
]
print ""
] |
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
| #Befunge | Befunge | 1 >:.55+,v
@_^#`9:+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.
| #Rust | Rust |
const ARRAY_MAX: usize = 25_000;
const LUDIC_MAX: usize = 2100;
/// Calculates and returns the first `LUDIC_MAX` Ludic numbers.
///
/// Needs a sufficiently large `ARRAY_MAX`.
fn ludic_numbers() -> Vec<usize> {
// The first two Ludic numbers
let mut numbers = vec![1, 2];
// We start the array with an immediate first removal to reduce memory usage by
// collecting only odd numbers.
numbers.extend((3..ARRAY_MAX).step_by(2));
// We keep the correct Ludic numbers in place, removing the incorrect ones.
for ludic_idx in 2..LUDIC_MAX {
let next_ludic = numbers[ludic_idx];
// We remove incorrect numbers by counting the indices after the correct numbers.
// We start from zero and keep until we reach the potentially incorrect numbers.
// Then we keep only those not divisible by the `next_ludic`.
let mut idx = 0;
numbers.retain(|_| {
let keep = idx <= ludic_idx || (idx - ludic_idx) % next_ludic != 0;
idx += 1;
keep
});
}
numbers
}
fn main() {
let ludic_numbers = ludic_numbers();
print!("First 25: ");
print_n_ludics(&ludic_numbers, 25);
println!();
print!("Number of Ludics below 1000: ");
print_num_ludics_upto(&ludic_numbers, 1000);
println!();
print!("Ludics from 2000 to 2005: ");
print_ludics_from_to(&ludic_numbers, 2000, 2005);
println!();
println!("Triplets below 250: ");
print_triplets_until(&ludic_numbers, 250);
}
/// Prints the first `n` Ludic numbers.
fn print_n_ludics(x: &[usize], n: usize) {
println!("{:?}", &x[..n]);
}
/// Calculates how many Ludic numbers are below `max_num`.
fn print_num_ludics_upto(x: &[usize], max_num: usize) {
let num = x.iter().take_while(|&&i| i < max_num).count();
println!("{}", num);
}
/// Prints Ludic numbers between two numbers.
fn print_ludics_from_to(x: &[usize], from: usize, to: usize) {
println!("{:?}", &x[from - 1..to - 1]);
}
/// Calculates triplets until a certain Ludic number.
fn triplets_below(ludics: &[usize], limit: usize) -> Vec<(usize, usize, usize)> {
ludics
.iter()
.enumerate()
.take_while(|&(_, &num)| num < limit)
.filter_map(|(idx, &number)| {
let triplet_2 = number + 2;
let triplet_3 = number + 6;
// Search for the other two triplet numbers. We know they are larger than
// `number` so we can give the searches lower bounds of `idx + 1` and
// `idx + 2`. We also know that the `n + 2` number can only ever be two
// numbers away from the previous and the `n + 6` number can only be four
// away (because we removed some in between). Short circuiting and doing
// the check more likely to fail first are also useful.
let is_triplet = ludics[idx + 1..idx + 3].binary_search(&triplet_2).is_ok()
&& ludics[idx + 2..idx + 5].binary_search(&triplet_3).is_ok();
if is_triplet {
Some((number, triplet_2, triplet_3))
} else {
None
}
})
.collect()
}
/// Prints triplets until a certain Ludic number.
fn print_triplets_until(ludics: &[usize], limit: usize) {
for (number, triplet_2, triplet_3) in triplets_below(ludics, limit) {
println!("{} {} {}", number, triplet_2, triplet_3);
}
}
|
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
| #Euphoria | Euphoria |
for i = 1 to 10 do
printf(1, "%g", {i})
if i < 10 then
puts(1, ", ")
end if
end for
|
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
| #F.23 | F# |
let rec print (lst : int list) =
match lst with
| hd :: [] ->
printf "%i " hd
| hd :: tl ->
printf "%i, " hd
print tl
| [] -> printf "\n"
print [1..10]
|
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Elixir | Elixir | defmodule Loops do
def nested do
list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
try do
nested(list)
catch
:find -> IO.puts "done"
end
end
def nested(list) do
Enum.each(list, fn row ->
Enum.each(row, fn x ->
IO.write "#{x} "
if x == 20, do: throw(:find)
end)
IO.puts ""
end)
end
end
Loops.nested |
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
| #Erlang | Erlang |
-module( loops_nested ).
-export( [task/0] ).
task() ->
Size = 20,
Two_dimensional_array = [random_array(Size) || _X <- lists:seq(1, Size)],
print_until_found( [], 20, Two_dimensional_array ).
print_until_found( [], N, [Row | T] ) -> print_until_found( print_until_found_row(N, Row), N, T );
print_until_found( _Found, _N, _Two_dimensional_array ) -> io:fwrite( "~n" ).
print_until_found_row( _N, [] ) -> [];
print_until_found_row( N, [N | T] ) -> [N | T];
print_until_found_row( N, [H | T] ) ->
io:fwrite( "~p ", [H] ),
print_until_found_row( N, T ).
random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)].
|
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
| #F.23 | F# | for i in [1 .. 10] do printfn "%d" i
List.iter (fun i -> printfn "%d" i) [1 .. 10] |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Factor | Factor | { 1 2 4 } [ . ] 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
| #CLU | CLU | luhn = proc (num: string) returns (bool) signals (bad_format)
total: int := 0
even: bool := true
for i: int in int$from_to_by(string$size(num), 1, -1) do
digit: int := int$parse(string$c2s(num[i])) resignal bad_format
even := ~even
if even then
digit := 2 * digit
if digit >= 10 then digit := digit//10 + 1 end
end
total := total + digit
end
return(total // 10 = 0)
end luhn
start_up = proc ()
po: stream := stream$primary_output()
tests: sequence[string] := sequence[string]$
["49927398716", "49927398717", "1234567812345678", "1234567812345670"]
for test: string in sequence[string]$elements(tests) do
stream$puts(po, test || ": ")
if luhn(test)
then stream$putl(po, "pass")
else stream$putl(po, "fail")
end
end
end start_up |
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).
| #Java | Java | import java.math.BigInteger;
public class Mersenne
{
public static boolean isPrime(int p) {
if (p == 2)
return true;
else if (p <= 1 || p % 2 == 0)
return false;
else {
int to = (int)Math.sqrt(p);
for (int i = 3; i <= to; i += 2)
if (p % i == 0)
return false;
return true;
}
}
public static boolean isMersennePrime(int p) {
if (p == 2)
return true;
else {
BigInteger m_p = BigInteger.ONE.shiftLeft(p).subtract(BigInteger.ONE);
BigInteger s = BigInteger.valueOf(4);
for (int i = 3; i <= p; i++)
s = s.multiply(s).subtract(BigInteger.valueOf(2)).mod(m_p);
return s.equals(BigInteger.ZERO);
}
}
// an arbitrary upper bound can be given as an argument
public static void main(String[] args) {
int upb;
if (args.length == 0)
upb = 500;
else
upb = Integer.parseInt(args[0]);
System.out.print(" Finding Mersenne primes in M[2.." + upb + "]:\nM2 ");
for (int p = 3; p <= upb; p += 2)
if (isPrime(p) && isMersennePrime(p))
System.out.print(" M" + p);
System.out.println();
}
} |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Perl | Perl | # Compress a string to a list of output symbols.
sub compress {
my $uncompressed = shift;
# Build the dictionary.
my $dict_size = 256;
my %dictionary = map {chr $_ => chr $_} 0..$dict_size-1;
my $w = "";
my @result;
foreach my $c (split '', $uncompressed) {
my $wc = $w . $c;
if (exists $dictionary{$wc}) {
$w = $wc;
} else {
push @result, $dictionary{$w};
# Add wc to the dictionary.
$dictionary{$wc} = $dict_size;
$dict_size++;
$w = $c;
}
}
# Output the code for w.
if ($w) {
push @result, $dictionary{$w};
}
return @result;
}
# Decompress a list of output ks to a string.
sub decompress {
my @compressed = @_;
# Build the dictionary.
my $dict_size = 256;
my %dictionary = map {chr $_ => chr $_} 0..$dict_size-1;
my $w = shift @compressed;
my $result = $w;
foreach my $k (@compressed) {
my $entry;
if (exists $dictionary{$k}) {
$entry = $dictionary{$k};
} elsif ($k == $dict_size) {
$entry = $w . substr($w,0,1);
} else {
die "Bad compressed k: $k";
}
$result .= $entry;
# Add w+entry[0] to the dictionary.
$dictionary{$dict_size} = $w . substr($entry,0,1);
$dict_size++;
$w = $entry;
}
return $result;
}
# How to use:
my @compressed = compress('TOBEORNOTTOBEORTOBEORNOT');
print "@compressed\n";
my $decompressed = decompress(@compressed);
print "$decompressed\n"; |
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
| #Stata | Stata | mata
: lud(a=(1,3,5\2,4,7\1,1,0),l=.,u=.,p=.)
: a
1 2 3
+-------------+
1 | 1 3 5 |
2 | 2 4 7 |
3 | 1 1 0 |
+-------------+
: l
1 2 3
+----------------+
1 | 1 0 0 |
2 | .5 1 0 |
3 | .5 -1 1 |
+----------------+
: u
1 2 3
+-------------------+
1 | 2 4 7 |
2 | 0 1 1.5 |
3 | 0 0 -2 |
+-------------------+
: p
1
+-----+
1 | 2 |
2 | 1 |
3 | 3 |
+-----+ |
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
| #Ruby | Ruby | puts "Enter a story, terminated by an empty line:"
story = ""
until (line = gets).chomp.empty?
story << line
end
story.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var|
print "Enter a value for '#{var}': "
story.gsub!(/<#{var}>/, gets.chomp)
end
puts
puts 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
| #Phix | Phix | atom i=42, n=1
while n<=42 do
if is_prime(i) then
printf(1,"n = %-2d %,19d\n", {n, i})
n += 1
i += i-1
end if
i += 1
end while
|
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
| #Python | Python | def isPrime(n):
for x in 2, 3:
if not n % x:
return n == x
d = 5
while d * d <= n:
for x in 2, 4:
if not n % d:
return False
d += x
return True
i = 42
n = 0
while n < 42:
if isPrime(i):
n += 1
print('n = {:2} {:20,}'.format(n, i))
i += i - 1
i += 1 |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Corescript | Corescript |
:top
print Spam!
goto top
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
loop
print("Spam\n");
end loop; |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod= 1; /*start with a product of unity. */
sum= 0; /* " " " sum " zero. */
x= +5;
y= -5;
z= -2;
one= 1;
three= 3;
seven= 7;
/*(below) ** is exponentiation: 4**3=64 */
do j= -three to 3**3 by three ,
-seven to +seven by x ,
555 to 550 - y ,
22 to -28 by -three ,
1927 to 1939 ,
x to y by z ,
11**x to 11**x + one;
/* ABS(n) = absolute value*/
sum= sum + abs(j); /*add absolute value of J.*/
if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/
end; /*not 0, then multiply it.*/
/*SUM and PROD are used for verification of J incrementation.*/
display (' sum= ' || sum); /*display strings to term.*/
display ('prod= ' || prod); /* " " " " */
Task
Simulate/translate the above PL/I program snippet as best as possible in your
language, with particular emphasis on the do loop construct.
The do index must be incremented/decremented in the same order shown.
If feasible, add commas to the two output numbers (being displayed).
Show all output here.
A simple PL/I DO loop (incrementing or decrementing) has the construct of:
DO variable = start_expression {TO ending_expression] {BY increment_expression} ;
---or---
DO variable = start_expression {BY increment_expression} {TO ending_expression] ;
where it is understood that all expressions will have a value. The variable is normally a
scaler variable, but need not be (but for this task, all variables and expressions are declared
to be scaler integers). If the BY expression is omitted, a BY value of unity is used.
All expressions are evaluated before the DO loop is executed, and those values are used
throughout the DO loop execution (even though, for instance, the value of Z may be
changed within the DO loop. This isn't the case here for this task.
A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges
(the use of multiple TO and/or BY keywords). This is the construct used in this task.
There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be
needed here. DO loops without a TO clause might need a WHILE clause or some other
means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other
(possible error) condition that causes transfer of control outside the DO loop.
Also, in PL/I, the check if the DO loop index value is outside the range is made at the
"head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but
that isn't the case for any of the ranges used in this task.
In the example above, the clause: x to y by z
will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5
In the example above, the clause: -seven to +seven by x
will cause the variable J to have to following values (in this order): -7 -2 3
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #uBasic.2F4tH | uBasic/4tH | p = 1 ' product
s = 0 ' sum
x = 5
y = -5
z = -2
o = 1 ' one
t = 3 ' three
v = 7 ' seVen
For j = -t To (3 ^ 3) Step t: Proc _Process(j) : Next
For j = -v To v Step x: Proc _Process(j) : Next
For j = 555 To 550 - y: Proc _Process(j) : Next
For j = 22 To -28 Step -t: Proc _Process(j) : Next
For j = 1927 To 1939: Proc _Process(j) : Next
For j = x To y Step z: Proc _Process(j) : Next
For j = (11 ^ x) To (11 ^ x) + o: Proc _Process(j) : Next
Print Using " sum= +###,###"; s
Print Using "prod= +###,###,###"; p
End
_Process
Param (1)
s = s + Abs(a@)
If (Abs(p) < (2 ^ 27)) * (a@ # 0) Then p = p * a@
Return |
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
| #Vala | Vala | const int CHARBIT = 8;
long prod = 1;
long sum = 0;
long labs(long n) {
long mask = n >> ((long)sizeof(long) * CHARBIT - 1);
return ((n + mask) ^ mask);
}
long lpow(long base_num, long exp)
{
long result = 1;
while (true)
{
if ((exp & 1) != 0) result *= base_num;
exp >>= 1;
if (exp == 0) break;
base_num *= base_num;
}
return result;
}
void process(long j) {
sum += labs(j);
if (labs(prod) < (1 << 27) && j != 0) prod *= j;
}
void main() {
const int x = 5;
const int y = -5;
const int z = -2;
const int one = 1;
const int three = 3;
const int seven = 11;
long p = lpow(11, x);
for (int j = -three; j <= lpow(3, 3); j += three ) process(j);
for (int j = -seven; j <= seven; j += x) process(j);
for (int j = 555; j <= 550 - y; ++j) process(j);
for (int j = 22; j >= -28; j -= three) process(j);
for (int j = 1928; j <= 1939; ++j) process(j);
for (int j = x; j >= y; j -= -z) process(j);
for (long j = p; j <= p + one; ++j) process(j);
stdout.printf("sum = %10ld\n", sum);
stdout.printf("prod = %10ld\n", prod);
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreachbas
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Dc | Dc | [ q ] sQ [ d 0!<Q p 2 / lW x ] sW 1024 lW 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
| #DCL | DCL | $ i = 1024
$Loop:
$ IF ( i .LE. 0 ) THEN GOTO LoopEnd
$ WRITE sys$output F$FAO( " i = !4UL", i ) ! formatted ASCII output, fixed-width field
$ ! Output alternatives:
$ ! WRITE sys$output F$STRING( i ) ! explicit integer-to-string conversion
$ ! WRITE sys$output i ! implicit conversion to string/output
$ i = i / 2
$ GOTO Loop
$LoopEnd: |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Ceylon | Ceylon | for (i in 10..0) {
print(i);
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Chapel | Chapel | for i in 1..10 by -1 do
writeln(i); |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #AWK | AWK | BEGIN {
val = 0
do {
val++
print val
} while( val % 6 != 0)
} |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Asymptote | Asymptote | for(int i = 0; i < 6; ++i) {
for(int j = 0; j < i; ++j) {
write("*", suffix=none);
}
write("");
} |
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
| #C | C | int i;
for(i = 1; i < 10; i += 2)
printf("%d\n", 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.
| #Scala | Scala | object Ludic {
def main(args: Array[String]): Unit = {
println(
s"""|First 25 Ludic Numbers: ${ludic.take(25).mkString(", ")}
|Ludic Numbers <= 1000: ${ludic.takeWhile(_ <= 1000).size}
|2000-2005th Ludic Numbers: ${ludic.slice(1999, 2005).mkString(", ")}
|Triplets <= 250: ${triplets.takeWhile(_._3 <= 250).mkString(", ")}""".stripMargin)
}
def dropByN[T](lst: LazyList[T], len: Int): LazyList[T] = lst.grouped(len).flatMap(_.init).to(LazyList)
def ludic: LazyList[Int] = 1 #:: LazyList.unfold(LazyList.from(2)){case n +: ns => Some((n, dropByN(ns, n)))}
def triplets: LazyList[(Int, Int, Int)] = LazyList.from(1).map(n => (n, n + 2, n + 6)).filter{case (a, b, c) => Seq(a, b, c).forall(ludic.takeWhile(_ <= c).contains)}
} |
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
| #Factor | Factor | : print-comma-list ( n -- )
[ [1,b] ] keep '[
[ number>string write ]
[ _ = [ ", " write ] unless ] bi
] each nl ; |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Falcon | Falcon | for value = 1 to 10
formiddle
>> value
>> ", "
end
forlast: > value
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
| #ERRE | ERRE |
DIM A%[10,10] ! in declaration part
.............
PRINT(CHR$(12);) !CLS
FOR ROW=1 TO 10 DO
FOR COL=1 TO 10 DO
A%[ROW,COL]=INT(RND(1)*20)+1 ! INT and RND are ERRE predeclared functions
! RND generates random numbers between 0 and 1
END FOR
END FOR
FOR ROW=1 TO 10 DO
FOR COL=1 TO 10 DO
PRINT(A%[ROW,COL])
EXIT IF A%[ROW,COL]=20
END FOR
EXIT IF A%[ROW,COL]=20 ! EXIT breaks the current loop only: you must repeat it,
! use a boolean variable or a GOTO label statement
END FOR
|
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over
[
1
,
…
,
20
]
{\displaystyle [1,\ldots ,20]}
.
The loops iterate rows and columns of the array printing the elements until the value
20
{\displaystyle 20}
is met.
Specifically, this task also shows how to break out of nested loops.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Euphoria | Euphoria | sequence a
a = rand(repeat(repeat(20, 10), 10))
integer wantExit
wantExit = 0
for i = 1 to 10 do
for j = 1 to 10 do
printf(1, "%g ", {a[i][j]})
if a[i][j] = 20 then
wantExit = 1
exit
end if
end for
if wantExit then
exit
end if
end for |
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
| #Fantom | Fantom | class Main
{
public static Void main ()
{
Int[] collection := [1, 2, 3, 4, 5]
collection.each |Int item|
{
echo (item)
}
}
} |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Fennel | Fennel | (each [k v (ipairs [:apple :banana :orange])]
(print k v)) |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. LUHNTEST.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
data division.
WORKING-STORAGE SECTION.
01 inp-card.
03 inp-card-ch pic x(01) occurs 20 times.
01 ws-result pic 9(01).
88 pass-luhn-test value 0.
PROCEDURE DIVISION.
move "49927398716" to inp-card
perform test-card
move "49927398717" to inp-card
perform test-card
move "1234567812345678" to inp-card
perform test-card
move "1234567812345670" to inp-card
perform test-card
stop run
.
test-card.
call "LUHN" using inp-card, ws-result
if pass-luhn-test
display "input=" inp-card "pass"
else
display "input=" inp-card "fail"
.
END PROGRAM LUHNTEST.
IDENTIFICATION DIVISION.
PROGRAM-ID. LUHN.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 maxlen pic 9(02) comp value 16.
01 inplen pic 9(02) comp value 0.
01 i pic 9(02) comp value 0.
01 j pic 9(02) comp value 0.
01 l pic 9(02) comp value 0.
01 dw pic 9(02) comp value 0.
01 ws-total pic 9(03) comp value 0.
01 ws-prod pic 99.
01 filler redefines ws-prod.
03 ws-prod-tens pic 9.
03 ws-prod-units pic 9.
01 ws-card.
03 filler occurs 16 times depending on maxlen.
05 ws-card-ch pic x(01).
05 ws-card-digit redefines ws-card-ch pic 9(01).
LINKAGE SECTION.
01 inp-card.
03 inp-card-ch pic x(01) occurs 20 times.
01 ws-result pic 9(01).
88 pass-luhn-test value 0.
PROCEDURE DIVISION using inp-card, ws-result.
perform varying i from 1 by +1
until i > maxlen
or inp-card-ch (i) = space
end-perform
compute l = i - 1
compute inplen = l
perform varying j from 1 by +1
until j > inplen
if l < 1
move "0" to ws-card-ch (j)
else
move inp-card-ch (l) to ws-card-ch (j)
compute l = l - 1
end-if
end-perform
move 0 to ws-total
perform varying i from 1 by +1
until i > inplen
compute dw = 2 - (i - 2 * function integer (i / 2))
compute ws-prod = ws-card-digit (i) * dw
compute ws-total = ws-total
+ ws-prod-tens
+ ws-prod-units
end-perform
compute ws-result = ws-total - 10 * function integer (ws-total / 10)
goback
.
END PROGRAM LUHN. |
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).
| #JavaScript | JavaScript |
////////// In JavaScript we don't have sqrt for BigInt - so here is implementation
function newtonIteration(n, x0) {
const x1 = ((n / x0) + x0) >> 1n;
if (x0 === x1 || x0 === (x1 - 1n)) {
return x0;
}
return newtonIteration(n, x1);
}
function sqrt(value) {
if (value < 0n) {
throw 'square root of negative numbers is not supported'
}
if (value < 2n) {
return value;
}
return newtonIteration(value, 1n);
}
////////// End of sqrt implementation
function isPrime(p) {
if (p == 2n) {
return true;
} else if (p <= 1n || p % 2n === 0n) {
return false;
} else {
var to = sqrt(p);
for (var i = 3n; i <= to; i += 2n)
if (p % i == 0n) {
return false;
}
return true;
}
}
function isMersennePrime(p) {
if (p == 2n) {
return true;
} else {
var m_p = (1n << p) - 1n;
var s = 4n;
for (var i = 3n; i <= p; i++) {
s = (s * s - 2n) % m_p;
}
return s === 0n;
}
}
var upb = 5000;
var tm = Date.now();
console.log(`Finding Mersenne primes in M[2..${upb}]:`);
console.log('M2');
for (var p = 3n; p <= upb; p += 2n){
if (isPrime(p) && isMersennePrime(p)) {
console.log("M" + p);
}
}
console.log(`... Took: ${Date.now()-tm} ms`);
|
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.
| #Phix | Phix | with javascript_semantics
function compress(string uncompressed)
integer dict = new_dict()
sequence result = {}
integer dictSize = 255, c
string word = ""
for i=0 to 255 do
setd(""&i,i,dict)
end for
for i=1 to length(uncompressed) do
c = uncompressed[i]
if getd_index(word&c,dict) then
word &= c
else
result &= getd(word,dict)
dictSize += 1
setd(word&c,dictSize,dict)
word = ""&c
end if
end for
if word!="" then
result &= getd(word,dict)
end if
destroy_dict(dict)
return result
end function
function decompress(sequence compressed)
integer dict = new_dict()
integer dictSize = 255, k, ki
string dent = "", result = "", word = ""
for i=0 to 255 do
setd(i,""&i,dict)
end for
for i=1 to length(compressed) do
k = compressed[i]
ki = getd_index(k,dict)
if ki then
dent = getd_by_index(ki,dict)
elsif k=dictSize then
dent = word&word[1]
else
return {NULL,i}
end if
result &= dent
setd(dictSize,word&dent[1],dict)
dictSize += 1
word = dent
end for
destroy_dict(dict)
return result
end function
constant example = "TOBEORNOTTOBEORTOBEORNOT"
sequence com = compress(example)
pp(com,{pp_IntCh,true,pp_Maxlen,90})
?decompress(com)
|
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
| #Tcl | Tcl | package require Tcl 8.5
namespace eval matrix {
namespace path {::tcl::mathfunc ::tcl::mathop}
# Construct an identity matrix of the given size
proc identity {order} {
set m [lrepeat $order [lrepeat $order 0]]
for {set i 0} {$i < $order} {incr i} {
lset m $i $i 1
}
return $m
}
# Produce the pivot matrix for a given matrix
proc pivotize {matrix} {
set n [llength $matrix]
set p [identity $n]
for {set j 0} {$j < $n} {incr j} {
set max [lindex $matrix $j $j]
set row $j
for {set i $j} {$i < $n} {incr i} {
if {[lindex $matrix $i $j] > $max} {
set max [lindex $matrix $i $j]
set row $i
}
}
if {$j != $row} {
# Row swap inlined; too trivial to have separate procedure
set tmp [lindex $p $j]
lset p $j [lindex $p $row]
lset p $row $tmp
}
}
return $p
}
# Decompose a square matrix A by PA=LU and return L, U and P
proc luDecompose {A} {
set n [llength $A]
set L [lrepeat $n [lrepeat $n 0]]
set U $L
set P [pivotize $A]
set A [multiply $P $A]
for {set j 0} {$j < $n} {incr j} {
lset L $j $j 1
for {set i 0} {$i <= $j} {incr i} {
lset U $i $j [- [lindex $A $i $j] [SumMul $L $U $i $j $i]]
}
for {set i $j} {$i < $n} {incr i} {
set sum [SumMul $L $U $i $j $j]
lset L $i $j [/ [- [lindex $A $i $j] $sum] [lindex $U $j $j]]
}
}
return [list $L $U $P]
}
# Helper that makes inner loop nicer; multiplies column and row,
# possibly partially...
proc SumMul {A B i j kmax} {
set s 0.0
for {set k 0} {$k < $kmax} {incr k} {
set s [+ $s [* [lindex $A $i $k] [lindex $B $k $j]]]
}
return $s
}
} |
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
| #Run_BASIC | Run 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
| #R | R | i <- 42
primeCount <- 0
while(primeCount < 42)
{
if(gmp::isprime(i) == 2)#1 means "probably prime" and won't come up for numbers this small, 2 is what we want.
{
primeCount <- primeCount + 1
extraCredit <- format(i, big.mark=",", scientific = FALSE)
cat("Prime count:", paste0(primeCount, ";"), "The prime just found was:", extraCredit, "\n")
i <- i + i#This is missing the -1 from the Kotlin solution. There is no need to check i + i (it's even).
}
i <- i + 1
} |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Crystal | Crystal | loop do
puts "SPAM"
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
| #D | D | import std.stdio;
void main() {
while (true)
writeln("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
| #VBA | VBA | Dim prod As Long, sum As Long
Public Sub LoopsWithMultipleRanges()
Dim x As Integer, y As Integer, z As Integer, one As Integer, three As Integer, seven As Integer, j As Long
prod = 1
sum = 0
x = 5
y = -5
z = -2
one = 1
three = 3
seven = 7
For j = -three To pow(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 = pow(11, x) To pow(11, x) + one: Call process(j): Next j
Debug.Print " sum= " & Format(sum, "#,##0")
Debug.Print "prod= " & Format(prod, "#,##0")
End Sub
Private Function pow(x As Long, y As Integer) As Long
pow = WorksheetFunction.Power(x, y)
End Function
Private Sub process(x As Long)
sum = sum + Abs(x)
If Abs(prod) < pow(2, 27) And x <> 0 Then prod = prod * x
End Sub |
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
| #Delphi | Delphi | var
i : Integer;
begin
i := 1024;
while i > 0 do
begin
Writeln(i);
i := i div 2;
end;
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
| #Draco | Draco | proc nonrec main() void:
word i;
i := 1024;
while i > 0 do
writeln(i);
i := i >> 1
od
corp |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Clipper | Clipper | FOR i := 10 TO 0 STEP -1
? i
NEXT |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Clojure | Clojure | (doseq [x (range 10 -1 -1)] (println x)) |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #Axe | Axe | 0→A
While 1
A++
Disp A▶Dec,i
End!If A^6 |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #AutoHotkey | AutoHotkey | Gui, Add, Edit, vOutput r5 w100 -VScroll ; Create an Edit-Control
Gui, Show ; Show the window
Loop, 5 ; loop 5 times
{
Loop, %A_Index% ; A_Index contains the Index of the current loop
{
output .= "*" ; append an "*" to the output var
GuiControl, , Output, %Output% ; update the Edit-Control with the new content
Sleep, 500 ; wait some(500ms) time, [just to show off]
}
Output .= (A_Index = 5) ? "" : "`n" ; append a new line to the output if A_Index is not "5"
}
Return ; End of auto-execution section |
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
| #C.23 | C# | using System;
class Program {
static void Main(string[] args) {
for (int i = 2; i <= 8; i+= 2) {
Console.Write("{0}, ", i);
}
Console.WriteLine("who do we appreciate?");
}
} |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func set of integer: ludicNumbers (in integer: n) is func
result
var set of integer: ludicNumbers is {1};
local
var set of integer: sieve is EMPTY_SET;
var integer: ludicNumber is 0;
var integer: number is 0;
var integer: count is 0;
begin
sieve := {2 .. n};
while sieve <> EMPTY_SET do
ludicNumber := min(sieve);
incl(ludicNumbers, ludicNumber);
count := 0;
for number range sieve do
if count rem ludicNumber = 0 then
excl(sieve, number);
end if;
incr(count);
end for;
end while;
end func;
const integer: limit is 22000;
const set of integer: ludicNumbers is ludicNumbers(limit);
const proc: main is func
local
var integer: number is 0;
var integer: count is 0;
begin
write("First 25:");
for number range ludicNumbers until count = 25 do
write(" " <& number);
incr(count);
end for;
writeln;
count := 0;
for number range ludicNumbers until number > 1000 do
incr(count);
end for;
writeln("Ludics below 1000: " <& count);
write("Ludic 2000 to 2005:");
count := 0;
for number range ludicNumbers until count >= 2005 do
incr(count);
if count >= 2000 then
write(" " <& number);
end if;
end for;
writeln;
write("Triples below 250:");
for number range ludicNumbers until number > 250 do
if number + 2 in ludicNumbers and number + 6 in ludicNumbers then
write(" (" <& number <& ", " <& number + 2 <& ", " <& number + 6 <& ")");
end if;
end for;
writeln;
end func; |
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
| #FALSE | FALSE | 1[$9>~][$.", "1+]#. |
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
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
for (Int i := 1; i <= 10; i++)
{
Env.cur.out.writeObj (i)
if (i == 10) break
Env.cur.out.writeChars (", ")
}
Env.cur.out.printLine ("")
}
}
|
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
| #F.23 | F# |
//Nigel Galloway: November 10th., 2017
let n = System.Random()
let g = Array2D.init 8 8 (fun _ _ -> 1+n.Next()%20)
Array2D.iter (fun n -> printf "%d " n) g; printfn ""
g |> Seq.cast<int> |> Seq.takeWhile(fun n->n<20) |> Seq.iter (fun n -> printf "%d " n)
|
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
| #Forth | Forth | create a 3 , 2 , 1 ,
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1 |
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
| #Fortran | Fortran | program main
implicit none
integer :: i
character(len=5),dimension(5),parameter :: colors = ['Red ','Green','Blue ','Black','White']
!using a do loop:
do i=1,size(colors)
write(*,'(A)') colors(i)
end do
!this will also print each element:
write(*,'(A)') colors
end program main |
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
| #Comal | Comal | 0010 FUNC luhn(s$) CLOSED
0020 total#:=0
0030 even#:=TRUE
0040 FOR i#:=LEN(s$) TO 1 STEP -1 DO
0050 digit#:=VAL(s$(i#))
0060 even#:=NOT even#
0070 IF even# THEN digit#:=(2*digit#) DIV 10+(2*digit#) MOD 10
0080 total#:+digit#
0090 ENDFOR i#
0100 RETURN total# MOD 10=0
0110 ENDFUNC luhn
0120 //
0130 PROC test(s$)
0140 PRINT s$,": ",
0150 IF luhn(s$) THEN
0160 PRINT "pass"
0170 ELSE
0180 PRINT "fail"
0190 ENDIF
0200 ENDPROC test
0210 //
0220 test("49927398716")
0230 test("49927398717")
0240 test("1234567812345678")
0250 test("1234567812345670")
0260 END |
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).
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else {i:23}
| until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
| .i * .i > $n
end;
# using the Lucac-Lehmer test for p>2, emit a stream of the form
# Mp:l where p is a Mersenne_prime and l is (p|tostring|length).
# 2^1 - 1 = 2 so we begin with M2:1.
def mersenne_primes:
"M2:1",
(range(3;infinite;2)
| . as $i
| select(is_prime)
| . as $p
| ((2 | power($p)) - 1) as $mp
| select(0 == (reduce range(3; $p + 1) as $_ (4; (power(2) -2) % $mp) ) )
| "M\($i):\($mp|tostring|length)" );
mersenne_primes |
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.
| #PHP | PHP | class LZW
{
function compress($unc) {
$i;$c;$wc;
$w = "";
$dictionary = array();
$result = array();
$dictSize = 256;
for ($i = 0; $i < 256; $i += 1) {
$dictionary[chr($i)] = $i;
}
for ($i = 0; $i < strlen($unc); $i++) {
$c = $unc[$i];
$wc = $w.$c;
if (array_key_exists($w.$c, $dictionary)) {
$w = $w.$c;
} else {
array_push($result,$dictionary[$w]);
$dictionary[$wc] = $dictSize++;
$w = (string)$c;
}
}
if ($w !== "") {
array_push($result,$dictionary[$w]);
}
return implode(",",$result);
}
function decompress($com) {
$com = explode(",",$com);
$i;$w;$k;$result;
$dictionary = array();
$entry = "";
$dictSize = 256;
for ($i = 0; $i < 256; $i++) {
$dictionary[$i] = chr($i);
}
$w = chr($com[0]);
$result = $w;
for ($i = 1; $i < count($com);$i++) {
$k = $com[$i];
if ($dictionary[$k]) {
$entry = $dictionary[$k];
} else {
if ($k === $dictSize) {
$entry = $w.$w[0];
} else {
return null;
}
}
$result .= $entry;
$dictionary[$dictSize++] = $w . $entry[0];
$w = $entry;
}
return $result;
}
}
//How to use
$str = 'TOBEORNOTTOBEORTOBEORNOT';
$lzw = new LZW();
$com = $lzw->compress($str);
$dec = $lzw->decompress($com);
echo $com . "<br>" . $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
| #VBA | VBA | Option Base 1
Private Function pivotize(m As Variant) As Variant
Dim n As Integer: n = UBound(m)
Dim im() As Double
ReDim im(n, n)
For i = 1 To n
For j = 1 To n
im(i, j) = 0
Next j
im(i, i) = 1
Next i
For i = 1 To n
mx = Abs(m(i, i))
row_ = i
For j = i To n
If Abs(m(j, i)) > mx Then
mx = Abs(m(j, i))
row_ = j
End If
Next j
If i <> Row Then
For j = 1 To n
tmp = im(i, j)
im(i, j) = im(row_, j)
im(row_, j) = tmp
Next j
End If
Next i
pivotize = im
End Function
Private Function lu(a As Variant) As Variant
Dim n As Integer: n = UBound(a)
Dim l() As Double
ReDim l(n, n)
For i = 1 To n
For j = 1 To n
l(i, j) = 0
Next j
Next i
u = l
p = pivotize(a)
a2 = WorksheetFunction.MMult(p, a)
For j = 1 To n
l(j, j) = 1#
For i = 1 To j
sum1 = 0#
For k = 1 To i
sum1 = sum1 + u(k, j) * l(i, k)
Next k
u(i, j) = a2(i, j) - sum1
Next i
For i = j + 1 To n
sum2 = 0#
For k = 1 To j
sum2 = sum2 + u(k, j) * l(i, k)
Next k
l(i, j) = (a2(i, j) - sum2) / u(j, j)
Next i
Next j
Dim res(4) As Variant
res(1) = a
res(2) = l
res(3) = u
res(4) = p
lu = res
End Function
Public Sub main()
a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]
Debug.Print "== a,l,u,p: =="
result = lu(a)
For i = 1 To 4
For j = 1 To UBound(result(1))
For k = 1 To UBound(result(1), 2)
Debug.Print result(i)(j, k),
Next k
Debug.Print
Next j
Debug.Print
Next i
a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]
Debug.Print "== a,l,u,p: =="
result = lu(a)
For i = 1 To 4
For j = 1 To UBound(result(1))
For k = 1 To UBound(result(1), 2)
Debug.Print Format(result(i)(j, k), "0.#####"),
Next k
Debug.Print
Next j
Debug.Print
Next i
End Sub |
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
| #Rust | Rust | extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::io;
fn main() {
let mut input_line = String::new();
let mut template = String::new();
println!("Please enter a multi-line story template with <parts> to replace, terminated by a blank line.\n");
loop {
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if input_line.trim().is_empty() {
break;
}
template.push_str(&input_line);
input_line.clear();
}
let re = Regex::new(r"<[^>]+>").unwrap();
let mut parts: HashMap<_, _> = re
.captures_iter(&template)
.map(|x| (x.get(0).unwrap().as_str().to_string(), "".to_string()))
.collect();
if parts.is_empty() {
println!("No <parts> to replace.\n");
} else {
for (k, v) in parts.iter_mut() {
println!("Please provide a replacement for {}: ", k);
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
*v = input_line.trim().to_string();
println!();
template = template.replace(k, v);
input_line.clear();
}
}
println!("Resulting story:\n\n{}", 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
| #Racket | Racket | #lang racket
(require math/number-theory)
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(let loop ([x 42] [cnt 0])
(cond
[(= cnt 42) (void)]
[(prime? x) (printf "~a: ~a\n" (add1 cnt) (comma x))
(loop (* 2 x) (add1 cnt))]
[else (loop (add1 x) cnt)])) |
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
| #Raku | Raku | # the actual sequence logic
my @seq = grep *.is-prime, (42, { .is-prime ?? $_+<1 !! $_+1 } … *);
# display code
say (1+$_).fmt("%-4s"), @seq[$_].flip.comb(3).join(',').flip.fmt("%20s") for ^42; |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Dart | Dart |
main() {
while(true) {
print("SPAM");
}
}
|
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #dc | dc | [[SPAM
]P dx]dx |
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
| #Visual_Basic_.NET | Visual Basic .NET | Partial Module Program
' Stop and Step are language keywords and must be escaped with brackets.
Iterator Function Range(start As Integer, [stop] As Integer, Optional [step] As Integer = 1) As IEnumerable(Of Integer)
For i = start To [stop] Step [step]
Yield i
Next
End Function
End Module |
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
| #Dragon | Dragon | i = 1024
while(i > 0){
showln i
i >>= 1 //also acceptable: i /= 2
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #COBOL | COBOL | identification division.
program-id. countdown.
environment division.
data division.
working-storage section.
01 counter pic 99.
88 counter-done value 0.
01 counter-disp pic Z9.
procedure division.
perform with test after varying counter from 10 by -1 until counter-done
move counter to counter-disp
display counter-disp
end-perform
stop run. |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #CoffeeScript | CoffeeScript | # The more compact "array comprehension" style
console.log i for i in [10..0]
# The "regular" for loop style.
for i in [10..0]
console.log i
# More compact version of the above
for i in [10..0] then console.log i |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #BASIC | BASIC | a = 0
DO
a = a + 1
PRINT a
LOOP WHILE a MOD 6 <> 0 |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #Avail | Avail | For each row from 1 to 5 do
[
For each length from 1 to row do [Print: "*";];
Print: "\n";
]; |
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
| #C.2B.2B | C++ | for (int i = 1; i < 10; i += 2)
std::cout << i << std::endl; |
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.
| #SequenceL | SequenceL |
import <Utilities/Set.sl>;
ludic(v(1), result(1)) :=
let
n := head(v);
filtered[i] := v[i] when (i-1) mod n /= 0;
in
result when size(v) < 1 else
ludic(filtered, result ++ [n]);
count : int(1) * int * int -> int;
count(v(1), top, index) :=
index-1 when v[index] > top else
count(v, top, index + 1);
main() :=
let
ludics := ludic(2...100000, [1]);
ludics250 := ludics[1 ... count(ludics, 250, 1)];
triplets[i] := [i, i+2, i+6] when elementOf(i+2, ludics250) and elementOf(i+6, ludics250)
foreach i within ludics250;
in
"First 25:\n" ++ toString(ludics[1...25]) ++
"\n\nLudics below 1000:\n" ++ toString(count(ludics, 1000, 1)) ++
"\n\nLudic 2000 to 2005:\n" ++ toString(ludics[2000...2005]) ++
"\n\nTriples below 250:\n" ++ toString(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
| #FBSL | FBSL |
#APPTYPE CONSOLE
FOR DIM i = 1 TO 10
PRINT i;
IF i < 10 THEN PRINT ", ";
NEXT
PAUSE |
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
| #Forth | Forth | : comma-list ( n -- )
dup 1 ?do i 1 .r ." , " loop
. ; |
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
| #Factor | Factor | USING: io kernel math.ranges prettyprint random sequences ;
10 [ 20 [ 20 [1,b] random ] replicate ] replicate ! make a table of random values
[ [ dup pprint bl 20 = ] find nl drop ] find 2drop ! print values until 20 is found |
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
| #Fantom | Fantom | class Main
{
public static Void main ()
{
rows := 10
cols := 10
// create and fill an array of given size with random numbers
Int[][] array := [,]
rows.times
{
row := [,]
cols.times { row.add(Int.random(1..20)) }
array.add (row)
}
// now do the search
try
{
for (i := 0; i < rows; i++)
{
for (j := 0; j < cols; j++)
{
echo ("now at ($i, $j) which is ${array[i][j]}")
if (array[i][j] == 20) throw (Err("found it"))
}
}
}
catch (Err e)
{
echo (e.msg)
return // and finish
}
echo ("No 20")
}
} |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #friendly_interactive_shell | friendly interactive shell | for path in $PATH
echo You have $path in PATH.
end |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Frink | Frink |
array = [1, 2, 3, 5, 7]
for n = array
println[n]
|
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
Taking the second, fourth ... and every other even digit in the reversed digits:
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
Sum the partial sums of the even digits to form s2
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
For example, if the trial number is 49927398716:
Reverse the digits:
61789372994
Sum the odd digits:
6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even digits:
1, 8, 3, 2, 9
Two times each even digit:
2, 16, 6, 4, 18
Sum the digits of each multiplication:
2, 7, 6, 4, 9
Sum the last:
2 + 7 + 6 + 4 + 9 = 28 = s2
s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test
Task
Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and
use it to validate the following numbers:
49927398716
49927398717
1234567812345678
1234567812345670
Related tasks
SEDOL
ISIN
| #Common_Lisp | Common Lisp | (defun luhn (n)
(labels ((sum-digits (n) (if (> n 9) (- n 9) n)))
(let ((n* (reverse n)) (l (length n)))
(let ((s1 (loop for i from 0 below l by 2
summing (digit-char-p (aref n* i))))
(s2 (loop for i from 1 below l by 2
summing (sum-digits (* 2 (digit-char-p (aref n* i)))))))
(zerop (mod (+ s1 s2) 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).
| #Julia | Julia |
using Primes
function getmersenneprimes(n)
t1 = time()
count = 0
i = 2
while(n > count)
if(isprime(i) && ismersenneprime(2^BigInt(i) - 1))
println("M$i, cumulative time elapsed: $(time() - t1) seconds")
count += 1
end
i += 1
end
end
getmersenneprimes(50)
|
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.
| #Picat | Picat | go =>
S = "TOBEORNOTTOBEORTOBEORNOT",
println(s=S),
println(len=S.length),
Compressed = compress(S),
println(compressed=Compressed),
println(len=Compressed.length),
Uncompressed = uncompress(Compressed),
println(uncompressed=Uncompressed),
printf("compressed to %3.3f%%\n", 100*(Compressed.length / S.length)),
if S = Uncompressed then
println("Same!")
else
println("Error: S != Uncompressed!"),
printf("S.length: %d Uncompressed.length: %d\n", S.length, Uncompressed.length),
edit(S,Uncompressed,Distance,Diffs),
println(distance=Distance),
println(diffs=Diffs)
end,
nl.
compress(Uncompressed) = Compressed =>
DictSize = 256,
Dict = new_map([C=C : I in 1..DictSize-1, C=chr(I).to_string()]),
W = "",
Result = [],
foreach(C in Uncompressed)
C := C.to_string(),
WC = W ++ C,
if Dict.has_key(WC) then
W := WC
else
Result := Result ++ [Dict.get(W)],
Dict.put(WC, DictSize),
DictSize := DictSize + 1,
W := C
end
end,
if W.length > 0 then
Result := Result ++ [Dict.get(W)]
end,
Compressed = Result.
uncompress(Compressed) = Uncompressed =>
DictSize = 256,
Dict = new_map([ C=C : I in 1..DictSize-1, C=chr(I).to_string()]),
W = Compressed.first(),
Compressed := Compressed.tail(),
Result = W,
Entry = "",
foreach(K in Compressed)
if Dict.has_key(K) then
Entry := Dict.get(K)
elseif K == DictSize then
Entry := W ++ W[1].to_string()
else
printf("Bad compressed K: %w\n", K)
end,
Result := Result ++ Entry,
Dict.put(DictSize,(W ++ Entry[1].to_string())),
DictSize := DictSize + 1,
W := Entry
end,
Uncompressed = Result.flatten().
%
% Computing the minimal editing distance of two given lists
%
table(+,+,min,-)
edit([],[],D,Diffs) => D=0, Diffs=[].
edit([X|Xs],[X|Ys],D,Diffs) => % copy
edit(Xs,Ys,D,Diffs).
edit(Xs,[Y|Ys],D,Diffs) ?=> % insert
edit(Xs,Ys,D1,Diffs1),
D=D1+1,
Diffs = [insert=Y,xPos=Xs.length,yPos=Ys.length|Diffs1].
edit([X|Xs],Ys,D,Diffs) => % delete
edit(Xs,Ys,D1,Diffs1),
D=D1+1,
Diffs = [[delete=X,xPos=Xs.length,yPos=Ys.length]|Diffs1]. |
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
| #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var arrays = [
[ [1, 3, 5],
[2, 4, 7],
[1, 1, 0] ],
[ [11, 9, 24, 2],
[ 1, 5, 2, 6],
[ 3, 17, 18, 1],
[ 2, 5, 7, 1] ]
]
for (array in arrays) {
var m = Matrix.new(array)
System.print("A\n")
Fmt.mprint(m, 2, 0)
System.print("\nL\n")
var lup = m.lup
Fmt.mprint(lup[0], 8, 5)
System.print("\nU\n")
Fmt.mprint(lup[1], 8, 5)
System.print("\nP\n")
Fmt.mprint(lup[2], 2, 0)
System.print()
} |
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
| #Scala | Scala | object MadLibs extends App{
val input = "<name> went for a walk in the park. <he or she>\nfound a <noun>. <name> decided to take it home."
println(input)
println
val todo = "(<[^>]+>)".r
val replacements = todo.findAllIn(input).toSet.map{found: String =>
found -> readLine(s"Enter a $found ")
}.toMap
val output = todo.replaceAllIn(input, found => replacements(found.matched))
println
println(output)
} |
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
| #REXX | REXX | /*REXX pgm displays primes found: starting Z at 42, if Z is a prime, add Z, else add 1.*/
numeric digits 20; d=digits() /*ensure enough decimal digits for Z. */
parse arg limit . /*obtain optional arguments from the CL*/
if limit=='' | limit=="," then limit=42 /*Not specified? Then use the default.*/
n=0 /*the count of number of primes found. */
do z=42 until n==limit /* ◄──this DO loop's index is modified.*/
if isPrime(z) then do; n=n + 1 /*Z a prime? Them bump prime counter.*/
say right('n='n, 9) right(commas(z), d)
z=z + z - 1 /*also, bump the DO loop index Z. */
end
end /*z*/ /* [↑] a small tribute to Douglas Adams*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do j=length(_)-3 to 1 by -3; _=insert(',', _, j); end; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg #; if wordpos(#, '2 3 5 7')\==0 then return 1
if # // 2==0 | # // 3 ==0 then return 0
do j=5 by 6 until j*j>#; if # // j==0 | # // (J+2)==0 then return 0
end /*j*/ /* ___ */
return 1 /*Exceeded √ # ? Then # is prime. */ |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #DCL | DCL | $ loop:
$ write sys$output "SPAM"
$ goto loop |
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
| #Delphi | Delphi | proc nonrec main() void:
while true do
writeln("SPAM")
od
corp |
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
| #Wren | Wren | import "/fmt" for Fmt
var prod = 1
var sum = 0
var x = 5
var y = -5
var z = -2
var one = 1
var three = 3
var seven = 7
var p = 11.pow(x)
var j = 0
var process = Fn.new {
sum = sum + j.abs
if (prod.abs < (1 << 27) && j != 0) prod = prod * j
}
j = -three
while (j <= 3.pow(3)) {
process.call()
j = j + three
}
j = -seven
while (j <= seven) {
process.call()
j = j + x
}
j = 555
while (j <= 550 - y) {
process.call()
j = j + 1
}
j = 22
while (j >= -28) {
process.call()
j = j - three
}
j = 1927
while (j <= 1939) {
process.call()
j = j + 1
}
j = x
while (j >= y) {
process.call()
j = j - (-z)
}
j = p
while (j <= p + one) {
process.call()
j = j + 1
}
System.print("sum = %(Fmt.dc(sum))")
System.print("prod = %(Fmt.dc(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
| #DUP | DUP | 1024[$][$.10,2/\%]# {Short form} |
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
| #DWScript | DWScript | var i := 1024;
while i > 0 do begin
PrintLn(i);
i := i div 2;
end; |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #ColdFusion | ColdFusion | <cfloop index = "i" from = "10" to = "0" step = "-1">
#i#
</cfloop> |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
| #Common_Lisp | Common Lisp | (loop for i from 10 downto 1 do
(print i)) |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
Do while loop Wikipedia.
| #bc | bc | i = 0
for (;;) {
++i /* increments then prints i */
if (i % 6 == 0) break
}
quit |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
Task
Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop.
Specifically print out the following pattern by using one for loop nested in another:
*
**
***
****
*****
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body
Loops/Infinite
Loops/N plus one half
Loops/Nested
Loops/While
Loops/with multiple ranges
Loops/Wrong ranges
Reference
For loop Wikipedia.
| #AWK | AWK | BEGIN {
for(i=1; i < 6; i++) {
for(j=1; j <= i; j++ ) {
printf "*"
}
print
}
} |
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
| #Ceylon | Ceylon | shared void run() {
for(i in (2..8).by(2)) {
process.write("``i`` ");
}
print("who do we appreciate?");
} |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Loop)
Take the first member of the resultant array as the next ludic number 2.
Remove every 2nd indexed item from the array (including the first).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
(Unrolling a few loops...)
Take the first member of the resultant array as the next ludic number 3.
Remove every 3rd indexed item from the array (including the first).
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ...
Take the first member of the resultant array as the next ludic number 5.
Remove every 5th indexed item from the array (including the first).
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ...
Take the first member of the resultant array as the next ludic number 7.
Remove every 7th indexed item from the array (including the first).
7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ...
...
Take the first member of the current array as the next ludic number L.
Remove every Lth indexed item from the array (including the first).
...
Task
Generate and show here the first 25 ludic numbers.
How many ludic numbers are there less than or equal to 1000?
Show the 2000..2005th ludic numbers.
Stretch goal
Show all triplets of ludic numbers < 250.
A triplet is any three numbers
x
,
{\displaystyle x,}
x
+
2
,
{\displaystyle x+2,}
x
+
6
{\displaystyle x+6}
where all three numbers are also ludic numbers.
| #Sidef | Sidef | func ludics_upto(nmax=100000) {
Enumerator({ |collect|
collect(1)
var arr = @(2..nmax)
while (arr) {
collect(var n = arr[0])
arr.range.by(n).each {|i| arr[i] = nil}
arr.compact!
}
})
}
func ludics_first(n) {
ludics_upto(n * n.log2).first(n)
}
say("First 25 Ludic numbers: ", ludics_first(25).join(' '))
say("Ludics below 1000: ", ludics_upto(1000).len)
say("Ludic numbers 2000 to 2005: ", ludics_first(2005).last(6).join(' '))
var a = ludics_upto(250).to_a
say("Ludic triples below 250: ", a.grep{|x| a.contains_all([x+2, x+6]) } \
.map {|x| '(' + [x, x+2, x+6].join(' ') + ')' } \
.join(' ')) |
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.