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/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
|
#PowerShell
|
PowerShell
|
$asString = 97..122 | ForEach-Object -Begin {$asArray = @()} -Process {$asArray += [char]$_} -End {$asArray -join('')}
$asString
|
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
|
#Prolog
|
Prolog
|
a_to_z(From, To, L) :-
maplist(atom_codes, [From, To], [[C_From], [C_To]]),
bagof([C], between(C_From, C_To, C), L1),
maplist(atom_codes,L, L1).
|
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
|
#Pop11
|
Pop11
|
printf('Hello world!\n');
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module CheckIt {
Compose = lambda (f, g)->{
=lambda f, g (x)->f(g(x))
}
Add5=lambda (x)->x+5
Division2=lambda (x)->x/2
Add5Div2=compose(Division2, Add5)
Print Add5Div2(15)=10 ' True
}
CheckIt
|
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.
|
#Mathcad
|
Mathcad
|
Composition[f, g][x]
Composition[f, g, h, i][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
|
#PureBasic
|
PureBasic
|
#Spread_Ang = 35
#Scaling_Factor = 0.75
#Deg_to_Rad = #PI / 180
#SizeH = 500
#SizeV = 375
#Init_Size = 100
Procedure drawTree(x1, y1, Size, theta, depth)
Protected x2 = x1 + Cos(theta * #Deg_to_Rad) * Size, y2 = y1 + Sin(theta * #Deg_to_Rad) * Size
LineXY(x1, y1, x2, y2, RGB(255, 255, 255))
If depth <= 0
ProcedureReturn
EndIf
;draw left branch
drawTree(x2, y2, Size * #Scaling_Factor, theta - #Spread_Ang, depth - 1)
;draw right branch
drawTree(x2, y2, Size * #Scaling_Factor, theta + #Spread_Ang, depth - 1)
EndProcedure
OpenWindow(0, 0, 0, #SizeH, #SizeV, "Fractal Tree", #PB_Window_SystemMenu)
Define fractal = CreateImage(#PB_Any, #SizeH, #SizeV, 32)
ImageGadget(0, 0, 0, 0, 0, ImageID(fractal))
If StartDrawing(ImageOutput(fractal))
drawTree(#SizeH / 2, #SizeV, #Init_Size, -90, 9)
StopDrawing()
SetGadgetState(0, ImageID(fractal))
EndIf
Repeat: Until WaitWindowEvent(10) = #PB_Event_CloseWindow
|
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.
|
#Wren
|
Wren
|
import "/dynamic" for Struct
import "/fmt" for Fmt
var Result = Struct.create("Result", ["n", "nine"])
var toNumber = Fn.new { |digits, removeDigit|
var digits2 = digits.toList
if (removeDigit != 0) {
var d = digits2.indexOf(removeDigit)
digits2.removeAt(d)
}
var res = digits2[0]
var i = 1
while (i < digits2.count) {
res = res * 10 + digits2[i]
i = i + 1
}
return res
}
var nDigits = Fn.new { |n|
var res = []
var digits = List.filled(n, 0)
var used = List.filled(9, false)
for (i in 0...n) {
digits[i] = i + 1
used[i] = true
}
while (true) {
var nine = List.filled(9, 0)
for (i in 0...used.count) {
if (used[i]) nine[i] = toNumber.call(digits, i+1)
}
res.add(Result.new(toNumber.call(digits, 0), nine))
var found = false
for (i in n-1..0) {
var d = digits[i]
if (!used[d-1]) {
Fiber.abort("something went wrong with 'used' array")
}
used[d-1] = false
var j = d
while (j < 9) {
if (!used[j]) {
used[j] = true
digits[i] = j + 1
for (k in i + 1...n) {
digits[k] = used.indexOf(false) + 1
used[digits[k]-1] = true
}
found = true
break
}
j = j + 1
}
if (found) break
}
if (!found) break
}
return res
}
for (n in 2..5) {
var rs = nDigits.call(n)
var count = 0
var omitted = List.filled(9, 0)
for (i in 0...rs.count-1) {
var xn = rs[i].n
var rn = rs[i].nine
for (j in i + 1...rs.count) {
var xd = rs[j].n
var rd = rs[j].nine
for (k in 0..8) {
var yn = rn[k]
var yd = rd[k]
if (yn != 0 && yd != 0 && xn/xd == yn/yd) {
count = count + 1
omitted[k] = omitted[k] + 1
if (count <= 12) {
Fmt.print("$d/$d => $d/$d (removed $d)", xn, xd, yn, yd, k+1)
}
}
}
}
}
Fmt.print("$d-digit fractions found:$d, omitted $s\n", n, count, omitted)
}
|
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.
|
#OCaml
|
OCaml
|
open Num
let get_input () =
num_of_int (
try int_of_string Sys.argv.(1)
with _ -> 10)
let get_max_steps () =
try int_of_string Sys.argv.(2)
with _ -> 50
let read_program () =
let line = read_line () in
let words = Str.split (Str.regexp " +") line in
List.map num_of_string words
let is_int n = n =/ (integer_num n)
let run_program num prog =
let replace n =
let rec step = function
| [] -> None
| h :: t ->
let n' = h */ n in
if is_int n' then Some n' else step t in
step prog in
let rec repeat m lim =
Printf.printf " %s\n" (string_of_num m);
if lim = 0 then print_endline "Reached max step limit" else
match replace m with
| None -> print_endline "Finished"
| Some x -> repeat x (lim-1)
in
let max_steps = get_max_steps () in
repeat num max_steps
let () =
let num = get_input () in
let prog = read_program () in
run_program num prog
|
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
|
#BQN
|
BQN
|
Multiply ← ×
|
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.
|
#uBasic.2F4tH
|
uBasic/4tH
|
Print "Index-------Value"
For i = 0 To 60
Print Using "____#"; i; Using "___________#"; FUNC(_fusc(i))
Next
Proc _printLargeFuscs (35500)
End
_fusc
Param (1)
If (a@ = 0) + (a@ = 1) Then Return (a@)
If (a@ % 2) = 0 Then Return (FUNC(_fusc(a@/2)))
Return (FUNC(_fusc((a@ - 1)/2)) + FUNC(_fusc((a@ + 1)/2)))
_printLargeFuscs
Param (1)
Local (4) ' (int) i, f, len, maxLen = 1
e@ = 1
Print "\n\nPrinting all largest Fusc numbers upto "; a@; "\nIndex-------Value"
For b@ = 0 To a@
c@ = FUNC(_fusc(b@))
d@ = Len(Str(c@))
If d@ > e@ Then
e@ = d@
Print Using "____#"; b@; Using "___________#"; c@
EndIf
Next
Return
|
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.
|
#Vala
|
Vala
|
int fusc(int n) {
if (n == 0 || n == 1)
return n;
else if (n % 2 == 0)
return fusc(n / 2);
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2);
}
void main() {
print("The first 61 fusc numbers:\n");
for (int i = 0; i < 61; i++)
print(@"$(fusc(i)) ");
print("\n\nThe fusc numbers whose lengths are greater than those of previous fusc numbers:\n");
print(" n fusc(n)\n");
print("-------------------\n");
var max_length = 0;
for (int i = 0; i < 700000; i++) {
var f = fusc(i);
var length = f.to_string().length;
if (length > max_length) {
max_length = length;
print("%9d %9d\n", i, f);
}
}
}
|
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
|
#OCaml
|
OCaml
|
let e = exp 1.
let pi = 4. *. atan 1.
let sqrttwopi = sqrt (2. *. pi)
module Lanczos = struct
(* Lanczos method *)
(* Coefficients used by the GNU Scientific Library *)
let g = 7.
let c = [|0.99999999999980993; 676.5203681218851; -1259.1392167224028;
771.32342877765313; -176.61502916214059; 12.507343278686905;
-0.13857109526572012; 9.9843695780195716e-6; 1.5056327351493116e-7|]
let rec ag z d =
if d = 0 then c.(0) +. ag z 1
else if d < 8 then c.(d) /. (z +. float d) +. ag z (succ d)
else c.(d) /. (z +. float d)
let gamma z =
let z = z -. 1. in
let p = z +. g +. 0.5 in
sqrttwopi *. p ** (z +. 0.5) *. exp (-. p) *. ag z 0
end
module Stirling = struct
(* Stirling method *)
let gamma z =
sqrttwopi /. sqrt z *. (z /. e) ** z
end
module Stirling2 = struct
(* Extended Stirling method seen in Abramowitz and Stegun *)
let d = [|1./.12.; 1./.288.; -139./.51840.; -571./.2488320.|]
let rec corr z x n =
if n < Array.length d - 1 then d.(n) /. x +. corr z (x *. z) (succ n)
else d.(n) /. x
let gamma z = Stirling.gamma z *. (1. +. corr z z 0)
end
let mirror gma z =
if z > 0.5 then gma z
else pi /. sin (pi *. z) /. gma (1. -. z)
let _ =
Printf.printf "z\t\tLanczos\t\tStirling\tStirling2\n";
for i = 1 to 20 do
let z = float i /. 10. in
Printf.printf "%-10.8g\t%10.8e\t%10.8e\t%10.8e\n"
z
(mirror Lanczos.gamma z)
(mirror Stirling.gamma z)
(mirror Stirling2.gamma z)
done;
for i = 1 to 7 do
let z = 10. *. float i in
Printf.printf "%-10.8g\t%10.8e\t%10.8e\t%10.8e\n"
z
(Lanczos.gamma z)
(Stirling.gamma z)
(Stirling2.gamma z)
done
|
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
|
#Tcl
|
Tcl
|
package require math::linearalgebra
set A {
{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}
}
set b {-0.01 0.61 0.91 0.99 0.60 0.02}
puts -nonewline [math::linearalgebra::show [math::linearalgebra::solveGauss $A $b] "%.2f"]
|
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
|
#Python
|
Python
|
# From the standard library:
from string import ascii_lowercase
# Generation:
lower = [chr(i) for i in range(ord('a'), ord('z') + 1)]
|
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
|
#Quackery
|
Quackery
|
[ [] 26 times [ i^ char a + join ] ] constant is alpha$ ( --> $ )
alpha$ echo$
|
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
|
#Portugol
|
Portugol
|
programa {
// funcao defines a new function
// inicio is the entry point of the program, like main in C
funcao inicio() {
// escreva is used to print stuff to the screen
escreva("Hello, world!\n") // no ';' needed
}
}
|
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.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
Composition[f, g][x]
Composition[f, g, h, i][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.
|
#Maxima
|
Maxima
|
/* built-in */
load(to_poly_solver);
compose_functions([sin, cos]);
/* lambda([%g0],sin(cos(%g0)))*/
/* An implementation, to show a use of buildq */
compose(f, g) := buildq([f, g], lambda([x], 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
|
#Processing
|
Processing
|
void setup() {
size(600, 600);
background(0);
stroke(255);
drawTree(300, 550, 9);
}
void drawTree(float x, float y, int depth) {
float forkAngle = radians(20);
float baseLen = 10.0;
if (depth > 0) {
pushMatrix();
translate(x, y - baseLen * depth);
line(0, baseLen * depth, 0, 0);
rotate(forkAngle);
drawTree(0, 0, depth - 1);
rotate(2 * -forkAngle);
drawTree(0, 0, depth - 1);
popMatrix();
}
}
|
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.
|
#zkl
|
zkl
|
fcn toInt(digits,remove_digit=0){
if(remove_digit!=0) digits=digits.copy().del(digits.index(remove_digit));
digits.reduce(fcn(s,d){ s*10 + d });
}
fcn nDigits(n){
//-- generate numbers with unique digits efficiently
//-- and store them in an array for multiple re-use,
//-- along with an array of the removed-digit values.
res,digits := List(), n.pump(List(),'+(1)); // 1,2,3,4..n
used := List.createLong(n,1).extend(List.createLong(9-n,0));
while(True){
nine:=List.createLong(9,0);
foreach i in (used.len()){ if(used[i]) nine[i]=toInt(digits,i+1) }
res.append(T(toInt(digits),nine));
found:=False;
foreach i in ([n-1..0, -1]){
d:=digits[i];
if(not used[d-1]) println("ack!");
used[d-1]=0;
foreach j in ([d..8]){
if(not used[j]){
used[j]=1;
digits[i]=j+1;
foreach k in ([i+1..n-1]){
digits[k] = used.find(0) + 1;
used[digits[k] - 1]=1;
}
found=True;
break;
}
}
if(found) break;
}//foreach i
if(not found) break;
}//while
res
}
foreach n in ([2..5]){
rs,rsz,count,omitted := nDigits(n),rs.len()-1, 0, List.createLong(9,0);
foreach i in (rsz){
xn,rn := rs[i];
foreach j in ([i+1..rsz]){
xd,rd := rs[j];
foreach k in ([0..8]){
yn,yd := rn[k],rd[k];
if(yn!=0 and yd!=0 and
xn.toFloat()/xd.toFloat() == yn.toFloat()/yd.toFloat()){
count+=1;
omitted[k]+=1;
if(count<=12)
println("%d/%d --> %d/%d (removed %d)".fmt(xn,xd,yn,yd,k+1));
}
}
}
}
println("%d-digit fractions found: %d, omitted %s\n"
.fmt(n,count,omitted.concat(",")));
}
|
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.
|
#PARI.2FGP
|
PARI/GP
|
\\ FRACTRAN
\\ 4/27/16 aev
fractran(val,ft,lim)={
my(ftn=#ft,fti,di,L=List(),j=0);
while(val&&j<lim, listput(L,val);
for(i=1,ftn, fti=ft[i]; di=denominator(fti);
if(val%di==0, break));\\fend i
val= numerator(fti)*val/di; j++);\\wend j
return(Vec(L));
}
{\\ Executing:
my(v=[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]);
print(fractran(2,v,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
|
#Bracmat
|
Bracmat
|
multiply=a b.!arg:(?a.?b)&!a*!b;
out$multiply$(123456789.987654321); { writes 121932631112635269 to standard output }
|
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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
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
|
#Octave
|
Octave
|
function g = lacz_gamma(a, cg=7)
p = [ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, \
771.32342877765313, -176.61502916214059, 12.507343278686905, \
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 ];
x=a;
if ( x < 0.5 )
g = pi / ( sin(pi*x) * lacz_gamma(1.0-x) );
else
x = x - 1.0;
t = p(1);
for i=1:(cg+1)
t = t + p(i+1)/(x+function/double.html">double(i));
endfor
w = x + function/double.html">double(cg) + 0.5;
g = sqrt(2.0*pi) * w**(x+0.5) * exp(-w) * t;
endif
endfunction
for i = 1:10
printf("%f %f\n", gamma(i/3.0), lacz_gamma(i/3.0));
endfor
|
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
|
#TI-83_BASIC
|
TI-83 BASIC
|
[[ 1.00 0.00 0.00 0.00 0.00 0.00 -0.01]
[ 1.00 0.63 0.39 0.25 0.16 0.10 0.61]
[ 1.00 1.26 1.58 1.98 2.49 3.13 0.91]
[ 1.00 1.88 3.55 6.70 12.62 23.80 0.99]
[ 1.00 2.51 6.32 15.88 39.90 100.28 0.60]
[ 1.00 3.14 9.87 31.01 97.41 306.02 0.02]]→[A]
Matr>List(rref([A]),7,L1)
L1
|
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
|
#R
|
R
|
# From constants built into R:
letters
# Or generate the same with:
sapply(97:122, intToUtf8)
|
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
|
#Racket
|
Racket
|
(define lowercase-letters (build-list 26 (lambda (x) (integer->char (+ x (char->integer #\a))))))
|
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
|
#PostScript
|
PostScript
|
%!PS
/Helvetica 20 selectfont
70 700 moveto
(Hello world!) show
showpage
|
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.
|
#min
|
min
|
(1 +) (2 *) concat print
|
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.
|
#MiniScript
|
MiniScript
|
funcA = function(x)
return x * 10
end function
funcB = function(x)
return x + 5
end function
compose = function(f, g)
return function(x)
return f(g(x))
end function
end function
f = compose(@funcA, @funcB)
print f(3) // should be equal to (3+5)*10
|
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
|
#Python
|
Python
|
import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Fractal Tree")
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
fork_angle = 20
base_len = 10.0
if depth > 0:
x2 = x1 + int(math.cos(math.radians(angle)) * depth * base_len)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * base_len)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - fork_angle, depth - 1)
drawTree(x2, y2, angle + fork_angle, depth - 1)
def input(event):
if event.type == pygame.QUIT:
exit(0)
drawTree(300, 550, -90, 9)
pygame.display.flip()
while True:
input(pygame.event.wait())
|
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.
|
#Perl
|
Perl
|
use strict;
use warnings;
use Math::BigRat;
my ($n, @P) = map Math::BigRat->new($_), qw{
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
};
$|=1;
MAIN: for( 1 .. 5000 ) {
print " " if $_ > 1;
my ($pow, $rest) = (0, $n->copy);
until( $rest->is_odd ) {
++$pow;
$rest->bdiv(2);
}
if( $rest->is_one ) {
print "2**$pow";
} else {
#print $n;
}
for my $f_i (@P) {
my $nf_i = $n * $f_i;
next unless $nf_i->is_int;
$n = $nf_i;
next MAIN;
}
last;
}
print "\n";
|
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
|
#Brat
|
Brat
|
multiply = { x, y | x * y }
p multiply 3 14 #Prints 42
|
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.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
System.print("The first 61 numbers in the fusc sequence are:")
var fusc = [0, 1]
var fusc2 = [[0, 0]]
var maxLen = 1
var n = 2
while (n < 20e6) { // limit to indices under 20 million say
var f = (n % 2 == 0) ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]
fusc.add(f)
var len = "%(f)".count
if (len > maxLen) {
maxLen = len
if (n <= 60) {
fusc2.add([n, f])
} else {
System.print("%(Fmt.dc(10, n)) %(Fmt.dc(0, f))")
}
}
if (n == 60 ) {
for (f in fusc) System.write("%(f) ")
System.print("\n\nFirst terms longer than any previous ones for indices < 20,000,000:")
System.print(" Index Value")
for (iv in fusc2) System.print("%(Fmt.d(10, iv[0])) %(iv[1])")
}
n = n + 1
}
|
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
|
#Oforth
|
Oforth
|
import: math
[
676.5203681218851, -1259.1392167224028, 771.32342877765313,
-176.61502916214059, 12.507343278686905, -0.13857109526572012,
9.9843695780195716e-6, 1.5056327351493116e-7
] const: Gamma.Lanczos
: gamma(z)
| i t |
z 0.5 < ifTrue: [ Pi dup z * sin 1.0 z - gamma * / return ]
z 1.0 - ->z
0.99999999999980993 Gamma.Lanczos size loop: i [ i Gamma.Lanczos at z i + / + ]
z Gamma.Lanczos size + 0.5 - ->t
2 Pi * sqrt *
t z 0.5 + powf *
t neg exp * ;
|
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
|
#VBA
|
VBA
|
'Option Base 1
Private Function gauss_eliminate(a As Variant, b As Variant) As Variant
Dim n As Integer: n = UBound(b)
Dim tmp As Variant, m As Integer, mx As Variant
For col = 1 To n
m = col
mx = a(m, m)
For i = col + 1 To n
tmp = Abs(a(i, col))
If tmp > mx Then
m = i
mx = tmp
End If
Next i
If col <> m Then
For j = 1 To UBound(a, 2)
tmp = a(col, j)
a(col, j) = a(m, j)
a(m, j) = tmp
Next j
tmp = b(col)
b(col) = b(m)
b(m) = tmp
End If
For i = col + 1 To n
tmp = a(i, col) / a(col, col)
For j = col + 1 To n
a(i, j) = a(i, j) - tmp * a(col, j)
Next j
a(i, col) = 0
b(i) = b(i) - tmp * b(col)
Next i
Next col
Dim x() As Variant
ReDim x(n)
For col = n To 1 Step -1
tmp = b(col)
For j = n To col + 1 Step -1
tmp = tmp - x(j) * a(col, j)
Next j
x(col) = tmp / a(col, col)
Next col
gauss_eliminate = x
End Function
Public Sub main()
a = [{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}]
b = [{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02}]
Dim s() As String, x() As Variant
ReDim s(UBound(b)), x(UBound(b))
Debug.Print "(";
x = gauss_eliminate(a, b)
For i = 1 To UBound(x)
s(i) = CStr(x(i))
Next i
t = Join(s, ", ")
Debug.Print t; ")"
End Sub
|
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
|
#Raku
|
Raku
|
say my @letters = '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
|
#Potion
|
Potion
|
"Hello world!\n" print
|
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.
|
#Nemerle
|
Nemerle
|
using System;
using System.Console;
using System.Math;
module Composition
{
Compose[T](f : T -> T, g : T -> T, x : T) : T
{
f(g(x))
}
Main() : void
{
def SinAsin = Compose(Sin, Asin, _);
WriteLine(SinAsin(0.5));
}
}
|
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.
|
#Never
|
Never
|
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int
{
let func (i : int) -> int { f(g(i)) }
}
func dec(i : int) -> int { 10 * i }
func succ(i : int) -> int { i + 1 }
func main() -> int
{
let h = compose(dec, succ);
print(h(1));
0
}
|
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
|
#QB64
|
QB64
|
_Title "Fractal Tree"
Const sw% = 640
Const sh% = 480
Screen _NewImage(sw, sh, 8)
Cls , 15: Color 2
Call tree(sw \ 2, sh - 10, _Pi * 1.5, _Pi / 180 * 29, 112, 15)
Sleep
System
Sub tree (x As Integer, y As Integer, initAngle As Double, theta As Double, length As Double, depth As Integer)
Dim As Integer iL, newX, newY, iX, iY, iD
iL = length: iX = x: iY = y: iD = depth
newX = Cos(initAngle) * length + iX
newY = Sin(initAngle) * length + iY
Line (iX, iY)-(newX, newY)
iL = length * .78
iD = iD - 1
If iD > 0 Then
Call tree(newX, newY, initAngle - theta, theta, iL, iD)
Call tree(newX, newY, initAngle + theta, theta, iL, iD)
End If
End Sub
|
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
|
#Quackery
|
Quackery
|
[ $ "turtleduck.qky" loadfile ] now!
[ [ 1 1
30 times
[ tuck + ]
swap join ] constant
do ] is phi ( --> n/d )
[ 2dup 5 1 v< iff
2drop done
2dup 5 1 v/
proper 2drop wide
2dup walk
1 5 turn
2dup phi v/
2dup recurse
-2 5 turn
recurse
1 5 turn
-v fly ] is tree ( n/d --> )
turtle
-1 4 turn
-450 1 fly
500 1 tree
|
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.
|
#Phix
|
Phix
|
without js -- 8s
--with javascript_semantics -- 52s!! (see note)
constant steps = 20,
primes = 45
sequence known_factors = {} -- nb: no specific order
function combine_factors(sequence n)
-- (inverse of as_primes)
atom res = 1
for i=1 to length(n) do
if n[i]!=0 then
res *= power(known_factors[i],n[i])
end if
end for
return res
end function
function as_primes(integer n)
-- eg as_primes(55) -> {5,11} -> indexes to known_factors
if n=1 then return {} end if
sequence pf = prime_factors(n,duplicates:=true)
sequence res = repeat(0,length(known_factors))
for i=1 to length(pf) do
integer k = find(pf[i],known_factors)
if k=0 then
known_factors = append(known_factors,pf[i])
res = append(res,1)
else
res[k] += 1
end if
end for
-- atom chk = combine_factors(res)
-- if chk!=n then ?9/0 end if
return res
end function
function parse(string s)
sequence res = split(s)
for i=1 to length(res) do
sequence sri = scanf(res[i],"%d/%d")
if length(sri)!=1 then ?9/0 end if -- oops!
integer {{n,d}} = sri
res[i] = {as_primes(n),as_primes(d)}
end for
return res
end function
function step(sequence pgm, sequence n)
for pc=1 to length(pgm) do
sequence d = pgm[pc][2], res = n
-- sequence d = pgm[pc][2], res = deep_copy(n) -- (see timing note)
bool ok = true
for f=1 to length(d) do
integer df = d[f]
if df!=0 then
if f>length(n) or df>n[f] then
ok = false
exit
end if
res[f] -= df
end if
end for
if ok then
n = pgm[pc][1]
integer zf = length(n)-length(res)
if zf>0 then res &= repeat(0,zf) end if
for i=1 to length(n) do
res[i] += n[i]
end for
return res
end if
end for
return 0
end function
constant src = "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"
sequence pgm = parse(src)
object n = as_primes(2)
sequence res = {}
for i=1 to steps do
n = step(pgm,n)
if n=0 then exit end if
res = append(res,combine_factors(n))
end for
printf(1,"first %d results: %v\n",{steps,res})
n = as_primes(2)
integer k2 = find(2,known_factors)
sequence n0 = repeat(0,length(known_factors))
res = {}
integer iteration = 1
atom t0 = time()
while length(res)<primes do
n = step(pgm,n)
if n=0 then exit end if
n0[k2] = n[k2]
if n=n0 then -- (ie all non-2 are 0)
-- and the prime itself is ready and waiting...
res = append(res,n[k2])
end if
iteration += 1
end while
printf(1,"first %d primes: %v\n",{primes,res})
printf(1,"%,d iterations in %s\n",{iteration,elapsed(time()-t0)})
|
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
|
#C
|
C
|
double multiply(double a, double b)
{
return 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.
|
#XPL0
|
XPL0
|
func IntLen(N); \Return number of digits in N
int N, L;
[L:= 0;
repeat N:= N/10;
L:= L+1;
until N = 0;
return L;
];
def Size = 1000000;
int Fusc(Size), N, Len, Max;
[Fusc(0):= 0; Fusc(1):= 1;
for N:= 2 to Size-1 do
Fusc(N):= if N&1 then Fusc((N-1)/2) + Fusc((N+1)/2) else Fusc(N/2);
for N:= 0 to 60 do
[IntOut(0, Fusc(N)); ChOut(0, ^ )];
Text(0, "
n fusc(n)
");
Max:= 0;
for N:= 0 to Size-1 do
[Len:= IntLen(Fusc(N));
if Len > Max then
[Max:= Len;
IntOut(0, N); ChOut(0, 9\tab\);
IntOut(0, Fusc(N)); CrLf(0);
];
];
]
|
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.
|
#Yabasic
|
Yabasic
|
maximo = 20000000
dim f(maximo)
fusc()
for i = 0 to 60
print f(i), " ";
next i
print "\n\n Index Value"
d = 0
for i = 0 to maximo-1
if f(i) >= d then
print i using "###,###,###", f(i) using "###,###,###"
if d = 0 d = 1
d = d * 10
end if
next i
end
sub fusc()
f(0) = 0 : f(1) = 1
for n = 2 to maximo-1
if mod(n, 2) then
f(n) = f((n-1) / 2) + f((n+1) / 2)
else
f(n) = f(n / 2)
end if
next n
end sub
|
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
|
#PARI.2FGP
|
PARI/GP
|
gamma(x)
|
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
|
#Pascal
|
Pascal
|
program GammaTest;
{$mode objfpc}{$H+}
uses SysUtils;
function Gamma( x : extended) : extended;
const COF : array [0..14] of extended =
( 0.999999999999997092, // may as well include this in the array
57.1562356658629235,
-59.5979603554754912,
14.1360979747417471,
-0.491913816097620199,
0.339946499848118887e-4,
0.465236289270485756e-4,
-0.983744753048795646e-4,
0.158088703224912494e-3,
-0.210264441724104883e-3,
0.217439618115212643e-3,
-0.164318106536763890e-3,
0.844182239838527433e-4,
-0.261908384015814087e-4,
0.368991826595316234e-5);
const
K = 2.5066282746310005;
PI_OVER_K = PI / K;
var
j : integer;
tmp, w, ser : extended;
reflect : boolean;
begin
reflect := (x < 0.5);
if reflect then w := 1.0 - x else w := x;
tmp := w + 5.2421875;
tmp := (w + 0.5)*Ln(tmp) - tmp;
ser := COF[0];
for j := 1 to 14 do ser := ser + COF[j]/(w + j);
try
if reflect then
result := PI_OVER_K * w * Exp(-tmp) / (Sin(PI*x) * ser)
else
result := K * Exp(tmp) * ser / w;
except
raise SysUtils.Exception.CreateFmt(
'Gamma(%g) is undefined or out of floating-point range', [x]);
end;
end;
// Main routine for testing the Gamma function
var
x, k : extended;
begin
WriteLn( 'Is it seamless at x = 1/2 ?');
x := 0.49999999999999;
WriteLn( SysUtils.Format( 'Gamma(%g) = %g', [x, Gamma(x)]));
x := 0.50000000000001;
WriteLn( SysUtils.Format( 'Gamma(%g) = %g', [x, Gamma(x)]));
WriteLn( 'Test a few values:');
WriteLn( SysUtils.Format( 'Gamma(1) = %g', [Gamma(1)]));
WriteLn( SysUtils.Format( 'Gamma(2) = %g', [Gamma(2)]));
WriteLn( SysUtils.Format( 'Gamma(3) = %g', [Gamma(3)]));
WriteLn( SysUtils.Format( 'Gamma(10) = %g', [Gamma(10)]));
WriteLn( SysUtils.Format( 'Gamma(101) = %g', [Gamma(101)]));
WriteLn( ' 100! = 9.33262154439442E157');
WriteLn( SysUtils.Format( 'Gamma(1/2) = %g', [Gamma(0.5)]));
WriteLn( SysUtils.Format( 'Sqrt(pi) = %g', [Sqrt(PI)]));
WriteLn( SysUtils.Format( 'Gamma(-7/2) = %g', [Gamma(-3.5)]));
(*
Note here a bug or misfeature in Lazarus (doesn't occur in Delphi):
Putting (16.0/105.0)*Sqrt(PI) does not give the required precision.
We have to explicitly define the integers as extended floating-point.
*)
k := extended(16.0)/extended(105.0);
WriteLn( SysUtils.Format( ' (16/105)Sqrt(pi) = %g', [k*Sqrt(PI)]));
WriteLn( SysUtils.Format( 'Gamma(-9/2) = %g', [Gamma(-4.5)]));
k := extended(32.0)/extended(945.0);
WriteLn( SysUtils.Format( '-(32/945)Sqrt(pi) = %g', [-k*Sqrt(PI)]));
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
|
#VBScript
|
VBScript
|
' Gaussian elimination - VBScript
const n=6
dim a(6,6),b(6),x(6),ab
ab=array( 1 , 0 , 0 , 0 , 0 , 0 , -0.01, _
1 , 0.63, 0.39, 0.25, 0.16, 0.10, 0.61, _
1 , 1.26, 1.58, 1.98, 2.49, 3.13, 0.91, _
1 , 1.88, 3.55, 6.70, 12.62, 23.80, 0.99, _
1 , 2.51, 6.32, 15.88, 39.90, 100.28, 0.60, _
1 , 3.14, 9.87, 31.01, 97.41, 306.02, 0.02)
k=-1
for i=1 to n
buf=""
for j=1 to n+1
k=k+1
if j<=n then
a(i,j)=ab(k)
else
b(i)=ab(k)
end if
buf=buf&right(space(8)&formatnumber(ab(k),2),8)&" "
next
wscript.echo buf
next
for j=1 to n
for i=j+1 to n
w=a(j,j)/a(i,j)
for k=j+1 to n
a(i,k)=a(j,k)-w*a(i,k)
next
b(i)=b(j)-w*b(i)
next
next
x(n)=b(n)/a(n,n)
for j=n-1 to 1 step -1
w=0
for i=j+1 to n
w=w+a(j,i)*x(i)
next
x(j)=(b(j)-w)/a(j,j)
next
wscript.echo "solution"
buf=""
for i=1 to n
buf=buf&right(space(8)&formatnumber(x(i),2),8)&vbcrlf
next
wscript.echo buf
|
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
|
#REXX
|
REXX
|
/* REXX ---------------------------------------------------------------
* 08.02.2014 Walter Pachl
*--------------------------------------------------------------------*/
say xrange('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
|
#Ring
|
Ring
|
for i in 'a':'z'
put i
next
|
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
|
#PowerBASIC
|
PowerBASIC
|
#COMPILE EXE
#COMPILER PBCC 6
FUNCTION PBMAIN () AS LONG
CON.PRINT "Hello world!"
CON.WAITKEY$
END FUNCTION
|
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.
|
#NewLISP
|
NewLISP
|
> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> ((compose sin asin) 0.5)
0.5
|
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.
|
#Nim
|
Nim
|
import sugar
proc compose[A,B,C](f: A -> B, g: B -> C): A -> C = (x: A) => f(g(x))
proc plustwo(x: int): int = x + 2
proc minustwo(x: int): int = x - 2
var plusminustwo = compose(plustwo, minustwo)
echo plusminustwo(10)
|
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
|
#R
|
R
|
## Recursive FT plotting
plotftree <- function(x, y, a, d, c) {
x2=y2=0; d2r=pi/180.0; a1 <- a*d2r; d1=0;
if(d<=0) {return()}
if(d>0)
{ d1=d*10.0;
x2=x+cos(a1)*d1;
y2=y+sin(a1)*d1;
segments(x*c, y*c, x2*c, y2*c, col='darkgreen');
plotftree(x2,y2,a-20,d-1,c);
plotftree(x2,y2,a+20,d-1,c);
#return(2);
}
}
## Plotting Fractal Tree. aev 3/27/17
## ord - order/depth, c - scale, xsh - x-shift, fn - file name,
## ttl - plot title.
pFractalTree <- function(ord, c=1, xsh=0, fn="", ttl="") {
cat(" *** START FRT:", date(), "\n");
m=640;
if(fn=="") {pf=paste0("FRTR", ord, ".png")} else {pf=paste0(fn, ".png")};
if(ttl=="") {ttl=paste0("Fractal tree, order - ", ord)};
cat(" *** Plot file -", pf, "title:", ttl, "\n");
##plot(NA, xlim=c(0,m), ylim=c(-m,0), xlab="", ylab="", main=ttl);
plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl);
plotftree(m/2+xsh,100,90,ord,c);
dev.copy(png, filename=pf, width=m, height=m);
dev.off(); graphics.off();
cat(" *** END FRT:",date(),"\n");
}
## Executing:
pFractalTree(9);
pFractalTree(12,0.6,210);
pFractalTree(15,0.35,600);
|
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
|
#Racket
|
Racket
|
#lang racket
(require graphics/turtles)
(define (tree n)
(when (> n 1)
(draw (/ n 2))
(tprompt (split* (turn 60) (turn -60))
(tree (/ n 2)))
(draw (/ n 2))
(turn 5)
(tree (- n 1))))
(turtles #t) (move 100) (turn 90) (move -200)
(tree 35)
(save-turtle-bitmap "tree.png" 'png)
|
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.
|
#Prolog
|
Prolog
|
load(Program, Fractions) :-
re_split("[ ]+", Program, Split), odd_items(Split, TextualFractions),
maplist(convert_frac, TextualFractions, Fractions).
odd_items(L, L) :- L = [_], !. % remove the even elements from a list.
odd_items([X,_|L], [X|R]) :- odd_items(L, R).
convert_frac(Text, Frac) :-
re_matchsub("([0-9]+)/([0-9]+)"/t, Text, Match, []),
Frac is Match.1 rdiv Match.2.
step(_, [], stop) :- !.
step(N, [F|Fs], R) :-
A is N*F,
(integer(A) -> R = A; step(N, Fs, R)).
exec(Prg, Start, Lz) :-
lazy_list(transition, Prg/Start, Lz).
transition(Prg/N0, Prg/N1, N1) :-
step(N0, Prg, N1).
steps(K, Start, Prg, Seq) :-
exec(Prg, Start, Values),
length(Seq, K), Seq = [Start|Rest], prefix(Rest, Values), !.
% The actual PRIMEGEN program follows...
primegen(Prg) :-
load("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", Prg).
primes(N, Primes) :-
primegen(Prg), exec(Prg, 2, Steps),
length(Primes, N), capture_primes(Primes, Steps).
capture_primes([], _) :- !.
capture_primes([P|Ps], [Q|Qs]) :- pow2(Q), !, P is lsb(Q), capture_primes(Ps, Qs).
capture_primes(Ps, [_|Qs]) :- capture_primes(Ps, Qs).
pow2(X) :- X /\ (X-1) =:= 0.
main :-
primegen(Prg), steps(15, 2, Prg, Steps),
format("The first 15 steps from PRIMEGEN are: ~w~n", [Steps]),
primes(20, Primes),
format("By running PRIMEGEN we found these primes: ~w~n", [Primes]),
halt.
?- main.
|
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
|
#C.23
|
C#
|
static double multiply(double a, double b)
{
return 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.
|
#zkl
|
zkl
|
fuscs:=List.createLong(1_000_000, 0); fuscs[1]=1; // we'll just use a big count
foreach n in ([2..fuscs.len()-1]){ // and generate
fuscs[n]=( if(n.isEven()) fuscs[n/2] else fuscs[(n-1)/2] + fuscs[(n+1)/2] )
}
println("First 61 terms of the Stern-Brocot sequence:");
fuscs[0,61].concat(" ").println();
println("\nIndex and value for first term longer than any previous:");
println(" Index : Value");
prevMax:=-1;
foreach n in (fuscs.len()){
f,fd := fuscs[n], f.numDigits;
if(fd>prevMax){ println("%15,d : %,d".fmt(n,f)); prevMax=fd }
}
|
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
|
#Perl
|
Perl
|
use strict;
use warnings;
use constant pi => 4*atan2(1, 1);
use constant e => exp(1);
# Normally would be: use Math::MPFR
# but this will use it if it's installed and ignore otherwise
my $have_MPFR = eval { require Math::MPFR; Math::MPFR->import(); 1; };
sub Gamma {
my $z = shift;
my $method = shift // 'lanczos';
if ($method eq 'lanczos') {
use constant g => 9;
$z < .5 ? pi / sin(pi * $z) / Gamma(1 - $z, $method) :
sqrt(2* pi) *
($z + g - .5)**($z - .5) *
exp(-($z + g - .5)) *
do {
my @coeff = qw{
1.000000000000000174663
5716.400188274341379136
-14815.30426768413909044
14291.49277657478554025
-6348.160217641458813289
1301.608286058321874105
-108.1767053514369634679
2.605696505611755827729
-0.7423452510201416151527e-2
0.5384136432509564062961e-7
-0.4023533141268236372067e-8
};
my ($sum, $i) = (shift(@coeff), 0);
$sum += $_ / ($z + $i++) for @coeff;
$sum;
}
} elsif ($method eq 'taylor') {
$z < .5 ? Gamma($z+1, $method)/$z :
$z > 1.5 ? ($z-1)*Gamma($z-1, $method) :
do {
my $s = 0; ($s *= $z-1) += $_ for qw{
0.00000000000000000002 -0.00000000000000000023 0.00000000000000000141
0.00000000000000000119 -0.00000000000000011813 0.00000000000000122678
-0.00000000000000534812 -0.00000000000002058326 0.00000000000051003703
-0.00000000000369680562 0.00000000000778226344 0.00000000010434267117
-0.00000000118127457049 0.00000000500200764447 0.00000000611609510448
-0.00000020563384169776 0.00000113302723198170 -0.00000125049348214267
-0.00002013485478078824 0.00012805028238811619 -0.00021524167411495097
-0.00116516759185906511 0.00721894324666309954 -0.00962197152787697356
-0.04219773455554433675 0.16653861138229148950 -0.04200263503409523553
-0.65587807152025388108 0.57721566490153286061 1.00000000000000000000
}; 1/$s;
}
} elsif ($method eq 'stirling') {
no warnings qw(recursion);
$z < 100 ? Gamma($z + 1, $method)/$z :
sqrt(2*pi*$z)*($z/e + 1/(12*e*$z))**$z / $z;
} elsif ($method eq 'MPFR') {
my $result = Math::MPFR->new();
Math::MPFR::Rmpfr_gamma($result, Math::MPFR->new($z), 0);
$result;
} else { die "unknown method '$method'" }
}
for my $method (qw(MPFR lanczos taylor stirling)) {
next if $method eq 'MPFR' && !$have_MPFR;
printf "%10s: ", $method;
print join(' ', map { sprintf "%.12f", Gamma($_/3, $method) } 1 .. 10);
print "\n";
}
|
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
|
#Wren
|
Wren
|
import "/trait" for Stepped
var 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]
]
var tb = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]
var tx = [
-0.01, 1.602790394502114, -1.6132030599055613,
1.2454941213714368, -0.4909897195846576, 0.065760696175232
]
var EPSILON = 1e-14 // tolerance required
var gaussPartial = Fn.new { |a0, b0|
var m = b0.count
var a = List.filled(m, null)
var i = 0
for (ai in a0) {
var row = ai.toList
row.add(b0[i])
a[i] = row
i = i + 1
}
for (k in 0...a.count) {
var iMax = 0
var max = -1
for (i in Stepped.ascend(k...m)) {
var row = a[i]
// compute scale factor s = max abs in row
var s = -1
for (j in Stepped.ascend(k...m)) {
var e = row[j].abs
if (e > s) s = e
}
// scale the abs used to pick the pivot
var abs = row[k].abs / s
if (abs > max) {
iMax = i
max = abs
}
}
if (a[iMax][k] == 0) Fiber.abort("Matrix is singular.")
a.swap(k, iMax)
for (i in Stepped.ascend(k + 1...m)) {
for (j in Stepped.ascend(k + 1..m)) {
a[i][j] = a[i][j] - a[k][j] * a[i][k] / a[k][k]
}
a[i][k] = 0
}
}
var x = List.filled(m, 0)
for (i in Stepped.descend(m - 1..0)) {
x[i] = a[i][m]
for (j in Stepped.ascend(i + 1...m)) {
x[i] = x[i] - a[i][j] * x[j]
}
x[i] = x[i] / a[i][i]
}
return x
}
var x = gaussPartial.call(ta, tb)
System.print(x)
var i = 0
for (xi in x) {
if ((tx[i] - xi).abs > EPSILON) {
System.print("Out of tolerance.")
System.print("Expected values are %(tx)")
return
}
i = i + 1
}
|
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
|
#Ruby
|
Ruby
|
p ('a' .. 'z').to_a
p [*'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
|
#Rust
|
Rust
|
fn main() {
// An iterator over the lowercase alpha's
let ascii_iter = (0..26)
.map(|x| (x + b'a') as char);
println!("{:?}", ascii_iter.collect::<Vec<char>>());
}
|
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
|
#PowerShell
|
PowerShell
|
'Hello world!'
|
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.
|
#Objeck
|
Objeck
|
bundle Default {
class Test {
@f : static : (Int) ~ Int;
@g : static : (Int) ~ Int;
function : Main(args : String[]) ~ Nil {
compose := Composer(F(Int) ~ Int, G(Int) ~ Int);
compose(13)->PrintLine();
}
function : F(a : Int) ~ Int {
return a + 14;
}
function : G(a : Int) ~ Int {
return a + 15;
}
function : Compose(x : Int) ~ Int {
return @f(@g(x));
}
function : Composer(f : (Int) ~ Int, g : (Int) ~ Int) ~ (Int) ~ Int {
@f := f;
@g := g;
return Compose(Int) ~ Int;
}
}
}
|
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
|
#Raku
|
Raku
|
my ($width, $height) = (1000,1000); # image dimension
my $scale = 6/10; # branch scale relative to trunk
my $length = 400; # trunk size
say "<?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);
say "</svg>";
multi tree($, $, $length where { $length < 1}, $) {}
multi tree($x, $y, $length, $angle)
{
my ($x2, $y2) = ( $x + $length * $angle.cos, $y + $length * $angle.sin);
say "<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>";
tree($x2, $y2, $length*$scale, $angle + pi/5);
tree($x2, $y2, $length*$scale, $angle - pi/5);
}
|
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.
|
#Python
|
Python
|
from fractions import Fraction
def fractran(n, fstring='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'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
|
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
|
#C.2B.2B
|
C++
|
inline double multiply(double a, double b)
{
return a*b;
}
|
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
|
#Phix
|
Phix
|
with javascript_semantics
sequence c = repeat(0,12)
function gamma(atom z)
atom accm = c[1]
if accm=0 then
accm = sqrt(2*PI)
c[1] = accm
atom k1_factrl = 1 -- (k - 1)!*(-1)^k with 0!==1
for k=2 to 12 do
c[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl
k1_factrl *= -(k-1)
end for
end if
for k=2 to 12 do
accm += c[k]/(z+k-1)
end for
accm *= exp(-(z+12))*power(z+12,z+0.5) -- Gamma(z+1)
return accm/z
end function
procedure sq(atom x, atom mul)
atom p = x*mul
printf(1,"%18.16g,%18.15g\n",{x,p*p})
end procedure
procedure si(atom x)
printf(1,"%18.15f\n",{x})
end procedure
sq(gamma(-3/2),3/4)
sq(gamma(-1/2),-1/2)
sq(gamma(1/2),1)
si(gamma(1))
sq(gamma(3/2),2)
si(gamma(2))
sq(gamma(5/2),4/3)
si(gamma(3))
sq(gamma(7/2),8/15)
si(gamma(4))
|
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
|
#zkl
|
zkl
|
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
a:=GSL.Matrix(6,6).set(
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);
b:=GSL.VectorFromData(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02);
x:=a.AxEQb(b);
x.format(8,5).println();
|
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
|
#S-lang
|
S-lang
|
variable alpha_ch = ['a':'z'], a;
|
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
|
#Scala
|
Scala
|
object Abc extends App {
val lowAlpha = 'a' to 'z' //That's all
// Now several tests
assert(lowAlpha.toSeq == Seq('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'),
"No complete lowercase alphabet.")
assert(lowAlpha.size == 26, "No 26 characters in alphabet")
assert(lowAlpha.start == 'a', "Character 'a' not first char! ???")
assert(lowAlpha.head == 'a', "Character 'a' not heading! ???")
assert(lowAlpha.head == lowAlpha(0), "Heading char is not first char.")
assert(lowAlpha contains 'n', "Character n not present.")
assert(lowAlpha.indexOf('n') == 13, "Character n not on the 14th position.")
assert(lowAlpha.last == lowAlpha(25), "Expected character (z)on the last and 26th pos.")
println(s"Successfully completed without errors. [within ${
scala.compat.Platform.currentTime - executionStart
} ms]")
}
|
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
|
#Processing
|
Processing
|
println("Hello world!");
|
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.
|
#ObjectIcon
|
ObjectIcon
|
# -*- ObjectIcon -*-
#
# The Rosetta Code function composition task, in Object Icon.
# Composition will result in a co-expression.
#
# Object Icon co-expressions are closures: they share the local
# variables of the context in which they are created. In Arizona Icon,
# co-expressions obtain only the *values* of those variables. However,
# this difference, despite its significance, is not really important
# to the notion of composition.
#
# This example is adapted from the Unicon implementation of the
# task. To simplify the example, I have removed support for string
# invocations.
#
import io
procedure main (arglist)
local f, g
# f gets a co-expression that is a composition of three procedures.
f := compose(append_exclamation, string_repeat, double_it)
write(123@f)
# g gets a co-expression that is a composition of a procedure and f.
g := compose(string_repeat, f)
write(123@g)
end
procedure double_it (n)
return n + n
end
procedure string_repeat (x)
return string(x) || string(x)
end
procedure append_exclamation (s)
return s || "!"
end
procedure compose (rfL[])
local x, f, saveSource, fL, cf
every push(fL := [], !rfL)
cf := create {
saveSource := &source
repeat {
x := x@saveSource
saveSource := &source
every f := !fL do {
case type(f) of {
"co-expression": x := x@f
default: x := f(x)
}
}
}
}
# Co-expressions often need to be "primed" before they can be
# used.
@cf
return cf
end
|
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.
|
#Objective-C
|
Objective-C
|
#include <Foundation/Foundation.h>
typedef id (^Function)(id);
// a commodity for "encapsulating" double f(double)
typedef double (*func_t)(double);
Function encapsulate(func_t f) {
return ^(id x) { return @(f([x doubleValue])); };
}
Function compose(Function a, Function b) {
return ^(id x) { return a(b(x)); };
}
// functions outside...
double my_f(double x)
{
return x+1.0;
}
double my_g(double x)
{
return x*x;
}
int main()
{
@autoreleasepool {
Function f = encapsulate(my_f);
Function g = encapsulate(my_g);
Function composed = compose(f, g);
printf("g(2.0) = %lf\n", [g(@2.0) doubleValue]);
printf("f(2.0) = %lf\n", [f(@2.0) doubleValue]);
printf("f(g(2.0)) = %lf\n", [composed(@2.0) doubleValue]);
}
return 0;
}
|
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
|
#Red
|
Red
|
Red [Needs: 'View]
color: brown
width: 9
view/tight/options/flags/no-wait [ ; click image to grow tree
img: image 1097x617 draw [
pen brown line-width 9 line 500x600 500x500] [grow]
] [offset: 0x0] [no-border]
ends: reduce [500x500 pi * 3 / 2] ; list of terminal nodes
da: pi * 30 / 180 ; angle of branches in radians
ea: pi * 5 / 180 ; offset added to angle to break symmetry
l: 200 ; branches initial lenght
scale: 0.7 ; branches scale factor
grow: does [ ; grows branches
l: l * scale
color: 2 * color + leaf / 3
width: width - 1
newends: copy []
foreach [p a] ends [
a1: a + da - ea
p1: p + as-pair l * cos a1 l * sin a1
a2: a - da - ea
p2: p + as-pair l * cos a2 l * sin a2
append img/draw compose/deep [
pen (color) line-width (width) line (p1) (p) (p2)]
append newends reduce [p1 a1 p2 a2]
]
ends: newends
]
|
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
|
#Ring
|
Ring
|
load "guilib.ring"
new qapp
{
win1 = new qwidget() {
setwindowtitle("drawing using qpainter")
setgeometry(100,100,500,500)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
draw()
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
new qpainter() {
begin(p1)
setpen(pen)
sizex = 400
sizey = 200
depth = 10
tree(self, sizex, 0, sizey/2, 90, depth)
endpaint()
}
label1 { setpicture(p1) show() }
func tree myObj, x1, y1, size, angle, depth
myObj{
scale = 0.76
spread = 25
x2 = x1 + size * cos(angle)
y2 = y1 + size * sin(angle)
drawline(x1, y1, x2, y2)
if depth > 0
tree(self, x2, y2, size * scale, angle - spread, depth - 1)
tree(self, x2, y2, size * scale, angle + spread, depth - 1) ok}
|
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.
|
#Quackery
|
Quackery
|
[ $ "bigrat.qky" loadfile ] now!
[ 1 & not ] is even ( n --> b )
[ nip 1 = ] is vint ( n/d --> b )
[ [ dup even while
1 >> again ]
1 = ] is powerof2 ( n --> b )
[ 0 swap
[ dup even while
dip 1+
1 >> again ]
drop ] is lowbit ( n --> n )
[ [] swap nest$
witheach
[ char / over find
space unrot poke
build nested join ] ] is parse$ ( $ --> [ )
[ stack ] is program ( s --> )
[ true temp put
witheach
[ do 2over v*
2dup vint iff
[ false temp replace
conclude ]
else 2drop ]
2swap 2drop
temp take ] is run ( n/d [ --> n/d b )
[ stack ] is primes ( --> s )
$ "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" join
parse$ program put
2 n->v
15 times
[ program share run
drop over echo sp ]
cr
2drop
2 n->v
[] primes put
[ program share run
drop over dup powerof2 iff
[ lowbit primes take
swap join primes put ]
else drop
primes share size 20 = until ]
2drop
primes take echo
program release
|
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
|
#ChucK
|
ChucK
|
fun float multiply (float a, float b)
{
return a * b;
}
// uncomment next line and change values to test
//<<< multiply(16,4) >>>;
|
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
|
#Phixmonti
|
Phixmonti
|
0.577215664901 var gamma
-0.65587807152056 var coeff
-0.042002635033944 var quad
0.16653861138228 var qui
-0.042197734555571 var theSet
def recigamma var z /# n -- n #/
z 6 power theSet *
z 5 power qui *
z 4 power quad *
z 3 power coeff *
z 2 power gamma *
z + + + + +
enddef
/# without var
def recigamma
dup 6 power theSet * swap
dup 5 power qui * swap
dup 4 power quad * swap
dup 3 power coeff * swap
dup 2 power gamma * swap
+ + + + +
enddef
#/
def gammafunc /# n -- n #/
dup 1 == if
else
dup abs 0.5 <= if
recigamma 1 swap /
else
dup 1 - gammafunc swap 1 - *
endif
endif
enddef
0.1 2.1 .1 3 tolist
for
dup print " = " print gammafunc print nl
endfor
|
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
|
#PicoLisp
|
PicoLisp
|
(scl 28)
(de *A
~(flip
(1.00000000000000000000 0.57721566490153286061 -0.65587807152025388108
-0.04200263503409523553 0.16653861138229148950 -0.04219773455554433675
-0.00962197152787697356 0.00721894324666309954 -0.00116516759185906511
-0.00021524167411495097 0.00012805028238811619 -0.00002013485478078824
-0.00000125049348214267 0.00000113302723198170 -0.00000020563384169776
0.00000000611609510448 0.00000000500200764447 -0.00000000118127457049
0.00000000010434267117 0.00000000000778226344 -0.00000000000369680562
0.00000000000051003703 -0.00000000000002058326 -0.00000000000000534812
0.00000000000000122678 -0.00000000000000011813 0.00000000000000000119
0.00000000000000000141 -0.00000000000000000023 0.00000000000000000002 ) ) )
(de gamma (X)
(let (Y (- X 1.0) Sum (car *A))
(for A (cdr *A)
(setq Sum (+ A (*/ Sum Y 1.0))) )
(*/ 1.0 1.0 Sum) ) )
|
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
|
#Scheme
|
Scheme
|
(map integer->char (iota 26 (char->integer #\a)))
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const proc: main is func
local
var string: lower is "";
var char: ch is ' ';
begin
for ch range 'a' to 'z' do
lower &:= ch;
end for;
writeln(lower);
end func;
|
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
|
#ProDOS
|
ProDOS
|
printline Hello world!
|
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.
|
#OCaml
|
OCaml
|
let compose f g x = f (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.
|
#Octave
|
Octave
|
function r = compose(f, g)
r = @(x) f(g(x));
endfunction
r = compose(@exp, @sin);
r(pi/3)
|
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
|
#Ruby
|
Ruby
|
Shoes.app(:title => "Fractal Tree", :width => 600, :height => 600) do
background "#fff"
stroke "#000"
@deg_to_rad = Math::PI / 180.0
def drawTree(x1, y1, angle, depth)
if depth != 0
x2 = x1 + (Math.cos(angle * @deg_to_rad) * depth * 10.0).to_i
y2 = y1 + (Math.sin(angle * @deg_to_rad) * depth * 10.0).to_i
line x1, y1, x2, y2
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1)
end
end
drawTree(300,550,-90,9)
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
|
#Rust
|
Rust
|
//Cargo deps :
// piston = "0.35.0"
// piston2d-graphics = "0.23.0"
// piston2d-opengl_graphics = "0.49.0"
// pistoncore-glutin_window = "0.42.0"
extern crate piston;
extern crate graphics;
extern crate opengl_graphics;
extern crate glutin_window;
use piston::window::WindowSettings;
use piston::event_loop::{Events, EventSettings};
use piston::input::RenderEvent;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{GlGraphics, OpenGL};
use graphics::{clear, line, Context};
const ANG: f64 = 20.0;
const COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];
const LINE_THICKNESS: f64 = 5.0;
const DEPTH: u32 = 11;
fn main() {
let mut window: Window = WindowSettings::new("Fractal Tree", [1024, 768])
.opengl(OpenGL::V3_2)
.exit_on_esc(true)
.build()
.unwrap();
let mut gl = GlGraphics::new(OpenGL::V3_2);
let mut events = Events::new(EventSettings::new());
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
gl.draw(args.viewport(), |c, g| {
clear([1.0, 1.0, 1.0, 1.0], g);
draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);
});
}
}
}
fn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {
let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;
let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;
line(
COLOR,
LINE_THICKNESS * depth as f64 * 0.2,
[x1, y1, x2, y2],
c.transform,
g,
);
if depth > 0 {
draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);
draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);
}
}
|
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.
|
#Racket
|
Racket
|
#lang racket
(define (displaysp x)
(display x)
(display " "))
(define (read-string-list str)
(map string->number
(string-split (string-replace str " " "") ",")))
(define (eval-fractran n list)
(for/or ([e (in-list list)])
(let ([en (* e n)])
(and (integer? en) en))))
(define (show-fractran fr n s)
(printf "First ~a members of fractran(~a):\n" s n)
(displaysp n)
(for/fold ([n n]) ([i (in-range (- s 1))])
(let ([new-n (eval-fractran n fr)])
(displaysp new-n)
new-n))
(void))
(define fractran
(read-string-list
(string-append "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")))
(show-fractran fractran 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
|
#Clay
|
Clay
|
multiply(x,y) = x * y;
|
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
|
#PL.2FI
|
PL/I
|
/* From Rosetta Fortran */
test: procedure options (main);
declare i fixed binary;
on underflow ;
put skip list ('Lanczos', 'Builtin' );
do i = 1 to 10;
put skip list (lanczos_gamma(i/3.0q0), gamma(i/3.0q0) );
end;
lanczos_gamma: procedure (a) returns (float (18)) recursive;
declare a float (18);
declare pi float (18) value (3.14159265358979324E0);
declare cg fixed binary initial ( 7 );
/* these precomputed values are taken by the sample code in Wikipedia, */
/* and the sample itself takes them from the GNU Scientific Library */
declare p(0:8) float (18) static initial
( 0.99999999999980993e0, 676.5203681218851e0, -1259.1392167224028e0,
771.32342877765313e0, -176.61502916214059e0, 12.507343278686905e0,
-0.13857109526572012e0, 9.9843695780195716e-6, 1.5056327351493116e-7 );
declare ( t, w, x ) float (18);
declare i fixed binary;
x = a;
if x < 0.5 then
return ( pi / ( sin(pi*x) * lanczos_gamma(1.0-x) ) );
else
do;
x = x - 1.0;
t = p(0);
do i = 1 to cg+2;
t = t + p(i)/(x+i);
end;
w = x + float(cg) + 0.5;
return ( sqrt(2*pi) * w**(x+0.5) * exp(-w) * t );
end;
end lanczos_gamma;
end test;
|
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
|
#PowerShell
|
PowerShell
|
Add-Type -Path "C:\Program Files (x86)\Math\MathNet.Numerics.3.12.0\lib\net40\MathNet.Numerics.dll"
1..20 | ForEach-Object {[MathNet.Numerics.SpecialFunctions]::Gamma($_ / 10)}
|
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
|
#Sidef
|
Sidef
|
var arr = 'a'..'z';
say arr.join(' ');
|
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
|
#Smalltalk
|
Smalltalk
|
| asciiLower |
asciiLower := String new.
97 to: 122 do: [:asciiCode |
asciiLower := asciiLower , asciiCode asCharacter
].
^asciiLower
|
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
|
#Programming_Language
|
Programming Language
|
print(Hello world!)
|
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.
|
#Oforth
|
Oforth
|
g f
|
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.
|
#Ol
|
Ol
|
(define (compose f g)
(lambda (x) (f (g x))))
;; or:
(define ((compose f g) x) (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
|
#Scala
|
Scala
|
import swing._
import java.awt.{RenderingHints, BasicStroke, Color}
object FractalTree extends SimpleSwingApplication {
val DEPTH = 9
def top = new MainFrame {
contents = new Panel {
preferredSize = new Dimension(600, 500)
override def paintComponent(g: Graphics2D) {
draw(300, 460, -90, DEPTH)
def draw(x1: Int, y1: Int, angle: Double, depth: Int) {
if (depth > 0) {
val x2 = x1 + (math.cos(angle.toRadians) * depth * 10).toInt
val y2 = y1 + (math.sin(angle.toRadians) * depth * 10).toInt
g.setColor(Color.getHSBColor(0.25f - depth * 0.125f / DEPTH, 0.9f, 0.6f))
g.setStroke(new BasicStroke(depth))
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.drawLine(x1, y1, x2, y2)
draw(x2, y2, angle - 20, depth - 1)
draw(x2, y2, angle + 20, depth - 1)
}
}
}
}
}
}
|
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.
|
#Raku
|
Raku
|
sub fractran(@program) {
2, { first Int, map (* * $_).narrow, @program } ... 0
}
say 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>)[^100];
|
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
|
#Clojure
|
Clojure
|
(defn multiply [x y]
(* x y))
(multiply 4 5)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.