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/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Processing | Processing |
int n = 18;
String f1 = "1";
String f2 = "0";
String f3;
void setup(){
size(600,600);
background(255);
translate(10, 10);
createSeries();
}
void createSeries(){
for(int i=0; i<n; i++){
f3 = f2+f1;
f1 = f2;
f2 = f3;
}
drawFractal();
}
void drawFractal(){
char[] a = f3.toCharArray();
for(int i=0; i<a.length; i++){
if(a[i]=='0'){
if(i%2==0){
rotate(PI/2);
}
else{
rotate(-PI/2);
}
}
line(0,0,2,0);
translate(2,0);
}
}
|
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Python | Python | from functools import wraps
from turtle import *
def memoize(obj):
cache = obj.cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def fibonacci_word(n):
assert n > 0
if n == 1:
return "1"
if n == 2:
return "0"
return fibonacci_word(n - 1) + fibonacci_word(n - 2)
def draw_fractal(word, step):
for i, c in enumerate(word, 1):
forward(step)
if c == "0":
if i % 2 == 0:
left(90)
else:
right(90)
def main():
n = 25 # Fibonacci Word to use.
step = 1 # Segment length.
width = 1050 # Width of plot area.
height = 1050 # Height of plot area.
w = fibonacci_word(n)
setup(width=width, height=height)
speed(0)
setheading(90)
left(90)
penup()
forward(500)
right(90)
backward(500)
pendown()
tracer(10000)
hideturtle()
draw_fractal(w, step)
# Save Poscript image.
getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps")
exitonclick()
if __name__ == '__main__':
main() |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #MATLAB_.2F_Octave | MATLAB / Octave |
function lcp = longest_common_dirpath(varargin)
ix = find(varargin{1}=='/');
ca = char(varargin);
flag = all(ca==ca(1,:),1);
for k = length(ix):-1:1,
if all(flag(1:ix(k))); break; end
end
lcp = ca(1,1:ix(k));
end
longest_common_dirpath('/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members')
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #Maxima | Maxima | scommon(a, b) := block([n: min(slength(a), slength(b))],
substring(a, 1, catch(for i thru n do (
if not cequal(charat(a, i), charat(b, i)) then throw(i)), n + 1)))$
commonpath(u, [l]) := block([s: lreduce(scommon, u), c, n],
n: sposition(if length(l) = 0 then "/" else l[1], sreverse(s)),
if integerp(n) then substring(s, 1, slength(s) - n) else ""
)$
commonpath(["c:/files/banister.jpg", "c:/files/bank.xls", "c:/files/banana-recipes.txt"]);
"c:/files" |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Clojure | Clojure | ;; range and filter create lazy seq's
(filter even? (range 0 100))
;; vec will convert any type of seq to an array
(vec (filter even? (vec (range 0 100)))) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Pascal | Pascal | my $x = 0;
recurse($x);
sub recurse ($x) {
print ++$x,"\n";
recurse($x);
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Perl | Perl | my $x = 0;
recurse($x);
sub recurse ($x) {
print ++$x,"\n";
recurse($x);
} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #GFA_Basic | GFA Basic |
' Fizz Buzz
'
FOR i%=1 TO 100
IF i% MOD 15=0
PRINT "FizzBuzz"
ELSE IF i% MOD 3=0
PRINT "Fizz"
ELSE IF i% MOD 5=0
PRINT "Buzz"
ELSE
PRINT i%
ENDIF
NEXT i%
|
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Lua | Lua | function GetFileSize( filename )
local fp = io.open( filename )
if fp == nil then
return nil
end
local filesize = fp:seek( "end" )
fp:close()
return filesize
end |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Maple | Maple | FileTools:-Size( "input.txt" ) |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
FileByteCount["input.txt"]
FileByteCount[FileNameJoin[{$RootDirectory, "input.txt"}]] |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Emacs_Lisp | Emacs Lisp | (defvar input (with-temp-buffer
(insert-file-contents "input.txt")
(buffer-string)))
(with-temp-file "output.txt"
(insert input))
|
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Erlang | Erlang |
-module( file_io ).
-export( [task/0] ).
task() ->
{ok, Contents} = file:read_file( "input.txt" ),
ok = file:write_file( "output.txt", Contents ).
|
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Factor | Factor | USING: assocs combinators formatting kernel math math.functions
math.ranges math.statistics namespaces pair-rocket sequences ;
IN: rosetta-code.fibonacci-word
SYMBOL: 37th-fib-word
: fib ( n -- m )
{
1 => [ 1 ]
2 => [ 1 ]
[ [ 1 - fib ] [ 2 - fib ] bi + ]
} case ;
: fib-word ( n -- seq )
{
1 => [ "1" ]
2 => [ "0" ]
[ [ 1 - fib-word ] [ 2 - fib-word ] bi append ]
} case ;
: nth-fib-word ( n -- seq )
dup 1 =
[ drop "1" ] [ 37th-fib-word get swap fib head ] if ;
: entropy ( seq -- entropy )
[ length ] [ histogram >alist [ second ] map ] bi
[ swap / ] with map
[ dup log 2 log / * ] map-sum
dup 0. = [ neg ] unless ;
37 fib-word 37th-fib-word set
"N" "Length" "Entropy" "%2s %8s %10s\n" printf
37 [1,b] [
dup nth-fib-word [ length ] [ entropy ] bi
"%2d %8d %.8f\n" printf
] each |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #FreeBASIC | FreeBASIC | ' version 25-06-2015
' compile with: fbc -s console
Function calc_entropy(source As String, base_ As Integer) As Double
Dim As Integer i, sourcelen = Len(source), totalchar(255)
Dim As Double prop, entropy
For i = 0 To sourcelen -1
totalchar(source[i]) += 1
Next
For i = 0 To 255
If totalchar(i) = 0 Then Continue For
prop = totalchar(i) / sourcelen
entropy = entropy - (prop * Log (prop) / Log(base_))
Next
Return entropy
End Function
' ------=< MAIN >=------
Dim As String fw1 = "1" , fw2 = "0", fw3
Dim As Integer i, n
Print" N Length Entropy Word"
n = 1
Print Using " ###";n; : Print Using " ###########"; Len(fw1);
Print Using " ##.############### "; calc_entropy(fw1,2);
Print fw1
n = 2
Print Using " ###";n ;: Print Using " ###########"; Len(fw2);
Print Using " ##.############### "; calc_entropy(fw2,2);
Print fw2
For n = 1 To 35
fw1 = "1" : fw2 = "0" ' construct string
For i = 1 To n
fw3 = fw2 + fw1
Swap fw1, fw2 ' swap pointers of fw1 and fw2
Swap fw2, fw3 ' swap pointers of fw2 and fw3
Next
fw1 = "" : fw3 = "" ' free up memory
Print Using " ### ########### ##.############### "; n +2; Len(fw2);_
calc_entropy(fw2, 2);
If Len(fw2) < 55 Then Print fw2 Else Print
Next
Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Crystal | Crystal |
# create tmp fasta file in /tmp/
tmpfile = "/tmp/tmp"+Random.rand.to_s+".fasta"
File.write(tmpfile, ">Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED")
# read tmp fasta file and store to hash
ref = tmpfile
id = seq = ""
fasta = {} of String => String
File.each_line(ref) do |line|
if line.starts_with?(">")
fasta[id] = seq.sub(/\s/, "") if id != ""
id = line.split(/\s/)[0].lstrip(">")
seq = ""
else
seq += line
end
end
fasta[id] = seq.sub(/\s/, "")
# show fasta component
fasta.each { |k,v| puts "#{k}: #{v}"}
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Delphi | Delphi | USING: formatting io kernel sequences ;
IN: rosetta-code.fasta
: process-fasta-line ( str -- )
dup ">" head? [ rest "\n%s: " printf ] [ write ] if ;
: main ( -- )
readln rest "%s: " printf [ process-fasta-line ] each-line ;
MAIN: main |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #ALGOL_68 | ALGOL 68 | BEGIN # construct some Farey Sequences and calculate their lengths #
# prints an element of a Farey Sequence #
PROC print element = ( INT a, b )VOID:
print( ( " ", whole( a, 0 ), "/", whole( b, 0 ) ) );
# returns the length of the Farey Sequence of order n, optionally #
# printing it #
PROC farey sequence length = ( INT n, BOOL print sequence )INT:
IF n < 1 THEN 0
ELSE
INT a := 0, b := 1, c := 1, d := n;
IF print sequence THEN
print( ( whole( n, -2 ), ":" ) );
print element( a, b )
FI;
INT length := 1;
WHILE c <= n DO
INT k = ( n + b ) OVER d;
INT old a = a, old b = b;
a := c;
b := d;
c := ( k * c ) - old a;
d := ( k * d ) - old b;
IF print sequence THEN print element( a, b ) FI;
length +:= 1
OD;
IF print sequence THEN print( ( newline ) ) FI;
length
FI # farey sequence length # ;
# task #
FOR i TO 11 DO farey sequence length( i, TRUE ) OD;
FOR n FROM 100 BY 100 TO 1 000 DO
print( ( "Farey Sequence of order ", whole( n, -4 )
, " has length: ", whole( farey sequence length( n, FALSE ), -6 )
, newline
)
)
OD
END |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #AppleScript | AppleScript | -- thueMorse :: Int -> [Int]
on thueMorse(base)
-- Non-finite sequence of Thue-Morse terms for a given base.
fmapGen(baseDigitsSumModBase(base), enumFrom(0))
end thueMorse
-- baseDigitsSumModBase :: Int -> Int -> Int
on baseDigitsSumModBase(b)
script
on |λ|(n)
script go
on |λ|(x)
if 0 < x then
Just(Tuple(x mod b, x div b))
else
Nothing()
end if
end |λ|
end script
sum(unfoldl(go, n)) mod b
end |λ|
end script
end baseDigitsSumModBase
-------------------------- TEST ---------------------------
on run
script rjust
on |λ|(x)
justifyRight(2, space, str(x))
end |λ|
end script
script test
on |λ|(n)
|λ|(n) of rjust & " -> " & ¬
showList(map(rjust, take(25, thueMorse(n))))
end |λ|
end script
unlines({"First 25 fairshare terms for N players:"} & ¬
map(test, {2, 3, 5, 11}))
end run
-------------------- GENERIC FUNCTIONS --------------------
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
-- Constructor for a pair of values, possibly of two different types.
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- enumFrom :: Enum a => a -> [a]
on enumFrom(x)
script
property v : missing value
property blnNum : class of x is not text
on |λ|()
if missing value is not v then
if blnNum then
set v to 1 + v
else
set v to succ(v)
end if
else
set v to x
end if
return v
end |λ|
end script
end enumFrom
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmapGen(f, gen)
script
property g : mReturn(f)
on |λ|()
set v to gen's |λ|()
if v is missing value then
v
else
g's |λ|(v)
end if
end |λ|
end script
end fmapGen
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- intercalateS :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, s)
if n > length of s then
text -n thru -1 of ((replicate(n, cFiller) as text) & s)
else
s
end if
end justifyRight
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(",", map(my str, xs)) & "]"
end showList
-- str :: a -> String
on str(x)
x as string
end str
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- > unfoldl (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
-- > [1,2,3,4,5,6,7,8,9,10]
-- unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
on unfoldl(f, v)
set xr to Tuple(v, v) -- (value, remainder)
set xs to {}
tell mReturn(f)
repeat -- Function applied to remainder.
set mb to |λ|(|2| of xr)
if Nothing of mb then
exit repeat
else -- New (value, remainder) tuple,
set xr to Just of mb
-- and value appended to output list.
set xs to ({|1| of xr} & xs)
end if
end repeat
end tell
return xs
end unfoldl
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #D | D | import std.algorithm : fold;
import std.conv : to;
import std.exception : enforce;
import std.format : formattedWrite;
import std.numeric : cmp, gcd;
import std.range : iota;
import std.stdio;
import std.traits;
auto abs(T)(T val)
if (isNumeric!T) {
if (val < 0) {
return -val;
}
return val;
}
struct Frac {
long num;
long denom;
enum ZERO = Frac(0, 1);
enum ONE = Frac(1, 1);
this(long n, long d) in {
enforce(d != 0, "Parameter d may not be zero.");
} body {
auto nn = n;
auto dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
auto g = gcd(abs(nn), abs(dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
auto opBinary(string op)(Frac rhs) const {
static if (op == "+" || op == "-") {
return mixin("Frac(num*rhs.denom"~op~"denom*rhs.num, rhs.denom*denom)");
} else if (op == "*") {
return Frac(num*rhs.num, denom*rhs.denom);
}
}
auto opUnary(string op : "-")() const {
return Frac(-num, denom);
}
int opCmp(Frac rhs) const {
return cmp(cast(real) this, cast(real) rhs);
}
bool opEquals(Frac rhs) const {
return num == rhs.num && denom == rhs.denom;
}
void toString(scope void delegate(const(char)[]) sink) const {
if (denom == 1) {
formattedWrite(sink, "%d", num);
} else {
formattedWrite(sink, "%d/%s", num, denom);
}
}
T opCast(T)() const if (isFloatingPoint!T) {
return cast(T) num / denom;
}
}
auto abs(Frac f) {
if (f.num >= 0) {
return f;
}
return -f;
}
auto bernoulli(int n) in {
enforce(n >= 0, "Parameter n must not be negative.");
} body {
Frac[] a;
a.length = n+1;
a[0] = Frac.ZERO;
foreach (m; 0..n+1) {
a[m] = Frac(1, m+1);
foreach_reverse (j; 1..m+1) {
a[j-1] = (a[j-1] - a[j]) * Frac(j, 1);
}
}
if (n != 1) {
return a[0];
}
return -a[0];
}
auto binomial(int n, int k) in {
enforce(n>=0 && k>=0 && n>=k);
} body {
if (n==0 || k==0) return 1;
auto num = iota(k+1, n+1).fold!"a*b"(1);
auto den = iota(2, n-k+1).fold!"a*b"(1);
return num / den;
}
Frac[] faulhaberTriangle(int p) {
Frac[] coeffs;
coeffs.length = p+1;
coeffs[0] = Frac.ZERO;
auto q = Frac(1, p+1);
auto sign = -1;
foreach (j; 0..p+1) {
sign *= -1;
coeffs[p - j] = q * Frac(sign, 1) * Frac(binomial(p+1, j), 1) * bernoulli(j);
}
return coeffs;
}
void main() {
foreach (i; 0..10) {
auto coeffs = faulhaberTriangle(i);
foreach (coeff; coeffs) {
writef("%5s ", coeff.to!string);
}
writeln;
}
writeln;
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #Factor | Factor | USING: formatting kernel math math.combinatorics math.extras
math.functions regexp sequences ;
: faulhaber ( p -- seq )
1 + dup recip swap dup <iota>
[ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ;
: (poly>str) ( seq -- str )
reverse [ 1 + "%un^%d" sprintf ] map-index reverse " + " join ;
: clean-up ( str -- str' )
R/ n\^1\z/ "n" re-replace ! Change n^1 to n.
R/ 1n/ "n" re-replace ! Change 1n to n.
R/ \+ -/ "- " re-replace ! Change + - to - .
R/ [+-] 0n(\^\d+ )?/ "" re-replace ; ! Remove terms of zero.
: poly>str ( seq -- str ) (poly>str) clean-up ;
10 [ dup faulhaber poly>str "%d: %s\n" printf ] each-integer |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(de isprime (N)
(cache '(NIL) N
(if (== N 2)
T
(and
(> N 1)
(bit? 1 N)
(let (Q (dec N) N1 (dec N) K 0 X)
(until (bit? 1 Q)
(setq
Q (>> 1 Q)
K (inc K) ) )
(catch 'composite
(do 16
(loop
(setq X
(**Mod
(rand 2 (min (dec N) 1000000000000))
Q
N ) )
(T (or (=1 X) (= X N1)))
(T
(do K
(setq X (**Mod X 2 N))
(when (=1 X) (throw 'composite))
(T (= X N1) T) ) )
(throw 'composite) ) )
(throw 'composite T) ) ) ) ) ) )
(de gcd (A B)
(until (=0 B)
(let M (% A B)
(setq A B B M) ) )
(abs A) )
(de g (A)
(% (+ (% (* A A) N) C) N) )
(de pollard-brent (N)
(let
(A (dec N)
Y (rand 1 (min A 1000000000000000000))
C (rand 1 (min A 1000000000000000000))
M (rand 1 (min A 1000000000000000000))
G 1
R 1
Q 1 )
(ifn (bit? 1 N)
2
(loop
(NIL (=1 G))
(setq X Y)
(do R
(setq Y (g Y)) )
(zero K)
(loop
(NIL (and (> R K) (=1 G)))
(setq YS Y)
(do (min M (- R K))
(setq
Y (g Y)
Q (% (* Q (abs (- X Y))) N) ) )
(setq
G (gcd Q N)
K (+ K M) )
)
(setq R (* R 2)) )
(when (== G N)
(loop
(NIL (> G 1))
(setq
YS (g YS)
G (gcd (abs (- X YS)) N) ) ) )
(if (== G N)
NIL
G ) ) ) )
(de factors (N)
(sort
(make
(loop
(setq N (/ N (link (pollard-brent N))))
(T (isprime N)) )
(link N) ) ) )
(de fermat (N)
(inc (** 2 (** 2 N))) )
(for (N 0 (>= 8 N) (inc N))
(println N ': (fermat N)) )
(prinl)
(for (N 0 (>= 8 N) (inc N))
(let N (fermat N)
(println
N
':
(if (isprime N) 'PRIME (factors N)) ) ) ) |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Python | Python | def factors(x):
factors = []
i = 2
s = int(x ** 0.5)
while i < s:
if x % i == 0:
factors.append(i)
x = int(x / i)
s = int(x ** 0.5)
i += 1
factors.append(x)
return factors
print("First 10 Fermat numbers:")
for i in range(10):
fermat = 2 ** 2 ** i + 1
print("F{} = {}".format(chr(i + 0x2080) , fermat))
print("\nFactors of first few Fermat numbers:")
for i in range(10):
fermat = 2 ** 2 ** i + 1
fac = factors(fermat)
if len(fac) == 1:
print("F{} -> IS PRIME".format(chr(i + 0x2080)))
else:
print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac)) |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #BASIC256 | BASIC256 | # Rosetta Code problem: https://www.rosettacode.org/wiki/Fibonacci_n-step_number_sequences
# by Jjuanhdez, 06/2022
arraybase 1
print " fibonacci =>";
dim a = {1,1}
call fib (a)
print " tribonacci =>";
dim a = {1,1,2}
call fib (a)
print " tetranacci =>";
dim a = {1,1,2,4}
call fib (a)
print " pentanacci =>";
dim a = {1,1,2,4,8}
call fib (a)
print " hexanacci =>";
dim a = {1,1,2,4,8,16}
call fib (a)
print " heptanacci =>";
dim a = {1,1,2,4,8,16,32}
call fib (a)
print " octonacci =>";
dim a = {1,1,2,4,8,16,32,64}
call fib (a)
print " nonanacci =>";
dim a = {1,1,2,4,8,16,32,64,128}
call fib (a)
print " decanacci =>";
dim a = {1,1,2,4,8,16,32,64,128,256}
call fib (a)
print " lucas =>";
dim a = {2,1}
call fib (a)
end
subroutine fib (a)
dim f(24) fill 0
b = 0
for x = 1 to a[?]
b += 1
f[x] = a[x]
next x
for i = b to 13 + b
print rjust(f[i-b+1], 5);
if i <> 13 + b then print ","; else print ", ..."
for j = (i-b+1) to i
f[i+1] = f[i+1] + f[j]
next j
next i
end subroutine |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Perl | Perl | use strict;
use warnings;
use Math::AnyNum 'sqr';
my $a1 = 1.0;
my $a2 = 0.0;
my $d1 = 3.2;
print " i δ\n";
for my $i (2..13) {
my $a = $a1 + ($a1 - $a2)/$d1;
for (1..10) {
my $x = 0;
my $y = 0;
for (1 .. 2**$i) {
$y = 1 - 2 * $y * $x;
$x = $a - sqr($x);
}
$a -= $x/$y;
}
$d1 = ($a1 - $a2) / ($a - $a1);
($a2, $a1) = ($a1, $a);
printf "%2d %17.14f\n", $i, $d1;
} |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Phix | Phix | constant maxIt = 13,
maxItJ = 10
atom a1 = 1.0,
a2 = 0.0,
d1 = 3.2
puts(1," i d\n")
for i=2 to maxIt do
atom a = a1 + (a1 - a2) / d1
for j=1 to maxItJ do
atom x = 0, y = 0
for k=1 to power(2,i) do
y = 1 - 2*y*x
x = a - x*x
end for
a = a - x/y
end for
atom d = (a1-a2)/(a-a1)
printf(1,"%2d %.8f\n",{i,d})
d1 = d
a2 = a1
a1 = a
end for
|
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Ring | Ring |
# Project : File extension is in extensions list
extensions = [".zip", ".rar", ".7z", ".gz", ".archive", ".a##", ".tar.bz2"]
filenames = ["MyData.a##", "MyData.tar.gz", "MyData.gzip", "MyData.7z.backup",
"MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"]
for n = 1 to len(filenames)
flag = 0
for m = 1 to len(extensions)
if right(filenames[n], len(extensions[m])) = extensions[m]
flag = 1
see filenames[n] + " -> " + extensions[m] + " -> " + " true" + nl
exit
ok
next
if flag = 0
see filenames[n] + " -> " + "false" + nl
ok
next
|
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Ruby | Ruby | def is_ext(filename, extensions)
if filename.respond_to?(:each)
filename.each do |fn|
is_ext(fn, extensions)
end
else
fndc = filename.downcase
extensions.each do |ext|
bool = fndc.end_with?(?. + ext.downcase)
puts "%20s : %s" % [filename, bool] if bool
end
end
end
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #PowerShell | PowerShell |
$modificationTime = (Get-ChildItem file.txt).LastWriteTime
Set-ItemProperty file.txt LastWriteTime (Get-Date)
$LastReadTime = (Get-ChildItem file.txt).LastAccessTime
Set-ItemProperty file.txt LastAccessTime(Get-Date)
$CreationTime = (Get-ChildItem file.txt).CreationTime
Set-ItemProperty file.txt CreationTime(Get-Date)
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #PureBasic | PureBasic | Debug FormatDate("%yyyy/%mm/%dd", GetFileDate("file.txt",#PB_Date_Modified))
SetFileDate("file.txt",#PB_Date_Modified,Date(1987, 10, 23, 06, 43, 15))
Debug FormatDate("%yyyy/%mm/%dd - %hh:%ii:%ss", GetFileDate("file.txt",#PB_Date_Modified)) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Python | Python | import os
#Get modification time:
modtime = os.path.getmtime('filename')
#Set the access and modification times:
os.utime('path', (actime, mtime))
#Set just the modification time:
os.utime('path', (os.path.getatime('path'), mtime))
#Set the access and modification times to the current time:
os.utime('path', None) |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #R | R |
## Fibonacci word/fractal 2/20/17 aev
## Create Fibonacci word order n
fibow <- function(n) {
t2="0"; t1="01"; t="";
if(n<2) {n=2}
for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t}
return(t)
}
## Plot Fibonacci word/fractal:
## n - word order, w - width, h - height, d - segment size, clr - color.
pfibofractal <- function(n, w, h, d, clr) {
dx=d; x=y=x2=y2=tx=dy=nr=0;
if(n<2) {n=2}
fw=fibow(n); nf=nchar(fw);
pf = paste0("FiboFractR", n, ".png");
ttl=paste0("Fibonacci word/fractal, n=",n);
cat(ttl,"nf=", nf, "pf=", pf,"\n");
plot(NA, xlim=c(0,w), ylim=c(-h,0), xlab="", ylab="", main=ttl)
for (i in 1:nf) {
fwi=substr(fw, i, i);
x2=x+dx; y2=y+dy;
segments(x, y, x2, y2, col=clr); x=x2; y=y2;
if(fwi=="0") {tx=dx; nr=i%%2;
if(nr==0) {dx=-dy;dy=tx} else {dx=dy;dy=-tx}}
}
dev.copy(png, filename=pf, width=w, height=h); # plot to png-file
dev.off(); graphics.off(); # Cleaning
}
## Executing:
pfibofractal(23, 1000, 1000, 1, "navy")
pfibofractal(25, 2300, 1000, 1, "red")
|
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Racket | Racket | #lang racket
(require "Fibonacci-word.rkt")
(require graphics/value-turtles)
(define word-order 23) ; is a 3k+2 fractal, shaped like an n
(define height 420)
(define width 600)
(define the-word
(parameterize ((f-word-max-length #f))
(F-Word word-order)))
(for/fold ((T (turtles width height
0 height ; in BL corner
(/ pi -2)))) ; point north
((i (in-naturals))
(j (in-string (f-word-str the-word))))
(match* (i j)
((_ #\1) (draw 1 T))
(((? even?) #\0) (turn -90 (draw 1 T)))
((_ #\0) (turn 90 (draw 1 T))))) |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #MUMPS | MUMPS | FCD
NEW D,SEP,EQ,LONG,DONE,I,J,K,RETURN
SET D(1)="/home/user1/tmp/coverage/test"
SET D(2)="/home/user1/tmp/covert/operator"
SET D(3)="/home/user1/tmp/coven/members"
SET SEP="/"
SET LONG=D(1)
SET DONE=0
FOR I=1:1:$LENGTH(LONG,SEP) QUIT:DONE SET EQ(I)=1 FOR J=2:1:3 SET EQ(I)=($PIECE(D(J),SEP,I)=$PIECE(LONG,SEP,I))&EQ(I) SET DONE='EQ(I) QUIT:'EQ(I)
SET RETURN=""
FOR K=1:1:I-1 Q:'EQ(K) SET:EQ(K) $PIECE(RETURN,SEP,K)=$PIECE(LONG,SEP,K)
WRITE !,"For the paths:" FOR I=1:1:3 WRITE !,D(I)
WRITE !,"The longest common directory is: ",RETURN
KILL D,SEP,EQ,LONG,DONE,I,J,K,RETURN
QUIT |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #Nim | Nim | import strutils
proc commonprefix(paths: openarray[string], sep = "/"): string =
if paths.len == 0: return ""
block outer:
for i in 0 ..< paths[0].len:
result = paths[0][0 .. i]
for path in paths:
if not path.startsWith(result):
break outer
result = result[0 .. result.rfind(sep)]
echo commonprefix(@["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]) |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #CoffeeScript | CoffeeScript | [1..10].filter (x) -> not (x%2) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Phix | Phix | atom t1 = time()+1
integer depth = 0
procedure recurse()
if time()>t1 then
?depth
t1 = time()+1
end if
depth += 1
-- only 1 of these will ever get called, of course...
recurse()
recurse()
recurse()
end procedure
recurse()
|
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PHP | PHP | <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a(); |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Gleam | Gleam | import gleam/int
import gleam/io
import gleam/iterator
pub fn main() {
iterator.range(1, 101)
|> iterator.map(to_fizzbuzz)
|> iterator.map(io.println)
|> iterator.run
}
fn to_fizzbuzz(n: Int) -> String {
case n % 3, n % 5 {
0, 0 -> "FizzBuzz"
0, _ -> "Fizz"
_, 0 -> "Buzz"
_, _ -> int.to_string(n)
}
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #MATLAB_.2F_Octave | MATLAB / Octave | d1 = dir('input.txt');
d2 = dir('/input.txt');
fprintf('Size of input.txt is %d bytes\n', d1.bytes)
fprintf('Size of /input.txt is %d bytes\n', d2.bytes) |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #MAXScript | MAXScript | -- Returns filesize in bytes or 0 if the file is missing
getFileSize "index.txt"
getFileSize "\index.txt" |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Mirah | Mirah | import java.io.File
puts File.new('file-size.mirah').length()
puts File.new("./#{File.separator}file-size.mirah").length() |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Euphoria | Euphoria | include std/io.e
write_lines("output.txt", read_lines("input.txt")) |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #F.23 | F# | open System.IO
let copyFile fromTextFileName toTextFileName =
let inputContent = File.ReadAllText fromTextFileName
inputContent |> fun text -> File.WriteAllText(toTextFileName, text)
[<EntryPoint>]
let main argv =
copyFile "input.txt" "output.txt"
0
|
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
)
// From http://rosettacode.org/wiki/Entropy#Go
func entropy(s string) float64 {
m := map[rune]float64{}
for _, r := range s {
m[r]++
}
hm := 0.
for _, c := range m {
hm += c * math.Log2(c)
}
l := float64(len(s))
return math.Log2(l) - hm/l
}
const F_Word1 = "1"
const F_Word2 = "0"
func FibonacciWord(n int) string {
a, b := F_Word1, F_Word2
for ; n > 1; n-- {
a, b = b, b+a
}
return a
}
func FibonacciWordGen() <-chan string {
ch := make(chan string)
go func() {
a, b := F_Word1, F_Word2
for {
ch <- a
a, b = b, b+a
}
}()
return ch
}
func main() {
fibWords := FibonacciWordGen()
fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word")
n := 1
for ; n < 10; n++ {
s := <-fibWords
// Just to show the function and generator do the same thing:
if s2 := FibonacciWord(n); s != s2 {
fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
}
fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s)
}
for ; n <= 37; n++ {
s := <-fibWords
fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s))
}
} |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Factor | Factor | USING: formatting io kernel sequences ;
IN: rosetta-code.fasta
: process-fasta-line ( str -- )
dup ">" head? [ rest "\n%s: " printf ] [ write ] if ;
: main ( -- )
readln rest "%s: " printf [ process-fasta-line ] each-line ;
MAIN: main |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Forth | Forth | 1024 constant max-Line
char > constant marker
: read-lines begin pad max-line >r over r> swap
read-line throw
while pad dup c@ marker =
if cr 1+ swap type ." : "
else swap type
then
repeat drop ;
: Test s" ./FASTA.txt" r/o open-file throw
read-lines
close-file throw
cr ;
Test
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function checkNoSpaces(s As String) As Boolean
For i As UInteger = 0 To Len(s) - 1
If s[i] = 32 OrElse s[i] = 9 Then Return False '' check for spaces or tabs
Next
Return True
End Function
Open "input.fasta" For Input As # 1
Dim As String ln, seq
Dim first As Boolean = True
While Not Eof(1)
Line Input #1, ln
If Left(ln, 1) = ">" Then
If Not first Then Print
Print Mid(ln, 2); ": ";
If first Then first = False
ElseIf first Then
Print: Print "Error : File does not begin with '>'";
Exit While
Else
If checkNoSpaces(ln) Then
Print ln;
Else
Print : Print "Error : Sequence contains space(s)";
Exit While
End If
End If
Wend
Close #1
Print : Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Fast_Fourier_transform | Fast Fourier transform | Task
Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #11l | 11l | F fft(x)
V n = x.len
I n <= 1
R x
V even = fft(x[(0..).step(2)])
V odd = fft(x[(1..).step(2)])
V t = (0 .< n I/ 2).map(k -> exp(-2i * math:pi * k / @n) * @odd[k])
R (0 .< n I/ 2).map(k -> @even[k] + @t[k]) [+]
(0 .< n I/ 2).map(k -> @even[k] - @t[k])
print(fft([Complex(1.0), 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]).map(f -> ‘#1.3’.format(abs(f))).join(‘ ’)) |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #APL | APL |
farey←{{⍵[⍋⍵]}∪∊{(0,⍳⍵)÷⍵}¨⍳⍵}
fract←{1∧(0(⍵=0)+⊂⍵)*1 ¯1}
print←{{(⍕⍺),'/',(⍕⍵),' '}⌿↑fract farey ⍵}
|
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #AWK | AWK |
# syntax: GAWK -f FAREY_SEQUENCE.AWK
BEGIN {
for (i=1; i<=11; i++) {
farey(i); printf("\n")
}
for (i=100; i<=1000; i+=100) {
printf(" %d items\n",farey(i))
}
exit(0)
}
function farey(n, a,aa,b,bb,c,cc,d,dd,items,k) {
a = 0; b = 1; c = 1; d = n
printf("%d:",n)
if (n <= 11) {
printf(" %d/%d",a,b)
}
while (c <= n) {
k = int((n+b)/d)
aa = c; bb = d; cc = k*c-a; dd = k*d-b
a = aa; b = bb; c = cc; d = dd
items++
if (n <= 11) {
printf(" %d/%d",a,b)
}
}
return(1+items)
}
|
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Arturo | Arturo | thueMorse: function [base, howmany][
i: 0
result: new []
while [howmany > size result][
'result ++ (sum digits.base:base i) % base
i: i + 1
]
return result
]
loop [2 3 5 11] 'b ->
print [
(pad.right "Base "++(to :string b) 7)++" =>"
join.with:" " map to [:string] thueMorse b 25 'x -> pad x 2
] |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #C | C | #include <stdio.h>
#include <stdlib.h>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
int i;
printf("Base %2d:", base);
for (i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
int *cnt = calloc(base, sizeof(int));
int i, minTurn, maxTurn, portion;
if (NULL == cnt) {
printf("Failed to allocate space to determine the spread of turns.\n");
return;
}
for (i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
minTurn = INT_MAX;
maxTurn = INT_MIN;
portion = 0;
for (i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
free(cnt);
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
} |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #F.23 | F# |
// Generate Faulhaber's Triangle. Nigel Galloway: May 8th., 2018
let Faulhaber=let fN n = (1N - List.sum n)::n
let rec Faul a b=seq{let t = fN (List.mapi(fun n g->b*g/BigRational.FromInt(n+2)) a)
yield t
yield! Faul t (b+1N)}
Faul [] 0N
|
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | n := X(Rationals, "n");
sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1);
sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1);
ForAll([0 .. 20], k -> sum1(k) = sum2(k));
for p in [0 .. 9] do
Print(sum1(p), "\n");
od;
n
1/2*n^2+1/2*n
1/3*n^3+1/2*n^2+1/6*n
1/4*n^4+1/2*n^3+1/4*n^2
1/5*n^5+1/2*n^4+1/3*n^3-1/30*n
1/6*n^6+1/2*n^5+5/12*n^4-1/12*n^2
1/7*n^7+1/2*n^6+1/2*n^5-1/6*n^3+1/42*n
1/8*n^8+1/2*n^7+7/12*n^6-7/24*n^4+1/12*n^2
1/9*n^9+1/2*n^8+2/3*n^7-7/15*n^5+2/9*n^3-1/30*n
1/10*n^10+1/2*n^9+3/4*n^8-7/10*n^6+1/2*n^4-3/20*n^2 |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #Raku | Raku | use ntheory:from<Perl5> <factor>;
my @Fermats = (^Inf).map: 2 ** 2 ** * + 1;
my $sub = '₀';
say "First 10 Fermat numbers:";
printf "F%s = %s\n", $sub++, $_ for @Fermats[^10];
$sub = '₀';
say "\nFactors of first few Fermat numbers:";
for @Fermats[^9].map( {"$_".&factor} ) -> $f {
printf "Factors of F%s: %s %s\n", $sub++, $f.join(' '), $f.elems == 1 ?? '- prime' !! ''
} |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Batch_File | Batch File |
@echo off
echo Fibonacci Sequence:
call:nfib 1 1
echo.
echo Tribonacci Sequence:
call:nfib 1 1 2
echo.
echo Tetranacci Sequence:
call:nfib 1 1 2 4
echo.
echo Lucas Numbers:
call:nfib 2 1
echo.
pause>nul
exit /b
:nfib
setlocal enabledelayedexpansion
for %%i in (%*) do (
set /a count+=1
set seq=!seq! %%i
)
set "seq=%seq% ^| "
set n=-%count%
set /a n+=1
for %%i in (%*) do (
set F!n!=%%i
set /a n+=1
)
for /l %%i in (1,1,10) do (
set /a termstart=%%i-%count%%
set /a termend=%%i-1
for /l %%j in (!termstart!,1,!termend!) do (
set /a F%%i+=!F%%j!
)
set seq=!seq! !F%%i!
)
echo %seq%
endlocal
exit /b
|
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Python | Python | max_it = 13
max_it_j = 10
a1 = 1.0
a2 = 0.0
d1 = 3.2
a = 0.0
print " i d"
for i in range(2, max_it + 1):
a = a1 + (a1 - a2) / d1
for j in range(1, max_it_j + 1):
x = 0.0
y = 0.0
for k in range(1, (1 << i) + 1):
y = 1.0 - 2.0 * y * x
x = a - x * x
a = a - x / y
d = (a1 - a2) / (a - a1)
print("{0:2d} {1:.8f}".format(i, d))
d1 = d
a2 = a1
a1 = a |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Racket | Racket | #lang racket
(define (feigenbaum #:max-it (max-it 13) #:max-it-j (max-it-j 10))
(displayln " i d" (current-error-port))
(define-values (_a _a1 d)
(for/fold ((a 1) (a1 0) (d 3.2))
((i (in-range 2 (add1 max-it))))
(let* ((a′ (for/fold ((a (+ a (/ (- a a1) d))))
((j (in-range max-it-j)))
(let-values (([x y] (for/fold ((x 0) (y 0))
((k (expt 2 i)))
(values (- a (* x x))
(- 1 (* 2 y x))))))
(- a (/ x y)))))
(d′ (/ (- a a1) (- a′ a))))
(eprintf "~a ~a\n" (~a i #:width 2) (real->decimal-string d′ 8))
(values a′ a d′))))
d)
(module+ main
(feigenbaum)) |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Raku | Raku | my $a1 = 1;
my $a2 = 0;
my $d = 3.2;
say ' i d';
for 2 .. 13 -> $exp {
my $a = $a1 + ($a1 - $a2) / $d;
do {
my $x = 0;
my $y = 0;
for ^2 ** $exp {
$y = 1 - 2 * $y * $x;
$x = $a - $x²;
}
$a -= $x / $y;
} xx 10;
$d = ($a1 - $a2) / ($a - $a1);
($a2, $a1) = ($a1, $a);
printf "%2d %.8f\n", $exp, $d;
} |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Rust | Rust | fn main() {
let exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"];
let filenames = [
"MyData.a##",
"MyData.tar.Gz",
"MyData.gzip",
"MyData.7z.backup",
"MyData...",
"MyData",
"MyData_v1.0.tar.bz2",
"MyData_v1.0.bz2",
];
println!("extenstions: {:?}\n", exts);
for filename in filenames.iter() {
let check = exts.iter().any(|ext| {
filename
.to_lowercase()
.ends_with(&format!(".{}", ext.to_lowercase()))
});
println!("{:20} {}", filename, check);
}
}
|
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Scala | Scala | def isExt(fileName: String, extensions: List[String]): Boolean = {
extensions.map { _.toLowerCase }.exists { fileName.toLowerCase endsWith "." + _ }
}
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #R | R | # Get the value
file.info(filename)$mtime
#To set the value, we need to rely on shell commands. The following works under windows.
shell("copy /b /v filename +,,>nul")
# and on Unix (untested)
shell("touch -m filename") |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Racket | Racket |
#lang racket
(file-or-directory-modify-seconds "foo.rkt")
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Raku | Raku | use NativeCall;
class utimbuf is repr('CStruct') {
has int $.actime;
has int $.modtime;
submethod BUILD(:$atime, :$mtime) {
$!actime = $atime;
$!modtime = $mtime.to-posix[0].round;
}
}
sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}
sub MAIN (Str $file) {
my $mtime = $file.IO.modified orelse .die;
my $ubuff = utimbuf.new(:atime(time),:mtime($mtime));
sysutime($file, $ubuff);
} |
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #Raku | Raku | constant @fib-word = '1', '0', { $^b ~ $^a } ... *;
sub MAIN($m = 17, $scale = 3) {
(my %world){0}{0} = 1;
my $loc = 0+0i;
my $dir = i;
my $n = 1;
for @fib-word[$m].comb {
when '0' {
step;
if $n %% 2 { turn-left }
else { turn-right; }
}
$n++;
}
braille-graphics %world;
sub step {
for ^$scale {
$loc += $dir;
%world{$loc.im}{$loc.re} = 1;
}
}
sub turn-left { $dir *= i; }
sub turn-right { $dir *= -i; }
}
sub braille-graphics (%a) {
my ($ylo, $yhi, $xlo, $xhi);
for %a.keys -> $y {
$ylo min= +$y; $yhi max= +$y;
for %a{$y}.keys -> $x {
$xlo min= +$x; $xhi max= +$x;
}
}
for $ylo, $ylo + 4 ...^ * > $yhi -> \y {
for $xlo, $xlo + 2 ...^ * > $xhi -> \x {
my $cell = 0x2800;
$cell += 1 if %a{y + 0}{x + 0};
$cell += 2 if %a{y + 1}{x + 0};
$cell += 4 if %a{y + 2}{x + 0};
$cell += 8 if %a{y + 0}{x + 1};
$cell += 16 if %a{y + 1}{x + 1};
$cell += 32 if %a{y + 2}{x + 1};
$cell += 64 if %a{y + 3}{x + 0};
$cell += 128 if %a{y + 3}{x + 1};
print chr($cell);
}
print "\n";
}
} |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #OCaml | OCaml | let rec aux acc paths =
if List.mem [] paths
then (List.rev acc) else
let heads = List.map List.hd paths in
let item = List.hd heads in
let all_the_same =
List.for_all ((=) item) (List.tl heads)
in
if all_the_same
then aux (item::acc) (List.map List.tl paths)
else (List.rev acc)
let common_prefix sep = function
| [] -> invalid_arg "common_prefix"
| dirs ->
let paths = List.map (Str.split (Str.regexp_string sep)) dirs in
let res = aux [] paths in
(sep ^ (String.concat sep res))
let () =
let dirs = [
"/home/user1/tmp/coverage/test";
"/home/user1/tmp/covert/operator";
"/home/user1/tmp/coven/members";
] in
print_endline (common_prefix "/" dirs);
;; |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Common_Lisp | Common Lisp | (remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
> (2 4 6 8 10) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PicoLisp | PicoLisp | $ ulimit -s
8192
$ pil +
: (let N 0 (recur (N) (recurse (msg (inc N)))))
...
730395
730396
730397
Segmentation fault |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PL.2FI | PL/I |
recurs: proc options (main) reorder;
dcl sysprint file;
dcl mod builtin;
dcl ri fixed bin(31) init (0);
recursive: proc recursive;
ri += 1;
if mod(ri, 1024) = 1 then
put data(ri);
call recursive();
end recursive;
call recursive();
end recurs;
|
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PowerShell | PowerShell |
function TestDepth ( $N )
{
$N
TestDepth ( $N + 1 )
}
try
{
TestDepth 1 | ForEach { $Depth = $_ }
}
catch
{
"Exception message: " + $_.Exception.Message
}
"Last level before error: " + $Depth
|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Go | Go | package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
switch {
case i%15==0:
fmt.Println("FizzBuzz")
case i%3==0:
fmt.Println("Fizz")
case i%5==0:
fmt.Println("Buzz")
default:
fmt.Println(i)
}
}
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #mIRC_Scripting_Language | mIRC Scripting Language | echo -ag $file(input.txt).size bytes
echo -ag $file(C:\input.txt).size bytes |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Modula-3 | Modula-3 | MODULE FSize EXPORTS Main;
IMPORT IO, Fmt, FS, File, OSError;
VAR fstat: File.Status;
BEGIN
TRY
fstat := FS.Status("input.txt");
IO.Put("Size of input.txt: " & Fmt.LongInt(fstat.size) & "\n");
fstat := FS.Status("/input.txt");
IO.Put("Size of /input.txt: " & Fmt.LongInt(fstat.size) & "\n");
EXCEPT
| OSError.E => IO.Put("ERROR: Could not get file status.\n");
END;
END FSize. |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Factor | Factor | "input.txt" binary file-contents
"output.txt" binary set-file-contents |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Forth | Forth | \ <to> <from> copy-file
: copy-file ( a1 n1 a2 n2 -- )
r/o open-file throw >r
w/o create-file throw r>
begin
pad maxstring 2 pick read-file throw
?dup while
pad swap 3 pick write-file throw
repeat
close-file throw
close-file throw ;
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Go | Go | package main
import (
"fmt"
"math"
)
// From http://rosettacode.org/wiki/Entropy#Go
func entropy(s string) float64 {
m := map[rune]float64{}
for _, r := range s {
m[r]++
}
hm := 0.
for _, c := range m {
hm += c * math.Log2(c)
}
l := float64(len(s))
return math.Log2(l) - hm/l
}
const F_Word1 = "1"
const F_Word2 = "0"
func FibonacciWord(n int) string {
a, b := F_Word1, F_Word2
for ; n > 1; n-- {
a, b = b, b+a
}
return a
}
func FibonacciWordGen() <-chan string {
ch := make(chan string)
go func() {
a, b := F_Word1, F_Word2
for {
ch <- a
a, b = b, b+a
}
}()
return ch
}
func main() {
fibWords := FibonacciWordGen()
fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word")
n := 1
for ; n < 10; n++ {
s := <-fibWords
// Just to show the function and generator do the same thing:
if s2 := FibonacciWord(n); s != s2 {
fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
}
fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s)
}
for ; n <= 37; n++ {
s := <-fibWords
fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s))
}
} |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Gambas | Gambas | Public Sub Main()
Dim sList As String = File.Load("../FASTA")
Dim sTemp, sOutput As String
For Each sTemp In Split(sList, gb.NewLine)
If sTemp Begins ">" Then
If sOutput Then Print sOutput
sOutput = Right(sTemp, -1) & ": "
Else
sOutput &= sTemp
Endif
Next
Print sOutput
End |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Go | Go | package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
} |
http://rosettacode.org/wiki/Fast_Fourier_transform | Fast Fourier transform | Task
Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #Ada | Ada |
with Ada.Numerics.Generic_Complex_Arrays;
generic
with package Complex_Arrays is
new Ada.Numerics.Generic_Complex_Arrays (<>);
use Complex_Arrays;
function Generic_FFT (X : Complex_Vector) return Complex_Vector;
|
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.
There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
The following is how to implement this modPow yourself:
For example, let's compute 223 mod 47.
Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.
Use the result of the modulo from the last step as the initial value of square in the next step:
remove optional
square top bit multiply by 2 mod 47
──────────── ─────── ───────────── ──────
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
Since 223 mod 47 = 1, 47 is a factor of 2P-1.
(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)
Since we've shown that 47 is a factor, 223-1 is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.
Finally any potential factor q must be prime.
As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).
These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.
Task
Using the above method find a factor of 2929-1 (aka M929)
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
See also
Computers in 1948: 2127 - 1
(Note: This video is no longer available because the YouTube account associated with this video has been terminated.)
| #11l | 11l | F is_prime(a)
I a == 2 {R 1B}
I a < 2 | a % 2 == 0 {R 0B}
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
F m_factor(p)
V max_k = 16384 I/ p
L(k) 0 .< max_k
V q = 2 * p * k + 1
I !is_prime(q)
L.continue
E I q % 8 != 1 & q % 8 != 7
L.continue
E I pow(2, p, q) == 1
R q
R 0
V exponent = Int(input(‘Enter exponent of Mersenne number: ’))
I !is_prime(exponent)
print(‘Exponent is not prime: #.’.format(exponent))
E
V factor = m_factor(exponent)
I factor == 0
print(‘No factor found for M#.’.format(exponent))
E
print(‘M#. has a factor: #.’.format(exponent, factor)) |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #BASIC256 | BASIC256 | for i = 1 to 11
print "F"; i; " = ";
call farey(i, FALSE)
next i
print
for i = 100 to 1000 step 100
print "F"; i;
if i <> 1000 then print " "; else print "";
print " = ";
call farey(i, FALSE)
next i
end
subroutine farey(n, descending)
a = 0 : b = 1 : c = 1 : d = n : k = 0
cont = 0
if descending = TRUE then
a = 1 : c = n -1
end if
cont += 1
if n < 12 then print a; "/"; b; " ";
while ((c <= n) and not descending) or ((a > 0) and descending)
aa = a : bb = b : cc = c : dd = d
k = (n + b) \ d
a = cc : b = dd : c = k * cc - aa : d = k * dd - bb
cont += 1
if n < 12 then print a; "/"; b; " ";
end while
if n < 12 then print else print rjust(cont,7)
end subroutine |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void farey(int n)
{
typedef struct { int d, n; } frac;
frac f1 = {0, 1}, f2 = {1, n}, t;
int k;
printf("%d/%d %d/%d", 0, 1, 1, n);
while (f2.n > 1) {
k = (n + f1.n) / f2.n;
t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n };
printf(" %d/%d", f2.d, f2.n);
}
putchar('\n');
}
typedef unsigned long long ull;
ull *cache;
size_t ccap;
ull farey_len(int n)
{
if (n >= ccap) {
size_t old = ccap;
if (!ccap) ccap = 16;
while (ccap <= n) ccap *= 2;
cache = realloc(cache, sizeof(ull) * ccap);
memset(cache + old, 0, sizeof(ull) * (ccap - old));
} else if (cache[n])
return cache[n];
ull len = (ull)n*(n + 3) / 2;
int p, q = 0;
for (p = 2; p <= n; p = q) {
q = n/(n/p) + 1;
len -= farey_len(n/p) * (q - p);
}
cache[n] = len;
return len;
}
int main(void)
{
int n;
for (n = 1; n <= 11; n++) {
printf("%d: ", n);
farey(n);
}
for (n = 100; n <= 1000; n += 100)
printf("%d: %llu items\n", n, farey_len(n));
n = 10000000;
printf("\n%d: %llu items\n", n, farey_len(n));
return 0;
} |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
printf("Base %2d:", base);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
std::vector<int> cnt(base, 0);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
int minTurn = INT_MAX;
int maxTurn = INT_MIN;
int portion = 0;
for (int i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
} |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #Factor | Factor | USING: kernel math math.combinatorics math.extras math.functions
math.ranges prettyprint sequences ;
: faulhaber ( p -- seq )
1 + dup recip swap dup 0 (a,b]
[ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ;
10 [ faulhaber . ] each-integer |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #FreeBASIC | FreeBASIC | ' version 12-08-2017
' compile with: fbc -s console
' uses GMP
#Include Once "gmp.bi"
#Define i_max 17
Dim As UInteger i, j, x
Dim As String s
Dim As ZString Ptr gmp_str : gmp_str = Allocate(100)
Dim As Mpq_ptr n, tmp1, tmp2, sum, one, zero
n = Allocate(Len(__mpq_struct)) : Mpq_init(n)
tmp1 = Allocate(Len(__mpq_struct)) : Mpq_init(tmp1)
tmp2 = Allocate(Len(__mpq_struct)) : Mpq_init(tmp2)
sum = Allocate(Len(__mpq_struct)) : Mpq_init(sum)
zero = Allocate(Len(__mpq_struct)) : Mpq_init(zero)
one = Allocate(Len(__mpq_struct)) : Mpq_init(one)
Mpq_set_ui(zero, 0, 0) ' 0/0 = 0
Mpq_set_ui(one , 1, 1) ' 1/1 = 1
Dim As Mpq_ptr Faulhaber_triangle(0 To i_max, 1 To i_max +1)
' only initialize the variables we need
For i = 0 To i_max
For j = 1 To i +1
Faulhaber_triangle(i, j) = Allocate(Len(__Mpq_struct))
Mpq_init(Faulhaber_triangle(i, j))
Next
Next
Mpq_set(Faulhaber_triangle(0, 1), one)
' we calculate the first 18 rows
For i = 1 To i_max
Mpq_set(sum, zero)
For j = i +1 To 2 Step -1
Mpq_set_ui(tmp1, i, j) ' i / j
Mpq_set(tmp2, Faulhaber_triangle(i -1, j -1))
Mpq_mul(Faulhaber_triangle(i, j), tmp2, tmp1)
Mpq_canonicalize(Faulhaber_triangle(i, j))
Mpq_add(sum, sum, Faulhaber_triangle(i, j))
Next
Mpq_sub(Faulhaber_triangle(i, 1), one, sum)
Next
Print "The first 10 rows"
For i = 0 To 9
For j = 1 To i +1
Mpq_get_str(gmp_str, 10, Faulhaber_triangle(i, j))
s = Space(6) + *gmp_str + Space(6)
x = InStr(s,"/")
If x = 0 Then x = 7 ' in case of 0 or 1
Print Mid(s, x -3, 7);
Next
Print
Next
print
' using the 17'the row
Mpq_set(sum, zero)
Mpq_set_ui(n, 1000, 1) ' 1000/1 = 1000
Mpq_set(tmp2, n)
For j = 1 To 18
Mpq_mul(tmp1, n, Faulhaber_triangle(17, j))
Mpq_add(sum, sum, tmp1)
Mpq_mul(n, n, tmp2)
Next
Mpq_get_str(gmp_str, 10, sum)
Print *gmp_str
' free memory
DeAllocate(gmp_str)
Mpq_clear(tmp1) : Mpq_clear(tmp2) : Mpq_clear(n)
Mpq_clear(zero) : Mpq_clear(one) : Mpq_clear(sum)
For i = 0 To i_max
For j = 1 To i +1
Mpq_clear(Faulhaber_triangle(i, j))
Next
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #GAP | GAP | n := X(Rationals, "n");
sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1);
sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1);
ForAll([0 .. 20], k -> sum1(k) = sum2(k));
for p in [0 .. 9] do
Print(sum1(p), "\n");
od;
n
1/2*n^2+1/2*n
1/3*n^3+1/2*n^2+1/6*n
1/4*n^4+1/2*n^3+1/4*n^2
1/5*n^5+1/2*n^4+1/3*n^3-1/30*n
1/6*n^6+1/2*n^5+5/12*n^4-1/12*n^2
1/7*n^7+1/2*n^6+1/2*n^5-1/6*n^3+1/42*n
1/8*n^8+1/2*n^7+7/12*n^6-7/24*n^4+1/12*n^2
1/9*n^9+1/2*n^8+2/3*n^7-7/15*n^5+2/9*n^3-1/30*n
1/10*n^10+1/2*n^9+3/4*n^8-7/10*n^6+1/2*n^4-3/20*n^2 |
http://rosettacode.org/wiki/Fermat_numbers | Fermat numbers | In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer.
Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.
As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.
Task
Write a routine (function, procedure, whatever) to generate Fermat numbers.
Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9.
Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you.
See also
Wikipedia - Fermat numbers
OEIS:A000215 - Fermat numbers
OEIS:A019434 - Fermat primes
| #REXX | REXX | /*REXX program to find and display Fermat numbers, and show factors of Fermat numbers.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 9 /*Not specified? Then use the default.*/
numeric digits 20 /*ensure enough decimal digits, for n=9*/
do j=0 to n; f= 2** (2**j) + 1 /*calculate a series of Fermat numbers.*/
say right('F'j, length(n) + 1)': ' f /*display a particular " " */
end /*j*/
say
do k=0 to n; f= 2** (2**k) + 1; say /*calculate a series of Fermat numbers.*/
say center(' F'k": " f' ', 79, "═") /*display a particular " " */
p= factr(f) /*factor a Fermat number, given time. */
if words(p)==1 then say f ' is prime.'
else say 'factors: ' p
end /*k*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure; parse arg x 1 z,,?
do k=1 to 11 by 2; j= k; if j==1 then j= 2; if j==9 then iterate
call build /*add J to the factors list. */
end /*k*/ /* [↑] factor X with some low primes*/
do y=0 by 2; j= j + 2 + y // 4 /*ensure not ÷ by three. */
parse var j '' -1 _; if _==5 then iterate /*last digit a "5"? Skip it.*/
if j*j>x | j>z then leave
call build /*add Y to the factors list. */
end /*y*/ /* [↑] factor X with other higher #s*/
j= z
if z\==1 then ?= build()
if ?='' then do; @.1= x; ?= x; #= 1; end
return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
build: do while z//j==0; z= z % j; ?= ? j; end; return strip(?) |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #BBC_BASIC | BBC BASIC | @% = 5 : REM Column width
PRINT "Fibonacci:"
DIM f2%(1) : f2%() = 1,1
FOR i% = 1 TO 12 : PRINT f2%(0); : PROCfibn(f2%()) : NEXT : PRINT " ..."
PRINT "Tribonacci:"
DIM f3%(2) : f3%() = 1,1,2
FOR i% = 1 TO 12 : PRINT f3%(0); : PROCfibn(f3%()) : NEXT : PRINT " ..."
PRINT "Tetranacci:"
DIM f4%(3) : f4%() = 1,1,2,4
FOR i% = 1 TO 12 : PRINT f4%(0); : PROCfibn(f4%()) : NEXT : PRINT " ..."
PRINT "Lucas:"
DIM fl%(1) : fl%() = 2,1
FOR i% = 1 TO 12 : PRINT fl%(0); : PROCfibn(fl%()) : NEXT : PRINT " ..."
END
DEF PROCfibn(f%())
LOCAL i%, s%
s% = SUM(f%())
FOR i% = 1 TO DIM(f%(),1)
f%(i%-1) = f%(i%)
NEXT
f%(i%-1) = s%
ENDPROC |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #REXX | REXX | /*REXX pgm calculates the (Mitchell) Feigenbaum bifurcation velocity, #digs can be given*/
parse arg digs maxi maxj . /*obtain optional argument from the CL.*/
if digs=='' | digs=="," then digs= 30 /*Not specified? Then use the default.*/
if maxi=='' | maxi=="," then maxi= 20 /* " " " " " " */
if maxJ=='' | maxJ=="," then maxJ= 10 /* " " " " " " */
#= 4.669201609102990671853203820466201617258185577475768632745651343004134330211314737138,
|| 68974402394801381716 /*◄──Feigenbaum's constant, true value.*/
numeric digits digs /*use the specified # of decimal digits*/
a1= 1
a2= 0
d1= 3.2
say 'Using ' maxJ " iterations for maxJ, with " digs ' decimal digits:'
say
say copies(' ', 9) center("correct", 11) copies(' ', digs+1)
say center('i', 9, "─") center('digits' , 11, "─") center('d', digs+1, "─")
do i=2 for maxi-1
a= a1 + (a1 - a2) / d1
do maxJ
x= 0; y= 0
do 2**i; y= 1 - 2 * x * y
x= a - x*x
end /*2**i*/
a= a - x / y
end /*maxj*/
d= (a1 - a2) / (a - a1) /*compute the delta (D) of the function*/
t= max(0, compare(d, #) - 2) /*# true digs so far, ignore dec. point*/
say center(i, 9) center(t, 11) d /*display values for I & D ──►terminal*/
parse value d a1 a with d1 a2 a1 /*assign 3 variables with 3 new values.*/
end /*i*/
/*stick a fork in it, we're all done. */
say left('', 9 + 1 + 11 + 1 + t )"↑" /*show position of greatest accuracy. */
say ' true value= ' # / 1 /*true value of Feigenbaum's constant. */ |
http://rosettacode.org/wiki/Feigenbaum_constant_calculation | Feigenbaum constant calculation | Task
Calculate the Feigenbaum constant.
See
Details in the Wikipedia article: Feigenbaum constant.
| #Ring | Ring | # Project : Feigenbaum constant calculation
decimals(8)
see "Feigenbaum constant calculation:" + nl
maxIt = 13
maxItJ = 10
a1 = 1.0
a2 = 0.0
d1 = 3.2
see "i " + "d" + nl
for i = 2 to maxIt
a = a1 + (a1 - a2) / d1
for j = 1 to maxItJ
x = 0
y = 0
for k = 1 to pow(2,i)
y = 1 - 2 * y * x
x = a - x * x
next
a = a - x / y
next
d = (a1 - a2) / (a - a1)
if i < 10
see "" + i + " " + d + nl
else
see "" + i + " " + d + nl
ok
d1 = d
a2 = a1
a1 = a
next |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Sidef | Sidef | func check_extension(filename, extensions) {
filename ~~ Regex('\.(' + extensions.map { .escape }.join('|') + ')\z', :i)
} |
http://rosettacode.org/wiki/File_extension_is_in_extensions_list | File extension is in extensions list | File extension is in extensions list
You are encouraged to solve this task according to the task description, using any language you may know.
Filename extensions are a rudimentary but commonly used way of identifying files types.
Task
Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.
Notes:
The check should be case insensitive.
The extension must occur at the very end of the filename, and be immediately preceded by a dot (.).
You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.
Extra credit:
Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:
archive.tar.gz
Please state clearly whether or not your solution does this.
Test cases
The following test cases all assume this list of extensions: zip, rar, 7z, gz, archive, A##
Filename
Result
MyData.a##
true
MyData.tar.Gz
true
MyData.gzip
false
MyData.7z.backup
false
MyData...
false
MyData
false
If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases:
Filename
Result
MyData_v1.0.tar.bz2
true
MyData_v1.0.bz2
false
Motivation
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java).
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the Extract file extension task.
Related tasks
Extract file extension
String matching
| #Tcl | Tcl |
# This example includes the extra credit.
# With a slight variation, a matching suffix can be identified.
# Note that suffixes with two or more dots (ie a dot in suffix) are checked for each case.
# This way, filename.1.txt will match for txt, and filename3.tar.gz.1 will match for tar.gz.1 for example.
# Example input data:
set f_list [list \
"MyData.a##" \
MyData.tar.Gz \
MyData.gzip \
MyData.7z.backup \
"MyData..." \
MyData \
MyData_v1.0.tar.bz2 \
MyData_v1.0.bz2 ]
set suffix_input_list [list zip rar 7z gz archive "A##" tar.bz2 ]
# Prefix a dot to any suffix that does not begin with a dot.
set suffix_list [list ]
foreach s $suffix_input_list {
if { [string range $s 0 0] ne "." } {
set s2 "."
} else {
set s2 ""
}
append s2 $s
lappend suffix_list [string tolower $s2]
}
# Check each filename
foreach filename0 $f_list {
set filename1 [string tolower [file tail $filename0]]
set suffix1 [file extension $filename1]
set file_suffix_list [list $suffix1]
set filename2 [file rootname $filename1]
set i 0
# i is an infinite loop breaker. In case there is some unforseen case..
while { $filename2 ne "" && $filename2 ne $filename1 && $i < 32} {
# Another suffix is possible
set suffix2 [file extension $filename2]
if { $suffix2 ne "" } {
# found another suffix
append suffix2 $suffix1
lappend file_suffix_list $suffix2
}
set suffix1 $suffix2
set filename1 $filename2
set filename2 [file rootname $filename2]
incr i
}
set a_suffix_found_p 0
foreach file_suffix $file_suffix_list {
if { $file_suffix in $suffix_list } {
set a_suffix_found_p 1
}
}
puts -nonewline "${filename0}\t"
if { $a_suffix_found_p } {
puts "true"
} else {
puts "false"
}
}
|
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #RapidQ | RapidQ | name$ = DIR$("input.txt", 0)
PRINT "File date: "; FileRec.Date
PRINT "File time: "; FileRec.Time |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #REALbasic | REALbasic |
Function getModDate(f As FolderItem) As Date
Return f.ModificationDate
End Function |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #REXX | REXX | /*REXX program obtains and displays a file's time of modification. */
parse arg $ . /*obtain required argument from the CL.*/
if $=='' then do; say "***error*** no filename was specified."; exit 13; end
q=stream($, 'C', "QUERY TIMESTAMP") /*get file's modification time info. */
if q=='' then q="specified file doesn't exist." /*set an error indication message. */
say 'For file: ' $ /*display the file ID information. */
say 'timestamp of last modification: ' q /*display the modification time info. */
/*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Fibonacci_word/fractal | Fibonacci word/fractal |
The Fibonacci word may be represented as a fractal as described here:
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
For F_wordm start with F_wordCharn=1
Draw a segment forward
If current F_wordChar is 0
Turn left if n is even
Turn right if n is odd
next n and iterate until end of F_word
Task
Create and display a fractal similar to Fig 1.
(Clicking on the above website (hal.archives-ouvertes.fr) will leave a cookie.)
| #REXX | REXX | /*REXX program generates a Fibonacci word, then (normally) displays the fractal curve.*/
parse arg order . /*obtain optional arguments from the CL*/
if order=='' | order=="," then order= 23 /*Not specified? Then use the default*/
tell= order>=0 /*Negative order? Then don't display. */
s= FibWord( abs(order) ) /*obtain the order of Fibonacci word.*/
x= 0; maxX= 0; dx= 0; b= ' '; @. = b; xp= 0
y= 0; maxY= 0; dy= 1; @.0.0= .; yp= 0
do n=1 for length(s); x= x + dx; y= y + dy /*advance the plot for the next point. */
maxX= max(maxX, x); maxY= max(maxY, y) /*set the maximums for displaying plot.*/
c= '│' /*glyph (character) used for the plot. */
if dx\==0 then c= "─" /*if x+dx isn't zero, use this char.*/
if n==1 then c= '┌' /*is this the first part to be graphed?*/
@.x.y= c /*assign a plotting character for curve*/
if @(xp-1, yp)\==b then if @(xp, yp-1)\==b then call @ xp,yp,'┐' /*fix─up a corner*/
if @(xp-1, yp)\==b then if @(xp, yp+1)\==b then call @ xp,yp,'┘' /* " " " */
if @(xp+1, yp)\==b then if @(xp, yp-1)\==b then call @ xp,yp,'┌' /* " " " */
if @(xp+1, yp)\==b then if @(xp, yp+1)\==b then call @ xp,yp,'└' /* " " " */
xp= x; yp= y /*save the old x & y coördinates.*/
z= substr(s, n, 1) /*assign a plot character for the graph*/
if z==1 then iterate /*Is Z equal to unity? Then ignore it.*/
ox= dx; oy= dy /*save DX,DY as the old versions. */
dx= 0; dy= 0 /*define DX,DY " " new " */
d= -n//2; if d==0 then d= 1 /*determine the sign for the chirality.*/
if oy\==0 then dx= -sign(oy) * d /*Going north│south? Go east|west */
if ox\==0 then dy= sign(ox) * d /* " east│west? " south|north */
end /*n*/
call @ x, y, '∙' /*set the last point that was plotted. */
do r=maxY to 0 by -1; _= /*show single row at a time, top first.*/
do c=0 for maxX+1; _= _ || @.c.r /*add a plot character (glyph) to line.*/
end /*c*/ /* [↑] construct a line char by char. */
_= strip(_, 'T') /*construct a line of the graph. */
if _=='' then iterate /*Is the line blank? Then ignore it. */
if tell then say _ /*Display the line to the terminal ? */
call lineout "FIBFRACT.OUT", _ /*write graph to disk (FIBFRACT.OUT). */
end /*r*/ /* [↑] only display the non-blank rows*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg xx,yy,p; if arg(3)=='' then return @.xx.yy; @.xx.yy= p; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
FibWord: procedure; parse arg x; !.= 0; !.1= 1 /*obtain the order of Fibonacci word. */
do k=3 to x /*generate the Kth " " */
k1= k-1; k2= k - 2 /*calculate the K-1 & K-2 shortcut.*/
!.k= !.k1 || !.k2 /*construct the next Fibonacci word. */
end /*k*/ /* [↑] generate a " " */
return !.x /*return the Xth " " */ |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
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
| #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION findCommonDir RETURNS CHAR(
i_cdirs AS CHAR,
i_cseparator AS CHAR
):
DEF VAR idir AS INT.
DEF VAR idepth AS INT.
DEF VAR cdir AS CHAR EXTENT.
DEF VAR lsame AS LOGICAL INITIAL TRUE.
DEF VAR cresult AS CHAR.
EXTENT( cdir ) = NUM-ENTRIES( i_cdirs, '~n' ).
DO idir = 1 TO NUM-ENTRIES( i_cdirs, '~n' ):
cdir[ idir ] = ENTRY( idir, i_cdirs, '~n' ).
END.
DO idepth = 2 TO NUM-ENTRIES( cdir [ 1 ], i_cseparator ) WHILE lsame:
DO idir = 1 TO EXTENT( cdir ) - 1 WHILE lsame:
lsame = (
ENTRY( idepth, cdir [ idir ], i_cseparator ) =
ENTRY( idepth, cdir [ idir + 1 ], i_cseparator )
).
END.
IF lsame THEN
cresult = cresult + i_cseparator + ENTRY( idepth, cdir [ 1 ], i_cseparator ).
END.
RETURN cresult.
END FUNCTION. |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Cowgol | Cowgol | include "cowgol.coh";
# Cowgol has strict typing and there are no templates either.
# Defining the type this way makes it easy to change.
typedef FilterT is uint32;
# In order to pass functions around, we need to define an
# interface. The 'FilterPredicate' interface will take an argument
# and return zero if it should be filtered out.
interface FilterPredicate(x: FilterT): (keep: uint8);
# Filter an array and store it a new location. Returns the new length.
sub Filter(f: FilterPredicate,
items: [FilterT],
length: intptr,
result: [FilterT]):
(newLength: intptr) is
newLength := 0;
while length > 0 loop
var item := [items];
items := @next items;
if f(item) != 0 then
[result] := item;
result := @next result;
newLength := newLength + 1;
end if;
length := length - 1;
end loop;
end sub;
# Filter an array in place. Returns the new length.
sub FilterInPlace(f: FilterPredicate,
items: [FilterT],
length: intptr):
(newLength: intptr) is
newLength := Filter(f, items, length, items);
end sub;
# Filter that selects even numbers
sub Even implements FilterPredicate is
keep := (~ x as uint8) & 1;
end sub;
# Filter an array
var array: uint32[] := {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var filtered: uint32[@sizeof array];
var length := Filter(Even, &array[0], @sizeof array, &filtered[0]);
# Print result
var i: uint8 := 0;
while i < length as uint8 loop
print_i32(filtered[i]);
print_char(' ');
i := i + 1;
end loop;
print_nl();
# Filter the result again in place for numbers less than 8
sub LessThan8 implements FilterPredicate is
if x < 8 then keep := 1;
else keep := 0;
end if;
end sub;
length := FilterInPlace(LessThan8, &filtered[0], length);
i := 0;
while i < length as uint8 loop
print_i32(filtered[i]);
print_char(' ');
i := i + 1;
end loop;
print_nl(); |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #PureBasic | PureBasic | Procedure Recur(n)
PrintN(str(n))
Recur(n+1)
EndProcedure
Recur(1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.