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/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Forth
Forth
: printit 26 0 do [char] a I + emit loop ;
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Fortran
Fortran
character(26) :: alpha integer :: i   do i = 1, 26 alpha(i:i) = achar(iachar('a') + i - 1) end do
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Oz
Oz
{Show "Hello world!"}
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#PARI.2FGP
PARI/GP
g = List(1); \\ generator stack   genpow(p) = my(a=g[1]++);listput(g,[0,p]);()->g[a][1]++^g[a][2];   genpowf(p,f) = my(a=g[1]++);listput(g,[0,p]);(s=0)->my(q);while(ispower(p=g[a][1]++^g[a][2],f)||(s&&q++<=s),);p;
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Scheme
Scheme
(import (scheme base) (scheme write) (srfi 1) ; list library (srfi 27)) ; random numbers   (random-source-randomize! default-random-source)   ;; Random integer in [start, end) (define (random-between start end) (let ((len (- end start 1))) (if (< len 2) start (+ start (random-integ...
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Bracmat
Bracmat
( ( compose = f g . !arg:(?f.?g)&'(.($f)$(($g)$!arg)) ) & compose $ ( (=.flt$(!arg,2)) . compose$((=.!arg*5/9).(=.!arg+-32)) )  : (=?FahrenheitToCelsius) & ( FahrenheitToCelsiusExample = deg . chu$(x2d$b0):?deg & out $ ( str $ (!arg " " !deg "F in " !de...
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Brat
Brat
compose = { f, g | { x | f g x } }   #Test add1 = { x | x + 1 } double = { x | x * 2 } b = compose(->double ->add1) p b 1 #should print 4
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#BASIC
BASIC
graphsize 300,300   level = 12 : len =63 # initial values x = 230: y = 285 rotation = pi/2   A1 = pi/27 : A2 = pi/8 # constants which determine shape C1 = 0.7 : C2 = 0.85   dim xs(level+1) : dim ys(level+1) # stacks   fastgraphics color black rect 0,0,graphwidth,graphheight refresh color green gosub tree refresh i...
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#C
C
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h>   #ifdef WITH_CAIRO #define PI 3.1415926535 #endif   #define SIZE 800 // determines size of window #define SCALE 5 // determines...
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#11l
11l
F indexOf(haystack, needle) V idx = 0 L(straw) haystack I straw == needle R idx E idx++ R -1   F getDigits(=n, =le, &digits) L n > 0 V r = n % 10 I r == 0 | indexOf(digits, r) >= 0 R 0B le-- digits[le] = r n = Int(n / 10) R 1B   F remov...
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#bash
bash
#! /bin/bash program="1/1 455/33 11/13 1/11 3/7 11/2 1/3" echo $program | tr " " "\n" | cut -d"/" -f1 | tr "\n" " " > "data" read -a ns < "data" echo $program | tr " " "\n" | cut -d"/" -f2 | tr "\n" " " > "data" read -a ds < "data"     t=0 n=72 echo "steps of computation" > steps.csv while [ $t -le 6 ]; do if [ $(($n*...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#PHP
PHP
  $server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com";   $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; ...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#PicoLisp
PicoLisp
(in '(curl "-sl" "ftp://kernel.org/pub/site/") (while (line) (prinl @) ) ) (call "curl" "-s" "-o" "sha256sums.asc" "ftp://kernel.org/pub/site/sha256sums.asc")
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Python
Python
  from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) # Default since Python 2.1 print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()  
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#Quackery
Quackery
forward is fibonacci ( n --> n )   [ dup 2 < if done dup 1 - fibonacci swap 2 - fibonacci + ] resolves fibonacci ( n --> n )
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#Racket
Racket
  #lang racket   (define (no-arg) (void))   (define (two-args a b) (void)) ;arguments are always named   (define (varargs . args) (void)) ;the extra arguments are stored in a list   (define (varargs2 a . args) (void)) ;one obligatory argument and the rest are contained in the list   (define (optional-arg (a 5)) (void))...
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#Raku
Raku
sub foo ( --> Int) {...}
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#ActionScript
ActionScript
function multiply(a:Number, b:Number):Number { return a * b; }
http://rosettacode.org/wiki/French_Republican_calendar
French Republican calendar
Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of...
#Sidef
Sidef
require('DateTime')   var month_names = %w( Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse Germinal Floréal Prairial Messidor Thermidor Fructidor )   var intercalary = [ 'Fête de la vertu', 'Fête du génie', 'Fête du travail', ...
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Delphi
Delphi
let n = 61 let l = [0, 1]   func fusc(n) { return l[n] when n < l.Length() let f = (n &&& 1) == 0 ? l[n >>> 1] : l[(n - 1) >>> 1] + l[(n + 1) >>> 1] l.Add(f) return f }   var lst = true var w = -1 var c = 0 var t = nil var res = ""   print("First \(n) numbers in the fusc sequence:") for i in 0..Integer....
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Dyalect
Dyalect
let n = 61 let l = [0, 1]   func fusc(n) { return l[n] when n < l.Length() let f = (n &&& 1) == 0 ? l[n >>> 1] : l[(n - 1) >>> 1] + l[(n + 1) >>> 1] l.Add(f) return f }   var lst = true var w = -1 var c = 0 var t = nil var res = ""   print("First \(n) numbers in the fusc sequence:") for i in 0..Integer....
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#REXX
REXX
fid='pgm.rex' cnt.=0 funl='' Do While lines(fid)>0 l=linein(fid) Do Until p=0 p=pos('(',l) If p>0 Then Do do i=p-1 To 1 By -1 While is_tc(substr(l,i,1)) End fn=substr(l,i+1,p-i-1) If fn<>'' Then Call store fn l=substr(l,p+1) End End End Do While funl<>'' ...
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Sidef
Sidef
func foo { } func bar { }   foo(); foo(); foo() bar(); bar();   var data = Perl.to_sidef(Parser{:vars}{:main}).flatten   data.sort_by { |v| -v{:count} }.first(10).each { |entry| if (entry{:type} == :func) { say ("Function `#{entry{:name}}` (declared at line", " #{entry{:line}}) is used #{entry{...
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Crystal
Crystal
# Taylor Series def a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0...
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Liberty_BASIC
Liberty BASIC
  [setup] nomainwin   speed=50   prompt "Number of balls to drop: ";cycleMax cycleMax=abs(int(cycleMax))   'create window WindowWidth=400 WindowHeight=470 UpperLeftX=1 UpperLeftY=1 graphicbox #1.gb, 10, 410,370,25 open "Galton Machine" for graphics_nf_nsb as #1 #1 "trapclose ...
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numb...
#jq
jq
# emit a stream of gapful numbers greater than or equal to $start, # which is assumed to be an integer def gapful($start): range($start; infinite) | . as $i | tostring as $s | (($s[:1] + $s[-1:]) | tonumber) as $x | select($i % $x == 0);   "First 30 gapful numbersstarting from 100:", ([limit(30;gap...
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numb...
#Julia
Julia
using Lazy, Formatting   firstlast(a) = 10 * a[end] + a[1] isgapful(n) = (d = digits(n); length(d) < 3 || (m = firstlast(d)) != 0 && mod(n, m) == 0) gapfuls(start) = filter(isgapful, Lazy.range(start))   for (x, n) in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)] println("First $n gapful numbers starting at ", ...
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Julia
Julia
x = A \ b
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Python
Python
  import numpy as np from numpy.linalg import inv a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]]) ainv = inv(a)   print(a) print(ainv)  
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#PARI.2FGP
PARI/GP
fizz(n,v[..])= { v=vecsort(v,1); for(k=1,n, my(t); for(i=1,#v, if(k%v[i][1]==0, print1(v[i][2]); t=1 ) ); print(if(t,"",k)) ); } fizz(20,[3,"Fizz"],[5,"Buzz"],[7,"Baxx"])
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Free_Pascal
Free Pascal
program lowerCaseAscii(input, output, stdErr); const alphabet = ['a'..'z']; begin end.
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Frink
Frink
map["char", char["a"] to char["z"]]
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PARI.2FGP
PARI/GP
print("Hello world!")
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Perl
Perl
# gen_pow($m) creates and returns an anonymous subroutine that will # generate and return the powers 0**m, 1**m, 2**m, ... sub gen_pow { my $m = shift; my $e = 0; return sub { return $e++ ** $m; }; }   # gen_filter($g1, $g2) generates everything returned from $g1 that # is not also returned from $g2. Both $...
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var string: start is "RKR"; var char: piece is ' '; var integer: pos is 0; begin for piece range "QNN" do pos := rand(1, succ(length(start))); start := start[.. pred(pos)] & str(piece) & start[pos ..]; end for; pos := ran...
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Sidef
Sidef
func is_valid_960 (backrank) { var king = backrank.index('♚') var (rook1, rook2) = backrank.indices_of('♜')... king.is_between(rook1, rook2) || return false var (bishop1, bishop2) = backrank.indices_of('♝')... bishop1+bishop2 -> is_odd }   func random_960_position(pieces = <♛ ♚ ♜ ♜ ♝ ♝ ♞ ♞>) { p...
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#C
C
#include <stdlib.h>   /* generic interface for functors from double to double */ typedef struct double_to_double { double (*fn)(struct double_to_double *, double); } double_to_double;   #define CALL(f, x) f->fn(f, x)     /* functor returned by compose */ typedef struct compose_functor { double (*fn)(struct compose_...
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <math.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const float PI = 3.1415926536f;   ...
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; procedure Fraction_Reduction is   type Int_Array is array (Natural range <>) of Integer;   function indexOf(haystack : Int_Array; needle : Integer) return Integer is idx : Integer := 0; begin for straw of haystack loop ...
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::Set the inputs set "code=17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" set "n=2" ::Basic validation of code for %%. in (!code!) do ( echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code ) ::Validate the input set /a...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Racket
Racket
  #lang racket (require net/ftp) (let* ([server "kernel.org"] [remote-dir "/pub/linux/kernel/"] [conn (ftp-establish-connection server 21 "anonymous" "")]) (ftp-cd conn remote-dir) (map (lambda (elem) (displayln (string-join elem "\t"))) ...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Raku
Raku
use Net::FTP;   my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = '';   my $ftp = Net::FTP.new( host => $host, :passive );   $ftp.login( user => $user, pass => $password );   $ftp.cwd( 'upload' );   $ftp.cwd( '/' );   say $_<name> for $ftp.ls;   $ftp.get( '1KB.zip', :binary );
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#REBOL
REBOL
  system/schemes/ftp/passive: on print read ftp://kernel.org/pub/linux/kernel/ write/binary %README read/binary ftp://kernel.org/pub/linux/kernel/README  
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#REXX
REXX
define('multiply(a,b)') :(mul_end) multiply multiply = a * b  :(return) mul_end   * Test output = multiply(10.1,12.2) output = multiply(10,12) end
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#SNOBOL4
SNOBOL4
define('multiply(a,b)') :(mul_end) multiply multiply = a * b  :(return) mul_end   * Test output = multiply(10.1,12.2) output = multiply(10,12) end
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#Wren
Wren
var factorial // forward declaration   factorial = Fn.new { |n| (n <= 1) ? 1 : factorial.call(n-1) * n }   System.print(factorial.call(5))
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Ada
Ada
function Multiply (A, B : Float) return Float;
http://rosettacode.org/wiki/French_Republican_calendar
French Republican calendar
Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of...
#Wren
Wren
import "/date" for Date import "/seq" for Lst import "/fmt" for Fmt   class FrenchRCDate { /* uses the 'continuous method' for years after 1805 */ static isLeapYear(y) { var yy = y + 1 return (yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0) }   static parse(frcDate) { var split...
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#F.23
F#
  // Generate the fusc sequence. Nigel Galloway: March 20th., 2019 let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g} let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))  
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Smalltalk
Smalltalk
bagOfCalls := Bag new. Smalltalk allClassesDo:[:cls | cls instAndClassMethodsDo:[:mthd | bagOfCalls addAll:mthd messagesSent ]. ]. (bagOfCalls sortedCounts to:10) do:[:assoc | Stdout printCR: e'method {assoc value} is called {assoc key} times.' ].
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Tcl
Tcl
package require Tcl 8.6   proc examine {filename} { global cmds set RE "(?:^|\[\[\{\])\[\\w:.\]+" set f [open $filename] while {[gets $f line] >= 0} { set line [string trim $line] if {$line eq "" || [string match "#*" $line]} { continue } foreach cmd [regexp -all -inline $RE $line] { incr ...
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#D
D
import std.stdio, std.math, std.mathspecial;   real taylorGamma(in real x) pure nothrow @safe @nogc { static immutable real[30] table = [ 0x1p+0, 0x1.2788cfc6fb618f4cp-1, -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, 0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5, -0x...
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Lua
Lua
Bitmap.render = function(self) for y = 1, self.height do print(table.concat(self.pixels[y], " ")) end end   -- globals (tweak here as desired) math.randomseed(os.time()) local W, H, MIDX = 15, 40, 7 local bitmap = Bitmap(W, H) local AIR, PIN, BALL, FLOOR = ".", "▲", "☻", "■" local nballs, balls = 60, {} local f...
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numb...
#Kotlin
Kotlin
private fun commatize(n: Long): String { val sb = StringBuilder(n.toString()) val le = sb.length var i = le - 3 while (i >= 1) { sb.insert(i, ',') i -= 3 } return sb.toString() }   fun main() { val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.t...
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Klong
Klong
  elim::{[h m];h::*m::x@>*'x;  :[2>#x;x;(,h),0,:\.f({1_x}'{x-h**x%*h}'1_m)]} subst::{[v];v::[]; {v::v,((*x)-/:[[]~v;[];v*x@1+!#v])%x@1+#v}'||'x;|v} gauss::{subst(elim(x))}  
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Racket
Racket
#lang racket   (require math/matrix math/array)   (define (inverse M) (define dim (square-matrix-size M)) (define MI (matrix-augment (list M (identity-matrix dim)))) (submatrix (matrix-row-echelon MI #t #t) (::) (:: dim #f)))   (define A (matrix [[1 2 3] [4 1 6] [7 8 9]]))   (inverse A) (matrix-inverse ...
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Raku
Raku
sub gauss-jordan-invert (@m where &is-square) { ^@m .map: { @m[$_].append: identity(+@m)[$_] }; @m.&rref[*]»[+@m .. *]; }   sub is-square (@m) { so @m == all @m[*] }   sub identity ($n) { [ 1, |(0 xx $n-1) ], *.rotate(-1).Array ... *.tail }   # reduced row echelon form (from 'Gauss-Jordan elimination' task) sub...
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Perl
Perl
  #!bin/usr/perl use 5.020; use strict; use warnings;   #Get a max number from the user say("Please enter the maximum possible multiple. "); my $max = <STDIN>;   #Get the factors from the user my @factors = (); my $buffer; say("Now enter the first factor and its associated word. Ex: 3 Fizz "); chomp($buffer = <STDIN>);...
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Furor
Furor
  #k 'a 'z ++ {|| {} print SPACE |} NL end  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short   For siCount = Asc("a") To Asc("z") Print Chr(siCount); Next   End
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Pascal
Pascal
program byeworld; begin writeln('Hello world!'); end.
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Phix
Phix
-- -- demo\rosetta\Generator_Exponential.exw -- ====================================== -- without js -- tasks bool terminate = false atom res procedure powers(integer p) integer i=0 while not terminate do res = power(i,p) task_suspend(task_self()) task_yield() i += 1 end while ...
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Swift
Swift
func isValid960Position(_ firstRank: String) -> Bool { var rooksPlaced = 0 var bishopColor = -1   for (i, piece) in firstRank.enumerated() { switch piece { case "♚" where rooksPlaced != 1: return false case "♜": rooksPlaced += 1 case "♝" where bishopColor == -1: bishopColor = i &...
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Tcl
Tcl
package require struct::list   proc chess960 {} { while true { set pos [join [struct::list shuffle {N N B B R R Q K}] ""] if {[regexp {R.*K.*R} $pos] && [regexp {B(..)*B} $pos]} { return $pos } } }   # A simple renderer proc chessRender {position} { string map {P ♙ N ♘ B ♗ R ♖ Q ♕ K ♔} $position }  ...
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#C.23
C#
using System; class Program { static void Main(string[] args) { Func<int, int> outfunc = Composer<int, int, int>.Compose(functA, functB); Console.WriteLine(outfunc(5)); //Prints 100 } static int functA(int i) { return i * 10; } static int functB(int i) { return i + 5; } class Com...
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Ceylon
Ceylon
import javax.swing {   JFrame { exitOnClose } } import java.awt {   Color { white, black }, Graphics } import ceylon.numeric.float {   cos, toRadians, sin }   shared void run() {   value fractalTree = object extends JFrame("fractal tree") {   background = black; setBounds(100, 100, 800, 600); ...
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Clojure
Clojure
(import '[java.awt Color Graphics] 'javax.swing.JFrame)   (defn deg-to-radian [deg] (* deg Math/PI 1/180)) (defn cos-deg [angle] (Math/cos (deg-to-radian angle))) (defn sin-deg [angle] (Math/sin (deg-to-radian angle)))   (defn draw-tree [^Graphics g, x y angle depth] (when (pos? depth) (let [x2 (+ x (int (* dept...
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct IntArray_t { int *ptr; size_t length; } IntArray;   IntArray make(size_t size) { IntArray temp; temp.ptr = calloc(size, sizeof(int)); temp.length = size; return temp; }   void destroy(IntArray *ia) {...
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Befunge
Befunge
p0" :snoitcarF">:#,_>&00g5p~$&00g:v v"Starting value: "_^#-*84~p6p00+1< >:#,_&0" :snoitaretI">:#,_#@>>$&\:v :$_\:10g5g*:10g6g%v1:\1$\$<|!:-1\.< g0^<!:-1\p01+1g01$_10g6g/\^>\010p00
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Ruby
Ruby
require 'net/ftp'   Net::FTP.open('ftp.ed.ac.uk', "anonymous","aaa@gmail.com" ) do |ftp| ftp.passive = true # default since Ruby 2.3 ftp.chdir('pub/courses') puts ftp.list ftp.getbinaryfile("make.notes.tar") end
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Rust
Rust
use std::{error::Error, fs::File, io::copy}; use ftp::FtpStream;   fn main() -> Result<(), Box<dyn Error>> { let mut ftp = FtpStream::connect("ftp.easynet.fr:21")?; ftp.login("anonymous", "")?; ftp.cwd("debian")?; for file in ftp.list(None)? { println!("{}", file); } let mut stream = ftp...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Scala
Scala
import java.io.{File, FileOutputStream, InputStream}   import org.apache.commons.net.ftp.{FTPClient, FTPFile, FTPReply}   import scala.util.{Failure, Try}   object FTPconn extends App { val (server, pass) = ("ftp.ed.ac.uk", "-ftptest@example.com") val (dir, filename, ftpClient) = ("/pub/cartonet/", "readme.txt", ne...
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#zkl
zkl
fcn{"Hello World"} // no expected args fcn(){"Hello World"} // ditto   fcn{vm.arglist}(1,2) // ask the VM for the passed in args -->L(1,2) fcn f(a,b){a+b} // fcn(1,2,3) works just fine fcn f(args){}(1,2,3) //args = 1 fcn(args){vm.arglist.sum()}(1,2,3) //-->6   fcn(a=1,b=2){vm.arglist}() //-->L(1,2) fcn(a=1,b=2){...
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Aime
Aime
real multiply(real a, real b) { return a * b; }
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Factor
Factor
USING: arrays assocs formatting io kernel make math math.parser math.ranges namespaces prettyprint sequences tools.memory.private ; IN: rosetta-code.fusc   <PRIVATE   : (fusc) ( n -- seq ) [ 2 ] dip [a,b) [ 0 , 1 , [ [ building get ] dip dup even? [ 2/ swap nth ] [ [ 1 - ...
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Forth
Forth
\ Gforth 0.7.9_20211014   : fusc ( n -- n) \ input n -- output fusc(n) dup dup 0= swap 1 = or \ n = 0 or 1 if exit \ return n else dup 2 mod 0= \ test even if 2/ recurse \ even fusc(n)= fusc(n/2) else du...
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Wren
Wren
import "io" for File import "os" for Process import "/pattern" for Pattern import "/set" for Bag import "/sort" for Sort import "/fmt" for Fmt   var args = Process.arguments if (args.count != 1) { Fiber.abort("There should be exactly one argument - the file path to be analyzed") } var p = Pattern.new("[+1/x.+1/x]("...
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Delphi
Delphi
  program Gamma_function;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   function lanczos7(z: double): Double; begin var t := z + 6.5; var x := 0.99999999999980993 + 676.5203681218851 / z - 1259.1392167224028 / (z + 1) + 771.32342877765313 / (z + 2) - 176.61502916214059 / (z + 3) + 12.50734...
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[MakePathFunction] MakePathFunction[{path_, acumpath_}] := Module[{f1, f2, f3, pf, n = Length[path]}, f1 = MapThread[{#1/2, #2 + 0.5 < z <= #2 + 1} &, {acumpath, n - Range[n + 1]}]; f2 = MapThread[{#1/2 + #2 Sqrt[1/4 - (z - #3)^2], #3 < z <= #3 + 1/2} &, {acumpath // Most, path, n - Range[n]...
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Nim
Nim
import random, strutils   const BoxW = 41 # Galton box width. BoxH = 37 # Galton box height. PinsBaseW = 19 # Pins triangle base. NMaxBalls = 55 # Number of balls.   const CenterH = PinsBaseW + (BoxW - (PinsBaseW * 2 - 1)) div 2 - 1   type   Cell = enum cEmpty = " " cBall = "o" ...
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numb...
#Lambdatalk
Lambdatalk
  {def gapfuls {lambda {:n :i :N} {if {>= :i :N} then else {if {= {% :n {W.first :n}{W.last :n}} 0} then :n {gapfuls {+ :n 1} {+ :i 1} :N} else {gapfuls {+ :n 1}  :i  :N}}}}} -> gapfuls   {gapfuls 100 0 30} -> 100 105 108 110 120 121 130 132 135 140 143 150 154 160 165 170 176 180 187 190 192 1...
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Kotlin
Kotlin
// version 1.1.51   val ta = arrayOf( doubleArrayOf(1.00, 0.00, 0.00, 0.00, 0.00, 0.00), doubleArrayOf(1.00, 0.63, 0.39, 0.25, 0.16, 0.10), doubleArrayOf(1.00, 1.26, 1.58, 1.98, 2.49, 3.13), doubleArrayOf(1.00, 1.88, 3.55, 6.70, 12.62, 23.80), doubleArrayOf(1.00, 2.51, 6.32, 15.88, 39.90, 100.28), ...
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#REXX
REXX
/* REXX */ Parse Arg seed nn If seed='' Then seed=23345 If nn='' Then nn=5 If seed='?' Then Do Say 'rexx gjmi seed n computes a random matrix with n rows and columns' Say 'Default is 23345 5' Exit End Numeric Digits 50 Call random 1,2,seed a='' Do i=1 To nn**2 a=a random(9)+1 End n2=words(a) Do n=2 To n2/...
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Phix
Phix
procedure general_fizz_buzz(integer lim, sequence words, facts) for i=1 to lim do string word = "" for j=1 to length(facts) do if remainder(i,facts[j])=0 then word &= words[j] end if end for if length(word)=0 then word = sprintf("%d...
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Go
Go
func loweralpha() string { p := make([]byte, 26) for i := range p { p[i] = 'a' + byte(i) } return string(p) }
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Groovy
Groovy
def lower = ('a'..'z')
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PASM
PASM
print "Hello world!\n" end
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#PHP
PHP
<?php function powers($m) { for ($n = 0; ; $n++) { yield pow($n, $m); } }   function filtered($s1, $s2) { while (true) { list($v, $f) = [$s1->current(), $s2->current()]; if ($v > $f) { $s2->next(); continue; } else if ($v < $f) { yield $v; ...
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Wren
Wren
import "random" for Random import "/dynamic" for Tuple import "/fmt" for Fmt   var Symbols = Tuple.create("Symbols", ["k", "q", "r", "b", "n"])   var A = Symbols.new("K", "Q", "R", "B", "N") var W = Symbols.new("♔", "♕", "♖", "♗", "♘") var B = Symbols.new("♚", "♛", "♜", "♝", "♞")   var krn = [ "nnrkr", "nrnkr", "nr...
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#C.2B.2B
C++
#include <functional> #include <cmath> #include <iostream>   // functor class to be returned by compose function template <class Fun1, class Fun2> class compose_functor : public std::unary_function<typename Fun2::argument_type, typename Fun1::result_type> { protected: Fun1 f; Fun2 g; ...
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Common_Lisp
Common Lisp
;; (require :lispbuilder-sdl)   (defun deg-to-radian (deg) "converts degrees to radians" (* deg pi 1/180))   (defun cos-deg (angle) "returns cosin of the angle expressed in degress" (cos (deg-to-radian angle)))   (defun sin-deg (angle) "returns sin of the angle expressed in degress" (sin (deg-to-radian angl...
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#C.23
C#
using System;   namespace FractionReduction { class Program { static int IndexOf(int n, int[] s) { for (int i = 0; i < s.Length; i++) { if (s[i] == n) { return i; } } return -1; }   static bool GetDigits(...
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#BQN
BQN
# Fractran interpreter   # Helpers _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} ToInt ← 10⊸×⊸+˜´·⌽-⟜'0' ToFrac ← { i ← ⊑/'/'=𝕩 ToInt¨i(↑⋈1⊸+⊸↓)𝕩 } Split ← ((¬-˜⊢×·+`»⊸>)∘≠⊔⊢)   Fractran ← { 𝕊 n‿num‿den: ind ← ⊑/0=den|num×n ⟨(n×ind⊑num)÷ind⊑den ⋄ num ⋄ den⟩ }   RunFractran ← { steps 𝕊 inp‿prg: num‿den ← <˘⍉>ToFr...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "ftp.s7i";   const proc: main is func local var ftpFileSys: ftp is fileSys.value; var string: line is ""; begin ftp := openFtp("kernel.org"); setActiveMode(ftp, FALSE); # Passive is the default. chdir(ftp, "/pub/linux/kernel"); for line range listDir(ftp,...
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Sidef
Sidef
require('Net::FTP');   var ftp = %s'Net::FTP'.new('ftp.ed.ac.uk', Passive => 1); ftp.login('anonymous','aaa@gmail.com'); ftp.cwd('pub/courses'); [ftp.dir].each {|line| say line }; ftp.binary; # set binary mode ftp.get("make.notes.tar"); ftp.quit;
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Tcl
Tcl
  package require ftp   set conn [::ftp::Open kernel.org anonymous "" -mode passive] ::ftp::Cd $conn /pub/linux/kernel foreach line [ftp::NList $conn] { puts $line } ::ftp::Type $conn binary ::ftp::Get $conn README README  
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#ALGOL_60
ALGOL 60
begin comment Function definition; integer procedure multiply(a,b); integer a,b; begin multiply:=a*b; end; integer c; c:=multiply(2,2); outinteger(1,c) end
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#FreeBASIC
FreeBASIC
' version 01-03-2019 ' compile with: fbc -s console   #Define max 20000000   Dim Shared As UInteger f(max)   Sub fusc   f(0) = 0 f(1) = 1   For n As UInteger = 2 To max If n And 1 Then f(n) = f((n -1) \ 2) + f((n +1) \ 2) Else f(n) = f(n \ 2) End If Next  ...
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Elixir
Elixir
defmodule Gamma do @a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_9509...
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Perl
Perl
use strict; use warnings;   use List::Util 'any'; use Time::HiRes qw(sleep); use List::AllUtils <pairwise pairs>;   use utf8; binmode STDOUT, ':utf8';   my $coins = shift || 100; my $peg_lines = shift || 13; my $row_count = $peg_lines; my $peg = '^'; my @coin_icons = ("\N{UPPER HALF BLOCK}", "\N{LOWER HAL...