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... | #F.23 | F# | let jdn (year, month, day) =
let a = (14 - month) / 12
let y = year + 4800 - a
let m = month + 12 * a - 3
day + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 - 32045
let date_from_jdn jdn =
let j = jdn + 32044
let g = j / 146097
let dg = j % 146097
let c = (dg / 36524 + 1) * 3 / 4
let ... |
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) .
| #JavaScript | JavaScript | (() => {
'use strict';
// INTERSECTION OF TWO LINES ----------------------------------------------
// intersection :: Line -> Line -> Either String (Float, Float)
const intersection = (ab, pq) => {
const
delta = f => x => f(fst(x)) - f(snd(x)),
[abDX, pqDX, abDY, pqDY] ... |
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 ... | #Lua | Lua | function make(xval, yval, zval)
return {x=xval, y=yval, z=zval}
end
function plus(lhs, rhs)
return make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
end
function minus(lhs, rhs)
return make(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
end
function times(lhs, scale)
return make(scale * lhs.x, scale... |
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)
... | #Arc | Arc | (for n 1 100
(prn:if
(multiple n 15) 'FizzBuzz
(multiple n 5) 'Buzz
(multiple n 3) 'Fizz
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... | #FreeBASIC | FreeBASIC | ' version 23-06-2015
' compile with: fbc -s console
Function wd(m As Integer, d As Integer, y As Integer) As Integer
' Zellerish
' 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday
' 4 = Thursday, 5 = Friday, 6 = Saturday
If m < 3 Then ' If m = 1 Or m = 2 Then
m += 12
y -= 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 ... | #Wren | Wren | import "/big" for BigInt
import "/math" for Nums
import "/fmt" for Conv, Fmt
var maxBase = 21
var minSq36 = "1023456789abcdefghijklmnopqrstuvwxyz"
var minSq36x = "10123456789abcdefghijklmnopqrstuvwxyz"
var containsAll = Fn.new { |sq, base|
var found = List.filled(maxBase, 0)
var le = sq.count
var reps... |
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... | #Groovy | Groovy | def compose = { f, g -> { x -> 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... | #Haskell | Haskell | cube :: Floating a => a -> a
cube x = x ** 3.0
croot :: Floating a => a -> a
croot x = x ** (1/3)
-- compose already exists in Haskell as the `.` operator
-- compose :: (a -> b) -> (b -> c) -> a -> c
-- compose f g = \x -> g (f x)
funclist :: Floating a => [a -> a]
funclist = [sin, cos, cube ]
invlist :: Floa... |
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... | #Perl | Perl |
use 5.10.0;
my $w = `tput cols` - 1;
my $h = `tput lines` - 1;
my $r = "\033[H";
my ($green, $red, $yellow, $norm) = ("\033[32m", "\033[31m", "\033[33m", "\033[m");
my $tree_prob = .05;
my $burn_prob = .0002;
my @forest = map([ map((rand(1) < $tree_prob) ? 1 : 0, 1 .. $w) ], 1 .. $h);
sub iterate {
my @new... |
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
| #FreeBASIC | FreeBASIC | Dim As String sComma, sString, sFlatter
Dim As Short siCount
sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString)
If Instr("[] ,", Mid(sString, siCount, 1)) = 0 Then
sFlatter += sComma + Mid(sString, siCount, 1)
sComma = ", "
End If
Next siCount
Print... |
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... | #Lua | Lua | function print_floyd(rows)
local c = 1
local h = rows*(rows-1)/2
for i=1,rows do
local s = ""
for j=1,i do
for k=1, #tostring(h+j)-#tostring(c) do
s = s .. " "
end
if j ~= 1 then s = s .. " " end
s = s .. tostring(c)
c = c + 1
end
print(s)
end
end
print_floyd(5)
print_floyd(14) |
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 ... | #SequenceL | SequenceL | import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;
ARC ::= (To: int, Weight: float);
arc(t,w) := (To: t, Weight: w);
VERTEX ::= (Label: int, Arcs: ARC(1));
vertex(l,arcs(1)) := (Label: l, Arcs: arcs);
getArcsFrom(vertex, graph(1)) :=
let
index := firstIndexOf(graph.Label, vertex);
in
... |
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 ... | #XPL0 | XPL0 | func Multiply(A, B); \the characters in parentheses are only a comment
int A, B; \the arguments are actually declared here, as integers
return A*B; \the default (undeclared) function type is integer
\no need to enclose a single statement in brackets
func real FloatM... |
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... | #Standard_ML | Standard ML | fun forward_difference xs = ListPair.map op- (tl xs, xs)
fun nth_forward_difference n xs =
if n = 0 then
xs
else
nth_forward_difference (n-1) (forward_difference xs) |
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 ... | #SystemVerilog | SystemVerilog |
module Half_Adder( input a, b, output s, c );
assign s = a ^ b;
assign c = a & b;
endmodule
module Full_Adder( input a, b, c_in, output s, c_out );
wire s_ha1, c_ha1, c_ha2;
Half_Adder ha1( .a(c_in), .b(a), .s(s_ha1), .c(c_ha1) );
Half_Adder ha2( .a(s_ha1), .b(b), .s(s), .c(c_ha2) );
assign c_out = ... |
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... | #Stata | Stata | clear
set seed 17760704
qui set obs 10000
gen x=rnormal() |
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... | #VBA | VBA | Option Base 1
Private Function median(tbl As Variant, lo As Integer, hi As Integer)
Dim l As Integer: l = hi - lo + 1
Dim m As Integer: m = lo + WorksheetFunction.Floor_Precise(l / 2)
If l Mod 2 = 1 Then
median = tbl(m)
Else
median = (tbl(m - 1) + tbl(m)) / 2
End if
End Function
Pri... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #D | D | void main() {
import std.stdio, std.string, std.algorithm, std.range, std.conv;
immutable perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
BADC BDAC CBDA DBCA DCAB".split;
// Version 1: test all permutations.... |
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... | #Factor | Factor | USING: calendar calendar.format command-line io kernel math math.parser
sequences ;
IN: rosetta-code.last-sunday
: parse-year ( -- ts ) (command-line) second string>number <year> ;
: print-last-sun ( ts -- ) last-sunday-of-month (timestamp>ymd) nl ;
: inc-month ( ts -- ts' ) 1 months time+ ;
: proces... |
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... | #FBSL | FBSL | #APPTYPE CONSOLE
DIM date AS INTEGER, dayname AS STRING
FOR DIM i = 1 TO 12
FOR DIM j = 31 DOWNTO 1
date = 20130000 + (i * 100) + j
IF CHECKDATE(i, j, 2013) THEN
dayname = DATECONV(date, "dddd")
IF dayname = "Sunday" THEN
PRINT 2013, " ", i, " ", j
... |
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) .
| #jq | jq | # determinant of 2x2 matrix
def det(a;b;c;d): a*d - b*c ;
# Input: an array representing a line (L1)
# Output: the intersection of L1 and L2 unless the lines are judged to be parallel
# This implementation uses "destructuring" to assign local variables
def lineIntersection(L2):
. as [[$ax,$ay], [$bx,$by]]
| L2... |
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) .
| #Julia | Julia | struct Point{T}
x::T
y::T
end
struct Line{T}
s::Point{T}
e::Point{T}
end
function intersection(l1::Line{T}, l2::Line{T}) where T<:Real
a1 = l1.e.y - l1.s.y
b1 = l1.s.x - l1.e.x
c1 = a1 * l1.s.x + b1 * l1.s.y
a2 = l2.e.y - l2.s.y
b2 = l2.s.x - l2.e.x
c2 = a2 * l2.s.x + b2 * ... |
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 ... | #Maple | Maple | geom3d:-plane(P, [geom3d:-point(p1,0,0,5), [0,0,1]]);
geom3d:-line(L, [geom3d:-point(p2,0,0,10), [0,-1,-1]]);
geom3d:-intersection(px,L,P);
geom3d:-detail(px); |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | RegionIntersection[InfiniteLine[{0, 0, 10}, {0, -1, -1}], InfinitePlane[{0, 0, 5}, {{0, 1, 0}, {1, 0, 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)
... | #ARM_Assembly | ARM Assembly |
/ * linux GAS */
.global _start
.data
Fizz: .ascii "Fizz\n"
Buzz: .ascii "Buzz\n"
FizzAndBuzz: .ascii "FizzBuzz\n"
numstr_buffer: .skip 3
newLine: .ascii "\n"
.text
_start:
bl FizzBuzz
mov r7, #1
mov r0, #0
svc #0
FizzBuzz:
push {lr}
mov r9, #100
fizzbuzz_loop:
mov r0, r9
... |
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... | #Gambas | Gambas | Public Sub Main()
Dim aMonth As Short[] = [1, 3, 5, 7, 8, 10, 12] 'All 31 day months
Dim aMMStore As New String[] 'To store results
Dim siYear, siMonth, siCount As Short 'Various variables
Dim dDay As Date ... |
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 ... | #zkl | zkl | fcn squareSearch(B){
basenumerals:=B.pump(String,T("toString",B)); // 13 --> "0123456789abc"
highest:=("10"+basenumerals[2,*]).toInt(B); // 13 --> "10" "23456789abc"
foreach n in ([highest.toFloat().sqrt().toInt() .. highest]){
ns:=(n*n).toString(B);
if(""==(basenumerals - ns) ) return(n.toString(B... |
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... | #Icon_and_Unicon | Icon and Unicon | link compose
procedure main(arglist)
fun := [sin,cos,cube]
inv := [asin,acos,cuberoot]
x := 0.5
every i := 1 to *inv do
write("f(",x,") := ", compose(inv[i],fun[i])(x))
end
procedure cube(x)
return x*x*x
end
procedure cuberoot(x)
return x ^ (1./3)
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... | #J | J | sin=: 1&o.
cos=: 2&o.
cube=: ^&3
square=: *:
unqo=: `:6
unqcol=: `:0
quot=: 1 :'{.u`'''''
A=: sin`cos`cube`square
B=: monad def'y unqo inv quot'"0 A
BA=. A dyad def'x unqo@(y unqo) quot'"0 B |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #Phix | Phix | --
-- demo\rosetta\Forest_fire.exw
-- ============================
--
-- A burning cell turns into an empty cell
-- A tree will burn if at least one neighbor is burning
-- A tree ignites with probability F even if no neighbor is burning
-- An empty space fills with a tree with probability P
--
-- Draws bigger "pix... |
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
| #Frink | Frink |
a = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
println[flatten[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... | #Maple | Maple | floyd := proc(rows)
local num, numRows, numInRow, i, digits;
digits := Array([]);
for i to 2 do
num := 1;
numRows := 1;
numInRow := 1;
while numRows <= rows do
if i = 2 then
printf(cat("%", digits[numInRow], "a "), num);
end if;
num := num + 1;
if i = 1 and numRows = rows then
digits(numI... |
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 ... | #Sidef | Sidef | func floyd_warshall(n, edge) {
var dist = n.of {|i| n.of { |j| i == j ? 0 : Inf }}
var nxt = n.of { n.of(nil) }
for u,v,w in edge {
dist[u-1][v-1] = w
nxt[u-1][v-1] = v-1
}
[^n] * 3 -> cartesian { |k, i, j|
if (dist[i][j] > dist[i][k]+dist[k][j]) {
dist[i][j] ... |
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 ... | #XSLT | XSLT | <xsl:template name="multiply">
<xsl:param name="a" select="2"/>
<xsl:param name="b" select="3"/>
<xsl:value-of select="$a * $b"/>
</xsl:template> |
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 ... | #Yorick | Yorick | func multiply(x, y) {
return x * y;
} |
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... | #Stata | Stata | gen y=x[_n+1]-x[_n] |
http://rosettacode.org/wiki/Forward_difference | Forward difference | Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer elem... | #Swift | Swift | func forwardsDifference<T: SignedNumeric>(of arr: [T]) -> [T] {
return zip(arr.dropFirst(), arr).map({ $0.0 - $0.1 })
}
func nthForwardsDifference<T: SignedNumeric>(of arr: [T], n: Int) -> [T] {
assert(n >= 0)
switch (arr, n) {
case ([], _):
return []
case let (arr, 0):
return arr
case let (arr,... |
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 ... | #Tcl | Tcl | package require Tcl 8.5
# Create our little language
proc pins args {
# Just declaration...
foreach p $args {upvar 1 $p v}
}
proc gate {name pins body} {
foreach p $pins {
lappend args _$p
append v " \$_$p $p"
}
proc $name $args "upvar 1 $v;$body"
}
# Fundamental gates; these are the only ones... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Imports System.Text
Module Module1
<Extension()>
Function AsString(Of T)(c As ICollection(Of T), Optional format As String = "{0}") As String
Dim sb As New StringBuilder("[")
Dim it = c.GetEnumerator()
If it.MoveNext() Then
sb.Appen... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Delphi | Delphi |
;; use the obvious methos
(lib 'list) ; for (permutations) function
;; input
(define perms '
(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB))
;; generate all permutations
(define all-perms (map list->string (permutations '(A B C D))))
→ all-p... |
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... | #Fortran | Fortran | D = DAYNUM(Y,M,D) !Daynumber from date.
DAYNUM(Y,M,D) = D !Date parts from a day number. |
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... | #Free_Pascal | Free Pascal |
program sundays;
Uses sysutils;
type
MonthLength = Array[1..13] of Integer;
procedure sund(y : Integer);
var
dt : TDateTime;
m,mm : Integer;
len : MonthLength;
begin
len[1] := 31; len[2] := 28; len[3] := 31; len[4] := 30;
len[5] := 31; len[6] := 30; len[7] := 31; len[8] := 31;
len[9] := 30; len... |
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) .
| #Kotlin | Kotlin | // version 1.1.2
class PointF(val x: Float, val y: Float) {
override fun toString() = "{$x, $y}"
}
class LineF(val s: PointF, val e: PointF)
fun findIntersection(l1: LineF, l2: LineF): PointF {
val a1 = l1.e.y - l1.s.y
val b1 = l1.s.x - l1.e.x
val c1 = a1 * l1.s.x + b1 * l1.s.y
val a2 = l2.e... |
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 ... | #MATLAB | MATLAB | function point = intersectPoint(rayVector, rayPoint, planeNormal, planePoint)
pdiff = rayPoint - planePoint;
prod1 = dot(pdiff, planeNormal);
prod2 = dot(rayVector, planeNormal);
prod3 = prod1 / prod2;
point = rayPoint - rayVector * prod3; |
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 ... | #Modula-2 | Modula-2 | MODULE LinePlane;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE
Vector3D = RECORD
x,y,z : REAL;
END;
PROCEDURE Minus(lhs,rhs : Vector3D) : Vector3D;
VAR out : Vector3D;
BEGIN
RETURN Vector3D{lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z};
END Minus;
PROCEDURE T... |
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)
... | #Arturo | Arturo | loop 1..100 [x][
case []
when? [0=x%15] -> print "FizzBuzz"
when? [0=x%3] -> print "Fizz"
when? [0=x%5] -> print "Buzz"
else -> print x
] |
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... | #GAP | GAP | # return a list of two lists :
# first is the list of months with five weekends between years y1 and y2 (included)
# second is the list of years without such months, in the same interval
FiveWeekends := function(y1, y2)
local L, yL, badL, d, m, y;
L := [ ];
badL := [ ];
for y in [y1 .. y2] do
yL := [ ];
... |
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... | #Go | Go | package main
import (
"fmt"
"time"
)
func main() {
var n int // for task item 2
var first, last time.Time // for task item 3
haveNone := make([]int, 0, 29) // for extra credit
fmt.Println("Months with five weekends:") // for task ite... |
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... | #Java | Java | import java.util.ArrayList;
public class FirstClass{
public interface Function<A,B>{
B apply(A x);
}
public static <A,B,C> Function<A, C> compose(
final Function<B, C> f, final Function<A, B> g) {
return new Function<A, C>() {
@Override public C apply(A x) {
return f.apply(g.apply(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... | #PHP | PHP | <?php
define('WIDTH', 10);
define('HEIGHT', 10);
define('GEN_CNT', 10);
define('PAUSE', 250000);
define('TREE_PROB', 50);
define('GROW_PROB', 5);
define('FIRE_PROB', 1);
define('BARE', ' ');
define('TREE', 'A');
define('BURN', '/');
$forest = makeNewForest();
for ($i = 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
| #Gambas | Gambas | 'Code 'borrowed' from Run BASIC
Public Sub Main()
Dim sComma, sString, sFlatter As String
Dim siCount As Short
sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString)
If InStr("[] ,", Mid$(sString, siCount, 1)) = 0 Then
sFlatter = sFlatter & sComma & Mid(sString, siCount, 1)
... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
f=Function[n,
Most/@(Range@@@Partition[FindSequenceFunction[{1,2,4,7,11}]/@Range[n+1],2,1])]
TableForm[f@5,TableAlignments->Right,TableSpacing->{1,1}]
TableForm[f@14,TableAlignments->Right,TableSpacing->{1,1}]
|
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function floyds_triangle(n)
s = 1;
for k = 1 : n
disp(s : s + k - 1)
s = s + k;
end |
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 ... | #Standard_ML | Standard ML | (*
Floyd-Warshall algorithm.
See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013
*)
(*------------------------------------------------------------------(*
In this program, I introduce more "abstraction" than there was in
earlier versions, which were written ... |
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 ... | #Z80_Assembly | Z80 Assembly | doMultiply:
;returns HL = HL times A. No overflow protection.
push bc
push de
rrca ;test if A is odd or even by dividing A by 2.
jr c, isOdd
;is even
ld b,a
loop_multiplyByEvenNumber:
add hl,hl ;double A until B runs out.
djnz loop_multiplyByEvenNu... |
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 ... | #zkl | zkl | fcn multiply(x,y){x*y} |
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... | #Tcl | Tcl | proc do_fwd_diff {list} {
set previous [lindex $list 0]
set new [list]
foreach current [lrange $list 1 end] {
lappend new [expr {$current - $previous}]
set previous $current
}
return $new
}
proc fwd_diff {list order} {
while {$order >= 1} {
set list [do_fwd_diff $list]
... |
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 ... | #TorqueScript | TorqueScript | function XOR(%a, %b)
{
return (!%a && %b) || (%a && !%b);
}
//Seperated by space
function HalfAdd(%a, %b)
{
return XOR(%a, %b) SPC %a && %b;
}
//First word is the carry bit
function FullAdd(%a, %b, %c0)
{
%r1 = HalfAdd(%a, %c0);
%r2 = HalfAdd(getWord(%r1, 0), %b);
%r3 = getWord(%r1, 1) || getWord(%r2, 1);
ret... |
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... | #Wren | Wren | import "/sort" for Sort
var fivenum = Fn.new { |a|
Sort.quick(a)
var n5 = List.filled(5, 0)
var n = a.count
var n4 = ((n + 3)/2).floor / 2
var d = [1, n4, (n + 1)/2, n + 1 - n4, n]
var e = 0
for (de in d) {
var floor = (de - 1).floor
var ceil = (de - 1).ceil
n5[e] ... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #EchoLisp | EchoLisp |
;; use the obvious methos
(lib 'list) ; for (permutations) function
;; input
(define perms '
(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB))
;; generate all permutations
(define all-perms (map list->string (permutations '(A B C D))))
→ all-p... |
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... | #FreeBASIC | FreeBASIC | ' version 23-06-2015
' compile with: fbc -s console
#Ifndef TRUE ' define true and false for older freebasic versions
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function leapyear(Year_ As Integer) As Integer
' from the leapyear entry
If (Year_ Mod 4) <> 0 Then Return FALSE
If (Year_ Mo... |
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) .
| #Lua | Lua | function intersection (s1, e1, s2, e2)
local d = (s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x)
local a = s1.x * e1.y - s1.y * e1.x
local b = s2.x * e2.y - s2.y * e2.x
local x = (a * (s2.x - e2.x) - (s1.x - e1.x) * b) / d
local y = (a * (s2.y - e2.y) - (s1.y - e1.y) * b) / d
return x, y
end
... |
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 ... | #Nim | Nim |
type Vector = tuple[x, y, z: float]
func `+`(v1, v2: Vector): Vector =
## Add two vectors.
(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)
func `-`(v1, v2: Vector): Vector =
## Subtract a vector to another one.
(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z)
func `*`(v1, v2: Vector): float =
## Compute the dot prod... |
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 ... | #Perl | Perl | package Line; sub new { my ($c, $a) = @_; my $self = { P0 => $a->{P0}, u => $a->{u} } } # point / ray
package Plane; sub new { my ($c, $a) = @_; my $self = { V0 => $a->{V0}, n => $a->{n} } } # point / normal
package main;
sub dot { my $p; $p += $_[0][$_] * $_[1][$_] for 0..@{$_[0]}-1; $p } # dot product
sub vd ... |
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)
... | #AsciiDots | AsciiDots | for(int number = 1; number <= 100; ++number) {
if (number % 15 == 0) {
write("FizzBuzz");
} else {
if (number % 3 == 0) {
write("Fizz");
} else {
if (number % 5 == 0) {
write("Buzz");
} else {
write(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... | #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-M-dd')
def isLongMonth = { firstDay -> (firstDay + 31).format('dd') == '01'}
def fiveWeekends = { years ->
years.collect { year ->
(1..12).collect { month... |
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... | #JavaScript | JavaScript | // Functions as values of a variable
var cube = function (x) {
return Math.pow(x, 3);
};
var cuberoot = function (x) {
return Math.pow(x, 1 / 3);
};
// Higher order function
var compose = function (f, g) {
return function (x) {
return f(g(x));
};
};
// Storing functions in a array
var fun = [Math.sin, M... |
http://rosettacode.org/wiki/Forest_fire | Forest fire |
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the fores... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
(scl 3)
(de forestFire (Dim ProbT ProbP ProbF)
(let Grid (grid Dim Dim)
(for Col Grid
(for This Col
(=: tree (> ProbT (rand 0 1.0))) ) )
(loop
(disp Grid NIL
'((This)
(cond
((: burn) "# ")
... |
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
| #GAP | GAP | Flat([[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... | #Modula-2 | Modula-2 | MODULE FloydTriangle;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
FormatString("%4i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE Print(r : INTEGER);
VAR n,i,limit : INTEGER;
BEGIN
I... |
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 ... | #Tcl | Tcl | package require Tcl 8.5 ;# for {*} and [dict]
package require struct::graph
package require struct::graph::op
struct::graph g
set arclist {
a b
a p
b m
b c
c d
d e
e f
f q
f g
}
g node insert {*}$arclist
foreach {from to} $arclist {
set a [g arc insert $from $to]
... |
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 ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT FN m(3,4): REM call our function to produce a value of 12
20 STOP
9950 DEF FN m(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... | #Ursala | Ursala | #import std
#import nat
#import flo
nth_diff "n" = rep"n" minus*typ |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module ForwardDifference
Sub Main()
Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})
For i As UInteger = 0 To 9
Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray()))
Next
Co... |
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 ... | #UNIX_Shell | UNIX Shell | xor() {
typeset -i a=$1 b=$2
printf '%d\n' $(( (a || b) && ! (a && b) ))
}
half_adder() {
typeset -i a=$1 b=$2
printf '%d %d\n' $(xor $a $b) $(( a && b ))
}
full_adder() {
typeset -i a=$1 b=$2 c=$3
typeset -i ha0_s ha0_c ha1_s ha1_c
read ha0_s ha0_c < <(half_adder "$c" "$a")
read ha1_s ha1_c < <(h... |
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... | #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn fiveNum(v){ // V is a GSL Vector, --> min, 1st qu, median, 3rd qu, max
v.sort();
return(v.min(),v.quantile(0.25),v.median(),v.quantile(0.75),v.max())
} |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Elixir | Elixir | defmodule RC do
def find_miss_perm(head, perms) do
all_permutations(head) -- perms
end
defp all_permutations(string) do
list = String.split(string, "", trim: true)
Enum.map(permutations(list), fn x -> Enum.join(x) end)
end
defp permutations([]), do: [[]]
defp permutations(list), do: (for x <... |
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... | #Frink | Frink | d = parseDate[ARGS@0]
for m = 1 to 12
{
d = beginningOfNextMonth[d]
n = d - parseInt[d -> ### u ###] days
println[n->###yyyy-MM-dd###]
} |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Form_Open()
Dim sYear As String 'To store the year chosen
Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday
sYear = InputBox("Input year", "Last Sunday of each month") 'Get ... |
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) .
| #M2000_Interpreter | M2000 Interpreter |
Module Lineintersection (lineAtuple, lineBtuple) {
class line {
private:
slop, k
public:
function f(x) {
=x*.slop-.k
}
function intersection(b as line) {
if b.slop==.slop then
=(,)
else
x1=(.k-b.k)/(.slop-b.slop)
=(x1, .f(x1))
end if
}
Class:
module line {
read x1, y1, x2, ... |
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) .
| #Maple | Maple | with(geometry):
line(L1, [point(A,[4,0]), point(B,[6,10])]):
line(L2, [point(C,[0,3]), point(E,[10,7])]):
coordinates(intersection(x,L1,L2)); |
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 ... | #Phix | Phix | with javascript_semantics
function dot(sequence a, b) return sum(sq_mul(a,b)) end function
function intersection_point(sequence line_vector,line_point,plane_normal,plane_point)
atom a = dot(line_vector,plane_normal)
if a=0 then return "no intersection" end if
sequence diff = sq_sub(line_point,plane_point)... |
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)
... | #ASIC | ASIC | for(int number = 1; number <= 100; ++number) {
if (number % 15 == 0) {
write("FizzBuzz");
} else {
if (number % 3 == 0) {
write("Fizz");
} else {
if (number % 5 == 0) {
write("Buzz");
} else {
write(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... | #Harbour | Harbour |
PROCEDURE Main()
LOCAL y, m, d, nFound, cNames, nTot := 0, nNotFives := 0
LOCAL aFounds := {}
SET DATE ANSI
FOR y := 1900 TO 2100
nFound := 0 ; cNames := ""
FOR m := 1 TO 12
d := CtoD( hb_NtoS( y ) +"/" + hb_NtoS( m ) + "/1" )
IF CDoW( d ) == "Friday"
IF DaysInMonth... |
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... | #Julia | Julia | #!/usr/bin/julia
function compose(f::Function, g::Function)
return x -> f(g(x))
end
value = 0.5
for pair in [(sin, asin), (cos, acos), (x -> x^3, x -> x^(1/3))]
func, inverse = pair
println(compose(func, inverse)(value))
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... | #Kotlin | Kotlin | // version 1.0.6
fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) }
fun cube(d: Double) = d * d * d
fun main(args: Array<String>) {
val listA = listOf(Math::sin, Math::cos, ::cube)
val listB = listOf(Math::asin, Math::acos, Math::cbrt)
val x = 0.5
for (... |
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... | #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
/size 400 def
/rand1 { rand 2147483647 div } def
/m { moveto } bind def
/l { rlineto} bind def
/drawforest {
0 1 n 1 sub { /y exch def
0 1 n 1 sub { /x exch def
forest x get y get dup 0 eq { pop } {
1 eq { 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
| #GNU_APL | GNU APL |
⊢list←(2 3ρι6)(2 2ρ(7 8(2 2ρ9 10 11 12)13)) 'ABCD'
┏→━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃┏→━━━━┓ ┏→━━━━━━━━━┓ "ABCD"┃
┃↓1 2 3┃ ↓ 7 8┃ ┃
┃┃4 5 6┃ ┃ ┃ ┃
┃┗━━━━━┛ ┃┏→━━━━┓ 13┃ ┃
┃ ┃↓ 9 10┃ ┃ ┃
┃ ┃┃11 12┃ ┃ ┃
┃ ┃┗━━━━━┛ ┃ ┃
┃ ┗∊━━━━━━━━━┛... |
http://rosettacode.org/wiki/Floyd%27s_triangle | Floyd's triangle | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like thi... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
/* REXX ***************************************************************
* 12.07.2012 Walter Pachl - translated from Python
**********************************************************************/
Parse Arg rowcount .
if rowcount.length() == 0 th... |
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 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub PrintResult(dist As Double(,), nxt As Integer(,))
Console.WriteLine("pair dist path")
For i = 1 To nxt.GetLength(0)
For j = 1 To nxt.GetLength(1)
If i <> j Then
Dim u = i
Dim v = j
Dim... |
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... | #Visual_FoxPro | Visual FoxPro |
#DEFINE CTAB CHR(9)
LOCAL lcList As String, i As Integer, n As Integer
n = 10
LOCAL ARRAY aa[n]
CLEAR
lcList = "90,47,58,29,22,32,55,5,55,73"
FOR i = 1 TO n
aa[i] = VAL(GETWORDNUM(lcList, i, ","))
ENDFOR
ShowOutput("Original", @aa)
k = n - 1
FOR i = 1 TO n - 1
ForwardDiff(@aa)
ShowOutput("Difference " + T... |
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... | #Wren | Wren | import "/fmt" for Fmt
var forwardDiff = Fn.new { |a, order|
if (order < 0) Fiber.abort("Order must be a non-negative integer.")
if (a.count == 0) return
Fmt.print(" 0: $5d", a)
if (a.count == 1) return
if (order == 0) return
for (o in 1..order) {
var b = List.filled(a.count-1, 0)
... |
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 ... | #Verilog | Verilog |
module Half_Adder( output c, s, input a, b );
xor xor01 (s, a, b);
and and01 (c, a, b);
endmodule // Half_Adder
module Full_Adder( output c_out, s, input a, b, c_in );
wire s_ha1, c_ha1, c_ha2;
Half_Adder ha01( c_ha1, s_ha1, a, b );
Half_Adder ha02( c_ha2, s, s_ha1, c_in );
or or01 ( c_out, c_ha1, c... |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Erlang | Erlang |
-module( find_missing_permutation ).
-export( [difference/2, task/0] ).
difference( Permutate_this, Existing_permutations ) -> all_permutations( Permutate_this ) -- Existing_permutations.
task() -> difference( "ABCD", existing_permutations() ).
all_permutations( String ) -> [[A, B, C, D] || A <- String, B... |
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... | #Gambas | Gambas | Public Sub Form_Open()
Dim sYear As String 'To store the year chosen
Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday
sYear = InputBox("Input year", "Last Sunday of each month") 'Get ... |
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) .
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RegionIntersection[
InfiniteLine[{{4, 0}, {6, 10}}],
InfiniteLine[{{0, 3}, {10, 7}}]
] |
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) .
| #MATLAB | MATLAB |
function cross=intersection(line1,line2)
a=polyfit(line1(:,1),line1(:,2),1);
b=polyfit(line2(:,1),line2(:,2),1);
cross=[a(1) -1; b(1) -1]\[-a(2);-b(2)];
end
|
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 ... | #Picat | Picat |
plus(U, V) = {U[1] + V[1], U[2] + V[2], U[3] + V[3]}.
minus(U, V) = {U[1] - V[1], U[2] - V[2], U[3] - V[3]}.
times(U, S) = {U[1] * S, U[2] * S, U[3] * S}.
dot(U, V) = U[1] * V[1] + U[2] * V[2] + U[3] * V[3].
intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint) = IntersectPoint =>
Diff = minus(Ray... |
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 ... | #Prolog | Prolog |
:- initialization(main).
vector_plus(U, V, W) :-
U = p(X1, Y1, Z1),
V = p(X2, Y2, Z2),
X3 is X1 + X2,
Y3 is Y1 + Y2,
Z3 is Z1 + Z2,
W = p(X3, Y3, Z3).
vector_minus(U, V, W) :-
U = p(X1, Y1, Z1),
V = p(X2, Y2, Z2),
X3 is X1 - X2,
Y3 is Y1 - Y2,
Z3 is Z1 - Z2,
W = p(X... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #Asymptote | Asymptote | for(int number = 1; number <= 100; ++number) {
if (number % 15 == 0) {
write("FizzBuzz");
} else {
if (number % 3 == 0) {
write("Fizz");
} else {
if (number % 5 == 0) {
write("Buzz");
} else {
write(number);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.