task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#jq
|
jq
|
# In case your jq does not have "until" defined:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# Zeller's Congruence from [[Day_of_the_week#jq]]
# Use Zeller's Congruence to determine the day of the week, given
# year, month and day as integers in the conventional way.
# If iso == "iso" or "ISO", then emit an integer in 1 -- 7 where
# 1 represents Monday, 2 Tuesday, etc;
# otherwise emit 0 for Saturday, 1 for Sunday, etc.
#
def day_of_week(year; month; day; iso):
if month == 1 or month == 2 then
[year - 1, month + 12, day]
else
[year, month, day]
end
| .[2] + (13*(.[1] + 1)/5|floor)
+ (.[0]%100) + ((.[0]%100)/4|floor)
+ (.[0]/400|floor) - 2*(.[0]/100|floor)
| if iso == "iso" or iso == "ISO" then 1 + ((. + 5) % 7)
else . % 7
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
|
#Julia
|
Julia
|
isdefined(:Date) || using Dates
const wday = Dates.Sun
const lo = 1
const hi = 12
print("\nThis script will print the last ", Dates.dayname(wday))
println("s of each month of the year given.")
println("(Leave input empty to quit.)")
while true
print("\nYear> ")
y = chomp(readline())
0 < length(y) || break
y = try
parseint(y)
catch
println("Sorry, but that does not compute as a year.")
continue
end
println()
for m in Date(y, lo):Month(1):Date(y, hi)
println(" ", tolast(m, wday))
end
end
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Ring
|
Ring
|
# Project : Find the intersection of two lines
xa=4
ya=0
xb=6
yb=10
xc=0
yc=3
xd=10
yd=7
see "the two lines are:" + nl
see "yab=" + (ya-xa*((yb-ya)/(xb-xa))) + "+x*" + ((yb-ya)/(xb-xa)) + nl
see "ycd=" + (yc-xc*((yd-yc)/(xd-xc))) + "+x*" + ((yd-yc)/(xd-xc)) + nl
x=((yc-xc*((yd-yc)/(xd-xc)))-(ya-xa*((yb-ya)/(xb-xa))))/(((yb-ya)/(xb-xa))-((yd-yc)/(xd-xc)))
see "x=" + x + nl
y=ya-xa*((yb-ya)/(xb-xa))+x*((yb-ya)/(xb-xa))
see "yab=" + y + nl
see "ycd=" + (yc-xc*((yd-yc)/(xd-xc))+x*((yd-yc)/(xd-xc))) + nl
see "intersection: " + x + "," + y + nl
|
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) .
|
#Ruby
|
Ruby
|
Point = Struct.new(:x, :y)
class Line
attr_reader :a, :b
def initialize(point1, point2)
@a = (point1.y - point2.y).fdiv(point1.x - point2.x)
@b = point1.y - @a*point1.x
end
def intersect(other)
return nil if @a == other.a
x = (other.b - @b).fdiv(@a - other.a)
y = @a*x + @b
Point.new(x,y)
end
def to_s
"y = #{@a}x + #{@b}"
end
end
l1 = Line.new(Point.new(4, 0), Point.new(6, 10))
l2 = Line.new(Point.new(0, 3), Point.new(10, 7))
puts "Line #{l1} intersects line #{l2} at #{l1.intersect(l2)}."
|
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
|
Find the intersection of a line with a plane
|
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Module1
Class Vector3D
Private ReadOnly x As Double
Private ReadOnly y As Double
Private ReadOnly z As Double
Sub New(nx As Double, ny As Double, nz As Double)
x = nx
y = ny
z = nz
End Sub
Public Function Dot(rhs As Vector3D) As Double
Return x * rhs.x + y * rhs.y + z * rhs.z
End Function
Public Shared Operator +(ByVal a As Vector3D, ByVal b As Vector3D) As Vector3D
Return New Vector3D(a.x + b.x, a.y + b.y, a.z + b.z)
End Operator
Public Shared Operator -(ByVal a As Vector3D, ByVal b As Vector3D) As Vector3D
Return New Vector3D(a.x - b.x, a.y - b.y, a.z - b.z)
End Operator
Public Shared Operator *(ByVal a As Vector3D, ByVal b As Double) As Vector3D
Return New Vector3D(a.x * b, a.y * b, a.z * b)
End Operator
Public Overrides Function ToString() As String
Return String.Format("({0:F}, {1:F}, {2:F})", x, y, z)
End Function
End Class
Function IntersectPoint(rayVector As Vector3D, rayPoint As Vector3D, planeNormal As Vector3D, planePoint As Vector3D) As Vector3D
Dim diff = rayPoint - planePoint
Dim prod1 = diff.Dot(planeNormal)
Dim prod2 = rayVector.Dot(planeNormal)
Dim prod3 = prod1 / prod2
Return rayPoint - rayVector * prod3
End Function
Sub Main()
Dim rv = New Vector3D(0.0, -1.0, -1.0)
Dim rp = New Vector3D(0.0, 0.0, 10.0)
Dim pn = New Vector3D(0.0, 0.0, 1.0)
Dim pp = New Vector3D(0.0, 0.0, 5.0)
Dim ip = IntersectPoint(rv, rp, pn, pp)
Console.WriteLine("The ray intersects the plane at {0}", ip)
End Sub
End Module
|
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
|
#BaCon
|
BaCon
|
for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done
|
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
|
#Lasso
|
Lasso
|
local(
months = array(1, 3, 5, 7, 8, 10, 12),
fivemonths = array,
emptyears = array,
checkdate = date,
countyear
)
#checkdate -> day = 1
loop(-from = 1900, -to = 2100) => {
#countyear = false
#checkdate -> year = loop_count
with month in #months
do {
#checkdate -> month = #month
if(#checkdate -> dayofweek == 6) => {
#countyear = true
#fivemonths -> insert(#checkdate -> format(`YYYY MMM`))
}
}
if(not #countyear) => {
#emptyears -> insert(loop_count)
}
}
local(
monthcount = #fivemonths -> size,
output = 'Total number of months ' + #monthcount + '<br /> Starting five months '
)
loop(5) => {
#output -> append(#fivemonths -> get(loop_count) + ', ')
}
#output -> append('<br /> Ending five months ')
loop(-from = #monthcount - 5, -to = #monthcount) => {
#output -> append(#fivemonths -> get(loop_count) + ', ')
}
#output -> append('<br /> Years with no five weekend months ' + #emptyears -> size + '<br />')
with year in #emptyears do {
#output -> append(#year + ', ')
}
#output
|
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
|
#Lua
|
Lua
|
local months={"JAN","MAR","MAY","JUL","AUG","OCT","DEC"}
local daysPerMonth={31+28,31+30,31+30,31,31+30,31+30,0}
function find5weMonths(year)
local list={}
local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
for i,v in ipairs(daysPerMonth) do
if startday==4 then list[#list+1]=months[i] end
if i==1 and year%4==0 and year%100~=0 or year%400==0 then
startday=startday+1
end
startday=(startday+v)%7
end
return list
end
local cnt_months=0
local cnt_no5we=0
for y=1900,2100 do
local list=find5weMonths(y)
cnt_months=cnt_months+#list
if #list==0 then
cnt_no5we=cnt_no5we+1
end
print(y.." "..#list..": "..table.concat(list,", "))
end
print("Months with 5 weekends: ",cnt_months)
print("Years without 5 weekends in the same month:",cnt_no5we)
|
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
|
#OCaml
|
OCaml
|
# let cube x = x ** 3. ;;
val cube : float -> float = <fun>
# let croot x = x ** (1. /. 3.) ;;
val croot : float -> float = <fun>
# let compose f g = fun x -> f (g x) ;; (* we could have written "let compose f g x = f (g x)" but we show this for clarity *)
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
# let funclist = [sin; cos; cube] ;;
val funclist : (float -> float) list = [<fun>; <fun>; <fun>]
# let funclisti = [asin; acos; croot] ;;
val funclisti : (float -> float) list = [<fun>; <fun>; <fun>]
# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
- : float list = [0.5; 0.499999999999999889; 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.
|
#Scala
|
Scala
|
import scala.util.Random
class Forest(matrix:Array[Array[Char]]){
import Forest._
val f=0.01; // auto combustion probability
val p=0.1; // tree creation probability
val rows=matrix.size
val cols=matrix(0).size
def evolve():Forest=new Forest(Array.tabulate(rows, cols){(y,x)=>
matrix(y)(x) match {
case EMPTY => if (Random.nextDouble<p) TREE else EMPTY
case BURNING => EMPTY
case TREE => if (neighbours(x, y).exists(_==BURNING)) BURNING
else if (Random.nextDouble<f) BURNING else TREE
}
})
def neighbours(x:Int, y:Int)=matrix slice(y-1, y+2) map(_.slice(x-1, x+2)) flatten
override def toString()=matrix map (_.mkString("")) mkString "\n"
}
object Forest{
val TREE='T'
val BURNING='#'
val EMPTY='.'
def apply(x:Int=30, y:Int=15)=new Forest(Array.tabulate(y, x)((y,x)=> if (Random.nextDouble<0.5) TREE else EMPTY))
}
|
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
|
#Java
|
Java
|
import java.util.LinkedList;
import java.util.List;
public final class FlattenUtil {
public static List<Object> flatten(List<?> list) {
List<Object> retVal = new LinkedList<Object>();
flatten(list, retVal);
return retVal;
}
public static void flatten(List<?> fromTreeList, List<Object> toFlatList) {
for (Object item : fromTreeList) {
if (item instanceof List<?>) {
flatten((List<?>) item, toFlatList);
} else {
toFlatList.add(item);
}
}
}
}
|
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.
|
#Prolog
|
Prolog
|
floyd(N) :-
forall(between(1, N, I),
( forall(between(1,I, J),
( Last is N * (N-1)/2+J,
V is I * (I-1) /2 + J,
get_column(Last, C),
sformat(AR, '~~t~~w~~~w| ', [C]),
sformat(AF, AR, [V]),
writef(AF))),
nl)).
get_column(Last, C) :-
name(Last, N1), length(N1,C).
|
http://rosettacode.org/wiki/Find_the_missing_permutation
|
Find the missing permutation
|
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
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)
|
#Icon_and_Unicon
|
Icon and Unicon
|
link strings # for permutes
procedure main()
givens := set![ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB",
"CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
every insert(full := set(), permutes("ABCD")) # generate all permutations
givens := full--givens # and difference
write("The difference is : ")
every write(!givens, " ")
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
|
#K
|
K
|
/ List the dates of last Sundays of each month of
/ a given year
/ lastsundt.k
isleap: {(+/~x!' 4 100 400)!2}
wd: {(_jd x)!7}
dom: (31;28;31;30;31;30;31;31;30;31;30;31)
init: {:[isleap x;dom[1]::29;dom[1]::28]}
wdme: {[m;y]; init y; dt:(10000*y)+(100*m)+dom[m-1];jd::(_jd dt);mewd::(wd dt)}
lsd: {[m;y]; wdme[m;y];:[mewd>5;jd::jd+(6-mewd);jd::jd-(1+mewd)];dt:_dj(jd);yy:$(yr:dt%10000);dd:$(d:dt!100);mm:$(mo:((dt-yr*10000)%100));arr::arr,$(yy,"-",(2$mm),"-",(2$dd))}
lsd1: {[y];arr::(); m:1; do[12;lsd[m;y];m+:1]}
main: {[y]; lsd1[y];`0: ,"Dates of last Sundays of ",($y); 12 10#arr}
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
import java.util.*
fun main(args: Array<String>) {
print("Enter a year : ")
val year = readLine()!!.toInt()
println("The last Sundays of each month in $year are as follows:")
val calendar = GregorianCalendar(year, 0, 31)
for (month in 1..12) {
val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
val lastSunday = daysInMonth - (calendar[Calendar.DAY_OF_WEEK] - Calendar.SUNDAY)
println("$year-" + "%02d-".format(month) + "%02d".format(lastSunday))
if (month < 12) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
calendar.add(Calendar.MONTH, 1)
calendar.add(Calendar.DAY_OF_MONTH, -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) .
|
#Rust
|
Rust
|
#[derive(Copy, Clone, Debug)]
struct Point {
x: f64,
y: f64,
}
impl Point {
pub fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
}
#[derive(Copy, Clone, Debug)]
struct Line(Point, Point);
impl Line {
pub fn intersect(self, other: Self) -> Option<Point> {
let a1 = self.1.y - self.0.y;
let b1 = self.0.x - self.1.x;
let c1 = a1 * self.0.x + b1 * self.0.y;
let a2 = other.1.y - other.0.y;
let b2 = other.0.x - other.1.x;
let c2 = a2 * other.0.x + b2 * other.0.y;
let delta = a1 * b2 - a2 * b1;
if delta == 0.0 {
return None;
}
Some(Point {
x: (b2 * c1 - b1 * c2) / delta,
y: (a1 * c2 - a2 * c1) / delta,
})
}
}
fn main() {
let l1 = Line(Point::new(4.0, 0.0), Point::new(6.0, 10.0));
let l2 = Line(Point::new(0.0, 3.0), Point::new(10.0, 7.0));
println!("{:?}", l1.intersect(l2));
let l1 = Line(Point::new(0.0, 0.0), Point::new(1.0, 1.0));
let l2 = Line(Point::new(1.0, 2.0), Point::new(4.0, 5.0));
println!("{:?}", l1.intersect(l2));
}
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Scala
|
Scala
|
object Intersection extends App {
val (l1, l2) = (LineF(PointF(4, 0), PointF(6, 10)), LineF(PointF(0, 3), PointF(10, 7)))
def findIntersection(l1: LineF, l2: LineF): PointF = {
val a1 = l1.e.y - l1.s.y
val b1 = l1.s.x - l1.e.x
val c1 = a1 * l1.s.x + b1 * l1.s.y
val a2 = l2.e.y - l2.s.y
val b2 = l2.s.x - l2.e.x
val c2 = a2 * l2.s.x + b2 * l2.s.y
val delta = a1 * b2 - a2 * b1
// If lines are parallel, intersection point will contain infinite values
PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
}
def l01 = LineF(PointF(0f, 0f), PointF(1f, 1f))
def l02 = LineF(PointF(1f, 2f), PointF(4f, 5f))
case class PointF(x: Float, y: Float) {
override def toString = s"{$x, $y}"
}
case class LineF(s: PointF, e: PointF)
println(findIntersection(l1, l2))
println(findIntersection(l01, l02))
}
|
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].
|
#Wren
|
Wren
|
class Vector3D {
construct new(x, y, z) {
_x = x
_y = y
_z = z
}
x { _x }
y { _y }
z { _z }
+(v) { Vector3D.new(_x + v.x, _y + v.y, _z + v.z) }
-(v) { Vector3D.new(_x - v.x, _y - v.y, _z - v.z) }
*(s) { Vector3D.new(s * _x, s * _y, s * _z) }
dot(v) { _x * v.x + _y * v.y + _z * v.z }
toString { "(%(_x), %(_y), %(_z))" }
}
var intersectPoint = Fn.new { |rayVector, rayPoint, planeNormal, planePoint|
var diff = rayPoint - planePoint
var prod1 = diff.dot(planeNormal)
var prod2 = rayVector.dot(planeNormal)
var prod3 = prod1 / prod2
return rayPoint - rayVector*prod3
}
var rv = Vector3D.new(0, -1, -1)
var rp = Vector3D.new(0, 0, 10)
var pn = Vector3D.new(0, 0, 1)
var pp = Vector3D.new(0, 0, 5)
var ip = intersectPoint.call(rv, rp, pn, pp)
System.print("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
|
#bash
|
bash
|
for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done
|
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
|
#Maple
|
Maple
|
five_weekends:= proc()
local i, month, count;
#Only months with 31 days can possibly satisfy the condition
local long_months := [1,3,5,7,8,10,12];
local months := ["January","February","March","April","May","June","July","August","September","October","November","December"];
count := 0;
for i from 1900 to 2100 by 1 do
for month in long_months do
if Calendar:-DayOfWeek(Date(i, month, 1)) = 6 then
printf("%d-%s\n", i, months[month]);
count++;
end if;
end do;
end do;
printf("%d months have five full weekends.\n", count);
end proc;
five_weekends();
|
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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
years = {1900, 2100}; months = {1 ,3 ,5 ,7 ,8 ,10 ,12};
result = Select[Tuples[{Range@@years, months}], (DateString[# ~ Join ~ 1, "DayNameShort"] == "Fri")&];
Print[result // Length," months with 5 weekends" ];
Print["First months: ", DateString[#,{"MonthName"," ","Year"}]& /@ result[[1 ;; 5]]];
Print["Last months: " , DateString[#,{"MonthName"," ","Year"}]& /@ result[[-5 ;; All]]];
Print[# // Length, " years without 5 weekend months:\n", #] &@
Complement[Range @@ years, Part[Transpose@result, 1]];
|
http://rosettacode.org/wiki/First-class_functions
|
First-class functions
|
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:
Create new functions from preexisting functions at run-time
Store functions in collections
Use functions as arguments to other functions
Use functions as 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
|
#Octave
|
Octave
|
function r = cube(x)
r = x.^3;
endfunction
function r = croot(x)
r = x.^(1/3);
endfunction
compose = @(f,g) @(x) f(g(x));
f1 = {@sin, @cos, @cube};
f2 = {@asin, @acos, @croot};
for i = 1:3
disp(compose(f1{i}, f2{i})(.5))
endfor
|
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.
|
#Sidef
|
Sidef
|
define w = `tput cols`.to_i-1
define h = `tput lines`.to_i-1
define r = "\033[H"
define red = "\033[31m"
define green = "\033[32m"
define yellow = "\033[33m"
define chars = [' ', green+'*', yellow+'&', red+'&']
define tree_prob = 0.05
define burn_prob = 0.0002
enum |Empty, Tree, Heating, Burning|
define dirs = [
%n(-1 -1), %n(-1 0), %n(-1 1), %n(0 -1),
%n(0 1), %n(1 -1), %n(1 0), %n(1 1),
]
var forest = h.of { w.of { 1.rand < tree_prob ? Tree : Empty } }
var range_h = h.range
var range_w = w.range
func iterate {
var new = h.of{ w.of(0) }
for i in range_h {
for j in range_w {
given (new[i][j] = forest[i][j]) {
when (Tree) {
1.rand < burn_prob && (new[i][j] = Heating; next)
dirs.each { |pair|
var y = pair[0]+i
range_h.contains(y) || next
var x = pair[1]+j
range_w.contains(x) || next
forest[y][x] == Heating && (new[i][j] = Heating; break)
}
}
when (Heating) { new[i][j] = Burning }
when (Burning) { new[i][j] = Empty }
case (1.rand < tree_prob) { new[i][j] = Tree }
}
}
}
forest = new
}
STDOUT.autoflush(true)
func init_forest {
print r
forest.each { |row|
print chars[row]
print "\033[E\033[1G"
}
iterate()
}
loop { init_forest() }
|
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
|
#JavaScript
|
JavaScript
|
function flatten(list) {
return list.reduce(function (acc, val) {
return acc.concat(val.constructor === Array ? flatten(val) : val);
}, []);
}
|
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.
|
#PureBasic
|
PureBasic
|
Procedure.i sumTo(n)
Protected r,i
For i=1 To n
r+i
Next
ProcedureReturn r.i
EndProcedure
; [1]
; array rsA(n)... string-lengths of the numbers
; in the bottom row
; [2]
; sumTo(i-1)+1 to sumTo(i)
; 11 12 13 14 15
; here k is the column-index for array rsA(k)
Procedure.s FloydsTriangle(n)
Protected r.s,s.s,t.s,i,j,k
; [1]
Dim rsA(n)
i=0
For j=sumTo(n-1)+1 To sumTo(n)
i+1
rsA(i)=Len(Str(j))
Next
; [2]
For i=1 To n
t.s="":k=0
For j=sumTo(i-1)+1 To sumTo(i)
k+1:t.s+RSet(Str(j),rsA(k)," ")+" "
Next
r.s+RTrim(t.s)+Chr(13)+Chr(10)
Next
r.s=Left(r.s,Len(r.s)-2)
ProcedureReturn r.s
EndProcedure
If OpenConsole()
n=5
r.s=FloydsTriangle(n)
PrintN(r.s)
n=14
r.s=FloydsTriangle(n)
PrintN(r.s)
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
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)
|
#J
|
J
|
permutations=: A.~ i.@!@#
missingPerms=: -.~ permutations @ {.
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
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
|
#Lasso
|
Lasso
|
local(
year = integer(web_request -> param('year') || 2013),
date = date(#year + '-1-1'),
lastsu = array,
lastday
)
with month in generateseries(1,12) do {
#date -> day = 1
#date -> month = #month
#lastday = #date -> month(-days)
#date -> day = #lastday
loop(7) => {
if(#date -> dayofweek == 1) => {
#lastsu -> insert(#date -> format(`dd MMMM`))
loop_abort
}
#date -> day--
}
}
#lastsu -> join('<br />')
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
yyyy=2013: if yyyy<1901 or yyyy>2099 then end
nda$="Lsu"
print "The last Sundays of "; yyyy
for mm=1 to 12
x=NthDayOfMonth(yyyy, mm, nda$)
select case mm
case 1: print " January "; x
case 2: print " February "; x
case 3: print " March "; x
case 4: print " April "; x
case 5: print " May "; x
case 6: print " June "; x
case 7: print " July "; x
case 8: print " August "; x
case 9: print " September "; x
case 10: print " October "; x
case 11: print " November "; x
case 12: print " December "; x
end select
next mm
end
function NthDayOfMonth(yyyy, mm, nda$)
' nda$ is a two-part code. The first character, n, denotes
' first, second, third, fourth, and last by 1, 2, 3, 4, or L.
' The last two characters, da, denote the day of the week by
' mo, tu, we, th, fr, sa, or su. For example:
' the nda$ for the second Monday of a month is "2mo";
' the nda$ for the last Thursday of a month is "Lth".
if yyyy<1900 or yyyy>2099 or mm<1 or mm>12 then
NthDayOfMonth=0: exit function
end if
nda$=lower$(trim$(nda$))
if len(nda$)<>3 then NthDayOfMonth=0: exit function
n$=left$(nda$,1): nC$="1234l"
da$=right$(nda$,2): daC$="tuwethfrsasumotuwethfrsasumo"
if not(instr(nC$,n$)) or not(instr(daC$,da$)) then
NthDayOfMonth=0: exit function
end if
NthDayOfMonth=1
mm$=str$(mm): if mm<10 then mm$="0"+mm$
db$=DayOfDate$(str$(yyyy)+mm$+"01")
if da$<>db$ then
x=instr(daC$,db$): y=instr(daC$,da$,x): NthDayOfMonth=1+(y-x)/2
end if
dim MD(12)
MD(1)=31: MD(2)=28: MD(3)=31: MD(4)=30: MD(5)=31: MD(6)=30
MD(7)=31: MD(8)=31: MD(9)=30: MD(10)=31: MD(11)=30: MD(12)=31
if yyyy mod 4 = 0 then MD(2)=29
if n$<>"1" then
if n$<>"l" then
NthDayOfMonth=NthDayOfMonth+((val(n$)-1)*7)
else
if NthDayOfMonth+27<MD(mm) then
NthDayOfMonth=NthDayOfMonth+28
else
NthDayOfMonth=NthDayOfMonth+21
end if
end if
end if
end function
function DayOfDate$(ObjectDate$) 'yyyymmdd format
if ObjectDate$="" then 'today
DaysSince1900 = date$("days")
else
DaysSince1900 = date$(mid$(ObjectDate$,5,2)+"/"+right$(ObjectDate$,2)_
+"/"+left$(ObjectDate$,4))
end if
DayOfWeek = DaysSince1900 mod 7
select case DayOfWeek
case 0: DayOfDate$="tu"
case 1: DayOfDate$="we"
case 2: DayOfDate$="th"
case 3: DayOfDate$="fr"
case 4: DayOfDate$="sa"
case 5: DayOfDate$="su"
case 6: DayOfDate$="mo"
end select
end function
|
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) .
|
#Sidef
|
Sidef
|
func det(a, b, c, d) { a*d - b*c }
func intersection(ax, ay, bx, by,
cx, cy, dx, dy) {
var detAB = det(ax,ay, bx,by)
var detCD = det(cx,cy, dx,dy)
var ΔxAB = (ax - bx)
var ΔyAB = (ay - by)
var ΔxCD = (cx - dx)
var ΔyCD = (cy - dy)
var x_numerator = det(detAB, ΔxAB, detCD, ΔxCD)
var y_numerator = det(detAB, ΔyAB, detCD, ΔyCD)
var denominator = det( ΔxAB, ΔyAB, ΔxCD, ΔyCD)
denominator == 0 && return 'lines are parallel'
[x_numerator / denominator, y_numerator / denominator]
}
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].
|
#zkl
|
zkl
|
class Line { fcn init(pxyz, ray_xyz) { var pt=pxyz, ray=ray_xyz; } }
class Plane{ fcn init(pxyz, normal_xyz){ var pt=pxyz, normal=normal_xyz; } }
fcn dotP(a,b){ a.zipWith('*,b).sum(0.0); } # dot product --> x
fcn linePlaneIntersection(line,plane){
cos:=dotP(plane.normal,line.ray); # cosine between normal & ray
_assert_((not cos.closeTo(0,1e-6)),
"Vectors are orthogonol; no intersection or line within plane");
w:=line.pt.zipWith('-,plane.pt); # difference between P0 and V0
si:=-dotP(plane.normal,w)/cos; # line segment where it intersets the plane
# point where line intersects the plane:
//w.zipWith('+,line.ray.apply('*,si)).zipWith('+,plane.pt); // or
w.zipWith('wrap(w,r,pt){ w + r*si + pt },line.ray,plane.pt);
}
|
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
|
#BASIC
|
BASIC
|
@echo off
for /L %%i in (1,1,100) do call :tester %%i
goto :eof
:tester
set /a test = %1 %% 15
if %test% NEQ 0 goto :NotFizzBuzz
echo FizzBuzz
goto :eof
:NotFizzBuzz
set /a test = %1 %% 5
if %test% NEQ 0 goto :NotBuzz
echo Buzz
goto :eof
:NotBuzz
set /a test = %1 %% 3
if %test% NEQ 0 goto :NotFizz
echo Fizz
goto :eof
:NotFizz
echo %1
|
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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
longmonth = [1 3 5 7 8 10 12];
i = 1;
for y = 1900:2100
for m = 1:numel(longmonth)
[num,name] = weekday(datenum(y,longmonth(m),1));
if num == 6
x(i,:) = datestr(datenum(y,longmonth(m),1),'mmm yyyy'); %#ok<SAGROW>
i = i+1;
end
end
end
fprintf('There are %i months with 5 weekends between 1900 and 2100.\n',length(x))
fprintf('\n The first 5 months are:\n')
for j = 1:5
fprintf('\t %s \n',x(j,:))
end
fprintf('\n The final 5 months are:\n')
for j = length(x)-4:length(x)
fprintf('\t %s \n',x(j,:))
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
|
#Oforth
|
Oforth
|
: compose(f, g) #[ g perform f perform ] ;
[ #cos, #sin, #[ 3 pow ] ] [ #acos, #asin, #[ 3 inv powf ] ] zipWith(#compose)
map(#[ 0.5 swap perform ]) conform(#[ 0.5 == ]) println
|
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
|
#Ol
|
Ol
|
; creation of new function from preexisting functions at run-time
(define (compose f g) (lambda (x) (f (g x))))
; storing functions in collection
(define (quad x) (* x x x x))
(define (quad-root x) (sqrt (sqrt x)))
(define collection (tuple quad quad-root))
; use functions as arguments to other functions
; and use functions as return values of other functions
(define identity (compose (ref collection 2) (ref collection 1)))
(print (identity 11211776))
|
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.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
# Build a grid
proc makeGrid {w h {treeProbability 0.5}} {
global grid gridW gridH
set gridW $w
set gridH $h
set grid [lrepeat $h [lrepeat $w " "]]
for {set x 0} {$x < $w} {incr x} {
for {set y 0} {$y < $h} {incr y} {
if {rand() < $treeProbability} {
lset grid $y $x "#"
}
}
}
}
# Evolve the grid (builds a copy, then overwrites)
proc evolveGrid {{fireProbability 0.01} {plantProbability 0.05}} {
global grid gridW gridH
set newGrid {}
for {set y 0} {$y < $gridH} {incr y} {
set row {}
for {set x 0} {$x < $gridW} {incr x} {
switch -exact -- [set s [lindex $grid $y $x]] {
" " {
if {rand() < $plantProbability} {
set s "#"
}
}
"#" {
if {[burningNeighbour? $x $y] || rand() < $fireProbability} {
set s "o"
}
}
"o" {
set s " "
}
}
lappend row $s
}
lappend newGrid $row
}
set grid $newGrid
}
# We supply the neighbourhood model as an optional parameter (not used...)
proc burningNeighbour? {
x y
{neighbourhoodModel {-1 -1 -1 0 -1 1 0 -1 0 1 1 -1 1 0 1 1}}
} {
global grid gridW gridH
foreach {dx dy} $neighbourhoodModel {
set i [expr {$x + $dx}]
if {$i < 0 || $i >= $gridW} continue
set j [expr {$y + $dy}]
if {$j < 0 || $j >= $gridH} continue
if {[lindex $grid $j $i] eq "o"} {
return 1
}
}
return 0
}
proc printGrid {} {
global grid
foreach row $grid {
puts [join $row ""]
}
}
# Simple main loop; press Return for the next step or send an EOF to stop
makeGrid 70 8
while 1 {
evolveGrid
printGrid
if {[gets stdin line] < 0} break
}
|
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
|
#Joy
|
Joy
|
"seqlib" libload.
[[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] treeflatten.
(* output: [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.
|
#Python
|
Python
|
>>> def floyd(rowcount=5):
rows = [[1]]
while len(rows) < rowcount:
n = rows[-1][-1] + 1
rows.append(list(range(n, n + len(rows[-1]) + 1)))
return rows
>>> floyd()
[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]]
>>> def pfloyd(rows=[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]):
colspace = [len(str(n)) for n in rows[-1]]
for row in rows:
print( ' '.join('%*i' % space_n for space_n in zip(colspace, row)))
>>> pfloyd()
1
2 3
4 5 6
7 8 9 10
>>> pfloyd(floyd(5))
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
>>> pfloyd(floyd(14))
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
>>>
|
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)
|
#Java
|
Java
|
import java.util.ArrayList;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
public class FindMissingPermutation {
public static void main(String[] args) {
Joiner joiner = Joiner.on("").skipNulls();
ImmutableSet<String> s = ImmutableSet.of("ABCD", "CABD", "ACDB",
"DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB",
"CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC",
"BDAC", "CBDA", "DBCA", "DCAB");
for (ArrayList<Character> cs : Utils.Permutations(Lists.newArrayList(
'A', 'B', 'C', 'D')))
if (!s.contains(joiner.join(cs)))
System.out.println(joiner.join(cs));
}
}
|
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
|
#LiveCode
|
LiveCode
|
function lastDay yyyy, dayofweek
-- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week.
convert the long date to dateitems
put 1 into item 2 of it
put 1 into item 3 of it
put yyyy into item 1 of it
put it into startDate
convert startDate to dateItems
repeat with m = 1 to 12
put m into item 2 of startDate
repeat with d = 20 to 31
put d into item 3 of startDate
convert startDate to dateItems
-- 1 is Sunday through to 7 Saturday
if item 7 of startDate is dayofweek and item 1 of startDate is yyyy and item 2 of startDate is m then
put item 3 of startDate into mydays[item 2 of startDate]
end if
end repeat
end repeat
combine mydays using cr and space
sort mydays ascending numeric
return mydays
end lastDay
|
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
|
#Lua
|
Lua
|
function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if isLeapYear(year) then monthLength[2] = 29 end
for month = 1, 12 do
day = monthLength[month]
while dayOfWeek(year, month, day) ~= wday do day = day - 1 end
print(year .. "-" .. month .. "-" .. day)
end
end
lastWeekdays("Sunday", tonumber(arg[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) .
|
#Swift
|
Swift
|
struct Point {
var x: Double
var y: Double
}
struct Line {
var p1: Point
var p2: Point
var slope: Double {
guard p1.x - p2.x != 0.0 else { return .nan }
return (p1.y-p2.y) / (p1.x-p2.x)
}
func intersection(of other: Line) -> Point? {
let ourSlope = slope
let theirSlope = other.slope
guard ourSlope != theirSlope else { return nil }
if ourSlope.isNaN && !theirSlope.isNaN {
return Point(x: p1.x, y: (p1.x - other.p1.x) * theirSlope + other.p1.y)
} else if theirSlope.isNaN && !ourSlope.isNaN {
return Point(x: other.p1.x, y: (other.p1.x - p1.x) * ourSlope + p1.y)
} else {
let x = (ourSlope*p1.x - theirSlope*other.p1.x + other.p1.y - p1.y) / (ourSlope - theirSlope)
return Point(x: x, y: theirSlope*(x - other.p1.x) + other.p1.y)
}
}
}
let l1 = Line(p1: Point(x: 4.0, y: 0.0), p2: Point(x: 6.0, y: 10.0))
let l2 = Line(p1: Point(x: 0.0, y: 3.0), p2: Point(x: 10.0, y: 7.0))
print("Intersection at : \(l1.intersection(of: l2)!)")
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#TI-83_BASIC
|
TI-83 BASIC
|
[[4,0][6,10][0,3][10,7]]→[A]
([A](2,2)-[A](1,2))/([A](2,1)-[A](1,1))→B
[A](1,2)-[A](1,1)*B→A
([A](4,2)-[A](3,2))/([A](4,1)-[A](3,1))→D
[A](3,2)-[A](3,1)*D→C
(C-A)/(B-D)→X
A+X*B→Y
C+X*D→Z
Disp {X,Y}
|
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
|
#BASIC256
|
BASIC256
|
@echo off
for /L %%i in (1,1,100) do call :tester %%i
goto :eof
:tester
set /a test = %1 %% 15
if %test% NEQ 0 goto :NotFizzBuzz
echo FizzBuzz
goto :eof
:NotFizzBuzz
set /a test = %1 %% 5
if %test% NEQ 0 goto :NotBuzz
echo Buzz
goto :eof
:NotBuzz
set /a test = %1 %% 3
if %test% NEQ 0 goto :NotFizz
echo Fizz
goto :eof
:NotFizz
echo %1
|
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
|
#Maxima
|
Maxima
|
left(a, n) := makelist(a[i], i, 1, n)$
right(a, n) := block([m: length(a)], makelist(a[i], i, m - n + 1, m))$
a: [ ]$
for year from 1900 thru 2100 do
for month in [1, 3, 5, 7, 8, 10, 12] do
if weekday(year, month, 1) = 'friday then
a: endcons([year, month], a)$
length(a);
201
left(a, 5);
[[1901,3],[1902,8],[1903,5],[1904,1],[1904,7]]
right(a, 5);
[[2097,3],[2098,8],[2099,5],[2100,1],[2100,10]]
|
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
|
#Oz
|
Oz
|
declare
fun {Compose F G}
fun {$ X}
{F {G X}}
end
end
fun {Cube X} {Number.pow X 3.0} end
fun {CubeRoot X} {Number.pow X 1.0/3.0} end
in
for
F in [Float.sin Float.cos Cube]
I in [Float.asin Float.acos CubeRoot]
do
{Show {{Compose I F} 0.5}}
end
|
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.
|
#uBasic.2F4tH
|
uBasic/4tH
|
B = 1 ' A burning tree
E = 16 ' An empty space
T = 256 ' A living tree
Input "%Chance a tree will burn: ";F ' Enter chance of combustion
Input "%Chance a tree will grow: ";P ' Enter chance of a new tree
Proc _CreateForest ' Now create a new forest
Do
Proc _PrintForest ' Print the current forest
Input "Press '1' to continue, '0' to quit: ";A
Proc _BurnForest ' See what happens
Proc _UpdateForest ' Update from buffer
While A ' Until the user has enough
Loop ' and answers with zero
End
_CreateForest ' Create an entire new forest
Local(1)
For a@ = 0 to 120 ' For each main cell determine
If RND(100) < P Then ' if a tree will grow here
@(a@) = T ' Ok, we got a tree
Else ' Otherwise it remains empty
@(a@) = E
EndIf
Next
Return
_BurnForest ' Now the forest starts to burn
Local(2)
For a@ = 0 To 10 ' Loop vertical
For b@ = 0 To 10 ' Loop horizontal
If @((a@ * 11) + b@) = B Then @((a@ * 11) + b@ + 121) = E
' A tree has been burned flat
If @((a@ * 11) + b@) = E Then ' For each open space determine
If RND(100) < P Then ' if a tree will grow here
@((a@ * 11) + b@ + 121) = T
Else ' Otherwise it remains an empty space
@((a@ * 11) + b@ + 121) = E
EndIf
EndIf
If @((a@ * 11) + b@) = T Then ' A tree grows here
If RND(100) < F Then ' See if it will spontaneously combust
@((a@ * 11) + b@ + 121) = B
Else ' No, then see if it got any burning
@((a@ * 11) + b@ + 121) = FUNC(_BurningTrees(a@, b@))
EndIf ' neighbors that will set it ablaze
EndIf
Next
Next
Return
_UpdateForest ' Update the main buffer
Local(1)
For a@ = 0 To 120 ' Move from temporary buffer to main
@(a@) = @(a@+121)
Next
Return
_PrintForest ' Print the forest on screen
Local(2)
Print ' Let's make a little space
For a@ = 0 To 10 ' Loop vertical
For b@ = 0 To 10 ' Loop horizontal
If @((a@ * 11) + b@) = B Then ' This is a burning tree
Print " *";
Else ' Otherwise..
If @((a@ * 11) + b@) = E Then ' It may be an empty space
Print " ";
Else ' Otherwise
Print " @"; ' It has to be a tree
EndIf
EndIf
Next
Print ' Terminate row
Next
Print ' Terminate map
Return
_BurningTrees Param(2) ' Check the trees environment
Local(2)
For c@ = a@-1 To a@+1 ' Loop vertical -1/+1
If c@ < 0 Then Continue ' Skip top edge
Until c@ > 10 ' End at bottom edge
For d@ = b@-1 To b@+1 ' Loop horizontal -1/+1
If d@ < 0 Then Continue ' Skip left edge
Until d@ > 10 ' End at right edge
If @((c@ * 11) + d@) = B Then Unloop : Unloop : Return (B)
Next ' We found a burning tree, exit!
Next ' Try next row
Return (T) ' No burning trees found
|
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
|
#jq
|
jq
|
def flatten:
reduce .[] as $i
([];
if $i | type == "array" then . + ($i | flatten)
else . + [$i]
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.
|
#q
|
q
|
floyd:{n:1+ til sum 1+til x;
t:d:0;
while[1+x-:1;0N!(t+:1)#(d+:t)_n]}
floyd2:{n:1+ til sum 1+til x;
t:d:0;
while[1+x-:1;1 (" " sv string each (t+:1)#(d+:t)_n),"\n"]}
//The latter function 'floyd2' includes logic to remove the leading "," before "1" in the first row.
floyd[5]
floyd2[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)
|
#JavaScript
|
JavaScript
|
permute = function(v, m){ //v1.0
for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
for(r = new Array(q); ++p < q;)
for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i],
x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
for(x[3][i] = x[2][i], f = 0; !f; f = !f)
for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
return r;
};
list = [ 'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB',
'DABC', 'BCAD', 'CADB', 'CDBA', 'CBAD', 'ABDC', 'ADBC', 'BDCA',
'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'];
all = permute(list[0].split('')).map(function(elem) {return elem.join('')});
missing = all.filter(function(elem) {return list.indexOf(elem) == -1});
print(missing); // ==> DBAC
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Maple
|
Maple
|
sundays := proc(year)
local i, dt, change, last_days;
last_days := [31,28,31,30,31,30,31,31,30,31,30,31];
if (Calendar:-IsLeapYear(year)) then
last_days[2] := 28;
end if;
for i to 12 do
dt := Date(year, i, last_days[i]);
change := 0;
if not(Calendar:-DayOfWeek(dt) = 1) then
change := -Calendar:-DayOfWeek(dt) + 1;
end if;
dt := Calendar:-AdjustDateField(dt, "date", change);
printf("%d-%d-%d\n", year, Month(dt), DayOfMonth(dt));
end do;
end proc;
sundays(2013);
|
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
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
LastSundays[year_] :=
Table[Last@
DayRange[{year, i},
DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i,
12}]
LastSundays[2013]
|
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) .
|
#Visual_Basic
|
Visual Basic
|
Option Explicit
Public Type Point
x As Double
y As Double
invalid As Boolean
End Type
Public Type Line
s As Point
e As Point
End Type
Public Function GetIntersectionPoint(L1 As Line, L2 As Line) As Point
Dim a1 As Double
Dim b1 As Double
Dim c1 As Double
Dim a2 As Double
Dim b2 As Double
Dim c2 As Double
Dim det As Double
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
det = a1 * b2 - a2 * b1
If det Then
With GetIntersectionPoint
.x = (b2 * c1 - b1 * c2) / det
.y = (a1 * c2 - a2 * c1) / det
End With
Else
GetIntersectionPoint.invalid = True
End If
End Function
Sub Main()
Dim ln1 As Line
Dim ln2 As Line
Dim ip As Point
ln1.s.x = 4
ln1.s.y = 0
ln1.e.x = 6
ln1.e.y = 10
ln2.s.x = 0
ln2.s.y = 3
ln2.e.x = 10
ln2.e.y = 7
ip = GetIntersectionPoint(ln1, ln2)
Debug.Assert Not ip.invalid
Debug.Assert ip.x = 5 And ip.y = 5
LSet ln2.s = ln2.e
ip = GetIntersectionPoint(ln1, ln2)
Debug.Assert ip.invalid
LSet ln2 = ln1
ip = GetIntersectionPoint(ln1, ln2)
Debug.Assert ip.invalid
End Sub
|
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) .
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Drawing
Module Module1
Function FindIntersection(s1 As PointF, e1 As PointF, s2 As PointF, e2 As PointF) As PointF
Dim a1 = e1.Y - s1.Y
Dim b1 = s1.X - e1.X
Dim c1 = a1 * s1.X + b1 * s1.Y
Dim a2 = e2.Y - s2.Y
Dim b2 = s2.X - e2.X
Dim c2 = a2 * s2.X + b2 * s2.Y
Dim delta = a1 * b2 - a2 * b1
'If lines are parallel, the result will be (NaN, NaN).
Return If(delta = 0, New PointF(Single.NaN, Single.NaN), New PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta))
End Function
Sub Main()
Dim p = Function(x As Single, y As Single) New PointF(x, y)
Console.WriteLine(FindIntersection(p(4.0F, 0F), p(6.0F, 10.0F), p(0F, 3.0F), p(10.0F, 7.0F)))
Console.WriteLine(FindIntersection(p(0F, 0F), p(1.0F, 1.0F), p(1.0F, 2.0F), p(4.0F, 5.0F)))
End Sub
End Module
|
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
|
#Batch_File
|
Batch File
|
@echo off
for /L %%i in (1,1,100) do call :tester %%i
goto :eof
:tester
set /a test = %1 %% 15
if %test% NEQ 0 goto :NotFizzBuzz
echo FizzBuzz
goto :eof
:NotFizzBuzz
set /a test = %1 %% 5
if %test% NEQ 0 goto :NotBuzz
echo Buzz
goto :eof
:NotBuzz
set /a test = %1 %% 3
if %test% NEQ 0 goto :NotFizz
echo Fizz
goto :eof
:NotFizz
echo %1
|
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
|
#MUMPS
|
MUMPS
|
FIVE
;List and count the months between 1/1900 and 12/2100 that have 5 full weekends
;Extra credit - list and count years with no months with five full weekends
;Using the test that the 31st of a month is on a Sunday
;Uses the VA's public domain routine %DTC (Part of the Kernel) named here DIDTC
NEW YEAR,MONTH,X,Y,CNTMON,NOT,NOTLIST
; YEAR is the year we're testing
; MONTH is the month we're testing
; X is the date in "internal" format, as an input to DOW^DIDTC
; Y is the day of the week (0=Sunday, 1=Monday...) output from DOW^DIDTC
; CNTMON is a count of the months that have 5 full weekends
; NOT is a flag if there were no months with 5 full weekends yet that year
; NOTLIST is a list of years that do not have any months with 5 full weekends
SET CNTMON=0,NOTLIST=""
WRITE !!,"The following months have five full weekends:"
FOR YEAR=200:1:400 DO ;years since 12/31/1700 epoch
. SET NOT=0
. FOR MONTH="01","03","05","07","08","10","12" DO
. . SET X=YEAR_MONTH_"31"
. . DO DOW^DIDTC
. . IF (Y=0) DO
. . . SET NOT=NOT+1,CNTMON=CNTMON+1
. . . WRITE !,MONTH_"-"_(YEAR+1700)
. SET:(NOT=0) NOTLIST=NOTLIST_$SELECT($LENGTH(NOTLIST)>1:",",1:"")_(YEAR+1700)
WRITE !,"For a total of "_CNTMON_" months."
WRITE !!,"There are "_$LENGTH(NOTLIST,",")_" years with no five full weekends in any month."
WRITE !,"They are: "_NOTLIST
KILL YEAR,MONTH,X,Y,CNTMON,NOT,NOTLIST
QUIT
F ;Same logic as the main entry point, shortened format
N R,M,X,Y,C,N,L S C=0,L=""
W !!,"The following months have five full weekends:"
F R=200:1:400 D
. S N=0 F M="01","03","05","07","08","10","12" S X=R_M_"31" D DOW^DIDTC I 'Y S N=N+1,C=C+1 W !,M_"-"_(R+1700)
. S:'N L=L_$S($L(L):",",1:"")_(R+1700)
W !,"For a total of "_C_" months.",!!,"There are "_$L(L,",")_" years with no five full weekends in any month.",!,"They are: "_L
Q
|
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
|
#NetRexx
|
NetRexx
|
/* NetRexx ************************************************************
* 30.08.2012 Walter Pachl derived from Rexx version 3
* omitting dead code left there
**********************************************************************/
options replace format comments java crossref savelog symbols
Numeric digits 20
nr5fwe=0
years_without_5fwe=0
mnl='Jan Mar May Jul Aug Oct Dec'
ml='1 3 5 7 8 10 12'
Loop j=1900 To 2100
year_has_5fwe=0
Loop mi=1 To ml.words()
m=ml.word(mi)
jd=greg2jul(j,m,1)
IF jd//7=4 Then Do /* 1st m j is a Friday */
nr5fwe=nr5fwe+1
year_has_5fwe=1
If j<=1905 | 2095<=j Then
Say mnl.word(mi) j 'has 5 full weekends'
End
End
If j=1905 Then Say '...'
if year_has_5fwe=0 Then years_without_5fwe=years_without_5fwe+1
End
Say ' '
Say nr5fwe 'occurrences of 5 full weekends in a month'
Say years_without_5fwe 'years without 5 full weekends'
exit
method greg2jul(yy,mm,d) public static returns Rexx
/***********************************************************************
* Converts a Gregorian date to the corresponding Julian day number
* 19891101 Walter Pachl REXXified algorithm published in CACM
* (Fliegel & vanFlandern, CACM Vol.11 No.10 October 1968)
***********************************************************************/
numeric digits 12
/***********************************************************************
* The published formula:
* res=d-32075+1461*(yy+4800+(mm-14)%12)%4+,
* 367*(mm-2-((mm-14)%12)*12)%12-3*((yy+4900+(mm-14)%12)%100)%4
***********************************************************************/
mma=(mm-14)%12
yya=yy+4800+mma
result=d-32075+1461*yya%4+367*(mm-2-mma*12)%12-3*((yya+100)%100)%4
Return result /* return the result */
|
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
|
#PARI.2FGP
|
PARI/GP
|
compose(f,g)={
x -> f(g(x))
};
fcf()={
my(A,B);
A=[x->sin(x), x->cos(x), x->x^2];
B=[x->asin(x), x->acos(x), x->sqrt(x)];
for(i=1,#A,
print(compose(A[i],B[i])(.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
|
#Perl
|
Perl
|
use Math::Complex ':trig';
sub compose {
my ($f, $g) = @_;
sub {
$f -> ($g -> (@_));
};
}
my $cube = sub { $_[0] ** (3) };
my $croot = sub { $_[0] ** (1/3) };
my @flist1 = ( \&Math::Complex::sin, \&Math::Complex::cos, $cube );
my @flist2 = ( \&asin, \&acos, $croot );
print join "\n", map {
compose($flist1[$_], $flist2[$_]) -> (0.5)
} 0..2;
|
http://rosettacode.org/wiki/Forest_fire
|
Forest fire
|
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Drossel and Schwabl definition of the forest-fire model.
It is basically a 2D cellular automaton where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia)
A burning cell turns into an empty cell
A tree will burn if at least one neighbor is burning
A tree ignites with probability f even if no neighbor is burning
An empty space fills with a tree with probability p
Neighborhood is the Moore neighborhood; boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition).
At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.
Task's requirements do not include graphical display or the ability to change parameters (probabilities p and f ) through a graphical or command line interface.
Related tasks
See Conway's Game of Life
See Wireworld.
|
#Vedit_macro_language
|
Vedit macro language
|
#1 = 25 // height of the grid
#2 = 60 // width of the grid
#3 = 2 // probability of random fire, per 1000
#4 = 40 // probability of new tree, per 1000
#5 = #2+2+Newline_Chars // total length of a line
#90 = Time_Tick // seed for random number generator
#91 = 1000 // get random numbers in range 0 to 999
// Fill the grid and draw border
Buf_Switch(Buf_Free)
Ins_Char('-', COUNT, #2+2)
Ins_Newline
for (#11=0; #11<#1; #11++) {
Ins_Char('|')
for (#12=0; #12<#2; #12++) {
Call("RANDOM")
if (Return_Value < 500) { // 50% propability for a tree
Ins_Char('♠')
} else {
Ins_Char(' ')
}
}
Ins_Char('|')
Ins_Newline
}
Ins_Char('-', COUNT, #2+2)
#8=1
Repeat(10) {
BOF
Update()
// calculate one generation
for (#11=1; #11<#1+2; #11++) {
Goto_Line(#11)
for (#12=1; #12<#2+2; #12++) {
Goto_Col(#12)
#14=Cur_Pos
Call("RANDOM")
#10 = Return_Value
if (Cur_Char == '♠') { // tree?
if (#10 < #3) {
Ins_Char('*', OVERWRITE) // random combustion
} else {
if (Search_Block("░", CP-#5-1, CP+#5+2, COLUMN+BEGIN+NOERR)) {
Goto_Pos(#14)
Ins_Char('*', OVERWRITE) // combustion
}
}
} else {
if (Cur_Char == ' ') { // empty space?
if (#10 < #4) {
Ins_Char('+', OVERWRITE) // new tree
}
}
}
}
}
// convert tmp symbols
Replace("░"," ", BEGIN+ALL+NOERR) // old fire goes out
Replace("*","░", BEGIN+ALL+NOERR) // new fire
Replace("+","♠", BEGIN+ALL+NOERR) // new tree
}
Return
//--------------------------------------------------------------
// Generate random numbers in range 0 <= Return_Value < #91
// #90 = Seed (0 to 0x7fffffff)
// #91 = Scaling (0 to 0xffff)
:RANDOM:
#92 = 0x7fffffff / 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
return ((#90 & 0xffff) * #91 / 0x10000)
|
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
|
#Jsish
|
Jsish
|
/* Flatten list, in Jsish */
function flatten(list) {
return list.reduce(function (acc, val) {
return acc.concat(typeof val === "array" ? flatten(val) : val);
}, []);
}
if (Interp.conf('unitTest')) {
; flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]);
}
/*
=!EXPECTSTART!=
flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]) ==> [ 1, 2, 3, 4, 5, 6, 7, 8 ]
=!EXPECTEND!=
*/
|
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.
|
#Quackery
|
Quackery
|
[ dup 1+ * 2 / ] is triangulared ( n --> n )
[ number$ tuck size -
times sp echo$ ] is rightecho ( n n --> )
[ dup triangulared
number$ size 1+
0 rot times
[ i^ 1+ times
[ 1+ 2dup
rightecho ]
cr ]
2drop ] is floyd ( n --> )
5 floyd
cr
14 floyd
|
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.
|
#R
|
R
|
Floyd <- function(n)
{
#The first argument of the seq call is a well-known formula for triangle numbers.
out <- t(sapply(seq_len(n), function(i) c(seq(to = 0.5 * (i * (i + 1)), by = 1, length.out = i), rep(NA, times = n - i))))
dimnames(out) <- list(rep("", times = nrow(out)), rep("", times = ncol(out)))
print(out, na.print = "")
}
Floyd(5)
Floyd(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)
|
#jq
|
jq
|
jq -R . Find_the_missing_permutation.txt | jq -s -f Find_the_missing_permutation.jq
|
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
|
#Nim
|
Nim
|
import os, strutils, times
const
DaysInMonth: array[Month, int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
DayDiffs: array[WeekDay, int] = [1, 2, 3, 4, 5, 6, 0]
let year = paramStr(1).parseInt
for month in mJan..mDec:
var lastDay = DaysInMonth[month]
if month == mFeb and year.isLeapYear: lastDay = 29
var date = initDateTime(lastDay, month, year, 0, 0, 0)
date = date - days(DayDiffs[date.weekday])
echo date.format("yyyy-MM-dd")
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#OCaml
|
OCaml
|
let is_leap_year y =
(* See OCaml solution on Rosetta Code for
determing if it's a leap year *)
if (y mod 100) = 0
then (y mod 400) = 0
else (y mod 4) = 0;;
let get_days y =
if is_leap_year y
then
[31;29;31;30;31;30;31;31;30;31;30;31]
else
[31;28;31;30;31;30;31;31;30;31;30;31];;
let print_date = Printf.printf "%d/%d/%d\n";;
let get_day_of_week y m d =
let y = if m > 2 then y else y - 1 in
let c = y / 100 in
let y = y mod 100 in
let m_shifted = float_of_int ( ((m + 9) mod 12) + 1) in
let m_factor = int_of_float (2.6 *. m_shifted -. 0.2) in
let leap_factor = 5 * (y mod 4) + 3 * (y mod 7) + 5 * (c mod 4) in
(d + m_factor + leap_factor) mod 7;;
let get_shift y m last_day =
get_day_of_week y m last_day;;
let print_last_sunday y m =
let days = get_days y in
let last_day = List.nth days (m - 1) in
let last_sunday = last_day - (get_shift y m last_day) in
print_date y m last_sunday;;
let print_last_sundays y =
let months = [1;2;3;4;5;6;7;8;9;10;11;12] in
List.iter (print_last_sunday y) months;;
match (Array.length Sys.argv ) with
2 -> print_last_sundays( int_of_string (Sys.argv.(1)));
|_ -> invalid_arg "Please enter a year";
|
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
|
Find the intersection of two lines
|
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
|
#Wren
|
Wren
|
class Point {
construct new(x, y) {
_x = x
_y = y
}
x { _x }
y { _y }
toString { "(%(_x), %(_y))" }
}
class Line {
construct new(s, e) {
_s = s
_e = e
}
s { _s }
e { _e }
}
var findIntersection = Fn.new { |l1, l2|
var a1 = l1.e.y - l1.s.y
var b1 = l1.s.x - l1.e.x
var c1 = a1*l1.s.x + b1*l1.s.y
var a2 = l2.e.y - l2.s.y
var b2 = l2.s.x - l2.e.x
var c2 = a2*l2.s.x + b2*l2.s.y
var delta = a1*b2 - a2*b1
// if lines are parallel, intersection point will contain infinite values
return Point.new((b2*c1 - b1*c2)/delta, (a1*c2 - a2*c1)/delta)
}
var l1 = Line.new(Point.new(4, 0), Point.new(6, 10))
var l2 = Line.new(Point.new(0, 3), Point.new(10, 7))
System.print(findIntersection.call(l1, l2))
l1 = Line.new(Point.new(0, 0), Point.new(1, 1))
l2 = Line.new(Point.new(1, 2), Point.new(4, 5))
System.print(findIntersection.call(l1, l2))
|
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
|
#BBC_BASIC
|
BBC BASIC
|
for (i = 1; i <= 100; i++) {
w = 0
if (i % 3 == 0) { "Fizz"; w = 1; }
if (i % 5 == 0) { "Buzz"; w = 1; }
if (w == 0) i
if (w == 1) "
"
}
quit
|
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
|
#NewLISP
|
NewLISP
|
#!/usr/local/bin/newlisp
(context 'KR)
(define (Kraitchik year month day)
; See https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Kraitchik.27s_variation
; Function adapted for specific task (not for general usage).
(if (or (= 1 month) (= 2 month))
(dec year)
)
;- - - -
(setf m-table '(_ 1 4 3 6 1 4 6 2 5 0 3 5)) ; - - - First element of list is dummy!
(setf m (m-table month))
;- - - -
(setf c-table '(0 5 3 1))
(setf century%4 (mod (int (slice (string year) 0 2)) 4))
(setf c (c-table century%4))
;- - - -
(setf yy* (slice (string year) -2))
(if (= "0" (yy* 0))
(setf yy* (yy* 1))
)
(setf yy (int yy*))
(setf y (mod (+ (/ yy 4) yy) 7))
;- - - -
(setf dow-table '(6 0 1 2 3 4 5))
(dow-table (mod (+ day m c y) 7))
)
(context 'MAIN)
(setf Fives 0)
(setf NotFives 0)
(setf Report '())
(setf months-table '((1 "Jan") (3 "Mar") (5 "May") (7 "Jul") (8 "Aug") (10 "Oct") (12 "Dec")))
(for (y 1900 2100)
(setf FivesFound 0)
(setf Names "")
(dolist (m '(1 3 5 7 8 10 12))
(setf Dow (KR:Kraitchik y m 1))
(if (= 5 Dow)
(begin
(++ FivesFound)
(setf Names (string Names " " (lookup m months-table)))
)
)
)
(if (zero? FivesFound)
(++ NotFives)
(begin
(setf Report (append Report (list (list y FivesFound (string "(" Names " )")))))
(setf Fives (+ Fives FivesFound))
)
)
)
;- - - - Display all report data
;(dolist (x Report)
; (println (x 0) ": " (x 1) " " (x 2))
;)
;- - - - Display only first five and last five records
(dolist (x (slice Report 0 5))
(println (x 0) ": " (x 1) " " (x 2))
)
(println "...")
(dolist (x (slice Report -5))
(println (x 0) ": " (x 1) " " (x 2))
)
(println "\nTotal months with five weekends: " Fives)
(println "Years with no five weekends months: " NotFives)
(exit)
|
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
|
#Phix
|
Phix
|
sequence ctable = {}
function compose(integer f, g)
ctable = append(ctable,{f,g})
integer cdx = length(ctable)
return cdx
end function
function call_composite(integer cdx, atom x)
integer {f,g} = ctable[cdx]
return f(g(x))
end function
function plus1(atom x)
return x+1
end function
function halve(atom x)
return x/2
end function
constant m = compose(halve,plus1)
?call_composite(m,1) -- displays 1
?call_composite(m,4) -- displays 2.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.
|
#Vlang
|
Vlang
|
import rand
import strings
import os
const (
rows = 20
cols = 30
p = .01
f = .001
)
const rx = rows + 2
const cx = cols + 2
fn main() {
mut odd := []string{len: rx*cx}
mut even := []string{len: rx*cx}
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
if rand.intn(2) or {1} == 1 {
odd[r*cx+c] = 'T'
}
}
}
mut _ := ''
for {
print_row(odd)
step(mut even, odd)
_ = os.input('')
print_row(even)
step(mut odd, even)
_ = os.input('')
}
}
fn print_row(model []string) {
println(strings.repeat_string("__", cols))
println('')
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
if model[r*cx+c] == '0' {
print(" ")
} else {
print(" ${model[r*cx+c]}")
}
}
println('')
}
}
fn step(mut dst []string, src []string) {
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
x := r*cx + c
dst[x] = src[x]
match dst[x] {
'#' {
// rule 1. A burning cell turns into an empty cell
dst[x] = '0'
}
'T' {
// rule 2. A tree will burn if at least one neighbor is burning
if src[x-cx-1]=='#' || src[x-cx]=='#' || src[x-cx+1]=='#' ||
src[x-1] == '#' || src[x+1] == '#' ||
src[x+cx-1]=='#' || src[x+cx]=='#' || src[x+cx+1] == '#' {
dst[x] = '#'
// rule 3. A tree ignites with probability f
// even if no neighbor is burning
} else if rand.f64() < f {
dst[x] = '#'
}
}
else {
// rule 4. An empty space fills with a tree with probability p
if rand.f64() < p {
dst[x] = 'T'
}
}
}
}
}
}
|
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
|
#Julia
|
Julia
|
isflat(x) = isempty(x) || first(x) === x
function flat_mapreduce(arr)
mapreduce(vcat, arr, init=[]) do x
isflat(x) ? x : flat(x)
end
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.
|
#Racket
|
Racket
|
#lang racket
(require math)
(define (tri n)
(if (zero? n) 0 (triangle-number n)))
(define (floyd n)
(define (width x) (string-length (~a x)))
(define (~n x c) (~a x
#:width (width (+ (tri (- n 1)) 1 c))
#:align 'right #:left-pad-string " "))
(for ([r n])
(for ([c (+ r 1)])
(display (~a (~n (+ (tri r) 1 c) c) " ")))
(newline)))
(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.
|
#Raku
|
Raku
|
constant @floyd1 = (1..*).rotor(1..*);
constant @floyd2 = gather for 1..* -> $s { take [++$ xx $s] }
sub format-rows(@f) {
my @table;
my @formats = @f[@f-1].map: {"%{.chars}s"}
for @f -> @row {
@table.push: (@row Z @formats).map: -> ($i, $f) { $i.fmt($f) }
}
join "\n", @table;
}
say format-rows(@floyd1[^5]);
say '';
say format-rows(@floyd2[^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)
|
#Julia
|
Julia
|
using BenchmarkTools, Combinatorics
function missingperm(arr::Vector)
allperms = String.(permutations(arr[1])) # revised for type safety
for perm in allperms
if perm ∉ arr return perm end
end
end
arr = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD",
"CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC",
"CBDA", "DBCA", "DCAB"]
@show missingperm(arr)
|
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)
|
#K
|
K
|
split:{1_'(&x=y)_ x:y,x}
g: ("ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB")
g,:(" CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB")
p: split[g;" "];
/ All permutations of "ABCD"
perm:{:[1<x;,/(>:'(x,x)#1,x#0)[;0,'1+_f x-1];,!x]}
p2:a@(perm(#a:"ABCD"));
/ Which permutations in p are there in p2?
p2 _lin p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
/ Invert the result
~p2 _lin p
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
/ It's the 20th permutation that is missing
&~p2 _lin p
,20
p2@&~p2 _lin p
"DBAC"
|
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
|
Find the last Sunday of each month
|
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
Related tasks
Day of the week
Five weekends
Last Friday of each month
|
#Oforth
|
Oforth
|
import: date
: lastSunday(y)
| m |
Date.JANUARY Date.DECEMBER for: m [
Date newDate(y, m, Date.DaysInMonth(y, m))
while(dup dayOfWeek Date.SUNDAY <>) [ addDays(-1) ] println
] ;
|
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
|
#PARI.2FGP
|
PARI/GP
|
\\ Normalized Julian Day Number from date
njd(D) =
{
my (m = D[2], y = D[1]);
if (D[2] > 2, m++, y--; m += 13);
(1461 * y) \ 4 + (306001 * m) \ 10000 + D[3] - 694024 + 2 - y \ 100 + y \ 400
}
\\ Date from Normalized Julian Day Number
njdate(J) =
{
my (a = J + 2415019, b = (4 * a - 7468865) \ 146097, c, d, m, y);
a += 1 + b - b \ 4 + 1524;
b = (20 * a - 2442) \ 7305;
c = (1461 * b) \ 4;
d = ((a - c) * 10000) \ 306001;
m = d - 1 - 12 * (d > 13);
y = b - 4715 - (m > 2);
d = a - c - (306001 * d) \ 10000;
[y, m, d]
}
for (m=1, 12, a=njd([2013,m+1,0]); print(njdate(a-(a+6)%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) .
|
#XPL0
|
XPL0
|
func real Det; real A0, B0, A1, B1;
return A0*B1 - A1*B0;
func Cramer; real A0, B0, C0, A1, B1, C1;
real Denom;
[Denom:= Det(A0, B0, A1, B1);
RlOut(0, Det(C0, B0, C1, B1) / Denom);
RlOut(0, Det(A0, C0, A1, C1) / Denom);
];
real L0, L1, M0, M1;
[L0:= [[ 4., 0.], [ 6., 10.]];
L1:= [[ 0., 3.], [10., 7.]];
M0:= (L0(1,1) - L0(0,1)) / (L0(1,0) - L0(0,0));
M1:= (L1(1,1) - L1(0,1)) / (L1(1,0) - L1(0,0));
Cramer(M0, -1., M0*L0(0,0)-L0(0,1), M1, -1., M1*L1(0,0)-L1(0,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) .
|
#zkl
|
zkl
|
fcn lineIntersect(ax,ay, bx,by, cx,cy, dx,dy){ // --> (x,y)
detAB,detCD := det(ax,ay, bx,by), det(cx,cy, dx,dy);
abDx,cdDx := ax - bx, cx - dx; // delta x
abDy,cdDy := ay - by, cy - dy; // delta y
xnom,ynom := det(detAB,abDx, detCD,cdDx), det(detAB,abDy, detCD,cdDy);
denom := det(abDx,abDy, cdDx,cdDy);
if(denom.closeTo(0.0, 0.0001))
throw(Exception.MathError("lineIntersect: Parallel lines"));
return(xnom/denom, ynom/denom);
}
fcn det(a,b,c,d){ a*d - b*c } // determinant
|
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
|
#bc
|
bc
|
for (i = 1; i <= 100; i++) {
w = 0
if (i % 3 == 0) { "Fizz"; w = 1; }
if (i % 5 == 0) { "Buzz"; w = 1; }
if (w == 0) i
if (w == 1) "
"
}
quit
|
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
|
#Nim
|
Nim
|
import times
const LongMonths = {mJan, mMar, mMay, mJul, mAug, mOct, mDec}
var sumNone = 0
for year in 1900..2100:
var none = true
for month in LongMonths:
if initDateTime(1, month, year, 0, 0, 0).weekday == dFri:
echo month, " ", year
none = false
if none: inc sumNone
echo "\nYears without a 5 weekend month: ", sumNone
|
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
|
#OCaml
|
OCaml
|
open CalendarLib
let list_first_five = function
| x1 :: x2 :: x3 :: x4 :: x5 :: _ -> [x1; x2; x3; x4; x5]
| _ -> invalid_arg "list_first_five"
let () =
let months = ref [] in
for year = 1900 to 2100 do
for month = 1 to 12 do
let we = ref 0 in
let num_days = Date.days_in_month (Date.make_year_month year month) in
for day = 1 to num_days - 2 do
let d0 = Date.day_of_week (Date.make year month day)
and d1 = Date.day_of_week (Date.make year month (day + 1))
and d2 = Date.day_of_week (Date.make year month (day + 2)) in
if (d0, d1, d2) = (Date.Fri, Date.Sat, Date.Sun) then incr we
done;
if !we = 5 then months := (year, month) :: !months
done;
done;
Printf.printf "Number of months with 5 weekends: %d\n" (List.length !months);
print_endline "First and last months between 1900 and 2100:";
let print_month (year, month) = Printf.printf "%d-%02d\n" year month in
List.iter print_month (list_first_five (List.rev !months));
List.iter print_month (List.rev (list_first_five !months));
;;
|
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
|
#PHP
|
PHP
|
$compose = function ($f, $g) {
return function ($x) use ($f, $g) {
return $f($g($x));
};
};
$fn = array('sin', 'cos', function ($x) { return pow($x, 3); });
$inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); });
for ($i = 0; $i < 3; $i++) {
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}
|
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.
|
#Wren
|
Wren
|
import "random" for Random
import "io" for Stdin
var rand = Random.new()
var rows = 20
var cols = 30
var p = 0.01
var f = 0.001
var rx = rows + 2
var cx = cols + 2
var step = Fn.new { |dst, src|
for (r in 1..rows) {
for (c in 1..cols) {
var x = r*cx + c
dst[x] = src[x]
if (dst[x] == "#") {
// rule 1. A burning cell turns into an empty cell
dst[x] = " "
} else if(dst[x] == "T") {
// rule 2. A tree will burn if at least one neighbor is burning
if (src[x-cx-1] == "#" || src[x-cx] == "#" || src[x-cx+1] == "#" ||
src[x-1] == "#" || src[x+1] == "#" ||
src[x+cx-1] == "#" || src[x+cx] == "#" || src[x+cx+1] == "#") {
dst[x] = "#"
// rule 3. A tree ignites with probability f
// even if no neighbor is burning
} else if (rand.float() < f) {
dst[x] = "#"
}
} else {
// rule 4. An empty space fills with a tree with probability p
if (rand.float() < p) dst[x] = "T"
}
}
}
}
var print = Fn.new { |model|
System.print("__" * cols)
System.print()
for (r in 1..rows) {
for (c in 1..cols) System.write(" %(model[r*cx+c])")
System.print()
}
}
var odd = List.filled(rx*cx, " ")
var even = List.filled(rx*cx, " ")
for (r in 1 ..rows) {
for (c in 1..cols) {
if (rand.int(2) == 1) odd[r*cx+c] = "T"
}
}
while (true) {
print.call(odd)
step.call(even, odd)
Stdin.readLine()
print.call(even)
step.call(odd, even)
Stdin.readLine()
}
|
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
|
#K
|
K
|
,//((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.
|
#REXX
|
REXX
|
/* REXX ***************************************************************
* Parse Arg rowcount
* 12.07.2012 Walter Pachl - translated from Python
**********************************************************************/
Parse Arg rowcount
col=0
ll='' /* last line of triangle */
Do j=rowcount*(rowcount-1)/2+1 to rowcount*(rowcount+1)/2
col=col+1 /* column number */
ll=ll j /* build last line */
len.col=length(j) /* remember length of column */
End
Do i=1 To rowcount-1 /* now do and output the rest */
ol=''
col=0
Do j=i*(i-1)/2+1 to i*(i+1)/2 /* elements of line i */
col=col+1
ol=ol right(j,len.col) /* element in proper length */
end
Say ol /* output ith line */
end
Say ll /* output last line */
|
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)
|
#Kotlin
|
Kotlin
|
// version 1.1.2
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun <T> missingPerms(input: List<T>, perms: List<List<T>>) = permute(input) - perms
fun main(args: Array<String>) {
val input = listOf('A', 'B', 'C', 'D')
val strings = listOf(
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
)
val perms = strings.map { it.toList() }
val missing = missingPerms(input, perms)
if (missing.size == 1)
print("The missing permutation is ${missing[0].joinToString("")}")
else {
println("There are ${missing.size} missing permutations, namely:\n")
for (perm in missing) println(perm.joinToString(""))
}
}
|
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
|
#Perl
|
Perl
|
#!/usr/bin/perl
use strict ;
use warnings ;
use DateTime ;
for my $i( 1..12 ) {
my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] ,
month => $i ) ;
while ( $date->dow != 7 ) {
$date = $date->subtract( days => 1 ) ;
}
my $ymd = $date->ymd ;
print "$ymd\n" ;
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#BCPL
|
BCPL
|
GET "libhdr"
LET start() BE $(
FOR i=1 TO 100 DO $(
TEST (i REM 15) = 0 THEN
writes("FizzBuzz")
ELSE TEST (i REM 3) = 0 THEN
writes("Fizz")
ELSE TEST (i REM 5) = 0 THEN
writes("Buzz")
ELSE
writen(i, 0)
newline()
$)
$)
|
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
|
#Oforth
|
Oforth
|
: fiveWeekEnd(y1, y2)
| y m |
ListBuffer new
y1 y2 for: y [
Date.JANUARY Date.DECEMBER for: m [
Date.DaysInMonth(y, m) 31 ==
[ y, m, 01 ] asDate dayOfWeek Date.FRIDAY == and
ifTrue: [ [ y, m ] over add ]
]
]
dup size println dup left(5) println right(5) println ;
|
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
|
#PARI.2FGP
|
PARI/GP
|
fiveWeekends()={
my(day=6); \\ 0 = Friday; this represents Thursday for March 1, 1900.
my(ny=[31,30,31,30,31,31,30,31,30,31,31,28],ly=ny,v,s);
ly[12]=29;
for(year=1900,2100,
v=if((year+1)%4,ny,ly); \\ Works for 1600 to 2398
for(month=1,12,
if(v[month] == 31 && !day,
if(month<11,
print(year" "month+2)
,
print(year+1" 1")
);
s++
);
day = (day + v[month])%7
)
);
s
};
|
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
|
#PicoLisp
|
PicoLisp
|
(load "@lib/math.l")
(de compose (F G)
(curry (F G) (X)
(F (G X)) ) )
(de cube (X)
(pow X 3.0) )
(de cubeRoot (X)
(pow X 0.3333333) )
(mapc
'((Fun Inv)
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )
|
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
|
#PostScript
|
PostScript
|
% PostScript has 'sin' and 'cos', but not these
/asin { dup dup 1. add exch 1. exch sub mul sqrt atan } def
/acos { dup dup 1. add exch 1. exch sub mul sqrt exch atan } def
/cube { 3 exp } def
/cuberoot { 1. 3. div exp } def
/compose { % f g -> { g f }
[ 3 1 roll exch
% procedures are not executed when encountered directly
% insert an 'exec' after procedures, but not after operators
1 index type /operatortype ne { /exec cvx exch } if
dup type /operatortype ne { /exec cvx } if
] cvx
} def
/funcs [ /sin load /cos load /cube load ] def
/ifuncs [ /asin load /acos load /cuberoot load ] def
0 1 funcs length 1 sub { /i exch def
ifuncs i get funcs i get compose
.5 exch exec ==
} for
|
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
|
#Kotlin
|
Kotlin
|
// version 1.0.6
@Suppress("UNCHECKED_CAST")
fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) {
for (e in nestList)
if (e is Int)
flatList.add(e)
else
// using unchecked cast here as can't check for instance of 'erased' generic type
flattenList(e as List<Any>, flatList)
}
fun main(args: Array<String>) {
val nestList : List<Any> = listOf(
listOf(1),
2,
listOf(listOf(3, 4), 5),
listOf(listOf(listOf<Int>())),
listOf(listOf(listOf(6))),
7,
8,
listOf<Int>()
)
println("Nested : " + nestList)
val flatList = mutableListOf<Int>()
flattenList(nestList, flatList)
println("Flattened : " + flatList)
}
|
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.
|
#Ring
|
Ring
|
rows = 10
n = 0
for r = 1 to rows
for c = 1 to r
n = n + 1
see string(n) + " "
next
see nl
next
|
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.
|
#Ruby
|
Ruby
|
def floyd(rows)
max = (rows * (rows + 1)) / 2
widths = ((max - rows + 1)..max).map {|n| n.to_s.length + 1}
n = 0
rows.times do |r|
puts (0..r).map {|i| n += 1; "%#{widths[i]}d" % n}.join
end
end
floyd(5)
floyd(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)
|
#Lua
|
Lua
|
local permute, tablex = require("pl.permute"), require("pl.tablex")
local permList, pStr = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
}
for perm in permute.iter({"A","B","C","D"}) do
pStr = table.concat(perm)
if not tablex.find(permList, pStr) then print(pStr) end
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
|
#Phix
|
Phix
|
include timedate.e
constant SUNDAY=7
procedure showlast(integer dow, integer doy, timedate td)
td = adjust_timedate(td,timedelta(days:=doy-1))
integer {year,month,day} = td
while day_of_week(year,month,day)!=dow do day-=1 end while
printf(1,"%4d-%02d-%02d\n",{year,month,day})
end procedure
procedure last_day_of_month(integer year, integer dow)
integer doy
timedate first = {year,1,1,0,0,0,0,0}
-- start by finding the 1st of the next month, less 1
for i=1 to 11 do
doy = day_of_year(year,i+1,1)-1
showlast(dow,doy,first)
end for
-- do December separately, as 1st would be next year
doy = day_of_year(year,12,31)
showlast(dow,doy,first)
end procedure
last_day_of_month(2013,SUNDAY)
|
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
|
#beeswax
|
beeswax
|
> q
>@F5~%"d@F{ > @F q
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp
;bL@~.~4~.5~5@ P<
|
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
|
#Pascal
|
Pascal
|
#!/usr/bin/perl -w
use DateTime ;
my @happymonths ;
my @workhardyears ;
my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ;
my @years = 1900..2100 ;
foreach my $year ( @years ) {
my $countmonths = 0 ;
foreach my $month ( @longmonths ) {
my $dt = DateTime->new( year => $year ,
month => $month ,
day => 1 ) ;
if ( $dt->day_of_week == 5 ) {
$countmonths++ ;
my $yearfound = $dt->year ;
my $monthfound = $dt->month_name ;
push ( @happymonths , "$yearfound $monthfound" ) ;
}
}
if ( $countmonths == 0 ) {
push ( @workhardyears, $year ) ;
}
}
print "There are " . @happymonths . " months with 5 full weekends!\n" ;
print "The first 5 and the last 5 of them are:\n" ;
foreach my $i ( 0..4 ) {
print "$happymonths[ $i ]\n" ;
}
foreach my $i ( -5..-1 ) {
print "$happymonths[ $i ]\n" ;
}
print "No long weekends in the following " . @workhardyears . " years:\n" ;
map { print "$_\n" } @workhardyears ;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.