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/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... | #Ada | Ada | >./last_weekday_in_month sunday 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29 |
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... | #ALGOL_68 | ALGOL 68 | BEGIN # find the last Sunday in each month of a year #
# returns true if year is a leap year, false otherwise #
# assumes year is in the Gregorian Calendar #
PROC is leap year = ( INT year )BOOL:
year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 );
# ... |
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) .
| #Ada | Ada | with Ada.Text_IO;
procedure Intersection_Of_Two_Lines
is
Do_Not_Intersect : exception;
type Line is record
a : Float;
b : Float;
end record;
type Point is record
x : Float;
y : Float;
end record;
function To_Line(p1, p2 : in Point) return Line
is
a : constant F... |
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)
... | #8080_Assembly | 8080 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... | #AutoHotkey | AutoHotkey | Year := 1900
End_Year := 2100
31_Day_Months = 01,03,05,07,08,10,12
While Year <= End_Year
{
Loop, Parse, 31_Day_Months, CSV
{
FormatTime, Day, %Year%%A_LoopField%01, dddd
IfEqual, Day, Friday
{
All_Months_With_5_Weekends .= A_LoopField . "/" . Year ", "
... |
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 ... | #D | D | import std.algorithm;
import std.exception;
import std.math;
import std.stdio;
import std.string;
string toBaseN(const long num, const int base)
in (base > 1, "base cannot be less than 2")
body {
immutable ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
enforce(base < ALPHABET.length, "base cannot be repre... |
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... | #Bori | Bori | double acos (double d) { return Math.acos(d); }
double asin (double d) { return Math.asin(d); }
double cos (double d) { return Math.cos(d); }
double sin (double d) { return Math.sin(d); }
double croot (double d) { return Math.pow(d, 1/3); }
double cube (double x) { return x * x * x; }
Var compose (Var f, Var g, doubl... |
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... | #BQN | BQN | funsA ← ⟨⋆⟜2,-,•math.Sin,{𝕩×3}⟩
funsB ← ⟨√,-,•math.Asin,{𝕩÷3}⟩
comp ← funsA {𝕎∘𝕏}¨ funsB
•Show comp {𝕎𝕩}¨<0.5 |
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... | #Factor | Factor | USING: combinators grouping kernel literals math math.matrices
math.vectors prettyprint random raylib.ffi sequences ;
IN: rosetta-code.forest-fire
! The following private vocab builds up to a useful combinator,
! matrix-map-neighbors, which takes a matrix, a quotation, and
! inside the quotation makes available each ... |
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 "... | #Kotlin | Kotlin | // version 1.1.3
class Environment(var seq: Int, var count: Int)
const val JOBS = 12
val envs = List(JOBS) { Environment(it + 1, 0) }
var seq = 0 // 'seq' for current environment
var count = 0 // 'count' for current environment
var currId = 0 // index of current environment
fun switchTo(id: Int) {
if ... |
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
| #CoffeeScript | CoffeeScript |
flatten = (arr) ->
arr.reduce ((xs, el) ->
if Array.isArray el
xs.concat flatten el
else
xs.concat [el]), []
# test
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
console.log flatten list
|
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 ... | #MATLAB | MATLAB | function FlippingBitsGame(n)
% Play the flipping bits game on an n x n array
% Generate random target array
fprintf('Welcome to the Flipping Bits Game!\n')
if nargin < 1
n = input('What dimension array should we use? ');
end
Tar = logical(randi([0 1], n));
% Generate starting array b... |
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12 | First power of 2 that has leading decimal digits of 12 | (This task is taken from a Project Euler problem.)
(All numbers herein are expressed in base ten.)
27 = 128 and 7 is
the first power of 2 whose leading decimal digits are 12.
The next power of 2 whose leading decimal digits
are 12 is 80,
280 = 1208925819614629174706176.
Define ... | #Kotlin | Kotlin | import kotlin.math.ln
import kotlin.math.pow
fun main() {
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)
}
private fun runTest(l: Int, n: Int) {
// System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n))
println("p($l, $n) = %,d".format(p(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... | #Lua | Lua |
-- This function returns another function that
-- keeps n1 and n2 in scope, ie. a closure.
function multiplier (n1, n2)
return function (m)
return n1 * n2 * m
end
end
-- Multiple assignment a-go-go
local x, xi, y, yi = 2.0, 0.5, 4.0, 0.25
local z, zi = x + y, 1.0 / ( x + y )
local ... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
\\ by default numbers are double
x = 2
xi = 0.5
y = 4
yi = 0.25
z = x + y
zi = 1 / ( x + y )
Composed=lambda (a, b)-> {
=lambda a,b (n)->{
=a*b*n
}
}
numbers=(x,y,z)
inverses=(xi,yi,zi)
... |
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... | #Oforth | Oforth | break |
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... | #Oz | Oz | case {OS.rand} mod 3
of 0 then {Foo}
[] 1 then {Bar}
[] 2 then {Buzz}
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... | #Cowgol | Cowgol | include "cowgol.coh";
sub width(n: uint16): (w: uint8) is
w := 1;
while n >= 10 loop
n := n / 10;
w := w + 1;
end loop;
end sub;
sub print_fixed(n: uint16, w: uint8) is
w := w - width(n);
while w > 0 loop
print_char(' ');
w := w - 1;
end loop;
print_i16(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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | g = Graph[{1 \[DirectedEdge] 3, 3 \[DirectedEdge] 4,
4 \[DirectedEdge] 2, 2 \[DirectedEdge] 1, 2 \[DirectedEdge] 3},
EdgeWeight -> {(1 \[DirectedEdge] 3) -> -2, (3 \[DirectedEdge] 4) ->
2, (4 \[DirectedEdge] 2) -> -1, (2 \[DirectedEdge] 1) ->
4, (2 \[DirectedEdge] 3) -> 3}]
vl = VertexList[g];
dm = G... |
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 ... | #SETL | SETL | proc multiply( a, b );
return a * b;
end proc; |
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 ... | #Sidef | Sidef | func multiply(a, b) {
a * b;
} |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Pascal | Pascal | Program ForwardDifferenceDemo(output);
procedure fowardDifference(list: array of integer);
var
b: array of integer;
i, newlength: integer;
begin
newlength := length(list) - 1;
if newlength > 0 then
begin
setlength(b, newlength);
for i := low(b) to high(b) do
begin
b[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.
| #Sather | Sather | class MAIN is
main is
#OUT + #FMT("<F0 #####.###>", 7.1257) + "\n";
#OUT + #FMT("<F0 #####.###>", 7.1254) + "\n";
end;
end; |
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.
| #Scala | Scala | object FormattedNumeric {
val r = 7.125 //> r : Double = 7.125
println(f" ${-r}%9.3f"); //> -7,125
println(f" $r%9.3f"); //> 7,125
println(f" $r%-9.3f"); //> 7,125
println(f" ${-r}%09.3f"... |
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 ... | #PicoLisp | PicoLisp | (de halfAdder (A B) #> (Carry . Sum)
(cons
(and A B)
(xor A B) ) )
(de fullAdder (A B C) #> (Carry . Sum)
(let (Ha1 (halfAdder C A) Ha2 (halfAdder (cdr Ha1) B))
(cons
(or (car Ha1) (car Ha2))
(cdr Ha2) ) ) )
(de 4bitsAdder (A4 A3 A2 A1 B4 B3 B2 B1) #> (V S4 S3 S2 S1)
... |
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... | #Groovy | Groovy | class Fivenum {
static double median(double[] x, int start, int endInclusive) {
int size = endInclusive - start + 1
if (size <= 0) {
throw new IllegalArgumentException("Array slice cannot be empty")
}
int m = start + (int) (size / 2)
return (size % 2 == 1) ? x[m] ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
mov si,perms ; Start of permutations
xor bx,bx ; First word of permutation
xor dx,dx ; Second word of permutation
mov cx,23 ; There are 23 permutations given
per... |
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... | #ALGOL-M | ALGOL-M |
BEGIN
% CALCULATE P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
COMMENT
RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN
GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE;
INTEGER FUNCTION DAYOFWEEK(MO, DA, YR);
INTEGER MO, DA, YR;
BEGIN
INTEGER Y, C, Z;
IF M... |
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... | #ALGOL_W | ALGOL W | begin % find the last Sunday in each month of a year %
% returns true if year is a leap year, false otherwise %
% assumes year is in the Gregorian Calendar %
logical procedure isLeapYear ( integer value year ) ;
year rem 400 = 0 or ( year rem 4 = 0 and year rem 100... |
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) .
| #ALGOL_68 | ALGOL 68 | BEGIN
# mode to hold a point #
MODE POINT = STRUCT( REAL x, y );
# mode to hold a line expressed as y = mx + c #
MODE LINE = STRUCT( REAL m, c );
# returns the line that passes through p1 and p2 #
PROC find line = ( POINT p1, p2 )LINE:
IF x OF p1 = x OF p2 THEN
# the line ... |
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 ... | #11l | 11l | F intersection_point(ray_direction, ray_point, plane_normal, plane_point)
R ray_point - ray_direction * dot(ray_point - plane_point, plane_normal) / dot(ray_direction, plane_normal)
print(‘The ray intersects the plane at ’intersection_point((0.0, -1.0, -1.0), (0.0, 0.0, 10.0), (0.0, 0.0, 1.0), (0.0, 0.0, 5.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)
... | #8086_Assembly | 8086 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... | #AutoIt | AutoIt |
#include <Date.au3>
#include <Array.au3>
$array = Five_weekends(1)
_ArrayDisplay($array)
$array = Five_weekends(2)
_ArrayDisplay($array)
$array = Five_weekends(3)
_ArrayDisplay($array)
Func Five_weekends($ret = 1)
If $ret < 1 Or $ret > 3 Then Return SetError(1, 0, 0)
Local $avDateArray[1]
Local $avYearArray[1]
... |
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 ... | #F.23 | F# |
// Nigel Galloway: May 21st., 2019
let fN g=let g=int64(sqrt(float(pown g (int(g-1L)))))+1L in (Seq.unfold(fun(n,g)->Some(n,(n+g,g+2L))))(g*g,g*2L+1L)
let fG n g=Array.unfold(fun n->if n=0L then None else let n,g=System.Math.DivRem(n,g) in Some(g,n)) n
let fL g=let n=set[0L..g-1L] in Seq.find(fun x->set(fG x g)=n) (f... |
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... | #Bracmat | Bracmat | ( (sqrt=.!arg^1/2)
& (log=.e\L!arg)
& (A=x2d (=.!arg^2) log (=.!arg*pi))
& ( B
= d2x sqrt (=.e^!arg) (=.!arg*pi^-1)
)
& ( compose
= f g
. !arg:(?f.?g)
& '(.($f)$(($g)$!arg))
)
& whl
' ( !A:%?F ?A
& !B:%?G ?B
& out$((compose$(!F.!G))$3210)
)
) |
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... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* declare a typedef for a function pointer */
typedef double (*Class2Func)(double);
/*A couple of functions with the above prototype */
double functionA( double v)
{
return v*v*v;
}
double functionB(double v)
{
return exp(log(v)/3);
}
/* A function t... |
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... | #Forth | Forth | 30 CONSTANT WIDTH
30 CONSTANT HEIGHT
WIDTH HEIGHT * CONSTANT SIZE
1 VALUE SEED
: (RAND) ( -- u) \ xorshift generator
SEED DUP 13 LSHIFT XOR
DUP 17 RSHIFT XOR
DUP 5 LSHIFT XOR
DUP TO SEED ;
10000 CONSTANT RANGE
100 CONSTANT GROW
1 CONSTANT BURN
: RAND ( -- u) ... |
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 "... | #Lua | Lua |
local envs = { }
for i = 1, 12 do
-- fallback to the global environment for io and math
envs[i] = setmetatable({ count = 0, n = i }, { __index = _G })
end
local code = [[
io.write(("% 4d"):format(n))
if n ~= 1 then
count = count + 1
n = (n % 2 == 1) and 3 * n + 1 or math.floor(n / 2)
end
]]
while ... |
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 "... | #Nim | Nim | import strformat
const Jobs = 12
type Environment = object
sequence: int
count: int
var
env: array[Jobs, Environment]
sequence, count: ptr int
#---------------------------------------------------------------------------------------------------
proc hail() =
stdout.write fmt"{sequence[]: 4d}"
if se... |
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
| #Common_Lisp | Common Lisp | (defun flatten (structure)
(cond ((null structure) nil)
((atom structure) (list structure))
(t (mapcan #'flatten structure)))) |
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 ... | #MiniScript | MiniScript | // Flipping Bits game.
// Transform a start grid to an end grid by flipping rows or columns.
size = 3
board = []
goal = []
for i in range(1,size)
row = []
for j in range(1,size)
row.push (rnd > 0.5)
end for
board.push row
goal.push row[0:]
end for
flipRow = function(n)
for j in ran... |
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 ... | #Nim | Nim | import random, strformat, strutils
type
Bit = range[0..1]
Board = array[3, array[3, Bit]]
#---------------------------------------------------------------------------------------------------
func flipRow(board: var Board; row: int) =
for cell in board[row].mitems:
cell = 1 - cell
#------------------... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | f = Compile[{{ll, _Integer}, {n, _Integer}},
Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2},
l = Abs[ll];
digitcount = Floor[Log[10, l]];
log10power = Log[10, pwr];
raised = -1;
found = 0;
While[found < n,
raised++;
firstdigits = Floor[10^(FractionalPart[lo... |
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 ... | #Nim | Nim | import math, strformat
const
Lfloat64 = pow(2.0, 64)
Log10_2_64 = int(Lfloat64 * log10(2.0))
#---------------------------------------------------------------------------------------------------
func ordinal(n: int): string =
case n
of 1: "1st"
of 2: "2nd"
of 3: "3rd"
else: $n & "th"
#-------------... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | multiplier[n1_,n2_]:=n1 n2 #&
num={2,4,2+4};
numi=1/num;
multiplierfuncs = multiplier @@@ Transpose[{num, numi}];
|
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... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
module FirstClassNums
{
Main() : void
{
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 multiplier = fun (a, b) {fun (c) {a * b * c}};
... |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #PARI.2FGP | PARI/GP | label
jumpto;
begin
...
jumpto:
some statement;
...
goto jumpto;
...
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... | #Pascal | Pascal | label
jumpto;
begin
...
jumpto:
some statement;
...
goto jumpto;
...
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... | #D | D | import std.stdio, std.conv;
void floydTriangle(in uint n) {
immutable lowerLeftCorner = n * (n - 1) / 2 + 1;
foreach (r; 0 .. n)
foreach (c; 0 .. r + 1)
writef("%*d%c",
text(lowerLeftCorner + c).length,
r * (r + 1) / 2 + c + 1,
c == ... |
http://rosettacode.org/wiki/Floyd-Warshall_algorithm | Floyd-Warshall algorithm | The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.
Task
Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ... | #Mercury | Mercury | :- module floyd_warshall_task.
:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
:- implementation.
:- import_module float.
:- import_module int.
:- import_module list.
:- import_module string.
:- import_module version_array2d.
%%%-----------------------------------------------... |
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 ... | #Simula | Simula | BEGIN
INTEGER PROCEDURE multiply(x, y);
INTEGER x, y;
BEGIN
multiply := x * y
END;
Outint(multiply(7,8), 2);
Outimage
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 ... | #Slate | Slate | define: #multiply -> [| :a :b | a * b]. |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Perl | Perl | sub dif {
my @s = @_;
map { $s[$_+1] - $s[$_] } 0 .. $#s-1
}
@a = qw<90 47 58 29 22 32 55 5 55 73>;
while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" } |
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.
| #Scheme | Scheme | (load "srfi-54.scm")
(load "srfi-54.scm") ;; Don't ask.
(define x 295643087.65432)
(dotimes (i 4)
(print (cat x 25 3.0 #\0 (list #\, (- 4 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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const proc: main is func
local
const float: r is 7.125;
begin
writeln( r digits 3 lpad 9);
writeln(-r digits 3 lpad 9);
writeln( r digits 3 lpad0 9);
writeln(-r digits 3 lpad0 9);
writeln( r digits 3);
writeln(-r digits 3);
end func; |
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 ... | #PL.2FI | PL/I |
/* 4-BIT ADDER */
TEST: PROCEDURE OPTIONS (MAIN);
DECLARE CARRY_IN BIT (1) STATIC INITIAL ('0'B) ALIGNED;
declare (m, n, sum)(4) bit(1) aligned;
declare i fixed binary;
get edit (m, n) (b(1));
put edit (m, ' + ', n, ' = ') (4 b, a);
do i = 4 to 1 by -1;
call full_adder ((carry_in), m(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... | #Haskell | Haskell | import Data.List (sort)
fivenum :: [Double] -> [Double]
fivenum [] = []
fivenum xs
| l >= 5 =
fmap
( (/ 2)
. ( (+) . (!!) s
. floor
<*> (!!) s . ceiling
)
. pred
)
[1, q, succ l / 2, succ l - q, l]
| otherwise = s
where
l ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Action.21 | Action! | PROC Main()
DEFINE PTR="CARD"
DEFINE COUNT="23"
PTR ARRAY perm(COUNT)
CHAR ARRAY s,missing=[4 0 0 0 0]
BYTE i,j
perm(0)="ABCD" perm(1)="CABD"
perm(2)="ACDB" perm(3)="DACB"
perm(4)="BCDA" perm(5)="ACBD"
perm(6)="ADCB" perm(7)="CDAB"
perm(8)="DABC" perm(9)="BCAD"
perm(10)="CADB" perm(11)="CDB... |
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... | #AppleScript | AppleScript | -- LAST SUNDAYS OF YEAR ------------------------------------------------------
-- lastSundaysOfYear :: Int -> [Date]
on lastSundaysOfYear(y)
-- lastWeekDaysOfYear :: Int -> Int -> [Date]
script lastWeekDaysOfYear
on |λ|(intYear, iWeekday)
-- lastWeekDay :: Int -> Int -> Date
... |
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) .
| #APL | APL |
⍝ APL has a powerful operator the « dyadic domino » to solve a system of N linear equations with N unknowns
⍝ We use it first to solve the a and b, defining the 2 lines as y = ax + b, with the x and y of the given points
⍝ The system of equations for first line will be:
⍝ 0 = 4a + b
⍝ 10 = 6a + b
⍝ The two argument... |
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) .
| #Arturo | Arturo | define :point [x,y][]
define :line [a, b][
init: [
this\slope: div this\b\y-this\a\y this\b\x-this\a\x
this\yInt: this\a\y - this\slope*this\a\x
]
]
evalX: function [line, x][
line\yInt + line\slope * x
]
intersect: function [line1, line2][
x: div line2\yInt-line1\yInt line1\slope-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 ... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE REALPTR="CARD"
TYPE VectorR=[REALPTR x,y,z]
PROC PrintVector(VectorR POINTER v)
Print("(") PrintR(v.x)
Print(",") PrintR(v.y)
Print(",") PrintR(v.z)
Print(")")
RETURN
PROC Vector(REAL POINTER vx,vy,vz VectorR POINTER v)
v.x=vx v.y=vy v.z=vz
RETURN
... |
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 ... | #Ada | Ada | with Ada.Numerics.Generic_Real_Arrays;
with Ada.Text_IO;
procedure Intersection is
type Real is new Long_Float;
package Real_Arrays is
new Ada.Numerics.Generic_Real_Arrays (Real => Real);
use Real_Arrays;
package Real_IO is
new Ada.Text_IO.Float_IO (Num => Real);
subtype Vector_3D i... |
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)
... | #8th | 8th |
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... | #AWK | AWK |
# usage: awk -f 5weekends.awk cal.txt
# Filter a file of month-calendars, such as
# ...
## January 1901
## Mo Tu We Th Fr Sa Su
## 1 2 3 4 5 6
## 7 8 9 10 11 12 13
## 14 15 16 17 18 19 20
## 21 22 23 24 25 26 27
## 28 29 30 31
# ...
## March 1901
## Mo Tu We Th Fr S... |
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 ... | #Factor | Factor | USING: assocs formatting fry kernel math math.functions
math.parser math.ranges math.statistics sequences ;
IN: rosetta-code.A260182
: pandigital? ( n base -- ? )
[ >base histogram assoc-size ] keep >= ;
! Return the smallest decimal integer square root whose squared
! digit length in base n is at least n.
: se... |
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 ... | #Forth | Forth |
#! /usr/bin/gforth-fast
: 2^ 1 swap lshift ;
: sq s" dup *" evaluate ; immediate
: min-root ( -- n ) \ minimum root that can be pandigitial
base @ s>f fdup 1e f- 0.5e f* f** f>s ;
: pandigital? ( n -- f )
0 swap \ bitmask
begin
base @ /mod
>r 2^ or r>
dup 0= until drop
... |
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... | #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));
var functionTuples = new[]
{
(forward: Math.Sin, backward: Math.Asin),
... |
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... | #Fortran | Fortran | module ForestFireModel
implicit none
type :: forestfire
integer, dimension(:,:,:), allocatable :: field
integer :: width, height
integer :: swapu
real :: prob_tree, prob_f, prob_p
end type forestfire
integer, parameter :: &
empty = 0, &
tree = 1, &
burning = 2
pr... |
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 "... | #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8hail ORDER_PP_FN( \
8fn(8N, 8cond((8equal(8N, 1), 1) \
(8is_0(8remainder(8N, 2)), 8quotient(8N, 2)) \
(8else, 8inc(8times(8N, 3))))) )
#define ORDER_PP_DEF_8h_loop ORDER_PP_FN( \
8... |
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 "... | #Perl | Perl |
use strict;
use warnings;
use Safe;
sub hail_next {
my $n = shift;
return 1 if $n == 1;
return $n * 3 + 1 if $n % 2;
$n / 2;
};
my @enviornments;
for my $initial ( 1..12 ) {
my $env = Safe->new;
${ $env->varglob('value') } = $initial;
${ $env->varglob('count') } = 0;
$env->share('&ha... |
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
| #Crystal | Crystal |
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
|
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 ... | #OCaml | OCaml | module FlipGame =
struct
type t = bool array array
let make side = Array.make_matrix side side false
let flipcol b n =
for i = 0 to (Array.length b - 1) do
b.(n).(i) <- not b.(n).(i)
done
let fliprow b n =
for i = 0 to (Array.length b - 1) do
b.(i).(n) <- not b.(i).(n)
done
... |
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 ... | #Pascal | Pascal | program Power2FirstDigits;
uses
sysutils,
strUtils;
const
{$IFDEF FPC}
{$MODE DELPHI}
ld10 :double = ln(2)/ln(10);// thats 1/log2(10)
{$ELSE}
ld10 = 0.30102999566398119521373889472449;
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
... |
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... | #Never | Never |
func multiplier(a : float, b : float) -> (float) -> float {
let func(m : float) -> float { a * b * m }
}
func main() -> int {
var x = 2.0;
var xi = 0.5;
var y = 4.0;
var yi = 0.25;
var z = x + y;
var zi = 1.0 / z;
var f = [ x, y, z ] : float;
var i = [ xi, yi, zi ] : float;
... |
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... | #Nim | Nim |
func multiplier(a, b: float): auto =
let ab = a * b
result = func(c: float): float = ab * c
let
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
let list = [x, y, z]
let invlist = [xi, yi, zi]
for i in 0..list.high:
# Create a multiplier function...
let f = multiplier(list... |
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... | #Perl | Perl | FORK:
# some code
goto FORK; |
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... | #Phix | Phix | without js -- (no goto in JavaScript)
procedure p()
goto :but_print
puts(1,"This will not be printed...\n")
::but_print
puts(1,"...but this will\n")
end procedure
p()
|
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... | #Elixir | Elixir | defmodule Floyd do
def triangle(n) do
max = trunc(n * (n + 1) / 2)
widths = for m <- (max - n + 1)..max, do: (m |> Integer.to_string |> String.length) + 1
format = Enum.map(widths, fn wide -> "~#{wide}w" end) |> List.to_tuple
line(n, 0, 1, format)
end
def line(n, n, _, _), do: :ok
def line(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... | #Erlang | Erlang |
-module( floyds_triangle ).
-export( [integers/1, print/1, strings/1, task/0] ).
integers( N ) ->
lists:reverse( integers_reversed(N) ).
print( N ) ->
[io:fwrite("~s~n", [lists:flatten(X)]) || X <- strings(N)].
strings( N ) ->
Strings_reversed = [strings_from_integers(X) || X <- integ... |
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 ... | #Modula-2 | Modula-2 | MODULE FloydWarshall;
FROM FormatString IMPORT FormatString;
FROM SpecialReals IMPORT Infinity;
FROM Terminal IMPORT ReadChar,WriteString,WriteLn;
CONST NUM_VERTICIES = 4;
TYPE
IntArray = ARRAY[0..NUM_VERTICIES-1],[0..NUM_VERTICIES-1] OF INTEGER;
RealArray = ARRAY[0..NUM_VERTICIES-1],[0..NUM_VERTICIES-1] OF R... |
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 ... | #Smalltalk | Smalltalk | |mul|
mul := [ :a :b | a * b ]. |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #SNOBOL4 | SNOBOL4 | define('multiply(a,b)') :(mul_end)
multiply multiply = a * b :(return)
mul_end
* Test
output = multiply(10.1,12.2)
output = multiply(10,12)
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... | #Phix | Phix | with javascript_semantics
function fwd_diff_n(sequence s, integer order)
assert(order<length(s))
s = deep_copy(s)
for i=1 to order do
for j=1 to length(s)-1 do
s[j] = s[j+1]-s[j]
end for
s = s[1..-2]
end for
return s
end function
constant s = {90, 47, 58, 29, 22... |
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.
| #Sidef | Sidef | printf("%09.3f\n", 7.125); |
http://rosettacode.org/wiki/Formatted_numeric_output | Formatted numeric output | Task
Express a number in decimal as a fixed-length string with leading zeros.
For example, the number 7.125 could be expressed as 00007.125.
| #Smalltalk | Smalltalk | Transcript show: (7.125 printPaddedWith: $0 to: 3.6); cr.
"output: 007.125000" |
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 ... | #PowerShell | PowerShell | function bxor2 ( [byte] $a, [byte] $b )
{
$out1 = $a -band ( -bnot $b )
$out2 = ( -bnot $a ) -band $b
$out1 -bor $out2
}
function hadder ( [byte] $a, [byte] $b )
{
@{
"S"=bxor2 $a $b
"C"=$a -band $b
}
}
function fadder ( [byte] $a, [byte] $b, [byte] $cd )
{
$out1 = hadder $cd... |
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... | #J | J | midpts=: (1 + #) <:@(] , -:@[ , -) -:@<.@-:@(3 + #) NB. mid points of y
quartiles=: -:@(+/)@((<. ,: >.)@midpts { /:~@]) NB. quartiles of y
fivenum=: <./ , quartiles , >./ NB. fivenum summary of y |
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... | #Java | Java | import java.util.Arrays;
public class Fivenum {
static double median(double[] x, int start, int endInclusive) {
int size = endInclusive - start + 1;
if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty");
int m = start + size / 2;
return (size % 2 == 1) ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Ada | Ada | with Ada.Text_IO;
procedure Missing_Permutations is
subtype Permutation_Character is Character range 'A' .. 'D';
Character_Count : constant :=
1 + Permutation_Character'Pos (Permutation_Character'Last)
- Permutation_Character'Pos (Permutation_Character'First);
type Permutation_String is
... |
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... | #Arturo | Arturo | lastSundayForMonth: function [m,y][
ensure -> in? m 1..12
daysOfMonth: @[0 31 (leap? y)? -> 28 -> 27 31 30 31 30 31 31 30 31 30 31]
loop range get daysOfMonth m 1 [d][
dt: to :date.format:"yyyy-M-dd" ~"|y|-|m|-|d|"
if dt\Day = "Sunday" -> return dt
]
]
getLastSundays: function [year]... |
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) .
| #AutoHotkey | AutoHotkey | LineIntersectionByPoints(L1, L2){
x1 := L1[1,1], y1 := L1[1,2]
x2 := L1[2,1], y2 := L1[2,2]
x3 := L2[1,1], y3 := L2[1,2]
x4 := L2[2,1], y4 := L2[2,2]
return ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) ", "
. ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*... |
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 ... | #APL | APL | ⍝ Find the intersection of a line with a plane
⍝ The intersection I belongs to a line defined by point L and vector V, translates to:
⍝ A real parameter t exists, that satisfies I = L + tV
⍝ I belongs to the plan defined by point P and normal vector N. This means that any two points of the plane make a vector
⍝ norm... |
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)
... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program FizzBuzz64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM... |
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... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
DIM Month$(12)
Month$() = "","January","February","March","April","May","June", \
\ "July","August","September","October","November","December"
num% = 0
FOR year% = 1900 TO 2100
PRINT ; year% ": " ;
oldnum% = num%
FOR month% = 1 TO ... |
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 ... | #Go | Go | package main
import (
"fmt"
"math/big"
"strconv"
"time"
)
const maxBase = 27
const minSq36 = "1023456789abcdefghijklmnopqrstuvwxyz"
const minSq36x = "10123456789abcdefghijklmnopqrstuvwxyz"
var bigZero = new(big.Int)
var bigOne = new(big.Int).SetUint64(1)
func containsAll(sq string, base int) boo... |
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... | #C.2B.2B | C++ |
#include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) {... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Go | Go | package main
import (
"fmt"
"math/rand"
"strings"
)
const (
rows = 20
cols = 30
p = .01
f = .001
)
const rx = rows + 2
const cx = cols + 2
func main() {
odd := make([]byte, rx*cx)
even := make([]byte, rx*cx)
for r := 1; r <= rows; r++ {
for c := 1; c <= 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 "... | #Phix | Phix | with javascript_semantics
function hail(integer n)
if remainder(n,2)=0 then
n /= 2
else
n = 3*n+1
end if
return n
end function
sequence hails = tagset(12),
counts = repeat(0,12),
results = columnize({hails})
function step(integer edx)
integer n = hails[edx]
... |
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
| #D | D | import std.stdio, std.algorithm, std.conv, std.range;
struct TreeList(T) {
union { // A tagged union
TreeList[] arr; // it's a node
T data; // It's a leaf.
}
bool isArray = true; // = Contains an arr on default.
static TreeList opCall(A...)(A items) pure nothrow {
TreeList re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.