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/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Ruby
Ruby
open("outfile.dat", "w") do |out_f| open("infile.dat") do |in_f| while record = in_f.read(80) out_f << record.reverse end end end # both files automatically closed  
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Fortran
Fortran
module floyd_warshall_algorithm   use, intrinsic :: ieee_arithmetic   implicit none   integer, parameter :: floating_point_kind = & & ieee_selected_real_kind (6, 37) integer, parameter :: fpk = floating_point_kind   integer, parameter :: nil_vertex = 0   type :: edge integer :: u real(kind ...
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 ...
#PureBasic
PureBasic
Procedure multiply(a,b) ProcedureReturn a*b EndProcedure
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#JavaScript
JavaScript
(() => { 'use strict';   // forwardDifference :: Num a => [a] -> [a] const forwardDifference = xs => zipWith(subtract)(xs)(tail(xs));     // nthForwardDifference :: Num a => [a] -> Int -> [a] const nthForwardDifference = xs => index(iterate(forwardDifference)(xs)).Just;     //---...
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
#X86-64_Assembly
X86-64 Assembly
  option casemap:none if @Platform eq 1 option dllimport:<kernel32> ExitProcess proto :dword option dllimport:none exit equ ExitProcess endif printf proto :qword, :vararg exit proto :dword   .code main proc invoke printf, CSTR("Goodbye, World!",10) invoke exit, 0...
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#OCaml
OCaml
Printf.printf "%09.3f\n" 7.125
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#OpenEdge.2FProgress
OpenEdge/Progress
MESSAGE STRING( 7.125, "99999.999" ) VIEW-AS ALERT-BOX.
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#LabVIEW
LabVIEW
  {def xor {lambda {:a :b} {or {and :a {not :b}} {and :b {not :a}}}}} -> xor   {def halfAdder {lambda {:a :b} {cons {and :a :b} {xor :a :b}}}} -> halfAdder   {def fullAdder {lambda {:a :b :c} {let { {:b :b} {:ha1 {halfAdder :c :a}} } {let { {:ha1 :ha1} {:ha2 {halfAdder {cdr :ha1} :b}}...
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Windows.Forms;   namespace ForestFire { class Program : Form { private static readonly Random rand = new Random(); private Bitmap img;   public Program(int w, int h, int f, int p) ...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#AutoHotkey
AutoHotkey
list := object(1, object(1, 1), 2, 2, 3, object(1, object(1, 3, 2, 4) , 2, 5), 4, object(1, object(1, object(1, object()))), 5 , object(1, object(1, 6)), 6, 7, 7, 8, 9, object()) msgbox % objPrint(list) ; (( 1 ) 2 (( 3 4 ) 5 )(((())))(( 6 )) 7 8 ()) msgbox % objPrint(objFlatten(list)) ; ( 1 2 3 4 5 6 7 8 ) ret...
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#D
D
import std.stdio, std.random, std.ascii, std.string, std.range, std.algorithm, std.conv;   enum N = 3; // Board side. static assert(N <= lowercase.length); enum columnIDs = lowercase[0 .. N]; alias Board = ubyte[N][N];   void flipBits(ref Board board, in size_t count=1) { foreach (immutable _; 0 .. count) ...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#ALGOL_68
ALGOL 68
# find values of p( L, n ) where p( L, n ) is the nth-smallest j such that # # the decimal representation of 2^j starts with the digits of L # BEGIN # returns a string representation of n with commas # PROC commatise = ( LONG INT n )STRING: BEGI...
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Axiom
Axiom
(x,xi,y,yi) := (2.0,0.5,4.0,0.25) (z,zi) := (x+y,1/(x+y)) (numbers,invers) := ([x,y,z],[xi,yi,zi]) multiplier(a:Float,b:Float):(Float->Float) == (m +-> a*b*m) [multiplier(number,inver) 0.5 for number in numbers for inver in invers]  
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#BBC_BASIC
BBC BASIC
REM Create some numeric variables: x = 2 : xi = 1/2 y = 4 : yi = 0.25 z = x + y : zi = 1 / (x + y)   REM Create the collections (here structures are used): DIM c{x, y, z} DIM ci{x, y, z} c.x = x : c.y = y : c.z = z ci.x = xi : ci.y = yi : ci.z = zi   REM Creat...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Fortran
Fortran
... ASSIGN 1101 to WHENCE !Remember my return point. GO TO 1000 !Dive into a "subroutine" 1101 CONTINUE !Resume. ... ASSIGN 1102 to WHENCE !Prepare for another invocation. GO TO 1000 !Like GOSUB in BASIC. 1102 CONTINUE !C...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#FreeBASIC
FreeBASIC
  '$lang: "qb"   Gosub subrutina   bucle: Print "Bucle infinito" Goto bucle End   subrutina: Print "En subrutina" Sleep 100 Return Sleep  
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Raku
Raku
use Lingua::EN::Numbers; # Version 2.4.0 or higher   sub card ($n) { cardinal($n).subst(/','/, '', :g) }   sub magic (Int $int is copy) { my $string; loop { $string ~= "{ card($int) } is "; if $int = ($int == 4) ?? 0 !! card($int).chars { $string ~= "{ card($int) }, " } else { ...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#AutoHotkey
AutoHotkey
Floyds_triangle(row){ i = 0 loop %row% { n := A_Index loop, %n% { m := n, j := i, i++ while (m<row) j += m , m++ res .= spaces(StrLen(j+1)-StrLen(i) +(A_Index=1?0:1)) i } if (A_Index < row) res .= "`r`n" } return res } Spaces(no){ loop, % no res.=" " return % res }
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Rust
Rust
use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, BufWriter};   fn reverse_file( input_filename: &str, output_filename: &str, record_len: usize, ) -> std::io::Result<()> { let mut input = BufReader::new(File::open(input_filename)?); let mut output = BufWriter::new(File::create(out...
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Tcl
Tcl
chan configure stdin -translation binary chan configure stdout -translation binary   set lines [regexp -inline -all {.{80}} [read stdin]] puts -nonewline [join [lmap line $lines {string reverse $line}] ""]   # More "traditional" way   # while {[set line [read stdin 80]] ne ""} { # puts -nonewline [string reverse $lin...
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Wren
Wren
import "io" for File import "/str" for Str   var records = File.read("infile.dat") File.create("outfile.dat") { |f| for (record in Str.chunks(records, 80)) { record = record[-1..0] f.writeBytes(record) } } records = File.read("outfile.dat") for (record in Str.chunks(records, 80)) System.print(re...
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const POSITIVE_INFINITY As Double = 1.0/0.0   Sub printResult(dist(any, any) As Double, nxt(any, any) As Integer) Dim As Integer u, v Print("pair dist path") For i As Integer = 0 To UBound(nxt, 1) For j As Integer = 0 To UBound(nxt, 1) If i <> j Then u = i + 1 ...
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 ...
#Python
Python
def multiply(a, b): return a * b
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 ...
#Q
Q
multiply:{[a;b] a*b}
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#jq
jq
# If n is a non-negative number and if input is # a (possibly empty) array of numbers, # emit an array, even if the input list is too short: def ndiff(n): if n==0 then . elif n == 1 then . as $in | [range(1;length) | $in[.] - $in[.-1]] else ndiff(1) | ndiff(n-1) end;
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Julia
Julia
ndiff(A::Array, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1))   s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] println.(collect(ndiff(s, i) for i in 0:9))
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
#XBasic
XBasic
  PROGRAM "hello" VERSION "0.0003"   DECLARE FUNCTION Entry()   FUNCTION Entry() PRINT "Hello World" END FUNCTION END PROGRAM  
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Oz
Oz
declare fun {PrintFloat X Prec} {Property.put 'print.floatPrecision' Prec} S = {Float.toString X} in {Append for I in 1..Prec-{Length S}+1 collect:C do {C &0} end S} end in {System.showInfo {PrintFloat 7.125 8}}
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#PARI.2FGP
PARI/GP
printf("%09.4f\n", Pi)
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Lambdatalk
Lambdatalk
  {def xor {lambda {:a :b} {or {and :a {not :b}} {and :b {not :a}}}}} -> xor   {def halfAdder {lambda {:a :b} {cons {and :a :b} {xor :a :b}}}} -> halfAdder   {def fullAdder {lambda {:a :b :c} {let { {:b :b} {:ha1 {halfAdder :c :a}} } {let { {:ha1 :ha1} {:ha2 {halfAdder {cdr :ha1} :b}}...
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#11l
11l
F fivenum(array) V n = array.len V x = sorted(array) V n4 = floor((n + 3.0) / 2.0) / 2.0 V d = [1.0, n4, (n + 1) / 2, n + 1 - n4, Float(n)] [Float] sum_array L(e) 5 V fl = Int(floor(d[e] - 1)) V ce = Int(ceil(d[e] - 1)) sum_array.append(0.5 * (x[fl] + x[ce])) R sum_array   V x = [...
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#C.2B.2B
C++
  #include <windows.h> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- enum states { NONE, TREE, FIRE }; const int MAX_SIDE...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#BaCon
BaCon
OPTION COLLAPSE TRUE   lst$ = "\"1\",2,\"\\\"3,4\\\",5\",\"\\\"\\\\\"\\\\\"\\\"\",\"\\\"\\\\\"6\\\\\"\\\"\",7,8,\"\""   PRINT lst$   REPEAT lst$ = FLATTEN$(lst$) UNTIL AMOUNT(lst$, ",") = AMOUNT(FLATTEN$(lst$), ",")   PRINT SORT$(lst$, ",")
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Elixir
Elixir
defmodule Flip_game do @az Enum.map(?a..?z, &List.to_string([&1])) @in2i Enum.concat(Enum.map(1..26, fn i -> {to_string(i), i} end), Enum.with_index(@az) |> Enum.map(fn {c,i} -> {c,-i-1} end)) |> Enum.into(Map.new)   def play(n) when n>2 do target = generate_target(n) display(...
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#FOCAL
FOCAL
01.10 T "FLIP THE BITS"!"-------------"!!;S M=0 01.20 A "SIZE",N;I (N-2)1.2;I (8-N)1.2 01.30 F I=0,N*N-1;D 3.2;S G(I)=A;S B(I)=A 01.35 D 3.3;S L=FITR(A*5)*2+6;F K=0,L;D 3.1;S Z=A;D 3.2;D 4.4 01.40 S A=0;F I=0,N*N-1;S A=A+FABS(G(I)-B(I)) 01.42 T "MOVES",%3,M,!;S M=M+1 01.45 I (0-A)1.5;T !"YOU WIN!"!;Q 01.50 D 2 01.55 A ...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#BASIC256
BASIC256
global FAC FAC = 0.30102999566398119521373889472449302677   print p(12, 1) print p(12, 2) print p(123, 45) print p(123, 12345) print p(123, 678910) end   function p(L, n) cont = 0 : j = 0 LS = string(L) while cont < n j += 1 x = FAC * j if x < length(LS) then continue while y...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#C
C
#include <math.h> #include <stdio.h>   int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val;   test++; val = (int)(factor * pow(10....
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#C.23
C#
using System; using System.Linq;   class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y);   var numlist = new[] { x, y, z }; var numlisti = new[] {...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short   LOOPIT:   Print siCount;; Inc siCount If siCount > 100 Then Quit Goto LoopIt   End
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Go
Go
func main() { inf: goto inf }
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#REXX
REXX
/*REXX pgm converts a # to English into the phrase: a is b, b is c, ... four is magic. */ numeric digits 3003 /*be able to handle gihugic numbers. */ parse arg x /*obtain optional numbers from the C.L.*/ if x='' then x= -164 0 4 6 11 13 75 100 337 92...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#AWK
AWK
#!/bin/awk -f   BEGIN { if (rows !~ /^[0-9]+$/ || rows < 0) { print "invalid rows or missing from command line" print "syntax: awk -v rows=14 -f floyds_triangle.awk" exit 1 }   for (row=cols=1; row<=rows; row++ cols++) { width[row] = length(row + (rows * (rows-1))/2) for (col=1; col<=cols; col++) printf...
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#zkl
zkl
Line 1...1.........2.........3.........4.........5.........6.........7.........8Line 2 Line 3 Line 4 ...
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Go
Go
package main   import ( "fmt" "strconv" )   // A Graph is the interface implemented by graphs that // this algorithm can run on. type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int }   // Nonnegative integer ID of vertex type Vertex int   // ig is a graph of integer...
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 ...
#Quack
Quack
fn multiply[ a; b ] ^ a * b end
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 ...
#Quackery
Quackery
[ * ] is multiply ( n n --> n )
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#K4
K4
fd:1_-':
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Kotlin
Kotlin
// version 1.1.2   fun forwardDifference(ia: IntArray, order: Int): IntArray { if (order < 0) throw IllegalArgumentException("Order must be non-negative") if (order == 0) return ia val size = ia.size if (size == 0) return ia // same empty array if (order >= size) return intArrayOf() // new empty a...
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
#xEec
xEec
  h#10 h$! h$d h$l h$r h$o h$w h#32 h$o h$l h$l h$e h$H >o o$ p jno  
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
#XL
XL
use XL.UI.CONSOLE WriteLn "Hello world!"
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Pascal
Pascal
procedure writeInFixedFormat(n: real); const wholeNumberPlaces = 5; fractionalPlaces = 3; zeroDigit = '0'; negative = '-'; var signPresent: boolean; i: integer; begin // NOTE: This does not catch “negative” zero. signPresent := n < 0.0; if signPresent then begin write(negative); n := abs(n); end;   // d...
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Lua
Lua
-- Build XOR from AND, OR and NOT function xor (a, b) return (a and not b) or (b and not a) end   -- Can make half adder now XOR exists function halfAdder (a, b) return xor(a, b), a and b end   -- Full adder is two half adders with carry outputs OR'd function fullAdder (a, b, cIn) local ha0s, ha0c = halfAdder(cIn, ...
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort;   procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io;   type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4);   procedure Sort is new Ada.Containers.Gener...
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   abstract class Cell() of tree | dirt | burning {} object tree extends Cell() { string => "A"; } object dirt extends Cell() { string => " "; } object burning extends Cell() { string => "#"; }   class Forest(Integer width, Integer height, Float f, Float p) {   value random = D...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#BASIC256
BASIC256
sComma = "": sFlatter = "" sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"   For siCount = 1 To Length(sString) If Instr("[] ,", Mid(sString, siCount, 1)) = 0 Then sFlatter = sFlatter & sComma & Mid(sString, siCount, 1) sComma = ", " End If Next siCount   Print "["; sFlatter; "]" End
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Fortran
Fortran
  !Implemented by Anant Dixit (October 2014) program flipping_bits implicit none character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)" integer :: N, i, j, io, seed(8), moves, input logical, allocatable :: Brd(:,:), Trgt(:,:) logical :: solved double precision :: r   do write(*,*) 'Enter the number of squares (b...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#C.2B.2B
C++
// a mini chrestomathy solution   #include <string> #include <chrono> #include <cmath> #include <locale>   using namespace std; using namespace chrono;   // translated from java example unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10)...
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#C.2B.2B
C++
#include <array> #include <iostream>   int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y );   const std::array values{x, y, z}; const std::array inverses{xi, yi, zi};   auto multiplier = [](double a, double b) { return ...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#GW-BASIC
GW-BASIC
10 LET a=1 20 IF a=2 THEN PRINT "This is a conditional statement" 30 IF a=1 THEN GOTO 50: REM a conditional jump 40 PRINT "This statement will be skipped" 50 PRINT ("Hello" AND (1=2)): REM This does NOT PRINT 100 PRINT "Endless loop" 110 GOTO 100:REM an unconditional jump
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Haskell
Haskell
import Control.Monad import Control.Monad.Trans import Control.Monad.Exit   main = do runExitTMaybe $ do forM_ [1..5] $ \x -> do forM_ [1..5] $ \y -> do lift $ print (x, y) when (x == 3 && y == 2) $ exitWith () putStrLn "Done."
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Ring
Ring
  /* Checking numbers from 0 to 10 */ for c = 0 to 10 See checkmagic(c) + NL next     /* The functions */   Func CheckMagic numb CardinalN = "" Result = "" if isnumber(numb) = false or numb < 0 or numb > 999_999_999_999_999 Return "ERROR: Number entered is incorrect" ok if numb = 4 Result = "Four is magic....
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Ruby
Ruby
module NumberToWord   NUMBERS = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => '...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#BASIC
BASIC
  100 : 110 REM FLOYD'S TRIANGLE 120 : 130 DEF FN Q(A) = INT ( LOG (A) / LOG (10)) + 1 140 N = 14 150 DIM P(N): P(0) = - 1: FOR J = 1 TO N: I = (N * N - N) / 2 + J 160 P(J) = P(J - 1) + FN Q(I) + 1: NEXT J 200 FOR R = 1 TO N: FOR C...
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Groovy
Groovy
class FloydWarshall { static void main(String[] args) { int[][] weights = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] int numVertices = 4   floydWarshall(weights, numVertices) }   static void floydWarshall(int[][] weights, int numVertices) { double[][] dist = ne...
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 ...
#R
R
mult <- function(a,b) a*b
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Lambdatalk
Lambdatalk
  {def fdiff {lambda {:l} {A.new {S.map {{lambda {:l :i} {- {A.get {+ :i 1} :l} {A.get :i :l}} } :l} {S.serie 0 {- {A.length :l} 2}}}}}} -> fdiff   {def disp {lambda {:l} {if {A.empty? {A.rest :l}} then else {let { {:l {fdiff :l}} } {br}:l {disp :l}}}}} -> disp   {def L {A.new 90 47 58 29 22 32...
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
#XLISP
XLISP
(DISPLAY "Hello world!") (NEWLINE)
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Perl
Perl
printf "%09.3f\n", 7.125;
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Phix
Phix
printf(1,"%09.3f\n",7.125)
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#M2000_Interpreter
M2000 Interpreter
  Module FourBitAdder { Flush dim not(0 to 1),and(0 to 1, 0 to 1),or(0 to 1, 0 to 1) not(0)=1,0 and(0,0)=0,0,0,1 or(0,0)=0,1,1,1 xor=lambda not(),and(),or() (a,b)-> or(and(a, not(b)), and(b, not(a))) ha=lambda xor, and() (a,b, &s, &c)->{ s=xor(a,b) c=and(a,b) } fa=lambda ha, or() (a, b, c0, &s, &c1)->{ ...
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#ALGOL_68
ALGOL 68
BEGIN # construct an R-style fivenum function # PR read "rows.incl.a68" PR   PROC fivenum = ( []REAL array )[]REAL: BEGIN INT n = ( UPB array + 1 ) - LWB array; [ 1 : n ]REAL x := array[ AT 1 ]; QUICKSORT x FROMELEMENT LWB x TOELEMENT UPB x; REAL n4 = (...
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#Clojure
Clojure
  (def burn-prob 0.1) (def new-tree-prob 0.5)   (defn grow-new-tree? [] (> new-tree-prob (rand))) (defn burn-tree? [] (> burn-prob (rand))) (defn tree-maker [] (if (grow-new-tree?) :tree :grass))   (defn make-forest ([] (make-forest 5)) ([size] (take size (repeatedly #(take size (repeatedly tree-maker))))))   (de...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#BQN
BQN
Enlist ← {(∾𝕊¨)⍟(1<≡)⥊𝕩}
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() {   rand.Seed(time.Now().UnixNano())   var n int = 3 // Change to define board size var moves int = 0   a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } }   b := make([][]int,...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#C.23
C#
// a mini chrestomathy solution   using System;   class Program {   // translated from java example static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res ...
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Clojure
Clojure
(def x 2.0) (def xi 0.5) (def y 4.0) (def yi 0.25) (def z (+ x y)) (def zi (/ 1.0 (+ x y)))   (def numbers [x y z]) (def invers [xi yi zi])   (defn multiplier [a b] (fn [m] (* a b m)))   > (for [[n i] (zipmap numbers invers)] ((multiplier n i) 0.5)) (0.5 0.5 0.5)
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Common_Lisp
Common Lisp
(defun multiplier (f g) #'(lambda (x) (* f g x)))   (let* ((x 2.0) (xi 0.5) (y 4.0) (yi 0.25) (z (+ x y)) (zi (/ 1.0 (+ x y))) (numbers (list x y z)) (inverses (list xi yi zi))) (loop with value = 0.5 for number in numbers for inverse in inverses ...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#HicEst
HicEst
1 GOTO 2 ! branch to label   2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3   3 ALARM(delay, n) ! n=2...9 simulate F2 to F9 keys: call asynchronously "Alarm"-SUBROUTINES F2...F9 with a delay   4 ALARM( 1 ) ! lets HicEst wait at this statement for any keyboard or mouse event   5 SYSTEM(W...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Icon_and_Unicon
Icon and Unicon
  if x := every i := 1 to *container do { # * is the 'length' operator if container[i] ~== y then write("item ", i, " is not interesting") else break a } then write("found item ", x) else write("did not find an item")  
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Rust
Rust
fn main() { magic(4); magic(2_340); magic(765_000); magic(27_000_001); magic(999_123_090); magic(239_579_832_723_441); magic(std::u64::MAX); }   fn magic(num: u64) { if num == 4 { println!("four is magic!"); println!(); return; } let name = number_name(num...
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Sidef
Sidef
func cardinal(n) { static lingua_en = frequire("Lingua::EN::Numbers") lingua_en.num2en(n) - / and|,/g }   func four_is_magic(n) { var str = "" loop { str += (cardinal(n) + " is ") if (n == 4) { str += "magic." break } else { n = cardinal(n).len ...
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like thi...
#Batch_File
Batch File
:: Floyd's triangle Task from Rosetta Code :: Batch File Implementation   @echo off rem main thing setlocal enabledelayedexpansion call :floydtriangle 5 echo( call :floydtriangle 14 exit /b 0   :floydtriangle set "fila=%1" for /l %%c in (1,1,%fila%) do ( set /a "lastRowNum=%%c+fila*(fila-1)/2" rem count number ...
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#Haskell
Haskell
import Control.Monad (join) import Data.List (union) import Data.Map hiding (foldr, union) import Data.Maybe (fromJust, isJust) import Data.Semigroup import Prelude hiding (lookup, filter)
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 ...
#Racket
Racket
(define (multiply a b) (* a b))
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 ...
#Raku
Raku
sub multiply { return @_[0] * @_[1]; }
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Lasso
Lasso
#!/usr/bin/lasso9   define forwardDiff(values, order::integer=1) => {  !#order ? return #values->asArray local(result = array) iterate(#values) => { loop_count < #values->size ? #result->insert(#values->get(loop_count+1) - #values->get(loop_count)) } #order > 1 ? #result = forwardDiff(#result, #order...
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Logo
Logo
to fwd.diff :l if empty? :l [output []] if empty? bf :l [output []] output fput (first bf :l)-(first :l) fwd.diff bf :l end to nth.fwd.diff :n :l if :n = 0 [output :l] output nth.fwd.diff :n-1 fwd.diff :l end   show nth.fwd.diff 9 [90 47 58 29 22 32 55 5 55 73] [-2921]
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
#XPL0
XPL0
code Text=12; Text(0, "Hello world! ")
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
#XPath
XPath
'Hello world&#xA;'
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#PHP
PHP
echo str_pad(7.125, 9, '0', STR_PAD_LEFT);
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
and[a_, b_] := Max[a, b]; or[a_, b_] := Min[a, b]; not[a_] := 1 - a; xor[a_, b_] := or[and[a, not[b]], and[b, not[a]]]; halfadder[a_, b_] := {xor[a, b], and[a, b]}; fulladder[a_, b_, c0_] := Module[{s, c, c1}, {s, c} = halfadder[c0, a]; {s, c1} = halfadder[s, b]; {s, or[c, c1]}]; fourbitadder[{a3_, a2_, a1_, a...
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#AppleScript
AppleScript
use AppleScript version "2.4" -- Mac OS X 10.10. (Yosemite) or later. use framework "Foundation"   on fivenum(listOfNumbers, l, r) script o property lst : missing value   on medianFromRange(l, r) set m1 to (l + r) div 2 set m2 to m1 + (l + r) mod 2 set median to m...
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. forest-fire.   DATA DIVISION. WORKING-STORAGE SECTION. *> Probability represents a fraction of 10000. *> For instance, IGNITE-PROB means a tree has a 1 in 10000 chance *> of igniting. 78 IGNITE-PROB VALUE 1. ...
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Bracmat
Bracmat
  ( (myList = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ())) & put$("Unevaluated:") & lst$myList & !myList:?myList { the expression !myList evaluates myList } & put$("Flattened:") & lst$myList )  
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Haskell
Haskell
import Data.List (intersperse)   import System.Random (randomRIO)   import Data.Array (Array, (!), (//), array, bounds)   import Control.Monad (zipWithM_, replicateM, foldM, when)   type Board = Array (Char, Char) Int   flp :: Int -> Int flp 0 = 1 flp 1 = 0   numRows, numCols :: Board -> String numRows t = let ((a, _...
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#D
D
import std.math; import std.stdio;   int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val;   test++; val = cast(int)(factor * pow(1...
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#D
D
import std.stdio;   auto multiplier(double a, double b) { return (double c) => a * b * c; }   void main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / (z);   double[3] f = [x, y, z]; double[3] r = [xi, yi, zi];   foreac...
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#E
E
def x := 2.0 def xi := 0.5 def y := 4.0 def yi := 0.25 def z := x + y def zi := 1.0 / (x + y) def forward := [x, y, z ] def reverse := [xi, yi, zi]   def multiplier(a, b) { return fn x { a * b * x } }   def s := 0.5 for i => a in forward { def b := reverse[i] println(`s = $s, a = $a, b = $b, multiplier($a...
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#IDL
IDL
test: ..some code here goto, test
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#J
J
2 * 1 2 3 2 4 6