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/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 ...
#Lua
Lua
local file = io.open("input.txt","r") local data = file:read("*a") file:close()   local output = {} local key = nil   -- iterate through lines for line in data:gmatch("(.-)\r?\n") do if line:match("%s") then error("line contained space") elseif line:sub(1,1) == ">" then key = line:sub(2) -- if key already exist...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Class FASTA_MACHINE { Events "GetBuffer", "header", "DataLine", "Quit" Public: Module Run { Const lineFeed$=chr$(13)+chr$(10) Const WhiteSpace$=" "+chr$(9)+chrcode$(160) Def long state=1, idstate=1 ...
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 ...
#0815
0815
  %<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~> }:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?  
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 |...
#360_Assembly
360 Assembly
* Factors of an integer - 07/10/2015 FACTOR CSECT USING FACTOR,R15 set base register LA R7,PG pgi=@pg LA R6,1 i L R3,N loop count LOOP L R5,N n LA R4,0 DR R4,R6 ...
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)...
#C
C
    #include <stdio.h> #include <math.h> #include <complex.h>   double PI; typedef double complex cplx;   void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2);   for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI...
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,...
#Arturo
Arturo
mersenneFactors: function [q][ if not? prime? q -> print "number not prime!" r: new q while -> r > 0 -> shl 'r 1 d: new 1 + 2 * q while [true][ i: new 1 p: new r while [p <> 0][ i: new (i * i) % d if p < 0 -> 'i * 2 if i > d -> 'i...
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,...
#AutoHotkey
AutoHotkey
MsgBox % MFact(27) ;-1: 27 is not prime MsgBox % MFact(2) ; 0 MsgBox % MFact(3) ; 0 MsgBox % MFact(5) ; 0 MsgBox % MFact(7) ; 0 MsgBox % MFact(11) ; 23 MsgBox % MFact(13) ; 0 MsgBox % MFact(17) ; 0 MsgBox % MFact(19) ; 0 MsgBox % MFact(23) ; 47 MsgBox % MFact(29) ; 233 MsgBox % MFact(31) ; 0 MsgBox % MF...
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...
#Crystal
Crystal
require "big"   def farey(n) a, b, c, d = 0, 1, 1, n fracs = [] of BigRational fracs << BigRational.new(0,1) while c <= n k = (n + b) // d a, b, c, d = c, d, k * c - a, k * d - b fracs << BigRational.new(a,b) end fracs.uniq.sort end   puts "Farey sequence for order 1 thro...
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...
#Haskell
Haskell
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap)   ------------- FAIR SHARE BETWEEN TWO AND MORE ------------   thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..]   baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( su...
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...
#Haskell
Haskell
import Data.Ratio (Ratio, denominator, numerator, (%))   ------------------------ FAULHABER -----------------------   faulhaber :: Int -> Rational -> Rational faulhaber p n = sum $ zipWith ((*) . (n ^)) [1 ..] (faulhaberTriangle !! p)     faulhaberTriangle :: [[Rational]] faulhaberTriangle = tail $ scanl ...
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...
#J
J
Bsecond=:verb define"0 +/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y )   Bfirst=: Bsecond - 1&=   Faul=:adverb define (0,|.(%m+1x) * (_1x&^ * !&(m+1) * Bfirst) i.1+m)&p. )
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Wren
Wren
import "/big" for BigInt   var fermat = Fn.new { |n| BigInt.two.pow(2.pow(n)) + 1 }   var fns = List.filled(10, null) System.print("The first 10 Fermat numbers are:") for (i in 0..9) { fns[i] = fermat.call(i) System.print("F%(String.fromCodePoint(0x2080+i)) = %(fns[i])") }   System.print("\nFactors of the first...
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}} ...
#C
C
/* The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/   #include<stdlib.h> #include<stdio.h>   int * anynacci (int *seedArray, int howMany) { int *...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#zkl
zkl
fcn feigenbaum{ maxIt,maxItJ,a1,a2,d1,a,d := 13, 10, 1.0, 0.0, 3.2, 0, 0; println(" i d"); foreach i in ([2..maxIt]){ a=a1 + (a1 - a2)/d1; foreach j in ([1..maxItJ]){ x,y := 0.0, 0.0; foreach k in ([1..(1).shiftLeft(i)]){ y,x = 1.0 - 2.0*y*x, a - x*x; } a-=x/y } d=(a1...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Smalltalk
Smalltalk
|a| a := File name: 'input.txt'. (a lastModifyTime) printNl.
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Standard_ML
Standard ML
val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)   (* unfortunately it seems like you have to set modification & access times together *) OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *) (* equivalent to: *) OS.FileSys.setTime (filename, SOME (Time.now (...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Tcl
Tcl
# Get the modification time: set timestamp [file mtime $filename]   # Set the modification time to ‘now’: file mtime $filename [clock seconds]
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Tcl
Tcl
package require Tk   # OK, this stripped down version doesn't work for n<2… proc fibword {n} { set fw {1 0} while {[llength $fw] < $n} { lappend fw [lindex $fw end][lindex $fw end-1] } return [lindex $fw end] } proc drawFW {canv fw {w {[$canv cget -width]}} {h {[$canv cget -height]}}} { set w [subs...
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...
#PHP
PHP
<?php   /* This works with dirs and files in any number of combinations. */   function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]);   $arr[$i] = count($dirList[$i]); }   $min = min($arr);   for($i = 0; $i < count($dir...
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
filter pred lst: ] for value in copy lst: if pred @value: @value [   even x: = 0 % x 2   !. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]
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.
#Ruby
Ruby
def recurse x puts x recurse(x+1) end   recurse(0)
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.
#Run_BASIC
Run BASIC
a = recurTest(1)   function recurTest(n) if n mod 100000 then cls:print n if n > 327000 then [ext] n = recurTest(n+1) [ext] end function
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) ...
#GW-BASIC
GW-BASIC
fizzbuzz :: Int -> String fizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x   main :: IO () main = mapM_ (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.
#Pascal
Pascal
my $size1 = -s 'input.txt'; my $size2 = -s '/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.
#Perl
Perl
my $size1 = -s 'input.txt'; my $size2 = -s '/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.
#Phix
Phix
function file_size(sequence file_name) object d = dir(file_name) if atom(d) or length(d)!=1 then return -1 end if return d[1][D_SIZE] end function procedure test(sequence file_name) integer size = file_size(file_name) if size<0 then printf(1,"%s file does not exist.\n",{file_name}) else ...
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 ...
#Go
Go
package main   import ( "fmt" "io/ioutil" )   func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
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 ...
#Groovy
Groovy
content = new File('input.txt').text new File('output.txt').write(content)
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-...
#jq
jq
# Input: an array of strings. # Output: an object with the strings as keys, # the values of which are the corresponding frequencies. def counter: reduce .[] as $item ( {}; .[$item] += 1 ) ;   # entropy in bits of the input string def entropy: (explode | map( [.] | implode ) | counter | [ .[] | . * (.|log) ] | add)...
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-...
#Julia
Julia
using DataStructures entropy(s::AbstractString) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s)))   function fibboword(n::Int64) # Initialize the result r = Array{String}(n) # First element r[1] = "0" # If more than 2, set the second element if n ≥ 2 r[2] = "1" end # Recur...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ImportString[">Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED ", "FASTA"]
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 ...
#Nim
Nim
  import strutils   let input = """>Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED""".unindent   proc fasta*(input: string) = var row = "" for line in input.splitLines: if line.startsWith(">"): if row != "": ech...
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 ...
#Objeck
Objeck
class Fasta { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { is_line := false; tokens := System.Utility.Parser->Tokenize(System.IO.File.FileReader->ReadFile(args[0]))<String>; each(i : tokens) { token := tokens->Get(i); if(token->Get(0) = '>') { i...
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 ...
#11l
11l
F fib_iter(n) I n < 2 R n V fib_prev = 1 V fib = 1 L 2 .< n (fib_prev, fib) = (fib, fib + fib_prev) R fib   L(i) 1..20 print(fib_iter(i), end' ‘ ’) print()
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 |...
#68000_Assembly
68000 Assembly
;max input range equals 0 to 0xFFFFFFFF.       jsr GetInput ;unimplemented routine to get user input for a positive (nonzero) integer. ;output of this routine will be in D0.   MOVE.L D0,D1 ;D1 will be used for temp storage. MOVE.L #1,D2 ;start with 1.   computeFactors: DIVU D2,D1 ...
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)...
#C.23
C#
using System; using System.Numerics; using System.Linq; using System.Diagnostics;   // Fast Fourier Transform in C# public class Program {   /* Performs a Bit Reversal Algorithm on a postive integer * for given number of bits * e.g. 011 with 3 bits is reversed to 110 */ public static int BitReverse(i...
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,...
#BBC_BASIC
BBC BASIC
PRINT "A factor of M929 is "; FNmersenne_factor(929) PRINT "A factor of M937 is "; FNmersenne_factor(937) END   DEF FNmersenne_factor(P%) LOCAL K%, Q% IF NOT FNisprime(P%) THEN = -1 FOR K% = 1 TO 1000000 Q% = 2*K%*P% + 1 IF (Q% AND 7) = 1 OR (Q% AND 7) = 7 THEN ...
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,...
#Bracmat
Bracmat
( ( modPow = square P divisor highbit log 2pow .  !arg:(?P.?divisor) & 1:?square & 2\L!P:#%?log+? & 2^!log:?2pow & whl ' ( mod $ ( ( div$(!P.!2pow):1&2 | 1 ) * !square^2 . !divisor ...
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...
#D
D
import std.stdio, std.algorithm, std.range, arithmetic_rational;   auto farey(in int n) pure nothrow @safe { return rational(0, 1).only.chain( iota(1, n + 1) .map!(k => iota(1, k + 1).map!(m => rational(m, k))) .join.sort().uniq); }   void main() @safe { writefln("Farey seque...
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...
#J
J
fairshare=: [ | [: +/"1 #.inv 2 3 5 11 fairshare"0 1/i.25 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 0 1 2 1 2 0 2 0 1 1 2 0 2 0 1 0 1 2 2 0 1 0 1 2 1 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 0 2 3 4 NB. In the 1st 50000 how many turns does e...
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...
#Java
Java
  import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class FairshareBetweenTwoAndMore {   public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } ...
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...
#J
J
faulhaberTriangle=: ([: %. [: x: (1 _2 (p.) 2 | +/~) * >:/~ * (!~/~ >:))@:i. faulhaberTriangle 10 1 0 0 0 0 0 0 0 0 0 1r2 1r2 0 0 0 0 0 0 0 0 1r6 1r2 1r3 0 0 0 0 0 0 0 0 1r4 1r2 1r4 0 0 0 0 0 0 _1r30 ...
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...
#Java
Java
import java.util.Arrays; import java.util.stream.IntStream;   public class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); }   private static class Frac implements Comparable<Frac> { private long num; ...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#zkl
zkl
fermatsW:=[0..].tweak(fcn(n){ BI(2).pow(BI(2).pow(n)) + 1 }); println("First 10 Fermat numbers:"); foreach n in (10){ println("F",n,": ",fermatsW.next()) }
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}} ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Fibonacci { class Program { static void Main(string[] args) { PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10)); PrintNumberSequence("Lucas", GetLucasNumbers(10)); ...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT file="rosetta.txt" ERROR/STOP OPEN (file,READ,-std-) modified=MODIFIED (file) PRINT "file ",file," last modified: ",modified  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#UNIX_Shell
UNIX Shell
T=`stat -c %Y $F`
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ursa
Ursa
decl java.util.Date d decl file f   f.open "example.txt" d.setTime (f.lastmodified) out d endl console   f.setlastmodified 10
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class FibonacciWordFractal { construct new(width, height, n) { Window.title = "Fibonacci Word Fractal" Window.resize(width, height) Canvas.resize(width, height) _fore = Color.green _wordFractal = wordFractal(n) ...
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Picat
Picat
find_common_directory_path(Dirs) = Path => maxof( (common_prefix(Dirs, Path,Len), append(_,"/",Path)), Len).   % % Find a common prefix of all lists/strings in Ls. % Using append/3. % common_prefix(Ls, Prefix,Len) => foreach(L in Ls) append(Prefix,_,L) end, Len = Prefix.length.
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...
#PicoLisp
PicoLisp
(de commonPath (Lst Chr) (glue Chr (make (apply find (mapcar '((L) (split (chop L) Chr)) Lst) '(@ (or (pass <>) (nil (link (next))))) ) ) ) )
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.
#E
E
pragma.enable("accumulator") accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Rust
Rust
fn recurse(n: i32) { println!("depth: {}", n); recurse(n + 1) }   fn main() { recurse(0); }
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.
#Sather
Sather
class MAIN is attr r:INT; recurse is r := r + 1; #OUT + r + "\n"; recurse; end; main is r := 0; recurse; end; end;
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.
#Scala
Scala
def recurseTest(i:Int):Unit={ try{ recurseTest(i+1) } catch { case e:java.lang.StackOverflowError => println("Recursion depth on this system is " + i + ".") } } recurseTest(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) ...
#Haskell
Haskell
fizzbuzz :: Int -> String fizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x   main :: IO () main = mapM_ (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.
#PHP
PHP
<?php echo filesize('input.txt'), "\n"; echo filesize('/input.txt'), "\n"; ?>
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#PicoLisp
PicoLisp
(println (car (info "input.txt"))) (println (car (info "/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.
#Pike
Pike
import Stdio;   int main(){ write(file_size("input.txt") + "\n"); write(file_size("/input.txt") + "\n"); }
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 ...
#GUISS
GUISS
Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste, Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]
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 ...
#Haskell
Haskell
main = readFile "input.txt" >>= writeFile "output.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-...
#Kotlin
Kotlin
// version 1.0.6   fun fibWord(n: Int): String { if (n < 1) throw IllegalArgumentException("Argument can't be less than 1") if (n == 1) return "1" val words = Array(n){ "" } words[0] = "1" words[1] = "0" for (i in 2 until n) words[i] = words[i - 1] + words[i - 2] return words[n - 1] }   fun ...
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 ...
#OCaml
OCaml
  (* This program reads from the standard input and writes to standard output. * Examples of use: * $ ocaml fasta.ml < fasta_file.txt * $ ocaml fasta.ml < fasta_file.txt > my_result.txt * * The FASTA file is assumed to have a specific format, where the first line * contains a label in the form of '>blablabl...
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 ...
#Pascal
Pascal
  program FASTA_Format; // FPC 3.0.2 var InF, OutF: Text; ch: char; First: Boolean=True; InDef: Boolean=False;   begin Assign(InF,''); Reset(InF); Assign(OutF,''); Rewrite(OutF); While Not Eof(InF) do begin Read(InF,ch); Case Ch of '>': begin if Not(First) then ...
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 ...
#360_Assembly
360 Assembly
* Fibonacci sequence 05/11/2014 * integer (31 bits) = 10 decimals -> max fibo(46) FIBONACC CSECT USING FIBONACC,R12 base register SAVEAREA B STM-SAVEAREA(R15) skip savearea DC 17F'0' savearea DC CL8'FIBONACC' eyecatcher STM STM R14,R12,12(R13) s...
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 |...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program factorst64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
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)...
#C.2B.2B
C++
#include <complex> #include <iostream> #include <valarray>   const double PI = 3.141592653589793238460;   typedef std::complex<double> Complex; typedef std::valarray<Complex> CArray;   // Cooley–Tukey FFT (in-place, divide-and-conquer) // Higher memory requirements and redundancy although more intuitive void fft(CArray...
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,...
#C
C
int isPrime(int n){ if (n%2==0) return n==2; if (n%3==0) return n==3; int d=5; while(d*d<=n){ if(n%d==0) return 0; d+=2; if(n%d==0) return 0; d+=4;} return 1;}   main() {int i,d,p,r,q=929; if (!isPrime(q)) return 1; r=q; while(r>0) r<<=1; d=2*q+1; do { for(p=r, i= 1; p; p<<= 1){ i=((long long)i *...
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...
#Delphi
Delphi
  (define distinct-divisors (compose make-set prime-factors))   ;; euler totient : Φ : n / product(p_i) * product (p_i - 1) ;; # of divisors <= n   (define (Φ n) (let ((pdiv (distinct-divisors n))) (/ (* n (for/product ((p pdiv)) (1- p))) (for/product ((p pdiv)) p))))   ;; farey-sequence length |Fn| = 1 + sigma...
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...
#JavaScript
JavaScript
(() => { 'use strict';   // thueMorse :: Int -> [Int] const thueMorse = base => // Thue-Morse sequence for a given base fmapGen(baseDigitsSumModBase(base))( enumFrom(0) )   // baseDigitsSumModBase :: Int -> Int -> Int const baseDigitsSumModBase = base => /...
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...
#Java
Java
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream;   public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256);   private static long gcd(long a, long b) { if (b == 0) { return a; ...
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...
#Julia
Julia
module Faulhaber   function bernoulli(n::Integer) n ≥ 0 || throw(DomainError(n, "n must be a positive-or-0 number")) a = fill(0 // 1, n + 1) for m in 1:n a[m] = 1 // (m + 1) for j in m:-1:2 a[j - 1] = (a[j - 1] - a[j]) * j end end return ifelse(n != 1, a[1], -a[1]...
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}} ...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <numeric> #include <iterator> #include <memory> #include <string> #include <algorithm> #include <iomanip>   std::vector<int> nacci ( const std::vector<int> & start , int arity ) { std::vector<int> result ( start ) ; int sumstart = 1 ;//summing starts at vector's begi...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#VBScript
VBScript
  WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Vedit_macro_language
Vedit macro language
Num_Type(File_Stamp_Time("input.txt"))
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Visual_Basic_.NET
Visual Basic .NET
Dim file As New IO.FileInfo("test.txt")   'Creation Time Dim createTime = file.CreationTime file.CreationTime = createTime.AddHours(1)   'Write Time Dim writeTime = file.LastWriteTime file.LastWriteTime = writeTime.AddHours(1)   'Access Time Dim accessTime = file.LastAccessTime file.LastAccessTime = accessTime.AddHour...
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#zkl
zkl
fcn drawFibonacci(img,x,y,word){ // word is "01001010...", 75025 characters dx:=0; dy:=1; // turtle direction foreach i,c in ([1..].zip(word)){ // Walker.zip(list)-->Walker of zipped list a:=x; b:=y; x+=dx; y+=dy; img.line(a,b, x,y, 0x00ff00); if (c=="0"){ dxy:=dx+dy; if(i.isEven){ dx...
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...
#Pike
Pike
array paths = ({ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" });   // append a / to each entry, so that a path like "/home/user1/tmp" will be recognized as a prefix // without it the prefix would end up being "/home/user1/" paths ...
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...
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6 $PATH_SEPARATOR = "/"   FUNCTION CommonDirectoryPath(Paths() AS STRING) AS STRING LOCAL s AS STRING LOCAL i, j, k AS LONG k = 1 DO FOR i = 0 TO UBOUND(Paths) IF i THEN IF INSTR(k, Paths(i), $PATH_SEPARATOR) <> j THEN EXIT DO ELSEIF LEFT$(Pat...
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.
#EasyLang
EasyLang
a[] = [ 1 2 3 4 5 6 7 8 9 ] for i range len a[] if a[i] mod 2 = 0 b[] &= a[i] . . print b[]
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.
#Scheme
Scheme
(define (recurse number) (begin (display number) (newline) (recurse (+ number 1))))   (recurse 1)
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.
#SenseTalk
SenseTalk
put recurse(1)   function recurse n put n get the recurse of (n+1) end recurse
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) ...
#hexiscript
hexiscript
for let i 1; i <= 100; i++ if i % 3 = 0 && i % 5 = 0; println "FizzBuzz" elif i % 3 = 0; println "Fizz" elif i % 5 = 0; println "Buzz" else println i; endif endfor
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.
#PL.2FI
PL/I
  /* To obtain file size of files in root as well as from current directory. */   test: proc options (main); declare ch character (1); declare i fixed binary (31); declare in1 file record;   /* Open a file in the root directory. */ open file (in1) title ('//asd.log,type(fixed),recsize(1)'); on endfile...
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.
#Pop11
Pop11
;;; prints file size in bytes sysfilesize('input.txt') => sysfilesize('/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.
#PostScript
PostScript
(input.txt ) print (input.txt) status pop pop pop = pop (/input.txt ) print (/input.txt) status pop pop pop = pop
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 ...
#hexiscript
hexiscript
let in openin "input.txt" let out openout "output.txt" while !(catch (let c read char in)) write c out endwhile close in; close out
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 ...
#HicEst
HicEst
CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096 SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)
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-...
#Lua
Lua
-- Return the base two logarithm of x function log2 (x) return math.log(x) / math.log(2) end   -- Return the Shannon entropy of X function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X:sub(char, char) if count[i] then count[i] = count[i] + 1 els...
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 ...
#Perl
Perl
my $fasta_example = <<'END_FASTA_EXAMPLE'; >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED END_FASTA_EXAMPLE   my $num_newlines = 0; while ( < $fasta_example > ) { if (/\A\>(.*)/) { print "\n" x $num_newlines, $1, ': '; } else { $num_newlines = 1; pr...
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 ...
#Phix
Phix
bool first = true integer fn = open("fasta.txt","r") if fn=-1 then ?9/0 end if while true do object line = trim(gets(fn)) if atom(line) then puts(1,"\n") exit end if if length(line) then if line[1]=='>' then if not first then puts(1,"\n") end if printf(1,"%s: ",{line[2..$]}) ...
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 ...
#6502_Assembly
6502 Assembly
LDA #0 STA $F0  ; LOWER NUMBER LDA #1 STA $F1  ; HIGHER NUMBER LDX #0 LOOP: LDA $F1 STA $0F1B,X STA $F2  ; OLD HIGHER NUMBER ADC $F0 STA $F1  ; NEW HIGHER NUMBER LDA $F2 STA $F0  ; NEW LOWER NUMBER INX ...
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 |...
#ACL2
ACL2
(defun factors-r (n i) (declare (xargs :measure (nfix (- n i)))) (cond ((zp (- n i)) (list n)) ((= (mod n i) 0) (cons i (factors-r n (1+ i)))) (t (factors-r n (1+ i)))))   (defun factors (n) (factors-r n 1))
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)...
#Common_Lisp
Common Lisp
  (defun fft (a &key (inverse nil) &aux (n (length a))) "Perform the FFT recursively on input vector A. Vector A must have length N of power of 2." (declare (type boolean inverse) (type (integer 1) n)) (if (= n 1) a (let* ((n/2 (/ n 2)) (2iπ/n (complex 0 (/ (* 2 pi) n (if in...
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,...
#C.23
C#
using System;   namespace prog { class MainClass { public static void Main (string[] args) { int q = 929; if ( !isPrime(q) ) return; int r = q; while( r > 0 ) r <<= 1; int d = 2 * q + 1; do { int i = 1; for( int p=r; p!=0; p<<=1 ) { i = (i*i) % d; if (p < 0) i *= 2;...
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...
#EchoLisp
EchoLisp
  (define distinct-divisors (compose make-set prime-factors))   ;; euler totient : Φ : n / product(p_i) * product (p_i - 1) ;; # of divisors <= n   (define (Φ n) (let ((pdiv (distinct-divisors n))) (/ (* n (for/product ((p pdiv)) (1- p))) (for/product ((p pdiv)) p))))   ;; farey-sequence length |Fn| = 1 + sigma...
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...
#jq
jq
# Using a "reverse array" representations of the integers base b (b>=2), # generate an unbounded stream of the integers from [0] onwards. # E.g. for binary: [0], [1], [0,1], [1,1] ...   def integers($base): def add1: [foreach (.[], null) as $d ({carry: 1}; if $d then ($d + .carry ) as $r | if $r >= $bas...
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...
#Julia
Julia
fairshare(nplayers,len) = [sum(digits(n, base=nplayers)) % nplayers for n in 0:len-1]   for n in [2, 3, 5, 11] println("Fairshare ", n > 2 ? "among" : "between", " $n people: ", fairshare(n, 25)) end  
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Kotlin
Kotlin
fun turn(base: Int, n: Int): Int { var sum = 0 var n2 = n while (n2 != 0) { val re = n2 % base n2 /= base sum += re } return sum % base }   fun fairShare(base: Int, count: Int) { print(String.format("Base %2d:", base)) for (i in 0 until count) { val t = turn(b...
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...
#JavaScript
JavaScript
(() => {   // Order of Faulhaber's triangle -> rows of Faulhaber's triangle // faulHaberTriangle :: Int -> [[Ratio Int]] const faulhaberTriangle = n => map(x => tail( scanl((a, x) => { const ys = map((nd, i) => ratioMult(nd, Ratio(x, i + 2)...