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/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 ...
#Ruby
Ruby
def 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 ...
#Rust
Rust
fn multiply(a: i32, b: i32) -> i32 { 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...
#Nial
Nial
fd is - [rest, front]
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...
#Nim
Nim
proc dif(s: seq[int]): seq[int] = result = newSeq[int](s.len-1) for i in 0..<s.high: result[i] = s[i+1] - s[i]   proc difn(s: seq[int]; n: int): seq[int] = if n > 0: difn(dif(s), n-1) else: s   const s = @[90, 47, 58, 29, 22, 32, 55, 5, 55, 73] echo difn(s, 0) echo difn(s, 1) echo difn(s, 2)
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
#Zoea
Zoea
program: hello_world output: "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
#Zoea_Visual
Zoea Visual
print "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.
#Raku
Raku
say 7.125.fmt('%09.3f');
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.
#Raven
Raven
7.125 "%09.3f" print   00007.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 ...
#OCaml
OCaml
  (* File blocks.ml   A block is just a black box with nin input lines and nout output lines, numbered from 0 to nin-1 and 0 to nout-1 respectively. It will be stored in a caml record, with the operation stored as a function. A value on a line is represented by a boolean value. *)   type block = { nin:int; nout:int; ap...
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...
#D
D
import std.algorithm; import std.exception; import std.math; import std.stdio;   double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; }   double[] fivenum(double[] x) { ...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#360_Assembly
360 Assembly
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: :...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Action.21
Action!
;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752 BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4] BYTE res   IF m<3 THEN y==-1 FI res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7 RETURN (res)   PROC Main() BYTE ARRAY m31=[1 3 5 7 ...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar;   use Ada.Calendar.Formatting;   procedure Five_Weekends is Months : Natural := 0; begin for Year in Year_Number range 1901..2100 loop for Month in Month_Number range 1..12 loop begin if D...
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#C
C
#include <stdio.h> #include <string.h>   #define BUFF_SIZE 32   void toBaseN(char buffer[], long long num, int base) { char *ptr = buffer; char *tmp;   // write it backwards while (num >= 1) { int rem = num % base; num /= base;   *ptr++ = "0123456789ABCDEF"[rem]; } *ptr--...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#AppleScript
AppleScript
-- Compose two functions, where each function is -- a script object with a call(x) handler. on compose(f, g) script on call(x) f's call(g's call(x)) end call end script end compose   script increment on call(n) n + 1 end call end script   script decrement on call(...
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...
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/env emacs -script ;; -*- lexical-binding: t -*- ;; run: ./forest-fire forest-fire.config (require 'cl-lib) ;; (setq debug-on-error t)   (defmacro swap (a b) `(setq ,b (prog1 ,a (setq ,a ,b))))   (defconst burning ?B) (defconst tree ?t)   (cl-defstruct world rows cols data)   (defun new-world (rows cols) ...
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Factor
Factor
USING: assocs continuations formatting io kernel math math.ranges sequences ;   : (next-hailstone) ( count value -- count' value' ) [ 1 + ] [ dup even? [ 2/ ] [ 3 * 1 + ] if ] bi* ;   : next-hailstone ( count value -- count' value' ) dup 1 = [ (next-hailstone) ] unless ;   : make-environments ( -- seq ) 12 [ 0 ...
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Go
Go
package main   import "fmt"   const jobs = 12   type environment struct{ seq, cnt int }   var ( env [jobs]environment seq, cnt *int )   func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq ...
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
#C.2B.2B
C++
#include <list> #include <boost/any.hpp>   typedef std::list<boost::any> anylist;   void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator;   iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ...
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 ...
#Kotlin
Kotlin
// version 1.1.3   import java.util.Random   val rand = Random() val target = Array(3) { IntArray(3) { rand.nextInt(2) } } val board = Array(3) { IntArray(3) }   fun flipRow(r: Int) { for (c in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0 }   fun flipCol(c: Int) { for (r in 0..2) board[r][c] = if (board[...
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 ...
#Haskell
Haskell
import Control.Monad (guard) import Text.Printf (printf)   p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFract...
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...
#Icon_and_Unicon
Icon and Unicon
import Utils   procedure main(A) mult := multiplier(get(A),get(A)) # first 2 args define function every write(mult(!A)) # remaining are passed to new function end   procedure multiplier(n1,n2) return makeProc { repeat inVal := n1 * n2 * (inVal@&source)[1] } end
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...
#J
J
x =: 2.0 xi =: 0.5 y =: 4.0 yi =: 0.25 z =: x + y zi =: 1.0 % (x + y) NB. / is spelled % in J   fwd =: x ,y ,z rev =: xi,yi,zi   multiplier =: 2 : 'm * n * ]'
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...
#Maxima
Maxima
/* goto */ block(..., label, ..., go(label), ...);   /* throw, which is like trapping errors, and can do non-local jumps to return a value */ catch(..., throw(value), ...);   /* error trapping */ errcatch(..., error("Bad luck!"), ...);
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...
#MUMPS
MUMPS
GOTO LABEL^ROUTINE
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...
#CLU
CLU
floyd = cluster is triangle rep = null   width = proc (n: int) returns (int) w: int := 1 while n >= 10 do w := w + 1 n := n / 10 end return (w) end width   triangle = proc (rows: int) returns (string) ss: stream := stream$create_output(...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. FLOYD-TRIANGLE.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES COMP. 02 NUM-LINES PIC 99. 02 CUR-LINE PIC 99. 02 CUR-COL PIC 99. 02 CUR-NUM PIC 999. 02 ...
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 ...
#Julia
Julia
# Floyd-Warshall algorithm: https://rosettacode.org/wiki/Floyd-Warshall_algorithm # v0.6   function floydwarshall(weights::Matrix, nvert::Int) dist = fill(Inf, nvert, nvert) for i in 1:size(weights, 1) dist[weights[i, 1], weights[i, 2]] = weights[i, 3] end # return dist next = collect(j != i...
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 ...
#S-BASIC
S-BASIC
  function multiply(a, b = real) = real end = 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 ...
#Sather
Sather
class MAIN is -- we cannot have "functions" (methods) outside classes mult(a, b:FLT):FLT is return a*b; end;   main is #OUT + mult(5.2, 3.4) + "\n"; end; 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...
#Objeck
Objeck
  bundle Default { class Test { function : Main(args : String[]) ~ Nil { a := [90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0]; Print(Diff(a, 1)); Print(Diff(a, 2)); Print(Diff(a, 9)); }   function : Print(a : Float[]) ~ Nil { if(a <> Nil) { '['->Print(); ...
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Zoomscript
Zoomscript
print "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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT "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.
#REBOL
REBOL
rebol [ Title: "Formatted Numeric Output" URL: http://rosettacode.org/wiki/Formatted_Numeric_Output ]   ; REBOL has no built-in facilities for printing pictured output. ; However, it's not too hard to cook something up using the ; string manipulation facilities.   zeropad: func [ "Pad number with zeros or spaces. ...
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.
#REXX
REXX
/*REXX program shows various ways to add leading zeroes to numbers. */ a=7.125 b=translate(format(a,10),0,' ') say 'a=' a say 'b=' b say   c=8.37 d=right(c,20,0) say 'c=' c say 'd=' d say   e=19.46 f='000000'e say 'e=' e say 'f=' f say   g=18.25e+1 h=000000||g say 'g=' g say 'h=' h say   i=45.2 j=translate(' '...
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 ...
#PARI.2FGP
PARI/GP
xor(a,b)=(!a&b)||(a&!b); halfadd(a,b)=[a&&b,xor(a,b)]; fulladd(a,b,c)=my(t=halfadd(a,c),s=halfadd(t[2],b));[t[1]||s[1],s[2]]; add4(a3,a2,a1,a0,b3,b2,b1,b0)={ my(s0,s1,s2,s3); s0=fulladd(a0,b0,0); s1=fulladd(a1,b1,s0[1]); s2=fulladd(a2,b2,s1[1]); s3=fulladd(a3,b3,s2[1]); [s3[1],s3[2],s2[2],s1[2],s0[2]] }; add4(0,0...
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...
#Delphi
Delphi
  program Fivenum;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#11l
11l
V perms = [‘ABCD’, ‘CABD’, ‘ACDB’, ‘DACB’, ‘BCDA’, ‘ACBD’, ‘ADCB’, ‘CDAB’, ‘DABC’, ‘BCAD’, ‘CADB’, ‘CDBA’, ‘CBAD’, ‘ABDC’, ‘ADBC’, ‘BDCA’, ‘DCBA’, ‘BACD’, ‘BADC’, ‘BDAC’, ‘CBDA’, ‘DBCA’, ‘DCAB’]   V missing = ‘’ L(i) 4 V cnt = [0] * 4 L(j) 0 .< perms.len cnt[perms[j][i].code - ‘A’.code...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#11l
11l
F last_sundays(year) [String] sundays L(month) 1..12 V last_day_of_month = I month < 12 {Time(year, month + 1)} E Time(year + 1) L last_day_of_month -= TimeDelta(days' 1) I last_day_of_month.strftime(‘%w’) == ‘0’ sundays [+]= year‘-’(‘#02’.format(month))‘-’last_day_of_mon...
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#11l
11l
F line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2) V d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) I d == 0 R (Float.infinity, Float.infinity)   V uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d V uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d   ...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#6502_Assembly
6502 Assembly
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: :...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#ALGOL_68
ALGOL 68
five_weekends: BEGIN INT m, year, nfives := 0, not5 := 0; BOOL no5weekend;   MODE MONTH = STRUCT( INT n, [3]CHAR name ) # MODE MONTH #;   []MONTH month = ( MONTH(13, "Jan"), MONTH(3, "Mar"), MONTH(5, "May"), MONTH(7, "Jul"), MONTH(8, "Aug"), MONTH(10, "Oct"), MONTH(12, ...
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#C.23
C#
using System; using System.Collections.Generic; using System.Numerics;   static class Program { static byte Base, bmo, blim, ic; static DateTime st0; static BigInteger bllim, threshold; static HashSet<byte> hs = new HashSet<byte>(), o = new HashSet<byte>(); static string chars = "0123456789ABCDEFGHIJKLMNOPQ...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Arturo
Arturo
cube: function [x] -> x^3 croot: function [x] -> x^(1//3)   names: ["sin/asin", "cos/acos", "cube/croot"] funclist: @[var 'sin, var 'cos, var 'cube] invlist: @[var 'asin, var 'acos, var 'croot]   num: 0.5   loop 0..2 'f [ result: call funclist\[f] @[num] print [names\[f] "=>" call invlist\[f] @[result]] ]
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#AutoHotkey
AutoHotkey
#NoEnv ; Set the floating-point precision SetFormat, Float, 0.15 ; Super-global variables for function objects Global F, G ; User-defined functions Cube(X) { Return X ** 3 } CubeRoot(X) { Return X ** (1/3) } ; Function arrays, Sin/ASin and Cos/ACos are built-in FuncArray1 := [Func("Sin"), Func("Cos"), Func("Cub...
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...
#Erlang
Erlang
  -module( forest_fire ).   -export( [task/0] ).   -record( state, {neighbours=[], position, probability_burn, probability_grow, tree} ).   task() -> erlang:spawn( fun() -> Pid_positions = forest_create( 5, 5, 0.5, 0.3, 0.2 ), Pids = [X || {X, _} <- Pid_positions], [X ! {tr...
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Haskell
Haskell
hailstone n | n == 1 = 1 | even n = n `div` 2 | odd n = 3*n + 1
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() every put(environment := [], hailenv(1 to 12,0)) # setup environments printf("Sequences:\n") while (e := !environment).sequence > 1 do { every hailstep(!environment) printf("\n") } printf("\nCounts:\n") every printf("%4d ",(!environment).count) prin...
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
#Ceylon
Ceylon
shared void run() { "Lazily flatten nested streams" {Anything*} flatten({Anything*} stream) => stream.flatMap((element) => switch (element) case (is {Anything*}) flatten(element) else [element]);   value list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8,...
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 ...
#Lua
Lua
  target, board, moves, W, H = {}, {}, 0, 3, 3   function getIndex( i, j ) return i + j * W - W end   function flip( d, r ) function invert( a ) if a == 1 then return 0 end return 1 end local idx if d == 1 then for i = 1, W do idx = getIndex( i, r ) board[idx] = invert( board...
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 ...
#J
J
  p=: adverb define : el =. x en =. y pwr =. m el =. <. | el digitcount =. <. 10 ^. el log10pwr =. 10 ^. pwr 'raised found' =. _1 0 while. found < en do. raised =. >: raised firstdigits =. (<.!.0) 10^digitcount + 1 | log10pwr * raised found =. found + firstdigits = el end. raised )  
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 ...
#Java
Java
  public class FirstPowerOfTwo {   public static void main(String[] args) { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); }   private static void runTest(int l, int n) { System.out.printf("p(%d, %d) = %,d%n", l, n...
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...
#jq
jq
# Infrastructure: # zip this and that def zip(that): . as $this | reduce range(0;length) as $i ([]; . + [ [$this[$i], that[$i]] ]);   # The task: 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 numlist: [x,y,z];   def invlist: [xi, yi, zi];   # Input: [x,y] def multipl...
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...
#JavaScript
JavaScript
const x = 2.0; const xi = 0.5; const y = 4.0; const yi = 0.25; const z = x + y; const zi = 1.0 / (x + y); const pairs = [[x, xi], [y, yi], [z, zi]]; const testVal = 0.5;   const multiplier = (a, b) => m => a * b * m;   const test = () => { return pairs.map(([a, b]) => { const f = multiplier(a, b); const resul...
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...
#Nemerle
Nemerle
loop xx = 1 to 10 if xx = 1 then leave -- loop terminated by leave say 'unreachable' 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...
#NetRexx
NetRexx
loop xx = 1 to 10 if xx = 1 then leave -- loop terminated by leave say 'unreachable' end
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...
#CoffeeScript
CoffeeScript
triangle = (array) -> for n in array console.log "#{n} rows:" printMe = 1 printed = 0 row = 1 to_print = "" while row <= n cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)) p = ("" + printMe).length while p++ <= cols to_print += ' ' to_prin...
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 ...
#Kotlin
Kotlin
// version 1.1   object FloydWarshall { fun doCalcs(weights: Array<IntArray>, nVertices: Int) { val dist = Array(nVertices) { DoubleArray(nVertices) { Double.POSITIVE_INFINITY } } for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2].toDouble() val next = Array(nVertices) { IntArray(nVertices) ...
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 ...
#Scala
Scala
def multiply(a: Int, b: Int) = 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 ...
#Scheme
Scheme
(define multiply *)
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...
#OCaml
OCaml
let rec forward_difference = function a :: (b :: _ as xs) -> b - a :: forward_difference xs | _ -> []   let rec nth_forward_difference n xs = if n = 0 then xs else nth_forward_difference (pred n) (forward_difference xs)
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.
#Ring
Ring
  decimals(3) see fixedprint(7.125, 5) + nl   func fixedprint num, digs for i = 1 to digs - len(string(floor(num))) see "0" next see num + nl  
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.
#Ruby
Ruby
r = 7.125 printf " %9.3f\n", r #=> 7.125 printf " %09.3f\n", r #=> 00007.125 printf " %09.3f\n", -r #=> -0007.125 printf " %+09.3f\n", r #=> +0007.125 puts " %9.3f" % r #=> 7.125 puts " %09.3f" % r #=> 00007.125 puts " %09.3f" % -r ...
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 ...
#Perl
Perl
sub dec2bin { sprintf "%04b", shift } sub bin2dec { oct "0b".shift } sub bin2bits { reverse split(//, substr(shift,0,shift)); } sub bits2bin { join "", map { 0+$_ } reverse @_ }   sub bxor { my($a, $b) = @_; (!$a & $b) | ($a & !$b); }   sub half_adder { my($a, $b) = @_; ( bxor($a,$b), $a & $b ); }   sub full_ad...
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...
#F.23
F#
open System   // Take from https://stackoverflow.com/a/1175123 let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list."   let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN"   let size = List.length(x) ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#360_Assembly
360 Assembly
* Find the missing permutation - 19/10/2015 PERMMISX CSECT USING PERMMISX,R15 set base register LA R4,0 i=0 LA R6,1 step LA R7,23 to LOOPI BXH R4,R6,ELOOPI do i=1 to hbound(perms) LA R5,0 ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#360_Assembly
360 Assembly
* Last Sunday of each month 31/01/2017 LASTSUND CSECT USING LASTSUND,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Action.21
Action!
;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752 BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4] BYTE res   IF m<3 THEN y==-1 FI res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7 RETURN (res)   BYTE FUNC IsLeapYear(INT y) IF y MOD...
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#360_Assembly
360 Assembly
* Intersection of two lines 01/03/2019 INTERSEC CSECT USING INTERSEC,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) li...
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE REALPTR="CARD" TYPE PointR=[REALPTR x,y]   PROC Det(REAL POINTER x1,y1,x2,y2,res) REAL tmp1,tmp2   RealMult(x1,y2,tmp1) RealMult(y1,x2,tmp2) RealSub(tmp1,tmp2,res) RETURN   BYTE FUNC IsZero(REAL POINTER a) CHAR ARRAY s(10)   StrR(a,s) IF s(0)=1 AND...
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#68000_Assembly
68000 Assembly
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: :...
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#AppleScript
AppleScript
set fiveWeekendMonths to {} set noFiveWeekendYears to {}   set someDate to current date set day of someDate to 1   repeat with someYear from 1900 to 2100 set year of someDate to someYear set foundOne to false repeat with someMonth in {January, March, May, July, ¬ August, October, Decem...
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do ...
#C.2B.2B
C++
#include <string> #include <iostream> #include <cstdlib> #include <math.h> #include <chrono> #include <iomanip>   using namespace std;   const int maxBase = 16; // maximum base tabulated int base, bmo, tc; // globals: base, base minus one, test count const string chars = "0123456789ABCDEF"; // characters to use for t...
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Axiom
Axiom
fns := [sin$Float, cos$Float, (x:Float):Float +-> x^3] inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)] [(f*g) 0.5 for f in fns for g in inv]
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#BBC_BASIC
BBC BASIC
REM Create some functions and their inverses: DEF FNsin(a) = SIN(a) DEF FNasn(a) = ASN(a) DEF FNcos(a) = COS(a) DEF FNacs(a) = ACS(a) DEF FNcube(a) = a^3 DEF FNroot(a) = a^(1/3)   dummy = FNsin(1)   REM Create the collections (here structures are used): DIM cA...
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...
#F.23
F#
open System open System.Diagnostics open System.Drawing open System.Drawing.Imaging open System.Runtime.InteropServices open System.Windows.Forms   module ForestFire =   type Cell = Empty | Tree | Fire   let rnd = new System.Random() let initial_factor = 0.35 let ignition_factor = 1e-5 // rate of lightn...
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#J
J
coclass 'hailstone'   step=:3 :0 NB. and determine next element in hailstone sequence if.1=N do. N return.end. NB. count how many times this has run when N was not 1 STEP=:STEP+1 if.0=2|N do. N=: N%2 else. N=: 1 + 3*N end. )   create=:3 :0 STEP=: 0 N=: y )   current=:3 :0 N__y )   run1=:...
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#jq
jq
{ "value": <HAILSTONE>, "count": <COUNT> }
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Julia
Julia
const jobs = 12   mutable struct Environment seq::Int cnt::Int Environment() = new(0, 0) end   const env = [Environment() for i in 1:jobs] const currentjob = [1]   seq() = env[currentjob[1]].seq cnt() = env[currentjob[1]].cnt seq(n) = (env[currentjob[1]].seq = n) cnt(n) = (env[currentjob[1]].cnt = n)   func...
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
#Clojure
Clojure
(defn flatten [coll] (lazy-seq (when-let [s (seq coll)] (if (coll? (first s)) (concat (flatten (first s)) (flatten (rest s))) (cons (first s) (flatten (rest s)))))))
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 ...
#Maple
Maple
FlippingBits := module() export ModuleApply; local gameSetup, flip, printGrid, checkInput; local board;   gameSetup := proc(n) local r, c, i, toFlip, target; randomize(): target := Array( 1..n, 1..n, rand(0..1) ); board := copy(target); for i to rand(3..9)() do toFlip := [0, 0]; toFlip[1] := StringT...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PermuteState] PermuteState[state_, {rc_, n_Integer}] := Module[{s}, s = state; Switch[rc, "R", s[[n]] = 1 - s[[n]], "C", s[[All, n]] = 1 - s[[All, n]] ]; s ] SeedRandom[1337]; n = 3; goalstate = state = RandomChoice[{0, 1}, {n, n}]; While[goalstate == state, permutations = {RandomChoice[{...
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 ...
#jq
jq
def normalize_base($base): def n: if length == 1 and .[0] < $base then .[0] else .[0] % $base, ((.[0] / $base|floor) as $carry |.[1:] | .[0] += $carry | n ) end; n;   def integers_as_arrays_times($n; $base): map(. * $n) | [normalize_base($base)];     def p($L...
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 ...
#Julia
Julia
function p(L, n) @assert(L > 0 && n > 0) places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0 for i in 1:typemax(Int) if L == trunc(10^(((i * logof2) % 1) + places)) && (nfound += 1) == n return i end end end   for (L, n) in [(12, 1), (12, 2), (123, 45), (123, 12345), (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...
#Julia
Julia
x, xi = 2.0, 0.5 y, yi = 4.0, 0.25 z, zi = x + y, 1.0 / ( x + y )   multiplier = (n1, n2) -> (m) -> n1 * n2 * m   numlist = [x , y, z] numlisti = [xi, yi, zi]   @show collect(multiplier(n, invn)(0.5) for (n, invn) in zip(numlist, numlisti))
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...
#Kotlin
Kotlin
// version 1.1.2   fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m}   fun main(args: Array<String>) { val x = 2.0 val xi = 0.5 val y = 4.0 val yi = 0.25 val z = x + y val zi = 1.0 / ( x + y) val a = doubleArrayOf(x, y, z) val ai = doubleArrayOf(xi, yi, zi) val...
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...
#Nim
Nim
block outer: for i in 0..1000: for j in 0..1000: if i + j == 3: break outer
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...
#OCaml
OCaml
exception Found of int   let () = (* search the first number in a list greater than 50 *) try let nums = [36; 23; 44; 51; 28; 63; 17] in List.iter (fun v -> if v > 50 then raise(Found v)) nums; print_endline "nothing found" with Found res -> Printf.printf "found %d\n" res
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...
#Common_Lisp
Common Lisp
;;;using flet to define local functions and storing precalculated column widths in array ;;;verbose, but more readable and efficient than version 2   (defun floydtriangle (rows) (let (column-widths) (setf column-widths (make-array rows :initial-element nil)) (flet ( (lazycat (n) ...
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 ...
#Lua
Lua
function printResult(dist, nxt) print("pair dist path") for i=0, #nxt do for j=0, #nxt do if i ~= j then u = i + 1 v = j + 1 path = string.format("%d -> %d  %2d  %s", u, v, dist[i][j], u) repeat u...
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 ...
#Seed7
Seed7
const func float: multiply (in float: a, in float: b) is 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 ...
#SenseTalk
SenseTalk
put multiply(3,7) as words   to multiply num1, num2 return num1 * num2 end multiply  
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...
#Oforth
Oforth
: forwardDiff(l) l right(l size 1 -) l zipWith(#-) ; : forwardDiffN(n, l) l #[ forwardDiff dup println ] times(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...
#PARI.2FGP
PARI/GP
fd(v)=vector(#v-1,i,v[i+1]-v[i]);
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.
#Run_BASIC
Run BASIC
print right$("00000";using("#####.##",7.125),8) ' => 00007.13
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.
#Rust
Rust
  fn main() { let x = 7.125;   println!("{:9}", x); println!("{:09}", x); println!("{:9}", -x); println!("{:09}", -x); }  
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 ...
#Phix
Phix
with javascript_semantics function xor_gate(bool a, bool b) return (a and not b) or (not a and b) end function function half_adder(bool a, bool b) bool s = xor_gate(a,b), c = a and b return {s,c} end function function full_adder(bool a, bool b, bool c) bool {s1,c1} = half_adder(c,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...
#Factor
Factor
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number   <PRIVATE   : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ;   : (fivenum) ( seq -- summary ) natural-sort { [ i...
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...
#Go
Go
package main   import ( "fmt" "math" "sort" )   func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#8080_Assembly
8080 Assembly
PRMLEN: equ 4 ; length of permutation string puts: equ 9 ; CP/M print string org 100h lxi d,perms ; Start with first permutation perm: lxi h,mperm ; Missing permutation mvi b,PRMLEN ; Length of permutation char: ...