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/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...
#C
C
  #include<limits.h> #include<stdio.h>   int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); }   int numLen(int n){ int sum = 1;   while(n>9){ n = n/...
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have...
#Swift
Swift
import Foundation   extension String { func paddedLeft(totalLen: Int) -> String { let needed = totalLen - count   guard needed > 0 else { return self }   return String(repeating: " ", count: needed) + self } }   class FCNode { let name: String let weight: Int   var coverage: Double { ...
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have...
#Wren
Wren
import "/fmt" for Fmt   class FCNode { construct new(name, weight, coverage) { _name = name _weight = weight _coverage = coverage _children = [] _parent = null }   static new(name, weight) { new(name, weight, 0) } static new(name) { new(name, 1, 0) }   ...
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...
#Julia
Julia
using Printf, DataStructures   function funcfreqs(expr::Expr) cnt = counter(Symbol) expr.head == :call && push!(cnt, expr.args[1]) for e in expr.args e isa Expr && merge!(cnt, funcfreqs(e)) end return cnt end   function parseall(str::AbstractString) exs = Any[] pos = start(st...
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...
#LiveCode
LiveCode
function handlerNames pScript put pScript into pScriptCopy filter pScript with regex pattern "^(on|function).*" -- add in the built-in commands & functions put the commandNames & the functionnames into cmdfunc repeat for each line builtin in cmdfunc put 0 into handlers[builtin] end repea...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
programCount[fn_] := Reverse[If[Length[#] > 10, Take[#, -10], #] &[SortBy[Tally[Cases[DownValues[fn], s_Symbol, \[Infinity], Heads -> True]], Last]]]
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...
#C.23
C#
using System; using System.Numerics;   static int g = 7; static double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};   Complex Gamma(Complex z) { // Ref...
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 ...
#J
J
initpins=: '* ' {~ '1'&i.@(-@|. |."_1 [: ":@-.&0"1 <:~/~)@i.
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...
#Groovy
Groovy
class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)) int le = sb.length() for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ',') } return sb.toString() }   static void main(String[] args) ...
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
#J
J
  f=: 6j2&": NB. formatting verb   sin=: 1&o. NB. verb to evaluate circle function 1, the sine   add_noise=: ] + (* (_0.5 + 0 ?@:#~ #)) NB. AMPLITUDE add_noise SIGNAL   f RADIANS=: o.@:(%~ i.@:>:)5 NB. monadic circle function is pi times 0.00 0.63 1.26 1.88 2.51 3.14   f SINES=: sin RADIAN...
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.
#Nim
Nim
import strformat, strutils   const Eps = 1e-10   type Matrix[M, N: static Positive] = array[M, array[N, float]] SquareMatrix[N: static Positive] = Matrix[N, N]     func toSquareMatrix[N: static Positive](a: array[N, array[N, int]]): SquareMatrix[N] = ## Convert a square matrix of integers to a square matrix of fl...
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 ...
#Maple
Maple
findNum := proc(str) #help parse input local i; i := 1: while (true) do if (StringTools:-IsAlpha(str[i])) then return i-2: end if: i := i+1: end do: end proc: path := "input.txt"; input := readline(path): T := table(): maxnum := parse(input): while (true) do input := readline(path): if input = 0 then bre...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
list={{5,"Buzz"},{3,"Fizz"},{7,"Baxx"}}; runTo=(*LCM@@list[[All,1]]+1*)20; Column@Table[ Select[list,Mod[x,#[[1]]]==0&][[All,2]]/.{}->{x} ,{x,1,runTo} ]
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...
#Erlang
Erlang
lists:seq($a,$z).
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...
#Excel
Excel
showAlphabet =LAMBDA(az, ENUMFROMTOCHAR( MID(az, 1, 1) )( MID(az, 2, 1) ) )
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
#OpenLisp
OpenLisp
  #!/openlisp/uxlisp -shell (format t "Hello world!~%") (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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
lastsquare = 1; nextsquare = -1; lastcube = -1; midcube = 0; nextcube = 1; Gensquares[] := Module[{}, lastsquare += nextsquare; nextsquare += 2; squares = lastsquare; squares ] Gencubes[] := Module[{}, lastcube += nextcube; nextcube += midcube; midcube += 6; cubes = lastcube ]     c = Gencubes[]; Do...
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...
#REXX
REXX
/*REXX program generates a random starting position for the Chess960 game. */ parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ @.=. /*define the first rank as being empty...
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...
#Arturo
Arturo
compose: function [f,g] -> return function [x].import:[f,g][ call f @[call g @[x]] ]   splitupper: compose 'split 'upper   print call 'splitupper ["done"]
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...
#ATS
ATS
(* The 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, (let's call the argument x), which works like applying function f to the result of applying function g to x.   In...
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
#11l
11l
-V Width = 1000 Height = 1000 TrunkLength = 400 ScaleFactor = 0.6 StartingAngle = 1.5 * math:pi DeltaAngle = 0.2 * math:pi   F drawTree(outfile, Float x, Float y; len, theta) -> N I len >= 1 V x2 = x + len * cos(theta) V y2 = y + len * sin(theta) outfile.write("<line x1='#.6' y1='...
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 ...
#Ada
Ada
with Ada.Text_IO;   procedure Fractan is   type Fraction is record Nom: Natural; Denom: Positive; end record; type Frac_Arr is array(Positive range <>) of Fraction;   function "/" (N: Natural; D: Positive) return Fraction is Frac: Fraction := (Nom => N, Denom => D); begin return Frac; 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.
#Java
Java
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply;   public class FTPconn {   public static void main(Stri...
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...
#Oforth
Oforth
Method new: myMethod
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...
#Ol
Ol
  'DECLARE FUNCTION' ABBREVIATED TO '!'   ! f() ' a procedure with no params ! f(int a) ' with 1 int param ! f(int *a) ' with 1 int pointer param ! f(int a, int b, inc c) ' with 3 int params ! f(int a,b,c) ' compaction with 3 int params ! f(string s, in...
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...
#OxygenBasic
OxygenBasic
  'DECLARE FUNCTION' ABBREVIATED TO '!'   ! f() ' a procedure with no params ! f(int a) ' with 1 int param ! f(int *a) ' with 1 int pointer param ! f(int a, int b, inc c) ' with 3 int params ! f(int a,b,c) ' compaction with 3 int params ! f(string s, in...
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 ...
#8086_Assembly
8086 Assembly
start: mov al, 0x04 mov bl, 0x05 call multiply ;at this point in execution, the AX register contains 0x0900. ;more code goes here, ideally with some sort of guard against "fallthrough" into multiply.   ; somewhere far away from start multiply: mul bl ;outputs 0x0014 to ax ret
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...
#Nim
Nim
  import strformat, strscans, strutils, times   const   RcMonths = ["Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor"]   SansCulottides = ["Fête de la vertu", "Fête du génie", "Fête du travail", ...
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...
#Perl
Perl
use feature 'state'; use DateTime; my @month_names = qw{ Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse Germinal Floréal Prairial Messidor Thermidor Fructidor }; my @intercalary = ( 'Fête de la vertu', 'Fête du génie', 'Fête du travail', "Fête de l'opinion", 'Fête des récompenses...
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...
#C.23
C#
using System; using System.Collections.Generic;   static class program { static int n = 61; static List<int> l = new List<int>() { 0, 1 };   static int fusc(int n) { if (n < l.Count) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.Add(f); retu...
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...
#Nim
Nim
# naive function calling counter # TODO consider a more sophisticated condition on counting function callings # without parenthesis which are common in nim lang. Be aware that the AST of # object accessor and procedure calling without parenthesis are same.   import macros, tables, strformat, os proc visitCall(node: N...
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...
#Perl
Perl
use PPI::Tokenizer; my $Tokenizer = PPI::Tokenizer->new( '/path/to/your/script.pl' ); my %counts; while (my $token = $Tokenizer->get_token) { # We consider all Perl identifiers. The following regex is close enough. if ($token =~ /\A[\$\@\%*[:alpha:]]/) { $counts{$token}++; } } my @desc_by_occurrence...
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...
#C.2B.2B
C++
#include <math.h> #include <numbers> #include <stdio.h> #include <vector>   // Calculate the coefficients used by Spouge's approximation (based on the C // implemetation) std::vector<double> CalculateCoefficients(int numCoeff) { std::vector<double> c(numCoeff); double k1_factrl = 1.0; c[0] = sqrt(2.0 * std:...
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 ...
#Java
Java
import java.util.Random; import java.util.List; import java.util.ArrayList;   public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); }   private final int m_pinRows; private final int m_startRow; private final Position[] m_balls...
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...
#Haskell
Haskell
{-# LANGUAGE NumericUnderscores #-}   gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n   main :: IO () main = do putStrLn $ "\nFirst 30 Gapful numbers >= 100 :\n" ++ r 30 [100,101..] putStrLn $ "\nFirst 15 Gapful numbers...
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
#Java
Java
import java.util.Locale;   public class GaussianElimination { public static double solve(double[][] a, double[][] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { throw new IllegalArgumentException("Invalid dimensions"); }   int n = b.length, p = b[0].length; ...
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.
#Perl
Perl
sub rref { our @m; local *m = shift; @m or return; my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));   foreach my $r (0 .. $rows - 1) { $lead < $cols or return; my $i = $r;   until ($m[$i][$lead]) {++$i == $rows or next; $i = $r; ++$lead == $cols and ret...
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 ...
#MiniScript
MiniScript
factorWords = {}   maxNr = val(input("Max number? "))   while true factorInput = input("Factor? ") if factorInput == "" then break // Split input parts = factorInput.split(" ") factor = val(parts[0]) word = parts[1] // Assign factor/word factorWords[factor] = word end while   for nr in range(1,maxNr) matchingW...
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 ...
#Modula-2
Modula-2
MODULE GeneralFizzBuzz; FROM Conversions IMPORT StrToInt; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   TYPE Word = ARRAY[0..63] OF CHAR;   PROCEDURE WriteInt(i : INTEGER); VAR buf : Word; BEGIN FormatString("%i", buf, i); WriteString(buf); END WriteInt;  ...
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...
#F.23
F#
let lower = ['a'..'z']   printfn "%A" lower
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...
#Factor
Factor
USING: spelling ; ! ALPHABET   ALPHABET print 0x61 0x7A [a,b] >string print : russian-alphabet-without-io ( -- str ) 0x0430 0x0450 [a,b) >string ; : russian-alphabet ( -- str ) 0x0451 6 russian-alphabet-without-io insert-nth ; russian-alphabet print
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
#Openscad
Openscad
  echo("Hello world!"); // writes to the console text("Hello world!"); // creates 2D text in the object space linear_extrude(height=10) text("Hello world!"); // creates 3D text in the object space  
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...
#Nim
Nim
type Iterator = iterator(): int   proc `^`*(base: Natural; exp: Natural): int = var (base, exp) = (base, exp) result = 1 while exp != 0: if (exp and 1) != 0: result *= base exp = exp shr 1 base *= base   proc next(s: Iterator): int = for n in s(): return n   proc powers(m: Natural): Iterator =...
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...
#Ruby
Ruby
pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) regexes = [/♗(..)*♗/, /♖.*♔.*♖/] row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} puts row
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...
#Rust
Rust
use std::collections::BTreeSet;   struct Chess960 ( BTreeSet<String> );   impl Chess960 { fn invoke(&mut self, b: &str, e: &str) { if e.len() <= 1 { let s = b.to_string() + e; if Chess960::is_valid(&s) { self.0.insert(s); } } else { for (i, c) in e.char_indices() ...
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...
#AutoHotkey
AutoHotkey
MsgBox % compose("sin","cos",1.5)   compose(f,g,x) { ; function composition Return %f%(%g%(x)) }
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...
#BBC_BASIC
BBC BASIC
REM Create some functions for testing: DEF FNsqr(a) = SQR(a) DEF FNabs(a) = ABS(a)   REM Create the function composition: SqrAbs = FNcompose(FNsqr(), FNabs())   REM Test calling the composition: x = -2 : PRINT ; x, FN(SqrAbs)(x) END   DEF FNcompose(RETURN f%, RETURN...
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
#Action.21
Action!
DEFINE MAXSIZE="12"   INT ARRAY SinTab=[ 0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83 88 92 96 100 104 108 112 116 120 124 128 132 136 139 143 147 150 154 158 161 165 168 171 175 178 181 184 187 190 193 196 199 202 204 207 210 212 215 217 219 222 224 226 228 230 232 234 236 237 239 241 242 243 245...
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
#Ada
Ada
with Ada.Numerics.Elementary_Functions;   with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Rectangles; with SDL.Events.Events;   procedure Fractal_Tree is   Width  : constant := 600; Height  : constant := 600; Level  : constant := 13; Length  : constant := 130.0; X_Start :...
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 ...
#ALGOL_68
ALGOL 68
# as the numbers required for finding the first 20 primes are quite large, # # we use Algol 68G's LONG LONG INT with a precision of 100 digits # PR precision 100 PR   # mode to hold fractions # MODE FRACTION = STRUCT( INT numerator, INT denominator );   # define / between two INTs to yield a FRACTION # OP / = ...
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.
#Julia
Julia
using FTPClient   ftp = FTP(hostname = "ftp.ed.ac.uk", username = "anonymous") cd(ftp, "pub/courses") println(readdir(ftp)) bytes = read(download(ftp, "make.notes.tar"))   close(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.
#Kotlin
Kotlin
headers = /usr/include/ftplib.h linkerOpts.linux = -L/usr/lib -lftp --- #include <sys/time.h> struct NetBuf { char *cput,*cget; int handle; int cavail,cleft; char *buf; int dir; netbuf *ctrl; netbuf *data; int cmode; struct timeval idletime; FtpCallback idlecb; void *i...
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.
#Lingo
Lingo
CURLOPT_URL = 10002 ch = xtra("Curl").new() url = "ftp://domain.com"   -- change to remote dir "/foo/bar/" put "/foo/bar/" after url   ch.setOption(CURLOPT_URL, url) res = ch.exec(1)   -- print raw FTP listing as string put res.readRawString(res.length)   -- download file "download.mp3" (passive mode is the internal de...
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.
#LiveCode
LiveCode
libURLSetFTPMode "passive" --default is passive anyway put url "ftp://ftp.hq.nasa.gov/" into listing repeat for each line ftpln in listing set itemdel to space if the first char of (the first item of ftpln) is "d" then -- is a directory put the last item of ftpln after dirlist else ...
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...
#PARI.2FGP
PARI/GP
long foo(GEN a, GEN b)
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...
#Perl
Perl
sub noargs(); # Declare a function with no arguments sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders sub noargs :prototype(); # Using the :attribute syntax instead sub twoargs :prototype($$);
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...
#Phix
Phix
forward function noargs() -- Declare a function with no arguments forward procedure twoargs(integer a, integer b) -- Declare a procedure with two arguments forward procedure twoargs(integer, integer /*b*/) -- Parameter names are optional in forward (and actual) definitions forward function anyargs(sequence s) -- vararg...
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program functMul64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
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...
#Phix
Phix
with javascript_semantics constant gregorians = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}, gregorian = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, republicans = {"Vendémiaire", "Brumaire", "F...
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...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <limits> #include <sstream> #include <vector>   const int n = 61; std::vector<int> l{ 0, 1 };   int fusc(int n) { if (n < l.size()) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.push_back(f); return f; }   int main() ...
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...
#Phix
Phix
else -- rType=FUNC|TYPE log_function_call(rtnNo)
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...
#PicoLisp
PicoLisp
(let Freq NIL (for "L" (filter pair (extract getd (all))) (for "F" (filter atom (fish '((X) (or (circ? X) (getd X))) "L" ) ) (accu 'Freq "F" 1) ) ) (for X (head 10 (flip (by cdr sort Freq))) (tab (-7 4) (car X) (cdr X)) ) )
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...
#Python
Python
import ast   class CallCountingVisitor(ast.NodeVisitor):   def __init__(self): self.calls = {}   def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count ...
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...
#Clojure
Clojure
(defn gamma "Returns Gamma(z + 1 = number) using Lanczos approximation." [number] (if (< number 0.5) (/ Math/PI (* (Math/sin (* Math/PI number)) (gamma (- 1 number)))) (let [n (dec number) c [0.99999999999980993 676.5203681218851 -1259.1392167224028 771.3234287776...
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 ...
#JavaScript
JavaScript
const readline = require('readline');   /** * Galton Box animation * @param {number} layers The number of layers in the board * @param {number} balls The number of balls to pass through */ const galtonBox = (layers, balls) => { const speed = 100; const ball = 'o'; const peg = '.'; const result = [];   con...
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...
#J
J
  gapful =: 0 = (|~ ({.,{:)&.(10&#.inv))   task =: 100&$: :(dyad define) NB. MINIMUM task TALLY gn =. y {. (#~ gapful&>) x + i. y * 25 assert 0 ~: {: gn 'The first ' , (": y) , ' gapful numbers exceeding ' , (":<:x) , ' are ' , (":gn) )  
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...
#Java
Java
import java.util.List;   public class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)); int le = sb.length(); for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ','); } return sb.toString(); }   ...
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
#JavaScript
JavaScript
// Lower Upper Solver function lusolve(A, b, update) { var lu = ludcmp(A, update) if (lu === undefined) return // Singular Matrix! return lubksb(lu, b, update) }   // Lower Upper Decomposition function ludcmp(A, update) { // A is a matrix that we want to decompose into Lower and Upper matrices. var d = true var n...
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.
#Phix
Phix
with javascript_semantics function ToReducedRowEchelonForm(sequence M) integer lead = 1, rowCount = length(M), columnCount = length(M[1]), i for r=1 to rowCount do if lead>=columnCount then exit end if i = r while M[i][lead]=0 do i += 1 if i=ro...
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 ...
#Nanoquery
Nanoquery
factors = {} words = {}   // get the max number print ">" max = int(input())   // get the factors inp = " " while inp != "" print ">" inp = input() if " " in inp factors.append(int(split(inp, " ")[0])) words.append(split(inp, " ")[1]) end end   // output all the numbers for i in range(1, max) foundfactor = f...
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 ...
#Nim
Nim
  import parseutils, strutils, algorithm   type FactorAndWord = tuple[factor:int, word: string]   var number: int var factorAndWords: array[3, FactorAndWord]   #custom comparison proc for the FactorAndWord type proc customCmp(x,y: FactorAndWord): int = if x.factor < y.factor: -1 elif x.factor > y.factor: 1 ...
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...
#FALSE
FALSE
'a[$'z>~][$,1+]#%
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...
#Fermat
Fermat
Array locase[1,26]; [locase]:=[<i=1,26>'a'+i-1]; !([locase:char);
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
#Oxygene
Oxygene
  namespace HelloWorld;   interface   type HelloClass = class public class method Main; end;   implementation   class method HelloClass.Main; begin writeLn('Hello world!'); end;   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...
#OCaml
OCaml
  (* Task : Generator/Exponential   Version using the Seq module types, but transparently *)   (*** Helper functions ***)   (* Generator type *) type 'a gen = unit -> 'a node and 'a node = Nil | Cons of 'a * 'a gen   (* Power function on integers *) let power (base : int) (exp : int) : int = let rec helper e...
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...
#Scala
Scala
import scala.annotation.tailrec   object Chess960 extends App {   private val pieces = List('♖', '♗', '♘', '♕', '♔', '♘', '♗', '♖')   @tailrec private def generateFirstRank(pieces: List[Char]): List[Char] = { def check(rank: String) = rank.matches(".*♖.*♔.*♖.*") && rank.matches(".*♗(..|....|......|)♗.*"...
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...
#Bori
Bori
double sin (double v) { return Math.sin(v); } double asin (double v) { return Math.asin(v); } Var compose (Func f, Func g, double d) { return f(g(d)); }   void button1_onClick (Widget widget) { double d = compose(sin, asin, 0.5); label1.setText(d.toString(9)); }
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...
#BQN
BQN
_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
#Arturo
Arturo
width: 1000 height: 1000   trunkLength: 400 scaleFactor: 0.6 startingAngle: 1.5 * pi deltaAngle: 0.2 * pi   drawTree: function [out x y len theta][ if len < 1 -> return null   x2: x + len * cos theta y2: y + len * sin theta   'out ++ ~"<line x1='|x|' y1='|y|' x2='|x2|' y2='|y2|' style='stroke: white; st...
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
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1   ; Uncomment if Gdip.ahk is not in your standard library ; #Include, Gdip.ahk   FileOut := A_Desktop "\MyNewFile.png" TreeColor := 0xff0066ff ; ARGB TrunkWidth := 10 ; Pixels TrunkLength := 80 ; Pixels Angle := 60 ; Degrees ImageWidth := 670 ; Pixels ImageHeight...
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 ...
#AutoHotkey
AutoHotkey
n := 2, steplimit := 15, numerator := [], denominator := [] s := "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"   Loop, Parse, s, % A_Space if (!RegExMatch(A_LoopField, "^(\d+)/(\d+)$", m)) MsgBox, % "Invalid input string (" A_LoopField ")." else numerator[A_I...
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.
#Nim
Nim
import asyncdispatch, asyncftpclient   const Host = "speedtest.tele2.net" Upload = "upload" File = "1KB.zip"   proc main {.async.} =   # Create session and connect. let ftp = newAsyncFtpClient(Host, user = "anonymous", pass = "anything") await ftp.connect() echo "Connected." echo await ftp.send("PASV") ...
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.
#Perl
Perl
use Net::FTP;   # set server and credentials my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = '';   # connect in passive mode my $f = Net::FTP->new($host) or die "Can't open $host\n"; $f->login($user, $password) or die "Can't login as $user\n"; $f->passive();   # change remote directory...
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.
#Phix
Phix
without js -- libcurl, allocate, file i/o include libcurl.e constant url = "ftp://speedtest.tele2.net/" curl_global_init() atom curl = curl_easy_init(), pErrorBuffer = allocate(CURL_ERROR_SIZE) curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, pErrorBuffer) curl_easy_setopt(curl, CURLOPT_URL, url) object res = curl_ea...
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...
#PL.2FI
PL/I
  declare s1 entry; declare s2 entry (fixed); declare s3 entry (fixed, float);   declare f1 entry returns (fixed); declare f2 entry (float) returns (float); declare f3 entry (character(*), character(*)) returns (character (20));  
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...
#PureBasic
PureBasic
;Forward procedure declare defined with no arguments and that returns a string Declare.s booTwo() ;Forward procedure declare defined with two arguments and that returns a float Declare.f moo(x.f, y.f) ;Forward procedure declare with two arguments and an optional argument and that returns a float Declare.f cmoo(x.f, y.f...
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 ...
#ACL2
ACL2
(defun multiply (a b) (* 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...
#Raku
Raku
use v6; constant @month_names = < Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse Germinal Floréal Prairial Messidor Thermidor Fructidor >; constant @intercalary = 'Fête de la vertu', 'Fête du génie', 'Fête du travail', "Fête de l'opinion", 'Fête des récompenses', 'Fête de la Révo...
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...
#CLU
CLU
fusc = iter () yields (int) q: array[int] := array[int]$[1] yield(0) yield(1)   while true do x: int := array[int]$reml(q) array[int]$addh(q,x) yield(x)   x := x + array[int]$bottom(q) array[int]$addh(q,x) yield(x) end end fusc   longest_fusc = iter ()...
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...
#D
D
import std.functional, std.stdio, std.format, std.conv;   ulong fusc(ulong n) => memoize!fuscImp(n);   ulong fuscImp(ulong n) => ( n < 2 ) ? n : ( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) : memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );   void main() { const N_FIRST=61; const MAX_N_DIGITS=5;   ...
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...
#Racket
Racket
  #lang racket (require math) (define in (open-input-file "function-frequency.rkt")) (void (read-language in)) (define s-exprs (for/list ([s (in-port read in)]) s)) (define symbols (filter symbol? (flatten s-exprs))) (define counts (sort (hash->list (samples->hash symbols)) >= #:key cdr)) (take counts (min 10 (length ...
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...
#Raku
Raku
my $text = qqx[raku --target=ast @*ARGS[]]; my %fun; for $text.lines { %fun{$0}++ if / '(call &' (.*?) ')' / }   for %fun.invert.sort.reverse[^10] { .value.say }
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...
#Common_Lisp
Common Lisp
; Taylor series coefficients (defconstant tcoeff '( 1.00000000000000000000 0.57721566490153286061 -0.65587807152025388108 -0.04200263503409523553 0.16653861138229148950 -0.04219773455554433675 -0.00962197152787697356 0.00721894324666309954 -0.00116516759185906511 -0.00021524167411495097 0.000128050282...
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 ...
#Julia
Julia
using Random function drawball(timer) global r, c, d print("\e[$r;$(c)H ") # clear last ball position (r,c) if (r+=1) > 14 close(timer) b = (bin[(c+2)>>2] += 1)# update count in bin print("\e[$b;$(c)Ho") # lengthen bar of balls in bin else r in 3:2:13 && c in 17-r...
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 ...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val boxW = 41 // Galton box width. val boxH = 37 // Galton box height. val pinsBaseW = 19 // Pins triangle base. val nMaxBalls = 55 // Number of balls.   val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1 val rand = Random()   enum class Cell(val c: ...
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...
#JavaScript
JavaScript
// Function to construct a new integer from the first and last digits of another function gapfulness_divisor (number) { var digit_string = number.toString(10) var digit_count = digit_string.length var first_digit = digit_string.substring(0, 1) var last_digit = digit_string.substring(digit_count - 1) return parseIn...
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
#jq
jq
def ta: [ [1.00, 0.00, 0.00, 0.00, 0.00, 0.00], [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02] ];   def tb:[-0.01, 0.61, 0.91, 0.9...
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.
#PL.2FI
PL/I
/* Gauss-Jordan matrix inversion */ G_J: procedure options (main); /* 4 November 2020 */ declare t float; declare (i, j, k, n) fixed binary; open file (sysin) title ('/GAUSSJOR.DAT'); get (n); /* Read in the order of the matrix. */ put skip data (n); begin; declare ...
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.
#PowerShell
PowerShell
  function gauss-jordan-inv([double[][]]$a) { $n = $a.count [double[][]]$b = 0..($n-1) | foreach{[double[]]$row = @(0) * $n; $row[$_] = 1; ,$row} for ($k = 0; $k -lt $n; $k++) { $lmax, $max = $k, [Math]::Abs($a[$k][$k]) for ($l = $k+1; $l -lt $n; $l++) { $tmp = [Math]::Abs($a[$l...
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 ...
#OCaml
OCaml
  (* Task : General_FizzBuzz *)   (* The FizzBuzz problem, but generalized to have any strings, at any steps, up to any number of iterations. *)   let gen_fizz_buzz (n : int) (l : (int * string) list) : unit = let fold_f i (acc : bool) (k, s) = if i mod k = 0 then (print_string s; true) else acc ...