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_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Python
Python
  import random   board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"]     def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_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.
#Fortran
Fortran
!----------------------------------------------------------------------- ! gjinv - Invert a matrix, Gauss-Jordan algorithm ! A is destroyed. ! !___Name_______Type_______________In/Out____Description_________________ ! A(LDA,N) Real In An N by N matrix ! LDA Integer In ...
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 ...
#Common_Lisp
Common Lisp
  (defun fizzbuzz (limit factor-words) (loop for i from 1 to limit if (assoc-if #'(lambda (factor) (zerop (mod i factor))) factor-words) do (loop for (factor . word) in factor-words when (zerop (mod i factor)) do (princ word) finally (fresh-line)) else do (format t "~a~%" i)))   (...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Ursa
Ursa
import "math"   def hailstone (int n) decl int<> seq while (> n 1) append n seq if (= (mod n 2) 0) set n (floor (/ n 2)) else set n (int (+ (* 3 n) 1)) end if end while append n seq return seq end hailstone
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...
#Bracmat
Bracmat
a:?seq:?c & whl ' ( chr$(asc$!c+1):~>z:?c & !seq !c:?seq ) & !seq
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
#Nyquist
Nyquist
(format t "Hello world!")
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Ursala
Ursala
pmgs("x","y") = ("y","x") # the pattern matching way   ugs = ~&rlX # the idiosyncratic Ursala way   #cast %sWL   test = <pmgs ('a','b'),ugs ('x','y')>
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#V
V
[swap [a b : b a] view].   1 2 swap = 2 1 'hello' 'hi' swap
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...
#FunL
FunL
def powers( m ) = map( (^ m), 0.. )   def filtered( s@sh:_, ch:ct ) | sh > ch = filtered( s, ct ) filtered( sh:st, c@ch:_ ) | sh < ch = sh # filtered( st, c ) filtered( _:st, c ) = filtered( st, c )   println( filtered(powers(2), powers(3)).drop(20).take(10) )
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#TSE_SAL
TSE SAL
    // library: math: get: greatest: common: divisor <description>greatest common divisor whole numbers. Euclid's algorithm. Recursive version</description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmacdi.s) [<Program>] [<Research>] [kn, ri, s...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#TXR
TXR
$ txr -p '(gcd (expt 2 123) (expt 6 49))' 562949953421312
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...
#J
J
row0=: u: 9812+2}.5|i.10 king=: u:9812 rook=: u:9814 bish=: u:9815 pos=: I.@e. bishok=: 1=2+/ .| pos&bish rookok=: pos&rook -: (<./,>./)@pos&(rook,king) ok=: bishok*rookok perm=: A.&i.~ ! valid=: (#~ ok"1) ~.row0{"1~perm 8 gen=: valid {~ ? bind 960
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...
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.List;   public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');   public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().re...
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...
#Aime
Aime
integer f0(void); # No arguments void f1(integer, real); # Two arguments real f2(...); # Varargs void f3(integer, ...); # Varargs   void f4(integer &, text &); # Two arguments (integer and string), pass by reference integer f5(integer, integer (*)(integer)); ...
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...
#ALGOL_68
ALGOL 68
#!/usr/bin/a68g --script # # -*- coding: utf-8 -*- #   # An explanation of any placement restrictions for prototype declarations # PROC VOID no args; # Declare a function with no argument that returns an INTeger # PROC (INT #a#,INT #b#)VOID two args; # Declare a function with two arguments that returns an INTeger # MOD...
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...
#Clojure
Clojure
(defn first-digit [n] (Integer/parseInt (subs (str n) 0 1)))   (defn last-digit [n] (mod n 10))   (defn bookend-number [n] (+ (* 10 (first-digit n)) (last-digit n)))   (defn is-gapful? [n] (and (>= n 100) (zero? (mod n (bookend-number n)))))   (defn gapful-from [n] (filter is-gapful? (iterate inc n)))   (defn gapful []...
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   #define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))   void swap_row(double *a, double *b, int r1, int r2, int n) { double tmp, *p1, *p2; int i;   if (r1 == r2) return; for (i = 0; i < n; i++) { p1 = mat_elem(a, r1, i, n); p2 = mat_elem(a, r2, i, n); ...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#R
R
  place_kings <- function(brd){ ### # Function that puts the two kings on the board # and makes sure that they are not adjacent ### while (TRUE) { # generate positions for white and black kings rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1) rank_black <- sample(1:8, 1) ; file_black ...
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.
#FreeBASIC
FreeBASIC
#include once "matmult.bas" #include once "rowech.bas"   function matinv( A as Matrix ) as Matrix dim ret as Matrix, working as Matrix dim as uinteger i, j if not ubound( A.m, 1 ) = ubound( A.m, 2 ) then return ret dim as integer n = ubound(A.m, 1) redim ret.m( n, n ) working = Matrix( n+1, 2*(n...
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 ...
#Crystal
Crystal
  counter = 0   puts "Enter a maximum number:" limit = gets   puts "Enter the first integer for factoring:" first_int = gets puts "Enter the name of the first integer:" first_int_name = gets   puts "Enter the second integer for factoring:" second_int = gets puts "Enter the name of the second integer:" second_int_name =...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Ursala
Ursala
#import std #import nat   hail = @iNC ~&h~=1->x ^C\~& @h ~&h?\~&t successor+ sum@iNiCX   #show+   main =   < ^T(@ixX take/$4; %nLP~~lrxPX; ^|TL/~& :/'...',' has length '--@h+ %nP+ length) hail 27, ^|TL(~&,:/' has sequence length ') %nP~~ nleq$^&r ^(~&,length+ hail)* nrange/1 100000>
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...
#Brainf.2A.2A.2A
Brainf***
Make room for 26 characters >>>>>>>>>>>>> >>>>>>>>>>>>> Set counter to 26 >> +++++++++++++ +++++++++++++ Generate the numbers 1 to 26 [-<< Decrement counter [+<] Add one to each nonzero cell moving right to left + Add one to first zero cell encountered [>]> Return head to counter ] << Add 96 to each cell...
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
#Oberon-2
Oberon-2
  MODULE Goodbye; IMPORT Out; PROCEDURE World*; BEGIN Out.String("Hello world!");Out.Ln END World; BEGIN World; END Goodbye.  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#VBScript
VBScript
sub swap( byref x, byref y ) dim temp temp = x x = y y = temp end sub
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Verbexx
Verbexx
// user-defined swap verb -- parms are passed by alias, not value, so they can be updated:   '<==> [_a] @FN [_b] { _a _b = _b _a } by_alias: ;     // test out swap verb   @VAR a = 12345; @VAR b = "*****";   @SAY "a=" a " b=" b;   \b <==> \a; // "\" verb prevents evaluation of a and b here, ...
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...
#Go
Go
package main   import ( "fmt" "math" )   // note: exponent not limited to ints func newPowGen(e float64) func() float64 { var i float64 return func() (r float64) { r = math.Pow(i, e) i++ return } }   // given two functions af, bf, both monotonically increasing, return a // ne...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#TypeScript
TypeScript
function gcd(a: number, b: number) { a = Math.abs(a); b = Math.abs(b);   if (b > a) { let temp = a; a = b; b = temp; }   while (true) { a %= b; if (a === 0) { return b; } b %= a; if (b === 0) { return a; } } }
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...
#JavaScript
JavaScript
function ch960startPos() { var rank = new Array(8), // randomizer (our die) d = function(num) { return Math.floor(Math.random() * ++num) }, emptySquares = function() { var arr = []; for (var i = 0; i < 8; i++) if (rank[i] == undefined) arr.push(i); return arr; }; // p...
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...
#Amazing_Hopper
Amazing Hopper
  #!/usr/bin/hopper   // Archivo Hopper #include <hopper.h>   #context-free noargs /* Declare a pseudo-function with no argument */ #synon noargs no arguments #context multiargs /* Declare a pseudo-function with multi arguments */ #proto twoargs(_X_,_Y_) /* Declare a pseudo-function w...
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...
#C
C
int noargs(void); /* Declare a function with no argument that returns an integer */ int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */ int twoargs(int ,int); /* Parameter names are optional in a prototype definition */ int anyargs(); /* An empty parameter list can be used to d...
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...
#C.23
C#
using System; abstract class Printer { public abstract void Print(); }   class PrinterImpl : Printer { public override void Print() { Console.WriteLine("Hello world!"); } }
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...
#11l
11l
V _a = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.000020...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. GAPFUL.   DATA DIVISION. WORKING-STORAGE SECTION. 01 COMPUTATION. 02 N PIC 9(10). 02 N-DIGITS REDEFINES N. 03 ND PIC 9 OCCURS 10 TIMES. 02 DIV-CHECK PIC 9(10)V9(2). ...
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
#C.23
C#
  using System;   namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows;   internal Vector(int rows) { this.rows = rows; b = new double[rows]; }   internal Vector(double[] initArray) { ...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Raku
Raku
sub pick-FEN { # First we chose how many pieces to place my $n = (2..32).pick;   # Then we pick $n squares my @n = (^64).pick($n);   # We try to find suitable king positions on non-adjacent squares. # If we could not find any, we return recursively return pick-FEN() unless my @kings[2] =...
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.
#Generic
Generic
  // The Generic Language is a database compiler. This code is compiled into database then executed out of database.   generic coordinaat { ecs; uuii;   coordinaat() { ecs=+a;uuii=+a;}   coordinaat(ecs_set,uuii_set) { ecs = ecs_set; uuii=uuii_set;}   operaator<(c) { iph ecs < c.ecs return troo; iph c.ecs < ...
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 ...
#D
D
import core.stdc.stdlib; import std.stdio;   void main() { int limit; write("Max number (>0): "); readf!"%d\n"(limit); if (limit <= 0) { writeln("The max number to consider must be greater than zero."); exit(1); }   int terms; write("Terms (>0): "); readf!"%d\n"(terms); ...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#VBA
VBA
Private Function hailstone(ByVal n As Long) As Collection Dim s As New Collection s.Add CStr(n), CStr(n) i = 0 Do While n <> 1 If n Mod 2 = 0 Then n = n / 2 Else n = 3 * n + 1 End If s.Add CStr(n), CStr(n) Loop Set hailstone = s End Functio...
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...
#Burlesque
Burlesque
blsq ) @azr\sh abcdefghijklmnopqrstuvwxyz
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...
#C
C
#include <stdlib.h>   #define N 26   int main() { unsigned char lower[N];   for (size_t i = 0; i < N; i++) { lower[i] = i + 'a'; }   return EXIT_SUCCESS; }  
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
#Objeck
Objeck
  class Hello { function : Main(args : String[]) ~ Nil { "Hello world!"->PrintLine(); } }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Visual_Basic
Visual Basic
Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim temp = a a = b b = temp End Sub
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...
#Haskell
Haskell
import Data.List.Ordered   powers :: Int -> [Int] powers m = map (^ m) [0..]   squares :: [Int] squares = powers 2   cubes :: [Int] cubes = powers 3   foo :: [Int] foo = filter (not . has cubes) squares   main :: IO () main = print $ take 10 $ drop 20 foo
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#uBasic.2F4tH
uBasic/4tH
Print "GCD of 18 : 12 = "; FUNC(_GCD_Iterative_Euclid(18,12)) Print "GCD of 1071 : 1029 = "; FUNC(_GCD_Iterative_Euclid(1071,1029)) Print "GCD of 3528 : 3780 = "; FUNC(_GCD_Iterative_Euclid(3528,3780))   End   _GCD_Iterative_Euclid Param(2) Local (1) Do While b@ c@ = a@ a@ = b@ b@ = c@ % b@ Loop Retur...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#UNIX_Shell
UNIX Shell
gcd() { # Calculate $1 % $2 until $2 becomes zero. until test 0 -eq "$2"; do # Parallel assignment: set -- 1 2 set -- "$2" "`expr "$1" % "$2"`" done   # Echo absolute value of $1. test 0 -gt "$1" && set -- "`expr 0 - "$1"`" echo "$1" }   gcd -47376 87843 # => 987
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...
#Julia
Julia
function generateposition() # Placeholder knights rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] lrank = length(rank)   # Check if a space is available isfree(x::Int) = rank[x] == '♘'   # Place the King rank[indking = rand(2:lrank-1)] = '♔'   # Place rooks rank[indrook = rand(filter...
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...
#Kotlin
Kotlin
object Chess960 : Iterable<String> { override fun iterator() = patterns.iterator()   private operator fun invoke(b: String, e: String) { if (e.length <= 1) { val s = b + e if (s.is_valid()) patterns += s } else { for (i in 0 until e.length) { i...
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...
#C.2B.2B
C++
int noargs(); // Declare a function with no arguments that returns an integer int twoargs(int a,int b); // Declare a function with two arguments that returns an integer int twoargs(int ,int); // Parameter names are optional in a prototype definition int anyargs(...); // An ellipsis is used to declare a function that ac...
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...
#Clojure
Clojure
(declare foo)
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...
#360_Assembly
360 Assembly
GAMMAT CSECT USING GAMMAT,R13 SAVEAR B STM-SAVEAR(R15) DC 17F'0' DC CL8'GAMMAT' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 * ---- CODE LE F4,=E'0' LH R2,NI LOOPI EQU * AE...
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 ...
#AutoHotkey
AutoHotkey
AutoTrim Off ; User settings bottompegs := 6 SleepTime := 200 fallspace := 30   ; create the board out := (pad2 := Space(bottompegs*2+1)) "`n" Loop % bottompegs { out .= Space(bottompegs-A_Index+1) Loop % A_Index out .= "* " out .= Space(bottompegs-A_Index+1) . "`n" } StringTrimRight, strboard, out, 1 ; remove ...
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...
#Commodore_BASIC
Commodore BASIC
100 DEF FNFD(N) = VAL(MID$(STR$(N),2,1)) 110 DEF FNLD(N) = N - 10 * INT(N/10) 120 DEF FNBE(N) = 10 * FNFD(N) + FNLD(N) 130 DEF FNGF(N) = (N >= 100) AND (N - FNBE(N)*INT(N/FNBE(N)) = 0) 140 READ S:IF S<0 THEN 260 150 READ C 160 PRINT"THE FIRST"C"GAPFUL NUMBERS >="S":" 170 I=S:F=0 180 IF NOT FNGF(I) THEN 220 190 PRINT I,...
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
#C.2B.2B
C++
#include <algorithm> #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <vector>   template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {}   matrix(size_t rows, size_t colum...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#REXX
REXX
/*REXX program generates a chess position (random pieces & positions) in a FEN format.*/ parse arg seed CBs . /*obtain optional arguments from the CL*/ if datatype(seed,'W') then call random ,,seed /*SEED given for RANDOM repeatability? */ if CBs=='' | CBs=="," then CBs=1 ...
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.
#Go
Go
package main   import "fmt"   type vector = []float64 type matrix []vector   func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(ve...
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 ...
#Elixir
Elixir
defmodule General do def fizzbuzz(input) do [num | nwords] = String.split(input) max = String.to_integer(num) dict = Enum.chunk(nwords, 2) |> Enum.map(fn[n,word] -> {String.to_integer(n),word} end) Enum.each(1..max, fn i -> str = Enum.map_join(dict, fn {n,word} -> if rem(i,n)==0, do: word end) ...
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 ...
#Erlang
Erlang
  %%% @doc Implementation of General FizzBuzz %%% @see https://rosettacode.org/wiki/General_FizzBuzz -module(general_fizzbuzz). -export([run/2]). -spec run(N :: pos_integer(), Factors :: list(tuple())) -> ok.   fizzbuzz(N, [], []) -> integer_to_list(N); fizzbuzz(_, [], Result) -> lists:flatten(lists:reverse(Res...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#VBScript
VBScript
  'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or '"e" for the number elements. Function hailstone_sequence(num,return) n = num sequence = num elements = 1 Do Until n = 1 If n Mod 2 = 0 Then n = n / 2 Else n = (3 * n) + 1 End If se...
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...
#C.23
C#
using System; using System.Linq;   internal class Program { private static void Main() { Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c))); } }
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
#Objective-C
Objective-C
  #import <Foundation/Foundation.h>   int main() { @autoreleasepool { NSLog(@"Hello, World!"); } }  
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Visual_Basic_.NET
Visual Basic .NET
Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim temp = a a = b b = temp End Sub
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Visual_FoxPro
Visual FoxPro
Since Visual FoxPro is not strongly typed, this will work with any data types.
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...
#Icon_and_Unicon
Icon and Unicon
procedure main()   write("Non-cube Squares (21st to 30th):") every (k := 0, s := noncubesquares()) do if(k +:= 1) > 30 then break else write(20 < k," : ",s) end   procedure mthpower(m) #: generate i^m for i = 0,1,... while (/i := 0) | (i +:= 1) do suspend i^m end   procedure noncubesquares() #: filter for ...
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Ursa
Ursa
import "math" out (gcd 40902 24140) endl console
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Ursala
Ursala
#import nat   gcd = ~&B?\~&Y ~&alh^?\~&arh2faltPrXPRNfabt2RCQ @a ~&ar^?\~&al ^|R/~& ^/~&r remainder
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...
#Lua
Lua
-- Insert 'str' into 't' at a random position from 'left' to 'right' function randomInsert (t, str, left, right) local pos repeat pos = math.random(left, right) until not t[pos] t[pos] = str return pos end   -- Generate a random Chess960 start position for white major pieces function chess960 () loc...
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...
#COBOL
COBOL
*> A subprogram taking no arguments and returning nothing. PROGRAM-ID. no-args PROTOTYPE. END PROGRAM no-args.   *> A subprogram taking two 8-digit numbers as arguments, and returning *> an 8-digit number. PROGRAM-ID. two-args PROTOTYPE. DATA DIVISION. LINKAGE SEC...
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...
#Go
Go
package main   import "fmt"   type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode }   func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} }   func (n *FCNode) addChildren(nodes []*FCN...
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...
#Ada
Ada
function Gamma (X : Long_Float) return Long_Float is A : constant array (0..29) of Long_Float := ( 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...
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 ...
#BASIC256
BASIC256
graphsize 150,125 fastgraphics color black rect 0,0,graphwidth,graphheight refresh   N = 10 # number of balls M = 5 # number of pins in last row dim ball(N,5) # (pos_x to center, level, x, y, direction} dim cnt(M+1)   rad = 6 slow = 0.3 diamond = {0,rad,rad,0,0,-rad,-rad,0} stepx = {rad/sqr(2),rad/2,rad/2,(1-1/sqr(2)...
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 ...
#BBC_BASIC
BBC BASIC
maxBalls% = 10 DIM ballX%(maxBalls%), ballY%(maxBalls%)   VDU 23,22,180;400;8,16,16,128 ORIGIN 180,0 OFF   REM Draw the pins: GCOL 9 FOR row% = 1 TO 7 FOR col% = 1 TO row% CIRCLE FILL 40*col% - 20*row% - 20, 800 - 40*row%, 12 NEXT NEXT row%...
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...
#Common_Lisp
Common Lisp
(defun first-digit (n) (parse-integer (string (char (write-to-string n) 0))))   (defun last-digit (n) (mod n 10))   (defun bookend-number (n) (+ (* 10 (first-digit n)) (last-digit n)))   (defun gapfulp (n) (and (>= n 100) (zerop (mod n (bookend-number n)))))   (defun gapfuls-in-range (start size) (loop for n from sta...
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
#Common_Lisp
Common Lisp
  (defmacro mapcar-1 (fn n list) "Maps a function of two parameters where the first one is fixed, over a list" `(mapcar #'(lambda (l) (funcall ,fn ,n l)) ,list) )     (defun gauss (m) (labels ((redc (m) ; Reduce to triangular form (if (null (cdr m)) m (cons (car m) (mapcar-1 #'cons 0 (...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Ruby
Ruby
  def hasNK( board, a, b ) for g in -1 .. 1 for f in -1 .. 1 aa = a + f; bb = b + g if aa.between?( 0, 7 ) && bb.between?( 0, 7 ) p = board[aa + 8 * bb] if p == "K" || p == "k"; return true; end end end end return false end...
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.
#Haskell
Haskell
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs   isSquareMatrix xs = null xs || all ((== (length xs)).length) xs   mult:: Num a => [[a]] -> [[a]] -> [[a]] mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss   matI::(Num a) => Int -> [[a...
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 ...
#Factor
Factor
USING: assocs combinators.extras io kernel math math.parser math.ranges prettyprint sequences splitting ; IN: rosetta-code.general-fizzbuzz   : prompt ( -- str ) ">" write readln ;   : get-factor ( -- seq ) prompt " " split first2 [ string>number ] dip { } 2sequence ;   : get-input ( -- assoc n ) prompt str...
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 ...
#Forth
Forth
\ gfb.fs - generalized fizz buzz : times ( xt n -- ) BEGIN dup WHILE 1- over swap 2>r execute 2r> REPEAT 2drop ; \ 'Domain Specific Language' compiling words \ -- First comment: stack-effect at compile-time \ -- Second comment: stack efect of compiled sequence : ]+[ ( u ca u -- ) ( u f -- u f' ) 2>r >r ] ]]...
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Visual_Basic
Visual Basic
Option Explicit Dim flag As Boolean ' true to print values Sub main() Dim longest As Long, n As Long Dim i As Long, value As Long ' Task 1: flag = True i = 27 Debug.Print "The hailstone sequence has length of "; i; " is "; hailstones(i) ' Task 2: flag = False longest = 0 For i = ...
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...
#C.2B.2B
C++
#include <string> #include <numeric>   int main() { std::string lower(26,' ');   std::iota(lower.begin(), lower.end(), 'a'); }
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...
#Clojure
Clojure
(map char (range (int \a) (inc (int \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
#OCaml
OCaml
print_endline "Hello world!"
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Wart
Wart
(swap! x y)
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Wren
Wren
var swap = Fn.new { |l| var t = l[0] l[0] = l[1] l[1] = t }   var a = 6 var b = 3 var c = [a, b] swap.call(c) // pass a list instead of individual variables a = c[0] // unpack b = c[1] // ditto System.print("a is now %(a)") System.print("b is now %(b)") System.print()   // all user defined classes are refer...
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...
#J
J
coclass 'mthPower' N=: 0 create=: 3 :0 M=: y ) next=: 3 :0 n=. N N=: N+1 n^M )
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#V
V
[gcd [0 >] [dup rollup %] while pop ].
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#VBA
VBA
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print[StringJoin[ RandomChoice[ Select[Union[ Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]", "\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]", "\[WhiteKnight]", "\[WhiteKnight]"}]], MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, "\[WhiteRook]",...
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...
#MiniScript
MiniScript
// placeholder knights rank = ["♘"] * 8   // function to get a random free space from a to b, inclusive randFree = function(a, b) free = [] for i in range(a, b) if rank[i] == "♘" then free.push i end for return free[rnd * free.len] end function   // place the king kingIdx = randFree(1, 6) rank[k...
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...
#Common_Lisp
Common Lisp
  (declaim (inline no-args)) (declaim (inline one-arg)) (declaim (inline two-args)) (declaim (inline optional-args))   (defun no-args () (format nil "no arguments!"))   (defun one-arg (x) ; inserts the value of x into a string (format nil "~a" x))   (defun two-args (x y) ; same as function `one-arg', but with ...
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...
#D
D
/// Declare a function with no arguments that returns an integer. int noArgs();   /// Declare a function with no arguments that returns an integer. int twoArgs(int a, int b);   /// Parameter names are optional in a prototype definition. int twoArgs2(int, int);   /// An ellipsis can be used to declare a function that ac...
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...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.Bifunctor (first) import Data.Bool (bool) import Data.Char (isSpace) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Read as T import Data.Tree (Forest, Tree (..), foldTree) import Numeric (showFFloat) import System.Directory...
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...
#ACL2
ACL2
(in-package "ACL2")   (set-state-ok t)   (defun read-all-objects (limit channel state) (mv-let (eof obj state) (read-object channel state) (if (or eof (zp limit)) (mv nil state) (mv-let (so-far state) (read-all-objects (- limit 1) channel state) (mv...
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...
#ALGOL_68
ALGOL 68
# Coefficients used by the GNU Scientific Library # []LONG REAL p = ( LONG 0.99999 99999 99809 93, LONG 676.52036 81218 851, -LONG 1259.13921 67224 028, LONG 771.32342 87776 5313, -LONG 176.61502 91621 4059, LONG 1...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b;   #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }   void show_board() { int i, j; for (puts(...
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...
#Crystal
Crystal
struct Int def gapful? a = self.to_s.chars.map(&.to_i) self % (a.first*10 + a.last) == 0 end end   specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}   specs.each do |start, count| puts "first #{count} gapful numbers >= #{start}:" puts (start..).each.select(&.gapful?).first(count).to_...
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
#D
D
import std.stdio, std.math, std.algorithm, std.range, std.numeric, std.typecons;   Tuple!(double[],"x", string,"err") gaussPartial(in double[][] a0, in double[] b0) pure /*nothrow*/ in { assert(a0.length == a0[0].length); assert(a0.length == b0.length); assert(a0.all!(row => row.length == a0[0].lengt...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Rust
Rust
use std::fmt::Write;   use rand::{Rng, distributions::{Distribution, Standard}};   const EMPTY: u8 = b'.';   #[derive(Clone, Debug)] struct Board { grid: [[u8; 8]; 8], }   impl Distribution<Board> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Board { let mut board = Board::empty(); ...
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Scala
Scala
import scala.math.abs import scala.util.Random   object RandomFen extends App { val rand = new Random   private def createFen = { val grid = Array.ofDim[Char](8, 8)   def placeKings(grid: Array[Array[Char]]): Unit = { var r1, c1, r2, c2 = 0 do { r1 = rand.nextInt(8) c1 = rand.nex...
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.
#J
J
require 'math/misc/linear' augmentR_I1=: ,. e.@i.@# NB. augment matrix on the right with its Identity matrix matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1
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 ...
#FreeBASIC
FreeBASIC
' version 01-03-2018 ' compile with: fbc -s console   Dim As UInteger f(), factor, c, i, n Dim As Integer max Dim As String w(), word Dim As boolean flag   Do Input "Enter maximum number, if number < 1 then the program wil end ", max If max < 1 Then Exit Do   Print While c = 0 Or c > max Input "...