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/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.
... | #Quackery | Quackery | 5 times [ i^ 1+ times [ say "*" ] cr ] |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Go | Go | package main
import (
"fmt"
"log"
"math"
"rcu"
)
var limit = int(math.Sqrt(1e9))
var primes = rcu.Primes(limit)
var memoPhi = make(map[int]int)
func cantorPair(x, y int) int {
if x < 0 || y < 0 {
log.Fatal("Arguments must be non-negative integers.")
}
return (x*x + 3*x + 2*x*y ... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Haskell | Haskell | costs :: String -> String -> [[Int]]
costs s1 s2 = reverse $ reverse <$> matrix
where
matrix = scanl transform [0 .. length s1] s2
transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1
where
calc z (c1, x, y) = minimum [ y + 1, z + 1
, x + fromEnum (c1 ... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #PowerShell | PowerShell |
function zip3 ($a1, $a2, $a3)
{
while ($a1)
{
$x, $a1 = $a1
$y, $a2 = $a2
$z, $a3 = $a3
[Tuple]::Create($x, $y, $z)
}
}
|
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Swift | Swift | func lookAndSay(_ seq: [Int]) -> [Int] {
var result = [Int]()
var cur = seq[0]
var curRunLength = 1
for i in seq.dropFirst() {
if cur == i {
curRunLength += 1
} else {
result.append(curRunLength)
result.append(cur)
curRunLength = 1
cur = i
}
}
result.append(curR... |
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.
... | #R | R | for(i in 0:4) {
s <- ""
for(j in 0:i) {
s <- paste(s, "*", sep="")
}
print(s)
} |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Java | Java | import java.util.*;
public class LegendrePrimeCounter {
public static void main(String[] args) {
LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
System.out.printf("10^%d\t%d\n", i, counter.primeCount((n)));
}
p... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #J | J | levalign=:4 :0
assert. x <:&# y
D=. x +/&i.&>:&# y
for_i. 1+i.#x do.
for_j. 1+i.#y do.
if. ((<:i){x)=(<:j){y do.
D=. (D {~<<:i,j) (<i,j)} D
else.
min=. 1+<./D{~(i,j) <@:-"1#:1 2 3
D=. min (<i,j)} D
end.
end.
end.
A=. B=. ''
ij=. x ,&# y
while. */ij do.
... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Prolog | Prolog | multiple_arrays(L1, L2, L3) :-
maplist(display, L1, L2, L3).
display(A,B,C) :-
writef('%s%s%s\n', [[A],[B],[C]]).
|
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Tcl | Tcl | proc lookandsay n {
set new ""
while {[string length $n] > 0} {
set char [string index $n 0]
for {set count 1} {[string index $n $count] eq $char} {incr count} {}
append new $count $char
set n [string range $n $count end]
}
interp alias {} next_lookandsay {} lookandsay $n... |
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.
... | #Racket | Racket | (for ([i (in-range 1 6)]) (for ([j i]) (display "*")) (newline)) |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Haskell | Haskell | data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Integral a => Memo a
nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)
memoize :: Integral a => (a... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Java | Java | public class LevenshteinAlignment {
public static String[] alignment(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int[][] costs = new int[a.length()+1][b.length()+1];
for (int j = 0; j <= b.length(); j++)
costs[0][j] = j;
for... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #PureBasic | PureBasic | OpenConsole()
; Fill arrays
Dim a.s(2)
Dim b.s(2)
Dim c(2)
For Arrayposition = 0 To ArraySize(a())
a(Arrayposition) = Chr(Asc("a") + Arrayposition)
b(Arrayposition) = Chr(Asc("A") + Arrayposition)
c(Arrayposition) = Arrayposition + 1
Next
; loop over them
For Arrayposition = 0 To ArraySize(a())
PrintN(a(Arraypo... |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT,{}
num=1,say=""
LOOP look
digits=STRINGS (num," ? ")
digitgrouped=ACCUMULATE (digits,howmany)
LOOP/CLEAR h=howmany,digit=digitgrouped
say=JOIN (say,"",h,digit)
ENDLOOP
PRINT say
num=VALUE(say),say=""
IF (look==14) EXIT
ENDLOOP
|
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #UNIX_Shell | UNIX Shell | lookandsay() {
local num=$1 char seq i
for ((i=0; i<=${#num}; i++)); do
char=${num:i:1}
if [[ $char == ${seq:0:1} ]]; then
seq+=$char
else
[[ -n $seq ]] && printf "%d%s" ${#seq} ${seq:0:1}
seq=$char
fi
done
}
for ((num=1, i=1; i<=10; i++)... |
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.
... | #Raku | Raku | for ^5 {
for 0..$_ {
print "*";
}
print "\n";
} |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #J | J | require'format/printf'
{{echo '10^%d: %d' sprintf y;p:inv 10^y}}"0 i.10
10^0: 0
10^1: 4
10^2: 25
10^3: 168
10^4: 1229
10^5: 9592
10^6: 78498
10^7: 664579
10^8: 5761455
10^9: 50847534 |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #jq | jq | # For the sake of the accuracy of integer arithmetic when using gojq:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# Input: $n, which is assumed to be positive integer,
# Output: an array of primes less than or equal to $n (e.g. 10|eratosthenes #=> [2,3,5,7]
def eratosthenes:
# erase(i) sets .[i... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Julia | Julia | function levenshteinalign(a::AbstractString, b::AbstractString)
a = lowercase(a)
b = lowercase(b)
len_a = length(a)
len_b = length(b)
costs = Matrix{Int}(len_a + 1, len_b + 1)
costs[1, :] .= 0:len_b
@inbounds for i in 2:(len_a + 1)
costs[i, 1] = i
for j in 2:(len_b + 1)
... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Kotlin | Kotlin | // version 1.1.3
fun levenshteinAlign(a: String, b: String): Array<String> {
val aa = a.toLowerCase()
val bb = b.toLowerCase()
val costs = Array(a.length + 1) { IntArray(b.length + 1) }
for (j in 0..b.length) costs[0][j] = j
for (i in 1..a.length) {
costs[i][0] = i
for (j in 1..b.l... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Python | Python | >>> print ( '\n'.join(''.join(x) for x in
zip('abc', 'ABC', '123')) )
aA1
bB2
cC3
>>> |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Ursala | Ursala | #import std
#import nat
look_and_say "n" = ~&H\'1' next"n" rlc~&E; *= ^lhPrT\~&hNC %nP+ length
#show+
main = look_and_say 10 |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #VBA | VBA |
Public Sub LookAndSay(Optional Niter As Integer = 10)
'generate "Niter" members of the look-and-say sequence
'(argument is optional; default is 10)
Dim s As String 'look-and-say number
Dim news As String 'next number in sequence
Dim curdigit As String 'current digit in s
Dim newdigit As Strin... |
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.
... | #REBOL | REBOL | ; Use 'repeat' when an index required, 'loop' when repetition suffices:
repeat i 5 [
loop i [prin "*"]
print ""
]
; or a more traditional for loop:
for i 1 5 1 [
loop i [prin "*"]
print ""
] |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Julia | Julia | using Primes
function primepi(N)
delta = round(Int, N^0.8)
return sum(i -> count(primesmask(i, min(i + delta - 1, N))), 1:delta:N)
end
@time for power in 0:9
println("10^", rpad(power, 5), primepi(10^power))
end
|
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Phi,pi]
$RecursionLimit = 10^6;
Phi[x_, 0] := x
Phi[x_, a_] := Phi[x, a] = Phi[x, a - 1] - Phi[Floor[x/Prime[a]], a - 1]
pi[n_] := Module[{a}, If[n < 2, 0, a = pi[Floor[Sqrt[n]]]; Phi[n, a] + a - 1]]
Scan[Print[pi[10^#]] &, Range[0,9]] |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | DamerauLevenshteinDistance["rosettacode", "raisethysword"] |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Nim | Nim | import algorithm, sequtils, strutils
proc levenshteinAlign(a, b: string): tuple[a, b: string] =
let a = a.toLower()
let b = b.toLower()
var costs = newSeqWith(a.len + 1, newSeq[int](b.len + 1))
for j in 0..b.len: costs[0][j] = j
for i in 1..a.len:
costs[i][0] = i
for j in 1..b.len:
let tmp = c... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Quackery | Quackery | [ rot witheach
[ emit
over i^ peek emit
dup i^ peek emit
cr ]
2drop ] is task ( $ $ $ --> )
$ "abc" $ "ABC" $ "123" task |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #VBScript | VBScript | function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #11l | 11l | print(cart_product(1..20, 1..20, 1..20).filter((x, y, z) -> x ^ 2 + y ^ 2 == z ^ 2 & y C x .. z)) |
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.
... | #Red | Red | Red[]
repeat i 5 [
loop i [prin "*"]
prin newline
] |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Nim | Nim | import math, strutils, sugar, tables
const
N = 1_000_000_000
S = sqrt(N.toFloat).int
var composite: array[3..S, bool]
for n in countup(3, S, 2):
if n * n > S: break
if not composite[n]:
for k in countup(n * n, S, 2 * n):
composite[k] = true
# Prime list. Add a dummy zero to start at index 1.
let... |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Legendre_prime_counting_function
use warnings;
no warnings qw(recursion);
use ntheory qw( nth_prime prime_count );
my (%cachephi, %cachepi);
sub phi
{
return $cachephi{"@_"} //= do {
my ($x, $aa) = @_;
$aa <= 0 ? $x : phi($x, $aa - 1) - phi(in... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Perl | Perl | use strict;
use warnings;
use List::Util qw(min);
sub levenshtein_distance_alignment {
my @s = ('^', split //, shift);
my @t = ('^', split //, shift);
my @A;
@{$A[$_][0]}{qw(d s t)} = ($_, join('', @s[1 .. $_]), ('~' x $_)) for 0 .. $#s;
@{$A[0][$_]}{qw(d s t)} = ($_, ('-' x $_), join '', @t[1... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #R | R | multiloop <- function(...)
{
# Retrieve inputs and convert to a list of character strings
arguments <- lapply(list(...), as.character)
# Get length of each input
lengths <- sapply(arguments, length)
# Loop over elements
for(i in seq_len(max(lengths)))
{
# Loop over inputs
for(j in... |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Vedit_macro_language | Vedit macro language | Repeat(10) {
BOL
Reg_Empty(20)
While (!At_EOL) {
Match("(.)\1*", REGEXP+ADVANCE)
Num_Str(Chars_Matched, 20, LEFT+APPEND)
Reg_Copy_Block(20, CP-1, CP, APPEND)
}
Ins_Newline Reg_Ins(20)
} |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #ABAP | ABAP |
CLASS lcl_pythagorean_triplet DEFINITION CREATE PUBLIC.
PUBLIC SECTION.
TYPES: BEGIN OF ty_triplet,
x TYPE i,
y TYPE i,
z TYPE i,
END OF ty_triplet,
tty_triplets TYPE STANDARD TABLE OF ty_triplet WITH NON-UNIQUE EMPTY KEY.
CLASS-METHODS:
g... |
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.
... | #ReScript | ReScript | let s = ref("")
for i in 1 to 5 {
for _ in 1 to i {
s := Js.String2.concat(s.contents, "*")
}
s := Js.String2.concat(s.contents, "\n")
}
Js.log(s.contents) |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Phix | Phix | with javascript_semantics
--
-- While a phix dictionary can handle keys of {x,a}, for this
-- task performance was dreadful (7,612,479 entries, >3mins),
-- so instead memophix maps known x to an index to memophia
-- which holds the full [1..a] for each x, dropping to a much
-- more respectable (albeit not super-fast)... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Phix | Phix | function LevenshteinAlignment(string a, b)
integer la = length(a)+1,
lb = length(b)+1
sequence costs = repeat(repeat(0,lb),la)
for j=1 to lb do
costs[1][j] = j
end for
for i=2 to la do
costs[i][1] = i
for j=2 to lb do
integer tmp1 = 1+min(costs[i-1][j]... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Racket | Racket |
#lang racket
(for ([x '(a b c)] ; list
[y #(A B C)] ; vector
[z "123"]
[i (in-naturals 1)]) ; 1, 2, ... infinitely
(printf "~s: ~s ~s ~s\n" i x y z))
|
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Vlang | Vlang | fn lss(s string) string {
mut r := ''
mut c := s[0..1]
mut nc := 1
for i := 1; i < s.len; i++ {
d := s[i..i+1]
if d == c {
nc++
continue
}
r += nc.str() + c
c = d
nc = 1
}
return r + nc.str() + c
}
fn main() {
mut s :=... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Doubly_Linked_Lists;
procedure Pythagore_Set is
type Triangles is array (1 .. 3) of Positive;
package Triangle_Lists is new Ada.Containers.Doubly_Linked_Lists (
Triangles);
use Triangle_Lists;
function Find_List (Upper_Bound : Positive) re... |
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.
... | #Retro | Retro | 6 [ 0; cr [ '* emit ] times ] iter |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Picat | Picat |
table(+, +, nt)
phi(X, 0, _) = X.
phi(X, A, Primes) = phi(X, A - 1, Primes) - phi(X // Primes[A], A - 1, Primes).
pi(N) = Count, N < 2 => Count = 0.
pi(N) = Count =>
M = floor(sqrt(N)),
A = pi(M),
Count = phi(N, A, math.primes(M)) + A - 1.
main =>
N = 1,
foreach (K in 0..9)
writef("10^... |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Python | Python | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a) # partial tail recursion
def legpi(n):
if n ... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Python | Python | from difflib import ndiff
def levenshtein(str1, str2):
result = ""
pos, removed = 0, 0
for x in ndiff(str1, str2):
if pos<len(str1) and str1[pos] == x[2]:
pos += 1
result += x[2]
if x[0] == "-":
removed += 1
continue
else:
if ... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Raku | Raku | for <a b c> Z <A B C> Z 1, 2, 3 -> ($x, $y, $z) {
say $x, $y, $z;
} |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Wren | Wren | var lookAndSay = Fn.new { |s|
var res = ""
var digit = s[0]
var count = 1
for (i in 1...s.count) {
if (s[i] == digit) {
count = count + 1
} else {
res = res + "%(count)%(digit)"
digit = s[i]
count = 1
}
}
return res + "%(cou... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #ALGOL_68 | ALGOL 68 | MODE XYZ = STRUCT(INT x,y,z);
OP +:= = (REF FLEX[]XYZ lhs, XYZ rhs)FLEX[]XYZ: (
[UPB lhs+1]XYZ out;
out[:UPB lhs] := lhs;
out[UPB out] := rhs;
lhs := out
);
INT n = 20;
print (([]XYZ(
FLEX[0]XYZ xyz;
FOR x TO n DO FOR y FROM x+1 TO n DO FOR z FROM y+1 TO n DO IF x*x + y*y = z*z THEN xyz +:= XYZ(x,y,z) F... |
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.
... | #REXX | REXX | /*REXX program demonstrates an outer DO loop controlling the inner DO loop with a "FOR".*/
do j=1 for 5 /*this is the same as: do j=1 to 5 */
$= /*initialize the value to a null string*/
do k=1 for j ... |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Raku | Raku | use Math::Primesieve;
my $sieve = Math::Primesieve.new;
say "10^$_\t" ~ $sieve.count: exp($_,10) for ^10;
say (now - INIT now) ~ ' elapsed seconds'; |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Sidef | Sidef | func legendre_phi(x, a) is cached {
return x if (a <= 0)
__FUNC__(x, a-1) - __FUNC__(idiv(x, a.prime), a-1)
}
func legendre_prime_count(n) is cached {
return 0 if (n < 2)
var a = __FUNC__(n.isqrt)
legendre_phi(n, a) + a - 1
}
print("e n Legendre builtin\n",
"- ... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Racket | Racket | #lang racket
(define (memoize f)
(local ([define table (make-hash)])
(lambda args
(dict-ref! table args (λ () (apply f args))))))
(define levenshtein
(memoize
(lambda (s t)
(cond
[(and (empty? s) (empty? t)) 0]
[(empty? s) (length t)]
[(empty? t) (length s)]
[else
... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Raku | Raku | sub align ( Str $σ, Str $t ) {
my @s = flat *, $σ.comb;
my @t = flat *, $t.comb;
my @A;
@A[$_][ 0]<d s t> = $_, @s[1..$_].join, '-' x $_ for ^@s;
@A[ 0][$_]<d s t> = $_, '-' x $_, @t[1..$_].join for ^@t;
for 1 ..^ @s X 1..^ @t -> (\i, \j) {
if @s[i] ne @t[j] {
@A[i][j]<d> = 1 + my $min... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Red | Red | >>blk: [["a" "b" "c"] ["A" "B" "C"] [1 2 3]]
== [["a" "b" "c"] ["A" "B" "C"] [1 2 3]]
>> repeat counter 3 [print [blk/1/:counter blk/2/:counter blk/3/:counter]]
a A 1
b B 2
c C 3 |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Yabasic | Yabasic |
dim X$(2)
i = 0 // índice de cadena de entrada
X$(i) = "1"
input "Indica cuantas repeticiones: " r
print "\nSecuencia:"
print X$(i)
for n = 1 to r-1
j = 1 - i // índice de cadena de salida
X$(j) = ""
k = 1
while k <= len(X$(i))
k0 = k + 1
while ((k0 <= len(X$(i))) and (mid$(X$(i)... |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #Yorick | Yorick | func looksay(input) {
// Special case: one digit
if(strlen(input) == 1)
return "1" + input;
// Convert string into an array of digits
digits = strchar(input)(:-1);
// Find indices where each run starts
w = where(digits(dif));
start = numberof(w) ? grow(1, w+1) : [1];
// Find leng... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #AppleScript | AppleScript | -- List comprehension by direct and unsugared use of list monad
-- pythagoreanTriples :: Int -> [(Int, Int, Int)]
on pythagoreanTriples(n)
script x
on |λ|(x)
script y
on |λ|(y)
script z
on |λ|(z)
if x * x +... |
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.
... | #Ring | Ring |
for i = 1 to 5 for x = 1 to i see "*" next see nl next
|
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Swift | Swift | import Foundation
extension Numeric where Self: Strideable {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
func eratosthenes(limit: Int) -> [Int] {
guard limit >= 3 else {
return limit < 2 ? [] : [2]
}
let ndxLimi... |
http://rosettacode.org/wiki/Legendre_prime_counting_function | Legendre prime counting function | The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle.
To calculate:
Define
φ(x, 0) = x
φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number.
then
π(n) ... | #Wren | Wren | import "/math" for Int
var limit = 1e9.sqrt.floor
var primes = Int.primeSieve(limit)
var memoPhi = {}
var phi // recursive function
phi = Fn.new { |x, a|
if (a == 0) return x
var key = Int.cantorPair(x, a)
if (memoPhi.containsKey(key)) return memoPhi[key]
var pa = primes[a-1]
return memoPhi[key]... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Ruby | Ruby | require 'lcs'
def levenshtein_align(a, b)
apos, bpos = LCS.new(a, b).backtrack2
c = ""
d = ""
x0 = y0 = -1
dx = dy = 0
apos.zip(bpos) do |x,y|
diff = x + dx - y - dy
if diff < 0
dx -= diff
c += "-" * (-diff)
elsif diff > 0
dy += diff
d += "-" * diff
end
c += a... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #REXX | REXX | /*REXX program shows how to simultaneously loop over multiple arrays.*/
x. = ' '; x.1 = "a"; x.2 = 'b'; x.3 = "c"
y. = ' '; y.1 = "A"; y.2 = 'B'; y.3 = "C"
z. = ' '; z.1 = "1"; z.2 = '2'; z.3 = "3"
do j=1 until output=''
output = x.j || y.j || ... |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #zkl | zkl | fcn lookAndSay(seed){ // numeric String --> numeric String
len,c:=[1..seed.len()-1].reduce(fcn([(len,c)]lc,index,s,sb){
if(c!=s[index]) { sb.write(len); sb.write(c); lc.clear(1,s[index]) }
else lc.clear(len+1,c);
},L(1,seed[0]), seed,sb:=Sink(String));
sb.write(len); sb.write(c);
sb.close();
} |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Arturo | Arturo | n: 20
triplets: @[
loop 1..n 'x [
loop x..n 'y [
loop y..n 'z [if (z^2) = (x^2)+(y^2) -> @[x y z]]
]
]
]
print triplets |
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.
... | #Ruby | Ruby | puts (1..5).map { |i| "*" * i } |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Rust | Rust | [dependencies]
edit-distance = "^1.0.0" |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Scala | Scala | import scala.collection.mutable
import scala.collection.parallel.ParSeq
object LevenshteinAlignment extends App {
val vlad = new Levenshtein("rosettacode", "raisethysword")
val alignment = vlad.revLevenstein()
class Levenshtein(s1: String, s2: String) {
val memoizedCosts = mutable.Map[(Int, Int), Int]()
... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Ring | Ring |
array1 = ["a", "b", "c"]
array2 = ["A", "B", "C"]
array3 = [1, 2, 3]
for n = 1 to 3
see array1[n] + array2[n] + array3[n] + nl
next
|
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #AutoHotkey | AutoHotkey |
comprehend("show", range(1, 20), "triples")
return
comprehend(doToVariable, inSet, satisfying)
{
set := %satisfying%(inSet.begin, inSet.end)
index := 1
While % set[index, 1]
{
item := set[index, 1] . ", " . set[index, 2] . ", " . set[index, 3]
%doToVariable%(item)
index += 1
}
return
}
s... |
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.
... | #Rust | Rust | fn main() {
for i in 0..5 {
for _ in 0..=i {
print!("*");
}
println!();
}
} |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Sidef | Sidef | func align(s, t) {
s.chars!.prepend!('^')
t.chars!.prepend!('^')
var A = []
{|i| A[i][0]{@|<d s t>} = (i, s.ft(1, i).join, '~' * i) } << ^s
{|i| A[0][i]{@|<d s t>} = (i, '-' * i, t.ft(1, i).join) } << ^t
for i (1 .. s.end) {
for j (1 .. t.end) {
if (s[i] != t[j]) {
A[... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Ruby | Ruby | ['a','b','c'].zip(['A','B','C'], [1,2,3]) {|i,j,k| puts "#{i}#{j}#{k}"} |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Bracmat | Bracmat |
:?py { Initialize the accumulating result list. }
& ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { This is the subject }
: ? { Here starts the pattern }
%@?x
?
%@?y
?
%@?z
( ?
& -1*!z^2+!x^2+!y^2... |
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.
... | #Salmon | Salmon | iterate (x; [0...4])
{
iterate (y; [0...x])
print("*");;
print("\n");
}; |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Tcl | Tcl | package require struct::list
proc levenshtein/align {a b} {
lassign [struct::list longestCommonSubsequence [split $a ""] [split $b ""]]\
apos bpos
set c ""
set d ""
set x0 [set y0 -1]
set dx [set dy 0]
foreach x $apos y $bpos {
if {$x+$dx < $y+$dy} {
set n [expr {($y+$dy)-($x+$dx)}]
... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Run_BASIC | Run BASIC | for i = 1 to 3
a$(i) = chr$(i+96)
b$(i) = chr$(i+64)
c(i) = i
next i
for i = 1 to 3
print a$(i);b$(i);c(i)
next |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #C | C |
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
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.
... | #SAS | SAS | data _null_;
length a $5;
do n=1 to 5;
a="*";
do i=2 to n;
a=trim(a) !! "*";
end;
put a;
end;
run;
/* Possible without the inner loop. Notice TRIM is replaced with STRIP,
otherwise there is a blank space on the left */
data _null_;
length a $5;
do n=1 to 5;
a=strip(a) !! "*";
put a;
end;
run; |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #Wren | Wren | import "/str" for Str
var levenshteinAlign = Fn.new { |a, b|
a = Str.lower(a)
b = Str.lower(b)
var costs = List.filled(a.count+1, null)
for (i in 0..a.count) costs[i] = List.filled(b.count+1, 0)
for (j in 0..b.count) costs[0][j] = j
for (i in 1..a.count) {
costs[i][0] = i
for (... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Rust | Rust | fn main() {
let a1 = ["a", "b", "c"];
let a2 = ["A", "B", "C"];
let a3 = [1, 2, 3];
for ((&x, &y), &z) in a1.iter().zip(a2.iter()).zip(a3.iter()) {
println!("{}{}{}", x, y, z);
}
} |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #C.23 | C# | using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.... |
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.
... | #Sather | Sather | class MAIN is
-- from, to, step
for!(once init:INT, once to:INT, once inc:INT):INT is
i ::= init;
loop while!( i <= to );
yield i;
i := i + inc;
end;
end;
main is
i, j :INT;
loop i := for!(1, 5, 1); -- 1.upto!(5)
loop j := for!(1, i, 1); -- 1.upto!(i)
#OUT + "*"... |
http://rosettacode.org/wiki/Levenshtein_distance/Alignment | Levenshtein distance/Alignment | The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used t... | #zkl | zkl | fcn alignment(a,b){
a,b = a.toLower(), b.toLower();
costs := (a.len()+1).pump(List(),'wrap(a){ [1..b.len()].pump(List(a)) });
foreach i,j in (a.len()+1, [1..b.len()]){
costs[i][j] = ( 1 + costs[i-1][j].min(costs[i][j-1]) )
.min(if(a[i-1] == b[j-1]) costs[i-1][j-1] else costs[i-1][j-1] + 1);
... |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Salmon | Salmon | // First, we'll define a general-purpose zip() to zip
any
// number of lists together.
function zip(...)
{
variable result;
variable list_num := 0;
iterate(arg; arguments)
{
variable elem_num := 0;
iterate (x; arg)
{
result[elem_num][list_num] := x;
... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #C.2B.2B | C++ | #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<... |
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.
... | #Scala | Scala | for (i <- 1 to 5) {
for (j <- 1 to i)
print("*")
println()
} |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Sather | Sather | class MAIN is
main is
a :ARRAY{STR} := |"a", "b", "c"|;
b :ARRAY{STR} := |"A", "B", "C"|;
c :ARRAY{STR} := |"1", "2", "3"|;
loop
#OUT + a.elt! + b.elt! + c.elt! + "\n";
end;
end;
end;
|
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Clojure | Clojure | (defn pythagorean-triples [n]
(for [x (range 1 (inc n))
y (range x (inc n))
z (range y (inc n))
:when (= (+ (* x x) (* y y)) (* z z))]
[x y z])) |
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.
... | #Scheme | Scheme | (do ((i 1 (+ i 1)))
((> i 5))
(do ((j 1 (+ j 1)))
((> j i))
(display "*"))
(newline)) |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Scala | Scala |
("abc", "ABC", "123").zipped foreach { (x, y, z) =>
println(x.toString + y + z)
}
|
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #CoffeeScript | CoffeeScript | flatten = (arr) -> arr.reduce ((memo, b) -> memo.concat b), []
pyth = (n) ->
flatten (for x in [1..n]
flatten (for y in [x..n]
for z in [y..n] when x*x + y*y is z*z
[x, y, z]
))
console.dir pyth 20 |
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.
... | #Scilab | Scilab | for i=1:5
s=""
for j=1:i
s=s+"*"
end
printf("%s\n",s)
end |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #11l | 11l | F leo_numbers(cnt, =l0 = 1, =l1 = 1, add = 1)
L 1..cnt
print(l0, end' ‘ ’)
(l0, l1) = (l1, l0 + l1 + add)
print()
print(‘Leonardo Numbers: ’, end' ‘’)
leo_numbers(25)
print(‘Fibonacci Numbers: ’, end' ‘’)
leo_numbers(25, 0, 1, 0) |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Scheme | Scheme |
(let ((a '("a" "b" "c"))
(b '("A" "B" "C"))
(c '(1 2 3)))
(for-each
(lambda (i1 i2 i3)
(display i1)
(display i2)
(display i3)
(newline))
a b c))
|
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Common_Lisp | Common Lisp | (defun pythagorean-triples (n)
(loop for x from 1 to n
append (loop for y from x to n
append (loop for z from y to n
when (= (+ (* x x) (* y y)) (* z z))
collect (list x y z))))) |
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.
... | #Seed7 | Seed7 | for I range 1 to 5 do
for J range 1 to I do
write("*");
end for;
writeln;
end for; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.