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/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...
#Haskell
Haskell
import Data.List (intercalate)   data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show)   -- the whole thing bases upon an infinite list of weeks   daysFrom1_1_1900 :: [DayOfWeek] daysFrom1_1_1900 = concat $ repeat [Monday, Tuesday, Wednesday, Thursday, Fri...
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...
#Lambdatalk
Lambdatalk
  {def cube {lambda {:x} {pow :x 3}}} {def cuberoot {lambda {:x} {pow :x {/ 1 3}}}} {def compose {lambda {:f :g :x} {:f {:g :x}}}} {def fun sin cos cube} {def inv asin acos cuberoot} {def display {lambda {:i} {br}{compose {nth :i {fun}} {nth :i {inv}} 0.5}}} {map display {serie 0 2}}   Output: 0.5 0...
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...
#Python
Python
''' Forest-Fire Cellular automation See: http://en.wikipedia.org/wiki/Forest-fire_model '''   L = 15 # d = 2 # Fixed initial_trees = 0.55 p = 0.01 f = 0.001   try: raw_input except: raw_input = input   import random     tree, burning, space = 'TB.' hood = ((-1,-1), (-1,0), (-1,1), (0,-1), (0, ...
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
#Go
Go
package main   import "fmt"   func list(s ...interface{}) []interface{} { return s }   func main() { s := list(list(1), 2, list(list(3, 4), 5), list(list(list())), list(list(list(6))), 7, 8, list(), ) fmt.Println(s) fmt.Println(flatten(s)) }   ...
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...
#Nim
Nim
import strutils   proc floyd(rowcount = 5): seq[seq[int]] = result = @[@[1]] while result.len < rowcount: let n = result[result.high][result.high] + 1 var row = newSeq[int]() for i in n .. n + result[result.high].len: row.add i result.add row   proc pfloyd(rows: seq[seq[int]]) = var colspace...
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...
#OCaml
OCaml
let ( |> ) f g x = g (f x) let rec last = function x::[] -> x | _::tl -> last tl | [] -> raise Not_found let rec list_map2 f l1 l2 = match (l1, l2) with | ([], _) | (_, []) -> [] | (x::xs, y::ys) -> (f x y) :: list_map2 f xs ys   let floyd n = let rec aux acc cur len i j = if (List.length acc) = n then (Lis...
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 ...
#Wren
Wren
import "/fmt" for Fmt   class FloydWarshall { static doCalcs(weights, nVertices) { var dist = List.filled(nVertices, null) for (i in 0...nVertices) dist[i] = List.filled(nVertices, 1/0) for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2] var next = List.filled(nVertices, null) ...
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...
#zkl
zkl
fcn forwardDiff(lst){ if(lst.len()<2) return(T); return(T(lst[1]-lst[0]).extend(forwardDiff(lst[1,*]))) } fcn nthForwardDiff(n,xs){ if(n==0) return(xs); return(nthForwardDiff(n-1,forwardDiff(xs))) // tail recursion }
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...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DATA 9,0,1,2,4,7,4,2,1,0 20 LET p=1 30 READ n: DIM b(n) 40 FOR i=1 TO n 50 READ b(i) 60 NEXT i 70 FOR j=1 TO p 80 FOR i=1 TO n-j 90 LET b(i)=b(i+1)-b(i) 100 NEXT i 110 NEXT j 120 FOR i=1 TO n-p 130 PRINT b(i);" "; 140 NEXT i
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 ...
#VHDL
VHDL
LIBRARY ieee; USE ieee.std_logic_1164.all;   entity four_bit_adder is port( a : in std_logic_vector (3 downto 0); b : in std_logic_vector (3 downto 0); s : out std_logic_vector (3 downto 0); v : out std_logic ); end four_bit_adder ;   LIBRARY ieee; USE ieee.std_logic_1164.al...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#ERRE
ERRE
  PROGRAM MISSING   CONST N=4   DIM PERMS$[23]   BEGIN PRINT(CHR$(12);) ! CLS DATA("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB") DATA("CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC") DATA("BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB")   FOR I%=1 TO UBOUND(PERMS$,1) DO READ(PERMS$[I%]...
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...
#Go
Go
package main   import ( "fmt" "time" )   func main() {   var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }   for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } }   fmt.P...
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) .
#Modula-2
Modula-2
MODULE LineIntersection; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   TYPE Point = RECORD x,y : REAL; END;   PROCEDURE PrintPoint(p : Point); VAR buf : ARRAY[0..31] OF CHAR; BEGIN WriteString("{"); RealToStr(p.x, buf); WriteString(buf); WriteString(...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Python
Python
#!/bin/python from __future__ import print_function import numpy as np   def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):   ndotu = planeNormal.dot(rayDirection) if abs(ndotu) < epsilon: raise RuntimeError("no intersection or line is within plane")   w = rayPoint - planePoint ...
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) ...
#ATS
ATS
#include "share/atspre_staload.hats"   implement main0() = loop(1, 100) where { fun loop(from: int, to: int): void = if from > to then () else let val by3 = (from % 3 = 0) val by5 = (from % 5 = 0) in case+ (by3, by5) of | (true, true) => print_string("FizzBuzz") | (true, fals...
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...
#Icon_and_Unicon
Icon and Unicon
link datetime,printf   procedure main(A) # five weekends printf( "There are %d months from %d to %d with five full weekends.\n", *(L := fiveweekends(s := 1900, f := 2100)), s,f) printf("The first and last five such months are:\n") every printf("%s\n",L[1 to 5]|"..."|L[-4 to 0]) printf( "There...
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...
#Lasso
Lasso
#!/usr/bin/lasso9   define cube(x::decimal) => { return #x -> pow(3.0) }   define cuberoot(x::decimal) => { return #x -> pow(1.0/3.0) }   define compose(f, g, v) => { return { return #f -> detach -> invoke(#g -> detach -> invoke(#1)) } -> detach -> invoke(#v) }     local(functions = array({return #1 -> sin}, {ret...
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...
#Lingo
Lingo
-- sin, cos and sqrt are built-in, square, asin and acos are user-defined A = [#sin, #cos, #square] B = [#asin, #acos, #sqrt]   testValue = 0.5   repeat with i = 1 to 3 -- for implementation details of compose() see https://www.rosettacode.org/wiki/Function_composition#Lingo f = compose(A[i], B[i]) res = call(f, ...
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...
#Racket
Racket
#lang racket (require 2htdp/universe) (require 2htdp/image)   (define (initial-forest w p-tree) (for/vector #:length w ((rw w)) (for/vector #:length w ((cl w)) (if (< (random) p-tree) #\T #\_))))   (define (has-burning-neighbour? forest r# c# w)  ;; note, this will check r# c#, too but it's not  ;; worth ...
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
#Groovy
Groovy
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]
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...
#OxygenBasic
OxygenBasic
  function Floyd(sys n) as string sys i,t for i=1 to n t+=i next string s=str t sys le=1+len s string cr=chr(13,10) sys lc=len cr string buf=space(le*t+n*lc) sys j,o,p=1 t=0 for i=1 to n for j=1 to i t++ s=str t o=le-len(s)-1 'right justify mid buf,p+o,str t p+=le next mid buf,p,cr p+=lc n...
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...
#PARI.2FGP
PARI/GP
{floyd(m)=my(lastrow_a,lastrow_e,lastrow_len=m,fl,idx); \\ +++ fl is a vector of fieldlengths in the last row lastrow_e=m*(m+1)/2;lastrow_a=lastrow_e+1-m; fl=vector(lastrow_len); for(k=1,m,fl[k] = 1 + #Str(k-1+lastrow_a) ); \\ idx=0; for(i=1,m, for(j=1,i, idx++; print...
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 ...
#zkl
zkl
fcn FloydWarshallWithPathReconstruction(dist){ // dist is munged V:=dist[0].len(); next:=V.pump(List,V.pump(List,Void.copy).copy); // VxV matrix of Void foreach u,v in (V,V){ if(dist[u][v]!=Void and u!=v) next[u][v] = v } foreach k,i,j in (V,V,V){ a,b,c:=dist[i][j],dist[i][k],dist[k][j]; if( (a...
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 ...
#Wren
Wren
var xor = Fn.new { |a, b| a&(~b) | b&(~a) }   var ha = Fn.new { |a, b| [xor.call(a, b), a & b] }   var fa = Fn.new { |a, b, c0| var res = ha.call(a, c0) var sa = res[0] var ca = res[1] res = ha.call(sa, b) return [res[0], ca | res[1]] }   var add4 = Fn.new { |a3, a2, a1, a0, b3, b2, b1, b0| var ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Factor
Factor
USING: io math.combinatorics sequences sets ;   "ABCD" all-permutations lines diff first print
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...
#Groovy
Groovy
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } }   def date = Date.&parse.curry('yyyy-MM-dd') def month = { it.format('MM') } def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) } def weekDays = { dayOfWeek, year -> days(year).findAll ...
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) .
#Nim
Nim
type Line = tuple slope: float yInt: float Point = tuple x: float y: float   func createLine(a, b: Point): Line = result.slope = (b.y - a.y) / (b.x - a.x) result.yInt = a.y - result.slope * a.x   func evalX(line: Line, x: float): float = line.slope * x + line.yInt   func intersection(line1, 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) .
#Perl
Perl
  sub intersect { my ($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4) = @_; my $a1 = $y2 - $y1; my $b1 = $x1 - $x2; my $c1 = $a1 * $x1 + $b1 * $y1; my $a2 = $y4 - $y3; my $b2 = $x3 - $x4; my $c2 = $a2 * $x3 + $b2 * $y3; my $delta = $a1 * $b2 - $a2 * $b1; return (undef, undef) if $delta == 0; # If delta is 0...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#R
R
intersect_point <- function(ray_vec, ray_point, plane_normal, plane_point) {   pdiff <- ray_point - plane_point prod1 <- pdiff %*% plane_normal prod2 <- ray_vec %*% plane_normal prod3 <- prod1 / prod2 point <- ray_point - ray_vec * as.numeric(prod3)   return(point) }
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Racket
Racket
#lang racket ;; {{trans|Sidef}} ;; vectors are represented by lists   (struct Line (P0 u⃗))   (struct Plane (V0 n⃗))   (define (· a b) (apply + (map * a b)))   (define (line-plane-intersection L P) (match-define (cons (Line P0 u⃗) (Plane V0 n⃗)) (cons L P)) (define cos (· n⃗ u⃗)) (when (zero? cos) (error "vec...
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) ...
#AutoHotkey
AutoHotkey
Loop, 100 { If (Mod(A_Index, 15) = 0) output .= "FizzBuzz`n" Else If (Mod(A_Index, 3) = 0) output .= "Fizz`n" Else If (Mod(A_Index, 5) = 0) output .= "Buzz`n" Else output .= A_Index "`n" } FileDelete, output.txt FileAppend, %output%, output.txt Run, cmd /k type output.txt
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...
#Inform_7
Inform 7
Calendar is a room.   When play begins: let happy month count be 0; let sad year count be 0; repeat with Y running from Y1900 to Y2100: if Y is a sad year, increment the sad year count; repeat with M running through months: if M of Y is a happy month: say "[M] [year number of Y]."; increment the happy...
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...
#J
J
require 'types/datetime numeric' find5wkdMonths=: verb define years=. range 2{. y months=. 1 3 5 7 8 10 12 m5w=. (#~ 0 = weekday) >,{years;months;31 NB. 5 full weekends iff 31st is Sunday(0) >'MMM YYYY' fmtDate toDayNo m5w )
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...
#Lua
Lua
function compose(f,g) return function(...) return f(g(...)) end end   fn = {math.sin, math.cos, function(x) return x^3 end} inv = {math.asin, math.acos, function(x) return x^(1/3) end}   for i, v in ipairs(fn) do local f = compose(v, inv[i]) print(f(0.5)) end
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...
#M2000_Interpreter
M2000 Interpreter
  Module CheckFirst { RAD = lambda -> number/180*pi ASIN = lambda RAD -> { Read x : x=Round(x,10) If x>=0 and X<1 Then { =RAD(abs(2*Round(ATN(x/(1+SQRT(1-x**2)))))) } Else.if x==1 Then { =RAD(90) } Else error "asin exit limit"...
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...
#Raku
Raku
my $RED = "\e[1;31m"; my $YELLOW = "\e[1;33m"; my $GREEN = "\e[1;32m"; my $CLEAR = "\e[0m";   enum Cell-State <Empty Tree Heating Burning>; my @pix = ' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木';   class Forest { has Rat $.p = 0.01; has Rat $.f = 0.001; has Int $!height; has Int $!width; has @!coor...
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
#Haskell
Haskell
import Data.Tree (Tree(..), flatten)   -- [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] -- implemented as multiway tree: -- Data.Tree represents trees where nodes have values too, unlike the trees in our problem. -- so we use a list as that value, where a node will have an empty list value, -- and a leaf will have a ...
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...
#Pascal
Pascal
Program FloydDemo (input, output);   function digits(number: integer): integer; begin digits := trunc(ln(number) / ln(10)) + 1; end;   procedure floyd1 (numberOfLines: integer); { variant with repeat .. until loop } var i, j, numbersInLine, startOfLastlLine: integer;   begin startOfLastlLine := (num...
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 ...
#XPL0
XPL0
code CrLf=9, IntOut=11;   func Not(A); int A; return not A;   func And(A, B); int A, B; return A and B;   func Or(A, B); int A, B; return A or B;   func Xor(A, B); int A, B; return Or(And(A, Not(B)), And(Not(A), B));   proc HalfAdd(A, B, S, C); int A, B, S, C; [S(0):= Xor(A, B); C(0):= And(A, B); ];   proc FullAdd(A, ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Forth
Forth
hex ABCD CABD xor ACDB xor DACB xor BCDA xor ACBD xor ADCB xor CDAB xor DABC xor BCAD xor CADB xor CDBA xor CBAD xor ABDC xor ADBC xor BDCA xor DCBA xor BACD xor BADC xor BDAC xor CBDA xor DBCA xor DCAB xor cr .( Missing permutation: ) u. decimal
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Fortran
Fortran
program missing_permutation   implicit none character (4), dimension (23), parameter :: list = & & (/'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB', & & 'DABC', 'BCAD', 'CADB', 'CDBA', 'CBAD', 'ABDC', 'ADBC', 'BDCA', & & 'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBC...
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...
#Haskell
Haskell
import Data.List (find, intercalate, transpose) import Data.Maybe (fromJust) import Data.Time.Calendar ( Day, addDays, fromGregorian, gregorianMonthLength, showGregorian, ) import Data.Time.Calendar.WeekDate (toWeekDate)   ---------------- LAST SUNDAY OF EACH MONTH ---------------   lastSundayOfEach...
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) .
#Phix
Phix
with javascript_semantics enum X, Y function abc(sequence s,e) -- yeilds {a,b,c}, corresponding to ax+by=c atom a = e[Y]-s[Y], b = s[X]-e[X], c = a*s[X]+b*s[Y] return {a,b,c} end function procedure intersect(sequence s1, e1, s2, e2) atom {a1,b1,c1} = abc(s1,e1), {a2,b2,c2} = abc(s2,e2), ...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Raku
Raku
class Line { has $.P0; # point has $.u⃗; # ray } class Plane { has $.V0; # point has $.n⃗; # normal }   sub infix:<∙> ( @a, @b where +@a == +@b ) { [+] @a «*» @b } # dot product   sub line-plane-intersection ($𝑳, $𝑷) { my $cos = $𝑷.n⃗ ∙ $𝑳.u⃗; # cosine between normal & ray return 'Vectors ...
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) ...
#AutoIt
AutoIt
For $i = 1 To 100 If Mod($i, 15) = 0 Then MsgBox(0, "FizzBuzz", "FizzBuzz") ElseIf Mod($i, 5) = 0 Then MsgBox(0, "FizzBuzz", "Buzz") ElseIf Mod($i, 3) = 0 Then MsgBox(0, "FizzBuzz", "Fizz") Else MsgBox(0, "FizzBuzz", $i) EndIf Next
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...
#Java
Java
import java.util.Calendar; import java.util.GregorianCalendar;   public class FiveFSS { private static boolean[] years = new boolean[201]; private static int[] month31 = {Calendar.JANUARY, Calendar.MARCH, Calendar.MAY, Calendar.JULY, Calendar.AUGUST, Calendar.OCTOBER, Calendar.DECEMBER};   public st...
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...
#Maple
Maple
  > A := [ sin, cos, x -> x^3 ]: > B := [ arcsin, arccos, rcurry( surd, 3 ) ]: > zip( `@`, A, B )( 2/3 ); [2/3, 2/3, 2/3]   > zip( `@`, B, A )( 2/3 ); [2/3, 2/3, 2/3]  
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
funcs = {Sin, Cos, #^3 &}; funcsi = {ArcSin, ArcCos, #^(1/3) &}; compositefuncs = Composition @@@ Transpose[{funcs, funcsi}]; Table[i[0.666], {i, compositefuncs}]
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...
#REXX
REXX
┌───────────────────────────elided version──────────────────────────┐ ├─── original version has many more options & enhanced displays. ───┤ └───────────────────────────────────────────────────────────────────┘
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
#Hy
Hy
(defn flatten [lst] (sum (genexpr (if (isinstance x list) (flatten x) [x]) [x lst]) []))   (print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])) ; [1, 2, 3, 4, 5, 6, 7, 8]
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...
#Perl
Perl
#!/usr/bin/env perl use strict; use warnings;   sub displayFloydTriangle { my $numRows = shift; print "\ndisplaying a $numRows row Floyd's triangle:\n\n"; my $maxVal = int($numRows * ($numRows + 1) / 2); # calculate the max value. my $digit = 0; foreach my $row (1 .. $numRows) { my $col = 0; my $outpu...
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 ...
#zkl
zkl
fcn xor(a,b) // a,b are 1|0 -->a^b(1|0) { a.bitAnd(b.bitNot()).bitOr(b.bitAnd(a.bitNot())) }   fcn halfAdder(a,b) // -->(carry, a+b) (1|0) { return(a.bitAnd(b), xor(a,b)) }   fcn fullBitAdder(c, a,b){ //-->(carry, a+b+c), a,b,c are 1|0 c1,s := halfAdder(a,c); c2,s := halfAdder(s,b); c3  := c1.bitOr(c2);...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#FreeBASIC
FreeBASIC
' version 30-03-2017 ' compile with: fbc -s console   Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD" Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA" Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD" Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"   ' ------=< MAIN >=------   Dim As ulong total(3, Asc("A") To Asc...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every write(lastsundays(!A)) end   procedure lastsundays(year) every m := 1 to 12 do { d := case m of { 2 : if IsLeapYear(year) then 29 else 28 4|6|9|11 : 30 default : 31 } # last day of month   z := 0 j := julian(m,d,year) + 1 # ...
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) .
#Processing
Processing
void setup() { // test lineIntersect() with visual and textual output float lineA[] = {4, 0, 6, 10}; // try 4, 0, 6, 4 float lineB[] = {0, 3, 10, 7}; // for non intersecting test PVector pt = lineInstersect(lineA[0], lineA[1], lineA[2], lineA[3], lineB[0], lineB[1], lineB[2], li...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#REXX
REXX
/* REXX */ Parse Value '0 0 1' With n.1 n.2 n.3 /* Normal Vector of the plane */ Parse Value '0 0 5' With p.1 p.2 p.3 /* Point in the plane */ Parse Value '0 0 10' With a.1 a.2 a.3 /* Point of the line */ Parse Value '0 -1 -1' With v.1 v.2 v.3 /* Vector of the line */   a=n.1 b=n.2 c=n.3 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) ...
#Avail
Avail
For each i from 1 to 100 do [ Print: if i mod 15 = 0 then ["FizzBuzz"] else if i mod 3 = 0 then ["Fizz"] else if i mod 5 = 0 then ["Buzz"] else [“i”] ++ "\n"; ];
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...
#JavaScript
JavaScript
function startsOnFriday(month, year) { // 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday return new Date(year, month, 1).getDay() === 5; } function has31Days(month, year) { return new Date(year, month, 31).getDate() === 31; } function checkMonths(year) { var month, count = 0; for (month = 0; month < 12; ...
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...
#Maxima
Maxima
a: [sin, cos, lambda([x], x^3)]$ b: [asin, acos, lambda([x], x^(1/3))]$ compose(f, g) := buildq([f, g], lambda([x], f(g(x))))$ map(lambda([fun], fun(x)), map(compose, a, b)); [x, x, x]
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...
#Mercury
Mercury
  :- module firstclass.   :- interface. :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module exception, list, math, std_util.   main(!IO) :- Forward = [sin, cos, (func(X) = ln(X))], Reverse = [asin, acos, (func(X) = exp(X))], Results = map_corresponding( ...
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...
#Ring
Ring
  # Project : Forest fire   load "guilib.ring" load "stdlib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("Forest fire") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,...
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
#Icon_and_Unicon
Icon and Unicon
link strings # for compress,deletec,pretrim   procedure sflatten(s) # uninteresting string solution return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',') 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...
#Phix
Phix
with javascript_semantics procedure Floyds_triangle(integer n) sequence widths = repeat(0,n) integer k = (n * (n-1))/2 for i=1 to n do widths[i] = sprintf("%%%dd",length(sprintf("%d",i+k))+1) end for k = 1 for i=1 to n do for j=1 to i do printf(1,widths[j],k) ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#GAP
GAP
# our deficient list L := [ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" ];   # convert L to permutations on 1..4 u := List(L, s -> List([1..4], i -> Position("ABCD", s[i])))...
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...
#J
J
require'dates' last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1
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) .
#Python
Python
def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2): """ returns a (x, y) tuple or None if there is no intersection """ d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) if d: uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d uB = ((Ax2 - Ax1) * (Ay1 - By1) - (A...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Ruby
Ruby
require "matrix"   def intersectPoint(rayVector, rayPoint, planeNormal, planePoint) diff = rayPoint - planePoint prod1 = diff.dot planeNormal prod2 = rayVector.dot planeNormal prod3 = prod1 / prod2 return rayPoint - rayVector * prod3 end   def main rv = Vector[0.0, -1.0, -1.0] rp = Vector[0....
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) ...
#AWK
AWK
For(I,1,100) !If I^3??I^5 Disp "FIZZBUZZ",i Else!If I^3 Disp "FIZZ",i Else!If I^5 Disp "BUZZ",i Else Disp I▶Dec,i End .Pause to allow the user to actually read the output Pause 1000 End
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...
#jq
jq
Use Zeller's Congruence to determine the day of the week, given # year, month and day as integers in the conventional way. # Emit 0 for Saturday, 1 for Sunday, etc. # def day_of_week(year; month; day): if month == 1 or month == 2 then [month + 12, year - 1] else [month, year] end | day + (13*(.[0] + 1...
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...
#min
min
('sin 'cos (3 pow)) =A ('asin 'acos (1 3 / pow)) =B   (A bool) ( 0.5 A first B first concat -> puts! A rest #A B rest #B ) while
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...
#Nemerle
Nemerle
using System; using System.Console; using System.Math; using Nemerle.Collections.NCollectionsExtensions;   module FirstClassFunc { Main() : void { def cube = fun (x) {x * x * x}; def croot = fun (x) {Pow(x, 1.0/3.0)}; def compose = fun(f, g) {fun (x) {f(g(x))}}; def funcs = [Sin,...
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...
#Ruby
Ruby
class Forest_Fire Neighborhood = [-1,0,1].product([-1,0,1]) - [0,0] States = {empty:" ", tree:"T", fire:"#"}   def initialize(xsize, ysize=xsize, p=0.5, f=0.01) @xsize, @ysize, @p, @f = xsize, ysize, p, f @field = Array.new(xsize+1) {|i| Array.new(ysize+1, :empty)} @generation = 0 end   def evolve...
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
#Ioke
Ioke
iik> [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten +> [1, 2, 3, 4, 5, 6, 7, 8]
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...
#PHP
PHP
  <?php floyds_triangle(5); floyds_triangle(14);   function floyds_triangle($n) { echo "n = " . $n . "\r\n";   for($r = 1, $i = 1, $c = 0; $r <= $n; $i++) { $cols = ceil(log10($n*($n-1)/2 + $c + 2)); printf("%".$cols."d ", $i); if(++$c == $r) { echo "\r\n"; $r++; ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Go
Go
package main   import ( "fmt" "strings" )   var given = strings.Split(`ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB`, "\n")   func main() { b := make([]byte, len(given[0])) for i := range b { m := make(map[byte]int) fo...
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...
#Java
Java
import java.util.Scanner;   public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};   public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year);   int[] days={31,isLeap?29:28,31...
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) .
#Racket
Racket
#lang racket/base (define (det a b c d) (- (* a d) (* b c))) ; determinant   (define (line-intersect ax ay bx by cx cy dx dy) ; --> (values x y) (let* ((det.ab (det ax ay bx by)) (det.cd (det cx cy dx dy)) (abΔx (- ax bx)) (cdΔx (- cx dx)) (abΔy (- ay by)) (cdΔy (- cy dy))...
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) .
#Raku
Raku
sub intersection (Real $ax, Real $ay, Real $bx, Real $by, Real $cx, Real $cy, Real $dx, Real $dy ) {   sub term:<|AB|> { determinate($ax, $ay, $bx, $by) } sub term:<|CD|> { determinate($cx, $cy, $dx, $dy) }   my $ΔxAB = $ax - $bx; my $ΔyAB = $ay - $by; my $ΔxCD = $cx - $dx; my ...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Rust
Rust
use std::ops::{Add, Div, Mul, Sub};   #[derive(Copy, Clone, Debug, PartialEq)] struct V3<T> { x: T, y: T, z: T, }   impl<T> V3<T> { fn new(x: T, y: T, z: T) -> Self { V3 { x, y, z } } }   fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U> where F: Fn(T, T) -> U, { V3 { x...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Scala
Scala
object LinePLaneIntersection extends App { val (rv, rp, pn, pp) = (Vector3D(0.0, -1.0, -1.0), Vector3D(0.0, 0.0, 10.0), Vector3D(0.0, 0.0, 1.0), Vector3D(0.0, 0.0, 5.0)) val ip = intersectPoint(rv, rp, pn, pp)   def intersectPoint(rayVector: Vector3D, rayPoint: Vector3D, ...
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) ...
#Axe
Axe
For(I,1,100) !If I^3??I^5 Disp "FIZZBUZZ",i Else!If I^3 Disp "FIZZ",i Else!If I^5 Disp "BUZZ",i Else Disp I▶Dec,i End .Pause to allow the user to actually read the output Pause 1000 End
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...
#Julia
Julia
isweekend(dt::Date) = Dates.dayofweek(dt) ∈ (Dates.Friday, Dates.Saturday, Dates.Sunday)   function hasfiveweekend(month::Integer, year::Integer) dmin = Date(year, month, 1) dmax = dmin + Dates.Day(Dates.daysinmonth(dmin) - 1) return count(isweekend, dmin:dmax) ≥ 15 end   months = collect((y, m) for y in 19...
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...
#k
k
  cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays m:__dj[cal_j]%100 / label the months mi:&15=+/'is_we[=m] / group by month and sum the weekend d...
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...
#newLISP
newLISP
> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g)) (lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g)) > (define (cube x) (pow x 3)) (lambda (x) (pow x 3)) > (define (cube-root x) (pow x (div 1 3))) (lambda (x) (pow x (div 1 3))) > (define functions '(sin cos cube)) (sin cos cube) > (define inverses '(a...
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...
#Rust
Rust
extern crate rand; extern crate ansi_term;   #[derive(Copy, Clone, PartialEq)] enum Tile { Empty, Tree, Burning, Heating, }   impl fmt::Display for Tile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let output = match *self { Empty => Black.paint(" "), Tree...
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
#Isabelle
Isabelle
theory Scratch imports Main begin   datatype 'a tree = Leaf 'a ("<_>") | Node "'a tree list" ("⟦ _ ⟧")   text‹The datatype introduces special pretty printing:› lemma "Leaf a = <a>" by simp lemma "Node [] = ⟦ [] ⟧" by simp   definition "example ≡ ⟦[ ⟦[<1>]⟧, <2>, ⟦[ ⟦[<3>, <4>]⟧, <5>]⟧, ⟦[⟦[⟦[]⟧]⟧]⟧, ...
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...
#Picat
Picat
import util.   % Calculate the numbers first and then format them floyd1(N) = S => M = [[J+SS : J in 1..I] : I in 1..N, SS=sum(1..I-1)], S = [slice(SS,2) : Row in M, SS = [to_fstring(to_fstring("%%%dd",M[N,I].to_string().length+1),E) : {E,I} in zip(Row,1..Row.length)].join('')].join("\n"...
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...
#PicoLisp
PicoLisp
(de floyd (N) (let LLC (/ (* N (dec N)) 2) (for R N (for C R (prin (align (length (+ LLC C)) (+ C (/ (* R (dec R)) 2)) ) ) (if (= C R) (prinl) (space)) ) ) ) )
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Groovy
Groovy
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() } def missingPerms missingPerms = {List elts, List perms -> perms.empty ? elts.permutations() : elts.collect { e -> def ePerms = perms.findAll { e == it[0] }.collect { it[1..-1] } ePerms.size() == fact(elts.size() - 1) ? [] \ ...
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...
#JavaScript
JavaScript
function lastSundayOfEachMonths(year) { var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var sundays = []; var date, month; if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) { lastDay[2] = 29; } for (date = new Date(), month = 0; month < 12; month += 1) { date.setFullYear(year, mont...
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) .
#REXX
REXX
/* REXX */ Parse Value '(4.0,0.0)' With '(' xa ',' ya ')' Parse Value '(6.0,10.0)' With '(' xb ',' yb ')' Parse Value '(0.0,3.0)' With '(' xc ',' yc ')' Parse Value '(10.0,7.0)' With '(' xd ',' yd ')'   Say 'The two lines are:' Say 'yab='ya-xa*((yb-ya)/(xb-xa))'+x*'||((yb-ya)/(xb-xa)) Say 'ycd='yc-xc*((yd-yc)/(xd-xc)...
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Sidef
Sidef
struct Line { P0, # point u⃗, # ray }   struct Plane { V0, # point n⃗, # normal }   func dot_prod(a, b) { a »*« b -> sum }   func line_plane_intersection(𝑳, 𝑷) { var cos = dot_prod(𝑷.n⃗, 𝑳.u⃗) -> || return 'Vectors are orthogonal' var 𝑊 = (𝑳.P0 »-« 𝑷.V0) ...
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) ...
#Babel
Babel
main: { { iter 1 + dup   15 % { "FizzBuzz" << zap } { dup 3 % { "Fizz" << zap } { dup 5 % { "Buzz" << zap} { %d << } ...
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...
#Kotlin
Kotlin
// version 1.0.6   import java.util.*   fun main(args: Array<String>) { val calendar = GregorianCalendar(1900, 0, 1) val months31 = arrayOf(1, 3, 5, 7, 8, 10, 12) val monthsWithFive = mutableListOf<String>() val yearsWithNone = mutableListOf<Int>() for (year in 1900..2100) { var countInYear...
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...
#Nim
Nim
from math import nil # Require qualifier to access functions.   type MF64 = proc(x: float64): float64   proc cube(x: float64) : float64 = math.pow(x, 3)   proc cuberoot(x: float64) : float64 = math.pow(x, 1/3)   proc compose[A](f: proc(x: A): A, g: proc(x: A): A) : (proc(x: A): A) = proc c(x: A): A = f(g(x))...
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...
#Objeck
Objeck
use Collection.Generic;   lambdas Func { Double : (FloatHolder) ~ FloatHolder }   class FirstClass { function : Main(args : String[]) ~ Nil { vector := Vector->New()<Func2Holder <FloatHolder, FloatHolder> >; # store functions in collections vector->AddBack(Func2Holder->New(\Func->Double : (v) => ...
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...
#Sather
Sather
class FORESTFIRE is private attr fields:ARRAY{ARRAY{INT}}; private attr swapu:INT; private attr rnd:RND; private attr verbose:BOOL; private attr generation:INT; readonly attr width, height:INT; const empty:INT := 0; const tree:INT := 1; const burning:INT := 2;   attr prob_tree, prob_p, prob_f :FLT; ...
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
#J
J
flatten =: [: ; <S:0
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...
#PL.2FI
PL/I
(fofl, size): floyd: procedure options (main); /* Floyd's Triangle. Wiki 12 July 2012 */   declare (i, m, n) fixed (10), (j, k, w, nr) fixed binary;   put list ('How many rows do you want?'); get list (nr); /* the number of rows */ n = nr*(nr+1)/2; /* the total number of values */   j,k = 1; m = n - ...
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Haskell
Haskell
import Data.List ((\\), permutations, nub) import Control.Monad (join)   missingPerm :: Eq a => [[a]] -> [[a]] missingPerm = (\\) =<< permutations . nub . join   deficientPermsList :: [String] deficientPermsList = [ "ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD" , "ADCB" , "CDAB" , "DABC" ,...