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/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)... | #EchoLisp | EchoLisp |
(define -∏*2 (complex 0 (* -2 PI)))
(define (fft xs N)
(if (<= N 1) xs
(let* [
(N/2 (/ N 2))
(even (fft (for/vector ([i (in-range 0 N 2)]) [xs i]) N/2))
(odd (fft (for/vector ([i (in-range 1 N 2)]) [xs i]) N/2))
]
(for ((k N/2)) (vector*= odd k (exp (/ (* -∏*2 k) N ))))
(vector-append (vector-map + ev... |
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,... | #Common_Lisp | Common Lisp | (defun mersenne-fac (p &aux (m (1- (expt 2 p))))
(loop for k from 1
for n = (1+ (* 2 k p))
until (zerop (mod m n))
finally (return n)))
(print (mersenne-fac 929)) |
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,... | #Crystal | Crystal | require "big"
def prime?(n) # P3 Prime Generator primality test
return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true
return false if n.gcd(6) != 1 # for n a P3 prime candidate (pc)
pc1, pc2 = -1, 1 # use P3's prime candidates sequence
... |
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 se... | #Go | Go | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func mai... |
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 t... | #Quackery | Quackery | [ dup dip digitsum mod ] is fairshare ( n n --> n )
' [ 2 3 5 11 ]
witheach
[ dup echo say ": "
25 times
[ i^ over fairshare echo sp ]
drop cr ] |
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 t... | #Racket | Racket | #lang racket
(define (Thue-Morse base)
(letrec ((q/r (curryr quotient/remainder base))
(inner (λ (n (s 0))
(match n
[0 (modulo s base)]
[(app q/r q r) (inner q (+ s r))]))))
inner))
(define (report-turns B n)
(printf "Base:\t~a\t~a~%... |
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 t... | #Raku | Raku | sub fairshare (\b) { ^∞ .hyper.map: { .polymod( b xx * ).sum % b } }
.say for <2 3 5 11>.map: { .fmt('%2d:') ~ .&fairshare[^25]».fmt('%2d').join: ', ' }
say "\nRelative fairness of this method. Scaled fairness correlation. The closer to 1.0 each person
is, the more fair the selection algorithm is. Gets better with ... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Faulhaber]
bernoulliB[1] := 1/2
bernoulliB[n_] := BernoulliB[n]
Faulhaber[n_, p_] := 1/(p + 1) Sum[Binomial[p + 1, j] bernoulliB[j] n^(p + 1 - j), {j, 0, p}]
Table[Rest@CoefficientList[Faulhaber[n, t], n], {t, 0, 9}] // Grid
Faulhaber[1000, 17] |
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.
R... | #Modula-2 | Modula-2 | MODULE Faulhaber;
FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
VAR TextWinExSrc : ExceptionSource;
(* Helper Functions *)
PROCEDURE Abs(n : INTEGER) : INTEGER;
BEGIN
IF n < 0 THEN
RETURN ... |
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}}
... | #Delphi | Delphi |
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
;; bind it to its name
(define (make-nacci name seed)
(define len (1+ (vector-length seed)))
(define-global name
`(lambda(n) (for/sum ((i (in-range (1- n) (- n ,len) -1))) (,name i))))
(remember name seed)
name)
(define nacci-f... |
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 foll... | #REXX | REXX | /*REXX program finds the common directory path for a list of files. */
@. = /*the default for all file lists (null)*/
@.1 = '/home/user1/tmp/coverage/test'
@.2 = '/home/user1/tmp/covert/operator'
@.3 = '/home/user1/tmp/coven/m... |
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.
| #Erlang | Erlang | Numbers = lists:seq(1, 5).
EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers). |
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.
| #VBScript | VBScript | 'mung.vbs
option explicit
dim c
if wscript.arguments.count = 1 then
c = wscript.arguments(0)
c = c + 1
else
c = 0
end if
wscript.echo "[Depth",c & "] Mung until no good."
CreateObject("WScript.Shell").Run "cscript Mung.vbs " & c, 1, true
wscript.echo "[Depth",c & "] no good." |
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.
| #Vlang | Vlang | // Find limit of recursion, in V
module main
// starts here, then call down until stacks become faulty
pub fn main() {
recurse(0)
}
fn recurse(n int) {
println(n)
recurse(n+1)
} |
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)
... | #Hy | Hy | (for [i (range 1 101)] (print (cond
[(not (% i 15)) "FizzBuzz"]
[(not (% i 5)) "Buzz"]
[(not (% i 3)) "Fizz"]
[True 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.
| #Ring | Ring | See len(read('input.txt')) + nl
see len(read('/input.txt')) + nl |
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.
| #Ruby | Ruby | size = File.size('input.txt')
size = File.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.
| #Run_BASIC | Run BASIC | print fileSize(DefaultDir$,"input.txt") ' current default directory
print fileSize("","input.txt") ' root directory
function fileSize(dir$,file$)
open dir$;"\";file$ FOR input as #f
fileSize = lof(#f) ' Length Of File
close #f
end function |
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 ... | #Julia | Julia | mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w") |
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 ... | #K | K | `output.txt 0:0:`input.txt |
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-... | #Pascal | Pascal | program FibWord;
{$IFDEF DELPHI}
{$APPTYPE CONSOLE}
{$ENDIF}
const
FibSMaxLen = 35;
type
tFibString = string[2*FibSMaxLen];//Ansistring;
tFibCnt = longWord;
tFib = record
ZeroCnt,
OneCnt : tFibCnt;
// fibS : tFibString;//didn't work :-(
end;
var
FibSCheck : boo... |
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
... | #Ruby | Ruby | def fasta_format(strings)
out, text = [], ""
strings.split("\n").each do |line|
if line[0] == '>'
out << text unless text.empty?
text = line[1..-1] + ": "
else
text << line
end
end
out << text unless text.empty?
end
data = <<'EOS'
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Exa... |
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
... | #Run_BASIC | Run BASIC | a$ = ">Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED"
i = 1
while i <= len(a$)
if mid$(a$,i,17) = ">Rosetta_Example_" then
print
print mid$(a$,i,18);": ";
i = i + 17
else
if asc(mid$(a$,i,1)) > 20 then print mid$(a$,i,1);
end if
... |
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
... | #Rust | Rust |
use std::env;
use std::io::{BufReader, Lines};
use std::io::prelude::*;
use std::fs::File;
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).unwrap();
for line in FastaIter::new(f) {
println!("{}", line);
}
}
struct FastaIter<T> {
buffer_lines: Lin... |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #ABAP | ABAP | FORM fibonacci_iter USING index TYPE i
CHANGING number_fib TYPE i.
DATA: lv_old type i,
lv_cur type i.
Do index times.
If sy-index = 1 or sy-index = 2.
lv_cur = 1.
lv_old = 0.
endif.
number_fib = lv_cur + lv_old.
lv_old = lv_cur.
lv_cur = number_fib.
end... |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ALGOL_68 | ALGOL 68 | MODE YIELDINT = PROC(INT)VOID;
PROC gen factors = (INT n, YIELDINT yield)VOID: (
FOR i FROM 1 TO ENTIER sqrt(n) DO
IF n MOD i = 0 THEN
yield(i);
INT other = n OVER i;
IF i NE other THEN yield(n OVER i) FI
FI
OD
);
[]INT nums2factor = (45, 53, 64);
FOR i TO UPB nums2factor DO
INT n... |
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)... | #ERRE | ERRE |
PROGRAM FFT
CONST CNT=8
!$DYNAMIC
DIM REL[0],IMG[0],CMP[0],V[0]
BEGIN
SIG=INT(LOG(CNT)/LOG(2)+0.9999)
REAL1=2^SIG
REAL=REAL1-1
REAL2=INT(REAL1/2)
REAL4=INT(REAL1/4)
REAL3=REAL4+REAL2
!$DIM REL[REAL1],IMG[REAL1],CMP[REAL3]
FOR I=0 TO CNT-1 DO
READ(REL[I],IMG[I])
END FOR
DATA(1,0,1,0,... |
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,... | #D | D | import std.stdio, std.math, std.traits;
ulong mersenneFactor(in ulong p) pure nothrow @nogc {
static bool isPrime(T)(in T n) pure nothrow @nogc {
if (n < 2 || n % 2 == 0)
return n == 2;
for (Unqual!T i = 3; i ^^ 2 <= n; i += 2)
if (n % i == 0)
return false;
... |
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 se... | #Haskell | Haskell | import Data.List (unfoldr, mapAccumR)
import Data.Ratio ((%), denominator, numerator)
import Text.Printf (PrintfArg, printf)
-- The n'th order Farey sequence.
farey :: Integer -> [Rational]
farey n = 0 : unfoldr step (0, 1, 1, n)
where
step (a, b, c, d)
| c > n = Nothing
| otherwise =
let k ... |
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 t... | #REXX | REXX | /*REXX program calculates N terms of the fairshare sequence for some group of peoples.*/
parse arg n g /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/
if g='' | g="," then g= 2 3 5 11 ... |
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 t... | #Ring | Ring |
str = []
people = [2,3,5,11]
result = people
for i in people
str = []
see "" + i + ": "
fair(25, i)
for n in result
add(str,n)
next
showarray(str)
next
func fair n,base
result = list(n)
for i=1 to n
j = i-1
t = 0
while j>0
t ... |
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... | #Nim | Nim | import algorithm, math, strutils
import bignum
type FaulhaberSequence = seq[Rat]
#---------------------------------------------------------------------------------------------------
func bernoulli(n: Natural): Rat =
## Return nth Bernoulli coefficient.
var a = newSeq[Rat](n + 1)
for m in 0..n:
a[m] = ... |
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.
R... | #Nim | Nim | import math, rationals
type
Fraction = Rational[int]
FaulhaberSequence = seq[Fraction]
const
Zero = 0 // 1
One = 1 // 1
MinusOne = -1 // 1
Powers = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
#---------------------------------------------------------------------------------------------------
... |
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}}
... | #EchoLisp | EchoLisp |
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
;; bind it to its name
(define (make-nacci name seed)
(define len (1+ (vector-length seed)))
(define-global name
`(lambda(n) (for/sum ((i (in-range (1- n) (- n ,len) -1))) (,name i))))
(remember name seed)
name)
(define nacci-f... |
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 foll... | #Ring | Ring |
# Project : Find common directory path
load "stdlib.ring"
i = null
o = null
path = list(3)
path[1] = "/home/user1/tmp/coverage/test"
path[2] = "/home/user1/tmp/covert/operator"
path[3] = "/home/user1/tmp/coven/members"
see commonpath(path, "/")
func commonpath(p, s)
while i != 0
o = i
i = substrin... |
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 foll... | #Ruby | Ruby | require 'abbrev'
dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )
common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop # => "/home/user1/tmp/cove"
common_directory = common_prefix.sub(%r{/[^/]*$}, '') # => "/home/user1/tmp" |
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.
| #Euphoria | Euphoria | sequence s, evens
s = {1, 2, 3, 4, 5, 6}
evens = {}
for i = 1 to length(s) do
if remainder(s[i], 2) = 0 then
evens = append(evens, s[i])
end if
end for
? evens |
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.
| #x86_Assembly | x86 Assembly | global main
section .text
main
xor eax, eax
call recurse
ret
recurse
add eax, 1
call recurse
ret |
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.
| #Wren | Wren | var f
f = Fn.new { |n|
if (n%500 == 0) System.print(n) // print progress after every 500 calls
System.write("") // required to fix a VM recursion bug
f.call(n + 1)
}
f.call(1) |
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)
... | #i | i | software {
for each 1 to 100
if i % 15 = 0
print("FizzBuzz")
else if i % 3 = 0
print("Fizz")
else if i % 5 = 0
print("Buzz")
else
print(i)
end
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.
| #Rust | Rust | use std::{env, fs, process};
use std::io::{self, Write};
use std::fmt::Display;
fn main() {
let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1));
let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2));
println!("Size of file.txt is {} bytes", meta... |
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.
| #Scala | Scala | import java.io.File
object FileSize extends App {
val name = "pg1661.txt"
println(s"$name : ${new File(name).length()} bytes")
println(s"/$name : ${new File(s"${File.separator}$name").length()} 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.
| #Scheme | Scheme |
(define (file-size filename)
(call-with-input-file filename (lambda (port)
(let loop ((c (read-char port))
(count 0))
(if (eof-object? c)
count
(loop (read-char port) (+ 1 count)))))))
(file-size "input.txt")
(file-size "/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 ... | #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun main(args: Array<String>) {
val text = File("input.txt").readText()
File("output.txt").writeText(text)
} |
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 ... | #LabVIEW | LabVIEW | : puts(*) . "\n" . ;
: set-file '> swap open ;
: >>contents slurp puts ;
: copy-file
swap set-file 'fdst set fdst fout >>contents fdst close ;
'output.txt '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-... | #Perl | Perl | sub fiboword;
{
my ($a, $b, $count) = (1, 0, 0);
sub fiboword {
$count++;
return $a if $count == 1;
return $b if $count == 2;
($a, $b) = ($b, "$b$a");
return $b;
}
}
sub entropy {
my %c;
$c{$_}++ for split //, my $str = shift;
my $e = 0;
for (values %c... |
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
... | #Scala | Scala | import java.io.File
import java.util.Scanner
object ReadFastaFile extends App {
val sc = new Scanner(new File("test.fasta"))
var first = true
while (sc.hasNextLine) {
val line = sc.nextLine.trim
if (line.charAt(0) == '>') {
if (first) first = false
else println()
printf("%s: ", line.... |
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
... | #Scheme | Scheme | (import (scheme base)
(scheme file)
(scheme write))
(with-input-from-file ; reads text from named file, one line at a time
"fasta.txt"
(lambda ()
(do ((first-line? #t #f)
(line (read-line) (read-line)))
((eof-object? line) (newline))
(cond ((char=? #\> (string-ref line 0))... |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #ACL2 | ACL2 | (defun fast-fib-r (n a b)
(if (or (zp n) (zp (1- n)))
b
(fast-fib-r (1- n) b (+ a b))))
(defun fast-fib (n)
(fast-fib-r n 1 1))
(defun first-fibs-r (n i)
(declare (xargs :measure (nfix (- n i))))
(if (zp (- n i))
nil
(cons (fast-fib i)
(first-fibs-r n (1+ i)))))
... |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ALGOL_W | ALGOL W | begin
% return the factors of n ( n should be >= 1 ) in the array factor %
% the bounds of factor should be 0 :: len (len must be at least 1) %
% the number of factors will be returned in factor( 0 ) %
procedure getFactorsOf ( integer value n
; int... |
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)... | #Factor | Factor |
IN: USE math.transforms.fft
IN: { 1 1 1 1 0 0 0 0 } fft .
{
C{ 4.0 0.0 }
C{ 1.0 -2.414213562373095 }
C{ 0.0 0.0 }
C{ 1.0 -0.4142135623730949 }
C{ 0.0 0.0 }
C{ 0.9999999999999999 0.4142135623730949 }
C{ 0.0 0.0 }
C{ 0.9999999999999997 2.414213562373095 }
}
|
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,... | #Delphi | Delphi |
;; M = 2^P - 1 , P prime
;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP
;; q is divisor if (powmod 2 P q) = 1
;; m-divisor returns q or #f
(define ( m-divisor P )
;; must limit the search as √ M may be HUGE
(define maxprime (min 1_000_000_000 (sqrt (expt 2 P))))
(for ((q (in-ra... |
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 se... | #J | J | Farey=: x:@/:~@(0 , ~.)@(#~ <:&1)@:,@(%/~@(1 + i.)) NB. calculates Farey sequence
displayFarey=: ('r/' charsub '0r' , ,&'r1')@": NB. format character representation of Farey sequence according to task requirements
order=: ': ' ,~ ": NB. decorate order of Farey sequen... |
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 se... | #Java | Java | import java.util.TreeSet;
public class Farey{
private static class Frac implements Comparable<Frac>{
int num;
int den;
public Frac(int num, int den){
this.num = num;
this.den = den;
}
@Override
public String toString(){
return num + "/" + den;
}
@Override
public int compareTo(Frac o)... |
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 t... | #Ruby | Ruby | def turn(base, n)
sum = 0
while n != 0 do
rem = n % base
n = n / base
sum = sum + rem
end
return sum % base
end
def fairshare(base, count)
print "Base %2d: " % [base]
for i in 0 .. count - 1 do
t = turn(base, i)
print " %2d" % [t]
end
print "\n"
... |
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... | #Pascal | Pascal |
program FaulhaberTriangle;
uses uIntX, uEnums, // units in the library IntXLib4Pascal
SysUtils;
// Convert a rational num/den to a string, right-justified in the given width.
// Before converting, remove any common factor of num and den.
// For this application we can assume den > 0.
function RationalToString(... |
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.
R... | #PARI.2FGP | PARI/GP |
\\ Using "Faulhaber's" formula based on Bernoulli numbers. aev 2/7/17
\\ In str string replace all occurrences of the search string ssrch with the replacement string srepl. aev 3/8/16
sreplace(str,ssrch,srepl)={
my(sn=#str,ssn=#ssrch,srn=#srepl,sres="",Vi,Vs,Vz,vin,vin1,vi,L=List(),tok,zi,js=1);
if(sn==0,return(... |
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}}
... | #Elixir | Elixir | defmodule RC do
def anynacci(start_sequence, count) do
n = length(start_sequence)
anynacci(Enum.reverse(start_sequence), count-n, n)
end
def anynacci(seq, 0, _), do: Enum.reverse(seq)
def anynacci(seq, count, n) do
next = Enum.sum(Enum.take(seq, n))
anynacci([next|seq], count-1, n)
end
end
... |
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 foll... | #Run_BASIC | Run BASIC | ' ------------------------------------------
' Find common directory to all directories
' and directories common with other Paths
' ------------------------------------------
print word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"<BR>") ' Universal time
dim path$(20)
path$(1) = "/home/u... |
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 foll... | #Rust | Rust |
use std::path::{Path, PathBuf};
fn main() {
let paths = [
Path::new("/home/user1/tmp/coverage/test"),
Path::new("/home/user1/tmp/covert/operator"),
Path::new("/home/user1/tmp/coven/members"),
];
match common_path(&paths) {
Some(p) => println!("The common path is: {:#?}", ... |
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.
| #F.23 | F# | let lst = [1;2;3;4;5;6]
List.filter (fun x -> x % 2 = 0) lst;;
val it : int list = [2; 4; 6] |
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.
| #Z80_Assembly | Z80 Assembly | org &0000
LD SP,&FFFF ;3 bytes
loop:
or a ;1 byte, clears the carry flag
ld (&0024),sp ;4 bytes
ld hl,(&0024) ;3 bytes
push af ;1 byte
ld bc,(&0024) ;4 bytes
sbc hl,bc ;4 bytes
jr z,loop ;2 bytes
jr * ;2 bytes
;address &0024 begins here
word 0 ;placeholder for stack pointer |
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.
| #zkl | zkl | fcn{self.fcn()}() |
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)
... | #Icon_and_Unicon | Icon and Unicon | # straight-forward modulo tester
procedure main()
every i := 1 to 100 do
if i % 15 = 0 then
write("FizzBuzz")
else if i % 5 = 0 then
write("Buzz")
else if i % 3 = 0 then
write("Fizz")
else
write(i)
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln(fileSize("input.txt"));
writeln(fileSize("/input.txt"));
end func; |
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.
| #Sidef | Sidef | say (Dir.cwd + %f'input.txt' -> size);
say (Dir.root + %f'input.txt' -> size); |
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.
| #Slate | Slate | (File newNamed: 'input.txt') fileInfo fileSize.
(File newNamed: '/input.txt') fileInfo fileSize. |
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 ... | #Lang5 | Lang5 | : puts(*) . "\n" . ;
: set-file '> swap open ;
: >>contents slurp puts ;
: copy-file
swap set-file 'fdst set fdst fout >>contents fdst close ;
'output.txt 'input.txt copy-file |
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 ... | #Liberty_BASIC | Liberty BASIC | nomainwin
open "input.txt" for input as #f1
qtyBytes = lof( #f1)
source$ = input$( #f1, qtyBytes)
close #f1
open "output.txt" for output as #f2
#f2 source$;
close #f2
end |
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-... | #Phix | Phix | with javascript_semantics
function entropy(sequence s)
sequence symbols = unique(s),
counts = repeat(0,length(symbols))
for i=1 to length(s) do
integer k = find(s[i],symbols)
counts[k] += 1
end for
atom H = 0
for i=1 to length(counts) do
atom ci = counts[i]/lengt... |
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
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: fastaFile is STD_NULL;
var string: line is "";
var boolean: first is TRUE;
begin
fastaFile := open("fasta_format.in", "r");
if fastaFile <> STD_NULL then
while hasNext(fastaFile) do
line := getln(fastaFile);
... |
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
... | #Sidef | Sidef | func fasta_format(strings) {
var out = []
var text = ''
for line in (strings.lines) {
if (line.begins_with('>')) {
text.len && (out << text)
text = line.substr(1)+': '
}
else {
text += line
}
}
text.len && (out << text)
return o... |
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
... | #Tcl | Tcl | proc fastaReader {filename} {
set f [open $filename]
set sep ""
while {[gets $f line] >= 0} {
if {[string match >* $line]} {
puts -nonewline "$sep[string range $line 1 end]: "
set sep "\n"
} else {
puts -nonewline $line
}
}
puts ""
close $f
}
fastaReader ./rosettacode.fas |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #Action.21 | Action! | INT FUNC Fibonacci(INT n)
INT curr,prev,tmp
IF n>=-1 AND n<=1 THEN
RETURN (n)
FI
prev=0
IF n>0 THEN
curr=1
DO
tmp=prev
prev=curr
curr==+tmp
n==-1
UNTIL n=1
OD
ELSE
curr=-1
DO
tmp=prev
prev=curr
curr==+tmp
n==+1
UNTIL n=-1
... |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #ALGOL-M | ALGOL-M |
BEGIN
COMMENT RETURN P MOD Q;
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
INTEGER I, N, LIMIT, FOUND, START, DELTA;
WHILE 1 = 1 DO
BEGIN
WRITE ("NUMBER TO FACTOR (OR 0 TO QUIT):");
READ (N);
IF N = 0 THEN GOTO DONE;
WRITE ("THE FACTORS ARE:");
COMME... |
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)... | #Fortran | Fortran |
module fft_mod
implicit none
integer, parameter :: dp=selected_real_kind(15,300)
real(kind=dp), parameter :: pi=3.141592653589793238460_dp
contains
! In place Cooley-Tukey FFT
recursive subroutine fft(x)
complex(kind=dp), dimension(:), intent(inout) :: x
complex(kind=dp) ... |
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,... | #EchoLisp | EchoLisp |
;; M = 2^P - 1 , P prime
;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP
;; q is divisor if (powmod 2 P q) = 1
;; m-divisor returns q or #f
(define ( m-divisor P )
;; must limit the search as √ M may be HUGE
(define maxprime (min 1_000_000_000 (sqrt (expt 2 P))))
(for ((q (in-ra... |
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 se... | #Julia | Julia | using DataStructures
function farey(n::Int)
rst = SortedSet{Rational}(Rational[0, 1])
for den in 1:n, num in 1:den-1
push!(rst, Rational(num, den))
end
return rst
end
for n in 1:11
print("F_$n: ")
for frac in farey(n)
print(numerator(frac), "/", denominator(frac), " ")
en... |
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 se... | #Kotlin | Kotlin | // version 1.1
fun farey(n: Int): List<String> {
var a = 0
var b = 1
var c = 1
var d = n
val f = mutableListOf("$a/$b")
while (c <= n) {
val k = (n + b) / d
val aa = a
val bb = b
a = c
b = d
c = k * c - aa
d = k * d - bb
f.add("$a... |
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 t... | #Rust | Rust | struct Digits {
rest: usize,
base: usize,
}
impl Iterator for Digits {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if self.rest == 0 {
return None;
}
let (digit, rest) = (self.rest % self.base, self.rest / self.base);
self.rest = rest;
... |
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 t... | #Sidef | Sidef | for b in (2,3,5,11) {
say ("#{'%2d' % b}: ", 25.of { .sumdigits(b) % b })
} |
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 t... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As 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... | #Perl | Perl | use 5.010;
use List::Util qw(sum);
use Math::BigRat try => 'GMP';
use ntheory qw(binomial bernfrac);
sub faulhaber_triangle {
my ($p) = @_;
map {
Math::BigRat->new(bernfrac($_))
* binomial($p, $_)
/ $p
} reverse(0 .. $p-1);
}
# First 10 rows of Faulhaber's triangle
foreach my... |
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.
R... | #Perl | Perl | use 5.014;
use Math::Algebra::Symbols;
sub bernoulli_number {
my ($n) = @_;
return 0 if $n > 1 && $n % 2;
my @A;
for my $m (0 .. $n) {
$A[$m] = symbols(1) / ($m + 1);
for (my $j = $m ; $j > 0 ; $j--) {
$A[$j - 1] = $j * ($A[$j - 1] - $A[$j]);
}
}
ret... |
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}}
... | #Erlang | Erlang |
-module( fibonacci_nstep ).
-export( [nacci/2, task/0] ).
nacci( N, Ns ) when N =< erlang:length(Ns) ->
{Sequence, _Not_sequence} = lists:split( N, Ns ),
Sequence;
nacci( N, Ns ) ->
Nth = erlang:length( Ns ),
{_Nth, Sequence_reversed} = lists:foldl( fun nacci_foldl/2, {Nth, lists:reverse(Ns)}, lists:seq(Nth+1... |
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 foll... | #Scala | Scala | object FindCommonDirectoryPath extends App {
def commonPath(paths: List[String]): String = {
def common(a: List[String], b: List[String]): List[String] = (a, b) match {
case (a :: as, b :: bs) if a equals b => a :: common(as, bs)
case _ => Nil
}
if (paths.length < 2) paths.headOption.getOrElse... |
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.
| #Factor | Factor | 10 <iota> >array [ even? ] filter .
! prints { 0 2 4 6 8 } |
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)
... | #Idris | Idris | partial
fizzBuzz : Nat -> String
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz"
else if (n `modNat` 3) == 0 then "Fizz"
else if (n `modNat` 5) == 0 then "Buzz"
else show n
main : IO ()
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100] |
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.
| #Smalltalk | Smalltalk | (File name: 'input.txt') size printNl.
(File name: '/input.txt') size printNl. |
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.
| #Standard_ML | Standard ML | val size = OS.FileSys.fileSize "input.txt" ;;
val size = OS.FileSys.fileSize "/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.
| #Stata | Stata | file open f using input.txt, read binary
file seek f eof
file seek f query
display r(loc)
file close f |
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 ... | #Lingo | Lingo | ----------------------------------------
-- Returns file as ByteArray
-- @param {string} tFile
-- @return {byteArray|false}
----------------------------------------
on getBytes (tFile)
fp = xtra("fileIO").new()
fp.openFile(tFile, 1)
if fp.status() then return false
data = fp.readByteArray(fp.getLength())
fp.c... |
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 ... | #Lisaac | Lisaac | Section Header
+ name := FILE_IO;
Section Public
- main <- (
+ e : ENTRY;
+ f : STD_FILE;
+ s : STRING;
e := FILE_SYSTEM.get "input.txt";
(e != NULL).if {
f ?= e.open_read_only;
(f != NULL).if {
s := STRING.create(f.size);
f.read s size (f.size);
f.close;
};
};
(s !... |
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-... | #Picat | Picat | go =>
foreach(N in 1..37)
F = fib(N),
E = entropy(F),
if N <= 10 then
printf("%3d %10d %0.16f %w\n",N,length(F),E,F)
else
printf("%3d %10d %0.16f\n",N,length(F),E)
end
end,
nl.
table
fib(1) = "1".
fib(2) = "0".
fib(N) = fib(N-1) ++ fib(N-2).
entropy(L) = Entropy => ... |
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-... | #PL.2FI | PL/I | fibword: procedure options (main); /* 9 October 2013 */
declare (fn, fnp1, fibword) bit (32000) varying;
declare (i, ln, lnp1, lfibword) fixed binary(31);
fn = '1'b; fnp1 = '0'b; ln, lnp1 = 1;
put skip edit (1, length(fn), fn) (f(2), f(10), x(1), b);
put skip edit (2, length(fnp1), fnp1) (f(2), f(... |
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
... | #TMG | TMG | prog: ignore(spaces)
loop: parse(line)\loop parse(( = {*} ));
line: ( name | * = {} | seqns );
name: <>> ignore(none) smark string(nonl) scopy *
( [f>0?] = {} | = {*} ) [f=0]
= { 1 2 <: > };
seqns: smark string(nonl) scopy * [f=0];
none: <<>>;
nonl: !<<
>>;
spaces: << >>;
f: 1; |
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
... | #uBasic.2F4tH | uBasic/4tH | If Cmd (0) < 2 Then Print "Usage: fasta <fasta file>" : End
If Set(a, Open (Cmd(2), "r")) < 0 Then Print "Cannot open \q";Cmd(2);"\q" : End
Do While Read (a) ' while there are lines to process
t = Tok (0) ' get a lime
If Peek(t, 0) = Ord(">") Then ' if it's a... |
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
... | #Wren | Wren | import "io" for File
var checkNoSpaces = Fn.new { |s| !s.contains(" ") && !s.contains("\t") }
var first = true
var process = Fn.new { |line|
if (line[0] == ">") {
if (!first) System.print()
System.write("%(line[1..-1]): ")
if (first) first = false
} else if (first) {
Fiber.... |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #ActionScript | ActionScript | public function fib(n:uint):uint
{
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #APL | APL | factors←{(0=(⍳⍵)|⍵)/⍳⍵}
factors 12345
1 3 5 15 823 2469 4115 12345
factors 720
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.