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)... | #FreeBASIC | FreeBASIC | 'Graphic fast Fourier transform demo,
'press any key for the next image.
'131072 samples: the FFT is fast indeed.
'screen resolution
const dW = 800, dH = 600
'--------------------------------------
type samples
declare constructor (byval p as integer)
'sw = 0 forward transform
'sw = 1 reverse transform
dec... |
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,... | #Elixir | Elixir | defmodule Mersenne do
def mersenne_factor(p) do
limit = :math.sqrt(:math.pow(2, p) - 1)
mersenne_loop(p, limit, 1)
end
defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil
defp mersenne_loop(p, limit, k) do
q = 2*k*p + 1
if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q),
... |
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,... | #Erlang | Erlang |
-module(mersene2).
-export([prime/1,modpow/3,mf/1]).
mf(P) -> merseneFactor(P,math:sqrt(math:pow(2,P)-1),2).
merseneFactor(P,Limit,Acc) when Acc >= Limit -> io:write("None found"); ... |
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... | #langur | langur | val .farey = f(.n) {
var .a, .b, .c, .d = 0, 1, 1, .n
while[=[[0, 1]]] .c <= .n {
val .k = (.n + .b) // .d
.a, .b, .c, .d = .c, .d, .k x .c - .a, .k x .d - .b
_while ~= [[.a, .b]]
}
}
writeln "Farey sequence for orders 1 through 11"
for .i of 11 {
writeln $"\.i:2;: ", 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 se... | #Lua | Lua | -- Return farey sequence of order n
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
-- Main procedure
for i = 1... |
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... | #Vlang | Vlang | fn fairshare(n int, base int) []int {
mut res := []int{len: n}
for i in 0..n {
mut j := i
mut sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
fn turns(n int, fss []int) string {
mut m := map[int]int... |
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... | #Wren | Wren | import "/fmt" for Fmt
import "/sort" for Sort
var fairshare = Fn.new { |n, base|
var res = List.filled(n, 0)
for (i in 0...n) {
var j = i
var sum = 0
while (j > 0) {
sum = sum + (j%base)
j = (j/base).floor
}
res[i] = sum % base
}
return r... |
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... | #Phix | Phix | with javascript_semantics
include builtins\pfrac.e -- (0.8.0+)
function bernoulli(integer n)
sequence a = {}
for m=0 to n do
a = append(a,{1,m+1})
for j=m to 1 by -1 do
a[j] = frac_mul({j,1},frac_sub(a[j+1],a[j]))
end for
end for
if n!=1 then return a[1] end if
... |
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... | #Phix | Phix | with javascript_semantics
include builtins\pfrac.e -- (0.8.0+)
function bernoulli(integer n)
sequence a = {}
for m=0 to n do
a = append(a,{1,m+1})
for j=m to 1 by -1 do
a[j] = frac_mul({j,1},frac_sub(a[j+1],a[j]))
end for
end for
if n!=1 then return a[1] end if
... |
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}}
... | #ERRE | ERRE |
PROGRAM FIBON
!
! for rosettacode.org
!
DIM F[20]
PROCEDURE FIB(TIPO$,F$)
FOR I%=0 TO 20 DO
F[I%]=0
END FOR
B=0
LOOP
Q=INSTR(F$,",")
B=B+1
IF Q=0 THEN
F[B]=VAL(F$)
EXIT
ELSE
F[B]=VAL(MID$(F$,1,Q-1))
F$=MID$(F$,Q+1)
END IF
END LOOP
PRINT(TIPO$;" =>";)
FOR I=B TO 14... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: commonLen (in array string: names, in char: sep) is func
result
var integer: result is -1;
local
var integer: index is 0;
var integer: pos is 1;
begin
if length(names) <> 0 then
repeat
for index range 1 to length(names) do
if ... |
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... | #Sidef | Sidef | var dirs = %w(
/home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members
);
var unique_pref = dirs.map{.split('/')}.abbrev.min_by{.len};
var common_dir = [unique_pref, unique_pref.pop][0].join('/');
say common_dir; # => /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.
| #Fantom | Fantom |
class Main
{
Void main ()
{
items := [1, 2, 3, 4, 5, 6, 7, 8]
// create a new list with just the even numbers
evens := items.findAll |i| { i.isEven }
// display the result
echo (evens.join(","))
}
}
|
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)
... | #Inform_6 | Inform 6 | [ Main i;
for(i = 1: i <= 100: i++)
{
if(i % 3 == 0) print "Fizz";
if(i % 5 == 0) print "Buzz";
if(i % 3 ~= 0 && i % 5 ~= 0) print i;
print "^";
}
]; |
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.
| #Tcl | Tcl | file size input.txt
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.
| #Toka | Toka | " input.txt" "R" file.open dup file.size . file.close
" /input.txt" "R" file.open dup file.size . file.close |
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.
| #TorqueScript | TorqueScript | %File = new FileObject();
%File.openForRead("input.txt");
while(!%File.isEOF())
{
%Length += strLen(%File.readLine());
}
%File.close();
%File.delete(); |
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 ... | #Logo | Logo | to copy :from :to
openread :from
openwrite :to
setread :from
setwrite :to
until [eof?] [print readrawline]
closeall
end
copy "input.txt "output.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 ... | #Lua | Lua |
inFile = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
-- other options are "*line",
-- or the number of characters to read.
inFile:close()
outFile = io.open("output.txt", "w")
outfile:write(data)
outfile:close()
-- Onel... |
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-... | #PureBasic | PureBasic | EnableExplicit
Define fwx$, n.i
NewMap uchar.i()
Macro RowPrint(ns,ls,es,ws)
Print(RSet(ns,4," ")+RSet(ls,12," ")+" "+es+" ") : If Len(ws)<55 : PrintN(ws) : Else : PrintN("...") : EndIf
EndMacro
Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure
Procedure countchar(s$, Map uchar())
If Len(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
... | #XPL0 | XPL0 | proc Echo; \Echo line of characters from file to screen
int Ch;
def LF=$0A, EOF=$1A;
[loop [Ch:= ChIn(3);
case Ch of
EOF: exit;
LF: quit
other ChOut(0, Ch);
];
];
int Ch;
[FSet(FOpen("fasta.txt", 0), ^i);
loop [Ch:= ChIn(3);
if Ch = ^> then
... |
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
... | #zkl | zkl | fcn fasta(data){ // a lazy cruise through a FASTA file
fcn(w){ // one string at a time, -->False garbage at front of file
line:=w.next().strip();
if(line[0]==">") w.pump(line[1,*]+": ",'wrap(l){
if(l[0]==">") { w.push(l); Void.Stop } else l.strip()
})
}.fp(data.walker()) : Utils.He... |
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 ... | #Ada | Ada | with Ada.Text_IO, Ada.Command_Line;
procedure Fib is
X: Positive := Positive'Value(Ada.Command_Line.Argument(1));
function Fib(P: Positive) return Positive is
begin
if P <= 2 then
return 1;
else
return Fib(P-1) + Fib(P-2);
end if;
end Fib;
begin
Ada.Text_IO.Put... |
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 |... | #AppleScript | AppleScript | -- integerFactors :: Int -> [Int]
on integerFactors(n)
if n = 1 then
{1}
else if 1 > n then
missing value
else
set realRoot to n ^ (1 / 2)
set intRoot to realRoot as integer
set blnPerfectSquare to intRoot = realRoot
-- isFactor :: Int -> Bool
scrip... |
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)... | #Frink | Frink | a = FFT[[1,1,1,1,0,0,0,0], 1, -1]
println[joinln[format[a, 1, 5]]]
|
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,... | #Factor | Factor | USING: combinators.short-circuit interpolate io kernel locals
math math.bits math.functions math.primes sequences ;
IN: rosetta-code.mersenne-factors
: mod-pow-step ( square bit m -- square' )
[ [ sq ] [ [ 2 * ] when ] bi* ] dip mod ;
:: mod-pow ( m q -- n )
1 :> s! m make-bits <reversed>
[ s swap q ... |
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,... | #Forth | Forth | : prime? ( odd -- ? )
3
begin 2dup dup * >=
while 2dup mod 0=
if 2drop false exit
then 2 +
repeat 2drop true ;
: 2-exp-mod { e m -- 2^e mod m }
1
0 30 do
e 1 i lshift >= if
dup *
e 1 i lshift and if 2* then
m mod
then
-1 +loop ;
: factor-mersenne ( exponent ... |
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... | #Maple | Maple | #Displays terms in Farey_sequence of order n
farey_sequence := proc(n)
local a,b,c,d,k;
a,b,c,d := 0,1,1,n;
printf("%d/%d", a,b);
while c <= n do
k := iquo(n+b,d);
a,b,c,d := c,d,c*k-a,d*k-b;
printf(", %d/%d", a,b)
end do;
printf("\n");
end proc:
#Returns the length of a Farey sequence
farey_l... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | farey[n_]:=StringJoin@@Riffle[ToString@Numerator[#]<>"/"<>ToString@Denominator[#]&/@FareySequence[n],", "]
TableForm[farey/@Range[11]]
Table[Length[FareySequence[n]], {n, 100, 1000, 100}] |
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... | #XPL0 | XPL0 | proc Fair(Base); \Show first 25 terms of fairshare sequence
int Base, Count, Sum, N, Q;
[RlOut(0, float(Base)); Text(0, ": ");
for Count:= 0 to 25-1 do
[Sum:= 0; N:= Count;
while N do
[Q:= N/Base;
Sum:= Sum + rem(0);
N:= Q;
];
RlOut(0, float(rem(Sum/Base)));
];
CrLf(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 t... | #zkl | zkl | fcn fairShare(n,b){ // b<=36
n.pump(List,'wrap(n){ n.toString(b).split("").apply("toInt",b).sum(0)%b })
}
foreach b in (T(2,3,5,11)){
println("%2d: %s".fmt(b,fairShare(25,b).pump(String,"%2d ".fmt)));
} |
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... | #Prolog | Prolog |
ft_rows(Lz) :-
lazy_list(ft_row, [], Lz).
ft_row([], R1, R1) :- R1 = [1].
ft_row(R0, R2, R2) :-
length(R0, P),
Jmax is 1 + P, numlist(2, Jmax, Qs),
maplist(term(P), Qs, R0, R1),
sum_list(R1, S), Bk is 1 - S, % Bk is Bernoulli number
R2 = [Bk | R1].
term(P, Q, R, S) :- S is R * (P rdiv Q).
... |
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... | #Python | Python | from fractions import Fraction
def nextu(a):
n = len(a)
a.append(1)
for i in range(n - 1, 0, -1):
a[i] = i * a[i] + a[i - 1]
return a
def nextv(a):
n = len(a) - 1
b = [(1 - n) * x for x in a]
b.append(1)
for i in range(n):
b[i + 1] += a[i]
return b
def sumpol(n)... |
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}}
... | #F.23 | F# | let fibinit = Seq.append (Seq.singleton 1) (Seq.unfold (fun n -> Some(n, 2*n)) 1)
let fiblike init =
Seq.append
(Seq.ofList init)
(Seq.unfold
(function | least :: rest ->
let this = least + Seq.reduce (+) rest
Some(this, rest @ ... |
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... | #Standard_ML | Standard ML | fun takeWhileEq ([], _) = []
| takeWhileEq (_, []) = []
| takeWhileEq (x :: xs, y :: ys) =
if x = y then x :: takeWhileEq (xs, ys) else []
fun commonPath sep =
let
val commonInit = fn [] => [] | x :: xs => foldl takeWhileEq x xs
and split = String.fields (fn c => c = sep)
and join = String.con... |
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... | #Swift | Swift | import Foundation
func getPrefix(_ text:[String]) -> String? {
var common:String = text[0]
for i in text {
common = i.commonPrefix(with: common)
}
return common
}
var test = ["/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"]
var outpu... |
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.
| #Forth | Forth | : sel ( dest 0 test src len -- dest len )
cells over + swap do ( dest len test )
i @ over execute if
i @ 2over cells + !
>r 1+ r>
then
cell +loop drop ;
create nums 1 , 2 , 3 , 4 , 5 , 6 ,
create evens 6 cells allot
: .array 0 ?do dup i cells + @ . loop drop ;
: even? ( n -- ? ) 1 and 0... |
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)
... | #Inform_7 | Inform 7 | Home is a room.
When play begins:
repeat with N running from 1 to 100:
let printed be false;
if the remainder after dividing N by 3 is 0:
say "Fizz";
now printed is true;
if the remainder after dividing N by 5 is 0:
say "Buzz";
now printed is true;
if printed is false, say N;
say ".";
end the ... |
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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
-- size of file input.txt
file="input.txt"
ERROR/STOP OPEN (file,READ,-std-)
file_size=BYTES ("input.txt")
ERROR/STOP CLOSE (file)
-- size of file x:/input.txt
ERROR/STOP OPEN (file,READ,x)
file_size=BYTES (file)
ERROR/STOP CLOSE (file)
|
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.
| #UNIX_Shell | UNIX Shell | size1=$(ls -l input.txt | tr -s ' ' | cut -d ' ' -f 5)
size2=$(ls -l /input.txt | tr -s ' ' | cut -d ' ' -f 5) |
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.
| #Ursa | Ursa | decl file f
f.open "input.txt"
out (size f) endl console
f.close
f.open "/input.txt"
out (size f) endl console
f.close |
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 ... | #M2000_Interpreter | M2000 Interpreter |
Module FileInputOutput {
Edit "Input.txt"
Document Doc$
Load.Doc Doc$, "Input.txt"
Report Doc$
Print "Press a key:";Key$
Save.Doc Doc$, "Output.txt"
Edit "Output.txt"
}
FileInputOutput
|
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 ... | #Maple | Maple |
inout:=proc(filename)
local f;
f:=FileTools[Text][ReadFile](filename);
FileTools[Text][WriteFile]("output.txt",f);
end proc;
|
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-... | #Python | Python | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length En... |
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 ... | #AdvPL | AdvPL |
#include "totvs.ch"
User Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
|
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 |... | #Arc | Arc |
(= divisor (fn (num)
(= dlist '())
(when (is 1 num) (= dlist '(1 0)))
(when (is 2 num) (= dlist '(2 1)))
(unless (or (is 1 num) (is 2 num))
(up i 1 (+ 1 (/ num 2))
(if (is 0 (mod num i))
(push i dlist)))
(= dlist (cons num dlist)))
dlist))
(map [rev _] (map [divisor _] '(45 53 60 ... |
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)... | #GAP | GAP | # Here an implementation with no optimization (O(n^2)).
# In GAP, E(n) = exp(2*i*pi/n), a primitive root of the unity.
Fourier := function(a)
local n, z;
n := Size(a);
z := E(n);
return List([0 .. n - 1], k -> Sum([0 .. n - 1], j -> a[j + 1]*z^(-k*j)));
end;
InverseFourier := function(a)
local n, z;
n := Size... |
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,... | #Fortran | Fortran | PROGRAM EXAMPLE
IMPLICIT NONE
INTEGER :: exponent, factor
WRITE(*,*) "Enter exponent of Mersenne number"
READ(*,*) exponent
factor = Mfactor(exponent)
IF (factor == 0) THEN
WRITE(*,*) "No Factor found"
ELSE
WRITE(*,"(A,I0,A,I0)") "M", exponent, " has a factor: ", factor
END IF
CONTAINS
FUN... |
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... | #Nim | Nim | import strformat
proc farey(n: int) =
var f1 = (d: 0, n: 1)
var f2 = (d: 1, n: n)
write(stdout, fmt"0/1 1/{n}")
while f2.n > 1:
let k = (n + f1.n) div f2.n
let aux = f1
f1 = f2
f2 = (f2.d * k - aux.d, f2.n * k - aux.n)
write(stdout, fmt" {f2.d}/{f2.n}")
write(stdout, "\n")
proc fareyLe... |
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... | #PARI.2FGP | PARI/GP | Farey(n)=my(v=List()); for(k=1,n,for(i=0,k,listput(v,i/k))); vecsort(Set(v));
countFarey(n)=1+sum(k=1, n, eulerphi(k));
fmt(n)=if(denominator(n)>1,n,Str(n,"/1"));
for(n=1,11,print(apply(fmt, Farey(n))))
apply(countFarey, 100*[1..10]) |
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... | #Python | Python | '''Faulhaber's triangle'''
from itertools import accumulate, chain, count, islice
from fractions import Fraction
# faulhaberTriangle :: Int -> [[Fraction]]
def faulhaberTriangle(m):
'''List of rows of Faulhaber fractions.'''
def go(rs, n):
def f(x, y):
return Fraction(n, x) * y
... |
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... | #Racket | Racket | #lang racket/base
(require racket/match
racket/string
math/number-theory)
(define simplify-arithmetic-expression
(letrec ((s-a-e
(match-lambda
[(list (and op '+) l ... (list '+ m ...) r ...) (s-a-e `(,op ,@l ,@m ,@r))]
[(list (and op '+) l ... (? number? n... |
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}}
... | #Factor | Factor | USING: formatting fry kernel make math namespaces qw sequences ;
: n-bonacci ( n initial -- seq ) [
[ [ , ] each ] [ length - ] [ length ] tri
'[ building get _ tail* sum , ] times
] { } make ;
qw{ fibonacci tribonacci tetranacci lucas }
{ { 1 1 } { 1 1 2 } { 1 1 2 4 } { 2 1 } }
[ 10 swap n-bona... |
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... | #Tcl | Tcl | package require Tcl 8.5
proc pop {varname} {
upvar 1 $varname var
set var [lassign $var head]
return $head
}
proc common_prefix {dirs {separator "/"}} {
set parts [split [pop dirs] $separator]
while {[llength $dirs]} {
set r {}
foreach cmp $parts elt [split [pop dirs] $separator] {... |
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.
| #Fortran | Fortran | module funcs
implicit none
contains
pure function iseven(x)
logical :: iseven
integer, intent(in) :: x
iseven = mod(x, 2) == 0
end function iseven
end module funcs |
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)
... | #Io | Io | for(a,1,100,
if(a % 15 == 0) then(
"FizzBuzz" println
) elseif(a % 3 == 0) then(
"Fizz" println
) elseif(a % 5 == 0) then(
"Buzz" println
) else (
a println
)
) |
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.
| #VBScript | VBScript |
With CreateObject("Scripting.FileSystemObject")
WScript.Echo .GetFile("input.txt").Size
WScript.Echo .GetFile("\input.txt").Size
End With
|
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.
| #Vedit_macro_language | Vedit macro language | Num_Type(File_Size("input.txt"))
Num_Type(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.
| #Visual_Basic | Visual Basic | Option Explicit
----
Sub DisplayFileSize(ByVal Path As String, ByVal Filename As String)
Dim i As Long
If InStr(Len(Path), Path, "\") = 0 Then
Path = Path & "\"
End If
On Error Resume Next 'otherwise runtime error if file does not exist
i = FileLen(Path & Filename)
If Err.Number = 0 Then
Debug.Pri... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetDirectory@NotebookDirectory[];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.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 ... | #MAXScript | MAXScript | inFile = openFile "input.txt"
outFile = createFile "output.txt"
while not EOF inFile do
(
format "%" (readLine inFile) to:outFile
)
close inFile
close outFile |
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-... | #R | R | entropy <- function(s)
{
if (length(s) > 1)
return(sapply(s, entropy))
freq <- prop.table(table(strsplit(s, '')[1]))
ret <- -sum(freq * log(freq, base=2))
return(ret)
}
fibwords <- function(n)
{
if (n == 1)
fibwords <- "1"
else
fibwords <- c("1", "0")
if (n > 2)
{
for (i in 3:n)
... |
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 ... | #Aime | Aime | integer
fibs(integer n)
{
integer w;
if (n == 0) {
w = 0;
} elif (n == 1) {
w = 1;
} else {
integer a, b, i;
i = 1;
a = 0;
b = 1;
while (i < n) {
w = a + b;
a = b;
b = w;
i += 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 |... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program factorst.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessDeb: .ascii "Factors of :"
sMessValeur: .fill 12, 1, ' '
.asciz "ar... |
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)... | #Go | Go | package main
import (
"fmt"
"math"
"math/cmplx"
)
func ditfft2(x []float64, y []complex128, n, s int) {
if n == 1 {
y[0] = complex(x[0], 0)
return
}
ditfft2(x, y, n/2, 2*s)
ditfft2(x[s:], y[n/2:], n/2, 2*s)
for k := 0; k < n/2; k++ {
tf := cmplx.Rect(1, -2*mat... |
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,... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As Integer) As Boolean
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
' test 929 plu... |
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... | #Pascal | Pascal | program Farey;
{$IFDEF FPC }{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils;
type
tNextFarey= record
nom,dom,n,c,d: longInt;
end;
function InitFarey(maxdom:longINt):tNextFarey;
Begin
with result do
Begin
nom := 0; dom := 1; n := maxdom;... |
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... | #Racket | Racket | #lang racket
(require math/number-theory)
(define (second-bernoulli-number n)
(if (= n 1) 1/2 (bernoulli-number n)))
(define (faulhaber-row:formulaic p)
(let ((p+1 (+ p 1)))
(reverse
(for/list ((j (in-range p+1)))
(* (/ p+1) (second-bernoulli-number j) (binomial p+1 j))))))
(define (sum-k^p:fo... |
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... | #Raku | Raku | # Helper subs
sub infix:<reduce> (\prev, \this) { this.key => this.key * (this.value - prev.value) }
sub next-bernoulli ( (:key($pm), :value(@pa)) ) {
$pm + 1 => [ map *.value, [\reduce] ($pm + 2 ... 1) Z=> 1 / ($pm + 2), |@pa ]
}
constant bernoulli = (0 => [1.FatRat], &next-bernoulli ... *).map: { .value[*-1... |
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... | #Raku | Raku | sub bernoulli_number($n) {
return 1/2 if $n == 1;
return 0/1 if $n % 2;
my @A;
for 0..$n -> $m {
@A[$m] = 1 / ($m + 1);
for $m, $m-1 ... 1 -> $j {
@A[$j - 1] = $j * (@A[$j - 1] - @A[$j]);
}
}
return @A[0];
}
sub binomial($n, $k) {
$k == 0 || $n == ... |
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}}
... | #Forth | Forth | : length @ ; \ length of an array is stored at its address
: a{ here cell allot ;
: } , here over - cell / over ! ;
defer nacci
: step ( a- i n -- a- i m )
>r 1- 2dup nacci r> + ;
: steps ( a- i n -- m )
0 tuck do step loop nip nip ;
:noname ( a- i -- n )
over length ove... |
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... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
common=""
dir1="/home/user1/tmp/coverage/test"
dir2="/home/user1/tmp/covert/operator"
dir3="/home/user1/tmp/coven/members"
dir1=SPLIT (dir1,":/:"),dir2=SPLIT (dir2,":/:"), dir3=SPLIT (dir3,":/:")
LOOP d1=dir1,d2=dir2,d3=dir3
IF (d1==d2,d3) THEN
common=APPEND(common,d1,"/")
ELSE
PRINT common
E... |
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... | #UNIX_Shell | UNIX Shell |
#!/bin/sh
pathlist='/home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members'
i=2
while [ $i -lt 100 ]
do
path=`echo "$pathlist" | cut -f1-$i -d/ | uniq -d`
if [ -z "$path" ]
then
echo $prev_path
break
else
prev_path=$path
fi
i=`expr $i + 1`
done
|
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type FilterType As Function(As Integer) As Boolean
Function isEven(n As Integer) As Boolean
Return n Mod 2 = 0
End Function
Sub filterArray(a() As Integer, b() As Integer, filter As FilterType)
If UBound(a) = -1 Then Return '' empty array
Dim count As Integer = 0
Redim b(0 To UBound(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)
... | #Ioke | Ioke | (1..100) each(x,
cond(
(x % 15) zero?, "FizzBuzz" println,
(x % 3) zero?, "Fizz" println,
(x % 5) zero?, "Buzz" println
)
) |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Dim local As New IO.FileInfo("input.txt")
Console.WriteLine(local.Length)
Dim root As New IO.FileInfo("\input.txt")
Console.WriteLine(root.Length) |
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.
| #Wren | Wren | import "io" for File
var name = "input.txt"
System.print("'%(name)' has a a size of %(File.size(name)) 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.
| #X86_Assembly | X86 Assembly |
; x86_64 linux nasm
section .data
localFileName: db "input.txt", 0
rootFileName: db "/initrd.img", 0
section .text
global _start
_start:
; open file in current dir
mov rax, 2
mov rdi, localFileName
xor rsi, rsi
mov rdx, 0
syscall
push rax
mov rdi, rax ; file descriptior
mov rsi, 0 ; offs... |
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 ... | #Mercury | Mercury | :- module file_io.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
main(!IO) :-
io.open_input("input.txt", InputRes, !IO),
(
InputRes = ok(Input),
io.read_file_as_string(Input, ReadRes, !IO),
(
ReadRes = ok(Contents),
io.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 ... | #mIRC_Scripting_Language | mIRC Scripting Language | alias Write2FileAndReadIt {
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
} |
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-... | #Racket | Racket | #lang racket
(provide F-Word gen-F-Word (struct-out f-word) f-word-max-length)
(require "entropy.rkt") ; save Entropy task implementation as "entropy.rkt"
(define f-word-max-length (make-parameter 80))
(define-struct f-word (str length count-0 count-1))
(define (string->f-word str)
(apply f-word str
(call-... |
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-... | #Raku | Raku | constant @fib-word = 1, 0, { $^b ~ $^a } ... *;
sub entropy {
-log(2) R/
[+] map -> \p { p * log p },
$^string.comb.Bag.values »/» $string.chars
}
for @fib-word[^37] {
printf "%5d\t%10d\t%.8e\t%s\n",
(state $n)++, .chars, .&entropy, $n > 10 ?? '' !! $_;
} |
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 ... | #ALGOL_60 | ALGOL 60 | begin
comment Fibonacci sequence;
integer procedure fibonacci(n); value n; integer n;
begin
integer i, fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn := 0;
for i := 1 step 1 until n do begin
fn := fn1 + fn2;
fn2 := fn1;
fn1 := fn
en... |
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 |... | #Arturo | Arturo | factors: $[num][
select 1..num [x][
(num%x)=0
]
]
print factors 36 |
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)... | #Golfscript | Golfscript | #Cooley-Tukey
{.,.({[\.2%fft\(;2%fft@-1?-1\?-2?:w;.,,{w\?}%[\]zip{{*}*}%]zip.{{+}*}%\{{-}*}%+}{;}if}:fft;
[1 1 1 1 0 0 0 0]fft n*
|
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,... | #Frink | Frink | for p = primes[]
if modPow[2, 929, p] - 1 == 0
println[p] |
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,... | #GAP | GAP | MersenneSmallFactor := function(n)
local k, m, d;
if IsPrime(n) then
d := 2*n;
m := 1;
for k in [1 .. 1000000] do
m := m + d;
if PowerModInt(2, n, m) = 1 then
return m;
fi;
od;
fi;
return fail;
end;
# If n is not pri... |
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... | #Perl | Perl | use warnings;
use strict;
use Math::BigRat;
use ntheory qw/euler_phi vecsum/;
sub farey {
my $N = shift;
my @f;
my($m0,$n0, $m1,$n1) = (0, 1, 1, $N);
push @f, Math::BigRat->new("$m0/$n0");
push @f, Math::BigRat->new("$m1/$n1");
while ($f[-1] < 1) {
my $m = int( ($n0 + $N) / $n1) * $m1 - $m0;
my $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... | #REXX | REXX | Numeric Digits 100
Do r=0 To 20
ra=r-1
If r=0 Then
f.r.1=1
Else Do
rsum=0
Do c=2 To r+1
ca=c-1
f.r.c=fdivide(fmultiply(f.ra.ca,r),c)
rsum=fsum(rsum,f.r.c)
End
f.r.1=fsubtract(1,rsum)
End
End
Do r=0 To 9
ol=''
Do c=1 To r+1
ol=ol right(f.r.c,5)
End
Say ol... |
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... | #Ruby | Ruby | def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k+1 .. n do
num = num * i
end
denom = 1
for i in 2 .. n-k do
denom = denom * i
end
return num / denom
end
def bernoul... |
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}}
... | #Fortran | Fortran |
! save this program as file f.f08
! gnu-linux command to build and test
! $ a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e 2\\n5\\n\\n | $a
! -*- mode: compilation; default-directory: "/tmp/" -*-
! Compilation started at Fri Apr 4 23:20:27
!
! a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e... |
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... | #Ursala | Ursala | #import std
comdir"s" "p" = mat"s" reduce(gcp,0) (map sep "s") "p" |
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... | #VBScript | VBScript |
' Read the list of paths (newline-separated) into an array...
strPaths = Split(WScript.StdIn.ReadAll, vbCrLf)
' Split each path by the delimiter (/)...
For i = 0 To UBound(strPaths)
strPaths(i) = Split(strPaths(i), "/")
Next
With CreateObject("Scripting.FileSystemObject")
' Test each path segment...
For j = ... |
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.
| #Frink | Frink |
b = array[1 to 100]
c = select[b, {|x| x mod 2 == 0}]
|
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)
... | #Iptscrae | Iptscrae | ; FizzBuzz in Iptscrae
1 a =
{
"" b =
{ "fizz" b &= } a 3 % 0 == IF
{ "buzz" b &= } a 5 % 0 == IF
{ a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE
a ++
}
{ a 100 <= } WHILE |
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.
| #XPL0 | XPL0 | proc ShowSize(FileName);
char FileName; int Size, C;
[Trap(false); \disable abort on error
FSet(FOpen(FileName, 0), ^i);
Size:= 0;
repeat C:= ChIn(3); \reads 2 EOFs before
Size:= Size+1; \ read beyond end-of-file
until GetErr; \ is detected
IntOut(0, Size-2);
CrLf(0);
];
[ShowSize("in... |
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.
| #zkl | zkl | File.info("input.txt").println();
File.info("/input.txt").println(); |
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 ... | #Modula-3 | Modula-3 | MODULE FileIO EXPORTS Main;
IMPORT IO, Rd, Wr;
<*FATAL ANY*>
VAR
infile: Rd.T;
outfile: Wr.T;
txt: TEXT;
BEGIN
infile := IO.OpenRead("input.txt");
outfile := IO.OpenWrite("output.txt");
txt := Rd.GetText(infile, LAST(CARDINAL));
Wr.PutText(outfile, txt);
Rd.Close(infile);
Wr.Close(outfile);
EN... |
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 ... | #Nanoquery | Nanoquery | import Nanoquery.IO
input = new(File, "input.txt")
output = new(File)
output.create("output.txt")
output.open("output.txt")
contents = input.readAll()
output.write(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-... | #REXX | REXX | /*REXX program displays the number of chars in a fibonacci word, and the word's entropy.*/
d= 21; de= d + 6; numeric digits de /*use more precision (the default is 9)*/
parse arg N . /*get optional argument from the C.L. */
if N=='' | N=="," then N= 42 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.