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/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...
#Kotlin
Kotlin
// version 1.1.51   fun findCommonDirPath(paths: List<String>, separator: Char): String { if (paths.isEmpty()) return "" if (paths.size == 1) return paths[0] val splits = paths[0].split(separator) val n = splits.size val paths2 = paths.drop(1) var k = 0 var common = "" while (true) { ...
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.
#C
C
#include <stdio.h> #include <stdlib.h>   int even_sel(int x) { return !(x & 1); } int tri_sel(int x) { return x % 3; }   /* using a predicate function sel() to select elements */ int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace) { int i, j, *out;   if (inplace) out = in; else out = malloc(sizeo...
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.
#Neko
Neko
/** Recursion limit, in Neko */   /* This version is effectively unlimited, (50 billion test before ctrl-c) */ sum = 0.0 counter = 0 tco = function(n) { sum += n counter += 1 if n > 10000000 return n else tco(n + 1) }   try $print("Tail call recursion: ", tco(0), " sum: ", sum, "\n") catch with $print("tco...
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.lang.management.   memoryInfo() digDeeper(0)   /** * Just keep digging * @param level depth gauge */ method digDeeper(level = int) private static binary do digDeeper(level + 1) catch ex = Error System.out.println('Re...
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) ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim siCount As Short Dim sText As String   For siCount = 1 To 100 sText = "" If siCount Mod 3 = 0 Then sText = "Fizz" If siCount Mod 5 = 0 Then sText = "Buzz" If siCount Mod 15 = 0 Then sText = "FizzBuzz" If sText Then Print sText Else Print siCount Next   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.
#J
J
require 'files' fsize 'input.txt';'/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.
#Java
Java
import java.io.File;   public class FileSize { public static void main ( String[] args ) { System.out.println("input.txt  : " + new File("input.txt").length() + " bytes"); System.out.println("/input.txt : " + new File("/input.txt").length() + " bytes"); } }  
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 ...
#DBL
DBL
; ; File Input and output examples for DBL version 4 by Dario B. ;   RECORD CUSTOM   CUCOD, D5  ;customer code CUNAM, A20  ;name CUCIT, A20  ;city , A55 ;------- 100 bytes -------------   A80, A80   PROC ;--------------------------------------------------------------   ...
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 ...
#DCL
DCL
$ open input input.txt $ open /write output output.txt $ loop: $ read /end_of_file = done input line $ write output line $ goto loop $ done: $ close input $ close output
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-...
#D
D
import std.stdio, std.algorithm, std.math, std.string, std.range;   real entropy(T)(T[] s) pure nothrow if (__traits(compiles, s.sort())) { immutable sLen = s.length; return s .sort() .group .map!(g => g[1] / real(sLen)) .map!(p => -p * p.log2) .sum; }   vo...
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 ...
#BASIC256
BASIC256
open 1, "input.fasta"   first = True   while not eof(1) ln = readline(1) if left(ln, 1) = ">" then if not first then print print mid(ln, 2, length(ln)-2) & ": "; if first then first = False else if first then print "Error : File does not begin with '>'" ...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read;   fp = fopen("fasta.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE);   int state = 0; while ((read = getline(&line, &len, fp)) != -1) { /* Delete trailing newline */ if (l...
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...
#C.23
C#
using System;   namespace FaulhabersFormula { internal class Frac { private long num; private long denom;   public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1);   public Frac(long n, long d) { if (d == 0) { ...
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-...
#Kotlin
Kotlin
import java.math.BigInteger import kotlin.math.pow   fun main() { println("First 10 Fermat numbers:") for (i in 0..9) { println("F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") for (i in 0..12) { println("F[$i] = ${getString(getFactors(i, fermat(i)...
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}} ...
#APL
APL
nStep ← {⊃(1↓⊢,+/)⍣(⍺-1)⊢⍵} nacci ← 2*0⌈¯2+⍳ ↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#jq
jq
def feigenbaum_delta(imax; jmax): def lpad: tostring | (" " * (4 - length)) + .; def pp(i;x): "\(i|lpad) \(x)";   "Feigenbaum's delta constant incremental calculation:", pp("i"; "δ"), pp(1; "3.20"), ( foreach range(2; 1+imax) as $i ( {a1: 1.0, a2: 0.0, d1: 3.2};   .a = .a1 + (....
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Julia
Julia
# http://en.wikipedia.org/wiki/Feigenbaum_constant   function feigenbaum_delta(imax=23, jmax=20) a1, a2, d1 = BigFloat(1.0), BigFloat(0.0), BigFloat(3.2) println("Feigenbaum's delta constant incremental calculation:\ni δ\n1 3.20") for i in 2:imax a = a1 + (a1 - a2) / d1 for j in 1:jmax ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Kotlin
Kotlin
// Version 1.2.40   fun feigenbaum() { val maxIt = 13 val maxItJ = 10 var a1 = 1.0 var a2 = 0.0 var d1 = 3.2 println(" i d") for (i in 2..maxIt) { var a = a1 + (a1 - a2) / d1 for (j in 1..maxItJ) { var x = 0.0 var y = 0.0 for (k in 1....
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...
#Perl
Perl
sub check_extension { my ($filename, @extensions) = @_; my $extensions = join '|', map quotemeta, @extensions; scalar $filename =~ / \. (?: $extensions ) $ /xi }
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...
#PHP
PHP
  $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed);   $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#OCaml
OCaml
#load "unix.cma";; open Unix;; let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)   utimes filename (stat filename).st_atime (time ());; (* keep atime unchanged set mtime to current time *)
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Oforth
Oforth
File new("myfile.txt") modified
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#OpenEdge.2FProgress
OpenEdge/Progress
FILE-INFO:FILE-NAME = 'c:/temp'. MESSAGE STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' ) VIEW-AS ALERT-BOX
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...
#PARI.2FGP
PARI/GP
  \\ Fibonacci word/fractals \\ 4/25/16 aev fibword(n)={ my(f1="1",f2="0",fw,fwn,n2); if(n<=4, n=5);n2=n-2; for(i=1,n2, fw=Str(f2,f1); f1=f2;f2=fw;); fwn=#fw; fw=Vecsmall(fw); for(i=1,fwn,fw[i]-=48); return(fw); }   nextdir(n,d)={ my(dir=-1); if(d==0, if(n%2==0, dir=0,dir=1)); \\0-left,1-right return(dir); }   plotfibo...
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...
#Lasso
Lasso
#!/usr/bin/lasso9   local( path1 = '/home/user1/tmp/coverage/test' -> split('/'), path2 = '/home/user1/tmp/covert/operator' -> split('/'), path3 = '/home/user1/tmp/coven/members' -> split('/') )   define commonpath(...) => { local(shared = #rest -> get(1)) loop(#rest -> size - 1) => { #shared = #shared -> inters...
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...
#Liberty_BASIC
Liberty BASIC
path$(1) = "/home/user1/tmp/coverage/test" path$(2) = "/home/user1/tmp/covert/operator" path$(3) = "/home/user1/tmp/coven/members"     print samepath$(3,"/") end   function samepath$(paths,sep$) d = 1 'directory depth n = 2 'path$(number) while 1 if word$(path$(1),d,sep$) <> word$(path$(n),d,sep$) o...
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.
#C.23
C#
ArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } ); ArrayList evens = new ArrayList(); foreach( int i in array ) { if( (i%2) == 0 ) evens.Add( i ); } foreach( int i in evens ) System.Console.WriteLine( i.ToString() );
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.
#Nim
Nim
proc recurse(i: int): int = echo i recurse(i+1) echo 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.
#OCaml
OCaml
# let last = ref 0 ;; val last : int ref = {contents = 0} # let rec f i = last := i; i + (f (i+1)) ;; val f : int -> int = <fun> # f 0 ;; stack overflow during evaluation (looping recursion?). # !last ;; - : int = 262067
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) ...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short Dim sText As String   For siCount = 1 To 100 sText = "" If siCount Mod 3 = 0 Then sText = "Fizz" If siCount Mod 5 = 0 Then sText = "Buzz" If siCount Mod 15 = 0 Then sText = "FizzBuzz" If sText Then Print sText Else Print siCount Next   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.
#JavaScript
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.GetFile('input.txt').Size; fso.GetFile('c:/input.txt').Size;
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#jq
jq
jq -Rs length input.txt   jq -Rs length /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.
#Julia
Julia
println(filesize("input.txt")) println(filesize("/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 ...
#Delphi
Delphi
- Read(F,V1..Vn) - ReadLn(F,V1..Vn) - Write(F,V1[,V2..Vn]) - WriteLn(f,V1[,V2..Vn]) - BlockRead(F,Buff,BytesToRead[,BytesRead]) - BlockWrite(F,Buff,BytesToRead[,BytesWritten])
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 ...
#DIBOL-11
DIBOL-11
  START  ;Simple File Input and Output   RECORD TEMP INLINE, A72     PROC OPEN (8,I,"input.txt") OPEN (9,O,"output.txt")     LOOP, READS(8,TEMP,END) WRITES(9,TEMP) GOTO LOOP   END, CLOSE 8 CLOSE 9   END  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Delphi
Delphi
  (lib 'struct) (struct FW ( count0 count1 length string)) ;; a fibonacci word (define (F-word n) ;; generator (define a (F-word (1- n))) (define b (F-word (- n 2))) (FW (+ (FW-count0 a) (FW-count0 b)) (+ (FW-count1 a) (FW-count1 b)) (+ (FW-length a) (FW-length b)) (if (> n 9...
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 ...
#C.23
C#
using System; using System.Collections.Generic; using System.IO; using System.Text;   class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } }   static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { ...
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...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   int binomial(int n, int k) { int num, denom, i;   if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1;   num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; }   denom = 1; for ...
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...
#C.2B.2B
C++
#include <iostream> #include <numeric> #include <sstream> #include <vector>   class Frac { public: Frac(long n, long d) { if (d == 0) { throw new std::runtime_error("d must not be zero"); }   long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; }   long ...
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-...
#langur
langur
val .fermat = f 2 ^ 2 ^ .n + 1   val .factors = f(var .x) { for[.f=[]] .i, .s = 2, truncate .x ^/ 2; .i < .s; .i += 1 { if .x div .i { .f ~= [.i] .x \= .i .s = truncate .x ^/ 2 } } ~ [.x] }   writeln "first 10 Fermat numbers" for .i in 0..9 { writeln $"F\(...
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-...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Fermat] Fermat[n_] := 2^(2^n) + 1 Fermat /@ Range[0, 9] Scan[FactorInteger /* Print, %]
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}} ...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     -- Start sequence -> Number of terms -> terms -- takeNFibs :: [Int] -> Int -> [Int] on takeNFibs(xs, n) script go on |λ|(xs, n) if 0 < n and 0 < length of xs then cons(head(xs), ¬ ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Lambdatalk
Lambdatalk
  {feigenbaum 11} // on my computer stackoverflow for values greater than 11 -> [3.2185114220380866,4.3856775985683365,4.600949276538056,4.6551304953919646,4.666111947822846, 4.668548581451485,4.66906066077106,4.669171554514976,4.669195154039278,4.669200256503637]   with:   {def feigenbaum {lambda {:maxi} {f3 :maxi...
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...
#Phix
Phix
with javascript_semantics constant extensions = lower({"zip","rar","7z","gz","archive","A##","tar.bz2"}) global function get_known_extension(string filename) for i=1 to length(filename) do if filename[i]='.' then string extension = lower(filename[i+1..$]) if find(extension,extensio...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} Modified = {Path.mtime "input.txt"} %% posix time in {Show {OsTime.localtime Modified}} %% human readable record
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Pascal
Pascal
my $mtime = (stat($file))[9]; # seconds since the epoch   # you should use the more legible version below: use File::stat qw(stat); my $mtime = stat($file)->mtime; # seconds since the epoch   utime(stat($file)->atime, time, $file); # keep atime unchanged # set mtime to current time
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...
#Perl
Perl
use strict; use warnings; use GD;   my @fword = ( undef, 1, 0 );   sub fword { my $n = shift; return $fword[$n] if $n<3; return $fword[$n] //= fword($n-1).fword($n-2); }   my $size = 3000; my $im = new GD::Image($size,$size); my $white = $im->colorAllocate(255,255,255); my $black = $im->colorAllocate(0,0,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...
#Lingo
Lingo
on getCommonPath (pathes, sep) _player.itemDelimiter = sep   -- find length of shortest path (in terms of items) commonCnt = the maxInteger repeat with p in pathes if p.item.count<commonCnt then commonCnt=p.item.count end repeat   pathCnt = pathes.count repeat with i = 1 to commonCnt repeat with j...
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...
#MapBasic
MapBasic
Include "MapBasic.def"   DECLARE SUB Main DECLARE FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING   FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING DIM tmpint1 AS INTEGER, tmpint2 AS INTEGER, tmpstr1 AS STRING, tmpstr2 AS STRING DIM L0 AS INTEGER, L1 AS INTEGE...
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.
#C.2B.2B
C++
#include <vector> #include <algorithm> #include <functional> #include <iterator> #include <iostream>   int main() { std::vector<int> ary; for (int i = 0; i < 10; i++) ary.push_back(i); std::vector<int> evens; std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens), std::bind2n...
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.
#Oforth
Oforth
: limit 1+ dup . limit ;   0 limit
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.
#ooRexx
ooRexx
Using ooRexx for the program shown under Rexx: rexx pgm 1>x1 2>x2 puts the numbers in x1 and the error messages in x2 ... 2785 2786 8 *-* call self .... 8 *-* call self 3 *-* call self Error 11 running C:\work.ooRexx\wc\main.4.1.1.release\Win32Rel\StreamClasses.orx line 366: Control stack full Er...
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) ...
#GAP
GAP
FizzBuzz := function() local i; for i in [1 .. 100] do if RemInt(i, 15) = 0 then Print("FizzBuzz\n"); elif RemInt(i, 3) = 0 then Print("Fizz\n"); elif RemInt(i, 5) = 0 then Print("Buzz\n"); else Print(i, "\n"); fi; od; 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.
#K
K
_size "input.txt" _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.
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { val paths = arrayOf("input.txt", "c:\\input.txt") for (path in paths) println("Length of $path is ${File(path).length()} bytes") }
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Lasso
Lasso
// local to current directory local(f = file('input.txt')) handle => { #f->close } #f->size   // file at file system root local(f = file('//input.txt')) handle => { #f->close } #f->size  
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 ...
#E
E
<file:output.txt>.setText(<file:input.txt>.getText())
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 ...
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make -- Run application. do create input_file.make_open_read ("input.txt") create output_file.make_open_write ("output.txt")   from input_file.read_character ...
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-...
#EchoLisp
EchoLisp
  (lib 'struct) (struct FW ( count0 count1 length string)) ;; a fibonacci word (define (F-word n) ;; generator (define a (F-word (1- n))) (define b (F-word (- n 2))) (FW (+ (FW-count0 a) (FW-count0 b)) (+ (FW-count1 a) (FW-count1 b)) (+ (FW-length a) (FW-length b)) (if (> n 9...
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 ...
#C.2B.2B
C++
#include <iostream> #include <fstream>   int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; }   std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << st...
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...
#C.23
C#
using System;   namespace FaulhabersTriangle { internal class Frac { private long num; private long denom;   public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1);   public Frac(long n, long d) { if (d == 0) { ...
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...
#D
D
import std.algorithm : fold; import std.exception : enforce; import std.format : formattedWrite; import std.numeric : cmp, gcd; import std.range : iota; import std.stdio; import std.traits;   auto abs(T)(T val) if (isNumeric!T) { if (val < 0) { return -val; } return val; }   struct Frac { long n...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Nim
Nim
import math import bignum import strformat import strutils import tables import times   const Composite = {9: "5529", 10: "6078", 11: "1037", 12: "5488", 13: "2884"}.toTable   const Subscripts = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]   let One = newInt(1)   #-------------------------------------------------...
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-...
#Perl
Perl
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<factor>;   my @Fermats = map { 2**(2**$_) + 1 } 0..9;   my $sub = 0; say 'First 10 Fermat numbers:'; printf "F%s = %s\n", $sub++, $_ for @Fermats;   $sub = 0; say "\nFactors of first few Fermat numbers:"; for my $f (map { [factor($_)] } ...
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}} ...
#AutoHotkey
AutoHotkey
for i, seq in ["nacci", "lucas"] Loop, 9 { Out .= seq "(" A_Index + 1 "): " for key, val in NStepSequence(i, 1, A_Index + 1, 15) Out .= val (A_Index = 15 ? "`n" : "`, ") } MsgBox, % Out   NStepSequence(v1, v2, n, k) { a := [v1, v2] Loop, % k - 2 { a[j := A_Index + 2] ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Lua
Lua
function leftShift(n,p) local r = n while p>0 do r = r * 2 p = p - 1 end return r end   -- main   local MAX_IT = 13 local MAX_IT_J = 10 local a1 = 1.0 local a2 = 0.0 local d1 = 3.2   print(" i d") for i=2,MAX_IT do local a = a1 + (a1 - a2) / d1 for j=1,MAX_IT_J do l...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
maxit = 13; maxitj = 10; a1 = 1.0; a2 = 0.0; d1 = 3.2; a = 0.0; Table[ a = a1 + (a1 - a2)/d1; Do[ x = 0.0; y = 0.0; Do[ y = 1.0 - 2.0 y x; x = a - x x; , {k, 1, 2^i} ]; a = a - x/y , {j, maxitj} ]; d = (a1 - a2)/(a - a1); d1 = d; a2 = a1; a1 = a; {i, d} , {i, 2...
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...
#Python
Python
  def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))  
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...
#Racket
Racket
  #lang racket   (define extensions '(".zip" ".rar" ".7z" ".gz" ".archive" ".a##" ".tar.bz2"))   (define filenames '("MyData.a##" "MyData.tar.Gz" "MyData....
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Perl
Perl
my $mtime = (stat($file))[9]; # seconds since the epoch   # you should use the more legible version below: use File::stat qw(stat); my $mtime = stat($file)->mtime; # seconds since the epoch   utime(stat($file)->atime, time, $file); # keep atime unchanged # set mtime to current time
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Phix
Phix
without js -- file i/o -- (however get as per the JavaScript entry above might be doable if needed) constant filename = "test.txt" ?get_file_date(filename) include timedate.e ?format_timedate(get_file_date(filename)) bool res = set_file_date(filename) ?format_timedate(get_file_date(filename))
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...
#Phix
Phix
-- -- demo\rosetta\FibonacciFractal.exw -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas procedure drawFibonacci(integer x, y, dx, dy, n) string prev = "1", word = "0" for i=3 to n do {prev,word} = {word,word&prev} end for for i=1 to length(word) do cdCa...
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...
#Maple
Maple
  dirpath:=proc(a,b,c) local dirtemp,dirnew,x; use StringTools in dirtemp:=LongestCommonSubString(c, LongestCommonSubString(a,b)); x:=FirstFromRight("/",dirtemp); dirnew:=dirtemp[1..x]; return dirnew; end use; end proc;  
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FindCommonDirectory[x_] := If[StringTake[#, -1] != "/", StringTake[#, Max[StringPosition[#, "/"]]], #] & [Fold[LongestCommonSubsequence, First[x] , Rest[x]]]   FindCommonDirectory[{"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}] ->"/home/user1/tmp/"
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Clean
Clean
module SelectFromArray   import StdEnv
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.
#Oz
Oz
declare proc {Recurse Number} {Show Number} {Recurse Number+1} end in {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.
#PARI.2FGP
PARI/GP
dive(n) = dive(n+1) dive(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) ...
#Genyris
Genyris
  @prefix u "http://www.genyris.org/lang/utilities#"   def fizzbuzz (n) map-left ^((3 = 'fizz') (5 = 'buzz')) lambda (d) cond (equal? 0 (% n d!left)) d!right else ''     for n in (range 1 100) define fb (''(.join (fizzbu...
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.
#Liberty_BASIC
Liberty BASIC
'input.txt in current directory OPEN DefaultDir$ + "/input.txt" FOR input AS #m PRINT "File size: "; lof(#m) CLOSE #m   'input.txt in root OPEN "c:/input.txt" FOR input AS #m PRINT "File size: "; lof(#m) CLOSE #m
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.
#Lingo
Lingo
---------------------------------------- -- Returns file size -- @param {string} filename -- @return {integer} ---------------------------------------- on getFileSize (filename) fp = xtra("fileIO").new() fp.openFile(filename, 1) if fp.status() then return 0 len = fp.getLength() fp.closeFile() return len 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.
#LiveCode
LiveCode
// root folder set the defaultfolder to "/" repeat for each line fline in (the detailed files) if item 1 of fline is "input.txt" then put item 2 of fline --bytes exit repeat end if end repeat   // current working dir of stack put the effective filename of this stack into tPath set the itemDelimi...
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 ...
#Elena
Elena
import system'io;   public program() { var text := File.assign("input.txt").readContent();   File.assign("output.txt").saveContent(text); }
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Elixir
Elixir
defmodule FileReadWrite do def copy(path,new_path) do case File.read(path) do # In case of success, write to the new file {:ok, body} -> # Can replace with :write! to generate an error upon failure File.write(new_path,body) # If not successful, raise an error {:error,reason...
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-...
#Elixir
Elixir
defmodule RC do def entropy(str) do leng = String.length(str) String.to_charlist(str) |> Enum.reduce(Map.new, fn c,acc -> Map.update(acc, c, 1, &(&1+1)) end) |> Map.values |> Enum.reduce(0, fn count, entropy -> freq = count / leng entropy - freq * :math.log2(freq) # log2 was...
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.23
F#
// include the code from /wiki/Entropy#F.23 for the entropy function   let fiboword = Seq.unfold (fun (state : string * string) -> Some (fst state, (snd state, (snd state) + (fst state)))) ("1", "0")   printfn "%3s %10s %10s %s" "#" "Length" "Entropy" "Word (if length < 40)" Seq.iteri (fun i...
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 ...
#Clojure
Clojure
(defn fasta [pathname] (with-open [r (clojure.java.io/reader pathname)] (doseq [line (line-seq r)] (if (= (first line) \>) (print (format "%n%s: " (subs line 1))) (print line)))))
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Common_Lisp
Common Lisp
;; * The input file as a parameter (defparameter *input* #p"fasta.txt" "The input file name.")   ;; * Reading the data (with-open-file (data *input*) (loop :for line = (read-line data nil nil) :while line ;; Check if we have a comment using a simple test instead of a RegEx :if (char=...
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...
#11l
11l
F farey(n) V a = 0 V b = 1 V c = 1 V d = n V far = ‘0/1 ’ V farn = 1 L c <= n V k = (n + b) I/ d (a, b, c, d) = (c, d, k * c - a, k * d - b) far ‘’= a‘/’b‘ ’ farn++ R (far, farn)   L(i) 1..11 print(i‘: ’farey(i)[0])   L(i) (100..1000).step(100) print(i‘: ’farey(i)[1...
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#11l
11l
F _basechange_int(=num, b) ‘ Return list of ints representing positive num in base b ’ I num == 0 R [0] [Int] result L num != 0 (num, V d) = divmod(num, b) result.append(d) R reversed(result)   F fairshare(b, n) [Int] r L(i) 0.. r [+]= sum(_basechange_int(i, b)) % 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...
#C.2B.2B
C++
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector>   class Frac { public:   Frac() : num(0), denom(1) {}   Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); }   int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd...
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...
#EchoLisp
EchoLisp
  (lib 'math) ;; for bernoulli numbers (string-delimiter "")   ;; returns list of polynomial coefficients (define (Faulhaber p) (cons 0 (for/list ([k (in-range p -1 -1)]) (* (Cnp (1+ p) k) (bernoulli k)))))   ;; prints formal polynomial (define (task (pmax 10)) (for ((p pmax)) (writeln p '→ (/ 1 (1+ 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-...
#Phix
Phix
with javascript_semantics -- demo\rosetta\Fermat.exw include mpfr.e procedure fermat(mpz res, integer n) integer pn = power(2,n) mpz_ui_pow_ui(res,2,pn) mpz_add_si(res,res,1) end procedure mpz fn = mpz_init() constant lim = iff(platform()=JS?18:29), -- (see note) print_lim = iff(platform()=JS?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}} ...
#AWK
AWK
  function sequence(values, howmany) { init_length = length(values) for (i=init_length + 1; i<=howmany; i++) { values[i] = 0 for (j=1; j<=init_length; j++) { values[i] += values[i-j] } } result = "" for (i in values) { result = result values[i] " " } ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Modula-2
Modula-2
MODULE Feigenbaum; FROM FormatString IMPORT FormatString; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR buf : ARRAY[0..63] OF CHAR; i,j,k,max_it,max_it_j : INTEGER; a,x,y,d,a1,a2,d1 : LONGREAL; BEGIN max_it := 13; max_it_j := 10;   a1 := 1.0; a2 := 0...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Nim
Nim
import strformat   iterator feigenbaum(): tuple[n: int; δ: float] = ## Yield successive approximations of Feigenbaum constant.   const MaxI = 13 MaxJ = 10 var a1 = 1.0 a2 = 0.0 δ = 3.2   for i in 2..MaxI: var a = a1 + (a1 - a2) / δ for j in 1..MaxJ: var x, y = 0.0 for _ 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...
#Raku
Raku
sub check-extension ($filename, *@extensions) { so $filename ~~ /:i '.' @extensions $/ }   # Testing:   my @extensions = <zip rar 7z gz archive A## tar.bz2>; my @files= < MyData.a## MyData.tar.Gz MyData.gzip MyData.7z.backup MyData... MyData MyData_v1.0.tar.bz2 MyData_v1.0.bz2 >; say "{$_.fmt: '%-19s'...
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...
#REXX
REXX
/*REXX pgm displays if a filename has a known extension (as per a list of extensions). */ $= 'zip rar 7z gz archive A## tar.bz2'; upper $ /*a list of "allowable" file extensions*/ parse arg fn /*obtain optional argument from the CL.*/ @.= ...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#PHP
PHP
<?php $filename = 'input.txt';   $mtime = filemtime($filename); // seconds since the epoch   touch($filename, time(), // set mtime to current time fileatime($filename)); // keep atime unchanged ?>
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#PicoLisp
PicoLisp
(let File "test.file" (and (info File) (prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC (call 'touch File) ) # Set modification time to "now"
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Pop11
Pop11
;;; Print modification time (seconds since Epoch) sysmodtime('file') =>