task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Processing
Processing
  int n = 18; String f1 = "1"; String f2 = "0"; String f3;     void setup(){ size(600,600); background(255); translate(10, 10); createSeries(); }   void createSeries(){ for(int i=0; i<n; i++){ f3 = f2+f1; f1 = f2; f2 = f3; } drawFractal(); }   void drawFractal(){ char[] a = f3.toCharArray();...
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...
#Python
Python
from functools import wraps from turtle import *   def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer   @memoize def...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
  function lcp = longest_common_dirpath(varargin) ix = find(varargin{1}=='/'); ca = char(varargin); flag = all(ca==ca(1,:),1); for k = length(ix):-1:1, if all(flag(1:ix(k))); break; end end lcp = ca(1,1:ix(k)); end   longest_common_dirpath('/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/h...
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...
#Maxima
Maxima
scommon(a, b) := block([n: min(slength(a), slength(b))], substring(a, 1, catch(for i thru n do ( if not cequal(charat(a, i), charat(b, i)) then throw(i)), n + 1)))$   commonpath(u, [l]) := block([s: lreduce(scommon, u), c, n], n: sposition(if length(l) = 0 then "/" else l[1], sreverse(s)), if integerp(n) th...
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Clojure
Clojure
;; range and filter create lazy seq's (filter even? (range 0 100)) ;; vec will convert any type of seq to an array (vec (filter even? (vec (range 0 100))))
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Pascal
Pascal
my $x = 0; recurse($x);   sub recurse ($x) { print ++$x,"\n"; recurse($x); }
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Perl
Perl
my $x = 0; recurse($x);   sub recurse ($x) { print ++$x,"\n"; recurse($x); }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#GFA_Basic
GFA Basic
  ' Fizz Buzz ' FOR i%=1 TO 100 IF i% MOD 15=0 PRINT "FizzBuzz" ELSE IF i% MOD 3=0 PRINT "Fizz" ELSE IF i% MOD 5=0 PRINT "Buzz" ELSE PRINT i% ENDIF NEXT i%  
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Lua
Lua
function GetFileSize( filename ) local fp = io.open( filename ) if fp == nil then return nil end local filesize = fp:seek( "end" ) fp:close() return filesize end
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Maple
Maple
FileTools:-Size( "input.txt" )
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  FileByteCount["input.txt"] FileByteCount[FileNameJoin[{$RootDirectory, "input.txt"}]]
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Emacs_Lisp
Emacs Lisp
(defvar input (with-temp-buffer (insert-file-contents "input.txt") (buffer-string)))   (with-temp-file "output.txt" (insert input))  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Erlang
Erlang
  -module( file_io ).   -export( [task/0] ).   task() -> {ok, Contents} = file:read_file( "input.txt" ), ok = file:write_file( "output.txt", Contents ).  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Factor
Factor
USING: assocs combinators formatting kernel math math.functions math.ranges math.statistics namespaces pair-rocket sequences ; IN: rosetta-code.fibonacci-word   SYMBOL: 37th-fib-word   : fib ( n -- m ) { 1 => [ 1 ] 2 => [ 1 ] [ [ 1 - fib ] [ 2 - fib ] bi + ] } case ;   : fib-word ( n -- ...
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-...
#FreeBASIC
FreeBASIC
' version 25-06-2015 ' compile with: fbc -s console   Function calc_entropy(source As String, base_ As Integer) As Double   Dim As Integer i, sourcelen = Len(source), totalchar(255) Dim As Double prop, entropy   For i = 0 To sourcelen -1 totalchar(source[i]) += 1 Next   For i = 0 To 255 ...
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 ...
#Crystal
Crystal
  # create tmp fasta file in /tmp/ tmpfile = "/tmp/tmp"+Random.rand.to_s+".fasta" File.write(tmpfile, ">Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED")   # read tmp fasta file and store to hash ref = tmpfile id = seq = "" fasta = {} of String => String File....
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 ...
#Delphi
Delphi
USING: formatting io kernel sequences ; IN: rosetta-code.fasta   : process-fasta-line ( str -- ) dup ">" head? [ rest "\n%s: " printf ] [ write ] if ;   : main ( -- ) readln rest "%s: " printf [ process-fasta-line ] each-line ;   MAIN: main
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#ALGOL_68
ALGOL 68
BEGIN # construct some Farey Sequences and calculate their lengths # # prints an element of a Farey Sequence # PROC print element = ( INT a, b )VOID: print( ( " ", whole( a, 0 ), "/", whole( b, 0 ) ) ); # returns the length of the Farey Sequence of order n, option...
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...
#AppleScript
AppleScript
-- thueMorse :: Int -> [Int] on thueMorse(base) -- Non-finite sequence of Thue-Morse terms for a given base. fmapGen(baseDigitsSumModBase(base), enumFrom(0)) end thueMorse     -- baseDigitsSumModBase :: Int -> Int -> Int on baseDigitsSumModBase(b) script on |λ|(n) script go ...
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...
#D
D
import std.algorithm : fold; import std.conv : to; import std.exception : enforce; import std.format : formattedWrite; import std.numeric : cmp, gcd; import std.range : iota; import std.stdio; import std.traits;   auto abs(T)(T val) if (isNumeric!T) { if (val < 0) { return -val; } return val; }   st...
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...
#Factor
Factor
USING: formatting kernel math math.combinatorics math.extras math.functions regexp sequences ;   : faulhaber ( p -- seq ) 1 + dup recip swap dup <iota> [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ;   : (poly>str) ( seq -- str ) reverse [ 1 + "%un^%d" sprintf ] map-index reverse " + " join ; ...
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-...
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8))) (de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (>> 1 Y))) M ) (setq X (% (* X X) N)) ) ) ) (de isprime (N) (cache '(NIL) N (if (== N 2) T (and (...
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-...
#Python
Python
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors   print("First 10 Fermat numbers:") for i in range(10): fermat = 2 *...
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}} ...
#BASIC256
BASIC256
# Rosetta Code problem: https://www.rosettacode.org/wiki/Fibonacci_n-step_number_sequences # by Jjuanhdez, 06/2022   arraybase 1 print " fibonacci =>"; dim a = {1,1} call fib (a) print " tribonacci =>"; dim a = {1,1,2} call fib (a) print " tetranacci =>"; dim a = {1,1,2,4} call fib (a) print " pentanacci =>"; dim a = ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Perl
Perl
use strict; use warnings; use Math::AnyNum 'sqr';   my $a1 = 1.0; my $a2 = 0.0; my $d1 = 3.2;   print " i δ\n";   for my $i (2..13) { my $a = $a1 + ($a1 - $a2)/$d1; for (1..10) { my $x = 0; my $y = 0; for (1 .. 2**$i) { $y = 1 - 2 * $y * $x; $x = $a - sqr...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Phix
Phix
constant maxIt = 13, maxItJ = 10 atom a1 = 1.0, a2 = 0.0, d1 = 3.2 puts(1," i d\n") for i=2 to maxIt do atom a = a1 + (a1 - a2) / d1 for j=1 to maxItJ do atom x = 0, y = 0 for k=1 to power(2,i) do y = 1 - 2*y*x x = a - x*x end for ...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Ring
Ring
  # Project : File extension is in extensions list   extensions = [".zip", ".rar", ".7z", ".gz", ".archive", ".a##", ".tar.bz2"]   filenames = ["MyData.a##", "MyData.tar.gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"]   for n = 1 to len(filenam...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Ruby
Ruby
def is_ext(filename, extensions) if filename.respond_to?(:each) filename.each do |fn| is_ext(fn, extensions) end else fndc = filename.downcase extensions.each do |ext| bool = fndc.end_with?(?. + ext.downcase) puts "%20s : %s" % [filename, bool] if bool end end end  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#PowerShell
PowerShell
  $modificationTime = (Get-ChildItem file.txt).LastWriteTime Set-ItemProperty file.txt LastWriteTime (Get-Date)   $LastReadTime = (Get-ChildItem file.txt).LastAccessTime Set-ItemProperty file.txt LastAccessTime(Get-Date)   $CreationTime = (Get-ChildItem file.txt).CreationTime Set-ItemProperty file.txt CreationTime(Get-...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#PureBasic
PureBasic
Debug FormatDate("%yyyy/%mm/%dd", GetFileDate("file.txt",#PB_Date_Modified)) SetFileDate("file.txt",#PB_Date_Modified,Date(1987, 10, 23, 06, 43, 15)) Debug FormatDate("%yyyy/%mm/%dd - %hh:%ii:%ss", GetFileDate("file.txt",#PB_Date_Modified))
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Python
Python
import os   #Get modification time: modtime = os.path.getmtime('filename')   #Set the access and modification times: os.utime('path', (actime, mtime))   #Set just the modification time: os.utime('path', (os.path.getatime('path'), mtime))   #Set the access and modification times to the current time: os.utime('path', Non...
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...
#R
R
  ## Fibonacci word/fractal 2/20/17 aev ## Create Fibonacci word order n fibow <- function(n) { t2="0"; t1="01"; t=""; if(n<2) {n=2} for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t} return(t) } ## Plot Fibonacci word/fractal: ## n - word order, w - width, h - height, d - segment size, clr - color. pfibofractal <-...
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...
#Racket
Racket
#lang racket (require "Fibonacci-word.rkt") (require graphics/value-turtles)   (define word-order 23) ; is a 3k+2 fractal, shaped like an n (define height 420) (define width 600)   (define the-word (parameterize ((f-word-max-length #f)) (F-Word word-order)))   (for/fold ((T (turtles width height ...
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...
#MUMPS
MUMPS
FCD NEW D,SEP,EQ,LONG,DONE,I,J,K,RETURN SET D(1)="/home/user1/tmp/coverage/test" SET D(2)="/home/user1/tmp/covert/operator" SET D(3)="/home/user1/tmp/coven/members" SET SEP="/" SET LONG=D(1) SET DONE=0 FOR I=1:1:$LENGTH(LONG,SEP) QUIT:DONE SET EQ(I)=1 FOR J=2:1:3 SET EQ(I)=($PIECE(D(J),SEP,I)=$PIECE(LONG,SEP,I...
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...
#Nim
Nim
import strutils   proc commonprefix(paths: openarray[string], sep = "/"): string = if paths.len == 0: return "" block outer: for i in 0 ..< paths[0].len: result = paths[0][0 .. i] for path in paths: if not path.startsWith(result): break outer result = result[0 .. result.rfind(sep...
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#CoffeeScript
CoffeeScript
[1..10].filter (x) -> not (x%2)
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Phix
Phix
atom t1 = time()+1 integer depth = 0 procedure recurse() if time()>t1 then ?depth t1 = time()+1 end if depth += 1 -- only 1 of these will ever get called, of course... recurse() recurse() recurse() end procedure recurse()
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PHP
PHP
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Gleam
Gleam
import gleam/int import gleam/io import gleam/iterator   pub fn main() { iterator.range(1, 101) |> iterator.map(to_fizzbuzz) |> iterator.map(io.println) |> iterator.run }   fn to_fizzbuzz(n: Int) -> String { case n % 3, n % 5 { 0, 0 -> "FizzBuzz" 0, _ -> "Fizz" _, 0 -> "Buzz" _, _ -> int.to_st...
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#MATLAB_.2F_Octave
MATLAB / Octave
d1 = dir('input.txt'); d2 = dir('/input.txt'); fprintf('Size of input.txt is %d bytes\n', d1.bytes) fprintf('Size of /input.txt is %d bytes\n', d2.bytes)
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#MAXScript
MAXScript
-- Returns filesize in bytes or 0 if the file is missing getFileSize "index.txt" getFileSize "\index.txt"
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Mirah
Mirah
import java.io.File   puts File.new('file-size.mirah').length() puts File.new("./#{File.separator}file-size.mirah").length()
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Euphoria
Euphoria
include std/io.e write_lines("output.txt", read_lines("input.txt"))
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#F.23
F#
open System.IO   let copyFile fromTextFileName toTextFileName = let inputContent = File.ReadAllText fromTextFileName inputContent |> fun text -> File.WriteAllText(toTextFileName, text)   [<EntryPoint>] let main argv = copyFile "input.txt" "output.txt" 0  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math" )   // From http://rosettacode.org/wiki/Entropy#Go func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l }   const F_Word1 = "1" co...
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 ...
#Factor
Factor
USING: formatting io kernel sequences ; IN: rosetta-code.fasta   : process-fasta-line ( str -- ) dup ">" head? [ rest "\n%s: " printf ] [ write ] if ;   : main ( -- ) readln rest "%s: " printf [ process-fasta-line ] each-line ;   MAIN: main
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Forth
Forth
1024 constant max-Line char > constant marker   : read-lines begin pad max-line >r over r> swap read-line throw while pad dup c@ marker = if cr 1+ swap type ."  : " else swap type ...
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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function checkNoSpaces(s As String) As Boolean For i As UInteger = 0 To Len(s) - 1 If s[i] = 32 OrElse s[i] = 9 Then Return False '' check for spaces or tabs Next Return True End Function   Open "input.fasta" For Input As # 1   Dim As String ln, seq Dim first As Boolean = True   While Not...
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)...
#11l
11l
F fft(x) V n = x.len I n <= 1 R x V even = fft(x[(0..).step(2)]) V odd = fft(x[(1..).step(2)]) V t = (0 .< n I/ 2).map(k -> exp(-2i * math:pi * k / @n) * @odd[k]) R (0 .< n I/ 2).map(k -> @even[k] + @t[k]) [+] (0 .< n I/ 2).map(k -> @even[k] - @t[k])   print(fft([Complex(1.0), 1.0, 1.0, 1....
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...
#APL
APL
  farey←{{⍵[⍋⍵]}∪∊{(0,⍳⍵)÷⍵}¨⍳⍵} fract←{1∧(0(⍵=0)+⊂⍵)*1 ¯1} print←{{(⍕⍺),'/',(⍕⍵),' '}⌿↑fract farey ⍵}  
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#AWK
AWK
  # syntax: GAWK -f FAREY_SEQUENCE.AWK BEGIN { for (i=1; i<=11; i++) { farey(i); printf("\n") } for (i=100; i<=1000; i+=100) { printf(" %d items\n",farey(i)) } exit(0) } function farey(n, a,aa,b,bb,c,cc,d,dd,items,k) { a = 0; b = 1; c = 1; d = n printf("%d:",n) if (n <= 11) ...
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...
#Arturo
Arturo
thueMorse: function [base, howmany][ i: 0 result: new [] while [howmany > size result][ 'result ++ (sum digits.base:base i) % base i: i + 1 ]   return result ]   loop [2 3 5 11] 'b -> print [ (pad.right "Base "++(to :string b) 7)++" =>" join.with:" " map to [:str...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; }   void fairshare(int base, int count) { int i;   printf("Base %2d:", base); for (i = 0; i < count; i...
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...
#F.23
F#
  // Generate Faulhaber's Triangle. Nigel Galloway: May 8th., 2018 let Faulhaber=let fN n = (1N - List.sum n)::n let rec Faul a b=seq{let t = fN (List.mapi(fun n g->b*g/BigRational.FromInt(n+2)) a) yield t yield! Faul t (b+1N)} ...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
n := X(Rationals, "n"); sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1); sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1); ForAll([0 .. 20], k -> sum1(k) = sum2(k));   for p in [0 .. 9] do ...
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-...
#Raku
Raku
use ntheory:from<Perl5> <factor>;   my @Fermats = (^Inf).map: 2 ** 2 ** * + 1;   my $sub = '₀'; say "First 10 Fermat numbers:"; printf "F%s = %s\n", $sub++, $_ for @Fermats[^10];   $sub = '₀'; say "\nFactors of first few Fermat numbers:"; for @Fermats[^9].map( {"$_".&factor} ) -> $f { printf "Factors of F%s: %s %s\...
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}} ...
#Batch_File
Batch File
  @echo off   echo Fibonacci Sequence: call:nfib 1 1 echo.   echo Tribonacci Sequence: call:nfib 1 1 2 echo.   echo Tetranacci Sequence: call:nfib 1 1 2 4 echo.   echo Lucas Numbers: call:nfib 2 1 echo.   pause>nul exit /b   :nfib setlocal enabledelayedexpansion   for %%i in (%*) do ( set /a count+=1 set seq=!seq! ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Python
Python
max_it = 13 max_it_j = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 a = 0.0   print " i d" for i in range(2, max_it + 1): a = a1 + (a1 - a2) / d1 for j in range(1, max_it_j + 1): x = 0.0 y = 0.0 for k in range(1, (1 << i) + 1): y = 1.0 - 2.0 * y * x x = a - x * x a...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Racket
Racket
#lang racket (define (feigenbaum #:max-it (max-it 13) #:max-it-j (max-it-j 10)) (displayln " i d" (current-error-port)) (define-values (_a _a1 d) (for/fold ((a 1) (a1 0) (d 3.2)) ((i (in-range 2 (add1 max-it)))) (let* ((a′ (for/fold ((a (+ a (/ (- a a1) d)))) ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Raku
Raku
my $a1 = 1; my $a2 = 0; my $d = 3.2;   say ' i d';   for 2 .. 13 -> $exp { my $a = $a1 + ($a1 - $a2) / $d; do { my $x = 0; my $y = 0; for ^2 ** $exp { $y = 1 - 2 * $y * $x; $x = $a - $x²; } $a -= $x / $y; } xx 10; $d = ($a1 - $a2) / ($a - ...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Rust
Rust
fn main() { let exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"]; let filenames = [ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", ];   printl...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Scala
Scala
def isExt(fileName: String, extensions: List[String]): Boolean = { extensions.map { _.toLowerCase }.exists { fileName.toLowerCase endsWith "." + _ } }  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#R
R
# Get the value file.info(filename)$mtime   #To set the value, we need to rely on shell commands. The following works under windows. shell("copy /b /v filename +,,>nul") # and on Unix (untested) shell("touch -m filename")
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Racket
Racket
  #lang racket (file-or-directory-modify-seconds "foo.rkt")  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Raku
Raku
use NativeCall;   class utimbuf is repr('CStruct') { has int $.actime; has int $.modtime;   submethod BUILD(:$atime, :$mtime) { $!actime = $atime; $!modtime = $mtime.to-posix[0].round; } }   sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}   sub MAIN (Str $file) { ...
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...
#Raku
Raku
constant @fib-word = '1', '0', { $^b ~ $^a } ... *;   sub MAIN($m = 17, $scale = 3) { (my %world){0}{0} = 1; my $loc = 0+0i; my $dir = i; my $n = 1;   for @fib-word[$m].comb { when '0' { step; if $n %% 2 { turn-left } else { turn-right; } } ...
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...
#OCaml
OCaml
let rec aux acc paths = if List.mem [] paths then (List.rev acc) else let heads = List.map List.hd paths in let item = List.hd heads in let all_the_same = List.for_all ((=) item) (List.tl heads) in if all_the_same then aux (item::acc) (List.map List.tl paths) else (List.rev acc)   let common_prefi...
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Common_Lisp
Common Lisp
(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10)) > (2 4 6 8 10)
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PicoLisp
PicoLisp
$ ulimit -s 8192 $ pil + : (let N 0 (recur (N) (recurse (msg (inc N))))) ... 730395 730396 730397 Segmentation fault
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PL.2FI
PL/I
  recurs: proc options (main) reorder; dcl sysprint file; dcl mod builtin;   dcl ri fixed bin(31) init (0);   recursive: proc recursive; ri += 1; if mod(ri, 1024) = 1 then put data(ri);   call recursive(); end recursive;   call recursive(); end recurs;  
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PowerShell
PowerShell
  function TestDepth ( $N ) { $N TestDepth ( $N + 1 ) }   try { TestDepth 1 | ForEach { $Depth = $_ } } catch { "Exception message: " + $_.Exception.Message } "Last level before error: " + $Depth  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Go
Go
package main   import "fmt"   func main() { for i := 1; i <= 100; i++ { switch { case i%15==0: fmt.Println("FizzBuzz") case i%3==0: fmt.Println("Fizz") case i%5==0: fmt.Println("Buzz") default: fmt.Println(i) } } }
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#mIRC_Scripting_Language
mIRC Scripting Language
echo -ag $file(input.txt).size bytes echo -ag $file(C:\input.txt).size bytes
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Modula-3
Modula-3
MODULE FSize EXPORTS Main;   IMPORT IO, Fmt, FS, File, OSError;   VAR fstat: File.Status;   BEGIN TRY fstat := FS.Status("input.txt"); IO.Put("Size of input.txt: " & Fmt.LongInt(fstat.size) & "\n"); fstat := FS.Status("/input.txt"); IO.Put("Size of /input.txt: " & Fmt.LongInt(fstat.size) & "\n"); EX...
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 ...
#Factor
Factor
"input.txt" binary file-contents "output.txt" binary set-file-contents
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Forth
Forth
\ <to> <from> copy-file : copy-file ( a1 n1 a2 n2 -- ) r/o open-file throw >r w/o create-file throw r> begin pad maxstring 2 pick read-file throw  ?dup while pad swap 3 pick write-file throw repeat close-file throw close-file throw ;   \ Invoke it like this: s" output.txt"...
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-...
#Go
Go
package main   import ( "fmt" "math" )   // From http://rosettacode.org/wiki/Entropy#Go func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l }   const F_Word1 = "1" co...
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 ...
#Gambas
Gambas
Public Sub Main() Dim sList As String = File.Load("../FASTA") Dim sTemp, sOutput As String   For Each sTemp In Split(sList, gb.NewLine) If sTemp Begins ">" Then If sOutput Then Print sOutput sOutput = Right(sTemp, -1) & ": " Else sOutput &= sTemp Endif Next   Print sOutput   End
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Go
Go
package main   import ( "bufio" "fmt" "os" )   func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() ...
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)...
#Ada
Ada
  with Ada.Numerics.Generic_Complex_Arrays;   generic with package Complex_Arrays is new Ada.Numerics.Generic_Complex_Arrays (<>); use Complex_Arrays; function Generic_FFT (X : Complex_Vector) return Complex_Vector;  
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#11l
11l
F is_prime(a) I a == 2 {R 1B} I a < 2 | a % 2 == 0 {R 0B} L(i) (3 .. Int(sqrt(a))).step(2) I a % i == 0 R 0B R 1B   F m_factor(p) V max_k = 16384 I/ p L(k) 0 .< max_k V q = 2 * p * k + 1 I !is_prime(q) L.continue E I q % 8 != 1 & q % 8 != 7 L.continue...
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...
#BASIC256
BASIC256
for i = 1 to 11 print "F"; i; " = "; call farey(i, FALSE) next i print for i = 100 to 1000 step 100 print "F"; i; if i <> 1000 then print " "; else print ""; print " = "; call farey(i, FALSE) next i end   subroutine farey(n, descending) a = 0 : b = 1 : c = 1 : d = n : k = 0 cont = 0   ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   void farey(int n) { typedef struct { int d, n; } frac; frac f1 = {0, 1}, f2 = {1, n}, t; int k;   printf("%d/%d %d/%d", 0, 1, 1, n); while (f2.n > 1) { k = (n + f1.n) / f2.n; t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n }; printf("...
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...
#C.2B.2B
C++
#include <iostream> #include <vector>   int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; }   void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { ...
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...
#Factor
Factor
USING: kernel math math.combinatorics math.extras math.functions math.ranges prettyprint sequences ;   : faulhaber ( p -- seq ) 1 + dup recip swap dup 0 (a,b] [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ;   10 [ faulhaber . ] each-integer
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#FreeBASIC
FreeBASIC
' version 12-08-2017 ' compile with: fbc -s console ' uses GMP   #Include Once "gmp.bi"   #Define i_max 17   Dim As UInteger i, j, x Dim As String s Dim As ZString Ptr gmp_str : gmp_str = Allocate(100)   Dim As Mpq_ptr n, tmp1, tmp2, sum, one, zero n = Allocate(Len(__mpq_struct)) : Mpq_init(n) tmp1 = Allocate(Len(...
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...
#GAP
GAP
n := X(Rationals, "n"); sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1); sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1); ForAll([0 .. 20], k -> sum1(k) = sum2(k));   for p in [0 .. 9] do ...
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-...
#REXX
REXX
/*REXX program to find and display Fermat numbers, and show factors of Fermat numbers.*/ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 9 /*Not specified? Then use the default.*/ numeric digits 20 ...
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}} ...
#BBC_BASIC
BBC BASIC
@% = 5 : REM Column width   PRINT "Fibonacci:" DIM f2%(1) : f2%() = 1,1 FOR i% = 1 TO 12 : PRINT f2%(0); : PROCfibn(f2%()) : NEXT : PRINT " ..."   PRINT "Tribonacci:" DIM f3%(2) : f3%() = 1,1,2 FOR i% = 1 TO 12 : PRINT f3%(0); : PROCfibn(f3%()) : NEXT : PRINT " ..."   PRI...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#REXX
REXX
/*REXX pgm calculates the (Mitchell) Feigenbaum bifurcation velocity, #digs can be given*/ parse arg digs maxi maxj . /*obtain optional argument from the CL.*/ if digs=='' | digs=="," then digs= 30 /*Not specified? Then use the default.*/ if maxi=='' | maxi=="," then maxi= 20 ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Ring
Ring
# Project : Feigenbaum constant calculation   decimals(8) see "Feigenbaum constant calculation:" + nl maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 see "i " + "d" + nl for i = 2 to maxIt a = a1 + (a1 - a2) / d1 for j = 1 to maxItJ x = 0 y = 0 for k = 1 to pow(2,i) ...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Sidef
Sidef
func check_extension(filename, extensions) { filename ~~ Regex('\.(' + extensions.map { .escape }.join('|') + ')\z', :i) }
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Tcl
Tcl
    # This example includes the extra credit. # With a slight variation, a matching suffix can be identified. # Note that suffixes with two or more dots (ie a dot in suffix) are checked for each case. # This way, filename.1.txt will match for txt, and filename3.tar.gz.1 will match for tar.gz.1 for example.   # Example ...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#RapidQ
RapidQ
name$ = DIR$("input.txt", 0) PRINT "File date: "; FileRec.Date PRINT "File time: "; FileRec.Time
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#REALbasic
REALbasic
  Function getModDate(f As FolderItem) As Date Return f.ModificationDate End Function
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#REXX
REXX
/*REXX program obtains and displays a file's time of modification. */ parse arg $ . /*obtain required argument from the CL.*/ if $=='' then do; say "***error*** no filename was specified."; exit 13; end q=stream($, 'C', "QUERY TIMESTAMP") /*get ...
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...
#REXX
REXX
/*REXX program generates a Fibonacci word, then (normally) displays the fractal curve.*/ parse arg order . /*obtain optional arguments from the CL*/ if order=='' | order=="," then order= 23 /*Not specified? Then use the default*/ tell= order>=0 ...
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...
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION findCommonDir RETURNS CHAR( i_cdirs AS CHAR, i_cseparator AS CHAR ):   DEF VAR idir AS INT. DEF VAR idepth AS INT. DEF VAR cdir AS CHAR EXTENT. DEF VAR lsame AS LOGICAL INITIAL TRUE. DEF VAR cresult AS CHAR.   EXTENT( cdir ) = NUM-ENTRIES( i_cdirs, '~n' ).  ...
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Cowgol
Cowgol
include "cowgol.coh";   # Cowgol has strict typing and there are no templates either. # Defining the type this way makes it easy to change. typedef FilterT is uint32;   # In order to pass functions around, we need to define an # interface. The 'FilterPredicate' interface will take an argument # and return zero if it s...
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#PureBasic
PureBasic
Procedure Recur(n) PrintN(str(n)) Recur(n+1) EndProcedure   Recur(1)