task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#Haskell
|
Haskell
|
import Data.List (intercalate)
data DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday |
Saturday | Sunday
deriving (Eq, Show)
-- the whole thing bases upon an infinite list of weeks
daysFrom1_1_1900 :: [DayOfWeek]
daysFrom1_1_1900 = concat $ repeat [Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday]
data Month = January | February | March | April | May | June | July |
August | September | October | November | December
deriving (Show)
type Year = Int
type YearCalendar = (Year, [DayOfWeek])
type MonthlyCalendar = (Year, [(Month, [DayOfWeek])])
-- makes groups of 365 or 366 days for each year (infinite list)
yearsFrom :: [DayOfWeek] -> Year -> [YearCalendar]
yearsFrom s i = (i, yeardays) : yearsFrom rest (i + 1)
where
yeardays = take (leapOrNot i) s
yearlen = length yeardays
rest = drop yearlen s
leapOrNot n = if isLeapYear n then 366 else 365
yearsFrom1900 :: [YearCalendar]
yearsFrom1900 = yearsFrom daysFrom1_1_1900 1900
-- makes groups of days for each month of the year
months :: YearCalendar -> MonthlyCalendar
months (y, d) = (y, [(January, january), (February, february),
(March, march), (April, april), (May, may), (June, june),
(July, july), (August, august), (September, september),
(October, october), (November, november), (December, december)])
where
leapOrNot = if isLeapYear y then 29 else 28
january = take 31 d
february = take leapOrNot $ drop 31 d
march = take 31 $ drop (31 + leapOrNot) d
april = take 30 $ drop (62 + leapOrNot) d
may = take 31 $ drop (92 + leapOrNot) d
june = take 30 $ drop (123 + leapOrNot) d
july = take 31 $ drop (153 + leapOrNot) d
august = take 31 $ drop (184 + leapOrNot) d
september = take 30 $ drop (215 + leapOrNot) d
october = take 31 $ drop (245 + leapOrNot) d
november = take 30 $ drop (276 + leapOrNot) d
december = take 31 $ drop (306 + leapOrNot) d
-- see if a year is a leap year
isLeapYear n
| n `mod` 100 == 0 = n `mod` 400 == 0
| otherwise = n `mod` 4 == 0
-- make a list of the months of a year that have 5 weekends
-- (they must have 31 days and the first day must be Friday)
-- if the year doesn't contain any 5-weekended months, then
-- return the year and an empty list
whichFiveWeekends :: MonthlyCalendar -> (Year, [Month])
whichFiveWeekends (y, ms) = (y, map (\(m, _) -> m) found) -- extract the months & leave out their days
where found = filter (\(m, a@(d:ds)) -> and [length a == 31,
d == Friday]) ms
-- take all days from 1900 until 2100, grouping them by years, then by
-- months, and calculating whether they have any 5-weekended months
-- or not
calendar :: [MonthlyCalendar]
calendar = map months $ yearsFrom1900
fiveWeekends1900To2100 :: [(Year, [Month])]
fiveWeekends1900To2100 = takeWhile (\(y, _) -> y <= 2100) $
map whichFiveWeekends calendar
main = do
-- count the number of years with 5 weekends
let answer1 = foldl (\c (_, m) -> c + length m) 0 fiveWeekends1900To2100
-- take only the years with 5-weekended months
answer2 = filter (\(_, m) -> not $ null m) fiveWeekends1900To2100
-- take only the years without 5-weekended months
answer30 = filter (\(_, m) -> null m) fiveWeekends1900To2100
-- count how many years without 5-weekended months there are
answer31 = length answer30
-- show the years without 5-weekended months
answer32 = intercalate ", " $ map (\(y, m) -> show y) answer30
putStrLn $ "There are " ++ show answer1 ++ " months with 5 weekends between 1900 and 2100."
putStrLn "\nThe first ones are:"
mapM_ (putStrLn . formatMonth) $ take 5 $ answer2
putStrLn "\nThe last ones are:"
mapM_ (putStrLn . formatMonth) $ reverse $ take 5 $ reverse answer2
putStrLn $ "\n" ++ show answer31 ++ " years don't have at least one five-weekened month"
putStrLn "\nThose are:"
putStrLn answer32
formatMonth :: (Year, [Month]) -> String
formatMonth (y, m) = show y ++ ": " ++ intercalate ", " [ show x | x <- m ]
|
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
|
#Lambdatalk
|
Lambdatalk
|
{def cube {lambda {:x} {pow :x 3}}}
{def cuberoot {lambda {:x} {pow :x {/ 1 3}}}}
{def compose {lambda {:f :g :x} {:f {:g :x}}}}
{def fun sin cos cube}
{def inv asin acos cuberoot}
{def display {lambda {:i}
{br}{compose {nth :i {fun}}
{nth :i {inv}} 0.5}}}
{map display {serie 0 2}}
Output:
0.5
0.49999999999999994
0.5000000000000001
|
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.
|
#Python
|
Python
|
'''
Forest-Fire Cellular automation
See: http://en.wikipedia.org/wiki/Forest-fire_model
'''
L = 15
# d = 2 # Fixed
initial_trees = 0.55
p = 0.01
f = 0.001
try:
raw_input
except:
raw_input = input
import random
tree, burning, space = 'TB.'
hood = ((-1,-1), (-1,0), (-1,1),
(0,-1), (0, 1),
(1,-1), (1,0), (1,1))
def initialise():
grid = {(x,y): (tree if random.random()<= initial_trees else space)
for x in range(L)
for y in range(L) }
return grid
def gprint(grid):
txt = '\n'.join(''.join(grid[(x,y)] for x in range(L))
for y in range(L))
print(txt)
def quickprint(grid):
t = b = 0
ll = L * L
for x in range(L):
for y in range(L):
if grid[(x,y)] in (tree, burning):
t += 1
if grid[(x,y)] == burning:
b += 1
print(('Of %6i cells, %6i are trees of which %6i are currently burning.'
+ ' (%6.3f%%, %6.3f%%)')
% (ll, t, b, 100. * t / ll, 100. * b / ll))
def gnew(grid):
newgrid = {}
for x in range(L):
for y in range(L):
if grid[(x,y)] == burning:
newgrid[(x,y)] = space
elif grid[(x,y)] == space:
newgrid[(x,y)] = tree if random.random()<= p else space
elif grid[(x,y)] == tree:
newgrid[(x,y)] = (burning
if any(grid.get((x+dx,y+dy),space) == burning
for dx,dy in hood)
or random.random()<= f
else tree)
return newgrid
if __name__ == '__main__':
grid = initialise()
iter = 0
while True:
quickprint(grid)
inp = raw_input('Print/Quit/<int>/<return> %6i: ' % iter).lower().strip()
if inp:
if inp[0] == 'p':
gprint(grid)
elif inp.isdigit():
for i in range(int(inp)):
iter +=1
grid = gnew(grid)
quickprint(grid)
elif inp[0] == 'q':
break
grid = gnew(grid)
iter +=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
|
#Go
|
Go
|
package main
import "fmt"
func list(s ...interface{}) []interface{} {
return s
}
func main() {
s := list(list(1),
2,
list(list(3, 4), 5),
list(list(list())),
list(list(list(6))),
7,
8,
list(),
)
fmt.Println(s)
fmt.Println(flatten(s))
}
func flatten(s []interface{}) (r []int) {
for _, e := range s {
switch i := e.(type) {
case int:
r = append(r, i)
case []interface{}:
r = append(r, flatten(i)...)
}
}
return
}
|
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.
|
#Nim
|
Nim
|
import strutils
proc floyd(rowcount = 5): seq[seq[int]] =
result = @[@[1]]
while result.len < rowcount:
let n = result[result.high][result.high] + 1
var row = newSeq[int]()
for i in n .. n + result[result.high].len:
row.add i
result.add row
proc pfloyd(rows: seq[seq[int]]) =
var colspace = newSeq[int]()
for n in rows[rows.high]: colspace.add(($n).len)
for row in rows:
for i, x in row:
stdout.write align($x, colspace[i])," "
echo ""
for i in [5, 14]:
pfloyd(floyd(i))
echo ""
|
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.
|
#OCaml
|
OCaml
|
let ( |> ) f g x = g (f x)
let rec last = function x::[] -> x | _::tl -> last tl | [] -> raise Not_found
let rec list_map2 f l1 l2 =
match (l1, l2) with
| ([], _) | (_, []) -> []
| (x::xs, y::ys) -> (f x y) :: list_map2 f xs ys
let floyd n =
let rec aux acc cur len i j =
if (List.length acc) = n then (List.rev acc) else
if j = len
then aux ((List.rev cur)::acc) [] (succ len) i 0
else aux acc (i::cur) len (succ i) (succ j)
in
aux [] [] 1 1 0
let print_floyd f =
let lens = List.map (string_of_int |> String.length) (last f) in
List.iter (fun row ->
print_endline (
String.concat " " (
list_map2 (Printf.sprintf "%*d") lens row))
) f
let () =
print_floyd (floyd (int_of_string Sys.argv.(1)))
|
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)
|
#Wren
|
Wren
|
import "/fmt" for Fmt
class FloydWarshall {
static doCalcs(weights, nVertices) {
var dist = List.filled(nVertices, null)
for (i in 0...nVertices) dist[i] = List.filled(nVertices, 1/0)
for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2]
var next = List.filled(nVertices, null)
for (i in 0...nVertices) next[i] = List.filled(nVertices, 0)
for (i in 0...next.count) {
for (j in 0...next.count) {
if (i != j) next[i][j] = j + 1
}
}
for (k in 0...nVertices) {
for (i in 0...nVertices) {
for (j in 0...nVertices) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
next[i][j] = next[i][k]
}
}
}
}
printResult_(dist, next)
}
static printResult_(dist, next) {
System.print("pair dist path")
for (i in 0...next.count) {
for (j in 0...next.count) {
if (i != j) {
var u = i + 1
var v = j + 1
var path = Fmt.swrite("$d -> $d $2d $s", u, v, dist[i][j].truncate, u)
while (true) {
u = next[u - 1][v - 1]
path = path + " -> " + u.toString
if (u == v) break
}
System.print(path)
}
}
}
}
}
var weights = [ [1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1] ]
var nVertices = 4
FloydWarshall.doCalcs(weights, nVertices)
|
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.)
|
#zkl
|
zkl
|
fcn forwardDiff(lst){
if(lst.len()<2)
return(T);
return(T(lst[1]-lst[0]).extend(forwardDiff(lst[1,*])))
}
fcn nthForwardDiff(n,xs){
if(n==0)
return(xs);
return(nthForwardDiff(n-1,forwardDiff(xs))) // tail recursion
}
|
http://rosettacode.org/wiki/Forward_difference
|
Forward difference
|
Task
Provide code that produces a list of numbers which is the nth order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
The first-order forward difference of a list of numbers A is a new list B, where Bn = An+1 - An.
List B should have one fewer 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.)
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 DATA 9,0,1,2,4,7,4,2,1,0
20 LET p=1
30 READ n: DIM b(n)
40 FOR i=1 TO n
50 READ b(i)
60 NEXT i
70 FOR j=1 TO p
80 FOR i=1 TO n-j
90 LET b(i)=b(i+1)-b(i)
100 NEXT i
110 NEXT j
120 FOR i=1 TO n-p
130 PRINT b(i);" ";
140 NEXT i
|
http://rosettacode.org/wiki/Four_bit_adder
|
Four bit adder
|
Task
"Simulate" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two half adders and an or gate. ;
Finally a half adder can be made using an xor gate and an and gate.
The xor gate can be made using two nots, two ands 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).
|
#VHDL
|
VHDL
|
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity four_bit_adder is
port(
a : in std_logic_vector (3 downto 0);
b : in std_logic_vector (3 downto 0);
s : out std_logic_vector (3 downto 0);
v : out std_logic
);
end four_bit_adder ;
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity fa is
port(
a : in std_logic;
b : in std_logic;
ci : in std_logic;
co : out std_logic;
s : out std_logic
);
end fa ;
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity ha is
port(
a : in std_logic;
b : in std_logic;
c : out std_logic;
s : out std_logic
);
end ha ;
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity xor_gate is
port(
a : in std_logic;
b : in std_logic;
x : out std_logic
);
end xor_gate ;
architecture struct of four_bit_adder is
signal ci0 : std_logic;
signal co0 : std_logic;
signal co1 : std_logic;
signal co2 : std_logic;
component fa
port (
a : in std_logic ;
b : in std_logic ;
ci : in std_logic ;
co : out std_logic ;
s : out std_logic
);
end component;
begin
ci0 <= '0';
i_fa0 : fa
port map (
a => a(0),
b => b(0),
ci => ci0,
co => co0,
s => s(0)
);
i_fa1 : fa
port map (
a => a(1),
b => b(1),
ci => co0,
co => co1,
s => s(1)
);
i_fa2 : fa
port map (
a => a(2),
b => b(2),
ci => co1,
co => co2,
s => s(2)
);
i_fa3 : fa
port map (
a => a(3),
b => b(3),
ci => co2,
co => v,
s => s(3)
);
end struct;
architecture struct of fa is
signal c1 : std_logic;
signal c2 : std_logic;
signal s1 : std_logic;
component ha
port (
a : in std_logic ;
b : in std_logic ;
c : out std_logic ;
s : out std_logic
);
end component;
begin
co <= c1 or c2;
i_ha0 : ha
port map (
a => ci,
b => a,
c => c1,
s => s1
);
i_ha1 : ha
port map (
a => s1,
b => b,
c => c2,
s => s
);
end struct;
architecture struct of ha is
component xor_gate
port (
a : in std_logic;
b : in std_logic;
x : out std_logic
);
end component;
begin
c <= a and b;
i_xor_gate : xor_gate
port map (
a => a,
b => b,
x => s
);
end struct;
architecture rtl of xor_gate is
begin
x <= (a and not b) or (b and not a);
end architecture rtl;
|
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)
|
#ERRE
|
ERRE
|
PROGRAM MISSING
CONST N=4
DIM PERMS$[23]
BEGIN
PRINT(CHR$(12);) ! CLS
DATA("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB")
DATA("CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC")
DATA("BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB")
FOR I%=1 TO UBOUND(PERMS$,1) DO
READ(PERMS$[I%])
END FOR
SOL$="...."
FOR I%=1 TO N DO
CH$=CHR$(I%+64)
COUNT%=0
FOR Z%=1 TO N DO
COUNT%=0
FOR J%=1 TO UBOUND(PERMS$,1) DO
IF CH$=MID$(PERMS$[J%],Z%,1) THEN COUNT%=COUNT%+1 END IF
END FOR
IF COUNT%<>6 THEN
!$RCODE="MID$(SOL$,Z%,1)=CH$"
END IF
END FOR
END FOR
PRINT("Solution is: ";SOL$)
END PROGRAM
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"time"
)
func main() {
var year int
var t time.Time
var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }
for {
fmt.Print("Please select a year: ")
_, err := fmt.Scanf("%d", &year)
if err != nil {
fmt.Println(err)
continue
} else {
break
}
}
fmt.Println("Last Sundays of each month of", year)
fmt.Println("==================================")
for i := 1;i < 13; i++ {
j := lastDay[i-1]
if i == 2 {
if time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC).Month() == time.Date(int(year), time.Month(i), j-1, 0, 0, 0, 0, time.UTC).Month() {
j = 29
} else {
j = 28
}
}
for {
t = time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC)
if t.Weekday() == 0 {
fmt.Printf("%s: %d\n", time.Month(i), j)
break
}
j = j - 1
}
}
}
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Modula-2
|
Modula-2
|
MODULE LineIntersection;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE
Point = RECORD
x,y : REAL;
END;
PROCEDURE PrintPoint(p : Point);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
WriteString("{");
RealToStr(p.x, buf);
WriteString(buf);
WriteString(", ");
RealToStr(p.y, buf);
WriteString(buf);
WriteString("}");
END PrintPoint;
TYPE
Line = RECORD
s,e : Point;
END;
PROCEDURE FindIntersection(l1,l2 : Line) : Point;
VAR a1,b1,c1,a2,b2,c2,delta : REAL;
BEGIN
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;
delta := a1 * b2 - a2 * b1;
RETURN Point{(b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta};
END FindIntersection;
VAR
l1,l2 : Line;
result : Point;
BEGIN
l1 := Line{{4.0,0.0}, {6.0,10.0}};
l2 := Line{{0.0,3.0}, {10.0,7.0}};
PrintPoint(FindIntersection(l1,l2));
WriteLn;
l1 := Line{{0.0,0.0}, {1.0,1.0}};
l2 := Line{{1.0,2.0}, {4.0,5.0}};
PrintPoint(FindIntersection(l1,l2));
WriteLn;
ReadChar;
END LineIntersection.
|
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].
|
#Python
|
Python
|
#!/bin/python
from __future__ import print_function
import numpy as np
def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):
ndotu = planeNormal.dot(rayDirection)
if abs(ndotu) < epsilon:
raise RuntimeError("no intersection or line is within plane")
w = rayPoint - planePoint
si = -planeNormal.dot(w) / ndotu
Psi = w + si * rayDirection + planePoint
return Psi
if __name__=="__main__":
#Define plane
planeNormal = np.array([0, 0, 1])
planePoint = np.array([0, 0, 5]) #Any point on the plane
#Define ray
rayDirection = np.array([0, -1, -1])
rayPoint = np.array([0, 0, 10]) #Any point along the ray
Psi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint)
print ("intersection at", Psi)
|
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
|
#ATS
|
ATS
|
#include "share/atspre_staload.hats"
implement main0() = loop(1, 100) where {
fun loop(from: int, to: int): void =
if from > to then () else
let
val by3 = (from % 3 = 0)
val by5 = (from % 5 = 0)
in
case+ (by3, by5) of
| (true, true) => print_string("FizzBuzz")
| (true, false) => print_string("Fizz")
| (false, true) => print_string("Buzz")
| (false, false) => print_int(from);
print_newline();
loop(from+1, to)
end
}
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#Icon_and_Unicon
|
Icon and Unicon
|
link datetime,printf
procedure main(A) # five weekends
printf( "There are %d months from %d to %d with five full weekends.\n",
*(L := fiveweekends(s := 1900, f := 2100)), s,f)
printf("The first and last five such months are:\n")
every printf("%s\n",L[1 to 5]|"..."|L[-4 to 0])
printf( "There are %d years without such months as follows:\n",
*(M := Bonus(s,f,L)))
every printf("%s\n",!M)
end
procedure fiveweekends(start,finish)
L := [] # months years with five weekends FRI-SUN
every year := start to finish & month := 1 to 12 do
if month = (2|4|6|9|11) then next
else if julian(month,1,year) % 7 = 4 then
put(L,sprintf("%d-%d-1",year,month))
return L
end
procedure Bonus(start,finish,fwe)
every insert(Y := set(), start to finish)
every insert(F := set(), integer(!fwe ? tab(find("-"))))
return sort(Y--F)
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
|
#Lasso
|
Lasso
|
#!/usr/bin/lasso9
define cube(x::decimal) => {
return #x -> pow(3.0)
}
define cuberoot(x::decimal) => {
return #x -> pow(1.0/3.0)
}
define compose(f, g, v) => {
return {
return #f -> detach -> invoke(#g -> detach -> invoke(#1))
} -> detach -> invoke(#v)
}
local(functions = array({return #1 -> sin}, {return #1 -> cos}, {return cube(#1)}))
local(inverse = array({return #1 -> asin}, {return #1 -> acos}, {return cuberoot(#1)}))
loop(3)
stdoutnl(
compose(
#functions -> get(loop_count),
#inverse -> get(loop_count),
0.5
)
)
/loop
|
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
|
#Lingo
|
Lingo
|
-- sin, cos and sqrt are built-in, square, asin and acos are user-defined
A = [#sin, #cos, #square]
B = [#asin, #acos, #sqrt]
testValue = 0.5
repeat with i = 1 to 3
-- for implementation details of compose() see https://www.rosettacode.org/wiki/Function_composition#Lingo
f = compose(A[i], B[i])
res = call(f, _movie, testValue)
put res = testValue
end repeat
|
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.
|
#Racket
|
Racket
|
#lang racket
(require 2htdp/universe)
(require 2htdp/image)
(define (initial-forest w p-tree)
(for/vector #:length w ((rw w))
(for/vector #:length w ((cl w))
(if (< (random) p-tree) #\T #\_))))
(define (has-burning-neighbour? forest r# c# w)
;; note, this will check r# c#, too but it's not
;; worth checking that r=r# and c=c# each time in
;; this case
(for*/first
((r (in-range (- r# 1) (+ r# 2)))
#:when (< 0 r w)
(c (in-range (- c# 1) (+ c# 2)))
#:when (< 0 c w)
#:when (equal? #\* (vector-ref (vector-ref forest r) c)))
#t))
(define (fire-tick forest p-sprout f-combust w)
(for/vector #:length w ((rw forest) (r# (in-naturals)))
(for/vector #:length w ((cl rw) (c# (in-naturals)))
(case cl
((#\_) (if (< (random) p-sprout) #\T #\_))
((#\*) #\_)
((#\T)
(cond
[(has-burning-neighbour? forest r# c# w) #\*]
[(< (random) f-combust) #\*]
[else #\T]))))))
(define (render-forest state)
(for/fold
((scn (empty-scene
(* (vector-length state) 8)
(* (vector-length (vector-ref state 0)) 8)
'black)))
((rw state) (r# (in-naturals)))
(for/fold
((scn scn))
((cl rw) (c# (in-naturals)))
(place-image (circle 4 'solid
(case cl
((#\_) 'brown)
((#\T) 'green)
((#\*) 'red)))
(+ 4 (* c# 8)) (+ 4 (* r# 8)) scn))))
(define (forest-fire p-tree p-sprout f-combust w)
(big-bang
(initial-forest w p-tree) ;; initial state
[on-tick (lambda (state)
;(displayln state)
(fire-tick state p-sprout f-combust w))]
[to-draw render-forest]))
(forest-fire 0 1/8 1/1024 50)
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Groovy
|
Groovy
|
assert [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten() == [1, 2, 3, 4, 5, 6, 7, 8]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#OxygenBasic
|
OxygenBasic
|
function Floyd(sys n) as string
sys i,t
for i=1 to n
t+=i
next
string s=str t
sys le=1+len s
string cr=chr(13,10)
sys lc=len cr
string buf=space(le*t+n*lc)
sys j,o,p=1
t=0
for i=1 to n
for j=1 to i
t++
s=str t
o=le-len(s)-1 'right justify
mid buf,p+o,str t
p+=le
next
mid buf,p,cr
p+=lc
next
return left buf,p-1
end function
putfile "s.txt",Floyd(5)+floyd(14)
|
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.
|
#PARI.2FGP
|
PARI/GP
|
{floyd(m)=my(lastrow_a,lastrow_e,lastrow_len=m,fl,idx);
\\ +++ fl is a vector of fieldlengths in the last row
lastrow_e=m*(m+1)/2;lastrow_a=lastrow_e+1-m;
fl=vector(lastrow_len);
for(k=1,m,fl[k] = 1 + #Str(k-1+lastrow_a) );
\\
idx=0;
for(i=1,m,
for(j=1,i,
idx++;
printf(Str("%" fl[j] "d"),idx)
);
print()
);
return();}
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)
|
#zkl
|
zkl
|
fcn FloydWarshallWithPathReconstruction(dist){ // dist is munged
V:=dist[0].len();
next:=V.pump(List,V.pump(List,Void.copy).copy); // VxV matrix of Void
foreach u,v in (V,V){ if(dist[u][v]!=Void and u!=v) next[u][v] = v }
foreach k,i,j in (V,V,V){
a,b,c:=dist[i][j],dist[i][k],dist[k][j];
if( (a!=Void and b!=Void and c!=Void and a>b+c) or // Inf math
(a==Void and b!=Void and c!=Void) ){
dist[i][j] = b+c;
next[i][j] = next[i][k];
}
}
return(dist,next)
}
fcn path(next,u,v){
if(Void==next[u][v]) return(T);
path:=List(u);
while(u!=v){ path.append(u = next[u][v]) }
path
}
fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%5s "*row.len()).fmt(row.xplode()) }
|
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).
|
#Wren
|
Wren
|
var xor = Fn.new { |a, b| a&(~b) | b&(~a) }
var ha = Fn.new { |a, b| [xor.call(a, b), a & b] }
var fa = Fn.new { |a, b, c0|
var res = ha.call(a, c0)
var sa = res[0]
var ca = res[1]
res = ha.call(sa, b)
return [res[0], ca | res[1]]
}
var add4 = Fn.new { |a3, a2, a1, a0, b3, b2, b1, b0|
var res = fa.call(a0, b0, 0)
var s0 = res[0]
var c0 = res[1]
res = fa.call(a1, b1, c0)
var s1 = res[0]
var c1 = res[1]
res = fa.call(a2, b2, c1)
var s2 = res[0]
var c2 = res[1]
res = fa.call(a3, b3, c2)
return [res[1], res[0], s2, s1, s0]
}
System.print(add4.call(1, 0, 1, 0, 1, 0, 0, 1))
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
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)
|
#Factor
|
Factor
|
USING: io math.combinatorics sequences sets ;
"ABCD" all-permutations lines diff first print
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
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
|
#Groovy
|
Groovy
|
enum Day {
Sun, Mon, Tue, Wed, Thu, Fri, Sat
static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) }
}
def date = Date.&parse.curry('yyyy-MM-dd')
def month = { it.format('MM') }
def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) }
def weekDays = { dayOfWeek, year -> days(year).findAll { Day.valueOf(it) == dayOfWeek } }
def lastWeekDays = { dayOfWeek, year ->
weekDays(dayOfWeek, year).reverse().inject([:]) { months, sunday ->
def monthStr = month(sunday)
!months[monthStr] ? months + [(monthStr):sunday] : months
}.values().sort()
}
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Nim
|
Nim
|
type
Line = tuple
slope: float
yInt: float
Point = tuple
x: float
y: float
func createLine(a, b: Point): Line =
result.slope = (b.y - a.y) / (b.x - a.x)
result.yInt = a.y - result.slope * a.x
func evalX(line: Line, x: float): float =
line.slope * x + line.yInt
func intersection(line1, line2: Line): Point =
let x = (line2.yInt - line1.yInt) / (line1.slope - line2.slope)
let y = evalX(line1, x)
(x, y)
var line1 = createLine((4.0, 0.0), (6.0, 10.0))
var line2 = createLine((0.0, 3.0), (10.0, 7.0))
echo intersection(line1, line2)
line1 = createLine((0.0, 0.0), (1.0, 1.0))
line2 = createLine((1.0, 2.0), (4.0, 5.0))
echo intersection(line1, line2)
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Perl
|
Perl
|
sub intersect {
my ($x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4) = @_;
my $a1 = $y2 - $y1;
my $b1 = $x1 - $x2;
my $c1 = $a1 * $x1 + $b1 * $y1;
my $a2 = $y4 - $y3;
my $b2 = $x3 - $x4;
my $c2 = $a2 * $x3 + $b2 * $y3;
my $delta = $a1 * $b2 - $a2 * $b1;
return (undef, undef) if $delta == 0;
# If delta is 0, i.e. lines are parallel then the below will fail
my $ix = ($b2 * $c1 - $b1 * $c2) / $delta;
my $iy = ($a1 * $c2 - $a2 * $c1) / $delta;
return ($ix, $iy);
}
my ($ix, $iy) = intersect(4, 0, 6, 10, 0, 3, 10, 7);
print "$ix $iy\n";
($ix, $iy) = intersect(0, 0, 1, 1, 1, 2, 4, 5);
print "$ix $iy\n";
|
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].
|
#R
|
R
|
intersect_point <- function(ray_vec, ray_point, plane_normal, plane_point) {
pdiff <- ray_point - plane_point
prod1 <- pdiff %*% plane_normal
prod2 <- ray_vec %*% plane_normal
prod3 <- prod1 / prod2
point <- ray_point - ray_vec * as.numeric(prod3)
return(point)
}
|
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
|
Find the intersection of a line with a plane
|
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
|
#Racket
|
Racket
|
#lang racket
;; {{trans|Sidef}}
;; vectors are represented by lists
(struct Line (P0 u⃗))
(struct Plane (V0 n⃗))
(define (· a b) (apply + (map * a b)))
(define (line-plane-intersection L P)
(match-define (cons (Line P0 u⃗) (Plane V0 n⃗)) (cons L P))
(define cos (· n⃗ u⃗))
(when (zero? cos) (error "vectors are orthoganal"))
(define W (map - P0 V0))
(define *SI (let ((SI (- (/ (· n⃗ W) cos)))) (λ (n) (* SI n))))
(map + W (map *SI u⃗) V0))
(module+ test
(require rackunit)
(check-equal?
(line-plane-intersection (Line '(0 0 10) '(0 -1 -1))
(Plane '(0 0 5) '(0 0 1)))
'(0 -5 5)))
|
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
|
#AutoHotkey
|
AutoHotkey
|
Loop, 100
{
If (Mod(A_Index, 15) = 0)
output .= "FizzBuzz`n"
Else If (Mod(A_Index, 3) = 0)
output .= "Fizz`n"
Else If (Mod(A_Index, 5) = 0)
output .= "Buzz`n"
Else
output .= A_Index "`n"
}
FileDelete, output.txt
FileAppend, %output%, output.txt
Run, cmd /k type output.txt
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#Inform_7
|
Inform 7
|
Calendar is a room.
When play begins:
let happy month count be 0;
let sad year count be 0;
repeat with Y running from Y1900 to Y2100:
if Y is a sad year, increment the sad year count;
repeat with M running through months:
if M of Y is a happy month:
say "[M] [year number of Y].";
increment the happy month count;
say "Found [happy month count] month[s] with five weekends and [sad year count] year[s] with no such months.";
end the story.
Section - Years
A year is a kind of value. Y1 specifies a year.
To decide which number is year number of (Y - year):
decide on Y / Y1.
To decide if (N - number) is divisible by (M - number):
decide on whether or not the remainder after dividing N by M is zero.
Definition: a year (called Y) is a leap year:
let YN be the year number of Y;
if YN is divisible by 400, yes;
if YN is divisible by 100, no;
if YN is divisible by 4, yes;
no.
Section - Months
A month is a kind of value. The months are defined by the Table of Months.
Table of Months
month month number
January 1
February 2
March 3
April 4
May 5
June 6
July 7
August 8
September 9
October 10
November 11
December 12
A month has a number called length. The length of a month is usually 31.
September, April, June, and November have length 30. February has length 28.
To decide which number is number of days in (M - month) of (Y - year):
let L be the length of M;
if M is February and Y is a leap year, decide on L + 1;
otherwise decide on L.
Section - Weekdays
A weekday is a kind of value. The weekdays are defined by the Table of Weekdays.
Table of Weekdays
weekday weekday number
Saturday 0
Sunday 1
Monday 2
Tuesday 3
Wednesday 4
Thursday 5
Friday 6
To decide which weekday is weekday of the/-- (N - number) of (M - month) of (Y - year):
let MN be the month number of M;
let YN be the year number of Y;
if MN is less than 3:
increase MN by 12;
decrease YN by 1;
let h be given by Zeller's Congruence;
let WDN be the remainder after dividing h by 7;
decide on the weekday corresponding to a weekday number of WDN in the Table of Weekdays.
Equation - Zeller's Congruence
h = N + ((MN + 1)*26)/10 + YN + YN/4 + 6*(YN/100) + YN/400
where h is a number, N is a number, MN is a number, and YN is a number.
To decide which number is number of (W - weekday) days in (M - month) of (Y - year):
let count be 0;
repeat with N running from 1 to the number of days in M of Y:
if W is the weekday of the N of M of Y, increment count;
decide on count.
Section - Happy Months and Sad Years
To decide if (M - month) of (Y - year) is a happy month:
if the number of days in M of Y is 31 and the weekday of the 1st of M of Y is Friday, decide yes;
decide no.
To decide if (Y - year) is a sad year:
repeat with M running through months:
if M of Y is a happy month, decide no;
decide yes.
|
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
|
#J
|
J
|
require 'types/datetime numeric'
find5wkdMonths=: verb define
years=. range 2{. y
months=. 1 3 5 7 8 10 12
m5w=. (#~ 0 = weekday) >,{years;months;31 NB. 5 full weekends iff 31st is Sunday(0)
>'MMM YYYY' fmtDate toDayNo m5w
)
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#Lua
|
Lua
|
function compose(f,g) return function(...) return f(g(...)) end end
fn = {math.sin, math.cos, function(x) return x^3 end}
inv = {math.asin, math.acos, function(x) return x^(1/3) end}
for i, v in ipairs(fn) do
local f = compose(v, inv[i])
print(f(0.5))
end
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module CheckFirst {
RAD = lambda -> number/180*pi
ASIN = lambda RAD -> {
Read x : x=Round(x,10)
If x>=0 and X<1 Then {
=RAD(abs(2*Round(ATN(x/(1+SQRT(1-x**2))))))
} Else.if x==1 Then {
=RAD(90)
} Else error "asin exit limit"
}
ACOS=lambda ASIN (x) -> PI/2 - ASIN(x)
POW3 = Lambda ->number**3
POW3INV =Lambda ->number**(1/3)
COSRAD =lambda ->Cos(number*180/pi)
SINRAD=lambda ->Sin(number*180/pi)
Composed=lambda (f1, f2) -> {
=lambda f1, f2 (x)->{
=f1(f2(x))
}
}
Dim Base 0, A(3), B(3), C(3)
A(0)=ACOS, ASIN, POW3INV
B(0)=COSRAD, SINRAD, POW3
C(0)=Composed(ACOS, COSRAD), Composed(ASIN, SINRAD), Composed(POW3INV, POW3)
Print $("0.00")
For i=0 To 2 {
Print A(i)(B(i)(.5)), C(i)(.5)
}
}
CheckFirst
|
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.
|
#Raku
|
Raku
|
my $RED = "\e[1;31m";
my $YELLOW = "\e[1;33m";
my $GREEN = "\e[1;32m";
my $CLEAR = "\e[0m";
enum Cell-State <Empty Tree Heating Burning>;
my @pix = ' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木';
class Forest {
has Rat $.p = 0.01;
has Rat $.f = 0.001;
has Int $!height;
has Int $!width;
has @!coords;
has @!spot;
has @!neighbors;
method BUILD (Int :$!height, Int :$!width) {
@!coords = ^$!height X ^$!width;
@!spot = [ (Bool.pick ?? Tree !! Empty) xx $!width ] xx $!height;
self!init-neighbors;
}
method !init-neighbors {
for @!coords -> ($i, $j) {
@!neighbors[$i][$j] = eager gather for
[-1,-1],[+0,-1],[+1,-1],
[-1,+0], [+1,+0],
[-1,+1],[+0,+1],[+1,+1]
{
take-rw @!spot[$i + .[0]][$j + .[1]] // next;
}
}
}
method step {
my @heat;
for @!coords -> ($i, $j) {
given @!spot[$i][$j] {
when Empty { $_ = Tree if rand < $!p }
when Tree { $_ = Heating if rand < $!f }
when Heating { $_ = Burning; push @heat, ($i, $j); }
when Burning { $_ = Empty }
}
}
for @heat -> ($i,$j) {
$_ = Heating for @!neighbors[$i][$j].grep(Tree);
}
}
method show {
for ^$!height -> $i {
say @pix[@!spot[$i].list].join;
}
}
}
my ($ROWS, $COLS) = qx/stty size/.words;
signal(SIGINT).act: { print "\e[H\e[2J"; exit }
sub MAIN (Int $height = $ROWS - 2, Int $width = +$COLS div 2 - 1) {
my Forest $forest .= new(:$height, :$width);
print "\e[2J"; # ANSI clear screen
loop {
print "\e[H"; # ANSI home
say $++;
$forest.show;
$forest.step;
}
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Haskell
|
Haskell
|
import Data.Tree (Tree(..), flatten)
-- [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
-- implemented as multiway tree:
-- Data.Tree represents trees where nodes have values too, unlike the trees in our problem.
-- so we use a list as that value, where a node will have an empty list value,
-- and a leaf will have a one-element list value and no subtrees
list :: Tree [Int]
list =
Node
[]
[ Node [] [Node [1] []]
, Node [2] []
, Node [] [Node [] [Node [3] [], Node [4] []], Node [5] []]
, Node [] [Node [] [Node [] []]]
, Node [] [Node [] [Node [6] []]]
, Node [7] []
, Node [8] []
, Node [] []
]
flattenList :: Tree [a] -> [a]
flattenList = concat . flatten
main :: IO ()
main = print $ flattenList list
|
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.
|
#Pascal
|
Pascal
|
Program FloydDemo (input, output);
function digits(number: integer): integer;
begin
digits := trunc(ln(number) / ln(10)) + 1;
end;
procedure floyd1 (numberOfLines: integer);
{ variant with repeat .. until loop }
var
i, j, numbersInLine, startOfLastlLine: integer;
begin
startOfLastlLine := (numberOfLines - 1) * numberOfLines div 2 + 1;
i := 1;
j := 1;
numbersInLine := 1;
repeat
repeat
write(i: digits(startOfLastlLine - 1 + j), ' ');
inc(i);
inc(j);
until (j > numbersInLine);
writeln;
j := 1;
inc(numbersInLine);
until (numbersInLine > numberOfLines);
end;
procedure floyd2 (numberOfLines: integer);
{ Variant with for .. do loop }
var
i, j, numbersInLine, startOfLastlLine: integer;
begin
startOfLastlLine := (numberOfLines - 1) * numberOfLines div 2 + 1;
i := 1;
for numbersInLine := 1 to numberOfLines do
begin
for j := 1 to numbersInLine do
begin
write(i: digits(startOfLastlLine - 1 + j), ' ');
inc(i);
end;
writeln;
end;
end;
begin
writeln ('*** Floyd 5 ***');
floyd1(5);
writeln;
writeln ('*** Floyd 14 ***');
floyd2(14);
end.
|
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).
|
#XPL0
|
XPL0
|
code CrLf=9, IntOut=11;
func Not(A);
int A;
return not A;
func And(A, B);
int A, B;
return A and B;
func Or(A, B);
int A, B;
return A or B;
func Xor(A, B);
int A, B;
return Or(And(A, Not(B)), And(Not(A), B));
proc HalfAdd(A, B, S, C);
int A, B, S, C;
[S(0):= Xor(A, B);
C(0):= And(A, B);
];
proc FullAdd(A, B, Ci, S, Co);
int A, B, Ci, S, Co; \(Ci and Co are reversed from drawing)
int S0, S1, C0, C1;
[HalfAdd(Ci, A, @S0, @C0);
HalfAdd(S0, B, @S1, @C1);
S(0):= S1;
Co(0):= Or(C0, C1);
];
proc Add4Bits(A0, A1, A2, A3, B0, B1, B2, B3, S0, S1, S2, S3, Co);
int A0, A1, A2, A3, B0, B1, B2, B3, S0, S1, S2, S3, Co;
int Co0, Co1, Co2;
[FullAdd(A0, B0, 0, S0, @Co0);
FullAdd(A1, B1, Co0, S1, @Co1);
FullAdd(A2, B2, Co1, S2, @Co2);
FullAdd(A3, B3, Co2, S3, Co);
];
proc BinOut(D, A0, A1, A2, A3, C);
int D, A0, A1, A2, A3, C;
[IntOut(D, C&1);
IntOut(D, A3&1);
IntOut(D, A2&1);
IntOut(D, A1&1);
IntOut(D, A0&1);
];
int S0, S1, S2, S3, C;
[Add4Bits(1, 0, 0, 0, 0, 0, 1, 0, @S0, @S1, @S2, @S3, @C); \0001 + 0100 = 00101
BinOut(0, S0, S1, S2, S3, C); CrLf(0);
Add4Bits(1, 0, 1, 0, 0, 1, 1, 1, @S0, @S1, @S2, @S3, @C); \0101 + 1110 = 10011
BinOut(0, S0, S1, S2, S3, C); CrLf(0);
Add4Bits(1, 1, 1, 1, 1, 1, 1, 1, @S0, @S1, @S2, @S3, @C); \1111 + 1111 = 11110
BinOut(0, S0, S1, S2, S3, C); CrLf(0);
]
|
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)
|
#Forth
|
Forth
|
hex
ABCD CABD xor ACDB xor DACB xor BCDA xor ACBD xor
ADCB xor CDAB xor DABC xor BCAD xor CADB xor CDBA xor
CBAD xor ABDC xor ADBC xor BDCA xor DCBA xor BACD xor
BADC xor BDAC xor CBDA xor DBCA xor DCAB xor
cr .( Missing permutation: ) u.
decimal
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
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)
|
#Fortran
|
Fortran
|
program missing_permutation
implicit none
character (4), dimension (23), parameter :: list = &
& (/'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB', &
& 'DABC', 'BCAD', 'CADB', 'CDBA', 'CBAD', 'ABDC', 'ADBC', 'BDCA', &
& 'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'/)
integer :: i, j, k
do i = 1, 4
j = minloc ((/(count (list (:) (i : i) == list (1) (k : k)), k = 1, 4)/), 1)
write (*, '(a)', advance = 'no') list (1) (j : j)
end do
write (*, *)
end program missing_permutation
|
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
|
#Haskell
|
Haskell
|
import Data.List (find, intercalate, transpose)
import Data.Maybe (fromJust)
import Data.Time.Calendar
( Day,
addDays,
fromGregorian,
gregorianMonthLength,
showGregorian,
)
import Data.Time.Calendar.WeekDate (toWeekDate)
---------------- LAST SUNDAY OF EACH MONTH ---------------
lastSundayOfEachMonth = lastWeekDayDates 7
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
putStrLn
( intercalate " "
<$> transpose
(lastSundayOfEachMonth <$> [2013 .. 2017])
)
------------------- NEAREST DAY OF WEEK ------------------
lastWeekDayDates :: Int -> Integer -> [String]
lastWeekDayDates dayOfWeek year =
(showGregorian . mostRecentWeekday dayOfWeek)
. (fromGregorian year <*> gregorianMonthLength year)
<$> [1 .. 12]
mostRecentWeekday :: Int -> Day -> Day
mostRecentWeekday dayOfWeek date =
fromJust
(find p ((`addDays` date) <$> [-6 .. 0]))
where
p x =
let (_, _, day) = toWeekDate x
in dayOfWeek == day
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Phix
|
Phix
|
with javascript_semantics
enum X, Y
function abc(sequence s,e)
-- yeilds {a,b,c}, corresponding to ax+by=c
atom a = e[Y]-s[Y], b = s[X]-e[X], c = a*s[X]+b*s[Y]
return {a,b,c}
end function
procedure intersect(sequence s1, e1, s2, e2)
atom {a1,b1,c1} = abc(s1,e1),
{a2,b2,c2} = abc(s2,e2),
delta = a1*b2 - a2*b1,
x = b2*c1 - b1*c2,
y = a1*c2 - a2*c1
?iff(delta=0?"parallel lines/do not intersect"
:{x/delta, y/delta})
end procedure
intersect({4,0},{6,10},{0,3},{10,7}) -- {5,5}
intersect({4,0},{6,10},{0,3},{10,7.1}) -- {5.010893246,5.054466231}
intersect({0,0},{0,0},{0,3},{10,7}) -- "parallel lines/do not intersect"
intersect({0,0},{1,1},{1,2},{4,5}) -- "parallel lines/do not intersect"
intersect({1,-1},{4,4},{2,5},{3,-2}) -- {2.5,1.5}
|
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].
|
#Raku
|
Raku
|
class Line {
has $.P0; # point
has $.u⃗; # ray
}
class Plane {
has $.V0; # point
has $.n⃗; # normal
}
sub infix:<∙> ( @a, @b where +@a == +@b ) { [+] @a «*» @b } # dot product
sub line-plane-intersection ($𝑳, $𝑷) {
my $cos = $𝑷.n⃗ ∙ $𝑳.u⃗; # cosine between normal & ray
return 'Vectors are orthogonal; no intersection or line within plane'
if $cos == 0;
my $𝑊 = $𝑳.P0 «-» $𝑷.V0; # difference between P0 and V0
my $S𝐼 = -($𝑷.n⃗ ∙ $𝑊) / $cos; # line segment where it intersects the plane
$𝑊 «+» $S𝐼 «*» $𝑳.u⃗ «+» $𝑷.V0; # point where line intersects the plane
}
say 'Intersection at point: ', line-plane-intersection(
Line.new( :P0(0,0,10), :u⃗(0,-1,-1) ),
Plane.new( :V0(0,0, 5), :n⃗(0, 0, 1) )
);
|
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
|
#AutoIt
|
AutoIt
|
For $i = 1 To 100
If Mod($i, 15) = 0 Then
MsgBox(0, "FizzBuzz", "FizzBuzz")
ElseIf Mod($i, 5) = 0 Then
MsgBox(0, "FizzBuzz", "Buzz")
ElseIf Mod($i, 3) = 0 Then
MsgBox(0, "FizzBuzz", "Fizz")
Else
MsgBox(0, "FizzBuzz", $i)
EndIf
Next
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#Java
|
Java
|
import java.util.Calendar;
import java.util.GregorianCalendar;
public class FiveFSS {
private static boolean[] years = new boolean[201];
private static int[] month31 = {Calendar.JANUARY, Calendar.MARCH, Calendar.MAY,
Calendar.JULY, Calendar.AUGUST, Calendar.OCTOBER, Calendar.DECEMBER};
public static void main(String[] args) {
StringBuilder months = new StringBuilder();
int numMonths = 0;
for (int year = 1900; year <= 2100; year++) {
for (int month : month31) {
Calendar date = new GregorianCalendar(year, month, 1);
if (date.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
years[year - 1900] = true;
numMonths++;
//months are 0-indexed in Calendar
months.append((date.get(Calendar.MONTH) + 1) + "-" + year +"\n");
}
}
}
System.out.println("There are "+numMonths+" months with five weekends from 1900 through 2100:");
System.out.println(months);
System.out.println("Years with no five-weekend months:");
for (int year = 1900; year <= 2100; year++) {
if(!years[year - 1900]){
System.out.println(year);
}
}
}
}
|
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
|
#Maple
|
Maple
|
> A := [ sin, cos, x -> x^3 ]:
> B := [ arcsin, arccos, rcurry( surd, 3 ) ]:
> zip( `@`, A, B )( 2/3 );
[2/3, 2/3, 2/3]
> zip( `@`, B, A )( 2/3 );
[2/3, 2/3, 2/3]
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
funcs = {Sin, Cos, #^3 &};
funcsi = {ArcSin, ArcCos, #^(1/3) &};
compositefuncs = Composition @@@ Transpose[{funcs, funcsi}];
Table[i[0.666], {i, compositefuncs}]
|
http://rosettacode.org/wiki/Forest_fire
|
Forest fire
|
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the 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.
|
#REXX
|
REXX
|
┌───────────────────────────elided version──────────────────────────┐
├─── original version has many more options & enhanced displays. ───┤
└───────────────────────────────────────────────────────────────────┘
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Hy
|
Hy
|
(defn flatten [lst]
(sum (genexpr (if (isinstance x list)
(flatten x)
[x])
[x lst])
[]))
(print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]))
; [1, 2, 3, 4, 5, 6, 7, 8]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#Perl
|
Perl
|
#!/usr/bin/env perl
use strict;
use warnings;
sub displayFloydTriangle {
my $numRows = shift;
print "\ndisplaying a $numRows row Floyd's triangle:\n\n";
my $maxVal = int($numRows * ($numRows + 1) / 2); # calculate the max value.
my $digit = 0;
foreach my $row (1 .. $numRows) {
my $col = 0;
my $output = '';
foreach (1 .. $row) {
++$digit;
++$col;
my $colMaxDigit = $maxVal - $numRows + $col;
$output .= sprintf " %*d", length($colMaxDigit), $digit;
}
print "$output\n";
}
return;
}
# ==== Main ================================================
my @counts;
@counts = @ARGV;
@counts = (5, 14) unless @ARGV;
foreach my $count (@counts) {
displayFloydTriangle($count);
}
0;
__END__
|
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).
|
#zkl
|
zkl
|
fcn xor(a,b) // a,b are 1|0 -->a^b(1|0)
{ a.bitAnd(b.bitNot()).bitOr(b.bitAnd(a.bitNot())) }
fcn halfAdder(a,b) // -->(carry, a+b) (1|0)
{ return(a.bitAnd(b), xor(a,b)) }
fcn fullBitAdder(c, a,b){ //-->(carry, a+b+c), a,b,c are 1|0
c1,s := halfAdder(a,c);
c2,s := halfAdder(s,b);
c3 := c1.bitOr(c2);
return(c3,s);
}
// big endian
fcn fourBitAdder(a3,a2,a1,a0, b3,b2,b1,b0){ //-->(carry, s3,s2,s1,s0)
c,s0 := fullBitAdder(0, a0,b0);
c,s1 := fullBitAdder(c, a1,b1);
c,s2 := fullBitAdder(c, a2,b2);
c,s3 := fullBitAdder(c, a3,b3);
return(c, s3,s2,s1,s0);
}
// add(10,9) result should be 1 0 0 1 1 (0x13, 3 carry 1)
println(fourBitAdder(1,0,1,0, 1,0,0,1));
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
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)
|
#FreeBASIC
|
FreeBASIC
|
' version 30-03-2017
' compile with: fbc -s console
Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD"
Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA"
Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD"
Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
' ------=< MAIN >=------
Dim As ulong total(3, Asc("A") To Asc("D")) ' total(0 to 3, 65 to 68)
Dim As ULong i, j, n = 24 \ 4 ' n! \ n
Dim As String tmp
For i = 1 To 23
Read tmp
For j = 0 To 3
total(j, tmp[j]) += 1
Next
Next
tmp = Space(4)
For i = 0 To 3
For j = Asc("A") To Asc("D")
If total(i, j) <> n Then
tmp[i] = j
End If
Next
Next
Print "The missing permutation is : "; tmp
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
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
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main(A)
every write(lastsundays(!A))
end
procedure lastsundays(year)
every m := 1 to 12 do {
d := case m of {
2 : if IsLeapYear(year) then 29 else 28
4|6|9|11 : 30
default : 31
} # last day of month
z := 0
j := julian(m,d,year) + 1 # first day of next month
until (j-:=1)%7 = 6 do z -:=1 # backup to last sunday (6)
suspend sprintf("%d-%d-%d",year,m,d+z)
}
end
link datetime, printf
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Processing
|
Processing
|
void setup() {
// test lineIntersect() with visual and textual output
float lineA[] = {4, 0, 6, 10}; // try 4, 0, 6, 4
float lineB[] = {0, 3, 10, 7}; // for non intersecting test
PVector pt = lineInstersect(lineA[0], lineA[1], lineA[2], lineA[3],
lineB[0], lineB[1], lineB[2], lineB[3]);
scale(9);
line(lineA[0], lineA[1], lineA[2], lineA[3]);
line(lineB[0], lineB[1], lineB[2], lineB[3]);
if (pt != null) {
stroke(255);
point(pt.x, pt.y);
println(pt.x, pt.y);
} else {
println("No point");
}
}
PVector lineInstersect(float Ax1, float Ay1, float Ax2, float Ay2,
float Bx1, float By1, float Bx2, float By2) {
// returns null if there is no intersection
float uA, uB;
float d = ((By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1));
if (d != 0) {
uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d;
uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d;
} else {
return null;
}
if (0 > uA || uA > 1 || 0 > uB || uB > 1) {
return null;
}
float x = Ax1 + uA * (Ax2 - Ax1);
float y = Ay1 + uA * (Ay2 - Ay1);
return new PVector(x, y);
}
|
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].
|
#REXX
|
REXX
|
/* REXX */
Parse Value '0 0 1' With n.1 n.2 n.3 /* Normal Vector of the plane */
Parse Value '0 0 5' With p.1 p.2 p.3 /* Point in the plane */
Parse Value '0 0 10' With a.1 a.2 a.3 /* Point of the line */
Parse Value '0 -1 -1' With v.1 v.2 v.3 /* Vector of the line */
a=n.1
b=n.2
c=n.3
d=n.1*p.1+n.2*p.2+n.3*p.3 /* Parameter form of the plane */
Say a'*x +' b'*y +' c'*z =' d
t=(d-(a*a.1+b*a.2+c*a.3))/(a*v.1+b*v.2+c*v.3)
x=a.1+t*v.1
y=a.2+t*v.2
z=a.3+t*v.3
Say 'Intersection: P('||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
|
#Avail
|
Avail
|
For each i from 1 to 100 do [
Print:
if i mod 15 = 0 then ["FizzBuzz"]
else if i mod 3 = 0 then ["Fizz"]
else if i mod 5 = 0 then ["Buzz"]
else [“i”]
++ "\n";
];
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#JavaScript
|
JavaScript
|
function startsOnFriday(month, year)
{
// 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
return new Date(year, month, 1).getDay() === 5;
}
function has31Days(month, year)
{
return new Date(year, month, 31).getDate() === 31;
}
function checkMonths(year)
{
var month, count = 0;
for (month = 0; month < 12; month += 1)
{
if (startsOnFriday(month, year) && has31Days(month, year))
{
count += 1;
document.write(year + ' ' + month + '<br>');
}
}
return count;
}
function fiveWeekends()
{
var
startYear = 1900,
endYear = 2100,
year,
monthTotal = 0,
yearsWithoutFiveWeekends = [],
total = 0;
for (year = startYear; year <= endYear; year += 1)
{
monthTotal = checkMonths(year);
total += monthTotal;
// extra credit
if (monthTotal === 0)
yearsWithoutFiveWeekends.push(year);
}
document.write('Total number of months: ' + total + '<br>');
document.write('<br>');
document.write(yearsWithoutFiveWeekends + '<br>');
document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '<br>');
}
fiveWeekends();
|
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
|
#Maxima
|
Maxima
|
a: [sin, cos, lambda([x], x^3)]$
b: [asin, acos, lambda([x], x^(1/3))]$
compose(f, g) := buildq([f, g], lambda([x], f(g(x))))$
map(lambda([fun], fun(x)), map(compose, a, b));
[x, x, x]
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#Mercury
|
Mercury
|
:- module firstclass.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module exception, list, math, std_util.
main(!IO) :-
Forward = [sin, cos, (func(X) = ln(X))],
Reverse = [asin, acos, (func(X) = exp(X))],
Results = map_corresponding(
(func(F, R) = compose(R, F, 0.5)),
Forward, Reverse),
write_list(Results, ", ", write_float, !IO),
write_string("\n", !IO).
|
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.
|
#Ring
|
Ring
|
# Project : Forest fire
load "guilib.ring"
load "stdlib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Forest fire")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
pregen = newlist(200,200)
newgen = newlist(200,200)
for gen = 1 to 20
see "gen = " + gen + nl
for x = 1 to 199
for y = 1 to 199
switch pregen[x][y]
on 0
if random(9)/10 > 0.099
newgen[x][y] = 1
color = new qcolor()
color.setrgb(0,128,0,255)
pen.setcolor(color)
setpen(pen)
drawpoint(x,y)
ok
on 2
newgen[x][y] = 0
color = new qcolor()
color.setrgb(165,42,42,255)
pen.setcolor(color)
setpen(pen)
drawpoint(x,y)
on 1
if pregen[x][y] = 2 or pregen[x][y] = 2 or pregen[x][y+1] = 2 or
pregen[x][y] = 2 or pregen[x][y+1] = 2 or pregen[x+1][y] = 2 or
pregen[x+1][y] = 2 or pregen[x+1][y+1] = 2 or random(9)/10 > 0.0999
color = new qcolor()
color.setrgb(255,0,0,255)
pen.setcolor(color)
setpen(pen)
drawpoint(x,y)
newgen[x][y] = 2
ok
off
pregen[x][y] = newgen[x][y]
next
next
next
endpaint()
}
label1 { setpicture(p1) show() }
return
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Icon_and_Unicon
|
Icon and Unicon
|
link strings # for compress,deletec,pretrim
procedure sflatten(s) # uninteresting string solution
return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',')
end
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#Phix
|
Phix
|
with javascript_semantics
procedure Floyds_triangle(integer n)
sequence widths = repeat(0,n)
integer k = (n * (n-1))/2
for i=1 to n do
widths[i] = sprintf("%%%dd",length(sprintf("%d",i+k))+1)
end for
k = 1
for i=1 to n do
for j=1 to i do
printf(1,widths[j],k)
k += 1
end for
printf(1,"\n")
end for
end procedure
Floyds_triangle(5)
Floyds_triangle(14)
|
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)
|
#GAP
|
GAP
|
# our deficient list
L :=
[ "ABCD", "CABD", "ACDB", "DACB", "BCDA",
"ACBD", "ADCB", "CDAB", "DABC", "BCAD",
"CADB", "CDBA", "CBAD", "ABDC", "ADBC",
"BDCA", "DCBA", "BACD", "BADC", "BDAC",
"CBDA", "DBCA", "DCAB" ];
# convert L to permutations on 1..4
u := List(L, s -> List([1..4], i -> Position("ABCD", s[i])));
# set difference (with all permutations)
v := Difference(PermutationsList([1..4]), u);
# convert back to letters
s := "ABCD";
List(v, p -> List(p, i -> s[i]));
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
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
|
#J
|
J
|
require'dates'
last_sundays=: 12 {. [: ({:/.~ }:"1)@(#~ 0 = weekday)@todate (i.366) + todayno@,&1 1
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Python
|
Python
|
def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
""" returns a (x, y) tuple or None if there is no intersection """
d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
if d:
uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d
else:
return
if not(0 <= uA <= 1 and 0 <= uB <= 1):
return
x = Ax1 + uA * (Ax2 - Ax1)
y = Ay1 + uA * (Ay2 - Ay1)
return x, y
if __name__ == '__main__':
(a, b), (c, d) = (4, 0), (6, 10) # try (4, 0), (6, 4)
(e, f), (g, h) = (0, 3), (10, 7) # for non intersecting test
pt = line_intersect(a, b, c, d, e, f, g, h)
print(pt)
|
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].
|
#Ruby
|
Ruby
|
require "matrix"
def intersectPoint(rayVector, rayPoint, planeNormal, planePoint)
diff = rayPoint - planePoint
prod1 = diff.dot planeNormal
prod2 = rayVector.dot planeNormal
prod3 = prod1 / prod2
return rayPoint - rayVector * prod3
end
def main
rv = Vector[0.0, -1.0, -1.0]
rp = Vector[0.0, 0.0, 10.0]
pn = Vector[0.0, 0.0, 1.0]
pp = Vector[0.0, 0.0, 5.0]
ip = intersectPoint(rv, rp, pn, pp)
puts "The ray intersects the plane at %s" % [ip]
end
main()
|
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
|
#AWK
|
AWK
|
For(I,1,100)
!If I^3??I^5
Disp "FIZZBUZZ",i
Else!If I^3
Disp "FIZZ",i
Else!If I^5
Disp "BUZZ",i
Else
Disp I▶Dec,i
End
.Pause to allow the user to actually read the output
Pause 1000
End
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#jq
|
jq
|
Use Zeller's Congruence to determine the day of the week, given
# year, month and day as integers in the conventional way.
# Emit 0 for Saturday, 1 for Sunday, etc.
#
def day_of_week(year; month; day):
if month == 1 or month == 2 then
[month + 12, year - 1]
else
[month, year]
end
| day + (13*(.[0] + 1)/5|floor)
+ (.[1]%100) + ((.[1]%100)/4|floor)
+ (.[1]/400|floor) - 2*(.[1]/100|floor)
| . % 7
;
|
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
|
#min
|
min
|
('sin 'cos (3 pow)) =A
('asin 'acos (1 3 / pow)) =B
(A bool) (
0.5 A first B first concat -> puts!
A rest #A
B rest #B
) while
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#Nemerle
|
Nemerle
|
using System;
using System.Console;
using System.Math;
using Nemerle.Collections.NCollectionsExtensions;
module FirstClassFunc
{
Main() : void
{
def cube = fun (x) {x * x * x};
def croot = fun (x) {Pow(x, 1.0/3.0)};
def compose = fun(f, g) {fun (x) {f(g(x))}};
def funcs = [Sin, Cos, cube];
def ifuncs = [Asin, Acos, croot];
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
}
}
|
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.
|
#Ruby
|
Ruby
|
class Forest_Fire
Neighborhood = [-1,0,1].product([-1,0,1]) - [0,0]
States = {empty:" ", tree:"T", fire:"#"}
def initialize(xsize, ysize=xsize, p=0.5, f=0.01)
@xsize, @ysize, @p, @f = xsize, ysize, p, f
@field = Array.new(xsize+1) {|i| Array.new(ysize+1, :empty)}
@generation = 0
end
def evolve
@generation += 1
work = @field.map{|row| row.map{|cell| cell}}
for i in 0...@xsize
for j in 0...@ysize
case cell=@field[i][j]
when :empty
cell = :tree if rand < @p
when :tree
cell = :fire if fire?(i,j)
else
cell = :empty
end
work[i][j] = cell
end
end
@field = work
end
def fire?(i,j)
rand < @f or Neighborhood.any? {|di,dj| @field[i+di][j+dj] == :fire}
end
def display
puts "Generation : #@generation"
puts @xsize.times.map{|i| @ysize.times.map{|j| States[@field[i][j]]}.join}
end
end
forest = Forest_Fire.new(10,30)
10.times do |i|
forest.evolve
forest.display
end
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Ioke
|
Ioke
|
iik> [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten
+> [1, 2, 3, 4, 5, 6, 7, 8]
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#PHP
|
PHP
|
<?php
floyds_triangle(5);
floyds_triangle(14);
function floyds_triangle($n) {
echo "n = " . $n . "\r\n";
for($r = 1, $i = 1, $c = 0; $r <= $n; $i++) {
$cols = ceil(log10($n*($n-1)/2 + $c + 2));
printf("%".$cols."d ", $i);
if(++$c == $r) {
echo "\r\n";
$r++;
$c = 0;
}
}
?>
|
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)
|
#Go
|
Go
|
package main
import (
"fmt"
"strings"
)
var given = strings.Split(`ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB`, "\n")
func main() {
b := make([]byte, len(given[0]))
for i := range b {
m := make(map[byte]int)
for _, p := range given {
m[p[i]]++
}
for char, count := range m {
if count&1 == 1 {
b[i] = char
break
}
}
}
fmt.Println(string(b))
}
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
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
|
#Java
|
Java
|
import java.util.Scanner;
public class LastSunday
{
static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};
public static int[] findLastSunday(int year)
{
boolean isLeap = isLeapYear(year);
int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31};
int[] lastDay=new int[12];
for(int m=0;i<12;i++)
{
int d;
for(d=days[m]; getWeekDay(year,m,d)!=0; d--)
;
lastDay[m]=d;
}
return lastDay;
}
private static boolean isLeapYear(int year)
{
if(year%4==0)
{
if(year%100!=0)
return true;
else if (year%400==0)
return true;
}
return false;
}
private static int getWeekDay(int y, int m, int d)
{
int f=y+d+3*m-1;
m++;
if(m<3)
y--;
else
f-=(int)(0.4*m+2.3);
f+=(int)(y/4)-(int)((y/100+1)*0.75);
f%=7;
return f;
}
private static void display(int year, int[] lastDay)
{
System.out.println("\nYEAR: "+year);
for(int m=0;i<12;i++)
System.out.println(months[m]+": "+lastDay[m]);
}
public static void main(String[] args) throws Exception
{
System.out.print("Enter year: ");
Scanner s=new Scanner(System.in);
int y=Integer.parseInt(s.next());
int[] lastDay = findLastSunday(y);
display(y, lastDay);
s.close();
}
}
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Racket
|
Racket
|
#lang racket/base
(define (det a b c d) (- (* a d) (* b c))) ; determinant
(define (line-intersect ax ay bx by cx cy dx dy) ; --> (values x y)
(let* ((det.ab (det ax ay bx by))
(det.cd (det cx cy dx dy))
(abΔx (- ax bx))
(cdΔx (- cx dx))
(abΔy (- ay by))
(cdΔy (- cy dy))
(xnom (det det.ab abΔx det.cd cdΔx))
(ynom (det det.ab abΔy det.cd cdΔy))
(denom (det abΔx abΔy cdΔx cdΔy)))
(when (zero? denom)
(error 'line-intersect "parallel lines"))
(values (/ xnom denom) (/ ynom denom))))
(module+ test (line-intersect 4 0 6 10
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) .
|
#Raku
|
Raku
|
sub intersection (Real $ax, Real $ay, Real $bx, Real $by,
Real $cx, Real $cy, Real $dx, Real $dy ) {
sub term:<|AB|> { determinate($ax, $ay, $bx, $by) }
sub term:<|CD|> { determinate($cx, $cy, $dx, $dy) }
my $ΔxAB = $ax - $bx;
my $ΔyAB = $ay - $by;
my $ΔxCD = $cx - $dx;
my $ΔyCD = $cy - $dy;
my $x-numerator = determinate( |AB|, $ΔxAB, |CD|, $ΔxCD );
my $y-numerator = determinate( |AB|, $ΔyAB, |CD|, $ΔyCD );
my $denominator = determinate( $ΔxAB, $ΔyAB, $ΔxCD, $ΔyCD );
return 'Lines are parallel' if $denominator == 0;
($x-numerator/$denominator, $y-numerator/$denominator);
}
sub determinate ( Real $a, Real $b, Real $c, Real $d ) { $a * $d - $b * $c }
# TESTING
say 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7 );
say 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7.1 );
say 'Intersection point: ', intersection( 0,0, 1,1, 1,2, 4,5 );
|
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].
|
#Rust
|
Rust
|
use std::ops::{Add, Div, Mul, Sub};
#[derive(Copy, Clone, Debug, PartialEq)]
struct V3<T> {
x: T,
y: T,
z: T,
}
impl<T> V3<T> {
fn new(x: T, y: T, z: T) -> Self {
V3 { x, y, z }
}
}
fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U>
where
F: Fn(T, T) -> U,
{
V3 {
x: f(a.x, b.x),
y: f(a.y, b.y),
z: f(a.z, b.z),
}
}
impl<T> Add for V3<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self {
zip_with(<T>::add, self, other)
}
}
impl<T> Sub for V3<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self {
zip_with(<T>::sub, self, other)
}
}
impl<T> Mul for V3<T>
where
T: Mul<Output = T>,
{
type Output = Self;
fn mul(self, other: Self) -> Self {
zip_with(<T>::mul, self, other)
}
}
impl<T> V3<T>
where
T: Mul<Output = T> + Add<Output = T>,
{
fn dot(self, other: Self) -> T {
let V3 { x, y, z } = self * other;
x + y + z
}
}
impl<T> V3<T>
where
T: Mul<Output = T> + Copy,
{
fn scale(self, scalar: T) -> Self {
self * V3 {
x: scalar,
y: scalar,
z: scalar,
}
}
}
fn intersect<T>(
ray_vector: V3<T>,
ray_point: V3<T>,
plane_normal: V3<T>,
plane_point: V3<T>,
) -> V3<T>
where
T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy,
{
let diff = ray_point - plane_point;
let prod1 = diff.dot(plane_normal);
let prod2 = ray_vector.dot(plane_normal);
let prod3 = prod1 / prod2;
ray_point - ray_vector.scale(prod3)
}
fn main() {
let rv = V3::new(0.0, -1.0, -1.0);
let rp = V3::new(0.0, 0.0, 10.0);
let pn = V3::new(0.0, 0.0, 1.0);
let pp = V3::new(0.0, 0.0, 5.0);
println!("{:?}", intersect(rv, rp, pn, pp));
}
|
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].
|
#Scala
|
Scala
|
object LinePLaneIntersection extends App {
val (rv, rp, pn, pp) =
(Vector3D(0.0, -1.0, -1.0), Vector3D(0.0, 0.0, 10.0), Vector3D(0.0, 0.0, 1.0), Vector3D(0.0, 0.0, 5.0))
val ip = intersectPoint(rv, rp, pn, pp)
def intersectPoint(rayVector: Vector3D,
rayPoint: Vector3D,
planeNormal: Vector3D,
planePoint: Vector3D): Vector3D = {
val diff = rayPoint - planePoint
val prod1 = diff dot planeNormal
val prod2 = rayVector dot planeNormal
val prod3 = prod1 / prod2
rayPoint - rayVector * prod3
}
case class Vector3D(x: Double, y: Double, z: Double) {
def +(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)
def -(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)
def *(s: Double) = Vector3D(s * x, s * y, s * z)
def dot(v: Vector3D): Double = x * v.x + y * v.y + z * v.z
override def toString = s"($x, $y, $z)"
}
println(s"The ray intersects the plane at $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
|
#Axe
|
Axe
|
For(I,1,100)
!If I^3??I^5
Disp "FIZZBUZZ",i
Else!If I^3
Disp "FIZZ",i
Else!If I^5
Disp "BUZZ",i
Else
Disp I▶Dec,i
End
.Pause to allow the user to actually read the output
Pause 1000
End
|
http://rosettacode.org/wiki/Five_weekends
|
Five weekends
|
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
Task
Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).
Show the number of months with this property (there should be 201).
Show at 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
|
#Julia
|
Julia
|
isweekend(dt::Date) = Dates.dayofweek(dt) ∈ (Dates.Friday, Dates.Saturday, Dates.Sunday)
function hasfiveweekend(month::Integer, year::Integer)
dmin = Date(year, month, 1)
dmax = dmin + Dates.Day(Dates.daysinmonth(dmin) - 1)
return count(isweekend, dmin:dmax) ≥ 15
end
months = collect((y, m) for y in 1900:2100, m in 1:12 if hasfiveweekend(m, y))
println("Number of months with 5 full-weekends: $(length(months))")
println("First five such months:")
for (y, m) in months[1:5] println(" - $y-$m") end
println("Last five such months:")
for (y, m) in months[end-4:end] println(" - $y-$m") end
# extra credit
yrs = getindex.(months, 1)
nyrs = 2100 - 1899 - length(unique(yrs))
println("Number of year with not one 5-full-weekend month: $nyrs")
|
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
|
#k
|
k
|
cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar
is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays
m:__dj[cal_j]%100 / label the months
mi:&15=+/'is_we[=m] / group by month and sum the weekend days
`0:,"There are ",($#mi)," months with five weekends"
m5:(?m)[mi]
`0:$5#m5
`0:,"..."
`0:$-5#m5
y:1900+!201 / enumerate the years in the range
y5:?_ m5%100 / label the years of the months
yn5:y@&~y _lin y5 / find any years not in the 5 weekend month list
`0:,"There are ",($#yn5)," years without any five-weekend months"
`0:,1_,/",",/:$yn5
|
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
|
#newLISP
|
newLISP
|
> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> (define (cube x) (pow x 3))
(lambda (x) (pow x 3))
> (define (cube-root x) (pow x (div 1 3)))
(lambda (x) (pow x (div 1 3)))
> (define functions '(sin cos cube))
(sin cos cube)
> (define inverses '(asin acos cube-root))
(asin acos cube-root)
> (map (fn (f g) ((compose f g) 0.5)) functions inverses)
(0.5 0.5 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.
|
#Rust
|
Rust
|
extern crate rand;
extern crate ansi_term;
#[derive(Copy, Clone, PartialEq)]
enum Tile {
Empty,
Tree,
Burning,
Heating,
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let output = match *self {
Empty => Black.paint(" "),
Tree => Green.bold().paint("T"),
Burning => Red.bold().paint("B"),
Heating => Yellow.bold().paint("T"),
};
write!(f, "{}", output)
}
}
// This has been added to the nightly rust build as of March 24, 2016
// Remove when in stable branch!
trait Contains<T> {
fn contains(&self, T) -> bool;
}
impl<T: PartialOrd> Contains<T> for std::ops::Range<T> {
fn contains(&self, elt: T) -> bool {
self.start <= elt && elt < self.end
}
}
const NEW_TREE_PROB: f32 = 0.01;
const INITIAL_TREE_PROB: f32 = 0.5;
const FIRE_PROB: f32 = 0.001;
const FOREST_WIDTH: usize = 60;
const FOREST_HEIGHT: usize = 30;
const SLEEP_MILLIS: u64 = 25;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::io::BufWriter;
use std::io::Stdout;
use std::process::Command;
use std::time::Duration;
use rand::Rng;
use ansi_term::Colour::*;
use Tile::{Empty, Tree, Burning, Heating};
fn main() {
let sleep_duration = Duration::from_millis(SLEEP_MILLIS);
let mut forest = [[Tile::Empty; FOREST_WIDTH]; FOREST_HEIGHT];
prepopulate_forest(&mut forest);
print_forest(forest, 0);
std::thread::sleep(sleep_duration);
for generation in 1.. {
for row in forest.iter_mut() {
for tile in row.iter_mut() {
update_tile(tile);
}
}
for y in 0..FOREST_HEIGHT {
for x in 0..FOREST_WIDTH {
if forest[y][x] == Burning {
heat_neighbors(&mut forest, y, x);
}
}
}
print_forest(forest, generation);
std::thread::sleep(sleep_duration);
}
}
fn prepopulate_forest(forest: &mut [[Tile; FOREST_WIDTH]; FOREST_HEIGHT]) {
for row in forest.iter_mut() {
for tile in row.iter_mut() {
*tile = if prob_check(INITIAL_TREE_PROB) {
Tree
} else {
Empty
};
}
}
}
fn update_tile(tile: &mut Tile) {
*tile = match *tile {
Empty => {
if prob_check(NEW_TREE_PROB) == true {
Tree
} else {
Empty
}
}
Tree => {
if prob_check(FIRE_PROB) == true {
Burning
} else {
Tree
}
}
Burning => Empty,
Heating => Burning,
}
}
fn heat_neighbors(forest: &mut [[Tile; FOREST_WIDTH]; FOREST_HEIGHT], y: usize, x: usize) {
let neighbors = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)];
for &(xoff, yoff) in neighbors.iter() {
let nx: i32 = (x as i32) + xoff;
let ny: i32 = (y as i32) + yoff;
if (0..FOREST_WIDTH as i32).contains(nx) && (0..FOREST_HEIGHT as i32).contains(ny) &&
forest[ny as usize][nx as usize] == Tree {
forest[ny as usize][nx as usize] = Heating
}
}
}
fn prob_check(chance: f32) -> bool {
let roll = rand::thread_rng().gen::<f32>();
if chance - roll > 0.0 {
true
} else {
false
}
}
fn print_forest(forest: [[Tile; FOREST_WIDTH]; FOREST_HEIGHT], generation: u32) {
let mut writer = BufWriter::new(io::stdout());
clear_screen(&mut writer);
writeln!(writer, "Generation: {}", generation + 1).unwrap();
for row in forest.iter() {
for tree in row.iter() {
write!(writer, "{}", tree).unwrap();
}
writer.write(b"\n").unwrap();
}
}
fn clear_screen(writer: &mut BufWriter<Stdout>) {
let output = Command::new("clear").output().unwrap();
write!(writer, "{}", String::from_utf8_lossy(&output.stdout)).unwrap();
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Isabelle
|
Isabelle
|
theory Scratch
imports Main
begin
datatype 'a tree = Leaf 'a ("<_>")
| Node "'a tree list" ("⟦ _ ⟧")
text‹The datatype introduces special pretty printing:›
lemma "Leaf a = <a>" by simp
lemma "Node [] = ⟦ [] ⟧" by simp
definition "example ≡ ⟦[ ⟦[<1>]⟧, <2>, ⟦[ ⟦[<3>, <4>]⟧, <5>]⟧, ⟦[⟦[⟦[]⟧]⟧]⟧, ⟦[⟦[⟦[<6>]⟧]⟧]⟧, <7>, <8>, ⟦[]⟧ ]⟧"
lemma "example =
Node [
Node [Leaf 1],
Leaf 2,
Node [Node [Leaf 3, Leaf 4], Leaf 5],
Node [Node [ Node []]],
Node [Node [Node [Leaf 6]]],
Leaf 7,
Leaf 8,
Node []
]"
by(simp add: example_def)
fun flatten :: "'a tree ⇒ 'a list" where
"flatten (Leaf a) = [a]"
| "flatten (Node xs) = concat (map flatten xs)"
lemma "flatten example = [1, 2, 3, 4, 5, 6, 7, 8]"
by(simp add: example_def)
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.
|
#Picat
|
Picat
|
import util.
% Calculate the numbers first and then format them
floyd1(N) = S =>
M = [[J+SS : J in 1..I] : I in 1..N, SS=sum(1..I-1)],
S = [slice(SS,2) : Row in M, SS = [to_fstring(to_fstring("%%%dd",M[N,I].to_string().length+1),E) :
{E,I} in zip(Row,1..Row.length)].join('')].join("\n").
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#PicoLisp
|
PicoLisp
|
(de floyd (N)
(let LLC (/ (* N (dec N)) 2)
(for R N
(for C R
(prin
(align
(length (+ LLC C))
(+ C (/ (* R (dec R)) 2)) ) )
(if (= C R) (prinl) (space)) ) ) ) )
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
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)
|
#Groovy
|
Groovy
|
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def missingPerms
missingPerms = {List elts, List perms ->
perms.empty ? elts.permutations() : elts.collect { e ->
def ePerms = perms.findAll { e == it[0] }.collect { it[1..-1] }
ePerms.size() == fact(elts.size() - 1) ? [] \
: missingPerms(elts - e, ePerms).collect { [e] + it }
}.sum()
}
|
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
|
#JavaScript
|
JavaScript
|
function lastSundayOfEachMonths(year) {
var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var sundays = [];
var date, month;
if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
lastDay[2] = 29;
}
for (date = new Date(), month = 0; month < 12; month += 1) {
date.setFullYear(year, month, lastDay[month]);
date.setDate(date.getDate() - date.getDay());
sundays.push(date.toISOString().substring(0, 10));
}
return sundays;
}
console.log(lastSundayOfEachMonths(2013).join('\n'));
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#REXX
|
REXX
|
/* REXX */
Parse Value '(4.0,0.0)' With '(' xa ',' ya ')'
Parse Value '(6.0,10.0)' With '(' xb ',' yb ')'
Parse Value '(0.0,3.0)' With '(' xc ',' yc ')'
Parse Value '(10.0,7.0)' With '(' xd ',' yd ')'
Say 'The two lines are:'
Say 'yab='ya-xa*((yb-ya)/(xb-xa))'+x*'||((yb-ya)/(xb-xa))
Say 'ycd='yc-xc*((yd-yc)/(xd-xc))'+x*'||((yd-yc)/(xd-xc))
x=((yc-xc*((yd-yc)/(xd-xc)))-(ya-xa*((yb-ya)/(xb-xa))))/,
(((yb-ya)/(xb-xa))-((yd-yc)/(xd-xc)))
Say 'x='||x
y=ya-xa*((yb-ya)/(xb-xa))+x*((yb-ya)/(xb-xa))
Say 'yab='y
Say 'ycd='yc-xc*((yd-yc)/(xd-xc))+x*((yd-yc)/(xd-xc))
Say 'Intersection: ('||x','y')'
|
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].
|
#Sidef
|
Sidef
|
struct Line {
P0, # point
u⃗, # ray
}
struct Plane {
V0, # point
n⃗, # normal
}
func dot_prod(a, b) { a »*« b -> sum }
func line_plane_intersection(𝑳, 𝑷) {
var cos = dot_prod(𝑷.n⃗, 𝑳.u⃗) ->
|| return 'Vectors are orthogonal'
var 𝑊 = (𝑳.P0 »-« 𝑷.V0)
var S𝐼 = -(dot_prod(𝑷.n⃗, 𝑊) / cos)
𝑊 »+« (𝑳.u⃗ »*» S𝐼) »+« 𝑷.V0
}
say ('Intersection at point: ', line_plane_intersection(
Line(P0: [0,0,10], u⃗: [0,-1,-1]),
Plane(V0: [0,0, 5], n⃗: [0, 0, 1]),
))
|
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
|
#Babel
|
Babel
|
main:
{ { iter 1 + dup
15 %
{ "FizzBuzz" <<
zap }
{ dup
3 %
{ "Fizz" <<
zap }
{ dup
5 %
{ "Buzz" <<
zap}
{ %d << }
if }
if }
if
"\n" << }
100 times }
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
import java.util.*
fun main(args: Array<String>) {
val calendar = GregorianCalendar(1900, 0, 1)
val months31 = arrayOf(1, 3, 5, 7, 8, 10, 12)
val monthsWithFive = mutableListOf<String>()
val yearsWithNone = mutableListOf<Int>()
for (year in 1900..2100) {
var countInYear = 0 // counts months in a given year with 5 weekends
for (month in 1..12) {
if ((month in months31) && (Calendar.FRIDAY == calendar[Calendar.DAY_OF_WEEK])) {
countInYear++
monthsWithFive.add("%02d".format(month) + "-" + year)
}
calendar.add(Calendar.MONTH, 1)
}
if (countInYear == 0) yearsWithNone.add(year)
}
println("There are ${monthsWithFive.size} months with 5 weekends")
println("The first 5 are ${monthsWithFive.take(5)}")
println("The final 5 are ${monthsWithFive.takeLast(5)}")
println()
println("There are ${yearsWithNone.size} years with no months which have 5 weekends, namely:")
println(yearsWithNone)
}
|
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
|
#Nim
|
Nim
|
from math import nil # Require qualifier to access functions.
type MF64 = proc(x: float64): float64
proc cube(x: float64) : float64 =
math.pow(x, 3)
proc cuberoot(x: float64) : float64 =
math.pow(x, 1/3)
proc compose[A](f: proc(x: A): A, g: proc(x: A): A) : (proc(x: A): A) =
proc c(x: A): A =
f(g(x))
return c
proc sin(x: float64) : float64 =
math.sin(x)
proc acos(x: float64) : float64 =
math.arccos(x)
var fun = @[sin, math.cos, cube]
var inv = @[MF64 math.arcsin, acos, cuberoot]
for i in 0..2:
echo compose(inv[i], fun[i])(0.5)
|
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
|
#Objeck
|
Objeck
|
use Collection.Generic;
lambdas Func {
Double : (FloatHolder) ~ FloatHolder
}
class FirstClass {
function : Main(args : String[]) ~ Nil {
vector := Vector->New()<Func2Holder <FloatHolder, FloatHolder> >;
# store functions in collections
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> v * v)<FloatHolder, FloatHolder>);
# new function from preexisting function at run-time
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> Float->SquareRoot(v->Get()))<FloatHolder, FloatHolder>);
# process collection
each(i : vector) {
# return value of other functions and pass argument to other function
Show(vector->Get(i)<Func2Holder>->Get()<FloatHolder, FloatHolder>);
};
}
function : Show(func : (FloatHolder) ~ FloatHolder) ~ Nil {
func(13.5)->Get()->PrintLine();
}
}
|
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.
|
#Sather
|
Sather
|
class FORESTFIRE is
private attr fields:ARRAY{ARRAY{INT}};
private attr swapu:INT;
private attr rnd:RND;
private attr verbose:BOOL;
private attr generation:INT;
readonly attr width, height:INT;
const empty:INT := 0;
const tree:INT := 1;
const burning:INT := 2;
attr prob_tree, prob_p, prob_f :FLT;
create(w, h:INT, v:BOOL):SAME is
res:FORESTFIRE := new;
res.fields := #(2);
res.fields[0] := #(w*h);
res.fields[1] := #(w*h);
res.width := w; res.height := h;
res.swapu := 0;
res.prob_tree := 0.55;
res.prob_p := 0.001;
res.prob_f := 0.00001;
res.rnd := #RND;
res.verbose := v;
res.generation := 0;
res.initfield;
return res;
end;
-- to give variability
seed(i:INT) is
rnd.seed(i);
end;
create(w, h:INT):SAME is
res ::= create(w, h, false);
return res;
end;
initfield is
n ::= 0;
swapu := 0;
if verbose and generation > 0 then
#ERR + "Previous generation " + generation + "\n";
end;
generation := 0;
loop i ::= 0.upto!(width-1);
loop j ::= 0.upto!(height-1);
if rnd.uniform > prob_tree.fltd then
cset(i, j, empty);
else
n := n + 1;
cset(i, j, tree);
end;
end;
end;
if verbose then
#ERR + #FMT("Field size is %dx%d (%d)", width, height, size) + "\n";
#ERR + "There are " + n + " trees (" + (100.0*n.flt/size.flt) + "%)\n";
#ERR + "prob_tree = " + prob_tree + "\n";
#ERR + "prob_f = " + prob_f + "\n";
#ERR + "prob_p = " + prob_p + "\n";
#ERR + "ratio = " + prob_p/prob_f + "\n";
end;
end;
field:ARRAY{INT} is
return fields[swapu];
end;
ofield:ARRAY{INT} is
return fields[swapu.bxor(1)];
end;
size:INT is
return width*height;
end;
set(i, j, t:INT)
pre bcheck(i, j)
is
ofield[j*width + i] := t;
end;
cset(i, j, t:INT)
pre bcheck(i, j)
is
field[j*width + i] := t;
end;
private bcheck(i, j:INT):BOOL is
if i.is_between(0, width-1) and j.is_between(0, height-1) then
return true; -- is inside
else
return false; -- is outside
end;
end;
get(i, j:INT):INT is
if ~bcheck(i, j) then
return empty;
end;
return field[j*width + i];
end;
oget(i, j:INT):INT is
if ~bcheck(i, j) then
return empty;
end;
return ofield[j*width + i];
end;
burning_neighbor(i, j:INT):BOOL is
loop x ::= (-1).upto!(1);
loop y ::= (-1).upto!(1);
if x /= y then
if get(i+x, j+y) = burning then return true; end;
end;
end;
end;
return false;
end;
evolve is
bp ::= 0;
loop i ::= 0.upto!(width-1);
loop j ::= 0.upto!(height-1);
case get(i, j)
when burning then set(i, j, empty); bp := bp + 1;
when empty then
if rnd.uniform > prob_p.fltd then
set(i, j, empty);
else
set(i, j, tree);
end;
when tree then
if burning_neighbor(i, j) then
set(i, j, burning);
else
if rnd.uniform > prob_f.fltd then
set(i, j, tree);
else
set(i, j, burning);
end;
end;
else
#ERR + "corrupted field\n";
end;
end;
end;
generation := generation + 1;
if verbose then
if bp > 0 then
#ERR + #FMT("Burning at gen %d: %d\n", generation-1, bp);
end;
end;
swapu := swapu.bxor(1);
end;
str:STR is
s ::= "";
loop j ::= 0.upto!(height -1);
loop i ::= 0.upto!(width -1);
case get(i, j)
when empty then s := s + ".";
when tree then s := s + "Y";
when burning then s := s + "*";
end;
end;
s := s + "\n";
end;
s := s + "\n";
return s;
end;
end;
class MAIN is
main is
forestfire ::= #FORESTFIRE(74, 40);
-- #FORESTFIRE(74, 40, true) to have some extra info
-- (redirecting stderr to a file is a good idea!)
#OUT + forestfire.str;
-- evolve 1000 times
loop i ::= 1000.times!;
forestfire.evolve;
-- ANSI clear screen sequence
#OUT + 0x1b.char + "[H" + 0x1b.char + "[2J";
#OUT + forestfire.str;
end;
end;
end;
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#J
|
J
|
flatten =: [: ; <S:0
|
http://rosettacode.org/wiki/Floyd%27s_triangle
|
Floyd's triangle
|
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
the first row is 1 (unity)
successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like 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.
|
#PL.2FI
|
PL/I
|
(fofl, size):
floyd: procedure options (main); /* Floyd's Triangle. Wiki 12 July 2012 */
declare (i, m, n) fixed (10), (j, k, w, nr) fixed binary;
put list ('How many rows do you want?');
get list (nr); /* the number of rows */
n = nr*(nr+1)/2; /* the total number of values */
j,k = 1; m = n - nr + 1;
do i = 1 to n;
put edit (i) ( x(1), f(length(trim(m))) );
if k > 1 then do; k = k - 1; m = m + 1; end;
else do; k,j = j + 1; m = n - nr + 1; put skip; end;
end;
end floyd;
|
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)
|
#Haskell
|
Haskell
|
import Data.List ((\\), permutations, nub)
import Control.Monad (join)
missingPerm
:: Eq a
=> [[a]] -> [[a]]
missingPerm = (\\) =<< permutations . nub . join
deficientPermsList :: [String]
deficientPermsList =
[ "ABCD"
, "CABD"
, "ACDB"
, "DACB"
, "BCDA"
, "ACBD"
, "ADCB"
, "CDAB"
, "DABC"
, "BCAD"
, "CADB"
, "CDBA"
, "CBAD"
, "ABDC"
, "ADBC"
, "BDCA"
, "DCBA"
, "BACD"
, "BADC"
, "BDAC"
, "CBDA"
, "DBCA"
, "DCAB"
]
main :: IO ()
main = print $ missingPerm deficientPermsList
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.