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/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Logo
|
Logo
|
to bookend_number :n
output sum product 10 first :n last :n
end
to gapful? :n
output and greaterequal? :n 100 equal? 0 modulo :n bookend_number :n
end
to gapfuls_in_range :start :size
localmake "gapfuls []
do.while [
if (gapful? :start) [
make "gapfuls (lput :start gapfuls)
]
make "start sum :start 1
] [less? (count :gapfuls) :size]
output :gapfuls
end
to report_range :start :size
print (word "|The first | :size "| gapful numbers >= | :start "|:|)
print gapfuls_in_range :start :size
(print)
end
foreach [ [1 30] [1000000 15] [1000000000 10] ] [
apply "report_range ?
]
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#LOLCODE
|
LOLCODE
|
HAI 1.2
HOW IZ I FurstDigit YR Numbr
I HAS A Digit
IM IN YR LOOP NERFIN YR Dummy WILE DIFFRINT Numbr AN 0
Digit R MOD OF Numbr AN 10
Numbr R QUOSHUNT OF Numbr AN 10
IM OUTTA YR LOOP
FOUND YR Digit
IF U SAY SO
HOW IZ I LastDigit YR Numbr
FOUND YR MOD OF Numbr AN 10
IF U SAY SO
HOW IZ I Bookend YR Numbr
FOUND YR SUM OF PRODUKT OF I IZ FurstDigit YR Numbr MKAY AN 10 AN I IZ LastDigit YR Numbr MKAY
IF U SAY SO
HOW IZ I CheckGapful YR Numbr
I HAS A Bookend ITZ I IZ Bookend YR Numbr MKAY
I HAS A BigEnuff ITZ BOTH SAEM Numbr AN BIGGR OF Numbr AN 100
FOUND YR BOTH OF BigEnuff AN BOTH SAEM 0 AN MOD OF Numbr AN Bookend
IF U SAY SO
HOW IZ I FindGapfuls YR Start AN YR HowMany
I HAS A Numbr ITZ Start
I HAS A Anser ITZ A BUKKIT
I HAS A Found ITZ 0
IM IN YR LOOP UPPIN YR Dummy WILE DIFFRINT Found AN HowMany
I IZ CheckGapful YR Numbr MKAY
O RLY?
YA RLY
Anser HAS A SRS Found ITZ Numbr
Found R SUM OF Found AN 1
OIC
Numbr R SUM OF Numbr AN 1
IM OUTTA YR LOOP
FOUND YR Anser
IF U SAY SO
HOW IZ I Report YR Start AN YR HowMany
VISIBLE "The furst " !
VISIBLE HowMany !
VISIBLE " Gapful numbrs starting with " !
VISIBLE Start !
VISIBLE ":"
I HAS A Anser ITZ I IZ FindGapfuls YR Start AN YR HowMany MKAY
IM IN YR Loop UPPIN YR Index TIL BOTH SAEM Index AN HowMany
DIFFRINT Index AN 0
O RLY?
YA RLY
VISIBLE ", " !
OIC
VISIBLE Anser'Z SRS Index !
IM OUTTA YR Loop
VISIBLE ""
VISIBLE ""
IF U SAY SO
I IZ Report YR 1 AN YR 30 MKAY
I IZ Report YR 1000000 AN YR 15 MKAY
I IZ Report YR 1000000000 AN YR 10 MKAY
KTHXBYE
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#Lambdatalk
|
Lambdatalk
|
{require lib_matrix}
{M.solve
{M.new [[1.00,0.00,0.00,0.00,0.00,0.00],
[1.00,0.63,0.39,0.25,0.16,0.10],
[1.00,1.26,1.58,1.98,2.49,3.13],
[1.00,1.88,3.55,6.70,12.62,23.80],
[1.00,2.51,6.32,15.88,39.90,100.28],
[1.00,3.14,9.87,31.01,97.41,306.02]]}
[-0.01,0.61,0.91,0.99,0.60,0.02]}
->
[-0.01,1.6027903945021094,-1.613203059905548,1.245494121371424,-0.49098971958465304,0.06576069617523143]
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Rust
|
Rust
|
fn main() {
let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0],
vec![4.0, 1.0, 6.0],
vec![7.0, 8.0, 9.0]
];
let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0],
vec![-1.0, 2.0, -1.0],
vec![0.0, -1.0, 2.0]
];
let mut ref_a = &mut a;
let rref_a = &mut ref_a;
let mut ref_b = &mut b;
let rref_b = &mut ref_b;
println!("Matrix A:\n");
print_matrix(rref_a);
println!("\nInverse of Matrix A:\n");
print_matrix(&mut matrix_inverse(rref_a));
println!("\n\nMatrix B:\n");
print_matrix(rref_b);
println!("\nInverse of Matrix B:\n");
print_matrix(&mut matrix_inverse(rref_b));
}
//Begin Matrix Inversion
fn matrix_inverse(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>>{
let len = matrix.len();
let mut aug = zero_matrix(len, len * 2);
for i in 0..len {
for j in 0.. len {
aug[i][j] = matrix[i][j];
}
aug[i][i + len] = 1.0;
}
gauss_jordan_general(&mut aug);
let mut unaug = zero_matrix(len, len);
for i in 0..len {
for j in 0..len {
unaug[i][j] = aug[i][j+len];
}
}
unaug
}
//End Matrix Inversion
//Begin Generalised Reduced Row Echelon Form
fn gauss_jordan_general(matrix: &mut Vec<Vec<f64>>) {
let mut lead = 0;
let row_count = matrix.len();
let col_count = matrix[0].len();
for r in 0..row_count {
if col_count <= lead {
break;
}
let mut i = r;
while matrix[i][lead] == 0.0 {
i = i + 1;
if row_count == i {
i = r;
lead = lead + 1;
if col_count == lead {
break;
}
}
}
let temp = matrix[i].to_owned();
matrix[i] = matrix[r].to_owned();
matrix[r] = temp.to_owned();
if matrix[r][lead] != 0.0 {
let div = matrix[r][lead];
for j in 0..col_count {
matrix[r][j] = matrix[r][j] / div;
}
}
for k in 0..row_count {
if k != r {
let mult = matrix[k][lead];
for j in 0..col_count {
matrix[k][j] = matrix[k][j] - matrix[r][j] * mult;
}
}
}
lead = lead + 1;
}
//matrix.to_owned()
}
fn zero_matrix(rows: usize, cols: usize) -> Vec<Vec<f64>> {
let mut matrix = Vec::with_capacity(cols);
for _ in 0..rows {
let mut col: Vec<f64> = Vec::with_capacity(rows);
for _ in 0..cols {
col.push(0.0);
}
matrix.push(col);
}
matrix
}
fn print_matrix(mat: &mut Vec<Vec<f64>>) {
for row in 0..mat.len(){
println!("{:?}", mat[row]);
}
}
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Sidef
|
Sidef
|
func gauss_jordan_invert (M) {
var I = M.len.of {|i|
M.len.of {|j|
i == j ? 1 : 0
}
}
var A = gather {
^M -> each {|i| take(M[i] + I[i]) }
}
rref(A).map { .last(M.len) }
}
var A = [
[-1, -2, 3, 2],
[-4, -1, 6, 2],
[ 7, -8, 9, 1],
[ 1, -2, 1, 3],
]
say gauss_jordan_invert(A).map {
.map { "%6s" % .as_rat }.join(" ")
}.join("\n")
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#PHP
|
PHP
|
<?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Haskell
|
Haskell
|
lower = ['a' .. 'z']
main = print lower
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Huginn
|
Huginn
|
import Algorithms as algo;
import Text as text;
main() {
print(
"{}\n".format(
text.character_class( text.CHARACTER_CLASS.LOWER_CASE_LETTER )
)
);
print(
"{}\n".format(
algo.materialize(
algo.map(
algo.range( integer( 'a' ), integer( 'z' ) + 1 ),
character
),
string
)
)
);
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#PDP-1_Assembly
|
PDP-1 Assembly
|
hello
/ above: title line - was punched in human readable letters on paper tape
/ below: location specifier - told assembler what address to assemble to
100/
lup, lac i ptr / load ac from address stored in pointer
cli / clear io register
lu2, rcl 6s / rotate combined ac + io reg 6 bits to the left
/ left 6 bits in ac move into right 6 bits of io reg
tyo / type out character in 6 right-most bits of io reg
sza / skip next instr if accumulator is zero
jmp lu2 / otherwise do next character in current word
idx ptr / increment pointer to next word in message
sas end / skip next instr if pointer passes the end of message
jmp lup / otherwise do next word in message
hlt / halt machine
ptr, msg / pointer to current word in message
msg, text "hello, world" / 3 6-bit fiodec chars packed into each 18-bit word
end, . / sentinel for end of message
start 100 / tells assembler where program starts
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#PicoLisp
|
PicoLisp
|
(de powers (M)
(co (intern (pack 'powers M))
(for (I 0 (inc 'I))
(yield (** I M)) ) ) )
(de filtered (N M)
(co 'filtered
(let (V (powers N) F (powers M))
(loop
(if (> V F)
(setq F (powers M))
(and (> F V) (yield V))
(setq V (powers N)) ) ) ) ) )
(do 20 (filtered 2 3))
(do 10 (println (filtered 2 3)))
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#XPL0
|
XPL0
|
char Col;
func ColNum(Start, Piece); \Return column number of Piece
int Start, Piece, I;
[for I:= Start to 7 do
if Col(I) = Piece then return I;
return -1;
];
proc Shuffle; \Randomly rearrange pieces in columns
int I, J, T;
[for I:= 8-1 downto 1 do
[J:= Ran(I); \range [0..I-1] (Sattolo cycle)
T:= Col(I); Col(I):= Col(J); Col(J):= T;
];
];
int N, B1, B2, BOK, R1, R2, K, KOK;
[for N:= 1 to 5 do
[Col:= "RNBQKBNR ";
repeat Shuffle;
B1:= ColNum(0, ^B);
B2:= ColNum(B1+1, ^B);
BOK:= ((B1 xor B2) and 1) # 0;
R1:= ColNum(0, ^R);
R2:= ColNum(R1+1, ^R);
K:= ColNum(0, ^K);
KOK:= R1<K and K<R2;
until BOK and KOK;
Text(0, Col); CrLf(0);
];
]
|
http://rosettacode.org/wiki/Generate_Chess960_starting_position
|
Generate Chess960 starting position
|
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:
as in the standard chess game, all eight white pawns must be placed on the second rank.
White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
the King must be between two rooks (with any number of other pieces between them all)
Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)
With those constraints there are 960 possible starting positions, thus the name of the variant.
Task
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
|
#zkl
|
zkl
|
const pieces="KQRrBbNN";
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){
I:=p.index;
I("B") % 2 != I("b") % 2 and // Bishop constraint.
// King constraint.
((I("r") < I("K") and I("K") < I("R")) or
(I("R") < I("K") and I("K") < I("r")))
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_);
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Clojure
|
Clojure
|
(defn compose [f g]
(fn [x]
(f (g x))))
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#CoffeeScript
|
CoffeeScript
|
compose = ( f, g ) -> ( x ) -> f g x
# Example
add2 = ( x ) -> x + 2
mul2 = ( x ) -> x * 2
mulFirst = compose add2, mul2
addFirst = compose mul2, add2
multiple = compose mul2, compose add2, mul2
console.log "add2 2 #=> #{ add2 2 }"
console.log "mul2 2 #=> #{ mul2 2 }"
console.log "mulFirst 2 #=> #{ mulFirst 2 }"
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#D
|
D
|
import std.stdio, std.math;
enum width = 1000, height = 1000; // Image dimension.
enum length = 400; // Trunk size.
enum scale = 6.0 / 10; // Branch scale relative to trunk.
void tree(in double x, in double y, in double length, in double angle) {
if (length < 1)
return;
immutable x2 = x + length * angle.cos;
immutable y2 = y + length * angle.sin;
writefln("<line x1='%f' y1='%f' x2='%f' y2='%f' " ~
"style='stroke:black;stroke-width:1'/>", x, y, x2, y2);
tree(x2, y2, length * scale, angle + PI / 5);
tree(x2, y2, length * scale, angle - PI / 5);
}
void main() {
"<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'>".writeln;
tree(width / 2.0, height, length, 3 * PI / 2);
"</svg>".writeln;
}
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#C.2B.2B
|
C++
|
#include <array>
#include <iomanip>
#include <iostream>
#include <vector>
int indexOf(const std::vector<int> &haystack, int needle) {
auto it = haystack.cbegin();
auto end = haystack.cend();
int idx = 0;
for (; it != end; it = std::next(it)) {
if (*it == needle) {
return idx;
}
idx++;
}
return -1;
}
bool getDigits(int n, int le, std::vector<int> &digits) {
while (n > 0) {
auto r = n % 10;
if (r == 0 || indexOf(digits, r) >= 0) {
return false;
}
le--;
digits[le] = r;
n /= 10;
}
return true;
}
int removeDigit(const std::vector<int> &digits, int le, int idx) {
static std::array<int, 5> pows = { 1, 10, 100, 1000, 10000 };
int sum = 0;
auto pow = pows[le - 2];
for (int i = 0; i < le; i++) {
if (i == idx) continue;
sum += digits[i] * pow;
pow /= 10;
}
return sum;
}
int main() {
std::vector<std::pair<int, int>> lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} };
std::array<int, 5> count;
std::array<std::array<int, 10>, 5> omitted;
std::fill(count.begin(), count.end(), 0);
std::for_each(omitted.begin(), omitted.end(),
[](auto &a) {
std::fill(a.begin(), a.end(), 0);
}
);
for (size_t i = 0; i < lims.size(); i++) {
std::vector<int> nDigits(i + 2);
std::vector<int> dDigits(i + 2);
for (int n = lims[i].first; n <= lims[i].second; n++) {
std::fill(nDigits.begin(), nDigits.end(), 0);
bool nOk = getDigits(n, i + 2, nDigits);
if (!nOk) {
continue;
}
for (int d = n + 1; d <= lims[i].second + 1; d++) {
std::fill(dDigits.begin(), dDigits.end(), 0);
bool dOk = getDigits(d, i + 2, dDigits);
if (!dOk) {
continue;
}
for (size_t nix = 0; nix < nDigits.size(); nix++) {
auto digit = nDigits[nix];
auto dix = indexOf(dDigits, digit);
if (dix >= 0) {
auto rn = removeDigit(nDigits, i + 2, nix);
auto rd = removeDigit(dDigits, i + 2, dix);
if ((double)n / d == (double)rn / rd) {
count[i]++;
omitted[i][digit]++;
if (count[i] <= 12) {
std::cout << n << '/' << d << " = " << rn << '/' << rd << " by omitting " << digit << "'s\n";
}
}
}
}
}
}
std::cout << '\n';
}
for (int i = 2; i <= 5; i++) {
std::cout << "There are " << count[i - 2] << ' ' << i << "-digit fractions of which:\n";
for (int j = 1; j <= 9; j++) {
if (omitted[i - 2][j] == 0) {
continue;
}
std::cout << std::setw(6) << omitted[i - 2][j] << " have " << j << "'s omitted\n";
}
std::cout << '\n';
}
return 0;
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Bracmat
|
Bracmat
|
(fractran=
np n fs A Z fi P p N L M
. !arg:(?N,?n,?fs) {Number of iterations, start n, fractions}
& :?P:?L {Initialise accumulators.}
& whl
' ( -1+!N:>0:?N {Stop when counted down to zero.}
& !n !L:?L {Prepend all numbers to result list.}
& (2\L!n:#?p&!P !p:?P|) {If log2(n) is rational, append it to list of primes.}
& !fs:? (/?fi&!n*!fi:~/:?n) ? {This line does the following (See task description):
"for the first fraction, fi, in the list for which
nfi is an integer, replace n by nfi ;"}
)
& :?M
& whl'(!L:%?n ?L&!n !M:?M) {Invert list of numbers. (append to long list is
very expensive. Better to prepend and finally invert.}
& (!M,!P) {Return the two lists}
);
( clk$:?t0
& fractran$(430000, 2, 17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1)
: (?numbers,?primes)
& lst$(numbers,"numbers.lst",NEW)
& put$("
FRACTRAN found these primes:"
!primes
"\nThe list of numbers is saved in numbers.txt
The biggest number in the list is"
( 0:?max
& !numbers:? (>%@!max:?max&~) ?
| !max
)
str$("\ntime: " flt$(clk$+-1*!t0,4) " sec\n")
, "FRACTRAN.OUT",NEW)
);
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#Wren
|
Wren
|
/* ftp.wren */
var FTPLIB_CONNMODE = 1
var FTPLIB_PASSIVE = 1
var FTPLIB_ASCII = 65 // 'A'
foreign class Ftp {
foreign static init()
construct connect(host) {}
foreign login(user, pass)
foreign options(opt, val)
foreign chdir(path)
foreign dir(outputFile, path)
foreign get(output, path, mode)
foreign quit()
}
Ftp.init()
var ftp = Ftp.connect("ftp.easynet.fr")
ftp.login("anonymous", "[email protected]")
ftp.options(FTPLIB_CONNMODE, FTPLIB_PASSIVE)
ftp.chdir("/debian/")
ftp.dir("", ".")
ftp.get("ftp.README", "README", FTPLIB_ASCII)
ftp.quit()
|
http://rosettacode.org/wiki/FTP
|
FTP
|
Task
Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
|
#zkl
|
zkl
|
zkl: var cURL=Import("zklCurl")
zkl: var d=cURL().get("ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/")
L(Data(2,567),1630,23) // downloaded listing, 1630 bytes of header, 23 bytes of trailer
zkl: d[0][1630,-23].text
-rw-rw-r-- 1 109 space-station 2327118 May 9 2005 09sept_spacepropulsion.mp3
...
-rw-rw-r-- 1 109 space-station 1134654 May 9 2005 When Space Makes you Dizzy.mp3
zkl: d=cURL().get("ftp.hq.nasa.gov/pub/issoutreach/Living in Space Stories (MP3 Files)/When Space Makes you Dizzy.mp3")
L(Data(1,136,358),1681,23)
zkl: File("foo.mp3","w").write(d[0][1681,-23])
1134654 // note that this matches size in listing
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ALGOL_68
|
ALGOL 68
|
PROC multiply = ( LONG REAL a, b ) LONG REAL:
(
a * b
)
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue // avoid expensive strconv operation where possible
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000) // examine first twenty million numbers say
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#F.23
|
F#
|
open System
let gamma z =
let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5]
let rec sumCoefficients acc i coefficients =
match coefficients with
| [] -> acc
| h::t -> sumCoefficients (acc + (h/i)) (i+1.0) t
let gamma = 5.0
let x = z - 1.0
Math.Pow(x + gamma + 0.5, x + 0.5) * Math.Exp( -(x + gamma + 0.5) ) * Math.Sqrt( 2.0 * Math.PI ) * sumCoefficients 1.000000000190015 (x + 1.0) lanczosCoefficients
seq { for i in 1 .. 20 do yield ((double)i/10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine("{0} : {1}", v, gamma v ) )
seq { for i in 1 .. 10 do yield ((double)i*10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine("{0} : {1}", v, gamma v ) )
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#Phix
|
Phix
|
without js -- clear_screen(), text_color(), position(), sleep(), get_key()...
constant balls = 80
clear_screen()
sequence screen = repeat(repeat(' ',23),12)
& repeat(join(repeat(':',12)),12)
& {repeat('.',23)},
Pxy = repeat({12,1},balls)
for peg=1 to 10 do
screen[peg+2][13-peg..11+peg] = join(repeat('.',peg))
end for
puts(1,join(screen,"\n"))
text_color(BRIGHT_RED)
bool moved = true
integer top = ' ' -- (new drop every other iteration)
while moved or top!=' ' do
moved = false
for i=1 to balls do
integer {Px,Py} = Pxy[i]
if Py!=1 or top=' ' then
integer Dx = 0, Dy = 0
if screen[Py+1,Px]=' ' then -- can vertical?
Dy = 1
else
Dx = {-1,+1}[rand(2)] -- try l;r or r;l
if screen[Py+1,Px+Dx]!=' ' then Dx = -Dx end if
if screen[Py+1,Px+Dx]==' ' then
Dy = 1
end if
end if
if Dy then
position(Py,Px) puts(1," ") screen[Py,Px] = ' '
Px += Dx
Py += Dy
position(Py,Px) puts(1,"o") screen[Py,Px] = 'o'
Pxy[i] = {Px,Py}
moved = true
if Py=2 then top = 'o' end if
end if
end if
end for
position(26,1)
sleep(0.2)
if get_key()!=-1 then exit end if
top = screen[2][12]
end while
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Lua
|
Lua
|
function generateGaps(start, count)
local counter = 0
local i = start
print(string.format("First %d Gapful numbers >= %d :", count, start))
while counter < count do
local str = tostring(i)
local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10)
if i % denom == 0 then
print(string.format("%3d : %d", counter + 1, i))
counter = counter + 1
end
i = i + 1
end
end
generateGaps(100, 30)
print()
generateGaps(1000000, 15)
print()
generateGaps(1000000000, 15)
print()
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#Lobster
|
Lobster
|
import std
// test case from Go version at http://rosettacode.org/wiki/Gaussian_elimination
//
let ta = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00],
[1.00, 0.63, 0.39, 0.25, 0.16, 0.10],
[1.00, 1.26, 1.58, 1.98, 2.49, 3.13],
[1.00, 1.88, 3.55, 6.70, 12.62, 23.80],
[1.00, 2.51, 6.32, 15.88, 39.90, 100.28],
[1.00, 3.14, 9.87, 31.01, 97.41, 306.02]]
let tb = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]
let tx = [-0.01, 1.602790394502114, -1.6132030599055613,
1.2454941213714368, -0.4909897195846576, 0.065760696175232]
// result from above test case turns out to be correct to this tolerance.
let ε = 1.0e-14
def GaussPartial(a0, b0) -> [float], string:
// make augmented matrix
let m = length(b0)
let a = map(m): []
for(a0) ai, i:
//let ai = a0[i]
a[i] = map(m+1) j: if j < m: ai[j] else: b0[i]
// WP algorithm from Gaussian elimination page produces row-eschelon form
var i = 0
var j = 0
for(a0) ak, k:
// Find pivot for column k:
var iMax = 0
var kmax = -1.0
i = k
while i < m:
let row = a[i]
// compute scale factor s = max abs in row
var s = -1.0
j = k
while j < m:
s = max(s, abs(row[j]))
j += 1
// scale the abs used to pick the pivot
let kabs = abs(row[k]) / s
if kabs > kmax:
iMax = i
kmax = kabs
i += 1
if a[iMax][k] == 0:
return [], "singular"
// swap rows(k, i_max)
let row = a[k]
a[k] = a[iMax]
a[iMax] = row
// Do for all rows below pivot:
i = k + 1
while i < m:
// Do for all remaining elements in current row:
j = k + 1
while j <= m:
a[i][j] -= a[k][j] * (a[i][k] / a[k][k])
j += 1
// Fill lower triangular matrix with zeros:
a[i][k] = 0
i += 1
// end of WP algorithm; now back substitute to get result
let x = map(m): 0.0
i = m - 1
while i >= 0:
x[i] = a[i][m]
j = i + 1
while j < m:
x[i] -= a[i][j] * x[j]
j += 1
x[i] /= a[i][i]
i -= 1
return x, ""
def test():
let x, err = GaussPartial(ta, tb)
if err != "":
print("Error: " + err)
return
print(x)
for(x) xi, i:
if abs(tx[i]-xi) > ε:
print("out of tolerance, expected: " + tx[i] + " got: " + xi)
test()
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#VBA
|
VBA
|
Private Function inverse(mat As Variant) As Variant
Dim len_ As Integer: len_ = UBound(mat)
Dim tmp() As Variant
ReDim tmp(2 * len_ + 1)
Dim aug As Variant
ReDim aug(len_)
For i = 0 To len_
If UBound(mat(i)) <> len_ Then Debug.Print 9 / 0 '-- "Not a square matrix"
aug(i) = tmp
For j = 0 To len_
aug(i)(j) = mat(i)(j)
Next j
'-- augment by identity matrix to right
aug(i)(i + len_ + 1) = 1
Next i
aug = ToReducedRowEchelonForm(aug)
Dim inv As Variant
inv = mat
'-- remove identity matrix to left
For i = 0 To len_
For j = len_ + 1 To 2 * len_ + 1
inv(i)(j - len_ - 1) = aug(i)(j)
Next j
Next i
inverse = inv
End Function
Public Sub main()
Dim test As Variant
test = inverse(Array( _
Array(2, -1, 0), _
Array(-1, 2, -1), _
Array(0, -1, 2)))
For i = LBound(test) To UBound(test)
For j = LBound(test(0)) To UBound(test(0))
Debug.Print test(i)(j),
Next j
Debug.Print
Next i
End Sub
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Picat
|
Picat
|
interactive =>
print("> "),
MaxNum = read_int(),
Map = new_map(),
print("> "),
while (Line = read_line(), Line != "")
[N,V] = split(Line),
Map.put(N.to_int,V),
print("> ")
end,
general_fizzbuzz(MaxNum,Map.to_list.sort),
nl.
general_fizzbuzz(N,L) =>
FB = [I.to_string : I in 1..N],
foreach(I in 1..N)
Vs = [V : K=V in L, I mod K == 0].join(''),
if Vs != "" then
FB[I] := Vs
end
end,
println([F : F in FB].join(" ")).
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#PicoLisp
|
PicoLisp
|
(de general (N Lst)
(for A N
(prinl
(or
(extract
'((L)
(and (=0 (% A (car L))) (cdr L)) )
Lst )
A ) ) ) )
(general 20 '((3 . Fizz) (5 . Buzz) (7 . Baxx)))
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
&lcase
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#J
|
J
|
thru=: <. + i.@(+*)@-~
thru&.(a.&i.)/'az'
abcdefghijklmnopqrstuvwxyz
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#PDP-11_Assembly
|
PDP-11 Assembly
|
.globl start
.text
start:
mov $1,r0 / r0=stream, STDOUT=$1
sys 4; outtext; outlen / sys 4 is write
sys 1 / sys 1 is exit
rts pc / in case exit returns
.data
outtext: <Hello world!\n>
outlen = . - outtext
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#PL.2FI
|
PL/I
|
Generate: procedure options (main); /* 27 October 2013 */
declare j fixed binary;
declare r fixed binary;
/* Ignore the first 20 values */
do j = 1 to 20;
/* put edit (filter() ) (f(6)); */
r = filter ();
end;
put skip;
do j = 1 to 10;
put edit (filter() ) (f(6));
end;
/* filters out cubes from the result of the square generator. */
filter: procedure returns (fixed binary);
declare n fixed binary static initial (-0);
declare (i, j, m) fixed binary;
do while ('1'b);
m = squares();
r = 0;
do j = 1 to m;
if m = cubes() then go to ignore;
end;
return (m);
ignore:
end;
end filter;
squares: procedure returns (fixed binary);
declare i fixed binary static initial (-0);
i = i + 1;
return (i**2);
end squares;
cubes: procedure returns (fixed binary);
r = r + 1;
return (r**3);
end cubes;
end Generate;
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Common_Lisp
|
Common Lisp
|
(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Crystal
|
Crystal
|
require "math"
def compose(f : Proc(T, _), g : Proc(_, _)) forall T
return ->(x : T) { f.call(g.call(x)) }
end
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#EasyLang
|
EasyLang
|
func tree x y deg n . .
if n > 0
linewidth n * 0.4
move x y
x += cos deg * n * 1.3 * (randomf + 0.5)
y += sin deg * n * 1.3 * (randomf + 0.5)
line x y
call tree x y deg - 20 n - 1
call tree x y deg + 20 n - 1
.
.
timer 0
on timer
clear
call tree 50 90 -90 10
timer 1
.
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#F.23
|
F#
|
let (cos, sin, pi) = System.Math.Cos, System.Math.Sin, System.Math.PI
let (width, height) = 1000., 1000. // image dimension
let scale = 6./10. // branch scale relative to trunk
let length = 400. // trunk size
let rec tree x y length angle =
if length >= 1. then
let (x2, y2) = x + length * (cos angle), y + length * (sin angle)
printfn "<line x1='%f' y1='%f' x2='%f' y2='%f' style='stroke:rgb(0,0,0);stroke-width:1'/>"
x y x2 y2
tree x2 y2 (length*scale) (angle + pi/5.)
tree x2 y2 (length*scale) (angle - pi/5.)
printfn "<?xml version='1.0' encoding='utf-8' standalone='no'?>
<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
<svg width='100%%' height='100%%' version='1.1'
xmlns='http://www.w3.org/2000/svg'>"
tree (width/2.) height length (3.*pi/2.)
printfn "</svg>"
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#D
|
D
|
import std.range;
import std.stdio;
int indexOf(Range, Element)(Range haystack, scope Element needle)
if (isInputRange!Range) {
int idx;
foreach (straw; haystack) {
if (straw == needle) {
return idx;
}
idx++;
}
return -1;
}
bool getDigits(int n, int le, int[] digits) {
while (n > 0) {
auto r = n % 10;
if (r == 0 || indexOf(digits, r) >= 0) {
return false;
}
le--;
digits[le] = r;
n /= 10;
}
return true;
}
int removeDigit(int[] digits, int le, int idx) {
enum pows = [ 1, 10, 100, 1_000, 10_000 ];
int sum = 0;
auto pow = pows[le - 2];
for (int i = 0; i < le; i++) {
if (i == idx) continue;
sum += digits[i] * pow;
pow /= 10;
}
return sum;
}
void main() {
auto lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ];
int[5] count;
int[10][5] omitted;
for (int i = 0; i < lims.length; i++) {
auto nDigits = new int[i + 2];
auto dDigits = new int[i + 2];
for (int n = lims[i][0]; n <= lims[i][1]; n++) {
nDigits[] = 0;
bool nOk = getDigits(n, i + 2, nDigits);
if (!nOk) {
continue;
}
for (int d = n + 1; d <= lims[i][1] + 1; d++) {
dDigits[] = 0;
bool dOk = getDigits(d, i + 2, dDigits);
if (!dOk) {
continue;
}
for (int nix = 0; nix < nDigits.length; nix++) {
auto digit = nDigits[nix];
auto dix = indexOf(dDigits, digit);
if (dix >= 0) {
auto rn = removeDigit(nDigits, i + 2, nix);
auto rd = removeDigit(dDigits, i + 2, dix);
if (cast(double)n / d == cast(double)rn / rd) {
count[i]++;
omitted[i][digit]++;
if (count[i] <= 12) {
writefln("%d/%d = %d/%d by omitting %d's", n, d, rn, rd, digit);
}
}
}
}
}
}
writeln;
}
for (int i = 2; i <= 5; i++) {
writefln("There are %d %d-digit fractions of which:", count[i - 2], i);
for (int j = 1; j <= 9; j++) {
if (omitted[i - 2][j] == 0) {
continue;
}
writefln("%6s have %d's omitted", omitted[i - 2][j], j);
}
writeln;
}
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef struct frac_s *frac;
struct frac_s {
int n, d;
frac next;
};
frac parse(char *s)
{
int offset = 0;
struct frac_s h = {0}, *p = &h;
while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) {
s += offset;
p = p->next = malloc(sizeof *p);
*p = h;
p->next = 0;
}
return h.next;
}
int run(int v, char *s)
{
frac n, p = parse(s);
mpz_t val;
mpz_init_set_ui(val, v);
loop: n = p;
if (mpz_popcount(val) == 1)
gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val);
else
gmp_printf(" %Zd", val);
for (n = p; n; n = n->next) {
// assuming the fractions are not reducible
if (!mpz_divisible_ui_p(val, n->d)) continue;
mpz_divexact_ui(val, val, n->d);
mpz_mul_ui(val, val, n->n);
goto loop;
}
gmp_printf("\nhalt: %Zd has no divisors\n", val);
mpz_clear(val);
while (p) {
n = p->next;
free(p);
p = n;
}
return 0;
}
int main(void)
{
run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 "
"77/19 1/17 11/13 13/11 15/14 15/2 55/1");
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ALGOL_W
|
ALGOL W
|
long real procedure multiply( long real value a, b );
begin
a * b
end
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Go
|
Go
|
package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue // avoid expensive strconv operation where possible
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000) // examine first twenty million numbers say
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Factor
|
Factor
|
! built in
USING: picomath prettyprint ;
0.1 gamma . ! 9.513507698668723
2.0 gamma . ! 1.0
10. gamma . ! 362880.0
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#PicoLisp
|
PicoLisp
|
(de galtonBox (Pins Height)
(let (Bins (need (inc (* 2 Pins)) 0) X 0 Y 0)
(until (= Height (apply max Bins))
(call 'clear)
(cond
((=0 Y) (setq X (inc Pins) Y 1))
((> (inc 'Y) Pins)
(inc (nth Bins X))
(zero Y) ) )
((if (rand T) inc dec) 'X)
(for Row Pins
(for Col (+ Pins Row 1)
(let D (dec (- Col (- Pins Row)))
(prin
(cond
((and (= X Col) (= Y Row)) "o")
((and (gt0 D) (bit? 1 D)) ".")
(T " ") ) ) ) )
(prinl) )
(prinl)
(for H (range Height 1)
(for B Bins
(prin (if (>= B H) "o" " ")) )
(prinl) )
(wait 200) ) ) )
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#Prolog
|
Prolog
|
:- dynamic tubes/1.
:- dynamic balls/2.
:- dynamic stop/1.
% number of rows of pins (0 -> 9)
row(9).
galton_box :-
retractall(tubes(_)),
retractall(balls(_,_)),
retractall(stop(_)),
assert(stop(@off)),
new(D, window('Galton Box')),
send(D, size, size(520,700)),
display_pins(D),
new(ChTubes, chain),
assert(tubes(ChTubes)),
display_tubes(D, ChTubes),
new(Balls, chain),
new(B, ball(D)),
send(Balls, append, B),
assert(balls(Balls, D)),
send(D, done_message, and(message(ChTubes, clear),
message(ChTubes, free),
message(Balls, for_all, message(@arg1, free)),
message(Balls, clear),
message(Balls, free),
message(@receiver, destroy))),
send(D, open).
% class pin, balls travel between pins
:- pce_begin_class(pin, circle, "pin").
initialise(P, Pos) :->
send(P, send_super, initialise, 18),
send(P, fill_pattern, new(_, colour(@default, 0, 0, 0))),
get(Pos, x, X),
get(Pos, y, Y),
send(P, geometry, x := X, y := Y).
:- pce_end_class.
% class tube, balls fall in them
:- pce_begin_class(tube, path, "tube where balls fall").
variable(indice, any, both, "index of the tube in the list").
variable(balls, any, both, "number of balls inside").
initialise(P, Ind, D) :->
row(Row),
send(P, send_super, initialise, kind := poly),
send(P, slot, balls, 0),
send(P, slot, indice, Ind),
X0 is 228 - Row * 20 + Ind * 40,
X1 is X0 + 20,
Y1 is 600, Y0 is 350,
send_list(P, append, [point(X0, Y0), point(X0, Y1),
point(X1,Y1), point(X1,Y0)]),
send(D, display, P).
% animation stop when a tube is full
add_ball(P) :->
get(P, slot, balls, B),
B1 is B+1,
send(P, slot, balls, B1),
( B1 = 12
-> retract(stop(_)), assert(stop(@on))
; true).
:- pce_end_class.
% class ball
:- pce_begin_class(ball, circle, "ball").
variable(angle, any, both, "angle of the ball with the pin").
variable(dir, any, both, "left / right").
variable(pin, point, both, "pin under the ball when it falls").
variable(position, point, both, "position of the ball").
variable(max_descent, any, both, "max descent").
variable(state, any, both, "in_pins / in_tube").
variable(window, any, both, "window to display").
variable(mytimer, timer, both, "timer of the animation").
initialise(P, W) :->
send(P, send_super, initialise, 18),
send(P, pen, 0),
send(P, state, in_pins),
send(P, fill_pattern, new(_, colour(@default, 65535, 0, 0))),
Ang is 3 * pi / 2,
send(P, slot, angle, Ang),
send(P, slot, window, W),
send(P, geometry, x := 250, y := 30),
send(P, pin, point(250, 50)),
send(P, choose_dir),
send(P, mytimer, new(_, timer(0.005, message(P, move_ball)))),
send(W, display, P),
send(P?mytimer, start).
% method called when the object is destroyed
% first the timer is stopped
% then all the resources are freed
unlink(P) :->
send(P?mytimer, stop),
send(P, send_super, unlink).
choose_dir(P) :->
I is random(2),
( I = 1 -> Dir = left; Dir = right),
send(P, dir, Dir).
move_ball(P) :->
get(P, state, State),
( State = in_pins
-> send(P, move_ball_in_pins)
; send(P, move_ball_in_tube)).
move_ball_in_pins(P) :->
get(P, slot, angle, Ang),
get(P, slot, pin, Pin),
get(P, slot, dir, Dir),
( Dir = left -> Ang1 is Ang-0.15 ; Ang1 is Ang + 0.15),
get(Pin, x, PX),
get(Pin, y, PY),
X is 21 * cos(Ang1) + PX,
Y is 21 * sin(Ang1) + PY,
send(P, geometry, x := X, y := Y),
send(P?window, display, P),
( abs(Ang1 - pi) < 0.1
-> PX1 is PX - 20,
send(P, next_move, PX1, PY)
; abs(Ang1 - 2 * pi) < 0.1
-> PX1 is PX + 20,
send(P, next_move, PX1, PY)
; send(P, slot, angle, Ang1)).
next_move(P, PX, PY) :->
row(Row),
Ang2 is 3 * pi / 2,
PY1 is PY + 30,
( PY1 =:= (Row + 1) * 30 + 50
-> send(P, slot, state, in_tube),
NumTube is round((PX - 228 + Row * 20) / 40),
tubes(ChTubes),
get(ChTubes, find,
message(@prolog, same_value,@arg1?indice, NumTube),
Tube),
send(Tube, add_ball),
get(Tube, slot, balls, Balls),
Max_descent is 600 - Balls * 20,
send(P, slot, max_descent, Max_descent),
send(P, slot, position, point(PX, PY))
; send(P, choose_dir),
send(P, slot, angle, Ang2),
send(P, slot, pin, point(PX, PY1))).
move_ball_in_tube(P) :->
get(P, slot, position, Descente),
get(Descente, x, PX1),
get(Descente, y, PY),
PY1 is PY+4,
send(P, geometry, x := PX1, y := PY1),
get(P, slot, max_descent, Max_descent),
( Max_descent =< PY1
-> send(P?mytimer, stop),
( stop(@off) -> send(@prolog, next_ball); true)
; send(P, slot, position, point(PX1, PY1))),
send(P?window, display, P).
:- pce_end_class.
next_ball :-
retract(balls(Balls, D)),
new(B, ball(D)),
send(Balls, append, B),
assert(balls(Balls, D)).
% test to find the appropriate tube
same_value(V, V).
display_pins(D) :-
row(Row),
forall(between(0, Row, I),
( Start is 250 - I * 20,
Y is I * 30 + 50,
forall(between(0, I, J),
( X is Start + J * 40,
new(P, pin(point(X,Y))),
send(D, display, P))))).
display_tubes(D, Ch) :-
row(Row),
Row1 is Row+1,
forall(between(0, Row1, I),
( new(T, tube(I, D)),
send(Ch, append, T),
send(D, display, T))).
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
ClearAll[GapFulQ]
GapFulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]]
i = 100;
res = {};
While[Length[res] < 30,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^6;
res = {};
While[Length[res] < 15,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^9;
res = {};
While[Length[res] < 10,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#min
|
min
|
(() 0 shorten) :new
(((10 mod) (10 div)) cleave) :moddiv
((dup 0 ==) (pop new) 'moddiv 'cons linrec) :digits
(digits ((last 10 *) (first +)) cleave) :flnum
(mod 0 ==) :divisor?
(dup flnum divisor?) :gapful?
(
:target :n 0 :count
"$1 gapful numbers starting at $2:" (target n) => % puts!
(count target <) (
(n gapful?) (
count succ @count
n print! " " print!
) when
n succ @n
) while
newline
) :show-gapfuls
100 30 show-gapfuls newline
1000000 15 show-gapfuls newline
1000000000 10 show-gapfuls
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#M2000_Interpreter
|
M2000 Interpreter
|
module checkit {
Dim Base 1, a(6, 6), b(6)
a(1,1)= 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02
\\ remove \\ to feed next array
\\ a(1,1)=1.1,0.12,0.13,0.12,0.14,-0.12,1.21,0.63,0.39,0.25,0.16,0.1,1.03,1.26,1.58,1.98,2.49,3.13, 1.06,1.88,3.55,6.7,12.62,23.8, 1.12,2.51,6.32,15.88,39.9,100.28,1.16,3.14,9.87,31.01,97.41,306.02
for i=1 to 6 : for j=1 to 6 : a(i,j)=val(a(i,j)->Decimal) :Next j:Next i
b(1)=-0.01, 0.61, 0.91, 0.99, 0.60, 0.02
for i=1 to 6 : b(i)=val(b(i)->Decimal) :Next i
function GaussJordan(a(), b()) {
cols=dimension(a(),1)
rows=dimension(a(),2)
\\ make augmented matrix
Dim Base 1, a(cols, rows)
\\ feed array with rationals
Dim Base 1, b(Len(b()))
for diag=1 to rows {
max_row=diag
max_val=abs(a(diag, diag))
if diag<rows Then {
for ro=diag+1 to rows {
d=abs(a(ro, diag))
if d>max_val then max_row=ro : max_val=d
}
}
\\ SwapRows diag, max_row
if diag<>max_row then {
for i=1 to cols {
swap a(diag, i), a(max_row, i)
}
swap b(diag), b(max_row)
}
invd= a(diag, diag)
if diag<=cols then {
for col=diag to cols {
a(diag, col)/=invd
}
}
b(diag)/=invd
for ro=1 to rows {
d1=a(ro,diag)
d2=d1*b(diag)
if ro<>diag Then {
for col=diag to cols {a(ro, col)-=d1*a(diag, col)}
b(ro)-=d2
}
}
}
=b()
}
Function ArrayLines$(a(), leftmargin=6, maxwidth=8,decimals$="") {
\\ defualt no set decimals, can show any number
ex$={
}
const way$=", {0:"+decimals$+":-"+str$(maxwidth,"")+"}"
if dimension(a())=1 then {
m=each(a())
while m {ex$+=format$(way$,array(m))}
Insert 3, 2 ex$=string$(" ", leftmargin)
=ex$ : Break
}
for i=1 to dimension(a(),1) {
ex1$=""
for j=1 to dimension(a(),2 ) {
ex1$+=format$(way$,a(i,j))
}
Insert 1,2 ex1$=string$(" ", leftmargin)
ex$+=ex1$+{
}
}
=ex$
}
mm=GaussJordan(a(), b())
c=each(mm)
while c {
print array(c)
}
\\ check accuracy
link mm to r()
\\ prepare output document
Document out$={Algorithm using decimals
}+"Matrix A:"+ArrayLines$(a(),,,"2")+{
}+"Vector B:"+ArrayLines$(b(),,,"2")+{
}+"Solution: "+{
}
acc=25
for i=1 to dimension(a(),1)
sum=a(1,1)-a(1,1)
For j=1 to dimension(a(),2)
sum+=r(j)*a(i,j)
next j
p$=format$("Coef. {0::-2}, rounding to {1} decimal, compare {2:-5}, solution: {3}", i, acc, round(sum-b(i),acc)=0@, r(i) )
Print p$
Out$=p$+{
}
next i
Report out$
clipboard out$
}
checkit
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#VBScript
|
VBScript
|
' Gauss-Jordan matrix inversion - VBScript - 22/01/2021
Option Explicit
Function rref(m)
Dim r, c, i, n, div, wrk
n=UBound(m)
For r = 1 To n 'row
div = m(r,r)
If div <> 0 Then
For c = 1 To n*2 'col
m(r,c) = m(r,c) / div
Next 'c
Else
WScript.Echo "inversion impossible!"
WScript.Quit
End If
For i = 1 To n 'row
If i <> r Then
wrk = m(i,r)
For c = 1 To n*2
m(i,c) = m(i,c) - wrk * m(r,c)
Next' c
End If
Next 'i
Next 'r
rref = m
End Function 'rref
Function inverse(mat)
Dim i, j, aug, inv, n
n = UBound(mat)
ReDim inv(n,n), aug(n,2*n)
For i = 1 To n
For j = 1 To n
aug(i,j) = mat(i,j)
Next 'j
aug(i,i+n) = 1
Next 'i
aug = rref(aug)
For i = 1 To n
For j = n+1 To 2*n
inv(i,j-n) = aug(i,j)
Next 'j
Next 'i
inverse = inv
End Function 'inverse
Sub wload(m)
Dim i, j, k
k = -1
For i = 1 To n
For j = 1 To n
k = k + 1
m(i,j) = w(k)
Next 'j
Next 'i
End Sub 'wload
Sub show(c, m, t)
Dim i, j, buf
buf = "Matrix " & c &"=" & vbCrlf & vbCrlf
For i = 1 To n
For j = 1 To n
If t="fixed" Then
buf = buf & FormatNumber(m(i,j),6,,,0) & " "
Else
buf = buf & m(i,j) & " "
End If
Next 'j
buf=buf & vbCrlf
Next 'i
WScript.Echo buf
End Sub 'show
Dim n, a, b, c, w
w = Array( _
2, 1, 1, 4, _
0, -1, 0, -1, _
1, 0, -2, 4, _
4, 1, 2, 2)
n=Sqr(UBound(w)+1)
ReDim a(n,n), b(n,n), c(n,n)
wload a
show "a", a, "simple"
b = inverse(a)
show "b", b, "fixed"
c = inverse(b)
show "c", c, "fixed"
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#PowerShell
|
PowerShell
|
$limit = 20
$data = @("3 Fizz","5 Buzz","7 Baxx")
#An array with whitespace as the delimiter
#Between the factor and the word
for ($i = 1;$i -le $limit;$i++){
$outP = ""
foreach ($x in $data){
$data_split = $x -split " " #Split the "<factor> <word>"
if (($i % $data_split[0]) -eq 0){
$outP += $data_split[1] #Append the <word> to outP
}
}
if(!$outP){ #Is outP equal to NUL?
Write-HoSt $i
} else {
Write-HoSt $outP
}
}
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Java
|
Java
|
public class LowerAscii {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(26);
for (char ch = 'a'; ch <= 'z'; ch++)
sb.append(ch);
System.out.printf("lower ascii: %s, length: %s", sb, sb.length());
}
}
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#JavaScript
|
JavaScript
|
(function (cFrom, cTo) {
function cRange(cFrom, cTo) {
var iStart = cFrom.charCodeAt(0);
return Array.apply(
null, Array(cTo.charCodeAt(0) - iStart + 1)
).map(function (_, i) {
return String.fromCharCode(iStart + i);
});
}
return cRange(cFrom, cTo);
})('a', 'z');
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#PepsiScript
|
PepsiScript
|
#include default-libraries
#author Childishbeat
class Hello world/Text:
function Hello world/Text:
print "Hello world!"
end
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Python
|
Python
|
from itertools import islice, count
def powers(m):
for n in count():
yield n ** m
def filtered(s1, s2):
v, f = next(s1), next(s2)
while True:
if v > f:
f = next(s2)
continue
elif v < f:
yield v
v = next(s1)
squares, cubes = powers(2), powers(3)
f = filtered(squares, cubes)
print(list(islice(f, 20, 30)))
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#D
|
D
|
import std.stdio;
T delegate(S) compose(T, U, S)(in T delegate(U) f,
in U delegate(S) g) {
return s => f(g(s));
}
void main() {
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10));
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10));
}
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Delphi
|
Delphi
|
program AnonCompose;
{$APPTYPE CONSOLE}
type
TFunc = reference to function(Value: Integer): Integer;
// Alternative: TFunc = TFunc<Integer,Integer>;
function Compose(F, G: TFunc): TFunc;
begin
Result:= function(Value: Integer): Integer
begin
Result:= F(G(Value));
end
end;
var
Func1, Func2, Func3: TFunc;
begin
Func1:=
function(Value: Integer): Integer
begin
Result:= Value * 2;
end;
Func2:=
function(Value: Integer): Integer
begin
Result:= Value * 3;
end;
Func3:= Compose(Func1, Func2);
Writeln(Func3(6)); // 36 = 6 * 3 * 2
Readln;
end.
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Fantom
|
Fantom
|
using fwt
using gfx
class FractalCanvas : Canvas
{
new make () : super() {}
Void drawTree (Graphics g, Int x1, Int y1, Int angle, Int depth)
{
if (depth == 0) return
Int x2 := x1 + (angle.toFloat.toRadians.cos * depth * 10.0).toInt;
Int y2 := y1 + (angle.toFloat.toRadians.sin * depth * 10.0).toInt;
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, angle - 20, depth - 1);
drawTree(g, x2, y2, angle + 20, depth - 1);
}
override Void onPaint (Graphics g)
{
drawTree (g, 400, 500, -90, 9)
}
}
class FractalTree
{
public static Void main ()
{
Window
{
title = "Fractal Tree"
size = Size(800, 600)
FractalCanvas(),
}.open
}
}
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#FreeBASIC
|
FreeBASIC
|
' version 17-03-2017
' compile with: fbc -s gui
Const As Double deg2rad = Atn(1) / 45
Dim Shared As Double scale = 0.76
Dim Shared As Double spread = 25 * deg2rad ' convert degree's to rad's
Sub branch(x1 As ULong, y1 As ULong, size As ULong, angle As Double, depth As ULong)
Dim As ULong x2, y2
x2 = x1 + size * Cos(angle)
y2 = y1 + size * Sin(angle)
Line (x1,y1) - (x2,y2), 2 ' palette color green
If depth > 0 Then
branch(x2, y2, size * scale, angle - spread, depth -1)
branch(x2, y2, size * scale, angle + spread, depth -1)
End If
End Sub
' ------=< MAIN >=-----
Dim As Double angle = -90 * deg2rad ' make sure that the tree grows up
Dim As ULong SizeX = 800
Dim As ULong SizeY = SizeX * 3 \ 4
Dim As Double size = SizeY \ 4
Dim As ULong depth = 11
ScreenRes SizeX, SizeY, 8
WindowTitle ("Fractal Tree")
branch(SizeX\2, SizeY, size, angle, depth)
' empty keyboard buffer
While InKey <> "" : Wend
windowtitle ("Fractal Tree, hit any key to end program")
Sleep
End
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Delphi
|
Delphi
|
package main
import (
"fmt"
"time"
)
func indexOf(n int, s []int) int {
for i, j := range s {
if n == j {
return i
}
}
return -1
}
func getDigits(n, le int, digits []int) bool {
for n > 0 {
r := n % 10
if r == 0 || indexOf(r, digits) >= 0 {
return false
}
le--
digits[le] = r
n /= 10
}
return true
}
var pows = [5]int{1, 10, 100, 1000, 10000}
func removeDigit(digits []int, le, idx int) int {
sum := 0
pow := pows[le-2]
for i := 0; i < le; i++ {
if i == idx {
continue
}
sum += digits[i] * pow
pow /= 10
}
return sum
}
func main() {
start := time.Now()
lims := [5][2]int{
{12, 97},
{123, 986},
{1234, 9875},
{12345, 98764},
{123456, 987653},
}
var count [5]int
var omitted [5][10]int
for i, lim := range lims {
nDigits := make([]int, i+2)
dDigits := make([]int, i+2)
blank := make([]int, i+2)
for n := lim[0]; n <= lim[1]; n++ {
copy(nDigits, blank)
nOk := getDigits(n, i+2, nDigits)
if !nOk {
continue
}
for d := n + 1; d <= lim[1]+1; d++ {
copy(dDigits, blank)
dOk := getDigits(d, i+2, dDigits)
if !dOk {
continue
}
for nix, digit := range nDigits {
if dix := indexOf(digit, dDigits); dix >= 0 {
rn := removeDigit(nDigits, i+2, nix)
rd := removeDigit(dDigits, i+2, dix)
if float64(n)/float64(d) == float64(rn)/float64(rd) {
count[i]++
omitted[i][digit]++
if count[i] <= 12 {
fmt.Printf("%d/%d = %d/%d by omitting %d's\n", n, d, rn, rd, digit)
}
}
}
}
}
}
fmt.Println()
}
for i := 2; i <= 6; i++ {
fmt.Printf("There are %d %d-digit fractions of which:\n", count[i-2], i)
for j := 1; j <= 9; j++ {
if omitted[i-2][j] == 0 {
continue
}
fmt.Printf("%6d have %d's omitted\n", omitted[i-2][j], j)
}
fmt.Println()
}
fmt.Printf("Took %s\n", time.Since(start))
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
class fractran
{
public:
void run( std::string p, int s, int l )
{
start = s; limit = l;
istringstream iss( p ); vector<string> tmp;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );
string item; vector< pair<float, float> > v;
pair<float, float> a;
for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
{
string::size_type pos = ( *i ).find( '/', 0 );
if( pos != std::string::npos )
{
a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
v.push_back( a );
}
}
exec( &v );
}
private:
void exec( vector< pair<float, float> >* v )
{
int cnt = 0;
while( cnt < limit )
{
cout << cnt << " : " << start << "\n";
cnt++;
vector< pair<float, float> >::iterator it = v->begin();
bool found = false; float r;
while( it != v->end() )
{
r = start * ( ( *it ).first / ( *it ).second );
if( r == floor( r ) )
{
found = true;
break;
}
++it;
}
if( found ) start = ( int )r;
else break;
}
}
int start, limit;
};
int main( int argc, char* argv[] )
{
fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
cin.get();
return 0;
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#ALGOL-M
|
ALGOL-M
|
INTEGER FUNCTION MULTIPLY( A, B );
INTEGER A, B;
BEGIN
MULTIPLY := A * B;
END;
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Groovy
|
Groovy
|
class FuscSequence {
static void main(String[] args) {
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
for (int n = 0; n < 61; n++) {
printf("%,d ", fusc[n])
}
println()
println()
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
int start = 0
for (int i = 0; i <= 5; i++) {
int val = i != 0 ? (int) Math.pow(10, i) : -1
for (int j = start; j < FUSC_MAX; j++) {
if (fusc[j] > val) {
printf("fusc[%,d] = %,d%n", j, fusc[j])
start = j
break
}
}
}
}
private static final int FUSC_MAX = 30000000
private static int[] fusc = new int[FUSC_MAX]
static {
fusc[0] = 0
fusc[1] = 1
for (int n = 2; n < FUSC_MAX; n++) {
int n2 = (int) (n / 2)
int n2m = (int) ((n - 1) / 2)
int n2p = (int) ((n + 1) / 2)
fusc[n] = n % 2 == 0
? fusc[n2]
: fusc[n2m] + fusc[n2p]
}
}
}
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Forth
|
Forth
|
8 constant (gamma-shift)
: (mortici) ( f1 -- f2)
-1 s>f f+ 1 s>f
fover 271828183e-8 f* 12 s>f f* f/
fover 271828183e-8 f/ f+
fover f** fswap
628318530e-8 f* fsqrt f* \ 2*pi
;
: gamma ( f1 -- f2)
fdup f0< >r fdup f0= r> or abort" Gamma less or equal to zero"
fdup (gamma-shift) s>f f+ (mortici) fswap
1 s>f (gamma-shift) 0 do fover i s>f f+ f* loop fswap fdrop f/
;
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#PureBasic
|
PureBasic
|
Global pegRadius, pegSize, pegSize2, height, width, delay, histogramSize, ball
Procedure eventLoop()
Protected event
Repeat
event = WindowEvent()
If event = #PB_Event_CloseWindow
End
EndIf
Until event = 0
EndProcedure
Procedure animate_actual(x1, y1, x2, y2, steps)
Protected x.f, y.f, xstep.f, ystep.f, i, lastX.f, lastY.f
x = x1
y = y1
xstep = (x2 - x1)/steps
ystep = (y2 - y1)/steps
For i = 1 To steps
lastX = x
lastY = y
StartDrawing(CanvasOutput(0))
DrawingMode(#PB_2DDrawing_XOr)
Circle(x, y, pegRadius, RGB(0, 255, 255))
StopDrawing()
eventLoop()
Delay(delay) ; wait in ms
StartDrawing(CanvasOutput(0))
DrawingMode(#PB_2DDrawing_XOr)
Circle(x, y, pegRadius, RGB(0, 255, 255))
StopDrawing()
eventLoop()
x + xstep
y + ystep
Next
EndProcedure
Procedure draw_ball(xpos, ypos)
Static Dim ballcounts(0) ;tally drop positions
If xpos > ArraySize(ballcounts())
Redim ballcounts(xpos)
EndIf
ballcounts(xpos) + 1
animate_actual(xpos, ypos, xpos, height - ballcounts(xpos) * pegSize, 20)
StartDrawing(CanvasOutput(0))
Circle(xpos, height - ballcounts(xpos) * pegSize, pegRadius, RGB(255, 0, 0))
StopDrawing()
eventLoop()
If ballcounts(xpos) <= histogramSize
ProcedureReturn 1
EndIf
SetWindowTitle(0, "Ended after " + Str(ball) + " balls") ;histogramSize exceeded
EndProcedure
Procedure animate(x1, y1, x2, y2)
animate_actual(x1, y1, x2, y1, 4)
animate_actual(x2, y1, x2, y2, 10)
EndProcedure
Procedure galton(pegRows)
;drop a ball into the galton box
Protected xpos, ypos, i, oldX, oldY
oldX = width / 2 - pegSize / 2
xpos = oldX
oldY = pegSize
ypos = oldY
animate_actual(oldX, 0, xpos, ypos, 10)
For i = 1 To pegRows
If Random(1)
xpos + pegSize
Else
xpos - pegSize
EndIf
ypos + pegSize2
animate(oldX, oldY, xpos, ypos)
oldX = xpos
oldY = ypos
Next
ProcedureReturn draw_ball(xpos, ypos)
EndProcedure
Procedure setup_window(numRows, ballCount)
;Draw numRows levels of pegs
Protected xpos, ypos, i, j
width = (2 * numRows + 2) * pegSize
histogramSize = (ballCount + 2) / 3
If histogramSize > 500 / pegSize: histogramSize = 500 / pegSize: EndIf
height = width + histogramSize * pegSize
OpenWindow(0, 0, 0, width, height, "Galton box animation", #PB_Window_SystemMenu)
CanvasGadget(0, 0, 0, width, height)
StartDrawing(CanvasOutput(0))
Box(0, 0, width, height, RGB($EB, $EB, $EB))
For i = 1 To numRows
ypos = i * pegSize2
xpos = width / 2 - (i - 1) * pegSize - pegSize / 2
For j = 1 To i
Circle(xpos, ypos, pegRadius, RGB(0, 0, 255))
xpos + pegSize2
Next
Next
For i = 1 To numRows
Line((numRows - i + 1) * pegSize2 - pegSize / 2, width - pegSize, 1, histogramSize * pegSize, 0)
Next
StopDrawing()
EndProcedure
;based on the galton box simulation from Unicon book
Define pegRows = 10, ballCount
pegRadius = 4
pegSize = pegRadius * 2 + 1
pegSize2 = pegSize * 2
delay = 2 ; ms delay
Repeat
ballCount = Val(InputRequester("Galton box simulator","How many balls to drop?", "100"))
Until ballCount > 0
setup_window(pegRows, ballCount)
eventLoop()
For ball = 1 To ballCount
If Not galton(pegRows): Break: EndIf
Next
Repeat: eventLoop(): ForEver
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#newLISP
|
newLISP
|
; Part 1: Useful functions
;; Create an integer out of the first and last digits of a given integer
(define (first-and-last-digits number)
(local (digits first-digit last-digit)
(set 'digits (format "%d" number))
(set 'first-digit (first digits))
(set 'last-digit (last digits))
(int (append first-digit last-digit))))
;; Divisbility test
(define (divisible-by? num1 num2)
(zero? (% num1 num2)))
;; Gapfulness test
(define (gapful? number)
(divisible-by? number (first-and-last-digits number)))
;; Increment until a gapful number is found
(define (next-gapful-after number)
(do-until (gapful? number)
(++ number)))
;; Return a list of gapful numbers beyond some (excluded) lower limit.
(define (gapful-numbers quantity lower-limit)
(let ((gapfuls '()) (number lower-limit))
(dotimes (counter quantity)
(set 'number (next-gapful-after number))
(push number gapfuls))
(reverse gapfuls)))
;; Format a list of numbers together into decimal notation.
(define (format-many numbers)
(map (curry format "%d") numbers))
;; Format a list of integers on one line with commas
(define (format-one-line numbers)
(join (format-many numbers) ", "))
;; Display a quantity of gapful numbers beyond some (excluded) lower limit.
(define (show-gapfuls quantity lower-limit)
(println "The first " quantity " gapful numbers beyond " lower-limit " are:")
(println (format-one-line (gapful-numbers quantity lower-limit))))
; Part 2: Complete the task
(show-gapfuls 30 99)
(show-gapfuls 15 999999)
(show-gapfuls 10 999999999)
(exit)
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
GaussianElimination[A_?MatrixQ, b_?VectorQ] := Last /@ RowReduce[Flatten /@ Transpose[{A, b}]]
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#Wren
|
Wren
|
import "/matrix" for Matrix
import "/fmt" for Fmt
var arrays = [
[ [ 1, 2, 3],
[ 4, 1, 6],
[ 7, 8, 9] ],
[ [ 2, -1, 0 ],
[-1, 2, -1 ],
[ 0, -1, 2 ] ],
[ [ -1, -2, 3, 2 ],
[ -4, -1, 6, 2 ],
[ 7, -8, 9, 1 ],
[ 1, -2, 1, 3 ] ]
]
for (array in arrays) {
System.print("Original:\n")
var m = Matrix.new(array)
Fmt.mprint(m, 2, 0)
System.print("\nInverse:\n")
Fmt.mprint(m.inverse, 9, 6)
System.print()
}
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Prolog
|
Prolog
|
maxNumber(105).
factors([(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]).
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#Python
|
Python
|
def genfizzbuzz(factorwords, numbers):
# sort entries by factor
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#jq
|
jq
|
"az" | explode | [range( .[0]; 1+.[1] )] | implode'
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#Jsish
|
Jsish
|
/* Generate the lower case alphabet with Jsish, assume ASCII */
var letterA = "a".charCodeAt(0);
var lowers = Array(26);
for (var i = letterA; i < letterA + 26; i++) {
lowers[i - letterA] = Util.fromCharCode(i);
}
puts(lowers);
puts(lowers.join(''));
puts(lowers.length);
/*
=!EXPECTSTART!=
[ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]
abcdefghijklmnopqrstuvwxyz
26
=!EXPECTEND!=
*/
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Perl
|
Perl
|
print "Hello world!\n";
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#Quackery
|
Quackery
|
[ ' [ this -1 peek
this -2 peek **
1 this tally
done ]
swap join
0 join ] is expogen ( n --> [ )
[ ' [ this temp put
temp share -3 peek do
dup temp share share = iff
[ drop
temp share -2 peek do
temp take replace ] again
[ dup temp share share > iff
[ temp share -2 peek do
temp share replace ]
again ]
temp release
done ]
unrot
dip nested
dup dip nested
do 3 times join ] is taskgen ( [ [ --> [ )
2 expogen
3 expogen taskgen
20 times [ dup do drop ]
10 times [ dup do echo sp ]
drop
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Diego
|
Diego
|
set_namespace(rosettacode);
begin_funct(compose)_arg(f, g);
[]_ret(x)_calc([f]([g]([x])));
end_funct[];
me_msg()_funct(compose)_arg(f)_sin()_arg(g)_asin()_var(x)_value(0.5); // result: 0.5
reset_namespace[];
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#Dylan
|
Dylan
|
define method compose(f,g)
method(x) f(g(x)) end
end;
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Frege
|
Frege
|
module FractalTree where
import Java.IO
import Prelude.Math
data AffineTransform = native java.awt.geom.AffineTransform where
native new :: () -> STMutable s AffineTransform
native clone :: Mutable s AffineTransform -> STMutable s AffineTransform
native rotate :: Mutable s AffineTransform -> Double -> ST s ()
native scale :: Mutable s AffineTransform -> Double -> Double -> ST s ()
native translate :: Mutable s AffineTransform -> Double -> Double -> ST s ()
data BufferedImage = native java.awt.image.BufferedImage where
pure native type_3byte_bgr "java.awt.image.BufferedImage.TYPE_3BYTE_BGR" :: Int
native new :: Int -> Int -> Int -> STMutable s BufferedImage
native createGraphics :: Mutable s BufferedImage -> STMutable s Graphics2D
data Color = pure native java.awt.Color where
pure native black "java.awt.Color.black" :: Color
pure native green "java.awt.Color.green" :: Color
pure native white "java.awt.Color.white" :: Color
pure native new :: Int -> Color
data BasicStroke = pure native java.awt.BasicStroke where
pure native new :: Float -> BasicStroke
data RenderingHints = native java.awt.RenderingHints where
pure native key_antialiasing "java.awt.RenderingHints.KEY_ANTIALIASING" :: RenderingHints_Key
pure native value_antialias_on "java.awt.RenderingHints.VALUE_ANTIALIAS_ON" :: Object
data RenderingHints_Key = pure native java.awt.RenderingHints.Key
data Graphics2D = native java.awt.Graphics2D where
native drawLine :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
native drawOval :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
native fillRect :: Mutable s Graphics2D -> Int -> Int -> Int -> Int -> ST s ()
native setColor :: Mutable s Graphics2D -> Color -> ST s ()
native setRenderingHint :: Mutable s Graphics2D -> RenderingHints_Key -> Object -> ST s ()
native setStroke :: Mutable s Graphics2D -> BasicStroke -> ST s ()
native setTransform :: Mutable s Graphics2D -> Mutable s AffineTransform -> ST s ()
data ImageIO = mutable native javax.imageio.ImageIO where
native write "javax.imageio.ImageIO.write" :: MutableIO BufferedImage -> String -> MutableIO File -> IO Bool throws IOException
drawTree :: Mutable s Graphics2D -> Mutable s AffineTransform -> Int -> ST s ()
drawTree g t i = do
let len = 10 -- ratio of length to thickness
shrink = 0.75
angle = 0.3 -- radians
i' = i - 1
g.setTransform t
g.drawLine 0 0 0 len
when (i' > 0) $ do
t.translate 0 (fromIntegral len)
t.scale shrink shrink
rt <- t.clone
t.rotate angle
rt.rotate (-angle)
drawTree g t i'
drawTree g rt i'
main = do
let width = 900
height = 800
initScale = 20
halfWidth = fromIntegral width / 2
buffy <- BufferedImage.new width height BufferedImage.type_3byte_bgr
g <- buffy.createGraphics
g.setRenderingHint RenderingHints.key_antialiasing RenderingHints.value_antialias_on
g.setColor Color.black
g.fillRect 0 0 width height
g.setColor Color.green
t <- AffineTransform.new ()
t.translate halfWidth (fromIntegral height)
t.scale initScale initScale
t.rotate pi
drawTree g t 16
f <- File.new "FractalTreeFrege.png"
void $ ImageIO.write buffy "png" f
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Frink
|
Frink
|
// Draw Fractal Tree in Frink
// Define the tree function
FractalTree[x1, y1, angleval, lengthval, graphicsobject] :=
{
if lengthval > 1
{
// Define current line end points (x2 and y2)
x2 = x1 + ((cos[angleval degrees]) * lengthval)
y2 = y1 + ((sin[angleval degrees]) * lengthval)
// Draw line - notice that graphicsobject is the graphics object passed into the function.
graphicsobject.line[x1,y1,x2,y2]
// Calculate branches. You can change the lengthval multiplier factor and angleval summand to create different trees
FractalTree[x2, y2, angleval - 20, lengthval * 0.7, graphicsobject]
FractalTree[x2, y2, angleval + 20, lengthval * 0.7, graphicsobject]
}
}
// Create graphics object
g = new graphics
// Start the recursive function. In Frink, a -90° angle moves from the bottom of the screen to the top.
FractalTree[0, 0, -90, 30, g]
// Show the final tree
g.show[]
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Go
|
Go
|
package main
import (
"fmt"
"time"
)
func indexOf(n int, s []int) int {
for i, j := range s {
if n == j {
return i
}
}
return -1
}
func getDigits(n, le int, digits []int) bool {
for n > 0 {
r := n % 10
if r == 0 || indexOf(r, digits) >= 0 {
return false
}
le--
digits[le] = r
n /= 10
}
return true
}
var pows = [5]int{1, 10, 100, 1000, 10000}
func removeDigit(digits []int, le, idx int) int {
sum := 0
pow := pows[le-2]
for i := 0; i < le; i++ {
if i == idx {
continue
}
sum += digits[i] * pow
pow /= 10
}
return sum
}
func main() {
start := time.Now()
lims := [5][2]int{
{12, 97},
{123, 986},
{1234, 9875},
{12345, 98764},
{123456, 987653},
}
var count [5]int
var omitted [5][10]int
for i, lim := range lims {
nDigits := make([]int, i+2)
dDigits := make([]int, i+2)
blank := make([]int, i+2)
for n := lim[0]; n <= lim[1]; n++ {
copy(nDigits, blank)
nOk := getDigits(n, i+2, nDigits)
if !nOk {
continue
}
for d := n + 1; d <= lim[1]+1; d++ {
copy(dDigits, blank)
dOk := getDigits(d, i+2, dDigits)
if !dOk {
continue
}
for nix, digit := range nDigits {
if dix := indexOf(digit, dDigits); dix >= 0 {
rn := removeDigit(nDigits, i+2, nix)
rd := removeDigit(dDigits, i+2, dix)
if float64(n)/float64(d) == float64(rn)/float64(rd) {
count[i]++
omitted[i][digit]++
if count[i] <= 12 {
fmt.Printf("%d/%d = %d/%d by omitting %d's\n", n, d, rn, rd, digit)
}
}
}
}
}
}
fmt.Println()
}
for i := 2; i <= 6; i++ {
fmt.Printf("There are %d %d-digit fractions of which:\n", count[i-2], i)
for j := 1; j <= 9; j++ {
if omitted[i-2][j] == 0 {
continue
}
fmt.Printf("%6d have %d's omitted\n", omitted[i-2][j], j)
}
fmt.Println()
}
fmt.Printf("Took %s\n", time.Since(start))
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#Common_Lisp
|
Common Lisp
|
(defun fractran (n frac-list)
(lambda ()
(prog1
n
(when n
(let ((f (find-if (lambda (frac)
(integerp (* n frac)))
frac-list)))
(when f (setf n (* f n))))))))
;; test
(defvar *primes-ft* '(17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1))
(loop with fractran-instance = (fractran 2 *primes-ft*)
repeat 20
for next = (funcall fractran-instance)
until (null next)
do (print next))
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#AmigaE
|
AmigaE
|
PROC my_molt(a,b)
-> other statements if needed... here they are not
ENDPROC a*b -> return value
-> or simplier
PROC molt(a,b) IS a*b
PROC main()
WriteF('\d\n', my_molt(10,20))
ENDPROC
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#Haskell
|
Haskell
|
---------------------- FUSC SEQUENCE ---------------------
fusc :: Int -> Int
fusc i
| 1 > i = 0
| otherwise = fst $ go (pred i)
where
go n
| 0 == n = (1, 0)
| even n = (x + y, y)
| otherwise = (x, x + y)
where
(x, y) = go (div n 2)
--------------------------- TEST -------------------------
main :: IO ()
main = do
putStrLn "First 61 terms:"
print $ fusc <$> [0 .. 60]
putStrLn "\n(Index, Value):"
mapM_ print $ take 5 widths
widths :: [(Int, Int)]
widths =
fmap
(\(_, i, x) -> (i, x))
(iterate nxtWidth (2, 0, 0))
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
nxtWidth (w, i, v) = (succ w, j, x)
where
fi = (,) <*> fusc
(j, x) =
until
((w <=) . length . show . snd)
(fi . succ . fst)
(fi i)
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#Fortran
|
Fortran
|
program ComputeGammaInt
implicit none
integer :: i
write(*, "(3A15)") "Simpson", "Lanczos", "Builtin"
do i=1, 10
write(*, "(3F15.8)") my_gamma(i/3.0), lacz_gamma(i/3.0), gamma(i/3.0)
end do
contains
pure function intfuncgamma(x, y) result(z)
real :: z
real, intent(in) :: x, y
z = x**(y-1.0) * exp(-x)
end function intfuncgamma
function my_gamma(a) result(g)
real :: g
real, intent(in) :: a
real, parameter :: small = 1.0e-4
integer, parameter :: points = 100000
real :: infty, dx, p, sp(2, points), x
integer :: i
logical :: correction
x = a
correction = .false.
! value with x<1 gives \infty, so we use
! \Gamma(x+1) = x\Gamma(x)
! to avoid the problem
if ( x < 1.0 ) then
correction = .true.
x = x + 1
end if
! find a "reasonable" infinity...
! we compute this integral indeed
! \int_0^M dt t^{x-1} e^{-t}
! where M is such that M^{x-1} e^{-M} ≤ \epsilon
infty = 1.0e4
do while ( intfuncgamma(infty, x) > small )
infty = infty * 10.0
end do
! using simpson
dx = infty/real(points)
sp = 0.0
forall(i=1:points/2-1) sp(1, 2*i) = intfuncgamma(2.0*(i)*dx, x)
forall(i=1:points/2) sp(2, 2*i - 1) = intfuncgamma((2.0*(i)-1.0)*dx, x)
g = (intfuncgamma(0.0, x) + 2.0*sum(sp(1,:)) + 4.0*sum(sp(2,:)) + &
intfuncgamma(infty, x))*dx/3.0
if ( correction ) g = g/a
end function my_gamma
recursive function lacz_gamma(a) result(g)
real, intent(in) :: a
real :: g
real, parameter :: pi = 3.14159265358979324
integer, parameter :: cg = 7
! these precomputed values are taken by the sample code in Wikipedia,
! and the sample itself takes them from the GNU Scientific Library
real, dimension(0:8), parameter :: p = &
(/ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, &
771.32342877765313, -176.61502916214059, 12.507343278686905, &
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 /)
real :: t, w, x
integer :: i
x = a
if ( x < 0.5 ) then
g = pi / ( sin(pi*x) * lacz_gamma(1.0-x) )
else
x = x - 1.0
t = p(0)
do i=1, cg+2
t = t + p(i)/(x+real(i))
end do
w = x + real(cg) + 0.5
g = sqrt(2.0*pi) * w**(x+0.5) * exp(-w) * t
end if
end function lacz_gamma
end program ComputeGammaInt
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#Python
|
Python
|
#!/usr/bin/python
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,1)
self.y += 1
def fall(self):
self.y +=1
class Board():
def __init__(self, width, well_depth, N):
self.balls = []
self.fallen = [0] * (width + 1)
self.width = width
self.well_depth = well_depth
self.N = N
self.shift = 4
def update(self):
for ball in self.balls:
if ball.y < self.width:
ball.update()
elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:
ball.fall()
elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:
self.fallen[ball.x] += 1
else:
pass
def balls_on_board(self):
return len(self.balls) - sum(self.fallen)
def add_ball(self):
if(len(self.balls) <= self.N):
self.balls.append(Ball())
def print_board(self):
for y in range(self.width + 1):
for x in range(y):
print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "#")
def print_ball(self, ball):
if ball.y <= self.width:
x = self.width - ball.y + 2*ball.x + self.shift
else:
x = 2*ball.x + self.shift
y = ball.y + 1
print_there(y, x, "*")
def print_all(self):
print(chr(27) + "[2J")
self.print_board();
for ball in self.balls:
self.print_ball(ball)
def main():
board = Board(width = 15, well_depth = 5, N = 10)
board.add_ball() #initialization
while(board.balls_on_board() > 0):
board.print_all()
time.sleep(0.25)
board.update()
board.print_all()
time.sleep(0.25)
board.update()
board.add_ball()
if __name__=="__main__":
main()
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Nim
|
Nim
|
import strutils
func gapfulDivisor(n: Positive): Positive =
## Return the gapful divisor of "n".
let last = n mod 10
var first = n div 10
while first > 9:
first = first div 10
result = 10 * first + last
iterator gapful(start: Positive): Positive =
## Yield the gapful numbers starting from "start".
var n = start
while true:
let d = n.gapfulDivisor()
if n mod d == 0: yield n
inc n
proc displayGapfulNumbers(start, num: Positive) =
## Display the first "num" gapful numbers greater or equal to "start".
echo "\nFirst $1 gapful numbers ⩾ $2:".format(num, start)
var count = 0
var line: string
for n in gapful(start):
line.addSep(" ")
line.add($n)
inc count
if count == num: break
echo line
when isMainModule:
displayGapfulNumbers(100, 30)
displayGapfulNumbers(1_000_000, 15)
displayGapfulNumbers(1_000_000_000, 10)
|
http://rosettacode.org/wiki/Gapful_numbers
|
Gapful numbers
|
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
187 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 187.
About 7.46% of positive integers are gapful.
Task
Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
Show the first 30 gapful numbers
Show the first 15 gapful numbers ≥ 1,000,000
Show the first 10 gapful numbers ≥ 1,000,000,000
Related tasks
Harshad or Niven series.
palindromic gapful numbers.
largest number divisible by its digits.
Also see
The OEIS entry: A108343 gapful numbers.
numbersaplenty gapful numbers
|
#Pascal
|
Pascal
|
program gapful;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils // IntToStr
{$IFDEF FPC}
,strUtils // Numb2USA aka commatize
{$ENDIF};
const
cIdx = 5;
starts: array[0..cIdx - 1] of Uint64 = (100, 1000 * 1000, 10 * 1000 * 1000,
1000 * 1000 * 1000, 7123);
counts: array[0..cIdx - 1] of Uint64 = (30, 15, 15, 10, 25);
//100| 74623687 => 1000*1000*1000
//100| 746236131 => 10*1000*1000*1000
//100|7462360431 =>100*1000*1000*1000
Base = 10;
var
ModsHL: array[0..99] of NativeUint;
Pow10: Uint64; //global, seldom used
countLmt: NativeUint; //Uint64; only for extreme counting
{$IFNDEF FPC}
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
while (i > 0) do
begin
if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then
begin
insert(',', Result, i);
inc(NA);
end;
Dec(i);
end;
end;
{$ENDIF}
procedure OutHeader(i: NativeInt);
begin
writeln('First ', counts[i], ', gapful numbers starting at ', Numb2USA(IntToStr
(starts[i])));
end;
procedure OutNum(n: Uint64);
begin
write(' ', n);
end;
procedure InitMods(n: Uint64; H_dgt: NativeUint);
//calculate first mod of n, when it reaches n
var
i, j: NativeInt;
begin
j := H_dgt; //= H_dgt+i
for i := 0 to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure InitMods2(n: Uint64; H_dgt, L_Dgt: NativeUint);
//calculate first mod of n, when it reaches n
//beware, that the lower n are reached in the next base round
var
i, j: NativeInt;
begin
j := H_dgt;
n := n - L_Dgt;
for i := 0 to L_Dgt - 1 do
begin
ModsHL[j] := (n + base) mod j;
inc(n);
inc(j);
end;
for i := L_Dgt to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure Main(TestNum: Uint64; Cnt: NativeUint);
var
LmtNextNewHiDgt: Uint64;
tmp, LowDgt, GapNum: NativeUint;
begin
countLmt := Cnt;
Pow10 := Base * Base;
LmtNextNewHiDgt := Base * Pow10;
while LmtNextNewHiDgt <= TestNum do
begin
Pow10 := LmtNextNewHiDgt;
LmtNextNewHiDgt := LmtNextNewHiDgt * Base;
end;
LowDgt := TestNum mod Base;
GapNum := TestNum div Pow10;
LmtNextNewHiDgt := (GapNum + 1) * Pow10;
GapNum := Base * GapNum;
if LowDgt <> 0 then
InitMods2(TestNum, GapNum, LowDgt)
else
InitMODS(TestNum, GapNum);
GapNum := GapNum + LowDgt;
repeat
// if TestNum MOD (GapNum) = 0 then
if ModsHL[GapNum] = 0 then
begin
tmp := countLmt - 1;
if tmp < 32 then
OutNum(TestNum);
countLmt := tmp;
// Test and BREAK only if something has changed
if tmp = 0 then
BREAK;
end;
tmp := Base + ModsHL[GapNum];
//translate into "if-less" version 3.35s -> 1.85s
//bad branch prediction :-(
//if tmp >= GapNum then tmp -= GapNum;
tmp := tmp - (-ORD(tmp >= GapNum) and GapNum);
ModsHL[GapNum] := tmp;
TestNum := TestNum + 1;
tmp := LowDgt + 1;
inc(GapNum);
if tmp >= Base then
begin
tmp := 0;
GapNum := GapNum - Base;
end;
LowDgt := tmp;
//next Hi Digit
if TestNum >= LmtNextNewHiDgt then
begin
LowDgt := 0;
GapNum := GapNum + Base;
LmtNextNewHiDgt := LmtNextNewHiDgt + Pow10;
//next power of 10
if GapNum >= Base * Base then
begin
Pow10 := Pow10 * Base;
LmtNextNewHiDgt := 2 * Pow10;
GapNum := Base;
end;
initMods(TestNum, GapNum);
end;
until false;
end;
var
i: integer;
begin
for i := 0 to High(starts) do
begin
OutHeader(i);
Main(starts[i], counts[i]);
writeln(#13#10);
end;
{$IFNDEF LINUX} readln; {$ENDIF}
end.
|
http://rosettacode.org/wiki/Gaussian_elimination
|
Gaussian elimination
|
Task
Solve Ax=b using Gaussian elimination then backwards substitution.
A being an n by n matrix.
Also, x and b are n by 1 vectors.
To improve accuracy, please use partial pivoting and scaling.
See also
the Wikipedia entry: Gaussian elimination
|
#MATLAB
|
MATLAB
|
function [ x ] = GaussElim( A, b)
% Ensures A is n by n
sz = size(A);
if sz(1)~=sz(2)
fprintf('A is not n by n\n');
clear x;
return;
end
n = sz(1);
% Ensures b is n x 1.
if n~=sz(1)
fprintf('b is not 1 by n.\n');
return
end
x = zeros(n,1);
aug = [A b];
tempmatrix = aug;
for i=2:sz(1)
% Find maximum of row and divide by the maximum
tempmatrix(1,:) = tempmatrix(1,:)/max(tempmatrix(1,:));
% Finds the maximum in column
temp = find(abs(tempmatrix) - max(abs(tempmatrix(:,1))));
if length(temp)>2
for j=1:length(temp)-1
if j~=temp(j)
maxi = j; %maxi = column number of maximum
break;
end
end
else % length(temp)==2
maxi=1;
end
% Row swap if maxi is not 1
if maxi~=1
temp = tempmatrix(maxi,:);
tempmatrix(maxi,:) = tempmatrix(1,:);
tempmatrix(1,:) = temp;
end
% Row reducing
for j=2:length(tempmatrix)-1
tempmatrix(j,:) = tempmatrix(j,:)-tempmatrix(j,1)/tempmatrix(1,1)*tempmatrix(1,:);
if tempmatrix(j,j)==0 || isnan(tempmatrix(j,j)) || abs(tempmatrix(j,j))==Inf
fprintf('Error: Matrix is singular.\n');
clear x;
return
end
end
aug(i-1:end,i-1:end) = tempmatrix;
% Decrease matrix size
tempmatrix = tempmatrix(2:end,2:end);
end
% Backwards Substitution
x(end) = aug(end,end)/aug(end,end-1);
for i=n-1:-1:1
x(i) = (aug(i,end)-dot(aug(i,1:end-1),x))/aug(i,i);
end
end
|
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
|
Gauss-Jordan matrix inversion
|
Task
Invert matrix A using Gauss-Jordan method.
A being an n × n matrix.
|
#zkl
|
zkl
|
var [const] GSL=Import.lib("zklGSL"); // libGSL (GNU Scientific Library)
m:=GSL.Matrix(3,3).set(1,2,3, 4,1,6, 7,8,9);
i:=m.invert();
i.format(10,4).println("\n");
(m*i).format(10,4).println();
|
http://rosettacode.org/wiki/General_FizzBuzz
|
General FizzBuzz
|
Task
Write a generalized version of FizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user
>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)
>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)
>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz".
If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7.
Output:
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
|
#R
|
R
|
genFizzBuzz <- function(n, ...)
{
args <- list(...)
#R doesn't like vectors of mixed types, so c(3, "Fizz") is coerced to c("3", "Fizz"). We must undo this.
#Treating "[[" as if it is a function is a bit of R's magic. You can treat it like a function because it actually is one.
factors <- as.integer(sapply(args, "[[", 1))
words <- sapply(args, "[[", 2)
sortedPermutation <- sort.list(factors)#Required by the task: We must go from least factor to greatest.
factors <- factors[sortedPermutation]
words <- words[sortedPermutation]
for(i in 1:n)
{
isFactor <- i %% factors == 0
print(if(any(isFactor)) paste0(words[isFactor], collapse = "") else i)
}
}
genFizzBuzz(105, c(3, "Fizz"), c(5, "Buzz"), c(7, "Baxx"))
genFizzBuzz(105, c(5, "Buzz"), c(9, "Prax"), c(3, "Fizz"), c(7, "Baxx"))
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Julia
|
Julia
|
@show collect('a':'z')
@show join('a':'z')
|
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
|
Generate lower case ASCII alphabet
|
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.
During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}
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
|
#K
|
K
|
`c$97+!26
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Peylang
|
Peylang
|
chaap 'Hello world!';
|
http://rosettacode.org/wiki/Generator/Exponential
|
Generator/Exponential
|
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
Task
Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
Use it to create a generator of:
Squares.
Cubes.
Create a new generator that filters all cubes from the generator of squares.
Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task requires the use of generators in the calculation of the result.
Also see
Generator
|
#R
|
R
|
powers = function(m)
{n = -1
function()
{n <<- n + 1
n^m}}
noncubic.squares = local(
{squares = powers(2)
cubes = powers(3)
cube = cubes()
function()
{square = squares()
while (1)
{if (square > cube)
{cube <<- cubes()
next}
else if (square < cube)
{return(square)}
else
{square = squares()}}}})
for (i in 1:20)
noncubic.squares()
for (i in 1:10)
message(noncubic.squares())
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
compose f g:
labda:
f g
|
http://rosettacode.org/wiki/Function_composition
|
Function composition
|
Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
|
#E
|
E
|
def compose(f, g) {
return fn x { return f(g(x)) }
}
|
http://rosettacode.org/wiki/Fractal_tree
|
Fractal tree
|
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
|
#Go
|
Go
|
package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Grayscale image
// * Xiaolin Wu's line algorithm
// * Write a PPM file
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
|
http://rosettacode.org/wiki/Fraction_reduction
|
Fraction reduction
|
There is a fine line between numerator and denominator. ─── anonymous
A method to "reduce" some reducible fractions is to cross out a digit from the
numerator and the denominator. An example is:
16 16
──── and then (simply) cross─out the sixes: ────
64 64
resulting in:
1
───
4
Naturally, this "method" of reduction must reduce to the proper value (shown as a fraction).
This "method" is also known as anomalous cancellation and also accidental cancellation.
(Of course, this "method" shouldn't be taught to impressionable or gullible minds.) 😇
Task
Find and show some fractions that can be reduced by the above "method".
show 2-digit fractions found (like the example shown above)
show 3-digit fractions
show 4-digit fractions
show 5-digit fractions (and higher) (optional)
show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
for each "size" fraction, only show a dozen examples (the 1st twelve found)
(it's recognized that not every programming solution will have the same generation algorithm)
for each "size" fraction:
show a count of how many reducible fractions were found. The example (above) is size 2
show a count of which digits were crossed out (one line for each different digit)
for each "size" fraction, show a count of how many were found. The example (above) is size 2
show each n-digit example (to be shown on one line):
show each n-digit fraction
show each reduced n-digit fraction
show what digit was crossed out for the numerator and the denominator
Task requirements/restrictions
only proper fractions and their reductions (the result) are to be used (no vulgar fractions)
only positive fractions are to be used (no negative signs anywhere)
only base ten integers are to be used for the numerator and denominator
no zeros (decimal digit) can be used within the numerator or the denominator
the numerator and denominator should be composed of the same number of digits
no digit can be repeated in the numerator
no digit can be repeated in the denominator
(naturally) there should be a shared decimal digit in the numerator and the denominator
fractions can be shown as 16/64 (for example)
Show all output here, on this page.
Somewhat related task
Farey sequence (It concerns fractions.)
References
Wikipedia entry: proper and improper fractions.
Wikipedia entry: anomalous cancellation and/or accidental cancellation.
|
#Groovy
|
Groovy
|
class FractionReduction {
static void main(String[] args) {
for (int size = 2; size <= 5; size++) {
reduce(size)
}
}
private static void reduce(int numDigits) {
System.out.printf("Fractions with digits of length %d where cancellation is valid. Examples:%n", numDigits)
// Generate allowed numerator's and denominator's
int min = (int) Math.pow(10, numDigits - 1)
int max = (int) Math.pow(10, numDigits) - 1
List<Integer> values = new ArrayList<>()
for (int number = min; number <= max; number++) {
if (isValid(number)) {
values.add(number)
}
}
Map<Integer, Integer> cancelCount = new HashMap<>()
int size = values.size()
int solutions = 0
for (int nIndex = 0; nIndex < size - 1; nIndex++) {
int numerator = values.get(nIndex)
// Must be proper fraction
for (int dIndex = nIndex + 1; dIndex < size; dIndex++) {
int denominator = values.get(dIndex)
for (int commonDigit : digitsInCommon(numerator, denominator)) {
int numRemoved = removeDigit(numerator, commonDigit)
int denRemoved = removeDigit(denominator, commonDigit)
if (numerator * denRemoved == denominator * numRemoved) {
solutions++
cancelCount.merge(commonDigit, 1, { v1, v2 -> v1 + v2 })
if (solutions <= 12) {
println(" When $commonDigit is removed, $numerator/$denominator = $numRemoved/$denRemoved")
}
}
}
}
}
println("Number of fractions where cancellation is valid = $solutions.")
List<Integer> sorted = new ArrayList<>(cancelCount.keySet())
Collections.sort(sorted)
for (int removed : sorted) {
println(" The digit $removed was removed ${cancelCount.get(removed)} times.")
}
println()
}
private static int[] powers = [1, 10, 100, 1000, 10000, 100000]
// Remove the specified digit.
private static int removeDigit(int n, int removed) {
int m = 0
int pow = 0
while (n > 0) {
int r = n % 10
if (r != removed) {
m = m + r * powers[pow]
pow++
}
n /= 10
}
return m
}
// Assumes no duplicate digits individually in n1 or n2 - part of task
private static List<Integer> digitsInCommon(int n1, int n2) {
int[] count = new int[10]
List<Integer> common = new ArrayList<>()
while (n1 > 0) {
int r = n1 % 10
count[r] += 1
n1 /= 10
}
while (n2 > 0) {
int r = n2 % 10
if (count[r] > 0) {
common.add(r)
}
n2 /= 10
}
return common
}
// No repeating digits, no digit is zero.
private static boolean isValid(int num) {
int[] count = new int[10]
while (num > 0) {
int r = num % 10
if (r == 0 || count[r] == 1) {
return false
}
count[r] = 1
num /= 10
}
return true
}
}
|
http://rosettacode.org/wiki/Fractran
|
Fractran
|
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
{\displaystyle n}
.
The program is run by updating the integer
n
{\displaystyle n}
as follows:
for the first fraction,
f
i
{\displaystyle f_{i}}
, in the list for which
n
f
i
{\displaystyle nf_{i}}
is an integer, replace
n
{\displaystyle n}
with
n
f
i
{\displaystyle nf_{i}}
;
repeat this rule until no fraction in the list produces an integer when multiplied by
n
{\displaystyle n}
, then halt.
Conway gave a program for primes in FRACTRAN:
17
/
91
{\displaystyle 17/91}
,
78
/
85
{\displaystyle 78/85}
,
19
/
51
{\displaystyle 19/51}
,
23
/
38
{\displaystyle 23/38}
,
29
/
33
{\displaystyle 29/33}
,
77
/
29
{\displaystyle 77/29}
,
95
/
23
{\displaystyle 95/23}
,
77
/
19
{\displaystyle 77/19}
,
1
/
17
{\displaystyle 1/17}
,
11
/
13
{\displaystyle 11/13}
,
13
/
11
{\displaystyle 13/11}
,
15
/
14
{\displaystyle 15/14}
,
15
/
2
{\displaystyle 15/2}
,
55
/
1
{\displaystyle 55/1}
Starting with
n
=
2
{\displaystyle n=2}
, this FRACTRAN program will change
n
{\displaystyle n}
to
15
=
2
×
(
15
/
2
)
{\displaystyle 15=2\times (15/2)}
, then
825
=
15
×
(
55
/
1
)
{\displaystyle 825=15\times (55/1)}
, generating the following sequence of integers:
2
{\displaystyle 2}
,
15
{\displaystyle 15}
,
825
{\displaystyle 825}
,
725
{\displaystyle 725}
,
1925
{\displaystyle 1925}
,
2275
{\displaystyle 2275}
,
425
{\displaystyle 425}
,
390
{\displaystyle 390}
,
330
{\displaystyle 330}
,
290
{\displaystyle 290}
,
770
{\displaystyle 770}
,
…
{\displaystyle \ldots }
After 2, this sequence contains the following powers of 2:
2
2
=
4
{\displaystyle 2^{2}=4}
,
2
3
=
8
{\displaystyle 2^{3}=8}
,
2
5
=
32
{\displaystyle 2^{5}=32}
,
2
7
=
128
{\displaystyle 2^{7}=128}
,
2
11
=
2048
{\displaystyle 2^{11}=2048}
,
2
13
=
8192
{\displaystyle 2^{13}=8192}
,
2
17
=
131072
{\displaystyle 2^{17}=131072}
,
2
19
=
524288
{\displaystyle 2^{19}=524288}
,
…
{\displaystyle \ldots }
which are the prime powers of 2.
Task
Write a program that reads a list of fractions in a natural format from the keyboard or from a string,
to parse it into a sequence of fractions (i.e. two integers),
and runs the FRACTRAN starting from a provided integer, writing the result at each step.
It is also required that the number of steps is limited (by a parameter easy to find).
Extra credit
Use this program to derive the first 20 or so prime numbers.
See also
For more on how to program FRACTRAN as a universal programming language, see:
J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.
J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.
Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
|
#D
|
D
|
import std.stdio, std.algorithm, std.conv, std.array;
void fractran(in string prog, int val, in uint limit) {
const fracts = prog.split.map!(p => p.split("/").to!(int[])).array;
foreach (immutable n; 0 .. limit) {
writeln(n, ": ", val);
const found = fracts.find!(p => val % p[1] == 0);
if (found.empty)
break;
val = found.front[0] * val / found.front[1];
}
}
void main() {
fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23
77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15);
}
|
http://rosettacode.org/wiki/Function_definition
|
Function definition
|
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are created and values returned).
Related task
Function prototype
|
#AntLang
|
AntLang
|
multiply: * /`*' is a normal function
multiply: {x * y}
|
http://rosettacode.org/wiki/Fusc_sequence
|
Fusc sequence
|
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
An observation
fusc(A) = fusc(B)
where A is some non-negative integer expressed in binary, and
where B is the binary value of A reversed.
Fusc numbers are also known as:
fusc function (named by Dijkstra, 1982)
Stern's Diatomic series (although it starts with unity, not zero)
Stern-Brocot sequence (although it starts with unity, not zero)
Task
show the first 61 fusc numbers (starting at zero) in a horizontal format.
show the fusc number (and its index) whose length is greater than any previous fusc number length.
(the length is the number of decimal digits when the fusc number is expressed in base ten.)
show all numbers with commas (if appropriate).
show all output here.
Related task
RosettaCode Stern-Brocot sequence
Also see
the MathWorld entry: Stern's Diatomic Series.
the OEIS entry: A2487.
|
#J
|
J
|
fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
fusc =: (, fusc_term)@:]^:[ 0 1"_
NB. show the first 61 fusc numbers (starting at zero) in a horizontal format.
61 {. fusc 70
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
9!:17]2 2 NB. specify bottom right position in box
FUSC =: fusc 99999
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
┌─────┬─┬──┬────┬─────┐
│index│0│37│1173│35499│
├─────┼─┼──┼────┼─────┤
│value│0│11│ 108│ 1076│
└─────┴─┴──┴────┴─────┘
|
http://rosettacode.org/wiki/Gamma_function
|
Gamma function
|
Task
Implement one algorithm (or more) to compute the Gamma (
Γ
{\displaystyle \Gamma }
) function (in the real field only).
If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.
The Gamma function can be defined as:
Γ
(
x
)
=
∫
0
∞
t
x
−
1
e
−
t
d
t
{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}
This suggests a straightforward (but inefficient) way of computing the
Γ
{\displaystyle \Gamma }
through numerical integration.
Better suggested methods:
Lanczos approximation
Stirling's approximation
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
Const pi = 3.1415926535897932
Const e = 2.7182818284590452
Function gammaStirling (x As Double) As Double
Return Sqr(2.0 * pi / x) * ((x / e) ^ x)
End Function
Function gammaLanczos (x As Double) As Double
Dim p(0 To 8) As Double = _
{ _
0.99999999999980993, _
676.5203681218851, _
-1259.1392167224028, _
771.32342877765313, _
-176.61502916214059, _
12.507343278686905, _
-0.13857109526572012, _
9.9843695780195716e-6, _
1.5056327351493116e-7 _
}
Dim As Integer g = 7
If x < 0.5 Then Return pi / (Sin(pi * x) * gammaLanczos(1-x))
x -= 1
Dim a As Double = p(0)
Dim t As Double = x + g + 0.5
For i As Integer = 1 To 8
a += p(i) / (x + i)
Next
Return Sqr(2.0 * pi) * (t ^ (x + 0.5)) * Exp(-t) * a
End Function
Print " x", " Stirling",, " Lanczos"
Print
For i As Integer = 1 To 20
Dim As Double d = i / 10.0
Print Using "#.##"; d;
Print , Using "#.###############"; gammaStirling(d);
Print , Using "#.###############"; gammaLanczos(d)
Next
Print
Print "Press any key to quit"
Sleep
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#Racket
|
Racket
|
;a ball's position...row is a natural number and col is an integer where 0 is the center
(define-struct pos (row col))
;state of simulation...list of all positions and vector of balls (index = bin)
(define-struct st (poss bins))
;increment vector @i
(define (vector-inc! v i) (vector-set! v i (add1 (vector-ref v i))))
(define BALL-RADIUS 6)
;for balls to fit perfectly between diamond-shaped pins, the side length is
;determined by inscribing the diamond in the circle
(define PIN-SIDE-LENGTH (* (sqrt 2) BALL-RADIUS))
;ultimate pin width and height
(define PIN-WH (* 2 BALL-RADIUS))
(define PIN-HOR-SPACING (* 2 PIN-WH))
;vertical space is the height of an equilateral triangle with side length = PIN-HOR-SPACING
(define PIN-VER-SPACING (* 1/2 (sqrt 3) PIN-HOR-SPACING))
;somewhat copying BASIC256's graphics
;determines how thick the outline will be
(define FILL-RATIO 0.7)
;freeze is a function that converts the drawing code into an actual bitmap forever
(define PIN (freeze (overlay (rotate 45 (square (* FILL-RATIO PIN-SIDE-LENGTH) "solid" "purple"))
(rotate 45 (square PIN-SIDE-LENGTH "solid" "magenta")))))
(define BALL (freeze (overlay (circle (* FILL-RATIO BALL-RADIUS) "solid" "green")
(circle BALL-RADIUS "solid" "dark green"))))
(define BIN-COLOR (make-color 255 128 192))
;# balls bin can fit
(define BIN-CAPACITY 10)
(define BIN-HEIGHT (* BIN-CAPACITY PIN-WH))
(define BIN (freeze (beside/align "bottom"
(line 0 BIN-HEIGHT BIN-COLOR)
(line PIN-WH 0 BIN-COLOR)
(line 0 BIN-HEIGHT BIN-COLOR))))
(define draw-background
(let ([background #f])
(λ (height)
(if (image? background)
background
(let* ([w (+ (image-width BIN) (* PIN-HOR-SPACING height))]
[h (+ PIN-WH (image-height BIN) (* PIN-VER-SPACING height))]
[draw-background (λ () (rectangle w h "solid" "black"))])
(begin (set! background (freeze (draw-background))) background))))))
;draws images using x horizontal space between center points
(define (spaced/x x is)
(if (null? is)
(empty-scene 0 0)
(let spaced/x ([n 1] [i (car is)] [is (cdr is)])
(if (null? is)
i
(overlay/xy i (* -1 n x) 0 (spaced/x (add1 n) (car is) (cdr is)))))))
(define (draw-pin-row r) (spaced/x PIN-HOR-SPACING (make-list (add1 r) PIN)))
;draws all pins, using saved bitmap for efficiency
(define draw-pins
(let ([bmp #f])
(λ (height)
(let ([draw-pins (λ () (foldl (λ (r i) (overlay/align/offset
;vertically line up all pin rows
"center" "bottom" (draw-pin-row r)
;shift down from the bottom of accum'ed image by ver spacing
0 (- PIN-VER-SPACING) i))
(draw-pin-row 0) (range 1 height 1)))])
(if (image? bmp)
bmp
(begin (set! bmp (freeze (draw-pins))) bmp))))))
(define (draw-ball p i)
;the ball starts at the top of the image
(overlay/align/offset "center" "top" BALL (* -1 (pos-col p) PIN-WH) (* -1 (pos-row p) PIN-VER-SPACING) i))
;bin has balls added from bottom, stacked exactly on top of each other
;the conditional logic is needed because above can't handle 0 or 1 things
(define (draw-bin n)
(if (zero? n)
BIN
(overlay/align "center" "bottom"
(if (= n 1) BALL (apply above (make-list n BALL)))
BIN)))
;main drawing function
(define (draw height s)
(let* ([bins (spaced/x PIN-HOR-SPACING (map draw-bin (vector->list (st-bins s))))]
;pins above bins
[w/pins (above (draw-pins height) bins)]
;draw this all one ball diameter (PIN-WH) below top
[w/background (overlay/align/offset "center" "top" w/pins
0 (- PIN-WH) (draw-background height))])
;now accumulate in each ball
(foldl draw-ball w/background (st-poss s))))
;a ball moves down by increasing its row and randomly changing its col by -1 or 1
(define (next-row height p)
(make-pos (add1 (pos-row p))
(+ -1 (* 2 (random 2)) (pos-col p))))
;each step, every ball goes to the next row and new balls are added at the top center
;balls that fall off go into bins
(define (tock height s)
(let* ([new-ps (map (λ (p) (next-row height p)) (st-poss s))]
;live balls haven't gone past the last row of pins
[live (filter (λ (p) (< (pos-row p) height)) new-ps)]
;dead balls have (partition from normal Racket would be useful here...)
[dead (filter (λ (p) (>= (pos-row p) height)) new-ps)]
;adjust col from [-x,x] to [0,2x]
[bin-indices (map (λ (p) (quotient (+ (pos-col p) height) 2)) dead)])
;add new balls to the live balls
(make-st (append (make-list (random 4) (make-pos 0 0)) live)
;sum dead ball positions into bins
(begin (for-each (λ (i) (vector-inc! (st-bins s) i)) bin-indices)
(st-bins s)))))
;run simulation with empty list of positions to start, stepping with "tock" and drawing with "draw"
(define (run height)
(big-bang (make-st '() (make-vector (add1 height) 0))
(on-tick (λ (ps) (tock height ps)) 0.5)
(to-draw (λ (ps) (draw height ps)))))
|
http://rosettacode.org/wiki/Galton_box_animation
|
Galton box animation
|
Example of a Galton Box at the end of animation.
A Galton device Sir Francis Galton's device is also known as a bean machine, a Galton Board, or a quincunx.
Description of operation
In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.
Eventually the balls are collected into bins at the bottom (as shown in the image), the ball column heights in the bins approximate a bell curve. Overlaying Pascal's triangle onto the pins shows the number of different paths that can be taken to get to each bin.
Task
Generate an animated simulation of a Galton device.
Task requirements
The box should have at least 5 pins on the bottom row.
A solution can use graphics or ASCII animation.
Provide a sample of the output/display such as a screenshot.
There can be one or more balls in flight at the same time.
If multiple balls are in flight, ensure they don't interfere with each other.
A solution should allow users to specify the number of balls, or it should run until full or a preset limit.
Optionally, display the number of balls.
|
#Raku
|
Raku
|
my $row-count = 6;
constant $peg = "*";
constant @coin-icons = "\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]";
sub display-board(@positions, @stats is copy, $halfstep) {
my $coin = @coin-icons[$halfstep.Int];
state @board-tmpl = {
# precompute a board
my @tmpl;
sub out(*@stuff) {
@tmpl.push: $[@stuff.join>>.ords.flat];
}
# three lines of space above
for 1..3 {
out " ", " " x (2 * $row-count);
}
# $row-count lines of pegs
for flat ($row-count...1) Z (1...$row-count) -> $spaces, $pegs {
out " ", " " x $spaces, ($peg xx $pegs).join(" "), " " x $spaces;
}
# four lines of space below
for 1..4 {
out " ", " " x (2 * $row-count);
}
@tmpl
}();
my $midpos = $row-count + 2;
my @output;
{
# collect all the output and output it all at once at the end
sub say(Str $foo) {
@output.push: $foo, "\n";
}
sub print(Str $foo) {
@output.push: $foo;
}
# make some space above the picture
say "" for ^10;
my @output-lines = map { [ @$_ ] }, @board-tmpl;
# place the coins
for @positions.kv -> $line, $pos {
next unless $pos.defined;
@output-lines[$line][$pos + $midpos] = $coin.ord;
}
# output the board with its coins
for @output-lines -> @line {
say @line.chrs;
}
# show the statistics
my $padding = 0;
while any(@stats) > 0 {
$padding++;
print " ";
@stats = do for @stats -> $stat {
given $stat {
when 1 {
print "\c[UPPER HALF BLOCK]";
$stat - 1;
}
when * <= 0 {
print " ";
0
}
default {
print "\c[FULL BLOCK]";
$stat - 2;
}
}
}
say "";
}
say "" for $padding...^10;
}
say @output.join("");
}
sub simulate($coins is copy) {
my $alive = True;
sub hits-peg($x, $y) {
if 3 <= $y < 3 + $row-count and -($y - 2) <= $x <= $y - 2 {
return not ($x - $y) %% 2;
}
return False;
}
my @coins = Int xx (3 + $row-count + 4);
my @stats = 0 xx ($row-count * 2);
# this line will dispense coins until turned off.
@coins[0] = 0;
while $alive {
$alive = False;
# if a coin falls through the bottom, count it
given @coins[*-1] {
when *.defined {
@stats[$_ + $row-count]++;
}
}
# move every coin down one row
for ( 3 + $row-count + 3 )...1 -> $line {
my $coinpos = @coins[$line - 1];
@coins[$line] = do if not $coinpos.defined {
Nil
} elsif hits-peg($coinpos, $line) {
# when a coin from above hits a peg, it will bounce to either side.
$alive = True;
($coinpos - 1, $coinpos + 1).pick;
} else {
# if there was a coin above, it will fall to this position.
$alive = True;
$coinpos;
}
}
# let the coin dispenser blink and turn it off if we run out of coins
if @coins[0].defined {
@coins[0] = Nil
} elsif --$coins > 0 {
@coins[0] = 0
}
# smooth out the two halfsteps of the animation
my $start-time;
ENTER { $start-time = now }
my $wait-time = now - $start-time;
sleep 0.1 - $wait-time if $wait-time < 0.1;
for @coin-icons.keys {
sleep $wait-time max 0.1;
display-board(@coins, @stats, $_);
}
}
}
sub MAIN($coins = 20, $peg-lines = 6) {
$row-count = $peg-lines;
simulate($coins);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.