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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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 dc = dg - c * 36524
let b = dc / 1461
let db = dc % 1461
let a = (db / 365 + 1) * 3 / 4
let da = db - a * 365
let y = g * 400 + c * 100 + b * 4 + a
let m = (da * 5 + 308) / 153 - 2
let d = da - (m + 4) * 153 / 5 + 122
(y - 4800 + (m + 2) / 12, (m + 2) % 12 + 1, d + 1)
[<EntryPoint>]
let main argv =
let year = System.Int32.Parse(argv.[0])
[for m in 1..12 do yield jdn (year,m+1,0)]
|> List.map (fun x -> date_from_jdn (x - (x+1)%7))
|> List.iter (printfn "%A")
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) .
|
#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] = apList(
[delta(fst), delta(snd)], [ab, pq]
),
determinant = abDX * pqDY - abDY * pqDX;
return determinant !== 0 ? Right((() => {
const [abD, pqD] = map(
([a, b]) => fst(a) * snd(b) - fst(b) * snd(a),
[ab, pq]
);
return apList(
[([pq, ab]) =>
(abD * pq - ab * pqD) / determinant
], [
[pqDX, abDX],
[pqDY, abDY]
]
);
})()) : Left('(Parallel lines – no intersection)');
};
// GENERIC FUNCTIONS ------------------------------------------------------
// Left :: a -> Either a b
const Left = x => ({
type: 'Either',
Left: x
});
// Right :: b -> Either a b
const Right = x => ({
type: 'Either',
Right: x
});
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const apList = (fs, xs) => //
[].concat.apply([], fs.map(f => //
[].concat.apply([], xs.map(x => [f(x)]))));
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// show :: a -> String
const show = x => JSON.stringify(x); //, null, 2);
// TEST --------------------------------------------------
// lrIntersection ::Either String Point
const lrIntersection = intersection([
[4.0, 0.0],
[6.0, 10.0]
], [
[0.0, 3.0],
[10.0, 7.0]
]);
return show(lrIntersection.Left || lrIntersection.Right);
})();
|
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 through [0, 0, 5].
|
#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 * lhs.y, scale * lhs.z)
end
function dot(lhs, rhs)
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
end
function tostr(val)
return "(" .. val.x .. ", " .. val.y .. ", " .. val.z .. ")"
end
function intersectPoint(rayVector, rayPoint, planeNormal, planePoint)
diff = minus(rayPoint, planePoint)
prod1 = dot(diff, planeNormal)
prod2 = dot(rayVector, planeNormal)
prod3 = prod1 / prod2
return minus(rayPoint, times(rayVector, prod3))
end
rv = make(0.0, -1.0, -1.0)
rp = make(0.0, 0.0, 10.0)
pn = make(0.0, 0.0, 1.0)
pp = make(0.0, 0.0, 5.0)
ip = intersectPoint(rv, rp, pn, pp)
print("The ray intersects the plane at " .. tostr(ip))
|
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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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
End If
Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7
End Function
' ------=< MAIN >=------
' only months with 31 day can have five weekends
' these months are: January, March, May, July, August, October, December
' in nr: 1, 3, 5, 7, 8, 10, 12
' the 1e day needs to be on a friday (= 5)
Dim As String month_names(1 To 12) => {"January","February","March",_
"April","May","June","July","August",_
"September","October","November","December"}
Dim As Integer m, yr, total, i, j, yr_without(200)
Dim As String answer
For yr = 1900 To 2100 ' Gregorian calendar
answer = ""
For m = 1 To 12 Step 2
If m = 9 Then m = 8
If wd(m , 1 , yr) = 5 Then
answer = answer + month_names(m) + ", "
total = total + 1
End If
Next
If answer <> "" Then
Print Using "#### | "; yr;
Print Left(answer, Len(answer) -2) ' get rid of extra " ,"
Else
i = i + 1
yr_without(i) = yr
End If
Next
Print
Print "nr of month for 1900 to 2100 that has five weekends";total
Print
Print i;" years don't have months with five weekends"
For j = 1 To i
Print yr_without(j); " ";
If j Mod 8 = 0 Then Print
Next
Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
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 a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#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 = 0
for (r in sq) {
var d = r.bytes[0] - 48
if (d > 38) d = d - 39
found[d] = found[d] + 1
if (found[d] > 1) {
reps = reps + 1
if (le - reps < base) return false
}
}
return true
}
var sumDigits = Fn.new { |n, base|
var sum = BigInt.zero
while (n > 0) {
sum = sum + (n%base)
n = n/base
}
return sum
}
var digitalRoot = Fn.new { |n, base|
while (n > base - 1) n = sumDigits.call(n, base)
return n.toSmall
}
var minStart = Fn.new { |base|
var ms = minSq36[0...base]
var nn = BigInt.fromBaseString(ms, base)
var bdr = digitalRoot.call(nn, base)
var drs = []
var ixs = []
for (n in 1...2*base) {
nn = BigInt.new(n*n)
var dr = digitalRoot.call(nn, base)
if (dr == 0) dr = n * n
if (dr == bdr) ixs.add(n)
if (n < base && dr >= bdr) drs.add(dr)
}
var inc = 1
if (ixs.count >= 2 && base != 3) inc = ixs[1] - ixs[0]
if (drs.count == 0) return [ms, inc, bdr]
var min = Nums.min(drs)
var rd = min - bdr
if (rd == 0) return [ms, inc, bdr]
if (rd == 1) return [minSq36x[0..base], 1, bdr]
var ins = minSq36[rd]
return [(minSq36[0...rd] + ins + minSq36[rd..-1])[0..base], inc, bdr]
}
var start = System.clock
var n = 2
var k = 1
var base = 2
while (true) {
if (base == 2 || (n % base) != 0) {
var nb = BigInt.new(n)
var sq = nb.square.toBaseString(base)
if (containsAll.call(sq, base)) {
var ns = Conv.itoa(n, base)
var tt = System.clock - start
Fmt.print("Base $2d:$15s² = $-27s in $8.3fs", base, ns, sq, tt)
if (base == maxBase) break
base = base + 1
var res = minStart.call(base)
var ms = res[0]
var inc = res[1]
var bdr = res[2]
k = inc
var nn = BigInt.fromBaseString(ms, base)
nb = nn.isqrt
if (nb < n + 1) nb = BigInt.new(n+1)
if (k != 1) {
while (true) {
nn = nb.square
var dr = digitalRoot.call(nn, base)
if (dr == bdr) {
n = nb.toSmall - k
break
}
nb = nb.inc
}
} else {
n = nb.toSmall - k
}
}
}
n = n + k
}
|
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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 :: Floating a => [a -> a]
invlist = [asin, acos, croot]
main :: IO ()
main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist
|
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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
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
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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 = map([ map(0, 1 .. $w) ], 1 .. $h);
for my $i (0 .. $h - 1) {
for my $j (0 .. $w - 1) {
$new[$i][$j] = $forest[$i][$j];
if ($forest[$i][$j] == 2) {
$new[$i][$j] = 3;
next;
} elsif ($forest[$i][$j] == 1) {
if (rand() < $burn_prob) {
$new[$i][$j] = 2;
next;
}
for ( [-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1] )
{
my $y = $_->[0] + $i;
next if $y < 0 || $y >= $h;
my $x = $_->[1] + $j;
next if $x < 0 || $x >= $w;
if ($forest[$y][$x] == 2) {
$new[$i][$j] = 2;
last;
}
}
} elsif (rand() < $tree_prob) {
$new[$i][$j] = 1;
} elsif ($forest[$i][$j] == 3) {
$new[$i][$j] = 0;
}
}}
@forest = @new;
}
sub forest {
print $r;
for (@forest) {
for (@$_) {
when(0) { print " "; }
when(1) { print "${green}*"}
when(2) { print "${red}&" }
when(3) { print "${yellow}&" }
}
print "\033[E\033[1G";
}
iterate;
}
forest while (1);
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#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 "["; sFlatter; "]"
Sleep
|
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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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
[] when index = 0
else
graph[index].Arcs;
getWeightTo(vertex, arcs(1)) :=
let
index := firstIndexOf(arcs.To, vertex);
in
0 when index = 0
else
arcs[index].Weight;
throughK(k, dist(2)) :=
let
newDist[i, j] := min(dist[i][k] + dist[k][j], dist[i][j]);
in
dist when k > size(dist)
else
throughK(k + 1, newDist);
floydWarshall(graph(1)) :=
let
initialResult[i,j] := 1.79769e308 when i /= j else 0
foreach i within 1 ... size(graph),
j within 1 ... size(graph);
singleResult[i,j] := getWeightTo(j, getArcsFrom(i, graph))
foreach i within 1 ... size(graph),
j within 1 ... size(graph);
start[i,j] :=
initialResult[i,j] when singleResult[i,j] = 0
else
singleResult[i,j];
in
throughK(1, start);
main() :=
let
graph := [vertex(1, [arc(3,-2)]),
vertex(2, [arc(1,4), arc(3,3)]),
vertex(3, [arc(4,2)]),
vertex(4, [arc(2,-1)])];
in
floydWarshall(graph);
|
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 created and values returned).
Related task
Function prototype
|
#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 FloatMul(A, B); \floating point version
real A, B; \arguments are declared here as floating point (doubles)
return 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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 = c_ha1 | c_ha2;
endmodule
module Multibit_Adder(a,b,s);
parameter N = 8;
input [N-1:0] a;
input [N-1:0] b;
output [N:0] s;
wire [N:0] c;
assign c[0] = 0;
assign s[N] = c[N];
generate
genvar I;
for (I=0; I<N; ++I) Full_Adder add( .a(a[I]), .b(b[I]), .s(s[I]), .c_in(c[I]), .c_out(c[I+1]) );
endgenerate
endmodule
|
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 implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#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 implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#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
Private Function fivenum(tbl As Variant) As Variant
Sort tbl, UBound(tbl)
Dim l As Integer: l = UBound(tbl)
Dim m As Integer: m = WorksheetFunction.Floor_Precise(l / 2) + l Mod 2
Dim r(5) As String
r(1) = CStr(tbl(1))
r(2) = CStr(median(tbl, 1, m))
r(3) = CStr(median(tbl, 1, l))
r(4) = CStr(median(tbl, m + 1, l))
r(5) = CStr(tbl(l))
fivenum = r
End Function
Public Sub main()
Dim x1 As Variant, x2 As Variant, x3 As Variant
x1 = [{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}]
x2 = [{36, 40, 7, 39, 41, 15}]
x3 = [{0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578}]
Debug.Print Join(fivenum(x1), " | ")
Debug.Print Join(fivenum(x2), " | ")
Debug.Print Join(fivenum(x3), " | ")
End Sub
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#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.
immutable permsSet = perms
.map!representation
.zip(true.repeat)
.assocArray;
auto perm = perms[0].dup.representation;
do {
if (perm !in permsSet)
writeln(perm.map!(c => char(c)));
} while (perm.nextPermutation);
// Version 2: xor all the ASCII values, the uneven one
// gets flushed out. Based on Raku (via Go).
enum len = 4;
char[len] b = 0;
foreach (immutable p; perms)
b[] ^= p[];
b.writeln;
// Version 3: sum ASCII values.
immutable rowSum = perms[0].sum;
len
.iota
.map!(i => to!char(rowSum - perms.transversal(i).sum % rowSum))
.writeln;
// Version 4: a checksum, Java translation. maxCode will be 36.
immutable maxCode = reduce!q{a * b}(len - 1, iota(3, len + 1));
foreach (immutable i; 0 .. len) {
immutable code = perms.map!(p => perms[0].countUntil(p[i])).sum;
// Code will come up 3, 1, 0, 2 short of 36.
perms[0][maxCode - code].write;
}
}
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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+ ;
: process-month ( ts -- ts' ) dup print-last-sun inc-month ;
: main ( -- ) parse-year 12 [ process-month ] times drop ;
MAIN: main
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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
EXIT FOR
END IF
END IF
NEXT
NEXT
PAUSE
|
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 as [[$cx,$cy], [$dx,$dy]]
| {detAB: det($ax;$ay; $bx;$by),
detCD: det($cx;$cy; $dx;$dy),
abDx: ($ax - $bx),
cdDx: ($cx - $dx),
abDy: ($ay - $by),
cdDy: ($cy - $dy)}
| . + {xnom: det(.detAB;.abDx;.detCD;.cdDx),
ynom: det(.detAB;.abDy;.detCD;.cdDy),
denom: det(.abDx; .abDy;.cdDx; .cdDy) }
| if (.denom|length < 10e-6) # length/0 emits the absolute value
then error("lineIntersect: parallel lines")
else [.xnom/.denom, .ynom/.denom]
end ;
|
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 * l2.s.y
Δ = a1 * b2 - a2 * b1
# If lines are parallel, intersection point will contain infinite values
return Point((b2 * c1 - b1 * c2) / Δ, (a1 * c2 - a2 * c1) / Δ)
end
l1 = Line(Point{Float64}(4, 0), Point{Float64}(6, 10))
l2 = Line(Point{Float64}(0, 3), Point{Float64}(10, 7))
println(intersection(l1, l2))
l1 = Line(Point{Float64}(0, 0), Point{Float64}(1, 1))
l2 = Line(Point{Float64}(1, 2), Point{Float64}(4, 5))
println(intersection(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 through [0, 0, 5].
|
#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 through [0, 0, 5].
|
#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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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
mov r1, #15
bl divide
cmp r1, #0
ldreq r1, =FizzAndBuzz
moveq r2, #9
beq fizzbuzz_print
mov r0, r9
mov r1, #3
bl divide
cmp r1, #0
ldreq r1, =Fizz
moveq r2, #5
beq fizzbuzz_print
mov r0, r9
mov r1, #5
bl divide
cmp r1, #0
ldreq r1, =Buzz
moveq r2, #5
beq fizzbuzz_print
mov r0, r9
bl make_num
mov r2, r1
mov r1, r0
fizzbuzz_print:
mov r0, #1
mov r7, #4
svc #0
sub r9, #1
cmp r9, #0
bgt fizzbuzz_loop
pop {lr}
mov pc, lr
make_num:
push {lr}
ldr r4, =numstr_buffer
mov r5, #4
mov r6, #1
mov r1, #100
bl divide
cmp r0, #0
subeq r5, #1
movne r6, #0
add r0, #48
strb r0, [r4, #0]
mov r0, r1
mov r1, #10
bl divide
cmp r0, #0
movne r6, #0
cmp r6, #1
subeq r5, #1
add r0, #48
strb r0, [r4, #1]
add r1, #48
strb r1, [r4, #2]
mov r2, #4
sub r0, r2, r5
add r0, r4, r0
mov r1, r5
pop {lr}
mov pc, lr
divide:
udiv r2, r0, r1
mul r3, r1, r2
sub r1, r0, r3
mov r0, r2
mov pc, lr
|
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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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 'To store the day to check
Dim sTemp As String 'Temp string
For siYear = 1900 To 2100 'Loop through each year
For siMonth = 0 To 6 'Loop through each 31 day month
dDay = Date(siYear, aMonth[siMonth], 1) 'Get the date of the 1st of the month
If WeekDay(dDay) = 5 Then aMMStore.Add(Format(dDay, "mmmm yyyy")) 'If the 1st is a Friday then store the result
Next
Next
For Each sTemp In aMMStore 'For each item in the stored array..
Inc siCount 'Increase siCount
If siCount < 6 Then Print aMMStore[siCount] 'If 1 of the 1st 5 dates then print it
If siCount = 6 Then Print String$(14, "-") 'Print a separator
If siCount > aMMStore.Max - 4 Then Print aMMStore[siCount - 1] 'If 1 of the last 5 dates then print it
Next
Print gb.NewLine & "Total months = " & Str(siCount) 'Print the number of months found
siCount = 0 'Reset siCount
sTemp = aMMStore.Join(",") 'Put all the stored dates in one string joined by commas
aMMStore.Clear 'Clear the store for reuse
For siYear = 1900 To 2100 'Loop through each year
If Not InStr(sTemp, Str(siYear)) Then 'If the year is not in the stored string then..
Inc siCount 'Increase siCount (Amount of years that don't have 5 weekend months)
aMMStore.Add(Str(siYear)) 'Add to the store
End If
Next
Print gb.NewLine & "There are " & Str(siCount) &
" years that do not have at least one five-weekend month" 'Print the amount of years with no 5 weekend months
Print aMMStore.Join(",") 'Print the years with no 5 weekend months
End
|
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 a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Task
Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated.
(optional) Do the same for bases 13 through 16.
(stretch goal) Continue on for bases 17 - ?? (Big Integer math)
See also
OEIS A260182: smallest square that is pandigital in base n.
Related task
Casting out nines
|
#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),ns);
}
Void
}
|
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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
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
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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 "pixels" when it feels the need to.
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas, hTimer
cdCanvas cddbuffer, cdcanvas
constant TITLE = "Forest Fire",
P = 0.03, -- probability of new tree growing
F = 0.00003 -- probability of new fire starting
enum EMPTY,TREE,FIRE -- (1,2,3)
constant colours = {CD_BLACK,CD_GREEN,CD_YELLOW}
sequence f = {} -- the forest
function randomf()
return rand(1000000)/1000000 -- returns 0.000001..1.000000
end function
function redraw_cb(Ihandle /*ih*/)
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"),
-- limit to 40K cells, otherwise it gets too slow.
-- n here is the cell size in pixels (min of 1x1)
-- Note you still get some setTimeout violations
-- in js even with the limit reduced to just 5K..
n = ceil(sqrt(width*height/40000)),
w = floor(width/n)+2, -- (see cx below)
h = floor(height/n)+2
cdCanvasActivate(cddbuffer)
if length(f)!=w
or length(f[1])!=h then
f = sq_rand(repeat(repeat(2,h),w)) -- (EMPTY or TREE)
end if
sequence fn = deep_copy(f)
--
-- There is a "dead border" of 1 cell all around the edge of f (& fn) which
-- we never display or update. If we have got this right/an exact fit, then
-- w*n should be exactly 2n too wide, whereas in the worst case there is an
-- (2n-1) pixel border, which we split between left and right, ditto cy.
--
integer cx = n+floor((width-w*n)/2)
for x=2 to w-1 do
integer cy = n+floor((height-h*n)/2)
for y=2 to h-1 do
integer fnxy
switch f[x,y] do
case EMPTY:
fnxy = EMPTY+(randomf()<P) -- (EMPTY or TREE)
case TREE:
fnxy = TREE
if f[x-1,y-1]=FIRE or f[x,y-1]=FIRE or f[x+1,y-1]=FIRE
or f[x-1,y ]=FIRE or (randomf()<F) or f[x+1,y ]=FIRE
or f[x-1,y+1]=FIRE or f[x,y+1]=FIRE or f[x+1,y+1]=FIRE then
fnxy = FIRE
end if
case FIRE:
fnxy = EMPTY
end switch
fn[x,y] = fnxy
cdCanvasSetForeground(cddbuffer,colours[fnxy])
cdCanvasBox(cddbuffer, cx, cx+n-1, cy, cy+n-1)
cy += n
end for
cx += n
end for
f = fn
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
return IUP_DEFAULT
end function
function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=225x100")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas, `TITLE="%s", MINSIZE=245x140`, {TITLE})
-- (above MINSIZE prevents the title from getting squished)
IupShow(dlg)
hTimer = IupTimer(Icallback("timer_cb"), 100) -- (10 fps)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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(numInRow) := StringTools[Length](convert(num-1, string));
end if;
if numInRow >= numRows then
if i = 2 then
printf("\n");
end if;
numInRow := 1;
numRows := numRows + 1;
else
numInRow := numInRow +1;
end if;
end do;
end do;
return NULL;
end proc:
floyd(5);
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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] = dist[i][k]+dist[k][j]
nxt[i][j] = nxt[i][k]
}
}
var summary = "pair dist path\n"
for i,j (^n ~X ^n) {
i==j && next
var u = i
var path = [u]
while (u != j) {
path << (u = nxt[u][j])
}
path.map!{|u| u+1 }.join!(" -> ")
summary += ("%d -> %d %4d %s\n" % (i+1, j+1, dist[i][j], path))
}
return summary
}
var n = 4
var edge = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]
print floyd_warshall(n, edge)
|
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 created and values returned).
Related task
Function prototype
|
#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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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, i):
return nthForwardsDifference(of: forwardsDifference(of: arr), n: i - 1)
}
}
for diff in (0...9).map({ nthForwardsDifference(of: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], n: $0) }) {
print(diff)
}
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 that use Tcl math ops
gate not {x out} {
set out [expr {1 & ~$x}]
}
gate and {x y out} {
set out [expr {$x & $y}]
}
gate or {x y out} {
set out [expr {$x | $y}]
}
gate GND pin {
set pin 0
}
# Composite gates: XOR
gate xor {x y out} {
pins nx ny x_ny nx_y
not x nx
not y ny
and x ny x_ny
and nx y nx_y
or x_ny nx_y out
}
# Composite gates: half adder
gate halfadd {a b sum carry} {
xor a b sum
and a b carry
}
# Composite gates: full adder
gate fulladd {a b c0 sum c1} {
pins sum_ac carry_ac carry_sb
halfadd c0 a sum_ac carry_ac
halfadd sum_ac b sum carry_sb
or carry_ac carry_sb c1
}
# Composite gates: 4-bit adder
gate 4add {a0 a1 a2 a3 b0 b1 b2 b3 s0 s1 s2 s3 v} {
pins c0 c1 c2 c3
GND c0
fulladd a0 b0 c0 s0 c1
fulladd a1 b1 c1 s1 c2
fulladd a2 b2 c2 s2 c3
fulladd a3 b3 c3 s3 v
}
|
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 implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#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.AppendFormat(format, it.Current)
End If
While it.MoveNext()
sb.Append(", ")
sb.AppendFormat(format, it.Current)
End While
Return sb.Append("]").ToString()
End Function
Function Median(x As Double(), start As Integer, endInclusive As Integer) As Double
Dim size = endInclusive - start + 1
If size <= 0 Then
Throw New ArgumentException("Array slice cannot be empty")
End If
Dim m = start + size \ 2
Return If(size Mod 2 = 1, x(m), (x(m - 1) + x(m)) / 2.0)
End Function
Function Fivenum(x As Double()) As Double()
For Each d In x
If Double.IsNaN(d) Then
Throw New ArgumentException("Unable to deal with arrays containing NaN")
End If
Next
Array.Sort(x)
Dim result(4) As Double
result(0) = x.First()
result(2) = Median(x, 0, x.Length - 1)
result(4) = x.Last()
Dim m = x.Length \ 2
Dim lowerEnd = If(x.Length Mod 2 = 1, m, m - 1)
result(1) = Median(x, 0, lowerEnd)
result(3) = Median(x, m, x.Length - 1)
Return result
End Function
Sub Main()
Dim x1 = {
New Double() {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
New Double() {36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
New Double() {
0.14082834, 0.0974879, 1.73131507, 0.87636009, -1.95059594, 0.73438555,
-0.03035726, 1.4667597, -0.74621349, -0.72588772, 0.6390516, 0.61501527,
-0.9898378, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,
0.75775634, 0.32566578
}
}
For Each x In x1
Dim result = Fivenum(x)
Console.WriteLine(result.AsString("{0:F8}"))
Next
End Sub
End Module
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#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-perms
;; {set} substraction
(set-substract (make-set all-perms) (make-set perms))
→ { DBAC }
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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[10] := 31; len[11] := 30; len[12] := 31; len[13] := 29;
for m := 1 to 12 do
begin
mm := m;
if (m = 2) and IsLeapYear( y ) then
mm := 13;
dt := EncodeDate( y, mm, len[mm] );
dt := EncodeDate( y, mm, len[mm] - DayOfWeek(dt) + 1 );
WriteLn(FormatDateTime('YYYY-MM-DD', dt ));
end;
end;
var
i : integer;
yy: integer;
begin
for i := 1 to paramCount() do begin
Val( paramStr(1), yy );
sund( yy );
end;
end.
|
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.y - l2.s.y
val b2 = l2.s.x - l2.e.x
val c2 = a2 * l2.s.x + b2 * l2.s.y
val delta = a1 * b2 - a2 * b1
// If lines are parallel, intersection point will contain infinite values
return PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
}
fun main(args: Array<String>) {
var l1 = LineF(PointF(4f, 0f), PointF(6f, 10f))
var l2 = LineF(PointF(0f, 3f), PointF(10f, 7f))
println(findIntersection(l1, l2))
l1 = LineF(PointF(0f, 0f), PointF(1f, 1f))
l2 = LineF(PointF(1f, 2f), PointF(4f, 5f))
println(findIntersection(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 through [0, 0, 5].
|
#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 through [0, 0, 5].
|
#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 Times(a : Vector3D; s : REAL) : Vector3D;
BEGIN
RETURN Vector3D{a.x*s, a.y*s, a.z*s};
END Times;
PROCEDURE Dot(lhs,rhs : Vector3D) : REAL;
BEGIN
RETURN lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z;
END Dot;
PROCEDURE ToString(self : Vector3D);
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
WriteString("(");
RealToStr(self.x,buf);
WriteString(buf);
WriteString(", ");
RealToStr(self.y,buf);
WriteString(buf);
WriteString(", ");
RealToStr(self.z,buf);
WriteString(buf);
WriteString(")");
END ToString;
PROCEDURE IntersectPoint(rayVector,rayPoint,planeNormal,planePoint : Vector3D) : Vector3D;
VAR
diff : Vector3D;
prod1,prod2,prod3 : REAL;
BEGIN
diff := Minus(rayPoint,planePoint);
prod1 := Dot(diff, planeNormal);
prod2 := Dot(rayVector, planeNormal);
prod3 := prod1 / prod2;
RETURN Minus(rayPoint, Times(rayVector, prod3));
END IntersectPoint;
VAR ip : Vector3D;
BEGIN
ip := IntersectPoint(Vector3D{0.0,-1.0,-1.0},Vector3D{0.0,0.0,10.0},Vector3D{0.0,0.0,1.0},Vector3D{0.0,0.0,5.0});
WriteString("The ray intersects the plane at ");
ToString(ip);
WriteLn;
ReadChar;
END LinePlane.
|
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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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 := [ ];
for m in [1, 3, 5, 7, 8, 10, 12] do
if WeekDay([1, m, y]) = "Fri" then
d := StringDate([1, m, y]);
Add(yL, d{[4 .. 11]});
fi;
od;
if Length(yL) = 0 then
Add(badL, y);
else
Append(L, yL);
fi;
od;
return [ L, badL ];
end;
r := FiveWeekends(1900, 2100);;
n := Length(r[1]);
# 201
Length(r[2]);
# 29
r[1]{[1 .. 5]};
# [ "Mar-1901", "Aug-1902", "May-1903", "Jan-1904", "Jul-1904" ]
r[1]{[n-4 .. n]};
# [ "Mar-2097", "Aug-2098", "May-2099", "Jan-2100", "Oct-2100" ]
|
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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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 item 1
for year := 1900; year <= 2100; year++ {
var hasOne bool // for extra credit
for _, month := range []time.Month{1, 3, 5, 7, 8, 10, 12} {
t := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
if t.Weekday() == time.Friday {
// task item 1: show month
fmt.Println(" ", t.Format("2006 January"))
n++
hasOne = true
last = t
if first.IsZero() {
first = t
}
}
}
if !hasOne {
haveNone = append(haveNone, year)
}
}
fmt.Println(n, "total\n") // task item 2: number of months
// task item 3
fmt.Println("First five dates of weekends:")
for i := 0; i < 5; i++ {
fmt.Println(" ", first.Format("Monday, January 2, 2006"))
first = first.Add(7 * 24 * time.Hour)
}
fmt.Println("Last five dates of weekends:")
for i := 0; i < 5; i++ {
fmt.Println(" ", last.Format("Monday, January 2, 2006"))
last = last.Add(7 * 24 * time.Hour)
}
// extra credit
fmt.Println("\nYears with no months with five weekends:")
for _, y := range haveNone {
fmt.Println(" ", y)
}
fmt.Println(len(haveNone), "total")
}
|
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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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));
}
};
}
public static void main(String[] args){
ArrayList<Function<Double, Double>> functions =
new ArrayList<Function<Double,Double>>();
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.cos(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.tan(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.acos(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.atan(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.sqrt(x);
}
});
System.out.println("Compositions:");
for(int i = 0; i < functions.size(); i++){
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
System.out.println("Hard-coded compositions:");
System.out.println(Math.cos(Math.acos(0.5)));
System.out.println(Math.tan(Math.atan(0.5)));
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}
|
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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
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
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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; $i < GEN_CNT; $i++) {
displayForest($forest, $i);
$forest = getNextForest($forest);
}
displayForest($forest, 'done');
exit;
function makeNewForest() {
return mapForest([
'func' => function(){
return isProb(TREE_PROB) ? TREE : BARE;
}
]);
}
function displayForest($forest, $generationNum) {
system("clear");
echo PHP_EOL . "Generation: $generationNum" . PHP_EOL;
mapForest(['forest' => $forest, 'func' => function($f, $x, $y){
echo $f[$y][$x] . ($x == WIDTH - 1 ? PHP_EOL : '');
}
]);
echo PHP_EOL;
usleep(PAUSE);
}
function getNextForest($oldForest) {
return mapForest(['forest' => $oldForest, 'func' => function($f, $x, $y){
switch ($f[$y][$x]) {
case BURN:
return BARE;
case BARE:
return isProb(GROW_PROB) ? TREE : BARE;
case TREE:
$caughtFire = isProb(FIRE_PROB);
$ablaze = $caughtFire ? true : getNumBurningNeighbors($f, $x, $y) > 0;
return $ablaze ? BURN : TREE;
}
}
]);
}
function getNumBurningNeighbors($forest, $x, $y) {
$burningNeighbors = mapForest([
'forest' => $forest,
'x1' => $x - 1, 'x2' => $x + 2,
'y1' => $y - 1, 'y2' => $y + 2,
'default' => 0,
'func' => function($f, $x, $y){
return $f[$y][$x] == BURN ? 1 : 0;
}
]);
$numOnFire = 0;
foreach ($burningNeighbors as $row) {
$numOnFire += array_sum($row);
}
return $numOnFire;
}
function mapForest($params) {
$p = array_merge([
'forest' => [],
'func' => function(){echo "default\n";},
'x1' => 0,
'x2' => WIDTH,
'y1' => 0,
'y2' => HEIGHT,
'default' => BARE
], $params);
$newForest = [];
for ($y = $p['y1']; $y < $p['y2']; $y++) {
$newRow = [];
for ($x = $p['x1']; $x < $p['x2']; $x++) {
$inBounds = ($x >= 0 && $x < WIDTH && $y >= 0 && $y < HEIGHT);
$newRow[] = ($inBounds ? $p['func']($p['forest'], $x, $y) : $p['default']);
}
$newForest[] = $newRow;
}
return $newForest;
}
function isProb($prob) {
return rand(0, 100) < $prob;
}
|
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)
sComma = ","
End If
Next
Print "["; sFlatter; "]"
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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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 in the SML-like languages
OCaml and ATS. This is an example of proceeding from where one has
gotten so far, to turn a program into a better one. The
improvements made here could be backported to the other languages.
In most respects, though, this program is very similar to the
OCaml.
Standard ML seems to specify its REAL signature is for IEEE
floating point, so this program assumes there is a positive
"infinity". (The difference is tiny between an algorithm with
"infinity" and one without.)
*)------------------------------------------------------------------*)
(* Square arrays with 1-based indexing. *)
signature SQUARE_ARRAY =
sig
type 'a squareArray
val make : int * 'a -> 'a squareArray
val get : 'a squareArray -> int * int -> 'a
val set : 'a squareArray -> int * int -> 'a -> unit
end
structure SquareArray : SQUARE_ARRAY =
struct
type 'a squareArray = int * 'a array
fun make (n, fill) =
(n, Array.array (n * n, fill))
fun get (n, r) (i, j) =
Array.sub (r, (i - 1) + (n * (j - 1)))
fun set (n, r) (i, j) x =
Array.update (r, (i - 1) + (n * (j - 1)), x)
end
(*------------------------------------------------------------------*)
(* A vertex is, internally, a positive integer, or 0 for the nil
object. *)
signature VERTEX =
sig
exception VertexError
eqtype vertex
val nilVertex : vertex
val isNil : vertex -> bool
val max : vertex * vertex -> vertex
val toInt : vertex -> int
val fromInt : int -> vertex
val toString : vertex -> string
val directedListToString : vertex list -> string
end
structure Vertex : VERTEX =
struct
exception VertexError
type vertex = int
val nilVertex = 0
fun isNil u = u = nilVertex
fun max (u, v) = Int.max (u, v)
fun toInt u = u
fun fromInt i =
if i < nilVertex then
raise VertexError
else
i
fun toString u = Int.toString u
fun directedListToString [] = ""
| directedListToString [u] = toString u
| directedListToString (u :: tail) =
(* This implementation is *not* tail recursive. *)
(toString u) ^ " -> " ^ (directedListToString tail)
end
(*------------------------------------------------------------------*)
(* Graph edges, with weights. *)
signature EDGE =
sig
type edge
val make : Vertex.vertex * real * Vertex.vertex -> edge
val first : edge -> Vertex.vertex
val weight : edge -> real
val second : edge -> Vertex.vertex
end
structure Edge : EDGE =
struct
type edge = Vertex.vertex * real * Vertex.vertex
fun make edge = edge
fun first (u, _, _) = u
fun weight (_, w, _) = w
fun second (_, _, v) = v
end
(*------------------------------------------------------------------*)
(* The "dist" array and its operations. *)
signature DISTANCES =
sig
type distances
val make : int -> distances
val get : distances -> int * int -> real
val set : distances -> int * int -> real -> unit
end
structure Distances : DISTANCES =
struct
type distances = real SquareArray.squareArray
fun make n = SquareArray.make (n, Real.posInf)
val get = SquareArray.get
val set = SquareArray.set
end
(*------------------------------------------------------------------*)
(* The "next" array and its operations. It lets you look up optimum
paths. *)
signature PATHS =
sig
type paths
val make : int -> paths
val get : paths -> int * int -> Vertex.vertex
val set : paths -> int * int -> Vertex.vertex -> unit
val path : (paths * int * int) -> Vertex.vertex list
val pathString : (paths * int * int) -> string
end
structure Paths : PATHS =
struct
type paths = Vertex.vertex SquareArray.squareArray
fun make n = SquareArray.make (n, Vertex.nilVertex)
val get = SquareArray.get
val set = SquareArray.set
fun path (p, u, v) =
if Vertex.isNil (get p (u, v)) then
[]
else
let
fun
build_path (p, u, v) =
if u = v then
[v]
else
let
val i = get p (u, v)
in
u :: build_path (p, i, v)
end
in
build_path (p, u, v)
end
fun pathString (p, u, v) =
Vertex.directedListToString (path (p, u, v))
end
(*------------------------------------------------------------------*)
(* Floyd-Warshall. *)
exception FloydWarshallError
fun find_max_vertex [] = Vertex.nilVertex
| find_max_vertex (edge :: tail) =
(* This implementation is *not* tail recursive. *)
Vertex.max (Vertex.max (Edge.first edge, Edge.second edge),
find_max_vertex tail)
fun floyd_warshall [] = raise FloydWarshallError
| floyd_warshall edges =
let
val n = find_max_vertex edges
val dist = Distances.make n
val next = Paths.make n
fun read_edges [] = ()
| read_edges (edge :: tail) =
let
val u = Edge.first edge
val v = Edge.second edge
val weight = Edge.weight edge
in
(Distances.set dist (u, v) weight;
Paths.set next (u, v) v;
read_edges tail)
end
val indices =
(* Indices in order from 1 .. n. *)
List.tabulate (n, fn i => i + 1)
in
(* Initialization. *)
read_edges edges;
List.app (fn i => (Distances.set dist (i, i) 0.0;
Paths.set next (i, i) i))
indices;
(* Perform the algorithm. *)
List.app
(fn k =>
List.app
(fn i =>
List.app
(fn j =>
let
val dist_ij = Distances.get dist (i, j)
val dist_ik = Distances.get dist (i, k)
val dist_kj = Distances.get dist (k, j)
val dist_ikj = dist_ik + dist_kj
in
if dist_ikj < dist_ij then
let
val new_dist = dist_ikj
val new_next = Paths.get next (i, k)
in
Distances.set dist (i, j) new_dist;
Paths.set next (i, j) new_next
end
else
()
end)
indices)
indices)
indices;
(* Return the results, as a 3-tuple. *)
(n, dist, next)
end
(*------------------------------------------------------------------*)
fun tilde_to_minus s =
String.translate (fn c => if c = #"~" then "-" else str c) s
fun main () =
let
val example_graph =
[Edge.make (Vertex.fromInt 1, ~2.0, Vertex.fromInt 3),
Edge.make (Vertex.fromInt 3, 2.0, Vertex.fromInt 4),
Edge.make (Vertex.fromInt 4, ~1.0, Vertex.fromInt 2),
Edge.make (Vertex.fromInt 2, 4.0, Vertex.fromInt 1),
Edge.make (Vertex.fromInt 2, 3.0, Vertex.fromInt 3)]
val (n, dist, next) = floyd_warshall example_graph
val indices =
(* Indices in order from 1 .. n. *)
List.tabulate (n, fn i => i + 1)
in
print " pair distance path\n";
print "---------------------------------------\n";
List.app
(fn u =>
List.app
(fn v =>
if u <> v then
(print " ";
print (Vertex.directedListToString [u, v]);
print " ";
if 0.0 <= Distances.get dist (u, v) then
print " "
else
();
print (tilde_to_minus
(Real.fmt (StringCvt.FIX (SOME 1))
(Distances.get dist (u, v))));
print " ";
print (Paths.pathString (next, u, v));
print "\n")
else
())
indices)
indices
end;
(* Comment out the following line, if you are using Poly/ML. *)
main ();
(*------------------------------------------------------------------*)
(* local variables: *)
(* mode: sml *)
(* sml-indent-level: 2 *)
(* sml-indent-args: 2 *)
(* 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 created and values returned).
Related task
Function prototype
|
#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_multiplyByEvenNumber
pop de
pop bc
ret
isOdd:
push hl
pop de ;de contains original HL. We'll need it later.
ld b,a
loop_multiplyByOddNumber:
add hl,hl
djnz loop_multiplyByOddNumber
add hl,de ;now add in original HL for the leftover add.
pop de
pop bc
ret
|
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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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]
incr order -1
}
return $list
}
set a {90.5 47 58 29 22 32 55 5 55 73.5}
for {set order 0} {$order <= 10} {incr order} {
puts [format "%d\t%s" $order [fwd_diff $a $order]]
}
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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);
return %r3 SPC getWord(%r2, 0);
}
//Outputs each bit seperated by a space.
function FourBitFullAdd(%a0, %a1, %a2, %a3, %b0, %b1, %b2, %b3)
{
%r0 = FullAdd(%a0, %b0, 0);
%r1 = FullAdd(%a1, %b1, getWord(%r0, 0));
%r2 = FullAdd(%a2, %b2, getWord(%r1, 0));
%r3 = FullAdd(%a3, %b3, getWord(%r2, 0));
return getWord(%r0,1) SPC getWord(%r1,1) SPC getWord(%r2,1) SPC getWord(%r3,1) SPC getWord(%r3,0);
}
|
http://rosettacode.org/wiki/Fivenum
|
Fivenum
|
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the R programming language implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#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] = 0.5 * (a[floor] + a[ceil])
e = e + 1
}
return n5
}
var x1 = [36, 40, 7, 39, 41, 15]
var x2 = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]
var x3 = [
0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,
0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,
0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,
0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578
]
for (x in [x1, x2, x3]) System.print(fivenum.call(x))
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#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-perms
;; {set} substraction
(set-substract (make-set all-perms) (make-set perms))
→ { DBAC }
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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_ Mod 100) = 0 AndAlso (Year_ Mod 400) <> 0 Then Return FALSE
Return TRUE
End Function
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
End If
Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7
End Function
' ------=< MAIN >=------
Type month_days
m_name As String
days As UByte
End Type
Dim As month_days arr(1 To 12)
Data "January", 31, "February", 28, "March", 31, "April", 30
Data "May", 31, "June", 30, "July", 31, "August", 31
Data "September", 30, "October", 31, "November", 30, "December", 31
Dim As Integer yr, d, i, x
Dim As String keypress
For i = 1 To 12
With arr(i)
Read .m_name
Read .days
End With
Next
Do
Do
Print "For what year do you want to find the last Sunday of the month"
Input "any number below 1800 stops program, year in YYYY format";yr
' empty input also stops
If yr < 1800 Then
End
Else
Exit Do
End If
Loop
Print : Print
Print "Last Sunday of the month for"; yr
For i = 1 To 12
d = arr(i).days
If i = 2 AndAlso leapyear(yr) = TRUE Then d = d + 1
x = wd(i, d, yr)
d = d - x ' don't test it just do it
Print d; " "; arr(i).m_name
Next
' empty key buffer
While Inkey <> "" : keypress = Inkey : Wend
Print : Print
Print "Find last Sunday for a other year [Y|y], anything else stops"
keypress =""
While keypress = "" : keypress = Inkey : Wend
If LCase(keypress) <> "y" Then Exit Do
Print : Print
Loop
End
|
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
local line1start, line1end = {x = 4, y = 0}, {x = 6, y = 10}
local line2start, line2end = {x = 0, y = 3}, {x = 10, y = 7}
print(intersection(line1start, line1end, line2start, line2end))
|
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 through [0, 0, 5].
|
#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 product of two vectors.
v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
func `*`(v: Vector; k: float): Vector =
## Multiply a vector by a scalar.
(v.x * k, v.y * k, v.z * k)
func intersection(lineVector, linePoint, planeVector, planePoint: Vector): Vector =
## Return the coordinates of the intersection of two vectors.
let tnum = planeVector * (planePoint - linePoint)
let tdenom = planeVector * lineVector
if tdenom == 0: return (Inf, Inf, Inf) # No intersection.
let t = tnum / tdenom
result = lineVector * t + linePoint
let coords = intersection(lineVector = (0.0, -1.0, -1.0),
linePoint = (0.0, 0.0, 10.0),
planeVector = (0.0, 0.0, 1.0),
planePoint = (0.0, 0.0, 5.0))
echo "Intersection at ", coords
|
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 through [0, 0, 5].
|
#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 { my @v; $v[$_] = $_[0][$_] - $_[1][$_] for 0..@{$_[0]}-1; @v } # vector difference
sub va { my @v; $v[$_] = $_[0][$_] + $_[1][$_] for 0..@{$_[0]}-1; @v } # vector addition
sub vp { my @v; $v[$_] = $_[0][$_] * $_[1][$_] for 0..@{$_[0]}-1; @v } # vector product
sub line_plane_intersection {
my($L, $P) = @_;
my $cos = dot($L->{u}, $P->{n}); # cosine between normal & ray
return 'Vectors are orthogonol; no intersection or line within plane' if $cos == 0;
my @W = vd($L->{P0},$P->{V0}); # difference between P0 and V0
my $SI = -dot($P->{n}, \@W) / $cos; # line segment where it intersets the plane
my @a = vp($L->{u},[($SI)x3]);
my @b = va($P->{V0},\@a);
va(\@W,\@b);
}
my $L = Line->new({ P0=>[0,0,10], u=>[0,-1,-1]});
my $P = Plane->new({ V0=>[0,0,5 ], n=>[0, 0, 1]});
print 'Intersection at point: ', join(' ', line_plane_intersection($L, $P)) . "\n";
|
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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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 ->
date("${year}-${month}-01")
}.findAll { firstDay ->
isLongMonth(firstDay) && Day.valueOf(firstDay) == Day.Fri
}
}.flatten()
}
|
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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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, Math.cos, cube];
var inv = [Math.asin, Math.acos, cuberoot];
for (var i = 0; i < 3; i++) {
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
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
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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) "# ")
((: tree) "T ")
(T ". ") ) ) )
(wait 1000)
(for Col Grid
(for This Col
(=: next
(cond
((: burn) NIL)
((: tree)
(if
(or
(find # Neighbor burning?
'((Dir) (get (Dir This) 'burn))
(quote
west east south north
((X) (south (west X)))
((X) (north (west X)))
((X) (south (east X)))
((X) (north (east X))) ) )
(> ProbF (rand 0 1.0)) )
'burn
'tree ) )
(T (and (> ProbP (rand 0 1.0)) 'tree)) ) ) ) )
(for Col Grid
(for This Col
(if (: next)
(put This @ T)
(=: burn)
(=: tree) ) ) ) ) ) )
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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
IF r<0 THEN RETURN END;
n := 1;
limit := 1;
WHILE r#0 DO
FOR i:=1 TO limit DO
WriteInt(n);
INC(n)
END;
WriteLn;
DEC(r);
INC(limit)
END
END Print;
BEGIN
Print(5);
WriteLn;
Print(14);
ReadChar
END FloydTriangle.
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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]
g arc setweight $a 1.0
}
set paths [::struct::graph::op::FloydWarshall g]
set paths [dict filter $paths key {a *}] ;# filter for paths starting at "a"
set paths [dict filter $paths value {[0-9]*}] ;# whose cost is not "Inf"
set paths [lsort -stride 2 -index 1 -real -decreasing $paths] ;# and print the longest first
puts $paths
|
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 created and values returned).
Related task
Function prototype
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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
Console.ReadKey()
End Sub
Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)
If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers")
For i As Integer = 1 To Level
Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _
Select Numbers(n + 1) - Numbers(n)).ToList()
Next
Return Numbers
End Function
End Module
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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 < <(half_adder "$ha0_s" "$b")
printf '%d %d\n' "$ha1_s" "$(( ha0_c || ha1_c ))"
}
four_bit_addr() {
typeset -i a0=$1 a1=$2 a2=$3 a3=$4 b0=$5 b1=$6 b2=$7 b3=$8
typeset -i fa0_s fa0_c fa1_s fa1_c fa2_s fa2_c fa3_s fa3_c
read fa0_s fa0_c < <(full_adder "$a0" "$b0" 0)
read fa1_s fa1_c < <(full_adder "$a1" "$b1" "$fa0_c")
read fa2_s fa2_c < <(full_adder "$a2" "$b2" "$fa1_c")
read fa3_s fa3_c < <(full_adder "$a3" "$b3" "$fa2_c")
printf '%s' "$fa0_s"
printf ' %s' "$fa1_s" "$fa2_s" "$fa3_s" "$fa3_c"
printf '\n'
}
is() {
typeset label=$1
shift
if eval "$*"; then
printf 'ok'
else
printf 'not ok'
fi
printf ' %s\n' "$label"
}
is "1 + 1 = 2" "[[ '$(four_bit_addr 1 0 0 0 1 0 0 0)' == '0 1 0 0 0' ]]"
is "5 + 5 = 10" "[[ '$(four_bit_addr 1 0 1 0 1 0 1 0)' == '0 1 0 1 0' ]]"
is "7 + 9 = overflow" "a=($(four_bit_addr 1 0 0 1 1 1 1 0)); (( \${a[-1]}==1 ))"
|
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 implements Tukey's five-number summary as the fivenum function.
Task
Given an array of numbers, compute the five-number summary.
Note
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
|
#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
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#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 <- list, y <- permutations(list -- [x]), do: [x|y])
end
perms = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
"CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
IO.inspect RC.find_miss_perm( hd(perms), perms )
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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 the user to enter a year
Print "Last Sundays in " & sYear 'Print a heading
For siMonth = 1 To 12 'Loop for each month
For siDay = 31 DownTo 23 'Count backwards from 31 to 23 (Sunday 23rd February 1930)
siWeekday = 7 'Set the Weekday to Saturday in case of error in the next line
Try siWeekday = WeekDay(Date(Val(sYear), siMonth, siDay)) 'TRY and get the Weekday. If there is an error it will be ignored e.g. 31 February
If siWeekday = 0 Then 'If Weekday is Sunday then..
Print Format(Date(Val(sYear), siMonth, siDay), "dddd dd mmmm yyyy") 'Print the date
Break 'Jump out of this loop
End If
Next
Next
End
|
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, y2
if x1==x2 then error "wrong input"
if x1>x2 then swap x1,x2 : swap y1, y2
.slop<=(y1-y2)/(x1-x2)
.k<=x1*.slop-y1
}
}
M=line(!lineAtuple)
N=line(!lineBtuple)
Print M.intersection(N)
}
Lineintersection (4,0,6,10), (0,3,10,7) ' print 5 5
|
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 through [0, 0, 5].
|
#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)
return sq_add(sq_add(diff,plane_point),sq_mul(-dot(diff,plane_normal)/a,line_vector))
end function
?intersection_point({0,-1,-1},{0,0,10},{0,0,1},{0,0,5})
?intersection_point({3,2,1},{0,2,4},{1,2,3},{3,3,3})
?intersection_point({1,1,0},{0,0,1},{0,0,3},{0,0,0}) -- (parallel to plane)
?intersection_point({1,1,0},{1,1,0},{0,0,3},{0,0,0}) -- (line within plane)
|
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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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 least the first and last five dates, in order.
Algorithm suggestions
Count the number of Fridays, Saturdays, and Sundays in every month.
Find all of the 31-day months that begin on Friday.
Extra credit
Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
Related tasks
Day of the week
Last Friday of each month
Find last sunday of each month
|
#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( m ) == 31
nFound++
cNames += CMonth( d ) + " "
ENDIF
ENDIF
NEXT
IF nFound > 0
AAdd( aFounds, hb_NtoS( y ) + " : " + hb_NtoS( nFound ) + " ( " + Rtrim( cNames ) + " )" )
nTot += nFound
ELSE
nNotFives++
ENDIF
NEXT
? "Total months with five weekends: " + hb_NtoS( nTot )
? "(see bellow the first and last five years/months with five weekends)"
?
AEval( aFounds, { | e, n | Iif( n < 6, Qout( e ), NIL ) } )
Qout("...")
AEval( aFounds, { | e, n | Iif( n > Len(aFounds)-5, Qout( e ), NIL ) } )
?
? "Years with no five weekends months: " + hb_NtoS( nNotFives )
RETURN
|
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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 return values of other functions
Task
Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy).
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
Related task
First-class Numbers
|
#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 (i in 0..2) println(compose(listA[i], listB[i])(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 forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
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
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#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 } { 1 0 0 } ifelse setrgbcolor
x c mul y c mul m
c 0 l 0 c l c neg 0 l closepath fill
} ifelse
} for
} for
} def
/r1n { dup 0 ge exch n lt and } def
/neighbors { /y exch def /x exch def /cnt 0 def
[
y 1 sub 1 y 1 add { /y1 exch def
y1 r1n {
x 1 sub 1 x 1 add { /x1 exch def
x1 r1n { forest x1 get y1 get } if
} for
} if
} for]
} def
/iter {
/nf [ n {[ n {0} repeat]} repeat ] def
0 1 n 1 sub { /x exch def
0 1 n 1 sub { /y exch def
nf x get y
forest x get y get dup
0 eq { pop rand1 treeprob le {1}{0} ifelse
} {
1 eq { /fire false def
x y neighbors {
-1 eq { /fire true def } if
} forall
fire {-1}{
rand1 burnprob lt {-1}{1} ifelse
} ifelse
}{0} ifelse
} ifelse
put
} for } for
/forest nf def
} def
/n 200 def
/treeprob .05 def
/burnprob .0001 def
/c size n div def
/forest [ n {[ n { rand1 treeprob le {1}{0} ifelse } repeat]} repeat ] def
1000 { drawforest showpage iter } repeat
%%EOF
|
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┃ ┃ ┃
┃ ┃┗━━━━━┛ ┃ ┃
┃ ┗∊━━━━━━━━━┛ ┃
┗∊∊━━━━━━━━━━━━━━━━━━━━━━━━━┛
∊list
┏→━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃1 2 3 4 5 6 7 8 9 10 11 12 13 'A''B''C''D'┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
|
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 this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task
Write a program to generate and display here the first n lines of a Floyd triangle.
(Use n=5 and n=14 rows).
Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
|
#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 then rowcount = 1
say 'Rows:' rowcount
say
col = 0
len = Rexx ''
ll = '' -- last line of triangle
Loop j = rowcount * (rowcount - 1) / 2 + 1 to rowcount * (rowcount + 1) / 2
col = col + 1 -- column number
ll = ll j -- build last line
len[col] = j.length() -- remember length of column
End j
Loop i = 1 To rowcount - 1 -- now do and output the rest
ol = ''
col = 0
Loop j = i * (i - 1) / 2 + 1 to i * (i + 1) / 2 -- elements of line i
col = col + 1
ol=ol j.right(len[col]) -- element in proper length
end
Say ol -- output ith line
end i
Say ll -- output last line
|
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 edges and negative cycles.
Print the pair, the distance and (optionally) the path.
Example
pair dist path
1 -> 2 -1 1 -> 3 -> 4 -> 2
1 -> 3 -2 1 -> 3
1 -> 4 0 1 -> 3 -> 4
2 -> 1 4 2 -> 1
2 -> 3 2 2 -> 1 -> 3
2 -> 4 4 2 -> 1 -> 3 -> 4
3 -> 1 5 3 -> 4 -> 2 -> 1
3 -> 2 1 3 -> 4 -> 2
3 -> 4 2 3 -> 4
4 -> 1 3 4 -> 2 -> 1
4 -> 2 -1 4 -> 2
4 -> 3 1 4 -> 2 -> 1 -> 3
See also
Floyd-Warshall Algorithm - step by step guide (youtube)
|
#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 path = String.Format("{0} -> {1} {2,2:G} {3}", u, v, dist(i - 1, j - 1), u)
Do
u = nxt(u - 1, v - 1)
path += String.Format(" -> {0}", u)
Loop While u <> v
Console.WriteLine(path)
End If
Next
Next
End Sub
Sub FloydWarshall(weights As Integer(,), numVerticies As Integer)
Dim dist(numVerticies - 1, numVerticies - 1) As Double
For i = 1 To numVerticies
For j = 1 To numVerticies
dist(i - 1, j - 1) = Double.PositiveInfinity
Next
Next
For i = 1 To weights.GetLength(0)
dist(weights(i - 1, 0) - 1, weights(i - 1, 1) - 1) = weights(i - 1, 2)
Next
Dim nxt(numVerticies - 1, numVerticies - 1) As Integer
For i = 1 To numVerticies
For j = 1 To numVerticies
If i <> j Then
nxt(i - 1, j - 1) = j
End If
Next
Next
For k = 1 To numVerticies
For i = 1 To numVerticies
For j = 1 To numVerticies
If dist(i - 1, k - 1) + dist(k - 1, j - 1) < dist(i - 1, j - 1) Then
dist(i - 1, j - 1) = dist(i - 1, k - 1) + dist(k - 1, j - 1)
nxt(i - 1, j - 1) = nxt(i - 1, k - 1)
End If
Next
Next
Next
PrintResult(dist, nxt)
End Sub
Sub Main()
Dim weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}}
Dim numVeritices = 4
FloydWarshall(weights, numVeritices)
End Sub
End Module
|
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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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 " + TRANSFORM(i), @aa)
ENDFOR
PROCEDURE ForwardDiff(a)
LOCAL i As Integer, n As Integer
n = ALEN(a)
LOCAL ARRAY b[n-1]
FOR i = 1 TO n - 1
b[i] = a[i+1] - a[i]
ENDFOR
DIMENSION a[n-1]
ACOPY(b, a)
ENDPROC
PROCEDURE ShowOutput(lcLabel, zz)
LOCAL i As Integer, n As Integer, lcTxt As String
n = ALEN(zz)
lcTxt = lcLabel + ":" + CTAB
FOR i = 1 TO n
lcTxt = lcTxt + TRANSFORM(zz[i]) + CTAB
ENDFOR
lcTxt = LEFT(lcTxt, LEN(lcTxt) - 1)
? lcTxt
ENDPROC
|
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 element as a result.
The second-order forward difference of A will be:
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
The same as the first-order forward difference of B.
That new list will have two fewer elements than A and one less than B.
The goal of this task is to repeat this process up to the desired order.
For a more formal description, see the related Mathworld article.
Algorithmic options
Iterate through all previous forward differences and re-calculate a new array each time.
Use this formula (from Wikipedia):
Δ
n
[
f
]
(
x
)
=
∑
k
=
0
n
(
n
k
)
(
−
1
)
n
−
k
f
(
x
+
k
)
{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}
(Pascal's Triangle may be useful for this option.)
|
#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)
for (i in 0...b.count) b[i] = a[i+1] - a[i]
Fmt.print("$2d: $5d", o, b)
if (b.count == 1) return
a = b
}
}
forwardDiff.call([90, 47, 58, 29, 22, 32, 55, 5, 55, 73], 9)
|
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 and one or.
Not, or and and, the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a bit type in your language, to be sure that the not does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra nand (and then not) with the constant 1 on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, connecting the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
Schematics of the "constructive blocks"
(Xor gate with ANDs, ORs and NOTs)
(A half adder)
(A full adder)
(A 4-bit adder)
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
|
#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_ha2 );
endmodule // Full_Adder
module Full_Adder4( output [4:0] s, input [3:0] a, b, input c_in );
wire [4:0] c;
Full_Adder adder00 ( c[1], s[0], a[0], b[0], c_in );
Full_Adder adder01 ( c[2], s[1], a[1], b[1], c[1] );
Full_Adder adder02 ( c[3], s[2], a[2], b[2], c[2] );
Full_Adder adder03 ( c[4], s[3], a[3], b[3], c[3] );
assign s[4] = c[4];
endmodule // Full_Adder4
module test_Full_Adder();
reg [3:0] a;
reg [3:0] b;
wire [4:0] s;
Full_Adder4 FA4 ( s, a, b, 0 );
initial begin
$display( " a + b = s" );
$monitor( "%4d + %4d = %5d", a, b, s );
a=4'b0000; b=4'b0000;
#1 a=4'b0000; b=4'b0001;
#1 a=4'b0001; b=4'b0001;
#1 a=4'b0011; b=4'b0001;
#1 a=4'b0111; b=4'b0001;
#1 a=4'b1111; b=4'b0001;
end
endmodule // test_Full_Adder
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols A, B, C, and D, except for one permutation that's not listed.
Task
Find that missing permutation.
Methods
Obvious method:
enumerate all permutations of A, B, C, and D,
and then look for the missing permutation.
alternate method:
Hint: if all permutations were shown above, how many
times would A appear in each position?
What is the parity of this number?
another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter A, B, C, and D from each
column cause the total value for each column to be unique?
Related task
Permutations)
|
#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 <- String, C <- String, D <- String, is_different([A, B, C, D])].
existing_permutations() -> ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"].
is_different( [_H] ) -> true;
is_different( [H | T] ) -> not lists:member(H, T) andalso is_different( T ).
|
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
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#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 the user to enter a year
Print "Last Sundays in " & sYear 'Print a heading
For siMonth = 1 To 12 'Loop for each month
For siDay = 31 DownTo 23 'Count backwards from 31 to 23 (Sunday 23rd February 1930)
siWeekday = 7 'Set the Weekday to Saturday in case of error in the next line
Try siWeekday = WeekDay(Date(Val(sYear), siMonth, siDay)) 'TRY and get the Weekday. If there is an error it will be ignored e.g. 31 February
If siWeekday = 0 Then 'If Weekday is Sunday then..
Print Format(Date(Val(sYear), siMonth, siDay), "dddd dd mmmm yyyy") 'Print the date
Break 'Jump out of this loop
End If
Next
Next
End
|
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 through [0, 0, 5].
|
#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(RayPoint, PlanePoint),
Prod1 = dot(Diff, PlaneNormal),
Prod2 = dot(RayVector, PlaneNormal),
Prod3 = Prod1 / Prod2,
IntersectPoint = minus(RayPoint, times(RayVector, Prod3)).
main =>
RayVector = {0.0, -1.0, -1.0},
RayPoint = {0.0, 0.0, 10.0},
PlaneNormal = {0.0, 0.0, 1.0},
PlanePoint = {0.0, 0.0, 5.0},
IntersectPoint = intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint),
printf("The ray intersects the plane at (%f, %f, %f)\n",
IntersectPoint[1],
IntersectPoint[2],
IntersectPoint[3]
).
|
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 through [0, 0, 5].
|
#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(X3, Y3, Z3).
vector_times(U, S, V) :-
U = p(X1, Y1, Z1),
X2 is X1 * S,
Y2 is Y1 * S,
Z2 is Z1 * S,
V = p(X2, Y2, Z2).
vector_dot(U, V, S) :-
U = p(X1, Y1, Z1),
V = p(X2, Y2, Z2),
S is X1 * X2 + Y1 * Y2 + Z1 * Z2.
intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint, IntersectPoint) :-
vector_minus(RayPoint, PlanePoint, Diff),
vector_dot(Diff, PlaneNormal, Prod1),
vector_dot(RayVector, PlaneNormal, Prod2),
Prod3 is Prod1 / Prod2,
vector_times(RayVector, Prod3, Times),
vector_minus(RayPoint, Times, IntersectPoint).
main :-
RayVector = p(0.0, -1.0, -1.0),
RayPoint = p(0.0, 0.0, 10.0),
PlaneNormal = p(0.0, 0.0, 1.0),
PlanePoint = p(0.0, 0.0, 5.0),
intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint, p(X, Y, Z)),
format("The ray intersects the plane at (~f, ~f, ~f)\n", [X, Y, Z]).
|
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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#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.